Index: DPWavesProc/trunk/DPWavesProc/8marrayconf.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/8marrayconf.m (revision 216) +++ (revision ) @@ -1,3 +1,0 @@ -%calculate just the frequency energy spectrum -arrayrawfreq=sum(arrayraw.S')*dirres; -array8mfreq=sum(array8m.S')*dirres; Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/CREDITS.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/CREDITS.txt (revision 225) @@ -1,0 +1,4 @@ +Gregory P Dusek - original prototype +Sara M Haines - project management +Chris Calloway (cbcunc) - testing, release management +Harvey E Seim - chief science officer Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/HISTORY.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/HISTORY.txt (revision 225) @@ -1,0 +1,3 @@ +adcp 0.9 - code cleanup, version controlled, unreleased January 2007 + +splitter 0.1 - original prototype, unreleased, December 2006 Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/LICENSE.GPL =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/LICENSE.GPL (revision 225) @@ -1,0 +1,280 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/LICENSE.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/LICENSE.txt (revision 225) @@ -1,0 +1,14 @@ +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, +MA 02111-1307 USA. Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/README.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/README.txt (revision 225) @@ -1,0 +1,2 @@ +For more information please see the website: http://trac.nccoos.org/dataproc/wiki/DPWavesProc/docs +Or email Greg Dusek at UNC Dept of Marine Sciences at gdusek@email.unc.edu Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/RELEASENOTES.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/RELEASENOTES.txt (revision 225) @@ -1,0 +1,1 @@ +This is the first BETA release of DPWavesProc. Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/TODO.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/TODO.txt (revision 225) @@ -1,0 +1,3 @@ +- refactor into PD0 class with methods like waves, currents, split, etc. +- create a setup.py for module +- add text to README and INSTALL Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/VERSION.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/VERSION.txt (revision 225) @@ -1,0 +1,1 @@ +0.9 Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/__init__.py =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/__init__.py (revision 225) @@ -1,0 +1,6 @@ +""" +Modules for ADCP data + +adcp.pd0 - functions to handle PD0 files +""" +__all__ = ['pd0'] Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/adcpwaves.py =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/adcpwaves.py (revision 225) @@ -1,0 +1,361 @@ +"""This code takes the raw waves portion of the adcp data from the splitter +and outputs pressure, range, orbital velocity and system info text files that +can be read into matlab.""" + + + + +import sys, struct, math, shutil, os + +try: + infileName = sys.argv[1] + +except: + print 'error' + sys.exit(1) + + +ifile = open(infileName, 'rb') + + +#header +firstHeader=31103 +Header=firstHeader +while Header == firstHeader: + readFirstHeader=ifile.read(2) + if len(readFirstHeader) == 0: + print('\n End of file') + break + + pressureOfile = open('pressure', 'w') + rangeOfile = open('range', 'w') + orbitOfile = open('orbit', 'w') + sysinfoOfile = open('sysinfo', 'w') + + Header =struct.unpack('H',readFirstHeader)[0] + #print 'headerID=', hex(Header) + + firstLeaderHeader=259 + wavePingHeader=515 + lastLeaderHeader=771 + + #read the length + length=ifile.read(2) + length=struct.unpack('H',length)[0] + + #read 4 bytes before the leader ID + ifile.read(4) + + readLeaderHeader=ifile.read(2) + leaderHeader =struct.unpack('H',readLeaderHeader)[0] + + if leaderHeader != firstLeaderHeader: + print('error with first leader header') + print hex(leaderHeader) + break + #read and write sysinfo + + #firmware version + readFwVersion=ifile.read(2) + fwVersion=struct.unpack('H',readFwVersion)[0] + sysinfoOfile.write(str(fwVersion)) + sysinfoOfile.write('\n') + + #Configuration (not sure what to do with this) + ifile.read(2) + + # number of depth cells + readNbins=ifile.read(1) + Nbins= struct.unpack('B',readNbins)[0] + sysinfoOfile.write(str(Nbins)) + sysinfoOfile.write('\n') + + #Samples per wave burst + readNumSamples=ifile.read(2) + numSamples=struct.unpack('H',readNumSamples)[0] + sysinfoOfile.write(str(numSamples)) + sysinfoOfile.write('\n') + + # Size of depth cell + readBinLength=ifile.read(2) + binLength= struct.unpack('H',readBinLength)[0] + #change size to meters + binLength=binLength/100.00 + sysinfoOfile.write(str(binLength)) + sysinfoOfile.write('\n') + + #Time between wave samples + readTBS=ifile.read(2) + TBS=struct.unpack('H',readTBS)[0] + sysinfoOfile.write(str(TBS)) + sysinfoOfile.write('\n') + + #Time between wave bursts + readTBB=ifile.read(2) + TBB=struct.unpack('H',readTBB)[0] + sysinfoOfile.write(str(TBB)) + sysinfoOfile.write('\n') + + # distance to first bin + readDist1=ifile.read(2) + dist1= struct.unpack('H',readDist1)[0] + #change distance to meters + dist1=dist1/100.00 + sysinfoOfile.write(str(dist1)) + sysinfoOfile.write('\n') + + + # number of bins output + readBinsOut=ifile.read(1) + binsOut= struct.unpack('B',readBinsOut)[0] + sysinfoOfile.write(str(binsOut)) + sysinfoOfile.write('\n') + + #reserved data (?) + ifile.read(2) + + #skip the directional bitmap + ifile.read(16) + + #read and write the bitmap for what bins are output + readByteList=ifile.read(16) + byteList=struct.unpack('16B',readByteList) + + def int2msbits(n, count=8): + """returns the most-significant binary of integer n, using count number of digits""" + return "".join([str((n >> y) & 1) for y in range(0, count)]) + + bytemap = '' + bitmap = '' + for ind in range(len(byteList)): + byte = struct.pack('B', byteList[ind]) + bytemap += byte + bits = int2msbits(byteList[ind]) + bitmap += bits + + # find indexes from bit map + # (1) one way to get indices of 1's + ind = []; + for i in range(len(bitmap)): + if bitmap[i]=='1': ind.append(i) + + # transducer height above the bottom + th = 0.4 + + # heights above transducer + hat = [dist1+(binLength*elem) for elem in ind] + + # heights above bottom + hab = [th+elem for elem in hat] + + for value in hab: + sysinfoOfile.write(str(value)) + sysinfoOfile.write('\n') + + + #Read start time and write to file + readCentury=ifile.read(1) + century =struct.unpack('B',readCentury)[0] + + readYear=ifile.read(1) + year =struct.unpack('B',readYear)[0] + + readMonth=ifile.read(1) + month=struct.unpack('B',readMonth)[0] + + readDay=ifile.read(1) + day=struct.unpack('B',readDay)[0] + + readHour=ifile.read(1) + hour=struct.unpack('B',readHour)[0] + + readMinute=ifile.read(1) + minute=struct.unpack('B',readMinute)[0] + + readSecond=ifile.read(1) + second=struct.unpack('B',readSecond)[0] + + readHundSec=ifile.read(1) + hundSec=struct.unpack('B',readHundSec)[0] + + startTime=str(century)+str('%02d' % year)+str('%02d' % month)+str('%02d' % day)+str('%02d' % hour)+str('%02d' % minute)+str('%02d' % second)+str('%02d' % hundSec) + + #create a time stamp for the file names that only includes from year up to minutes + FileStamp=str('%02d' % year)+str('%02d' % month)+str('%02d' % day)+str('%02d' % hour)+str('%02d' % minute) + + sysinfoOfile.write(startTime) + sysinfoOfile.write('\n') + + #Burst number (how to unpack this? dont think we need it) + readBurstNum=ifile.read(4) + + #Serial number (how to unpack this? dont think we need it) + readSerial=ifile.read(8) + + #Temperature (dont need this, use the avg temp instead) + readTemp=ifile.read(2) + + + #Reserved space (?) + ifile.read(8) + + + + # Done with the First Leader Type>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + + #Wave Ping Type + + leaderHeader = wavePingHeader + while leaderHeader == wavePingHeader: + + + #read the length + length=ifile.read(2) + if len(length) == 0: + print('\n End of file') + break + length=struct.unpack('H',length)[0] + + #read 4 bytes before the leader ID + ifile.read(4) + + readLeaderHeader=ifile.read(2) + leaderHeader =struct.unpack('H',readLeaderHeader)[0] + + # if the leader header isnt the wave ping header move on to the next leader + if leaderHeader != wavePingHeader: + break + + #read through sample number and time since burst (don't need this) + ifile.read(6) + + #read and write the pressure data + pressure=ifile.read(4) + pressure=struct.unpack('I',pressure)[0] + + pressureOfile.write(str(pressure)) + pressureOfile.write('\n') + + #read and write the range data + + range1=ifile.read(4) + range1=struct.unpack('I',range1)[0] + rangeOfile.write(str(range1)) + rangeOfile.write(' ') + + range2=ifile.read(4) + range2=struct.unpack('I',range2)[0] + rangeOfile.write(str(range2)) + rangeOfile.write(' ') + + range3=ifile.read(4) + range3=struct.unpack('I',range3)[0] + rangeOfile.write(str(range3)) + rangeOfile.write(' ') + + range4=ifile.read(4) + range4=struct.unpack('I',range4)[0] + rangeOfile.write(str(range4)) + rangeOfile.write('\n') + + + #read and write the orbital velocity data + + bytes=40 + + while bytes > 0: + orbit=ifile.read(2) + orbit=struct.unpack('h',orbit)[0] + orbitOfile.write('%06d' % orbit) + orbitOfile.write(' ') + bytes=bytes-2 + + orbitOfile.write('\n') + + #reserved space (?) + ifile.read(6) + + # Done with the Wave Ping Type>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + + + #readLeaderHeader=ifile.read(2) + #leaderHeader =struct.unpack('H',readLeaderHeader)[0] + + if leaderHeader != lastLeaderHeader: + break + + #average depth + readAvgDepth= ifile.read(2) + avgDepth= struct.unpack('H', readAvgDepth)[0] + sysinfoOfile.write(str(avgDepth)) + sysinfoOfile.write('\n') + + #Average speed of sound in m/s + readAvgSound=ifile.read(2) + avgSound=struct.unpack('H',readAvgSound)[0] + sysinfoOfile.write(str(avgSound)) + sysinfoOfile.write('\n') + + #Average Temp in .01 deg C + readAvgTemp=ifile.read(2) + avgTemp=struct.unpack('H',readAvgTemp)[0] + sysinfoOfile.write(str(avgTemp)) + sysinfoOfile.write('\n') + + #heading + readHeading= ifile.read(2) + heading= struct.unpack('H', readHeading)[0] + sysinfoOfile.write(str(heading)) + sysinfoOfile.write('\n') + + #skip the std dev heading + ifile.read(2) + + #pitch + readPitch= ifile.read(2) + pitch= struct.unpack('h', readPitch)[0] + sysinfoOfile.write(str(pitch)) + sysinfoOfile.write('\n') + + #skip the std dev pitch + stdPitch=ifile.read(2) + + #Roll + readRoll= ifile.read(2) + roll= struct.unpack('h', readRoll)[0] + sysinfoOfile.write(str(roll)) + sysinfoOfile.write('\n') + + #skip std dev roll and last 4 bytes (what are they? maybe a checksum?) + stdRoll=ifile.read(2) + + test1=ifile.read(2) + + test2=ifile.read(2) + + + + + pressureOfile.close() + rangeOfile.close() + orbitOfile.close() + sysinfoOfile.close() + + + shutil.copy('pressure','pressure_'+FileStamp+'.txt') + shutil.copy('orbit','orbit_'+FileStamp+'.txt') + shutil.copy('range','range_'+FileStamp+'.txt') + shutil.copy('sysinfo','sysinfo_'+FileStamp+'.txt') + + os.remove('pressure') + os.remove('orbit') + os.remove('range') + os.remove('sysinfo') + + +ifile.close() +print 'processing complete' + + Index: DPWavesProc/trunk/DPWavesProc/ADCP_splitter/pd0.py =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/ADCP_splitter/pd0.py (revision 225) @@ -1,0 +1,242 @@ +#!/usr/bin/python +"""Functions to handle Acoustic Doppler Current Profiler data. + +As a script (to split a raw PD0 file into waves and currents): + +python pd0.py [path] rawFile wavesFile currentsFile +python pd0.py [-p path] -r rawFile -w wavesFile -c currentsFile +python pd0.py [--path=path] \\ + --raw=rawFile \\ + --waves=wavesFile \\ + --currents=currentsFile + +where: + path is a path to prepend to the following + rawFile is path of raw PD0 format input file + wavesFile is path of waves PD0 format output file + currentsFile is path of currents PD0 format output file + +or (to run the test suite): + +python pd0.py -t +python pd0.py --test + +or (to see this help message): + +python pd0.py -h +python pd0.py --help + +As a module: + +import adcp.pd0 +adcp.pd0.split(rawFile,wavesFile,currentsFile) + +where: + rawFile is a file object representing the raw PD0 format input + wavesFile is a file object representing the waves PD0 format output + currentsFile is a file object representing the currents PD0 format output +""" + +import struct + +# +# The rawfile is assumed to be in PD0 format. +# +# PD0 format assumes the file is a succession of ensembles. +# +# Each ensemble starts with a two byte header identifying the type of data +# contained in the ensemble. +# +# Following the header is a two byte length field specifying the length of +# the header, length field, and data combined +# +# Following the length field is raw data for the number of bytes indicated by +# the length field +# +# Following the raw data is a checksum field which is the two least +# significant bytes of the sum of the byte values of the header, length field, +# and raw data. +# +def split(rawFile,wavesFile,currentsFile): + """Split PD0 format data into seperate waves and currents + + split()rawFile,wavesFile,currentsFile -> None + """ + + # header IDs + wavesId=0x797f + currentsId=0x7f7f + + # convenience function reused for header, length, and checksum + def __nextLittleEndianUnsignedShort(file): + """Get next little endian unsigned short from file""" + raw = file.read(2) + return (raw, struct.unpack('= 0,(firstWaves,firstCurrents))) + + #seeks to the first occurence of a waves or currents data + rawFile.seek(firstEnsemble) + + # loop through raw data + rawHeader, header = __nextLittleEndianUnsignedShort(rawFile) + + while (header == wavesId) or (header == currentsId): + # get ensemble length + rawLength, length = __nextLittleEndianUnsignedShort(rawFile) + # read up to the checksum + rawEnsemble = rawFile.read(length-4) + # get checksum + rawChecksum, checksum = __nextLittleEndianUnsignedShort(rawFile) + + computedChecksum = __computeChecksum(rawHeader, rawLength, rawEnsemble) + + if checksum != computedChecksum: + raise IOError, "Checksum error" + + # append to output stream + if header == wavesId: + wavesFile.write(rawHeader) + wavesFile.write(rawLength) + wavesFile.write(rawEnsemble) + wavesFile.write(rawChecksum) + elif header == currentsId: + currentsFile.write(rawHeader) + currentsFile.write(rawLength) + currentsFile.write(rawEnsemble) + currentsFile.write(rawChecksum) + + try: + rawHeader, header = __nextLittleEndianUnsignedShort(rawFile) + except struct.error: + break + + +def test(): + """Execute test suite""" + try: + import adcp.tests.runalltests as runalltests + except: + # possible if executed as script + import sys,os + sys.path.append(os.path.join(os.path.dirname(__file__),'tests')) + import runalltests + runalltests.runalltests(subset='pd0') + +class __TestException(Exception): + """Flow control for running as script""" + pass + +# wrapper function +def __test(): + """Execute test suite from command line""" + test() + raise __TestException, 'Wrapper function for command line testing only' + +def __main(): + """Process as script from command line""" + import getopt,os,sys + + # get the command line options and arguments + path = '' + rawName,wavesName,currentsName = 3*[None] + + try: + opts, args = getopt.gnu_getopt(sys.argv[1:], + 'htp:r:w:c:', + ['help', + 'test', + 'path=', + 'raw=', + 'waves=', + 'currents=']) + for opt,arg in opts: + if opt in ['-h','--help']: + raise getopt.GetoptError,'' + if opt in ['-t','--test']: + __test() + elif opt in ['-p','--path']: + path = arg + elif opt in ['-r','--raw']: + rawName = arg + elif opt in ['-w','--waves']: + wavesName = arg + elif opt in ['-c','--currents']: + currentsName = arg + else: + raise getopt.GetoptError,'' + if (rawName is None) or \ + (wavesName is None) or \ + (currentsName is None): + if len(args) not in [3, 4]: + raise getopt.GetoptError,'' + else: + if (rawName is not None) or \ + (wavesName is not None) or \ + (currentsName is not None): + raise getopt.GetoptError,'' + else: + if len(args) == 4: + path = args[0] + del args[0] + rawName = args[0] + wavesName = args[1] + currentsName = args[2] + elif len(args) != 0: + raise getopt.GetoptError,'' + except getopt.GetoptError: + print __doc__ + return + except __TestException: + return + + # split a raw PD0 file + rawName = os.path.join(path, rawName) + print 'Raw file path:', rawName + wavesName = os.path.join(path, wavesName) + print 'Waves file path:', wavesName + currentsName = os.path.join(path, currentsName) + print 'Currents file path:', currentsName + rawFile = open(rawName, 'rb') + try: + wavesFile = open(wavesName, 'wb') + try: + currentsFile = open(currentsName, 'wb') + try: + split(rawFile, wavesFile, currentsFile) + finally: + currentsFile.close() + finally: + wavesFile.close() + finally: + rawFile.close() + +if __name__ == "__main__": + __main() + Index: DPWavesProc/trunk/DPWavesProc/CREDITS.txt =================================================================== --- DPWavesProc/trunk/DPWavesProc/CREDITS.txt (revision 40) +++ (revision ) @@ -1,4 +1,0 @@ -Gregory P Dusek - original prototype -Sara M Haines - project management -Chris Calloway (cbcunc) - testing, release management -Harvey E Seim - chief science officer Index: DPWavesProc/trunk/DPWavesProc/HISTORY.txt =================================================================== --- DPWavesProc/trunk/DPWavesProc/HISTORY.txt (revision 40) +++ (revision ) @@ -1,3 +1,0 @@ -adcp 0.9 - code cleanup, version controlled, unreleased January 2007 - -splitter 0.1 - original prototype, unreleased, December 2006 Index: DPWavesProc/trunk/DPWavesProc/LICENSE.GPL =================================================================== --- DPWavesProc/trunk/DPWavesProc/LICENSE.GPL (revision 40) +++ (revision ) @@ -1,280 +1,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS Index: DPWavesProc/trunk/DPWavesProc/LICENSE.txt =================================================================== --- DPWavesProc/trunk/DPWavesProc/LICENSE.txt (revision 40) +++ (revision ) @@ -1,14 +1,0 @@ -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, -MA 02111-1307 USA. Index: DPWavesProc/trunk/DPWavesProc/README.txt =================================================================== --- DPWavesProc/trunk/DPWavesProc/README.txt (revision 214) +++ (revision ) @@ -1,2 +1,0 @@ -For more information please see the website: http://trac.nccoos.org/dataproc/wiki/DPWavesProc/docs -Or email Greg Dusek at UNC Dept of Marine Sciences at gdusek@email.unc.edu Index: DPWavesProc/trunk/DPWavesProc/RELEASENOTES.txt =================================================================== --- DPWavesProc/trunk/DPWavesProc/RELEASENOTES.txt (revision 215) +++ (revision ) @@ -1,1 +1,0 @@ -This is the first BETA release of DPWavesProc. Index: DPWavesProc/trunk/DPWavesProc/TODO.txt =================================================================== --- DPWavesProc/trunk/DPWavesProc/TODO.txt (revision 41) +++ (revision ) @@ -1,3 +1,0 @@ -- refactor into PD0 class with methods like waves, currents, split, etc. -- create a setup.py for module -- add text to README and INSTALL Index: DPWavesProc/trunk/DPWavesProc/VERSION.txt =================================================================== --- DPWavesProc/trunk/DPWavesProc/VERSION.txt (revision 40) +++ (revision ) @@ -1,1 +1,0 @@ -0.9 Index: DPWavesProc/trunk/DPWavesProc/__init__.py =================================================================== --- DPWavesProc/trunk/DPWavesProc/__init__.py (revision 40) +++ (revision ) @@ -1,6 +1,0 @@ -""" -Modules for ADCP data - -adcp.pd0 - functions to handle PD0 files -""" -__all__ = ['pd0'] Index: DPWavesProc/trunk/DPWavesProc/adcp_matlab/Winfo_plot.m =================================================================== --- adcp/trunk/adcp/adcp_matlab/Winfo_plot.m (revision 168) +++ DPWavesProc/trunk/DPWavesProc/adcp_matlab/Winfo_plot.m (revision 225) @@ -1,3 +1,3 @@ -function [fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot(Winfo); +function [fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot1(Winfo); %This function takes the wave info (sigH, peak period, direction of peak and dominant direction @@ -9,13 +9,7 @@ fig_sigh=figure('Position',[scrsz]); h1=plot(Winfo.time,Winfo.hsig(1,:),'b.-'); -hold on -h2=plot(Winfo.time,Winfo.hsig(2,:),'r.-'); -h3=plot(Winfo.time,Winfo.hsig(3,:),'g.-'); -h4=plot(Winfo.time,Winfo.hsig(4,:),'c.-'); -h5=plot(Winfo.time,Winfo.hsig(5,:),'m.-'); -h6=plot(Winfo.time,Winfo.hsig(7,:),'k.-'); datetick('x',15,'keepticks'); -legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +legend([h1],'EMEP radial','location','best'); title(['Significant Wave Height starting on ',datestr(Winfo.time(:,1),0)]); xlabel('time'); @@ -25,13 +19,7 @@ fig_pp=figure('Position',[scrsz]); h1=plot(Winfo.time,Winfo.peakP(1,:),'b.-'); -hold on -h2=plot(Winfo.time,Winfo.peakP(2,:),'r.-'); -h3=plot(Winfo.time,Winfo.peakP(3,:),'g.-'); -h4=plot(Winfo.time,Winfo.peakP(4,:),'c.-'); -h5=plot(Winfo.time,Winfo.peakP(5,:),'m.-'); -h6=plot(Winfo.time,Winfo.peakP(7,:),'k.-'); datetick('x',15,'keepticks'); -legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +legend([h1],'EMEP radial','location','best'); title(['Peak Period starting on ',datestr(Winfo.time(:,1),0)]); xlabel('time'); @@ -41,13 +29,7 @@ fig_dp=figure('Position',[scrsz]); h1=plot(Winfo.time,Winfo.dirP(1,:),'b.-'); -hold on -h2=plot(Winfo.time,Winfo.dirP(2,:),'r.-'); -h3=plot(Winfo.time,Winfo.dirP(3,:),'g.-'); -h4=plot(Winfo.time,Winfo.dirP(4,:),'c.-'); -h5=plot(Winfo.time,Winfo.dirP(5,:),'m.-'); -h6=plot(Winfo.time,Winfo.dirP(7,:),'k.-'); datetick('x',15,'keepticks'); -legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +legend([h1],'EMEP radial','location','best'); title(['Direction of Peak Period starting on ',datestr(Winfo.time(:,1),0)]); xlabel('time'); @@ -58,13 +40,7 @@ fig_dd=figure('Position',[scrsz]); h1=plot(Winfo.time,Winfo.Ddir(1,:),'b.-'); -hold on -h2=plot(Winfo.time,Winfo.Ddir(2,:),'r.-'); -h3=plot(Winfo.time,Winfo.Ddir(3,:),'g.-'); -h4=plot(Winfo.time,Winfo.Ddir(4,:),'c.-'); -h5=plot(Winfo.time,Winfo.Ddir(5,:),'m.-'); -h6=plot(Winfo.time,Winfo.Ddir(7,:),'k.-'); datetick('x',15,'keepticks'); -legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +legend([h1],'EMEP radial','location','best'); title(['Dominant Direction starting on ',datestr(Winfo.time(:,1),0)] ); xlabel('time'); Index: DPWavesProc/trunk/DPWavesProc/adcp_matlab/Winfo_plot1.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/adcp_matlab/Winfo_plot1.m (revision 216) +++ (revision ) @@ -1,48 +1,0 @@ -function [fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot1(Winfo); - -%This function takes the wave info (sigH, peak period, direction of peak and dominant direction -%for a series of bursts and plots it as a function of time - - -%plot sig wave height -scrsz = get(0,'ScreenSize'); -fig_sigh=figure('Position',[scrsz]); -h1=plot(Winfo.time,Winfo.hsig(1,:),'b.-'); - -datetick('x',15,'keepticks'); -legend([h1],'EMEP radial','location','best'); -title(['Significant Wave Height starting on ',datestr(Winfo.time(:,1),0)]); -xlabel('time'); -ylabel('Wave Height (m)'); - -%plot peak period -fig_pp=figure('Position',[scrsz]); -h1=plot(Winfo.time,Winfo.peakP(1,:),'b.-'); - -datetick('x',15,'keepticks'); -legend([h1],'EMEP radial','location','best'); -title(['Peak Period starting on ',datestr(Winfo.time(:,1),0)]); -xlabel('time'); -ylabel('Period (seconds)'); - -%plot dir of peak period -fig_dp=figure('Position',[scrsz]); -h1=plot(Winfo.time,Winfo.dirP(1,:),'b.-'); - -datetick('x',15,'keepticks'); -legend([h1],'EMEP radial','location','best'); -title(['Direction of Peak Period starting on ',datestr(Winfo.time(:,1),0)]); -xlabel('time'); -ylabel('Direction (Degrees True)'); - -%plot the dominant direction - -fig_dd=figure('Position',[scrsz]); -h1=plot(Winfo.time,Winfo.Ddir(1,:),'b.-'); - -datetick('x',15,'keepticks'); -legend([h1],'EMEP radial','location','best'); -title(['Dominant Direction starting on ',datestr(Winfo.time(:,1),0)] ); -xlabel('time'); -ylabel('Direction (Degrees True)'); - Index: DPWavesProc/trunk/DPWavesProc/adcp_matlab/radialwaveplot.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/adcp_matlab/radialwaveplot.m (revision 224) +++ (revision ) @@ -1,260 +1,0 @@ -function [E_radial_WI,I_radial_WI,fig5,fig6]=radialwaveplot(radialE,radialI,spec,sysinfo) - -%make sure to load the EMEP, IMLM and wavesmon samples -%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') -%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') - -%set up the wavesmon data in a structure - -%what is the magnetic variation to nearest degree -magvar=-10; - -%first change to m^2/Hz/deg -wmon.S=spec/(360*1000*1000); - -%what is the start angle -heading=sysinfo(18,:); -heading=heading/100; -sangle=heading+magvar; - -%what is the frequency and dir resolution for those generated in DIWASP -freqres=0.01; -freqs=[0.01:0.01:.4]; -dirres=2; -dirs=[-180:2:180]; - -%set up the directions -adj_angle=90-sangle+360+180; -wmon.dirs=[adj_angle:-4:-(356-adj_angle)]; -wmondirres=4; -wmon.xaxisdir=90; -wmon.freqs=[0.00781250:0.00781250:1]; -wmonfreqres=0.00781250; - -% plot the spectrum generated through DIWASP -scrsz = get(0,'ScreenSize'); -fig5=figure('Position',[scrsz]); -subplot(2,3,1); -subplotspec(radialE,4); -title('EMEP radial vel'); - -subplot(2,3,2); -subplotspec(radialI,4); -title('IMLM radial vel'); - -subplot(2,3,3); -subplotspec(wmon,4); -title('Wavesmon output'); - - -%calculate just the dir energy spectrum on a single graph - -EMEPdir=sum(radialE.S)*freqres; -IMLMdir=sum(real(radialI.S))*freqres; -wmondir=sum(wmon.S)*wmonfreqres; - -%calculate just the frequency energy spectrum -EMEPfreq=sum(radialE.S')*dirres; -IMLMfreq=sum(real(radialI.S)')*dirres; -wmonfreq=sum(wmon.S')*wmondirres; - -%Compute the coefficient for the upper and lower error bounds for the -%frequency -%spectrum assuming 95% confidence. Added on 9/17/08 -degF=radialE.degF; -chiUp=chi2inv(.975,degF); -chiLow=chi2inv(.025,degF); -coeffUp=degF/chiLow; -coeffLow=degF/chiUp; - -%calculate the conf limits throughout the frequency spectrum -EMEPfreqUP=EMEPfreq*coeffUp; -EMEPfreqLOW=EMEPfreq*coeffLow; - -%Find the maximum for the directional spectrum so we can set up the proper -%x-axis -[maxvalue,maxindex] = max(EMEPdir); -maxdir=dirs(maxindex); -% set up the x-axis for all of the spectra depending on the max -if ((100 < maxdir) | (maxdir < -100)); - %for diwasp spectra - index1=find(dirs < 0); - index2=find(dirs > -1); - dirs(index1)=dirs(index1) +360; - %for wavesmon - Aindex=find(wmon.dirs < 0); - Bindex=find((-1 < wmon.dirs) & (wmon.dirs < 361)); - Bindex2=find(wmon.dirs > 360); - wmon.dirs(Bindex2)=wmon.dirs(Bindex2)-360; - wmon.dirs(Aindex)=wmon.dirs(Aindex)+360; - %plot the directional energy spectrum - fig6=figure('Position',[scrsz]); - subplot(1,2,1); - h1 = plot(dirs(index2),EMEPdir(index2),'b'); - hold on - h1a= plot(dirs(index1),EMEPdir(index1),'b'); - %plot the wavesmon data - h2 = plot(wmon.dirs(Bindex2),wmondir(Bindex2),'k'); - h2a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); - h2b= plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); - axis(axis); - h5 = plot(dirs(index2),IMLMdir(index2),'c'); - h5a= plot(dirs(index1),IMLMdir(index1),'c'); - -else - %for diwasp spectra do nothing - - %for wavesmon - Aindex=find(wmon.dirs > 180); - Bindex=find(wmon.dirs < 181); - wmon.dirs(Aindex)=wmon.dirs(Aindex)-360; - %plot the directional energy spectrum - fig6=figure('Position',[scrsz]); - subplot(1,2,1); - h1 = plot(dirs,EMEPdir,'b'); - hold on - %plot the wavesmon data - h2 = plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); - h2a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); - axis(axis); - h5 = plot(dirs,IMLMdir,'c'); -end - -legend([h1, h2,h5], 'EMEP radial vel','wavesmon','IMLM radial vel','location','best'); -title('directional wave spectrum integrated over frequency'); -xlabel('axis angle (degrees true)'); -ylabel('m^2 / deg'); - -%plot the frequency energy spectrum -subplot(1,2,2); -h1 = plot(freqs,EMEPfreq,'b'); -hold on -%h2 = plot(freqs,EMEPfreqLOW,'b--'); -%h3 = plot(freqs,EMEPfreqUP,'b--'); -h4 = plot(wmon.freqs,wmonfreq,'k'); -axis(axis); -h5 = plot(freqs,IMLMfreq,'c'); -legend([h1,h4,h5],'EMEP radial vel','wavesmon','IMLM radial vel','location','best'); -title('directional wave spectrum integrated over direction'); -xlabel('frequency in Hz'); -ylabel('m^2 / Hz'); - -% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ - -%For EMEP radial - -%calculate the 0,1,2 moments -m0=sum(EMEPfreq*freqres); -m1=sum(freqs.*EMEPfreq*freqres); -m2=sum((freqs.^2).*EMEPfreq*freqres); -% Calculate the Sig wave height -EMEP_radial_Hsig=4*sqrt(m0); -%Use the function HsigConf.m to calculate the sigH confidence limits -EMEP_HsConf=HsigConf(radialE); - -% Calculate the peak period Tp -[P,I]=max(EMEPfreq); -EMEP_radial_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(radialE.S(I,:))); -EMEP_radial_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(EMEPdir); -EMEP_radial_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP radial vel']); -disp(['SigH (meters): ' num2str(EMEP_radial_Hsig)]); -disp(['SigH 95% confidence limits: ' num2str(EMEP_HsConf)]); -disp(['peak period (seconds): ' num2str(EMEP_radial_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(EMEP_radial_DTp, radialE.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(EMEP_radial_Dp, radialE.xaxisdir))]); -disp([' ']); - -E_radial_WI.hsig=EMEP_radial_Hsig; -E_radial_WI.hconf=EMEP_HsConf; -E_radial_WI.tp=EMEP_radial_Tp; -E_radial_WI.dtp=compangle(EMEP_radial_DTp, radialE.xaxisdir); -E_radial_WI.dp=compangle(EMEP_radial_Dp, radialE.xaxisdir); - -% For IMLM r - -%calculate the 0,1,2 moments -m0=sum(IMLMfreq*freqres); -m1=sum(freqs.*IMLMfreq*freqres); -m2=sum((freqs.^2).*IMLMfreq*freqres); -% Calculate the Sig wave height -IMLM_radial_Hsig=4*sqrt(m0); -%Use the function HsigConf.m to calculate the sigH confidence limits -IMLM_HsConf=HsigConf(radialI); - -% Calculate the peak period Tp -[P,I]=max(IMLMfreq); -IMLM_radial_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(radialI.S(I,:))); -IMLM_radial_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(IMLMdir); -IMLM_radial_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM radial vel']); -disp(['SigH (meters): ' num2str(IMLM_radial_Hsig)]); -disp(['SigH 95% confidence limits: ' num2str(IMLM_HsConf)]); -disp(['peak period (seconds): ' num2str(IMLM_radial_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(IMLM_radial_DTp, radialI.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(IMLM_radial_Dp, radialI.xaxisdir))]); -disp([' ']); - -I_radial_WI.hsig=IMLM_radial_Hsig; -I_radial_WI.hconf=IMLM_HsConf; -I_radial_WI.tp=IMLM_radial_Tp; -I_radial_WI.dtp=compangle(IMLM_radial_DTp, radialI.xaxisdir); -I_radial_WI.dp=compangle(IMLM_radial_Dp, radialI.xaxisdir); - -% for wavesmon - -%calculate the 0,1,2 moments -m0=sum(wmonfreq*wmonfreqres); -m1=sum(wmon.freqs.*wmonfreq*wmonfreqres); -m2=sum((wmon.freqs.^2).*wmonfreq*wmonfreqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(wmonfreq); -Tp=1/(wmon.freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(wmon.S(I,:))); -DTp=wmon.dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(wmondir); -Dp=wmon.dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['Wavesmon output']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, wmon.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, wmon.xaxisdir))]); -disp([' ']); - - -%function to change from axis angles to compass bearings - -function angle=compangle(angle,xaxisdir) -angle=xaxisdir*ones(size(angle))-angle; -angle=angle+360*(angle<0); -angle=angle-360*(angle>360); - - - - - Index: DPWavesProc/trunk/DPWavesProc/adcp_matlab/specmultiplot.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/adcp_matlab/specmultiplot.m (revision 222) +++ DPWavesProc/trunk/DPWavesProc/adcp_matlab/specmultiplot.m (revision 225) @@ -67,5 +67,5 @@ %Use waveplot to plot the polar, freq and dir plots of the spectra - [E_radial_WI,fig1,fig2]=waveplottest1(radialE,sysinfo); + [E_radial_WI,fig1,fig2]=waveplot(radialE,sysinfo); saveas(fig1,['polar1_' dateinfo '.fig']); @@ -151,5 +151,5 @@ %now create the time series plots of the wave info -[fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot1(Winfo); +[fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot(Winfo); saveas(fig_sigh,['sigh_' dateinfo '.fig']); Index: DPWavesProc/trunk/DPWavesProc/adcp_matlab/specmultiplot1.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/adcp_matlab/specmultiplot1.m (revision 216) +++ (revision ) @@ -1,159 +1,0 @@ -function [Winfo,spec2d,fd,thetad,td]=specmultiplot1(dateinfo1,dateinfo2,timestep); -%where dateinfo1 and 2 are the strings of the first and last date extension -%of the pressure,range,etc files and timestep is the time in hours between -%each burst - -%This function takes the pressure, range, orbit and sysinfo files created -%in python and outputs a Winfo data structure with the sig wave height, -%peak period, direction of peak period and dominant dir. It also generates -%polar plots and 2d freq and directional plots of a variety of different -%estimation methods, resolutions and the wavesmon output. - - -%first set up the time vector going from dateinfo1 to dateinfo2 -Winfo.time=[]; - -date1=datevec(dateinfo1, 'yymmddHHMM'); -date2=datevec(dateinfo2,'yymmddHHMM'); - -if date1 == date2 - Winfo.time=[datenum(date1)]; -else - Winfo.time=[datenum(date1)]; - newdate=date1; - while datenum(newdate) ~= datenum(date2) - newdate=newdate+[0 0 0 timestep 0 0]; - Winfo.time=[horzcat(Winfo.time,datenum(newdate))]; - end -end - -%Make a directory for the data -mkdir('tempdir'); - -%set up time, which is Winfo.time as date str in the yymmddHHMM format -time=datestr(Winfo.time, 'yymmddHHMM'); - -%set up data structure for wave info -Winfo.setup={'EMEP radial'}; -Winfo.hsig=[]; -Winfo.hconf=[]; -Winfo.peakP=[]; -Winfo.dirP=[]; -Winfo.Ddir=[]; -Winfo.Spectrum.EMEPradial=[]; - -%Load the data and run the script -for i=1:length(time(:,1)) - dateinfo=time(i,:); - - pressure=strcat('pressure_',dateinfo,'.txt'); - range=strcat('range_',dateinfo,'.txt'); - orbit=strcat('orbit_',dateinfo,'.txt'); - sysinfo=strcat('sysinfo_',dateinfo,'.txt'); - - - pressure=load(pressure); - range=load(range); - orbit=load(orbit); - sysinfo=load(sysinfo); - - - %set up data with radial velocities, freq and dir at default - [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,3); - - % run diwasp to generate this spectrum with EMEP - [radialE, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %Use waveplot to plot the polar, freq and dir plots of the spectra - - [E_radial_WI,fig1,fig2]=waveplottest1(radialE,sysinfo); - - saveas(fig1,['polar1_' dateinfo '.fig']); - saveas(fig2,['dirfreq1_' dateinfo '.fig']); - - movefile(['polar1_' dateinfo '.fig'],'tempdir'); - movefile(['dirfreq1_' dateinfo '.fig'],'tempdir'); - close all; - - - %Fill up the Winfo data structure - - hsig=[vertcat(E_radial_WI.hsig)]; - hconf=[vertcat(E_radial_WI.hconf)]; - peakP=[vertcat(E_radial_WI.tp)]; - dirP=[vertcat(E_radial_WI.dtp)]; - Ddir=[vertcat(E_radial_WI.dp)]; - - - Winfo.hsig=[horzcat(Winfo.hsig,hsig)]; - Winfo.hconf=[horzcat(Winfo.hconf,hconf)]; - Winfo.peakP=[horzcat(Winfo.peakP,peakP)]; - Winfo.dirP=[horzcat(Winfo.dirP,dirP)]; - Winfo.Ddir=[horzcat(Winfo.Ddir,Ddir)]; - Winfo.Spectrum.EMEPradial=[cat(3,Winfo.Spectrum.EMEPradial,radialE.S)]; -end - -Winfo.Spectrum.EMEPradial=permute(Winfo.Spectrum.EMEPradial,[3,1,2]); - -%this is added in to format the data for Xwaves (using radial velocities) - -spec2d=Winfo.Spectrum.EMEPradial; -spec2d=spec2d(:,:,1:180); -%firstspec=spec2d(:,:,91:180); -%nextspec=spec2d(:,:,1:90); -%spec2d=cat(3,firstspec,nextspec); -spec2d=spec2d*(360/(2*pi)); - -%this changes the coordinates from axis to compass -newspec2d=zeros(size(spec2d)); -for i= 1:size(spec2d,1) - oldspec=squeeze(spec2d(i,:,:)); - - newspec=zeros(size(oldspec)); - - for j = 1:46 - newspec(:,j)=oldspec(:,47-j); - end - for j = 47:180 - newspec(:,j)=oldspec(:,181-(j-46)); - end - - %firstspec=newspec(:,91:180); - %secondspec=newspec(:,1:90); - %newspec=cat(2,firstspec,secondspec); - - newspec2d(i,:,:)=newspec; -end -spec2d=newspec2d; - - -fd=[0.01:0.01:0.4]; -thetad=[0:2:358]; -date1=datevec(Winfo.time); -td=date1(:,1:5); - -save(['specdata_' dateinfo],'Winfo','spec2d','fd','thetad','td'); -movefile(['specdata_' dateinfo '.mat'],'tempdir'); - - - -%now create the time series plots of the wave info -[fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot1(Winfo); - -saveas(fig_sigh,['sigh_' dateinfo '.fig']); -saveas(fig_pp,['peakp_' dateinfo '.fig']); -saveas(fig_dp,['dirpeak_' dateinfo '.fig']); -saveas(fig_dd,['domdir_' dateinfo '.fig']); - -movefile(['sigh_' dateinfo '.fig'],'tempdir'); -movefile(['peakp_' dateinfo '.fig'],'tempdir'); -movefile(['dirpeak_' dateinfo '.fig'],'tempdir'); -movefile(['domdir_' dateinfo '.fig'],'tempdir'); - -movefile('tempdir',strcat('procdata_',dateinfo)); - -close all; - - - - Index: DPWavesProc/trunk/DPWavesProc/adcp_matlab/waveplot.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/adcp_matlab/waveplot.m (revision 224) +++ DPWavesProc/trunk/DPWavesProc/adcp_matlab/waveplot.m (revision 225) @@ -1,3 +1,3 @@ -function [E_UVW_WI,I_UVW_WI,E_range_WI,I_range_WI,wmon_WI,fig1,fig2]=waveplot(EMEP,IMLM,rangeE,rangeI,spec,sysinfo) +function [E_radial_WI,fig1,fig2]=waveplottest1(radialE,sysinfo) %make sure to load the EMEP, IMLM and wavesmon samples @@ -8,8 +8,5 @@ %what is the magnetic variation to nearest degree -magvar=-10; - -%first change to m^2/Hz/deg -wmon.S=spec/(360*1000*1000); +magvar=10; %what is the start angle @@ -26,9 +23,4 @@ %set up the directions adj_angle=90-sangle+360+180; -wmon.dirs=[adj_angle:-4:-(356-adj_angle)]; -wmondirres=4; -wmon.xaxisdir=90; -wmon.freqs=[0.00781250:0.00781250:1]; -wmonfreqres=0.00781250; % plot the spectrum generated through DIWASP @@ -36,50 +28,20 @@ scrsz = get(0,'ScreenSize'); fig1=figure('Position',[scrsz]); -subplot(2,3,1); -subplotspec(EMEP,4); -title('EMEP uvw'); +subplot(1,1,1); +subplotspec(radialE,4); +title('radial velocity data'); -subplot(2,3,2); -subplotspec(IMLM,4); -title('IMLM uvw'); - -subplot(2,3,3); -subplotspec(wmon,4); -title('Wavesmon output'); - -subplot(2,3,4); -subplotspec(rangeE,4); -title('EMEP Range'); - -subplot(2,3,5); -subplotspec(rangeI,4); -title('IMLM Range'); %calculate just the dir energy spectrum on a single graph -EMEPdir=sum(EMEP.S)*freqres; -IMLMdir=sum(real(IMLM.S))*freqres; -EMEPrangedir=sum(rangeE.S)*freqres; -IMLMrangedir=sum(real(rangeI.S))*freqres; -wmondir=sum(wmon.S)*wmonfreqres; + +EMEPradialdir=sum(radialE.S)*freqres; %calculate just the frequency energy spectrum -EMEPfreq=sum(EMEP.S')*dirres; -IMLMfreq=sum(real(IMLM.S)')*dirres; -EMEPrangefreq=sum(rangeE.S')*dirres; -IMLMrangefreq=sum(real(rangeI.S)')*dirres; -wmonfreq=sum(wmon.S')*wmondirres; - -%Compute the coefficient for the upper and lower error bounds for the power -%spectrum assuming 95% confidence. Added on 9/17/08 -degF=EMEP.degF; -chiUp=chi2inv(.975,degF); -chiLow=chi2inv(.025,degF); -coeffUp=degF/chiLow; -coeffLow=degF/chiUp; +EMEPradialfreq=sum(radialE.S')*dirres; %Find the maximum for the directional spectrum so we can set up the proper %x-axis -[maxvalue,maxindex] = max(EMEPdir); +[maxvalue,maxindex] = max(EMEPradialdir); maxdir=dirs(maxindex); % set up the x-axis for all of the spectra depending on the max @@ -89,50 +51,20 @@ index2=find(dirs > -1); dirs(index1)=dirs(index1) +360; - %for wavesmon - Aindex=find(wmon.dirs < 0); - Bindex=find((-1 < wmon.dirs) & (wmon.dirs < 361)); - Bindex2=find(wmon.dirs > 360); - wmon.dirs(Bindex2)=wmon.dirs(Bindex2)-360; - wmon.dirs(Aindex)=wmon.dirs(Aindex)+360; %plot the directional energy spectrum fig2=figure('Position',[scrsz]); subplot(1,2,1); - h1 = plot(dirs(index2),EMEPdir(index2),'b'); + h1 = plot(dirs(index2),EMEPradialdir(index2),'b'); hold on - h1a= plot(dirs(index1),EMEPdir(index1),'b'); - h2 = plot(dirs(index2),EMEPrangedir(index2),'r'); - h2a= plot(dirs(index1),EMEPrangedir(index1),'r'); - h3 = plot(dirs(index2),IMLMrangedir(index2),'g'); - h3a= plot(dirs(index1),IMLMrangedir(index1),'g'); - %plot the wavesmon data - h4 = plot(wmon.dirs(Bindex2),wmondir(Bindex2),'k'); - h4a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); - h4b= plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); - axis(axis); - h5 = plot(dirs(index2),IMLMdir(index2),'c'); - h5a= plot(dirs(index1),IMLMdir(index1),'c'); - + h1a= plot(dirs(index1),EMEPradialdir(index1),'b'); else %for diwasp spectra do nothing - %for wavesmon - Aindex=find(wmon.dirs > 180); - Bindex=find(wmon.dirs < 181); - wmon.dirs(Aindex)=wmon.dirs(Aindex)-360; %plot the directional energy spectrum fig2=figure('Position',[scrsz]); subplot(1,2,1); - h1 = plot(dirs,EMEPdir,'b'); - hold on - h2 = plot(dirs,EMEPrangedir,'r'); - h3 = plot(dirs,IMLMrangedir,'g'); - %plot the wavesmon data - h4 = plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); - h4a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); - axis(axis); - h5 = plot(dirs,IMLMdir,'c'); + h1 = plot(dirs,EMEPradialdir,'b'); end -legend([h1, h2, h3, h4, h5],'EMEP uvw','EMEP range','IMLM range','wavesmon','IMLM uvw','location','best'); +legend([h1],'EMEP radial','location','best'); title('directional wave spectrum integrated over frequency'); xlabel('axis angle (degrees true)'); @@ -141,12 +73,6 @@ %plot the frequency energy spectrum subplot(1,2,2); -plot(freqs,EMEPfreq,'b'); -hold on -plot(freqs,EMEPrangefreq,'r'); -plot(freqs,IMLMrangefreq,'g'); -plot(wmon.freqs,wmonfreq,'k'); -axis(axis); -plot(freqs,IMLMfreq,'c'); -legend('EMEP uvw','EMEP range','IMLM range','wavesmon','IMLM uvw','location','best'); +plot(freqs,EMEPradialfreq,'b'); +legend('EMEP radial','location','best'); title('directional wave spectrum integrated over direction'); xlabel('frequency in Hz'); @@ -155,174 +81,39 @@ % ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ -%For EMEP uvw + +% for Radial of EMEP + % Calculate the Sig wave height -EMEP_UVW_Hsig=Hsig(EMEP); +EMEP_radial_Hsig=Hsig(radialE); %Use the function HsigConf.m to calculate the sigH confidence limits -EMEP_HsConf=HsigConf(EMEP); +EMEP_radial_HsConf=HsigConf(radialE); % Calculate the peak period Tp -[P,I]=max(EMEPfreq); -EMEP_UVW_Tp=1/(freqs(I)); +[P,I]=max(EMEPradialfreq); +EMEP_radial_Tp=1/(freqs(I)); %Calculate the Direction of the peak period DTp -[P,I]=max(real(EMEP.S(I,:))); -EMEP_UVW_DTp=dirs(I); +[P,I]=max(real(radialE.S(I,:))); +EMEP_radial_DTp=dirs(I); %Calculate the Dominant Direction Dp -[P,I]=max(EMEPdir); -EMEP_UVW_Dp=dirs(I); +[P,I]=max(EMEPradialdir); +EMEP_radial_Dp=dirs(I); %Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP uvw']); -disp(['SigH (meters): ' num2str(EMEP_UVW_Hsig)]); -disp(['SigH 95% confidence limits: ' num2str(EMEP_HsConf)]); -disp(['peak period (seconds): ' num2str(EMEP_UVW_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(EMEP_UVW_DTp, EMEP.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(EMEP_UVW_Dp, EMEP.xaxisdir))]); +disp(['EMEP radial']); +disp(['SigH (meters): ' num2str(EMEP_radial_Hsig)]); +disp(['SigH 95% confidence limits: ' num2str(EMEP_radial_HsConf)]); +disp(['peak period (seconds): ' num2str(EMEP_radial_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(EMEP_radial_DTp, radialE.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(EMEP_radial_Dp, radialE.xaxisdir))]); disp([' ']); -E_UVW_WI.hsig=EMEP_UVW_Hsig; -E_UVW_WI.hconf=EMEP_HsConf; -E_UVW_WI.tp=EMEP_UVW_Tp; -E_UVW_WI.dtp=compangle(EMEP_UVW_DTp, EMEP.xaxisdir); -E_UVW_WI.dp=compangle(EMEP_UVW_Dp, EMEP.xaxisdir); +E_radial_WI.hsig=EMEP_radial_Hsig; +E_radial_WI.hconf=EMEP_radial_HsConf; +E_radial_WI.tp=EMEP_radial_Tp; +E_radial_WI.dtp=compangle(EMEP_radial_DTp, radialE.xaxisdir); +E_radial_WI.dp=compangle(EMEP_radial_Dp, radialE.xaxisdir); - -% For IMLM uvw - -% Calculate the Sig wave height -IMLM_UVW_Hsig=Hsig(IMLM); -%Use the function HsigConf.m to calculate the sigH confidence limits -IMLM_HsConf=HsigConf(IMLM); - -% Calculate the peak period Tp -[P,I]=max(IMLMfreq); -IMLM_UVW_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(IMLM.S(I,:))); -IMLM_UVW_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(IMLMdir); -IMLM_UVW_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM uvw']); -disp(['SigH (meters): ' num2str(IMLM_UVW_Hsig)]); -disp(['SigH 95% confidence limits: ' num2str(IMLM_HsConf)]); -disp(['peak period (seconds): ' num2str(IMLM_UVW_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(IMLM_UVW_DTp, IMLM.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(IMLM_UVW_Dp, IMLM.xaxisdir))]); -disp([' ']); - -I_UVW_WI.hsig=IMLM_UVW_Hsig; -I_UVW_WI.hconf=IMLM_HsConf; -I_UVW_WI.tp=IMLM_UVW_Tp; -I_UVW_WI.dtp=compangle(IMLM_UVW_DTp, IMLM.xaxisdir); -I_UVW_WI.dp=compangle(IMLM_UVW_Dp, IMLM.xaxisdir); - -% for Range of EMEP - -% Calculate the Sig wave height -EMEP_range_Hsig=Hsig(rangeE); -%Use the function HsigConf.m to calculate the sigH confidence limits -EMEP_range_HsConf=HsigConf(rangeE); - -% Calculate the peak period Tp -[P,I]=max(EMEPrangefreq); -EMEP_range_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(rangeE.S(I,:))); -EMEP_range_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(EMEPrangedir); -EMEP_range_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP range']); -disp(['SigH (meters): ' num2str(EMEP_range_Hsig)]); -disp(['SigH 95% confidence limits: ' num2str(EMEP_range_HsConf)]); -disp(['peak period (seconds): ' num2str(EMEP_range_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(EMEP_range_DTp, rangeE.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(EMEP_range_Dp, rangeE.xaxisdir))]); -disp([' ']); - -E_range_WI.hsig=EMEP_range_Hsig; -E_range_WI.hconf=EMEP_range_HsConf; -E_range_WI.tp=EMEP_range_Tp; -E_range_WI.dtp=compangle(EMEP_range_DTp, rangeE.xaxisdir); -E_range_WI.dp=compangle(EMEP_range_Dp, rangeE.xaxisdir); - - -%for Range of IMLM - -% Calculate the Sig wave height -IMLM_range_Hsig=Hsig(rangeI); -%Use the function HsigConf.m to calculate the sigH confidence limits -IMLM_range_HsConf=HsigConf(rangeI); - -% Calculate the peak period Tp -[P,I]=max(IMLMrangefreq); -IMLM_range_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(rangeI.S(I,:))); -IMLM_range_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(IMLMrangedir); -IMLM_range_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM range']); -disp(['SigH (meters): ' num2str(IMLM_range_Hsig)]); -disp(['SigH 95% confidence limits: ' num2str(IMLM_range_HsConf)]); -disp(['peak period (seconds): ' num2str(IMLM_range_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(IMLM_range_DTp, rangeI.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(IMLM_range_Dp, rangeI.xaxisdir))]); -disp([' ']); - -I_range_WI.hsig=IMLM_range_Hsig; -I_range_WI.hconf=IMLM_range_HsConf; -I_range_WI.tp=IMLM_range_Tp; -I_range_WI.dtp=compangle(IMLM_range_DTp, rangeI.xaxisdir); -I_range_WI.dp=compangle(IMLM_range_Dp, rangeI.xaxisdir); - -% for wavesmon - -%calculate the 0,1,2 moments -m0=sum(wmonfreq*wmonfreqres); -m1=sum(wmon.freqs.*wmonfreq*wmonfreqres); -m2=sum((wmon.freqs.^2).*wmonfreq*wmonfreqres); -% Calculate the Sig wave height -wmon_Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(wmonfreq); -wmon_Tp=1/(wmon.freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(wmon.S(I,:))); -wmon_DTp=wmon.dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(wmondir); -wmon_Dp=wmon.dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['Wavesmon output']); -disp(['SigH (meters): ' num2str(wmon_Hsig)]); -disp(['peak period (seconds): ' num2str(wmon_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(wmon_DTp, wmon.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(wmon_Dp, wmon.xaxisdir))]); -disp([' ']); - -wmon_WI.hsig=wmon_Hsig; -wmon_WI.tp=wmon_Tp; -wmon_WI.dtp=compangle(wmon_DTp, wmon.xaxisdir); -wmon_WI.dp=compangle(wmon_Dp, wmon.xaxisdir); Index: DPWavesProc/trunk/DPWavesProc/adcp_matlab/waveplottest1.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/adcp_matlab/waveplottest1.m (revision 216) +++ (revision ) @@ -1,130 +1,0 @@ -function [E_radial_WI,fig1,fig2]=waveplottest1(radialE,sysinfo) - -%make sure to load the EMEP, IMLM and wavesmon samples -%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') -%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') - -%set up the wavesmon data in a structure - -%what is the magnetic variation to nearest degree -magvar=10; - -%what is the start angle -heading=sysinfo(18,:); -heading=heading/100; -sangle=heading+magvar; - -%what is the frequency and dir resolution for those generated in DIWASP -freqres=0.01; -freqs=[0.01:0.01:.4]; -dirres=2; -dirs=[-180:2:180]; - -%set up the directions -adj_angle=90-sangle+360+180; - -% plot the spectrum generated through DIWASP - -scrsz = get(0,'ScreenSize'); -fig1=figure('Position',[scrsz]); -subplot(1,1,1); -subplotspec(radialE,4); -title('radial velocity data'); - - -%calculate just the dir energy spectrum on a single graph - - -EMEPradialdir=sum(radialE.S)*freqres; - -%calculate just the frequency energy spectrum -EMEPradialfreq=sum(radialE.S')*dirres; - -%Find the maximum for the directional spectrum so we can set up the proper -%x-axis -[maxvalue,maxindex] = max(EMEPradialdir); -maxdir=dirs(maxindex); -% set up the x-axis for all of the spectra depending on the max -if ((100 < maxdir) | (maxdir < -100)); - %for diwasp spectra - index1=find(dirs < 0); - index2=find(dirs > -1); - dirs(index1)=dirs(index1) +360; - %plot the directional energy spectrum - fig2=figure('Position',[scrsz]); - subplot(1,2,1); - h1 = plot(dirs(index2),EMEPradialdir(index2),'b'); - hold on - h1a= plot(dirs(index1),EMEPradialdir(index1),'b'); -else - %for diwasp spectra do nothing - - %plot the directional energy spectrum - fig2=figure('Position',[scrsz]); - subplot(1,2,1); - h1 = plot(dirs,EMEPradialdir,'b'); -end - -legend([h1],'EMEP radial','location','best'); -title('directional wave spectrum integrated over frequency'); -xlabel('axis angle (degrees true)'); -ylabel('m^2 / deg'); - -%plot the frequency energy spectrum -subplot(1,2,2); -plot(freqs,EMEPradialfreq,'b'); -legend('EMEP radial','location','best'); -title('directional wave spectrum integrated over direction'); -xlabel('frequency in Hz'); -ylabel('m^2 / hz'); - -% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ - - -% for Radial of EMEP - -% Calculate the Sig wave height -EMEP_radial_Hsig=Hsig(radialE); -%Use the function HsigConf.m to calculate the sigH confidence limits -EMEP_radial_HsConf=HsigConf(radialE); - -% Calculate the peak period Tp -[P,I]=max(EMEPradialfreq); -EMEP_radial_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(radialE.S(I,:))); -EMEP_radial_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(EMEPradialdir); -EMEP_radial_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP radial']); -disp(['SigH (meters): ' num2str(EMEP_radial_Hsig)]); -disp(['SigH 95% confidence limits: ' num2str(EMEP_radial_HsConf)]); -disp(['peak period (seconds): ' num2str(EMEP_radial_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(EMEP_radial_DTp, radialE.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(EMEP_radial_Dp, radialE.xaxisdir))]); -disp([' ']); - -E_radial_WI.hsig=EMEP_radial_Hsig; -E_radial_WI.hconf=EMEP_radial_HsConf; -E_radial_WI.tp=EMEP_radial_Tp; -E_radial_WI.dtp=compangle(EMEP_radial_DTp, radialE.xaxisdir); -E_radial_WI.dp=compangle(EMEP_radial_Dp, radialE.xaxisdir); - - - -%function to change from axis angles to compass bearings - -function angle=compangle(angle,xaxisdir) -angle=xaxisdir*ones(size(angle))-angle; -angle=angle+360*(angle<0); -angle=angle-360*(angle>360); - - - - - Index: DPWavesProc/trunk/DPWavesProc/adcpwaves.py =================================================================== --- DPWavesProc/trunk/DPWavesProc/adcpwaves.py (revision 95) +++ (revision ) @@ -1,361 +1,0 @@ -"""This code takes the raw waves portion of the adcp data from the splitter -and outputs pressure, range, orbital velocity and system info text files that -can be read into matlab.""" - - - - -import sys, struct, math, shutil, os - -try: - infileName = sys.argv[1] - -except: - print 'error' - sys.exit(1) - - -ifile = open(infileName, 'rb') - - -#header -firstHeader=31103 -Header=firstHeader -while Header == firstHeader: - readFirstHeader=ifile.read(2) - if len(readFirstHeader) == 0: - print('\n End of file') - break - - pressureOfile = open('pressure', 'w') - rangeOfile = open('range', 'w') - orbitOfile = open('orbit', 'w') - sysinfoOfile = open('sysinfo', 'w') - - Header =struct.unpack('H',readFirstHeader)[0] - #print 'headerID=', hex(Header) - - firstLeaderHeader=259 - wavePingHeader=515 - lastLeaderHeader=771 - - #read the length - length=ifile.read(2) - length=struct.unpack('H',length)[0] - - #read 4 bytes before the leader ID - ifile.read(4) - - readLeaderHeader=ifile.read(2) - leaderHeader =struct.unpack('H',readLeaderHeader)[0] - - if leaderHeader != firstLeaderHeader: - print('error with first leader header') - print hex(leaderHeader) - break - #read and write sysinfo - - #firmware version - readFwVersion=ifile.read(2) - fwVersion=struct.unpack('H',readFwVersion)[0] - sysinfoOfile.write(str(fwVersion)) - sysinfoOfile.write('\n') - - #Configuration (not sure what to do with this) - ifile.read(2) - - # number of depth cells - readNbins=ifile.read(1) - Nbins= struct.unpack('B',readNbins)[0] - sysinfoOfile.write(str(Nbins)) - sysinfoOfile.write('\n') - - #Samples per wave burst - readNumSamples=ifile.read(2) - numSamples=struct.unpack('H',readNumSamples)[0] - sysinfoOfile.write(str(numSamples)) - sysinfoOfile.write('\n') - - # Size of depth cell - readBinLength=ifile.read(2) - binLength= struct.unpack('H',readBinLength)[0] - #change size to meters - binLength=binLength/100.00 - sysinfoOfile.write(str(binLength)) - sysinfoOfile.write('\n') - - #Time between wave samples - readTBS=ifile.read(2) - TBS=struct.unpack('H',readTBS)[0] - sysinfoOfile.write(str(TBS)) - sysinfoOfile.write('\n') - - #Time between wave bursts - readTBB=ifile.read(2) - TBB=struct.unpack('H',readTBB)[0] - sysinfoOfile.write(str(TBB)) - sysinfoOfile.write('\n') - - # distance to first bin - readDist1=ifile.read(2) - dist1= struct.unpack('H',readDist1)[0] - #change distance to meters - dist1=dist1/100.00 - sysinfoOfile.write(str(dist1)) - sysinfoOfile.write('\n') - - - # number of bins output - readBinsOut=ifile.read(1) - binsOut= struct.unpack('B',readBinsOut)[0] - sysinfoOfile.write(str(binsOut)) - sysinfoOfile.write('\n') - - #reserved data (?) - ifile.read(2) - - #skip the directional bitmap - ifile.read(16) - - #read and write the bitmap for what bins are output - readByteList=ifile.read(16) - byteList=struct.unpack('16B',readByteList) - - def int2msbits(n, count=8): - """returns the most-significant binary of integer n, using count number of digits""" - return "".join([str((n >> y) & 1) for y in range(0, count)]) - - bytemap = '' - bitmap = '' - for ind in range(len(byteList)): - byte = struct.pack('B', byteList[ind]) - bytemap += byte - bits = int2msbits(byteList[ind]) - bitmap += bits - - # find indexes from bit map - # (1) one way to get indices of 1's - ind = []; - for i in range(len(bitmap)): - if bitmap[i]=='1': ind.append(i) - - # transducer height above the bottom - th = 0.4 - - # heights above transducer - hat = [dist1+(binLength*elem) for elem in ind] - - # heights above bottom - hab = [th+elem for elem in hat] - - for value in hab: - sysinfoOfile.write(str(value)) - sysinfoOfile.write('\n') - - - #Read start time and write to file - readCentury=ifile.read(1) - century =struct.unpack('B',readCentury)[0] - - readYear=ifile.read(1) - year =struct.unpack('B',readYear)[0] - - readMonth=ifile.read(1) - month=struct.unpack('B',readMonth)[0] - - readDay=ifile.read(1) - day=struct.unpack('B',readDay)[0] - - readHour=ifile.read(1) - hour=struct.unpack('B',readHour)[0] - - readMinute=ifile.read(1) - minute=struct.unpack('B',readMinute)[0] - - readSecond=ifile.read(1) - second=struct.unpack('B',readSecond)[0] - - readHundSec=ifile.read(1) - hundSec=struct.unpack('B',readHundSec)[0] - - startTime=str(century)+str('%02d' % year)+str('%02d' % month)+str('%02d' % day)+str('%02d' % hour)+str('%02d' % minute)+str('%02d' % second)+str('%02d' % hundSec) - - #create a time stamp for the file names that only includes from year up to minutes - FileStamp=str('%02d' % year)+str('%02d' % month)+str('%02d' % day)+str('%02d' % hour)+str('%02d' % minute) - - sysinfoOfile.write(startTime) - sysinfoOfile.write('\n') - - #Burst number (how to unpack this? dont think we need it) - readBurstNum=ifile.read(4) - - #Serial number (how to unpack this? dont think we need it) - readSerial=ifile.read(8) - - #Temperature (dont need this, use the avg temp instead) - readTemp=ifile.read(2) - - - #Reserved space (?) - ifile.read(8) - - - - # Done with the First Leader Type>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> - - - #Wave Ping Type - - leaderHeader = wavePingHeader - while leaderHeader == wavePingHeader: - - - #read the length - length=ifile.read(2) - if len(length) == 0: - print('\n End of file') - break - length=struct.unpack('H',length)[0] - - #read 4 bytes before the leader ID - ifile.read(4) - - readLeaderHeader=ifile.read(2) - leaderHeader =struct.unpack('H',readLeaderHeader)[0] - - # if the leader header isnt the wave ping header move on to the next leader - if leaderHeader != wavePingHeader: - break - - #read through sample number and time since burst (don't need this) - ifile.read(6) - - #read and write the pressure data - pressure=ifile.read(4) - pressure=struct.unpack('I',pressure)[0] - - pressureOfile.write(str(pressure)) - pressureOfile.write('\n') - - #read and write the range data - - range1=ifile.read(4) - range1=struct.unpack('I',range1)[0] - rangeOfile.write(str(range1)) - rangeOfile.write(' ') - - range2=ifile.read(4) - range2=struct.unpack('I',range2)[0] - rangeOfile.write(str(range2)) - rangeOfile.write(' ') - - range3=ifile.read(4) - range3=struct.unpack('I',range3)[0] - rangeOfile.write(str(range3)) - rangeOfile.write(' ') - - range4=ifile.read(4) - range4=struct.unpack('I',range4)[0] - rangeOfile.write(str(range4)) - rangeOfile.write('\n') - - - #read and write the orbital velocity data - - bytes=40 - - while bytes > 0: - orbit=ifile.read(2) - orbit=struct.unpack('h',orbit)[0] - orbitOfile.write('%06d' % orbit) - orbitOfile.write(' ') - bytes=bytes-2 - - orbitOfile.write('\n') - - #reserved space (?) - ifile.read(6) - - # Done with the Wave Ping Type>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> - - - - #readLeaderHeader=ifile.read(2) - #leaderHeader =struct.unpack('H',readLeaderHeader)[0] - - if leaderHeader != lastLeaderHeader: - break - - #average depth - readAvgDepth= ifile.read(2) - avgDepth= struct.unpack('H', readAvgDepth)[0] - sysinfoOfile.write(str(avgDepth)) - sysinfoOfile.write('\n') - - #Average speed of sound in m/s - readAvgSound=ifile.read(2) - avgSound=struct.unpack('H',readAvgSound)[0] - sysinfoOfile.write(str(avgSound)) - sysinfoOfile.write('\n') - - #Average Temp in .01 deg C - readAvgTemp=ifile.read(2) - avgTemp=struct.unpack('H',readAvgTemp)[0] - sysinfoOfile.write(str(avgTemp)) - sysinfoOfile.write('\n') - - #heading - readHeading= ifile.read(2) - heading= struct.unpack('H', readHeading)[0] - sysinfoOfile.write(str(heading)) - sysinfoOfile.write('\n') - - #skip the std dev heading - ifile.read(2) - - #pitch - readPitch= ifile.read(2) - pitch= struct.unpack('h', readPitch)[0] - sysinfoOfile.write(str(pitch)) - sysinfoOfile.write('\n') - - #skip the std dev pitch - stdPitch=ifile.read(2) - - #Roll - readRoll= ifile.read(2) - roll= struct.unpack('h', readRoll)[0] - sysinfoOfile.write(str(roll)) - sysinfoOfile.write('\n') - - #skip std dev roll and last 4 bytes (what are they? maybe a checksum?) - stdRoll=ifile.read(2) - - test1=ifile.read(2) - - test2=ifile.read(2) - - - - - pressureOfile.close() - rangeOfile.close() - orbitOfile.close() - sysinfoOfile.close() - - - shutil.copy('pressure','pressure_'+FileStamp+'.txt') - shutil.copy('orbit','orbit_'+FileStamp+'.txt') - shutil.copy('range','range_'+FileStamp+'.txt') - shutil.copy('sysinfo','sysinfo_'+FileStamp+'.txt') - - os.remove('pressure') - os.remove('orbit') - os.remove('range') - os.remove('sysinfo') - - -ifile.close() -print 'processing complete' - - Index: DPWavesProc/trunk/DPWavesProc/compangle.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/compangle.m (revision 216) +++ (revision ) @@ -1,6 +1,0 @@ -%function to change from axis angles to compass bearings - -function angle=compangle(angle,xaxisdir) -angle=xaxisdir*ones(size(angle))-angle; -angle=angle+360*(angle<0); -angle=angle-360*(angle>360); Index: DPWavesProc/trunk/DPWavesProc/diwasp_1_1GD/compangle.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/diwasp_1_1GD/compangle.m (revision 225) @@ -1,0 +1,6 @@ +%function to change from axis angles to compass bearings + +function angle=compangle(angle,xaxisdir) +angle=xaxisdir*ones(size(angle))-angle; +angle=angle+360*(angle<0); +angle=angle-360*(angle>360); Index: DPWavesProc/trunk/DPWavesProc/pd0.py =================================================================== --- DPWavesProc/trunk/DPWavesProc/pd0.py (revision 40) +++ (revision ) @@ -1,242 +1,0 @@ -#!/usr/bin/python -"""Functions to handle Acoustic Doppler Current Profiler data. - -As a script (to split a raw PD0 file into waves and currents): - -python pd0.py [path] rawFile wavesFile currentsFile -python pd0.py [-p path] -r rawFile -w wavesFile -c currentsFile -python pd0.py [--path=path] \\ - --raw=rawFile \\ - --waves=wavesFile \\ - --currents=currentsFile - -where: - path is a path to prepend to the following - rawFile is path of raw PD0 format input file - wavesFile is path of waves PD0 format output file - currentsFile is path of currents PD0 format output file - -or (to run the test suite): - -python pd0.py -t -python pd0.py --test - -or (to see this help message): - -python pd0.py -h -python pd0.py --help - -As a module: - -import adcp.pd0 -adcp.pd0.split(rawFile,wavesFile,currentsFile) - -where: - rawFile is a file object representing the raw PD0 format input - wavesFile is a file object representing the waves PD0 format output - currentsFile is a file object representing the currents PD0 format output -""" - -import struct - -# -# The rawfile is assumed to be in PD0 format. -# -# PD0 format assumes the file is a succession of ensembles. -# -# Each ensemble starts with a two byte header identifying the type of data -# contained in the ensemble. -# -# Following the header is a two byte length field specifying the length of -# the header, length field, and data combined -# -# Following the length field is raw data for the number of bytes indicated by -# the length field -# -# Following the raw data is a checksum field which is the two least -# significant bytes of the sum of the byte values of the header, length field, -# and raw data. -# -def split(rawFile,wavesFile,currentsFile): - """Split PD0 format data into seperate waves and currents - - split()rawFile,wavesFile,currentsFile -> None - """ - - # header IDs - wavesId=0x797f - currentsId=0x7f7f - - # convenience function reused for header, length, and checksum - def __nextLittleEndianUnsignedShort(file): - """Get next little endian unsigned short from file""" - raw = file.read(2) - return (raw, struct.unpack('= 0,(firstWaves,firstCurrents))) - - #seeks to the first occurence of a waves or currents data - rawFile.seek(firstEnsemble) - - # loop through raw data - rawHeader, header = __nextLittleEndianUnsignedShort(rawFile) - - while (header == wavesId) or (header == currentsId): - # get ensemble length - rawLength, length = __nextLittleEndianUnsignedShort(rawFile) - # read up to the checksum - rawEnsemble = rawFile.read(length-4) - # get checksum - rawChecksum, checksum = __nextLittleEndianUnsignedShort(rawFile) - - computedChecksum = __computeChecksum(rawHeader, rawLength, rawEnsemble) - - if checksum != computedChecksum: - raise IOError, "Checksum error" - - # append to output stream - if header == wavesId: - wavesFile.write(rawHeader) - wavesFile.write(rawLength) - wavesFile.write(rawEnsemble) - wavesFile.write(rawChecksum) - elif header == currentsId: - currentsFile.write(rawHeader) - currentsFile.write(rawLength) - currentsFile.write(rawEnsemble) - currentsFile.write(rawChecksum) - - try: - rawHeader, header = __nextLittleEndianUnsignedShort(rawFile) - except struct.error: - break - - -def test(): - """Execute test suite""" - try: - import adcp.tests.runalltests as runalltests - except: - # possible if executed as script - import sys,os - sys.path.append(os.path.join(os.path.dirname(__file__),'tests')) - import runalltests - runalltests.runalltests(subset='pd0') - -class __TestException(Exception): - """Flow control for running as script""" - pass - -# wrapper function -def __test(): - """Execute test suite from command line""" - test() - raise __TestException, 'Wrapper function for command line testing only' - -def __main(): - """Process as script from command line""" - import getopt,os,sys - - # get the command line options and arguments - path = '' - rawName,wavesName,currentsName = 3*[None] - - try: - opts, args = getopt.gnu_getopt(sys.argv[1:], - 'htp:r:w:c:', - ['help', - 'test', - 'path=', - 'raw=', - 'waves=', - 'currents=']) - for opt,arg in opts: - if opt in ['-h','--help']: - raise getopt.GetoptError,'' - if opt in ['-t','--test']: - __test() - elif opt in ['-p','--path']: - path = arg - elif opt in ['-r','--raw']: - rawName = arg - elif opt in ['-w','--waves']: - wavesName = arg - elif opt in ['-c','--currents']: - currentsName = arg - else: - raise getopt.GetoptError,'' - if (rawName is None) or \ - (wavesName is None) or \ - (currentsName is None): - if len(args) not in [3, 4]: - raise getopt.GetoptError,'' - else: - if (rawName is not None) or \ - (wavesName is not None) or \ - (currentsName is not None): - raise getopt.GetoptError,'' - else: - if len(args) == 4: - path = args[0] - del args[0] - rawName = args[0] - wavesName = args[1] - currentsName = args[2] - elif len(args) != 0: - raise getopt.GetoptError,'' - except getopt.GetoptError: - print __doc__ - return - except __TestException: - return - - # split a raw PD0 file - rawName = os.path.join(path, rawName) - print 'Raw file path:', rawName - wavesName = os.path.join(path, wavesName) - print 'Waves file path:', wavesName - currentsName = os.path.join(path, currentsName) - print 'Currents file path:', currentsName - rawFile = open(rawName, 'rb') - try: - wavesFile = open(wavesName, 'wb') - try: - currentsFile = open(currentsName, 'wb') - try: - split(rawFile, wavesFile, currentsFile) - finally: - currentsFile.close() - finally: - wavesFile.close() - finally: - rawFile.close() - -if __name__ == "__main__": - __main() - Index: DPWavesProc/trunk/DPWavesProc/radialtouvw1.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/radialtouvw1.m (revision 215) +++ (revision ) @@ -1,304 +1,0 @@ -function [ID,SM,EP,orbitnew]=radialtouvw1(pressure,range,orbit,sysinfo,data_type) - - -%This code takes the loaded orbit, pressure and system info data from an -%ADCP waves output and computes the uvw velocities in earth coordinates. -%It also interpolates to remove bad data points and prepares the data -%structure required for running the DIWASP program. The output will be in -%the structures ID, SM and EP. - -%data_type is: -%1 to use uvw and pressure to generate the data structures, -%2 to use ranges -%3 to use radial velocity data - - - -%make sure to load: pressure=load('pressure data'), -%orbit=load('orbital data'),sysinfo=load('sysinfo data') and range - -%what is the transducer face height off the bottom? -adcpheight=0.4; - -%whats the magnetic variation -magvar=9.63; - -%set up sysinfo file -samplesInBurst=sysinfo(3,:); -bin1height=sysinfo(9,:); -bin2height=sysinfo(10,:); -bin3height=sysinfo(11,:); -bin4height=sysinfo(12,:); -bin5height=sysinfo(13,:); -heading=sysinfo(18,:); -pitch=sysinfo(19,:); -roll=sysinfo(20,:); - -%set up pressure -press=pressure/1000; - -%find the average depth -avgdepth=mean(press)+adcpheight; - -%set up range -range=range/1000; -meanrange=mean(range); -meanrange=repmat(meanrange,samplesInBurst,1); -dmrange=range-meanrange; -std_range=std(dmrange); - -% Take out any bad data points in orbital data -ibad=find(orbit < -32000); -orbit(ibad) = NaN; -orbit=orbit/1000; -orbitnew=orbit; -%interpolate to take out any NaNs and QC for bad data in orbital data -std_orbit=ones(1,20); -for i=1:20 - - %first take out any points outside of 4 std deviations - std_orbit(i)=nanstd(orbit(:,i)); - ibad_std=find(abs(orbit(:,i)) > 4*std_orbit(i)); - orbit(ibad_std,i)=NaN; -end -%find the avg std deviation for each group 4 beams -for i=4:4:20 - avgstd_orbit(i-3:i)=mean(std_orbit(i-3:i)); -end - -%now remove the points outside 4avg std dev and interp -for i=1:20 - ibad_std=find(abs(orbit(:,i)) > 4*avgstd_orbit(i)); - orbit(ibad_std,i)=NaN; - - time=[1:1:length(orbit(:,i))]; - NaNs=isnan(orbit(:,i)); - igood=find(NaNs == 0); - ibad=find(NaNs == 1); - - intValues= interp1(time(igood),orbit(igood,i),time(ibad),'linear','extrap'); - orbitnew(ibad,i)=intValues; -end - -% Do similar QC for the range data -rangenew=dmrange; -for i=1:4 - ibad=find(abs(dmrange(:,i)) > 4*std_range(:,i)); - dmrange(ibad,i)=NaN; - time=[1:1:length(range(:,i))]; - NaNs=isnan(dmrange(:,i)); - igood=find(NaNs == 0); - ibad=find(NaNs == 1); - - intValues= interp1(time(igood),dmrange(igood,i),time(ibad),'linear','extrap'); - rangenew(ibad,i)=intValues; -end - -dmrange=rangenew; - -%change heading, pitch, roll into degrees - -heading = heading/100; -pitch=pitch/100; -roll=roll/100; -pitch_out=pitch; -roll_out=roll; - -%When converting to earth coordinates, the directions will be wrong unless we -%correct for bottom/up facing ADCPs, simply by rotating the roll by 180 -roll=roll+180; - -%Set up geometry for transformation from beam to instrument -C1 = 1; -A1 = 1/(2*sin(20*pi/180)); -B1 = 1/(4*cos(20*pi/180)); -D1 = A1/sqrt(2); - -% coordinate transformation matrix -CH = cos((heading+magvar)*pi/180); -SH = sin((heading+magvar)*pi/180); -CP = cos((pitch)*pi/180); -SP = sin((pitch)*pi/180); -CR = cos((roll)*pi/180); -SR = sin((roll)*pi/180); - -% let the matrix elements be ( a b c; d e f; g h j); -a = CH.*CR + SH.*SP.*SR; b = SH.*CP; c = CH.*SR - SH.*SP.*CR; -d = -SH.*CR + CH.*SP.*SR; e = CH.*CP; f = -SH.*SR - CH.*SP.*CR; -g = -CP.*SR; h = SP; j = CP.*CR; -uno=1; - -%reshape the orbital matrix to 3 dimensions - -radial=reshape(orbitnew,samplesInBurst,4,5); - -% Compute uvw velocities and change to earth coordinates - -u = C1*A1*(radial(:,1,:)-radial(:,2,:)); -v = C1*A1*(radial(:,4,:)-radial(:,3,:)); -w = B1*(radial(:,1,:)+radial(:,2,:)+radial(:,3,:)+radial(:,4,:)); -error_vel = D1*(radial(:,1,:)+radial(:,2,:)-radial(:,3,:)-radial(:,4,:)); - -u=reshape(u,samplesInBurst,5); -v=reshape(v,samplesInBurst,5); -w=reshape(w,samplesInBurst,5); -error_vel=reshape(error_vel,samplesInBurst,5); - -[m,n] = size(u); -uno = ones(m,5); -unew = u.*(uno*a) + v.*(uno*b) + w.*(uno*c); -vnew = u.*(uno*d) + v.*(uno*e) + w.*(uno*f); -wnew = u.*(uno*g) + v.*(uno*h) + w.*(uno*j); - -u_all = unew;v_all=vnew;w_all=wnew; -error_vel_all = error_vel; - -%compute the original x,y,z positions for each beam for each bin to be accurate we need to take out the adcpheight - -xyzpos=ones(3,4,5); -heights=[bin1height bin2height bin3height bin4height bin5height avgdepth]-adcpheight; -pos=heights*tan(20*pi/180); -for i=1:5 - xyzpos(:,1,i)=[pos(i),0,heights(i)]; - xyzpos(:,2,i)=[-pos(i),0,heights(i)]; - xyzpos(:,3,i)=[0,pos(i),heights(i)]; - xyzpos(:,4,i)=[0,-pos(i),heights(i)]; -end - -% set up the new coordinate transformation matrix -CH = cos((heading+magvar)*pi/180); -SH = sin((heading+magvar)*pi/180); -CP = cos((pitch_out)*pi/180); -SP = sin((pitch_out)*pi/180); -CR = cos((-roll_out)*pi/180); -SR = sin((-roll_out)*pi/180); - -% let the matrix elements be ( a b c; d e f; g h j), a slightly different -% matrix from before; -a = CH.*CR - SH.*SP.*SR; b = SH.*CP; c = -CH.*SR - SH.*SP.*CR; -d = -SH.*CR - CH.*SP.*SR; e = CH.*CP; f = SH.*SR - CH.*SP.*CR; -g = CP.*SR; h = SP; j = CP.*CR; - -%transform the original x,y,z positions to the new positions accounting for -%heading, pitch and roll... we also add adcpheight back in -newxyzpos=ones(3,4,5); -new_xyzpos(1,:,:)=xyzpos(1,:,:)*a+xyzpos(2,:,:)*b+xyzpos(3,:,:)*c; -new_xyzpos(2,:,:)=xyzpos(1,:,:)*d+xyzpos(2,:,:)*e+xyzpos(3,:,:)*f; -new_xyzpos(3,:,:)=xyzpos(1,:,:)*g+xyzpos(2,:,:)*h+xyzpos(3,:,:)*j+adcpheight; - -xyzpositions=new_xyzpos; - - -%now we need to figure out the xyz positions at the surface for the range -%sin45=0.7071 - -binheight=heights(:,6); - -%beam 3 -bearing=(heading+magvar)*(pi/180); -distfromz=binheight*tan((20-pitch_out)*(pi/180)); -xpos=sin(bearing)*distfromz; -ypos=cos(bearing)*distfromz; - -distroll=binheight*tan(roll_out*(pi/180)); -beam3xpos=xpos+0.7071*distroll; -beam3ypos=ypos+0.7071*distroll; - -%beam 4 -bearing=bearing+pi; -distfromz=binheight*tan((20+pitch_out)*(pi/180)); -xpos=sin(bearing)*distfromz; -ypos=cos(bearing)*distfromz; - -distroll=binheight*tan(roll_out*(pi/180)); -beam4xpos=xpos+0.7071*distroll; -beam4ypos=ypos+0.7071*distroll; - -%beam 1 -bearing=bearing-pi/2; -distfromz=binheight*tan((20+roll_out)*(pi/180)); -xpos=sin(bearing)*distfromz; -ypos=cos(bearing)*distfromz; - -distroll=binheight*tan(pitch_out*(pi/180)); -beam1xpos=xpos+0.7071*distroll; -beam1ypos=ypos+0.7071*distroll; - -%beam2 -bearing=bearing+pi; -distfromz=binheight*tan((20-roll_out)*(pi/180)); -xpos=sin(bearing)*distfromz; -ypos=cos(bearing)*distfromz; - -distroll=binheight*tan(pitch_out*(pi/180)); -beam2xpos=xpos+0.7071*distroll; -beam2ypos=ypos+0.7071*distroll; - -xypositions(:,:)=[beam1xpos beam2xpos beam3xpos beam4xpos; beam1ypos beam2ypos beam3ypos beam4ypos]; - -%Put into structures for DIWASP - - -%sampling frequency -ID.fs=2; -%depth -ID.depth=(adcpheight+mean(press)); -%the spectral matrix structure -SM.freqs=[0.01:0.01:0.4]; -SM.dirs=[-180:2:180]; -SM.xaxisdir= 90; -%the estimation parameter -EP.method= 'EMEP'; -EP.iter=100; - -if data_type == 1 - %For uvw and pressure for bins 2,3,4 - % the datatypes - ID.datatypes={'pres' 'velx' 'vely' 'velz' 'velx' 'vely' 'velz' 'velx' 'vely' 'velz'}; - % the layout - ID.layout = [ 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0; - adcpheight bin2height bin2height bin2height bin3height bin3height bin3height bin4height bin4height bin4height]; - % the data - ID.data = horzcat(press, u_all(:,2), v_all(:,2), w_all(:,2), u_all(:,3), v_all(:,3), w_all(:,3),u_all(:,4), v_all(:,4), w_all(:,4)); - -elseif data_type == 2 - %For the ranges of each beam - % the datatypes - ID.datatypes={'elev' 'elev' 'elev' 'elev'}; - % the layout - ID.layout = [xypositions(1,1) xypositions(1,2) xypositions(1,3) xypositions(1,4); - xypositions(2,1) xypositions(2,2) xypositions(2,3) xypositions(2,4); - avgdepth avgdepth avgdepth avgdepth]; - % the data - ID.data = horzcat(dmrange(:,1), dmrange(:,2), dmrange(:,3), dmrange(:,4)); - -elseif data_type == 3 - % For the radial velocities bins 2,3,4 - % the datatypes - ID.datatypes={'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial'}; - % the layout - %ID.layout = [xyzpositions(1,1,2) xyzpositions(1,2,2) xyzpositions(1,3,2) xyzpositions(1,4,2) xyzpositions(1,1,3) xyzpositions(1,2,3) xyzpositions(1,3,3) xyzpositions(1,4,3) xyzpositions(1,1,4) xyzpositions(1,2,4) xyzpositions(1,3,4) xyzpositions(1,4,4); - %xyzpositions(2,1,2) xyzpositions(2,2,2) xyzpositions(2,3,2) xyzpositions(2,4,2) xyzpositions(2,1,3) xyzpositions(2,2,3) xyzpositions(2,3,3) xyzpositions(2,4,3) xyzpositions(2,1,4) xyzpositions(2,2,4) xyzpositions(2,3,4) xyzpositions(2,4,4); - %xyzpositions(3,1,2) xyzpositions(3,2,2) xyzpositions(3,3,2) xyzpositions(3,4,2) xyzpositions(3,1,3) xyzpositions(3,2,3) xyzpositions(3,3,3) xyzpositions(3,4,3) xyzpositions(3,1,4) xyzpositions(3,2,4) xyzpositions(3,3,4) xyzpositions(3,4,4)]; - % the data - %ID.data = horzcat(orbitnew(:,5),orbitnew(:,6),orbitnew(:,7),orbitnew(:,8),orbitnew(:,9),orbitnew(:,10),orbitnew(:,11),orbitnew(:,12),orbitnew(:,13),orbitnew(:,14),orbitnew(:,15),orbitnew(:,16)); - - % the layout using bins 3,4,5 - ID.layout = [xyzpositions(1,1,5) xyzpositions(1,2,5) xyzpositions(1,3,5) xyzpositions(1,4,5) xyzpositions(1,1,4) xyzpositions(1,2,4) xyzpositions(1,3,4) xyzpositions(1,4,4) xyzpositions(1,1,3) xyzpositions(1,2,3) xyzpositions(1,3,3) xyzpositions(1,4,3); - xyzpositions(2,1,3) xyzpositions(2,2,3) xyzpositions(2,3,3) xyzpositions(2,4,3) xyzpositions(2,1,4) xyzpositions(2,2,4) xyzpositions(2,3,4) xyzpositions(2,4,4) xyzpositions(2,1,3) xyzpositions(2,2,3) xyzpositions(2,3,3) xyzpositions(2,4,3); - xyzpositions(3,1,3) xyzpositions(3,2,3) xyzpositions(3,3,3) xyzpositions(3,4,3) xyzpositions(3,1,4) xyzpositions(3,2,4) xyzpositions(3,3,4) xyzpositions(3,4,4) xyzpositions(3,1,3) xyzpositions(3,2,3) xyzpositions(3,3,3) xyzpositions(3,4,3)]; - % the data - ID.data = horzcat(orbitnew(:,17),orbitnew(:,18),orbitnew(:,19),orbitnew(:,20),orbitnew(:,13),orbitnew(:,14),orbitnew(:,15),orbitnew(:,16),orbitnew(:,9),orbitnew(:,10),orbitnew(:,11),orbitnew(:,12)); - -end - - - - - - - - - - - Index: DPWavesProc/trunk/DPWavesProc/rdradcp.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/rdradcp.m (revision 168) +++ (revision ) @@ -1,863 +1,0 @@ -function [adcp,cfg,ens]=rdradcp(name,varargin); -% RDRADCP Read (raw binary) RDI ADCP files, -% ADCP=RDRADCP(NAME) reads the raw binary RDI BB/Workhorse ADCP file NAME and -% puts all the relevant configuration and measured data into a data structure -% ADCP (which is self-explanatory). This program is designed for handling data -% recorded by moored instruments (primarily Workhorse-type but can also read -% Broadband) and then downloaded post-deployment. For vessel-mount data I -% usually make p-files (which integrate nav info and do coordinate transformations) -% and then use RDPADCP. -% -% This current version does have some handling of VMDAS and WINRIVER output -% files, but it is still 'beta'. -% -% [ADCP,CFG]=RDRADCP(...) returns configuration data in a -% separate data structure. -% -% Various options can be specified on input: -% [..]=RDRADCP(NAME,NUMAV) averages NUMAV ensembles together in the result. -% [..]=RDRADCP(NAME,NUMAV,NENS) reads only NENS ensembles (-1 for all). -% [..]=RDRADCP(NAME,NUMAV,[NFIRST NEND]) reads only the specified range -% of ensembles. This is useful if you want to get rid of bad data before/after -% the deployment period. -% -% Note - sometimes the ends of files are filled with garbage. In this case you may -% have to rerun things explicitly specifying how many records to read (or the -% last record to read). I don't handle bad data very well. -% -% - I don't read in absolutely every parameter stored in the binaries; -% just the ones that are 'most' useful. -% -% String parameter/option pairs can be added after these initial parameters: -% -% 'baseyear' : Base century for BB/v8WH firmware (default to 2000). -% -% 'despike' : [ 'no' | 'yes' | 3-element vector ] -% Controls ensemble averaging. With 'no' a simple mean is used -% (default). With 'yes' a mean is applied to all values that fall -% within a window around the median (giving some outlier rejection). -% This is useful for noisy data. Window sizes are [.3 .3 .3] m/s -% for [ horiz_vel vert_vel error_vel ] values. If you want to -% change these values, set 'despike' to the 3-element vector. -% -% R. Pawlowicz (rich@ocgy.ubc.ca) - 17/09/99 - -% R. Pawlowicz - 17/Oct/99 -% 5/july/00 - handled byte offsets (and mysterious 'extra" bytes) slightly better, Y2K -% 5/Oct/00 - bug fix - size of ens stayed 2 when NUMAV==1 due to initialization, -% hopefully this is now fixed. -% 10/Mar/02 - #bytes per record changes mysteriously, -% tried a more robust workaround. Guess that we have an extra -% 2 bytes if the record length is even? -% 28/Mar/02 - added more firmware-dependent changes to format; hopefully this -% works for everything now (put previous changes on firmer footing?) -% 30/Mar/02 - made cfg output more intuitive by decoding things. -% - An early version of WAVESMON and PARSE which split out this -% data from a wave recorder inserted an extra two bytes per record. -% I have removed the code to handle this but if you need it see line 509 -% 29/Nov/02 - A change in the bottom-track block for version 4.05 (very old!). -% 29/Jan/03 - Status block in v4.25 150khzBB two bytes short? -% 14/Oct/03 - Added code to at least 'ignore' WinRiver GPS blocks. -% 11/Nov/03 - VMDAS navigation block, added hooks to output -% navigation data. - -num_av=5; % Block filtering and decimation parameter (# ensembles to block together). -nens=-1; % Read all ensembles. -century=2000; % ADCP clock does not have century prior to firmware 16.05. -vels='no'; % Default to simple averaging - -lv=length(varargin); -if lv>=1 & ~isstr(varargin{1}), - num_av=varargin{1}; % Block filtering and decimation parameter (# ensembles to block together). - varargin(1)=[]; - lv=lv-1; - if lv>=1 & ~isstr(varargin{1}), - nens=varargin{1}; - varargin(1)=[]; - lv=lv-1; - end; -end; - -% Read optional args -while length(varargin)>0, - switch varargin{1}(1:3), - case 'bas', - century = varargin{2}; - case 'des', - if isstr(varargin{2}), - if strcmp(varargin{2},'no'), vels='no'; - else vels=[.3 .3 .3]; end; - else - vels=varargin{2}; - end; - otherwise, - error(['Unknown command line option ->' varargin{1}]); - end; - varargin([1 2])=[]; -end; - - - - -% Check file information first - -naminfo=dir(name); - -if isempty(naminfo), - fprintf('ERROR******* Can''t find file %s\n',name); - return; -end; - -fprintf('\nOpening file %s\n\n',name); -fd=fopen(name,'r','ieee-le'); - -% Read first ensemble to initialize parameters - -[ens,hdr,cfg]=rd_buffer(fd,-2); % Initialize and read first two records -fseek(fd,0,'bof'); % Rewind - -if (cfg.prog_ver<16.05 & cfg.prog_ver>5.999) | cfg.prog_ver<5.55, - fprintf('**************Assuming that the century begins year %d *********** \n\n',century); -else - century=0; % century included in clock. -end; - -dats=datenum(century+ens.rtc(1,:),ens.rtc(2,:),ens.rtc(3,:),ens.rtc(4,:),ens.rtc(5,:),ens.rtc(6,:)+ens.rtc(7,:)/100); -t_int=diff(dats); -fprintf('Record begins at %s\n',datestr(dats(1),0)); -fprintf('Ping interval appears to be %s\n',datestr(t_int,13)); - - -% Estimate number of records (since I don't feel like handling EOFs correctly, -% we just don't read that far!) - - -% Now, this is a puzzle - it appears that this is not necessary in -% a firmware v16.12 sent to me, and I can't find any example for -% which it *is* necessary so I'm not sure why its there. It could be -% a leftoever from dealing with the bad WAVESMON/PARSE problem (now -% fixed) that inserted extra bytes. -% ...So its out for now. -%if cfg.prog_ver>=16.05, extrabytes=2; else extrabytes=0; end; % Extra bytes -extrabytes=0; - -if length(nens)==1, - if nens==-1, - nens=fix(naminfo.bytes/(hdr.nbyte+2+extrabytes)); - fprintf('\nEstimating %d ensembles in this file\nReducing by a factor of %d\n',nens,num_av); - else - fprintf('\nReading %d ensembles in this file\nReducing by a factor of %d\n',nens,num_av); - end; -else - fprintf('\nReading ensembles %d-%d in this file\nReducing by a factor of %d\n',nens,num_av); - fseek(fd,(hdr.nbyte+2+extrabytes)*(nens(1)-1),'bof'); - nens=diff(nens)+1; -end; - -if num_av>1, - if isstr(vels), - fprintf('\n Simple mean used for ensemble averaging\n'); - else - fprintf('\n Averaging after outlier rejection with parameters [%f %f %f]\n',vels); - end; -end; - -% Number of records after averaging. - -n=fix(nens/num_av); - -% Structure to hold all ADCP data -% Note that I am not storing all the data contained in the raw binary file, merely -% things I think are useful. - -switch cfg.sourceprog, - case 'WINRIVER', - adcp=struct('name','adcp','config',cfg,'mtime',zeros(1,n),'number',zeros(1,n),'pitch',zeros(1,n),... - 'roll',zeros(1,n),'heading',zeros(1,n),'pitch_std',zeros(1,n),... - 'roll_std',zeros(1,n),'heading_std',zeros(1,n),'depth',zeros(1,n),... - 'temperature',zeros(1,n),'salinity',zeros(1,n),... - 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... - 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... - 'error_vel',zeros(cfg.n_cells,n),'corr',zeros(cfg.n_cells,4,n),... - 'status',zeros(cfg.n_cells,4,n),'intens',zeros(cfg.n_cells,4,n),... - 'bt_range',zeros(4,n),'bt_vel',zeros(4,n),... - 'nav_longitude',zeros(1,n),'nav_latitude',zeros(1,n)); - case 'VMDAS', - adcp=struct('name','adcp','config',cfg,'mtime',zeros(1,n),'number',zeros(1,n),'pitch',zeros(1,n),... - 'roll',zeros(1,n),'heading',zeros(1,n),'pitch_std',zeros(1,n),... - 'roll_std',zeros(1,n),'heading_std',zeros(1,n),'depth',zeros(1,n),... - 'temperature',zeros(1,n),'salinity',zeros(1,n),... - 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... - 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... - 'error_vel',zeros(cfg.n_cells,n),'corr',zeros(cfg.n_cells,4,n),... - 'status',zeros(cfg.n_cells,4,n),'intens',zeros(cfg.n_cells,4,n),... - 'bt_range',zeros(4,n),'bt_vel',zeros(4,n),... - 'nav_smtime',zeros(1,n),'nav_emtime',zeros(1,n),... - 'nav_slongitude',zeros(1,n),'nav_elongitude',zeros(1,n),... - 'nav_slatitude',zeros(1,n),'nav_elatitude',zeros(1,n)); - otherwise - adcp=struct('name','adcp','config',cfg,'mtime',zeros(1,n),'number',zeros(1,n),'pitch',zeros(1,n),... - 'roll',zeros(1,n),'heading',zeros(1,n),'pitch_std',zeros(1,n),... - 'roll_std',zeros(1,n),'heading_std',zeros(1,n),'depth',zeros(1,n),... - 'temperature',zeros(1,n),'salinity',zeros(1,n),... - 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... - 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... - 'error_vel',zeros(cfg.n_cells,n),'corr',zeros(cfg.n_cells,4,n),... - 'status',zeros(cfg.n_cells,4,n),'intens',zeros(cfg.n_cells,4,n),... - 'bt_range',zeros(4,n),'bt_vel',zeros(4,n)); -end; - - -% Calibration factors for backscatter data - -clear global ens -% Loop for all records -for k=1:n, - - % Gives display so you know something is going on... - - if rem(k,50)==0, fprintf('\n%d',k*num_av);end; - fprintf('.'); - - % Read an ensemble - - ens=rd_buffer(fd,num_av); - - - if ~isstruct(ens), % If aborting... - fprintf('Only %d records found..suggest re-running RDRADCP using this parameter\n',(k-1)*num_av); - fprintf('(If this message preceded by a POSSIBLE PROGRAM PROBLEM message, re-run using %d)\n',(k-1)*num_av-1); - break; - end; - - dats=datenum(century+ens.rtc(1,:),ens.rtc(2,:),ens.rtc(3,:),ens.rtc(4,:),ens.rtc(5,:),ens.rtc(6,:)+ens.rtc(7,:)/100); - adcp.mtime(k)=median(dats); - adcp.number(k) =ens.number(1); - adcp.heading(k) =mean(ens.heading); - adcp.pitch(k) =mean(ens.pitch); - adcp.roll(k) =mean(ens.roll); - adcp.heading_std(k) =mean(ens.heading_std); - adcp.pitch_std(k) =mean(ens.pitch_std); - adcp.roll_std(k) =mean(ens.roll_std); - adcp.depth(k) =mean(ens.depth); - adcp.temperature(k) =mean(ens.temperature); - adcp.salinity(k) =mean(ens.salinity); - adcp.pressure(k) =mean(ens.pressure); - adcp.pressure_std(k)=mean(ens.pressure_std); - - if isstr(vels), - adcp.east_vel(:,k) =nmean(ens.east_vel ,2); - adcp.north_vel(:,k) =nmean(ens.north_vel,2); - adcp.vert_vel(:,k) =nmean(ens.vert_vel ,2); - adcp.error_vel(:,k) =nmean(ens.error_vel,2); - else - adcp.east_vel(:,k) =nmedian(ens.east_vel ,vels(1),2); - adcp.north_vel(:,k) =nmedian(ens.north_vel,vels(1),2); - adcp.vert_vel(:,k) =nmedian(ens.vert_vel ,vels(2),2); - adcp.error_vel(:,k) =nmedian(ens.error_vel,vels(3),2); - end; - - adcp.corr(:,:,k) =nmean(ens.corr,3); % added correlation RKD 9/00 - adcp.status(:,:,k) =nmean(ens.status,3); - - adcp.intens(:,:,k) =nmean(ens.intens,3); - - adcp.bt_range(:,k) =nmean(ens.bt_range,2); - adcp.bt_vel(:,k) =nmean(ens.bt_vel,2); - - switch cfg.sourceprog, - case 'WINRIVER', - adcp.nav_longitude(k)=nmean(ens.slongitude); - adcp.nav_latitude(k)=nmean(ens.slatitude); - case 'VMDAS', - adcp.nav_smtime(k) =ens.smtime(1); - adcp.nav_emtime(k) =ens.emtime(end); - adcp.nav_slatitude(k)=ens.slatitude(1); - adcp.nav_elatitude(k)=ens.elatitude(end); - adcp.nav_slongitude(k)=ens.slongitude(1); - adcp.nav_elongitude(k)=ens.elongitude(end); - end; -end; - -fprintf('\n'); -fclose(fd); - - -%------------------------------------- -function hdr=rd_hdr(fd); -% Read config data - -cfgid=fread(fd,1,'uint16'); -if cfgid~=hex2dec('7F7F'), - error(['File ID is ' dec2hex(cfgid) ' not 7F7F - data corrupted or not a BB/WH raw file?']); -end; - -hdr=rd_hdrseg(fd); - -%------------------------------------- -function cfg=rd_fix(fd); -% Read config data - -cfgid=fread(fd,1,'uint16'); -if cfgid~=hex2dec('0000'), - warning(['Fixed header ID ' cfgid 'incorrect - data corrupted or not a BB/WH raw file?']); -end; - -cfg=rd_fixseg(fd); - - - -%-------------------------------------- -function [hdr,nbyte]=rd_hdrseg(fd); -% Reads a Header - -hdr.nbyte =fread(fd,1,'int16'); -fseek(fd,1,'cof'); -ndat=fread(fd,1,'int8'); -hdr.dat_offsets =fread(fd,ndat,'int16'); -nbyte=4+ndat*2; - -%------------------------------------- -function opt=getopt(val,varargin); -% Returns one of a list (0=first in varargin, etc.) -if val+1>length(varargin), - opt='unknown'; -else - opt=varargin{val+1}; -end; - -% -%------------------------------------- -function [cfg,nbyte]=rd_fixseg(fd); -% Reads the configuration data from the fixed leader - -%%disp(fread(fd,10,'uint8')) -%%fseek(fd,-10,'cof'); - -cfg.name='wh-adcp'; -cfg.sourceprog='instrument'; % default - depending on what data blocks are - % around we can modify this later in rd_buffer. -cfg.prog_ver =fread(fd,1,'uint8')+fread(fd,1,'uint8')/100; - -if fix(cfg.prog_ver)==4 | fix(cfg.prog_ver)==5, - cfg.name='bb-adcp'; -elseif fix(cfg.prog_ver)==8 | fix(cfg.prog_ver)==16, - cfg.name='wh-adcp'; -else - cfg.name='unrecognized firmware version' ; -end; - -config =fread(fd,2,'uint8'); % Coded stuff -cfg.config =[dec2base(config(2),2,8) '-' dec2base(config(1),2,8)]; - cfg.beam_angle =getopt(bitand(config(2),3),15,20,30); - cfg.beam_freq =getopt(bitand(config(1),7),75,150,300,600,1200,2400); - cfg.beam_pattern =getopt(bitand(config(1),8)==8,'concave','convex'); % 1=convex,0=concave - cfg.orientation =getopt(bitand(config(1),128)==128,'down','up'); % 1=up,0=down -cfg.simflag =getopt(fread(fd,1,'uint8'),'real','simulated'); % Flag for simulated data -fseek(fd,1,'cof'); -cfg.n_beams =fread(fd,1,'uint8'); -cfg.n_cells =fread(fd,1,'uint8'); -cfg.pings_per_ensemble=fread(fd,1,'uint16'); -cfg.cell_size =fread(fd,1,'uint16')*.01; % meters -cfg.blank =fread(fd,1,'uint16')*.01; % meters -cfg.prof_mode =fread(fd,1,'uint8'); % -cfg.corr_threshold =fread(fd,1,'uint8'); -cfg.n_codereps =fread(fd,1,'uint8'); -cfg.min_pgood =fread(fd,1,'uint8'); -cfg.evel_threshold =fread(fd,1,'uint16'); -cfg.time_between_ping_groups=sum(fread(fd,3,'uint8').*[60 1 .01]'); % seconds -coord_sys =fread(fd,1,'uint8'); % Lots of bit-mapped info - cfg.coord=dec2base(coord_sys,2,8); - cfg.coord_sys =getopt(bitand(bitshift(coord_sys,-3),3),'beam','instrument','ship','earth'); - cfg.use_pitchroll =getopt(bitand(coord_sys,4)==4,'no','yes'); - cfg.use_3beam =getopt(bitand(coord_sys,2)==2,'no','yes'); - cfg.bin_mapping =getopt(bitand(coord_sys,1)==1,'no','yes'); -cfg.xducer_misalign=fread(fd,1,'int16')*.01; % degrees -cfg.magnetic_var =fread(fd,1,'int16')*.01; % degrees -cfg.sensors_src =dec2base(fread(fd,1,'uint8'),2,8); -cfg.sensors_avail =dec2base(fread(fd,1,'uint8'),2,8); -cfg.bin1_dist =fread(fd,1,'uint16')*.01; % meters -cfg.xmit_pulse =fread(fd,1,'uint16')*.01; % meters -cfg.water_ref_cells=fread(fd,2,'uint8'); -cfg.fls_target_threshold =fread(fd,1,'uint8'); -fseek(fd,1,'cof'); -cfg.xmit_lag =fread(fd,1,'uint16')*.01; % meters -nbyte=40; - -if cfg.prog_ver>=8.14, % Added CPU serial number with v8.14 - cfg.serialnum =fread(fd,8,'uint8'); - nbyte=nbyte+8; -end; - -if cfg.prog_ver>=8.24, % Added 2 more bytes with v8.24 firmware - cfg.sysbandwidth =fread(fd,2,'uint8'); - nbyte=nbyte+2; -end; - -if cfg.prog_ver>=16.05, % Added 1 more bytes with v16.05 firmware - cfg.syspower =fread(fd,1,'uint8'); - nbyte=nbyte+1; -end; - -% It is useful to have this precomputed. - -cfg.ranges=cfg.bin1_dist+[0:cfg.n_cells-1]'*cfg.cell_size; -if cfg.orientation==1, cfg.ranges=-cfg.ranges; end - - -%----------------------------- -function [ens,hdr,cfg]=rd_buffer(fd,num_av); - -% To save it being re-initialized every time. -global ens hdr - -% A fudge to try and read files not handled quite right. -global FIXOFFSET SOURCE - -% If num_av<0 we are reading only 1 element and initializing -if num_av<0 | isempty(ens), - FIXOFFSET=0; - SOURCE=0; % 0=instrument, 1=VMDAS, 2=WINRIVER - n=abs(num_av); - pos=ftell(fd); - hdr=rd_hdr(fd); - cfg=rd_fix(fd); - fseek(fd,pos,'bof'); - clear global ens - global ens - - ens=struct('number',zeros(1,n),'rtc',zeros(7,n),'BIT',zeros(1,n),'ssp',zeros(1,n),'depth',zeros(1,n),'pitch',zeros(1,n),... - 'roll',zeros(1,n),'heading',zeros(1,n),'temperature',zeros(1,n),'salinity',zeros(1,n),... - 'mpt',zeros(1,n),'heading_std',zeros(1,n),'pitch_std',zeros(1,n),... - 'roll_std',zeros(1,n),'adc',zeros(8,n),'error_status_wd',zeros(1,n),... - 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... - 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... - 'error_vel',zeros(cfg.n_cells,n),'intens',zeros(cfg.n_cells,4,n),'percent',zeros(cfg.n_cells,4,n),... - 'corr',zeros(cfg.n_cells,4,n),'status',zeros(cfg.n_cells,4,n),'bt_range',zeros(4,n),'bt_vel',zeros(4,n),... - 'smtime',zeros(1,n),'emtime',zeros(1,n),'slatitude',zeros(1,n),... - 'slongitude',zeros(1,n),'elatitude',zeros(1,n),'elongitude',zeros(1,n),... - 'flags',zeros(1,n)); - num_av=abs(num_av); -end; - -k=0; -while k' id1]); - end; - startpos=ftell(fd)-2; % Starting position. - - - % Read the # data types. - [hdr,nbyte]=rd_hdrseg(fd); - byte_offset=nbyte+2; -%%disp(length(hdr.dat_offsets)) - % Read all the data types. - for n=1:length(hdr.dat_offsets), - - id=fread(fd,1,'uint16'); -%% fprintf('ID=%s\n',dec2hex(id,4)); - - % handle all the various segments of data. Note that since I read the IDs as a two - % byte number in little-endian order the high and low bytes are exchanged compared to - % the values given in the manual. - % - - switch dec2hex(id,4), - case '0000', % Fixed leader - [cfg,nbyte]=rd_fixseg(fd); - nbyte=nbyte+2; - - case '0080' % Variable Leader - k=k+1; - ens.number(k) =fread(fd,1,'uint16'); - ens.rtc(:,k) =fread(fd,7,'uint8'); - ens.number(k) =ens.number(k)+65536*fread(fd,1,'uint8'); - ens.BIT(k) =fread(fd,1,'uint16'); - ens.ssp(k) =fread(fd,1,'uint16'); - ens.depth(k) =fread(fd,1,'uint16')*.1; % meters - ens.heading(k) =fread(fd,1,'uint16')*.01; % degrees - ens.pitch(k) =fread(fd,1,'int16')*.01; % degrees - ens.roll(k) =fread(fd,1,'int16')*.01; % degrees - ens.salinity(k) =fread(fd,1,'int16'); % PSU - ens.temperature(k) =fread(fd,1,'int16')*.01; % Deg C - ens.mpt(k) =sum(fread(fd,3,'uint8').*[60 1 .01]'); % seconds - ens.heading_std(k) =fread(fd,1,'uint8'); % degrees - ens.pitch_std(k) =fread(fd,1,'int8')*.1; % degrees - ens.roll_std(k) =fread(fd,1,'int8')*.1; % degrees - ens.adc(:,k) =fread(fd,8,'uint8'); - nbyte=2+40; - - if strcmp(cfg.name,'bb-adcp'), - - if cfg.prog_ver>=5.55, - fseek(fd,15,'cof'); % 14 zeros and one byte for number WM4 bytes - cent=fread(fd,1,'uint8'); % possibly also for 5.55-5.58 but - ens.rtc(:,k)=fread(fd,7,'uint8'); % I have no data to test. - ens.rtc(1,k)=ens.rtc(1,k)+cent*100; - nbyte=nbyte+15+8; - end; - - elseif strcmp(cfg.name,'wh-adcp'), % for WH versions. - - ens.error_status_wd(k)=fread(fd,1,'uint32'); - nbyte=nbyte+4;; - - if cfg.prog_ver>=8.13, % Added pressure sensor stuff in 8.13 - fseek(fd,2,'cof'); - ens.pressure(k) =fread(fd,1,'uint32'); - ens.pressure_std(k) =fread(fd,1,'uint32'); - nbyte=nbyte+10; - end; - - if cfg.prog_ver>8.24, % Spare byte added 8.24 - fseek(fd,1,'cof'); - nbyte=nbyte+1; - end; - - if cfg.prog_ver>=16.05, % Added more fields with century in clock 16.05 - cent=fread(fd,1,'uint8'); - ens.rtc(:,k)=fread(fd,7,'uint8'); - ens.rtc(1,k)=ens.rtc(1,k)+cent*100; - nbyte=nbyte+8; - end; - end; - - case '0100', % Velocities - vels=fread(fd,[4 cfg.n_cells],'int16')'*.001; % m/s - ens.east_vel(:,k) =vels(:,1); - ens.north_vel(:,k)=vels(:,2); - ens.vert_vel(:,k) =vels(:,3); - ens.error_vel(:,k)=vels(:,4); - nbyte=2+4*cfg.n_cells*2; - - case '0200', % Correlations - ens.corr(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; - nbyte=2+4*cfg.n_cells; - - case '0300', % Echo Intensities - ens.intens(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; - nbyte=2+4*cfg.n_cells; - - case '0400', % Percent good - ens.percent(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; - nbyte=2+4*cfg.n_cells; - - case '0500', % Status - % Note in one case with a 4.25 firmware SC-BB, it seems like - % this block was actually two bytes short! - ens.status(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; - nbyte=2+4*cfg.n_cells; - - case '0600', % Bottom track - % In WINRIVER GPS data is tucked into here in odd ways, as long - % as GPS is enabled. - if SOURCE==2, - fseek(fd,2,'cof'); - long1=fread(fd,1,'uint16'); - fseek(fd,6,'cof'); - cfac=180/2^31; - ens.slatitude(k) =fread(fd,1,'int32')*cfac; - else - fseek(fd,14,'cof'); % Skip over a bunch of stuff - end; - ens.bt_range(:,k)=fread(fd,4,'uint16')*.01; % - ens.bt_vel(:,k) =fread(fd,4,'int16'); - if SOURCE==2, - fseek(fd,12+2,'cof'); - ens.slongitude(k)=(long1+65536*fread(fd,1,'uint16'))*cfac; - if ens.slongitude(k)>180, ens.slongitude(k)=ens.slongitude(k)-360; end; - fseek(fd,71-33-16,'cof'); - nbyte=2+68; - else - fseek(fd,71-33,'cof'); - nbyte=2+68; - end; - if cfg.prog_ver>=5.3, % Version 4.05 firmware seems to be missing these last 11 bytes. - fseek(fd,78-71,'cof'); - ens.bt_range(:,k)=ens.bt_range(:,k)+fread(fd,4,'uint8')*655.36; - nbyte=nbyte+11; - if cfg.prog_ver>=16, % RDI documentation claims these extra bytes were added in v 8.17 - fseek(fd,4,'cof'); % but they don't appear in my 8.33 data. - nbyte=nbyte+4; - end; - end; - -% The raw files produced by VMDAS contain a binary navigation data -% block. - - case '2000', % Something from VMDAS. - cfg.sourceprog='VMDAS'; - SOURCE=1; - utim =fread(fd,4,'uint8'); - mtime =datenum(utim(3)+utim(4)*256,utim(2),utim(1)); - ens.smtime(k) =mtime+fread(fd,1,'uint32')/8640000; - fseek(fd,4,'cof'); - cfac=180/2^31; - ens.slatitude(k) =fread(fd,1,'int32')*cfac; - ens.slongitude(k) =fread(fd,1,'int32')*cfac; - ens.emtime(k) =mtime+fread(fd,1,'uint32')/8640000; - ens.elatitude(k) =fread(fd,1,'int32')*cfac; - ens.elongitude(k) =fread(fd,1,'int32')*cfac; - fseek(fd,12,'cof'); - ens.flags(k) =fread(fd,1,'uint16'); - fseek(fd,30,'cof'); - nbyte=2+76; - -% The following blocks come from WINRIVER files, they aparently contain -% the raw NMEA data received from a serial port. -% -% Note that for WINRIVER files somewhat decoded data is also available -% tucked into the bottom track block. - - case '2100', % $xxDBT (Winriver addition) 38 - cfg.sourceprog='WINRIVER'; - SOURCE=2; - str=fread(fd,38,'uchar')'; - nbyte=2+38; - - case '2101', % $xxGGA (Winriver addition) 94 in maanual but 97 seems to work - cfg.sourceprog='WINRIVER'; - SOURCE=2; - str=fread(fd,97,'uchar')'; - nbyte=2+97; - % disp(setstr(str(1:80))); - - case '2102', % $xxVTG (Winriver addition) 45 - cfg.sourceprog='WINRIVER'; - SOURCE=2; - str=fread(fd,45,'uchar')'; - nbyte=2+45; -% disp(setstr(str)); - - case '2103', % $xxGSA (Winriver addition) 60 - cfg.sourceprog='WINRIVER'; - SOURCE=2; - str=fread(fd,60,'uchar')'; -% disp(setstr(str)); - nbyte=2+60; - - case '2104', %xxHDT or HDG (Winriver addition) 38 - cfg.sourceprog='WINRIVER'; - SOURCE=2; - str=fread(fd,38,'uchar')'; -% disp(setstr(str)); - nbyte=2+38; - - - - case '0701', % Number of good pings - fseek(fd,4*cfg.n_cells,'cof'); - nbyte=2+4*cfg.n_cells; - - case '0702', % Sum of squared velocities - fseek(fd,4*cfg.n_cells,'cof'); - nbyte=2+4*cfg.n_cells; - - case '0703', % Sum of velocities - fseek(fd,4*cfg.n_cells,'cof'); - nbyte=2+4*cfg.n_cells; - -% These blocks were implemented for 5-beam systems - - case '0A00', % Beam 5 velocity (not implemented) - fseek(fd,cfg.n_cells,'cof'); - nbyte=2+cfg.n_cells; - - case '0301', % Beam 5 Number of good pings (not implemented) - fseek(fd,cfg.n_cells,'cof'); - nbyte=2+cfg.n_cells; - - case '0302', % Beam 5 Sum of squared velocities (not implemented) - fseek(fd,cfg.n_cells,'cof'); - nbyte=2+cfg.n_cells; - - case '0303', % Beam 5 Sum of velocities (not implemented) - fseek(fd,cfg.n_cells,'cof'); - nbyte=2+cfg.n_cells; - - case '020C', % Ambient sound profile (not implemented) - fseek(fd,4,'cof'); - nbyte=2+4; - - otherwise, - - fprintf('Unrecognized ID code: %s\n',dec2hex(id,4)); - nbyte=2; - %% ens=-1; - %% return; - - - end; - - % here I adjust the number of bytes so I am sure to begin - % reading at the next valid offset. If everything is working right I shouldn't have - % to do this but every so often firware changes result in some differences. - - %%fprintf('#bytes is %d, original offset is %d\n',nbyte,byte_offset); - byte_offset=byte_offset+nbyte; - - if n=16.05, - % fseek(fd,2,'cof'); - %end; - -end; - -% Blank out stuff bigger than error velocity -% big_err=abs(ens.error_vel)>.2; -big_err=0; - -% Blank out invalid data -ens.east_vel(ens.east_vel==-32.768 | big_err)=NaN; -ens.north_vel(ens.north_vel==-32.768 | big_err)=NaN; -ens.vert_vel(ens.vert_vel==-32.768 | big_err)=NaN; -ens.error_vel(ens.error_vel==-32.768 | big_err)=NaN; - - - - -%-------------------------------------- -function y=nmedian(x,window,dim); -% Copied from median but with handling of NaN different. - -if nargin==2, - dim = min(find(size(x)~=1)); - if isempty(dim), dim = 1; end -end - -siz = [size(x) ones(1,dim-ndims(x))]; -n = size(x,dim); - -% Permute and reshape so that DIM becomes the row dimension of a 2-D array -perm = [dim:max(length(size(x)),dim) 1:dim-1]; -x = reshape(permute(x,perm),n,prod(siz)/n); - -% Sort along first dimension -x = sort(x,1); -[n1,n2]=size(x); - -if n1==1, - y=x; -else - if n2==1, - kk=sum(finite(x),1); - if kk>0, - x1=x(max(fix(kk/2),1)); - x2=x(max(ceil(kk/2),1)); - x(abs(x-(x1+x2)/2)>window)=NaN; - end; - x = sort(x,1); - kk=sum(finite(x),1); - x(isnan(x))=0; - y=NaN; - if kk>0, - y=sum(x)/kk; - end; - else - kk=sum(finite(x),1); - ll=kkwindow)=NaN; - x = sort(x,1); - kk=sum(finite(x),1); - x(isnan(x))=0; - y=NaN+ones(1,n2); - if any(kk), - y(kk>0)=sum(x(:,kk>0))./kk(kk>0); - end; - end; -end; - -% Permute and reshape back -siz(dim) = 1; -y = ipermute(reshape(y,siz(perm)),perm); - -%-------------------------------------- -function y=nmean(x,dim); -% R_NMEAN Computes the mean of matrix ignoring NaN -% values -% R_NMEAN(X,DIM) takes the mean along the dimension DIM of X. -% - -kk=finite(x); -x(~kk)=0; - -if nargin==1, - % Determine which dimension SUM will use - dim = min(find(size(x)~=1)); - if isempty(dim), dim = 1; end -end; - -if dim>length(size(x)), - y=x; % For matlab 5.0 only!!! Later versions have a fixed 'sum' -else - ndat=sum(kk,dim); - indat=ndat==0; - ndat(indat)=1; % If there are no good data then it doesn't matter what - % we average by - and this avoid div-by-zero warnings. - - y = sum(x,dim)./ndat; - y(indat)=NaN; -end; - - - - - - - - - - - - - - - - - - - - - - - - - Index: DPWavesProc/trunk/DPWavesProc/specmultiplot_wfreqdirs.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/specmultiplot_wfreqdirs.m (revision 168) +++ (revision ) @@ -1,148 +1,0 @@ -function [Winfo]=specmultiplot(dateinfo1,dateinfo2,timestep); -%where dateinfo1 and 2 are the strings of the first and last date extension -%of the pressure,range,etc files and timestep is the time in hours between -%each burst - -%This function takes the pressure, range, orbit and sysinfo files created -%in python and outputs a Winfo data structure with the sig wave height, -%peak period, direction of peak period and dominant dir. It also generates -%polar plots and 2d freq and directional plots of a variety of different -%estimation methods, resolutions and the wavesmon output. - - -%first set up the time vector going from dateinfo1 to dateinfo2 -Winfo.time=[]; - -date1=datevec(dateinfo1, 'yymmddHHMM'); -date2=datevec(dateinfo2,'yymmddHHMM'); - -if date1 == date2 - Winfo.time=[datenum(date1)]; -else - Winfo.time=[datenum(date1)]; - newdate=date1; - while datenum(newdate) ~= datenum(date2) - newdate=newdate+[0 0 0 timestep 0 0]; - Winfo.time=[horzcat(Winfo.time,datenum(newdate))]; - end -end - - -%set up time, which is Winfo.time as date str in the yymmddHHMM format -time=datestr(Winfo.time, 'yymmddHHMM'); - -%set up data structure for wave info -Winfo.setup={'EMEP UVW','EMEP UVW F005','EMEP UVW D01','IMLM UVW','IMLM UVW F005','IMLM UVW D01','EMEP range','IMLM range','EMEP radial','IMLM radial','wavesmon'}'; -Winfo.hsig=[]; -Winfo.peakP=[]; -Winfo.dirP=[]; -Winfo.Ddir=[]; - -%Load the data and run the script -for i=1:length(time(:,1)) - dateinfo=time(i,:); - - pressure=strcat('pressure_',dateinfo,'.txt'); - range=strcat('range_',dateinfo,'.txt'); - orbit=strcat('orbit_',dateinfo,'.txt'); - sysinfo=strcat('sysinfo_',dateinfo,'.txt'); - spec=strcat('DSpec',dateinfo,'.txt'); - - pressure=load(pressure); - range=load(range); - orbit=load(orbit); - sysinfo=load(sysinfo); - spec=load(spec); - - %set up data with uvw and pressure, freq at 0.01 and dir at 2 - [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,1); - - %run diwasp to generate this spectrum - [E_uvw_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %now for IMLM - EP.method='IMLM'; - EP.iter=3; - [I_uvw_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %now for IMLM with increased Freq resolution - SM.freqs=[0.005:0.005:0.4]; - [I_uvw_F005_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %now for IMLM with increased Dir resolution - SM.freqs=[0.01:0.01:0.4]; - SM.dirs=[-180:1:180]; - [I_uvw_F01_D1, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %now for EMEP with increased Freq res and then Dir res - EP.method='EMEP'; - EP.iter=100; - SM.freqs=[0.005:0.005:0.4]; - SM.dirs=[-180:2:180]; - [E_uvw_F005_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - SM.freqs=[0.01:0.01:0.4]; - SM.dirs=[-180:1:180]; - [E_uvw_F01_D1, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - - %set up data with ranges, freq and dir at default - [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,2); - - % run diwasp to generate this spectrum with EMEP - [E_range_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %now with IMLM - EP.method='IMLM'; - EP.iter=3; - [I_range_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %set up data with radial velocities, freq and dir at default - [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,3); - - % run diwasp to generate this spectrum with EMEP - [E_radial_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %now with IMLM - EP.method='IMLM'; - EP.iter=3; - [I_radial_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); - - %Use waveplot to plot the polar, freq and dir plots of the spectra - - [E_UVW_WI,I_UVW_WI,E_range_WI,I_range_WI,wmon_WI,fig1,fig2]=waveplot(E_uvw_F01_D2,I_uvw_F01_D2,E_range_F01_D2,I_range_F01_D2,spec,sysinfo); - - saveas(fig1,['polar1_' dateinfo '.fig']); - saveas(fig2,['dirfreq1_' dateinfo '.fig']); - - [E_UVW_F_WI,E_UVW_D_WI,I_UVW_F_WI,I_UVW_D_WI,fig3,fig4]=waveplot2(E_uvw_F01_D2,I_uvw_F01_D2,E_uvw_F005_D2,I_uvw_F005_D2,E_uvw_F01_D1,I_uvw_F01_D1,sysinfo); - - saveas(fig3,['polar2_' dateinfo '.fig']); - saveas(fig4,['dirfreq2_' dateinfo '.fig']); - - [E_radial_WI,I_radial_WI,fig5,fig6]=radialwaveplot(E_radial_F01_D2,I_radial_F01_D2,spec,sysinfo); - - saveas(fig5,['polar3_' dateinfo '.fig']); - saveas(fig6,['dirfreq3_' dateinfo '.fig']); - - close all; - - %Fill up the Winfo data structure - - hsig=[vertcat(E_UVW_WI.hsig,E_UVW_F_WI.hsig,E_UVW_D_WI.hsig,I_UVW_WI.hsig,I_UVW_F_WI.hsig,I_UVW_D_WI.hsig,E_range_WI.hsig,I_range_WI.hsig,E_radial_WI.hsig,I_radial_WI.hsig,wmon_WI.hsig)]; - peakP=[vertcat(E_UVW_WI.tp,E_UVW_F_WI.tp,E_UVW_D_WI.tp,I_UVW_WI.tp,I_UVW_F_WI.tp,I_UVW_D_WI.tp,E_range_WI.tp,I_range_WI.tp,E_radial_WI.tp,I_radial_WI.tp,wmon_WI.tp)]; - dirP=[vertcat(E_UVW_WI.dtp,E_UVW_F_WI.dtp,E_UVW_D_WI.dtp,I_UVW_WI.dtp,I_UVW_F_WI.dtp,I_UVW_D_WI.dtp,E_range_WI.dtp,I_range_WI.dtp,E_radial_WI.dtp,I_radial_WI.dtp,wmon_WI.dtp)]; - Ddir=[vertcat(E_UVW_WI.dp,E_UVW_F_WI.dp,E_UVW_D_WI.dp,I_UVW_WI.dp,I_UVW_F_WI.dp,I_UVW_D_WI.dp,E_range_WI.dp,I_range_WI.dp,E_radial_WI.dp,I_radial_WI.dp,wmon_WI.dp)]; - - Winfo.hsig=[horzcat(Winfo.hsig,hsig)]; - Winfo.peakP=[horzcat(Winfo.peakP,peakP)]; - Winfo.dirP=[horzcat(Winfo.dirP,dirP)]; - Winfo.Ddir=[horzcat(Winfo.Ddir,Ddir)]; - -end - -% change Winfo.time back to a matlab datenum - -%Winfo.time=datenum(Winfo.time); - - Index: DPWavesProc/trunk/DPWavesProc/test_code/8marrayconf.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/8marrayconf.m (revision 225) @@ -1,0 +1,3 @@ +%calculate just the frequency energy spectrum +arrayrawfreq=sum(arrayraw.S')*dirres; +array8mfreq=sum(array8m.S')*dirres; Index: DPWavesProc/trunk/DPWavesProc/test_code/Winfo_plot_compare.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/Winfo_plot_compare.m (revision 225) @@ -1,0 +1,72 @@ +function [fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot(Winfo); + +%This function takes the wave info (sigH, peak period, direction of peak and dominant direction +%for a series of bursts and plots it as a function of time + + +%plot sig wave height +scrsz = get(0,'ScreenSize'); +fig_sigh=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.hsig(1,:),'b.-'); +hold on +h2=plot(Winfo.time,Winfo.hsig(2,:),'r.-'); +h3=plot(Winfo.time,Winfo.hsig(3,:),'g.-'); +h4=plot(Winfo.time,Winfo.hsig(4,:),'c.-'); +h5=plot(Winfo.time,Winfo.hsig(5,:),'m.-'); +h6=plot(Winfo.time,Winfo.hsig(7,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +title(['Significant Wave Height starting on ',datestr(Winfo.time(:,1),0)]); +xlabel('time'); +ylabel('Wave Height (m)'); + +%plot peak period +fig_pp=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.peakP(1,:),'b.-'); +hold on +h2=plot(Winfo.time,Winfo.peakP(2,:),'r.-'); +h3=plot(Winfo.time,Winfo.peakP(3,:),'g.-'); +h4=plot(Winfo.time,Winfo.peakP(4,:),'c.-'); +h5=plot(Winfo.time,Winfo.peakP(5,:),'m.-'); +h6=plot(Winfo.time,Winfo.peakP(7,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +title(['Peak Period starting on ',datestr(Winfo.time(:,1),0)]); +xlabel('time'); +ylabel('Period (seconds)'); + +%plot dir of peak period +fig_dp=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.dirP(1,:),'b.-'); +hold on +h2=plot(Winfo.time,Winfo.dirP(2,:),'r.-'); +h3=plot(Winfo.time,Winfo.dirP(3,:),'g.-'); +h4=plot(Winfo.time,Winfo.dirP(4,:),'c.-'); +h5=plot(Winfo.time,Winfo.dirP(5,:),'m.-'); +h6=plot(Winfo.time,Winfo.dirP(7,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +title(['Direction of Peak Period starting on ',datestr(Winfo.time(:,1),0)]); +xlabel('time'); +ylabel('Direction (Degrees True)'); + +%plot the dominant direction + +fig_dd=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.Ddir(1,:),'b.-'); +hold on +h2=plot(Winfo.time,Winfo.Ddir(2,:),'r.-'); +h3=plot(Winfo.time,Winfo.Ddir(3,:),'g.-'); +h4=plot(Winfo.time,Winfo.Ddir(4,:),'c.-'); +h5=plot(Winfo.time,Winfo.Ddir(5,:),'m.-'); +h6=plot(Winfo.time,Winfo.Ddir(7,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1, h2, h3, h4, h5, h6],'EMEP uvw','IMLM uvw','EMEP range','IMLM range','EMEP radial','wavesmon','location','best'); +title(['Dominant Direction starting on ',datestr(Winfo.time(:,1),0)] ); +xlabel('time'); +ylabel('Direction (Degrees True)'); + Index: DPWavesProc/trunk/DPWavesProc/test_code/nortek_Winfo_plot_compare.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/nortek_Winfo_plot_compare.m (revision 225) @@ -1,0 +1,64 @@ +function [fig_sigh,fig_pp,fig_dp,fig_dd]=nortek_Winfo_plot(Winfo); + +%This function takes the wave info (sigH, peak period, direction of peak and dominant direction +%for a series of bursts and plots it as a function of time + + +%plot sig wave height +scrsz = get(0,'ScreenSize'); +fig_sigh=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.hsig(1,:),'b.-'); +hold on +h1a=plot(Winfo.time,Winfo.hconf(1,1:2:end),'b--'); +plot(Winfo.time,Winfo.hconf(1,2:2:end),'b--'); +h2=plot(Winfo.time,Winfo.hsig(2,:),'r.-'); +h2a=plot(Winfo.time,Winfo.hconf(2,1:2:end),'r--'); +plot(Winfo.time,Winfo.hconf(2,2:2:end),'r--'); +h3=plot(Winfo.time,Winfo.hsig(3,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1,h1a,h2,h2a,h3],'EMEP','EMEP 95% confidence','IMLM','IMLM 95% confidence','nortek','location','best'); +title(['Significant Wave Height starting on ',datestr(Winfo.time(:,1),0)]); +xlabel('time'); +ylabel('Wave Height (m)'); + +%plot peak period +fig_pp=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.peakP(1,:),'b.-'); +hold on +h2=plot(Winfo.time,Winfo.peakP(2,:),'r.-'); +h3=plot(Winfo.time,Winfo.peakP(3,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1, h2, h3],'EMEP','IMLM','nortek','location','best'); +title(['Peak Period starting on ',datestr(Winfo.time(:,1),0)]); +xlabel('time'); +ylabel('Period (seconds)'); + +%plot dir of peak period +fig_dp=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.dirP(1,:),'b.-'); +hold on +h2=plot(Winfo.time,Winfo.dirP(2,:),'r.-'); +h3=plot(Winfo.time,Winfo.dirP(3,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1, h2, h3],'EMEP','IMLM','nortek','location','best'); +title(['Direction of Peak Period starting on ',datestr(Winfo.time(:,1),0)]); +xlabel('time'); +ylabel('Direction (Degrees True)'); + +%plot the dominant direction + +fig_dd=figure('Position',[scrsz]); +h1=plot(Winfo.time,Winfo.Ddir(1,:),'b.-'); +hold on +h2=plot(Winfo.time,Winfo.Ddir(2,:),'r.-'); +h3=plot(Winfo.time,Winfo.Ddir(3,:),'k.-'); + +datetick('x',15,'keepticks'); +legend([h1, h2, h3],'EMEP','IMLM','nortek','location','best'); +title(['Dominant Direction starting on ',datestr(Winfo.time(:,1),0)]); +xlabel('time'); +ylabel('Direction (Degrees True)'); + Index: DPWavesProc/trunk/DPWavesProc/test_code/nortek_specmultiplot_compare.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/nortek_specmultiplot_compare.m (revision 225) @@ -1,0 +1,118 @@ +function [Winfo]=nortek_specmultiplot(dateinfo1,dateinfo2,timestep); + +%NOTE: This function is for the Nortek AWAC profiler! + +%where dateinfo1 and 2 are the strings of the first and last date extension +%of the pressure,range,etc files and timestep is the time in hours between +%each burst + +%This function takes the pressure, range, orbit and sysinfo files created +%in python and outputs a Winfo data structure with the sig wave height, +%peak period, direction of peak period and dominant dir. It also generates +%polar plots and 2d freq and directional plots of a variety of different +%estimation methods, resolutions and the nortek quickwave output. + + +%first set up the time vector going from dateinfo1 to dateinfo2 +Winfo.time=[]; + +date1=datevec(dateinfo1, 'yymmddHHMM'); +date2=datevec(dateinfo2,'yymmddHHMM'); + +if date1 == date2 + Winfo.time=[datenum(date1)]; +else + Winfo.time=[datenum(date1)]; + newdate=date1; + while datenum(newdate) ~= datenum(date2) + newdate=newdate+[0 0 0 timestep 0 0]; + Winfo.time=[horzcat(Winfo.time,datenum(newdate))]; + end +end + + +%set up time, which is Winfo.time as date str in the yymmddHHMM format +time=datestr(Winfo.time, 'yymmddHHMM'); + +%set up data structure for wave info +Winfo.setup={'EMEP','IMLM' 'nortek'}'; +Winfo.hsig=[]; +Winfo.hconf=[]; +Winfo.peakP=[]; +Winfo.dirP=[]; +Winfo.Ddir=[]; +Winfo.Spectrum.EMEP=[]; +Winfo.Spectrum.IMLM=[]; +Winfo.Spectrum.nortek=[]; + +%load the wave data from the nortek quick wave software +wavedata=load('BPWave01.wap'); + +%Load the data and run the script +for i=1:length(time(:,1)) + dateinfo=time(i,:); + + pressure=strcat('pressure_',dateinfo,'.txt'); + range=strcat('range_',dateinfo,'.txt'); + orbit=strcat('orbit_',dateinfo,'.txt'); + sysinfo=strcat('sysinfo_',dateinfo,'.txt'); + nortekspec=strcat('nortekspec_',dateinfo,'.txt'); + + pressure=load(pressure); + range=load(range); + orbit=load(orbit); + sysinfo=load(sysinfo); + nortekspec=load(nortekspec); + + %set up data with standard AST freq at 0.01 and dir at 2 + [ID,SM,EP]=nortek_radialtouvw(pressure,range,orbit,sysinfo,1); + + %run diwasp to generate this spectrum + [E_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now for IMLM + EP.method='IMLM'; + EP.iter=3; + [I_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + + %Use waveplot to plot the polar, freq and dir plots of the spectra + + [E_WI,I_WI,nortek_WI,fig1,fig2]=nortek_waveplot(E_F01_D2,I_F01_D2,sysinfo,nortekspec); + + saveas(fig1,['polar1_' dateinfo '.fig']); + saveas(fig2,['dirfreq1_' dateinfo '.fig']); + + close all; + + %Fill up the Winfo data structure + + hsig=[vertcat(E_WI.hsig,I_WI.hsig,nortek_WI.hsig)]; + hconf=[vertcat(E_WI.hconf,I_WI.hconf,nortek_WI.hconf)]; + peakP=[vertcat(E_WI.tp,I_WI.tp,nortek_WI.tp)]; + dirP=[vertcat(E_WI.dtp,I_WI.dtp,nortek_WI.dtp)]; + Ddir=[vertcat(E_WI.dp,I_WI.dp,nortek_WI.dp)]; + + Winfo.hsig=[horzcat(Winfo.hsig,hsig)]; + Winfo.hconf=[horzcat(Winfo.hconf,hconf)]; + Winfo.peakP=[horzcat(Winfo.peakP,peakP)]; + Winfo.dirP=[horzcat(Winfo.dirP,dirP)]; + Winfo.Ddir=[horzcat(Winfo.Ddir,Ddir)]; + Winfo.Spectrum.EMEP=[cat(3,Winfo.Spectrum.EMEP,E_F01_D2.S)]; + Winfo.Spectrum.IMLM=[cat(3,Winfo.Spectrum.IMLM,I_F01_D2.S)]; + Winfo.Spectrum.nortek=[cat(3,Winfo.Spectrum.nortek,nortekspec)]; + +end + +%now create the time series plots of the wave info +[fig_sigh,fig_pp,fig_dp,fig_dd]=nortek_Winfo_plot(Winfo); + +saveas(fig_sigh,['sigh_' dateinfo '.fig']); +saveas(fig_pp,['peakp_' dateinfo '.fig']); +saveas(fig_dp,['dirpeak_' dateinfo '.fig']); +saveas(fig_dd,['domdir_' dateinfo '.fig']); + +close all; + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/nortek_waveplot_compare.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/nortek_waveplot_compare.m (revision 225) @@ -1,0 +1,268 @@ +function [E_WI,I_WI,nortek_WI,fig1,fig2]=nortek_waveplot(EMEP,IMLM,sysinfo,nortekspec) + +%make sure to load the EMEP, IMLM and wavesmon samples +%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') +%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') + +%set up the wavesmon data in a structure + +%what is the magnetic variation to nearest degree +magvar=-10; + +%what is the frequency and dir resolution for those generated in DIWASP +freqres=0.01; +freqs=[0.01:0.01:.4]; +dirres=2; +dirs=[-180:2:180]; + +%what is the frequency and dir resolution for those created by nortek +%freqres is the same +nortekfreqs=[0.01:0.01:.4]; +nortekdirres=4; +nortekdirs=[270:-4:-86]; +nortek.S=nortekspec; +nortek.dirs=nortekdirs; +nortek.freqs=nortekfreqs; +nortek.xaxisdir=90; + +% plot the spectrum generated through DIWASP + +scrsz = get(0,'ScreenSize'); +fig1=figure('Position',[scrsz]); +subplot(2,2,1); +subplotspec(EMEP,4); +title('EMEP AST beam and radial velocities'); + +subplot(2,2,2); +subplotspec(IMLM,4); +title('IMLM AST beam and radial velocities'); + +subplot(2,2,3); +subplotspec(nortek,4); +title('nortek quick wave spectrum'); + + +%calculate just the dir energy spectrum on a single graph + +EMEPdir=sum(EMEP.S)*freqres; +IMLMdir=sum(real(IMLM.S))*freqres; +nortekdir=sum(nortek.S)*freqres; + + +%calculate just the frequency energy spectrum +EMEPfreq=sum(EMEP.S')*dirres; +IMLMfreq=sum(real(IMLM.S)')*dirres; +nortekfreq=sum(nortek.S')*nortekdirres; + +%Compute the coefficient for the upper and lower error bounds for the +%frequency +%spectrum assuming 95% confidence. Added on 9/17/08 +degF=2*EMEP.degF; % 2* since for the Nortek the range beam sampled at 4hz (4096) is decimated or averaged to 2hz (2048) +chiUp=chi2inv(.975,degF); +chiLow=chi2inv(.025,degF); +coeffUp=degF/chiLow; +coeffLow=degF/chiUp; + +%calculate the conf limits throughout the frequency spectrum +EMEPfreqUP=EMEPfreq*coeffUp; +EMEPfreqLOW=EMEPfreq*coeffLow; +IMLMfreqUP=IMLMfreq*coeffUp; +IMLMfreqLOW=IMLMfreq*coeffLow; + +%Find the maximum for the directional spectrum so we can set up the proper +%x-axis +[maxvalue,maxindex] = max(EMEPdir); +maxdir=dirs(maxindex); +% set up the x-axis for all of the spectra depending on the max +if ((100 < maxdir) | (maxdir < -100)); + %for diwasp spectra + index1=find(dirs < 0); + index2=find(dirs > -1); + dirs(index1)=dirs(index1) +360; + %for nortek + Aindex=find(nortek.dirs < 0); + Bindex=find((-1 < nortek.dirs) & (nortek.dirs < 361)); + Bindex2=find(nortek.dirs > 360); + nortek.dirs(Bindex2)=nortek.dirs(Bindex2)-360; + nortek.dirs(Aindex)=nortek.dirs(Aindex)+360; + + %plot the directional energy spectrum + fig2=figure('Position',[scrsz]); + subplot(1,2,1); + h1 = plot(dirs(index2),EMEPdir(index2),'b'); + hold on + h1a= plot(dirs(index1),EMEPdir(index1),'b'); + h2 = plot(dirs(index2),IMLMdir(index2),'r'); + h2a= plot(dirs(index1),IMLMdir(index1),'r'); + %plot the nortek data + h3 = plot(nortek.dirs(Bindex2),nortekdir(Bindex2),'k'); + h3a = plot(nortek.dirs(Bindex),nortekdir(Bindex),'k'); + h3b= plot(nortek.dirs(Aindex),nortekdir(Aindex),'k'); +else + %for diwasp spectra do nothing + + %for nortek + Aindex=find(nortek.dirs > 180); + Bindex=find(nortek.dirs < 181); + nortek.dirs(Aindex)=nortek.dirs(Aindex)-360; + %plot the directional energy spectrum + fig2=figure('Position',[scrsz]); + subplot(1,2,1); + h1 = plot(dirs,EMEPdir,'b'); + hold on + h2 = plot(dirs,IMLMdir,'r'); + %plot the nortek data + h3a = plot(nortek.dirs(Bindex),nortekdir(Bindex),'k'); + h3b = plot(nortek.dirs(Aindex),nortekdir(Aindex),'k'); + +end + +legend([h1, h2, h3a],'EMEP','IMLM','nortek quickwave','location','best'); +title('directional wave spectrum integrated over frequency'); +xlabel('axis angle (degrees true)'); +ylabel('m^2 / deg'); + +%plot the frequency energy spectrum +subplot(1,2,2); +h1=plot(freqs,EMEPfreq,'b'); +hold on +h2=plot(freqs,EMEPfreqUP,'b--'); +plot(freqs,EMEPfreqLOW,'b--'); +h3=plot(freqs,IMLMfreq,'r'); +h4=plot(freqs,IMLMfreqUP,'r--'); +plot(freqs,IMLMfreqLOW,'r--'); +h5=plot(nortekfreqs,nortekfreq,'k'); +legend('EMEP','EMEP 95% confidence','IMLM','IMLM 95% confidence','nortek quickwave','location','best'); +title('directional wave spectrum integrated over direction'); +xlabel('frequency in Hz'); +ylabel('m^2 / hz'); + +% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ + +%For EMEP AST and radial velocities + +%calculate the 0,1,2 moments +m0=sum(EMEPfreq*freqres); +m1=sum(freqs.*EMEPfreq*freqres); +m2=sum((freqs.^2).*EMEPfreq*freqres); +% Calculate the Sig wave height +EMEP_Hsig=4*sqrt(m0); +%Use the function HsigConf.m to calculate the sigH confidence limits +EMEP_HsConf=nortek_HsigConf(EMEP); + +% Calculate the peak period Tp +[P,I]=max(EMEPfreq); +EMEP_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(EMEP.S(I,:))); +EMEP_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(EMEPdir); +EMEP_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP']); +disp(['SigH (meters): ' num2str(EMEP_Hsig)]); +disp(['SigH 95% conf. (meters): ' num2str(EMEP_HsConf)]); +disp(['peak period (seconds): ' num2str(EMEP_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(EMEP_DTp, EMEP.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(EMEP_Dp, EMEP.xaxisdir))]); +disp([' ']); + +E_WI.hsig=EMEP_Hsig; +E_WI.hconf=EMEP_HsConf; +E_WI.tp=EMEP_Tp; +E_WI.dtp=compangle(EMEP_DTp, EMEP.xaxisdir); +E_WI.dp=compangle(EMEP_Dp, EMEP.xaxisdir); + + +% For IMLM AST and radial velocities + +%calculate the 0,1,2 moments +m0=sum(IMLMfreq*freqres); +m1=sum(freqs.*IMLMfreq*freqres); +m2=sum((freqs.^2).*IMLMfreq*freqres); +% Calculate the Sig wave height +IMLM_Hsig=4*sqrt(m0); +%Use the function HsigConf.m to calculate the sigH confidence limits +IMLM_HsConf=nortek_HsigConf(IMLM); + +% Calculate the peak period Tp +[P,I]=max(IMLMfreq); +IMLM_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(IMLM.S(I,:))); +IMLM_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(IMLMdir); +IMLM_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM']); +disp(['SigH (meters): ' num2str(IMLM_Hsig)]); +disp(['SigH 95% conf. (meters): ' num2str(IMLM_HsConf)]); +disp(['peak period (seconds): ' num2str(IMLM_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(IMLM_DTp, IMLM.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(IMLM_Dp, IMLM.xaxisdir))]); +disp([' ']); + +I_WI.hsig=IMLM_Hsig; +I_WI.hconf=IMLM_HsConf; +I_WI.tp=IMLM_Tp; +I_WI.dtp=compangle(IMLM_DTp, IMLM.xaxisdir); +I_WI.dp=compangle(IMLM_Dp, IMLM.xaxisdir); + + + +%for nortek generated spectrum + +%calculate the 0,1,2 moments +m0=sum(nortekfreq*freqres); +m1=sum(nortekfreqs.*nortekfreq*freqres); +m2=sum((nortekfreqs.^2).*nortekfreq*freqres); +% Calculate the Sig wave height +nortek_Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(nortekfreq); +nortek_Tp=1/(nortekfreqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(nortek.S(I,:))); +nortek_DTp=nortekdirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(nortekdir); +nortek_Dp=nortekdirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['nortek']); +disp(['SigH (meters): ' num2str(nortek_Hsig)]); +disp(['peak period (seconds): ' num2str(nortek_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(nortek_DTp, nortek.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(nortek_Dp, nortek.xaxisdir))]); +disp([' ']); + +nortek_WI.hsig=nortek_Hsig; +nortek_WI.hconf=[NaN NaN]; +nortek_WI.tp=nortek_Tp; +nortek_WI.dtp=compangle(nortek_DTp, nortek.xaxisdir); +nortek_WI.dp=compangle(nortek_Dp, nortek.xaxisdir); + + + +%function to change from axis angles to compass bearings + +function angle=compangle(angle,xaxisdir) +angle=xaxisdir*ones(size(angle))-angle; +angle=angle+360*(angle<0); +angle=angle-360*(angle>360); + + + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/radialtouvw1.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/radialtouvw1.m (revision 225) @@ -1,0 +1,304 @@ +function [ID,SM,EP,orbitnew]=radialtouvw1(pressure,range,orbit,sysinfo,data_type) + + +%This code takes the loaded orbit, pressure and system info data from an +%ADCP waves output and computes the uvw velocities in earth coordinates. +%It also interpolates to remove bad data points and prepares the data +%structure required for running the DIWASP program. The output will be in +%the structures ID, SM and EP. + +%data_type is: +%1 to use uvw and pressure to generate the data structures, +%2 to use ranges +%3 to use radial velocity data + + + +%make sure to load: pressure=load('pressure data'), +%orbit=load('orbital data'),sysinfo=load('sysinfo data') and range + +%what is the transducer face height off the bottom? +adcpheight=0.4; + +%whats the magnetic variation +magvar=9.63; + +%set up sysinfo file +samplesInBurst=sysinfo(3,:); +bin1height=sysinfo(9,:); +bin2height=sysinfo(10,:); +bin3height=sysinfo(11,:); +bin4height=sysinfo(12,:); +bin5height=sysinfo(13,:); +heading=sysinfo(18,:); +pitch=sysinfo(19,:); +roll=sysinfo(20,:); + +%set up pressure +press=pressure/1000; + +%find the average depth +avgdepth=mean(press)+adcpheight; + +%set up range +range=range/1000; +meanrange=mean(range); +meanrange=repmat(meanrange,samplesInBurst,1); +dmrange=range-meanrange; +std_range=std(dmrange); + +% Take out any bad data points in orbital data +ibad=find(orbit < -32000); +orbit(ibad) = NaN; +orbit=orbit/1000; +orbitnew=orbit; +%interpolate to take out any NaNs and QC for bad data in orbital data +std_orbit=ones(1,20); +for i=1:20 + + %first take out any points outside of 4 std deviations + std_orbit(i)=nanstd(orbit(:,i)); + ibad_std=find(abs(orbit(:,i)) > 4*std_orbit(i)); + orbit(ibad_std,i)=NaN; +end +%find the avg std deviation for each group 4 beams +for i=4:4:20 + avgstd_orbit(i-3:i)=mean(std_orbit(i-3:i)); +end + +%now remove the points outside 4avg std dev and interp +for i=1:20 + ibad_std=find(abs(orbit(:,i)) > 4*avgstd_orbit(i)); + orbit(ibad_std,i)=NaN; + + time=[1:1:length(orbit(:,i))]; + NaNs=isnan(orbit(:,i)); + igood=find(NaNs == 0); + ibad=find(NaNs == 1); + + intValues= interp1(time(igood),orbit(igood,i),time(ibad),'linear','extrap'); + orbitnew(ibad,i)=intValues; +end + +% Do similar QC for the range data +rangenew=dmrange; +for i=1:4 + ibad=find(abs(dmrange(:,i)) > 4*std_range(:,i)); + dmrange(ibad,i)=NaN; + time=[1:1:length(range(:,i))]; + NaNs=isnan(dmrange(:,i)); + igood=find(NaNs == 0); + ibad=find(NaNs == 1); + + intValues= interp1(time(igood),dmrange(igood,i),time(ibad),'linear','extrap'); + rangenew(ibad,i)=intValues; +end + +dmrange=rangenew; + +%change heading, pitch, roll into degrees + +heading = heading/100; +pitch=pitch/100; +roll=roll/100; +pitch_out=pitch; +roll_out=roll; + +%When converting to earth coordinates, the directions will be wrong unless we +%correct for bottom/up facing ADCPs, simply by rotating the roll by 180 +roll=roll+180; + +%Set up geometry for transformation from beam to instrument +C1 = 1; +A1 = 1/(2*sin(20*pi/180)); +B1 = 1/(4*cos(20*pi/180)); +D1 = A1/sqrt(2); + +% coordinate transformation matrix +CH = cos((heading+magvar)*pi/180); +SH = sin((heading+magvar)*pi/180); +CP = cos((pitch)*pi/180); +SP = sin((pitch)*pi/180); +CR = cos((roll)*pi/180); +SR = sin((roll)*pi/180); + +% let the matrix elements be ( a b c; d e f; g h j); +a = CH.*CR + SH.*SP.*SR; b = SH.*CP; c = CH.*SR - SH.*SP.*CR; +d = -SH.*CR + CH.*SP.*SR; e = CH.*CP; f = -SH.*SR - CH.*SP.*CR; +g = -CP.*SR; h = SP; j = CP.*CR; +uno=1; + +%reshape the orbital matrix to 3 dimensions + +radial=reshape(orbitnew,samplesInBurst,4,5); + +% Compute uvw velocities and change to earth coordinates + +u = C1*A1*(radial(:,1,:)-radial(:,2,:)); +v = C1*A1*(radial(:,4,:)-radial(:,3,:)); +w = B1*(radial(:,1,:)+radial(:,2,:)+radial(:,3,:)+radial(:,4,:)); +error_vel = D1*(radial(:,1,:)+radial(:,2,:)-radial(:,3,:)-radial(:,4,:)); + +u=reshape(u,samplesInBurst,5); +v=reshape(v,samplesInBurst,5); +w=reshape(w,samplesInBurst,5); +error_vel=reshape(error_vel,samplesInBurst,5); + +[m,n] = size(u); +uno = ones(m,5); +unew = u.*(uno*a) + v.*(uno*b) + w.*(uno*c); +vnew = u.*(uno*d) + v.*(uno*e) + w.*(uno*f); +wnew = u.*(uno*g) + v.*(uno*h) + w.*(uno*j); + +u_all = unew;v_all=vnew;w_all=wnew; +error_vel_all = error_vel; + +%compute the original x,y,z positions for each beam for each bin to be accurate we need to take out the adcpheight + +xyzpos=ones(3,4,5); +heights=[bin1height bin2height bin3height bin4height bin5height avgdepth]-adcpheight; +pos=heights*tan(20*pi/180); +for i=1:5 + xyzpos(:,1,i)=[pos(i),0,heights(i)]; + xyzpos(:,2,i)=[-pos(i),0,heights(i)]; + xyzpos(:,3,i)=[0,pos(i),heights(i)]; + xyzpos(:,4,i)=[0,-pos(i),heights(i)]; +end + +% set up the new coordinate transformation matrix +CH = cos((heading+magvar)*pi/180); +SH = sin((heading+magvar)*pi/180); +CP = cos((pitch_out)*pi/180); +SP = sin((pitch_out)*pi/180); +CR = cos((-roll_out)*pi/180); +SR = sin((-roll_out)*pi/180); + +% let the matrix elements be ( a b c; d e f; g h j), a slightly different +% matrix from before; +a = CH.*CR - SH.*SP.*SR; b = SH.*CP; c = -CH.*SR - SH.*SP.*CR; +d = -SH.*CR - CH.*SP.*SR; e = CH.*CP; f = SH.*SR - CH.*SP.*CR; +g = CP.*SR; h = SP; j = CP.*CR; + +%transform the original x,y,z positions to the new positions accounting for +%heading, pitch and roll... we also add adcpheight back in +newxyzpos=ones(3,4,5); +new_xyzpos(1,:,:)=xyzpos(1,:,:)*a+xyzpos(2,:,:)*b+xyzpos(3,:,:)*c; +new_xyzpos(2,:,:)=xyzpos(1,:,:)*d+xyzpos(2,:,:)*e+xyzpos(3,:,:)*f; +new_xyzpos(3,:,:)=xyzpos(1,:,:)*g+xyzpos(2,:,:)*h+xyzpos(3,:,:)*j+adcpheight; + +xyzpositions=new_xyzpos; + + +%now we need to figure out the xyz positions at the surface for the range +%sin45=0.7071 + +binheight=heights(:,6); + +%beam 3 +bearing=(heading+magvar)*(pi/180); +distfromz=binheight*tan((20-pitch_out)*(pi/180)); +xpos=sin(bearing)*distfromz; +ypos=cos(bearing)*distfromz; + +distroll=binheight*tan(roll_out*(pi/180)); +beam3xpos=xpos+0.7071*distroll; +beam3ypos=ypos+0.7071*distroll; + +%beam 4 +bearing=bearing+pi; +distfromz=binheight*tan((20+pitch_out)*(pi/180)); +xpos=sin(bearing)*distfromz; +ypos=cos(bearing)*distfromz; + +distroll=binheight*tan(roll_out*(pi/180)); +beam4xpos=xpos+0.7071*distroll; +beam4ypos=ypos+0.7071*distroll; + +%beam 1 +bearing=bearing-pi/2; +distfromz=binheight*tan((20+roll_out)*(pi/180)); +xpos=sin(bearing)*distfromz; +ypos=cos(bearing)*distfromz; + +distroll=binheight*tan(pitch_out*(pi/180)); +beam1xpos=xpos+0.7071*distroll; +beam1ypos=ypos+0.7071*distroll; + +%beam2 +bearing=bearing+pi; +distfromz=binheight*tan((20-roll_out)*(pi/180)); +xpos=sin(bearing)*distfromz; +ypos=cos(bearing)*distfromz; + +distroll=binheight*tan(pitch_out*(pi/180)); +beam2xpos=xpos+0.7071*distroll; +beam2ypos=ypos+0.7071*distroll; + +xypositions(:,:)=[beam1xpos beam2xpos beam3xpos beam4xpos; beam1ypos beam2ypos beam3ypos beam4ypos]; + +%Put into structures for DIWASP + + +%sampling frequency +ID.fs=2; +%depth +ID.depth=(adcpheight+mean(press)); +%the spectral matrix structure +SM.freqs=[0.01:0.01:0.4]; +SM.dirs=[-180:2:180]; +SM.xaxisdir= 90; +%the estimation parameter +EP.method= 'EMEP'; +EP.iter=100; + +if data_type == 1 + %For uvw and pressure for bins 2,3,4 + % the datatypes + ID.datatypes={'pres' 'velx' 'vely' 'velz' 'velx' 'vely' 'velz' 'velx' 'vely' 'velz'}; + % the layout + ID.layout = [ 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0; + adcpheight bin2height bin2height bin2height bin3height bin3height bin3height bin4height bin4height bin4height]; + % the data + ID.data = horzcat(press, u_all(:,2), v_all(:,2), w_all(:,2), u_all(:,3), v_all(:,3), w_all(:,3),u_all(:,4), v_all(:,4), w_all(:,4)); + +elseif data_type == 2 + %For the ranges of each beam + % the datatypes + ID.datatypes={'elev' 'elev' 'elev' 'elev'}; + % the layout + ID.layout = [xypositions(1,1) xypositions(1,2) xypositions(1,3) xypositions(1,4); + xypositions(2,1) xypositions(2,2) xypositions(2,3) xypositions(2,4); + avgdepth avgdepth avgdepth avgdepth]; + % the data + ID.data = horzcat(dmrange(:,1), dmrange(:,2), dmrange(:,3), dmrange(:,4)); + +elseif data_type == 3 + % For the radial velocities bins 2,3,4 + % the datatypes + ID.datatypes={'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial' 'radial'}; + % the layout + %ID.layout = [xyzpositions(1,1,2) xyzpositions(1,2,2) xyzpositions(1,3,2) xyzpositions(1,4,2) xyzpositions(1,1,3) xyzpositions(1,2,3) xyzpositions(1,3,3) xyzpositions(1,4,3) xyzpositions(1,1,4) xyzpositions(1,2,4) xyzpositions(1,3,4) xyzpositions(1,4,4); + %xyzpositions(2,1,2) xyzpositions(2,2,2) xyzpositions(2,3,2) xyzpositions(2,4,2) xyzpositions(2,1,3) xyzpositions(2,2,3) xyzpositions(2,3,3) xyzpositions(2,4,3) xyzpositions(2,1,4) xyzpositions(2,2,4) xyzpositions(2,3,4) xyzpositions(2,4,4); + %xyzpositions(3,1,2) xyzpositions(3,2,2) xyzpositions(3,3,2) xyzpositions(3,4,2) xyzpositions(3,1,3) xyzpositions(3,2,3) xyzpositions(3,3,3) xyzpositions(3,4,3) xyzpositions(3,1,4) xyzpositions(3,2,4) xyzpositions(3,3,4) xyzpositions(3,4,4)]; + % the data + %ID.data = horzcat(orbitnew(:,5),orbitnew(:,6),orbitnew(:,7),orbitnew(:,8),orbitnew(:,9),orbitnew(:,10),orbitnew(:,11),orbitnew(:,12),orbitnew(:,13),orbitnew(:,14),orbitnew(:,15),orbitnew(:,16)); + + % the layout using bins 3,4,5 + ID.layout = [xyzpositions(1,1,5) xyzpositions(1,2,5) xyzpositions(1,3,5) xyzpositions(1,4,5) xyzpositions(1,1,4) xyzpositions(1,2,4) xyzpositions(1,3,4) xyzpositions(1,4,4) xyzpositions(1,1,3) xyzpositions(1,2,3) xyzpositions(1,3,3) xyzpositions(1,4,3); + xyzpositions(2,1,3) xyzpositions(2,2,3) xyzpositions(2,3,3) xyzpositions(2,4,3) xyzpositions(2,1,4) xyzpositions(2,2,4) xyzpositions(2,3,4) xyzpositions(2,4,4) xyzpositions(2,1,3) xyzpositions(2,2,3) xyzpositions(2,3,3) xyzpositions(2,4,3); + xyzpositions(3,1,3) xyzpositions(3,2,3) xyzpositions(3,3,3) xyzpositions(3,4,3) xyzpositions(3,1,4) xyzpositions(3,2,4) xyzpositions(3,3,4) xyzpositions(3,4,4) xyzpositions(3,1,3) xyzpositions(3,2,3) xyzpositions(3,3,3) xyzpositions(3,4,3)]; + % the data + ID.data = horzcat(orbitnew(:,17),orbitnew(:,18),orbitnew(:,19),orbitnew(:,20),orbitnew(:,13),orbitnew(:,14),orbitnew(:,15),orbitnew(:,16),orbitnew(:,9),orbitnew(:,10),orbitnew(:,11),orbitnew(:,12)); + +end + + + + + + + + + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/radialwaveplot.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/radialwaveplot.m (revision 225) @@ -1,0 +1,260 @@ +function [E_radial_WI,I_radial_WI,fig5,fig6]=radialwaveplot(radialE,radialI,spec,sysinfo) + +%make sure to load the EMEP, IMLM and wavesmon samples +%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') +%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') + +%set up the wavesmon data in a structure + +%what is the magnetic variation to nearest degree +magvar=-10; + +%first change to m^2/Hz/deg +wmon.S=spec/(360*1000*1000); + +%what is the start angle +heading=sysinfo(18,:); +heading=heading/100; +sangle=heading+magvar; + +%what is the frequency and dir resolution for those generated in DIWASP +freqres=0.01; +freqs=[0.01:0.01:.4]; +dirres=2; +dirs=[-180:2:180]; + +%set up the directions +adj_angle=90-sangle+360+180; +wmon.dirs=[adj_angle:-4:-(356-adj_angle)]; +wmondirres=4; +wmon.xaxisdir=90; +wmon.freqs=[0.00781250:0.00781250:1]; +wmonfreqres=0.00781250; + +% plot the spectrum generated through DIWASP +scrsz = get(0,'ScreenSize'); +fig5=figure('Position',[scrsz]); +subplot(2,3,1); +subplotspec(radialE,4); +title('EMEP radial vel'); + +subplot(2,3,2); +subplotspec(radialI,4); +title('IMLM radial vel'); + +subplot(2,3,3); +subplotspec(wmon,4); +title('Wavesmon output'); + + +%calculate just the dir energy spectrum on a single graph + +EMEPdir=sum(radialE.S)*freqres; +IMLMdir=sum(real(radialI.S))*freqres; +wmondir=sum(wmon.S)*wmonfreqres; + +%calculate just the frequency energy spectrum +EMEPfreq=sum(radialE.S')*dirres; +IMLMfreq=sum(real(radialI.S)')*dirres; +wmonfreq=sum(wmon.S')*wmondirres; + +%Compute the coefficient for the upper and lower error bounds for the +%frequency +%spectrum assuming 95% confidence. Added on 9/17/08 +degF=radialE.degF; +chiUp=chi2inv(.975,degF); +chiLow=chi2inv(.025,degF); +coeffUp=degF/chiLow; +coeffLow=degF/chiUp; + +%calculate the conf limits throughout the frequency spectrum +EMEPfreqUP=EMEPfreq*coeffUp; +EMEPfreqLOW=EMEPfreq*coeffLow; + +%Find the maximum for the directional spectrum so we can set up the proper +%x-axis +[maxvalue,maxindex] = max(EMEPdir); +maxdir=dirs(maxindex); +% set up the x-axis for all of the spectra depending on the max +if ((100 < maxdir) | (maxdir < -100)); + %for diwasp spectra + index1=find(dirs < 0); + index2=find(dirs > -1); + dirs(index1)=dirs(index1) +360; + %for wavesmon + Aindex=find(wmon.dirs < 0); + Bindex=find((-1 < wmon.dirs) & (wmon.dirs < 361)); + Bindex2=find(wmon.dirs > 360); + wmon.dirs(Bindex2)=wmon.dirs(Bindex2)-360; + wmon.dirs(Aindex)=wmon.dirs(Aindex)+360; + %plot the directional energy spectrum + fig6=figure('Position',[scrsz]); + subplot(1,2,1); + h1 = plot(dirs(index2),EMEPdir(index2),'b'); + hold on + h1a= plot(dirs(index1),EMEPdir(index1),'b'); + %plot the wavesmon data + h2 = plot(wmon.dirs(Bindex2),wmondir(Bindex2),'k'); + h2a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); + h2b= plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); + axis(axis); + h5 = plot(dirs(index2),IMLMdir(index2),'c'); + h5a= plot(dirs(index1),IMLMdir(index1),'c'); + +else + %for diwasp spectra do nothing + + %for wavesmon + Aindex=find(wmon.dirs > 180); + Bindex=find(wmon.dirs < 181); + wmon.dirs(Aindex)=wmon.dirs(Aindex)-360; + %plot the directional energy spectrum + fig6=figure('Position',[scrsz]); + subplot(1,2,1); + h1 = plot(dirs,EMEPdir,'b'); + hold on + %plot the wavesmon data + h2 = plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); + h2a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); + axis(axis); + h5 = plot(dirs,IMLMdir,'c'); +end + +legend([h1, h2,h5], 'EMEP radial vel','wavesmon','IMLM radial vel','location','best'); +title('directional wave spectrum integrated over frequency'); +xlabel('axis angle (degrees true)'); +ylabel('m^2 / deg'); + +%plot the frequency energy spectrum +subplot(1,2,2); +h1 = plot(freqs,EMEPfreq,'b'); +hold on +%h2 = plot(freqs,EMEPfreqLOW,'b--'); +%h3 = plot(freqs,EMEPfreqUP,'b--'); +h4 = plot(wmon.freqs,wmonfreq,'k'); +axis(axis); +h5 = plot(freqs,IMLMfreq,'c'); +legend([h1,h4,h5],'EMEP radial vel','wavesmon','IMLM radial vel','location','best'); +title('directional wave spectrum integrated over direction'); +xlabel('frequency in Hz'); +ylabel('m^2 / Hz'); + +% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ + +%For EMEP radial + +%calculate the 0,1,2 moments +m0=sum(EMEPfreq*freqres); +m1=sum(freqs.*EMEPfreq*freqres); +m2=sum((freqs.^2).*EMEPfreq*freqres); +% Calculate the Sig wave height +EMEP_radial_Hsig=4*sqrt(m0); +%Use the function HsigConf.m to calculate the sigH confidence limits +EMEP_HsConf=HsigConf(radialE); + +% Calculate the peak period Tp +[P,I]=max(EMEPfreq); +EMEP_radial_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(radialE.S(I,:))); +EMEP_radial_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(EMEPdir); +EMEP_radial_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP radial vel']); +disp(['SigH (meters): ' num2str(EMEP_radial_Hsig)]); +disp(['SigH 95% confidence limits: ' num2str(EMEP_HsConf)]); +disp(['peak period (seconds): ' num2str(EMEP_radial_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(EMEP_radial_DTp, radialE.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(EMEP_radial_Dp, radialE.xaxisdir))]); +disp([' ']); + +E_radial_WI.hsig=EMEP_radial_Hsig; +E_radial_WI.hconf=EMEP_HsConf; +E_radial_WI.tp=EMEP_radial_Tp; +E_radial_WI.dtp=compangle(EMEP_radial_DTp, radialE.xaxisdir); +E_radial_WI.dp=compangle(EMEP_radial_Dp, radialE.xaxisdir); + +% For IMLM r + +%calculate the 0,1,2 moments +m0=sum(IMLMfreq*freqres); +m1=sum(freqs.*IMLMfreq*freqres); +m2=sum((freqs.^2).*IMLMfreq*freqres); +% Calculate the Sig wave height +IMLM_radial_Hsig=4*sqrt(m0); +%Use the function HsigConf.m to calculate the sigH confidence limits +IMLM_HsConf=HsigConf(radialI); + +% Calculate the peak period Tp +[P,I]=max(IMLMfreq); +IMLM_radial_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(radialI.S(I,:))); +IMLM_radial_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(IMLMdir); +IMLM_radial_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM radial vel']); +disp(['SigH (meters): ' num2str(IMLM_radial_Hsig)]); +disp(['SigH 95% confidence limits: ' num2str(IMLM_HsConf)]); +disp(['peak period (seconds): ' num2str(IMLM_radial_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(IMLM_radial_DTp, radialI.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(IMLM_radial_Dp, radialI.xaxisdir))]); +disp([' ']); + +I_radial_WI.hsig=IMLM_radial_Hsig; +I_radial_WI.hconf=IMLM_HsConf; +I_radial_WI.tp=IMLM_radial_Tp; +I_radial_WI.dtp=compangle(IMLM_radial_DTp, radialI.xaxisdir); +I_radial_WI.dp=compangle(IMLM_radial_Dp, radialI.xaxisdir); + +% for wavesmon + +%calculate the 0,1,2 moments +m0=sum(wmonfreq*wmonfreqres); +m1=sum(wmon.freqs.*wmonfreq*wmonfreqres); +m2=sum((wmon.freqs.^2).*wmonfreq*wmonfreqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(wmonfreq); +Tp=1/(wmon.freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(wmon.S(I,:))); +DTp=wmon.dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(wmondir); +Dp=wmon.dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['Wavesmon output']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, wmon.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, wmon.xaxisdir))]); +disp([' ']); + + +%function to change from axis angles to compass bearings + +function angle=compangle(angle,xaxisdir) +angle=xaxisdir*ones(size(angle))-angle; +angle=angle+360*(angle<0); +angle=angle-360*(angle>360); + + + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/rdradcp.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/rdradcp.m (revision 225) @@ -1,0 +1,863 @@ +function [adcp,cfg,ens]=rdradcp(name,varargin); +% RDRADCP Read (raw binary) RDI ADCP files, +% ADCP=RDRADCP(NAME) reads the raw binary RDI BB/Workhorse ADCP file NAME and +% puts all the relevant configuration and measured data into a data structure +% ADCP (which is self-explanatory). This program is designed for handling data +% recorded by moored instruments (primarily Workhorse-type but can also read +% Broadband) and then downloaded post-deployment. For vessel-mount data I +% usually make p-files (which integrate nav info and do coordinate transformations) +% and then use RDPADCP. +% +% This current version does have some handling of VMDAS and WINRIVER output +% files, but it is still 'beta'. +% +% [ADCP,CFG]=RDRADCP(...) returns configuration data in a +% separate data structure. +% +% Various options can be specified on input: +% [..]=RDRADCP(NAME,NUMAV) averages NUMAV ensembles together in the result. +% [..]=RDRADCP(NAME,NUMAV,NENS) reads only NENS ensembles (-1 for all). +% [..]=RDRADCP(NAME,NUMAV,[NFIRST NEND]) reads only the specified range +% of ensembles. This is useful if you want to get rid of bad data before/after +% the deployment period. +% +% Note - sometimes the ends of files are filled with garbage. In this case you may +% have to rerun things explicitly specifying how many records to read (or the +% last record to read). I don't handle bad data very well. +% +% - I don't read in absolutely every parameter stored in the binaries; +% just the ones that are 'most' useful. +% +% String parameter/option pairs can be added after these initial parameters: +% +% 'baseyear' : Base century for BB/v8WH firmware (default to 2000). +% +% 'despike' : [ 'no' | 'yes' | 3-element vector ] +% Controls ensemble averaging. With 'no' a simple mean is used +% (default). With 'yes' a mean is applied to all values that fall +% within a window around the median (giving some outlier rejection). +% This is useful for noisy data. Window sizes are [.3 .3 .3] m/s +% for [ horiz_vel vert_vel error_vel ] values. If you want to +% change these values, set 'despike' to the 3-element vector. +% +% R. Pawlowicz (rich@ocgy.ubc.ca) - 17/09/99 + +% R. Pawlowicz - 17/Oct/99 +% 5/july/00 - handled byte offsets (and mysterious 'extra" bytes) slightly better, Y2K +% 5/Oct/00 - bug fix - size of ens stayed 2 when NUMAV==1 due to initialization, +% hopefully this is now fixed. +% 10/Mar/02 - #bytes per record changes mysteriously, +% tried a more robust workaround. Guess that we have an extra +% 2 bytes if the record length is even? +% 28/Mar/02 - added more firmware-dependent changes to format; hopefully this +% works for everything now (put previous changes on firmer footing?) +% 30/Mar/02 - made cfg output more intuitive by decoding things. +% - An early version of WAVESMON and PARSE which split out this +% data from a wave recorder inserted an extra two bytes per record. +% I have removed the code to handle this but if you need it see line 509 +% 29/Nov/02 - A change in the bottom-track block for version 4.05 (very old!). +% 29/Jan/03 - Status block in v4.25 150khzBB two bytes short? +% 14/Oct/03 - Added code to at least 'ignore' WinRiver GPS blocks. +% 11/Nov/03 - VMDAS navigation block, added hooks to output +% navigation data. + +num_av=5; % Block filtering and decimation parameter (# ensembles to block together). +nens=-1; % Read all ensembles. +century=2000; % ADCP clock does not have century prior to firmware 16.05. +vels='no'; % Default to simple averaging + +lv=length(varargin); +if lv>=1 & ~isstr(varargin{1}), + num_av=varargin{1}; % Block filtering and decimation parameter (# ensembles to block together). + varargin(1)=[]; + lv=lv-1; + if lv>=1 & ~isstr(varargin{1}), + nens=varargin{1}; + varargin(1)=[]; + lv=lv-1; + end; +end; + +% Read optional args +while length(varargin)>0, + switch varargin{1}(1:3), + case 'bas', + century = varargin{2}; + case 'des', + if isstr(varargin{2}), + if strcmp(varargin{2},'no'), vels='no'; + else vels=[.3 .3 .3]; end; + else + vels=varargin{2}; + end; + otherwise, + error(['Unknown command line option ->' varargin{1}]); + end; + varargin([1 2])=[]; +end; + + + + +% Check file information first + +naminfo=dir(name); + +if isempty(naminfo), + fprintf('ERROR******* Can''t find file %s\n',name); + return; +end; + +fprintf('\nOpening file %s\n\n',name); +fd=fopen(name,'r','ieee-le'); + +% Read first ensemble to initialize parameters + +[ens,hdr,cfg]=rd_buffer(fd,-2); % Initialize and read first two records +fseek(fd,0,'bof'); % Rewind + +if (cfg.prog_ver<16.05 & cfg.prog_ver>5.999) | cfg.prog_ver<5.55, + fprintf('**************Assuming that the century begins year %d *********** \n\n',century); +else + century=0; % century included in clock. +end; + +dats=datenum(century+ens.rtc(1,:),ens.rtc(2,:),ens.rtc(3,:),ens.rtc(4,:),ens.rtc(5,:),ens.rtc(6,:)+ens.rtc(7,:)/100); +t_int=diff(dats); +fprintf('Record begins at %s\n',datestr(dats(1),0)); +fprintf('Ping interval appears to be %s\n',datestr(t_int,13)); + + +% Estimate number of records (since I don't feel like handling EOFs correctly, +% we just don't read that far!) + + +% Now, this is a puzzle - it appears that this is not necessary in +% a firmware v16.12 sent to me, and I can't find any example for +% which it *is* necessary so I'm not sure why its there. It could be +% a leftoever from dealing with the bad WAVESMON/PARSE problem (now +% fixed) that inserted extra bytes. +% ...So its out for now. +%if cfg.prog_ver>=16.05, extrabytes=2; else extrabytes=0; end; % Extra bytes +extrabytes=0; + +if length(nens)==1, + if nens==-1, + nens=fix(naminfo.bytes/(hdr.nbyte+2+extrabytes)); + fprintf('\nEstimating %d ensembles in this file\nReducing by a factor of %d\n',nens,num_av); + else + fprintf('\nReading %d ensembles in this file\nReducing by a factor of %d\n',nens,num_av); + end; +else + fprintf('\nReading ensembles %d-%d in this file\nReducing by a factor of %d\n',nens,num_av); + fseek(fd,(hdr.nbyte+2+extrabytes)*(nens(1)-1),'bof'); + nens=diff(nens)+1; +end; + +if num_av>1, + if isstr(vels), + fprintf('\n Simple mean used for ensemble averaging\n'); + else + fprintf('\n Averaging after outlier rejection with parameters [%f %f %f]\n',vels); + end; +end; + +% Number of records after averaging. + +n=fix(nens/num_av); + +% Structure to hold all ADCP data +% Note that I am not storing all the data contained in the raw binary file, merely +% things I think are useful. + +switch cfg.sourceprog, + case 'WINRIVER', + adcp=struct('name','adcp','config',cfg,'mtime',zeros(1,n),'number',zeros(1,n),'pitch',zeros(1,n),... + 'roll',zeros(1,n),'heading',zeros(1,n),'pitch_std',zeros(1,n),... + 'roll_std',zeros(1,n),'heading_std',zeros(1,n),'depth',zeros(1,n),... + 'temperature',zeros(1,n),'salinity',zeros(1,n),... + 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... + 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... + 'error_vel',zeros(cfg.n_cells,n),'corr',zeros(cfg.n_cells,4,n),... + 'status',zeros(cfg.n_cells,4,n),'intens',zeros(cfg.n_cells,4,n),... + 'bt_range',zeros(4,n),'bt_vel',zeros(4,n),... + 'nav_longitude',zeros(1,n),'nav_latitude',zeros(1,n)); + case 'VMDAS', + adcp=struct('name','adcp','config',cfg,'mtime',zeros(1,n),'number',zeros(1,n),'pitch',zeros(1,n),... + 'roll',zeros(1,n),'heading',zeros(1,n),'pitch_std',zeros(1,n),... + 'roll_std',zeros(1,n),'heading_std',zeros(1,n),'depth',zeros(1,n),... + 'temperature',zeros(1,n),'salinity',zeros(1,n),... + 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... + 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... + 'error_vel',zeros(cfg.n_cells,n),'corr',zeros(cfg.n_cells,4,n),... + 'status',zeros(cfg.n_cells,4,n),'intens',zeros(cfg.n_cells,4,n),... + 'bt_range',zeros(4,n),'bt_vel',zeros(4,n),... + 'nav_smtime',zeros(1,n),'nav_emtime',zeros(1,n),... + 'nav_slongitude',zeros(1,n),'nav_elongitude',zeros(1,n),... + 'nav_slatitude',zeros(1,n),'nav_elatitude',zeros(1,n)); + otherwise + adcp=struct('name','adcp','config',cfg,'mtime',zeros(1,n),'number',zeros(1,n),'pitch',zeros(1,n),... + 'roll',zeros(1,n),'heading',zeros(1,n),'pitch_std',zeros(1,n),... + 'roll_std',zeros(1,n),'heading_std',zeros(1,n),'depth',zeros(1,n),... + 'temperature',zeros(1,n),'salinity',zeros(1,n),... + 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... + 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... + 'error_vel',zeros(cfg.n_cells,n),'corr',zeros(cfg.n_cells,4,n),... + 'status',zeros(cfg.n_cells,4,n),'intens',zeros(cfg.n_cells,4,n),... + 'bt_range',zeros(4,n),'bt_vel',zeros(4,n)); +end; + + +% Calibration factors for backscatter data + +clear global ens +% Loop for all records +for k=1:n, + + % Gives display so you know something is going on... + + if rem(k,50)==0, fprintf('\n%d',k*num_av);end; + fprintf('.'); + + % Read an ensemble + + ens=rd_buffer(fd,num_av); + + + if ~isstruct(ens), % If aborting... + fprintf('Only %d records found..suggest re-running RDRADCP using this parameter\n',(k-1)*num_av); + fprintf('(If this message preceded by a POSSIBLE PROGRAM PROBLEM message, re-run using %d)\n',(k-1)*num_av-1); + break; + end; + + dats=datenum(century+ens.rtc(1,:),ens.rtc(2,:),ens.rtc(3,:),ens.rtc(4,:),ens.rtc(5,:),ens.rtc(6,:)+ens.rtc(7,:)/100); + adcp.mtime(k)=median(dats); + adcp.number(k) =ens.number(1); + adcp.heading(k) =mean(ens.heading); + adcp.pitch(k) =mean(ens.pitch); + adcp.roll(k) =mean(ens.roll); + adcp.heading_std(k) =mean(ens.heading_std); + adcp.pitch_std(k) =mean(ens.pitch_std); + adcp.roll_std(k) =mean(ens.roll_std); + adcp.depth(k) =mean(ens.depth); + adcp.temperature(k) =mean(ens.temperature); + adcp.salinity(k) =mean(ens.salinity); + adcp.pressure(k) =mean(ens.pressure); + adcp.pressure_std(k)=mean(ens.pressure_std); + + if isstr(vels), + adcp.east_vel(:,k) =nmean(ens.east_vel ,2); + adcp.north_vel(:,k) =nmean(ens.north_vel,2); + adcp.vert_vel(:,k) =nmean(ens.vert_vel ,2); + adcp.error_vel(:,k) =nmean(ens.error_vel,2); + else + adcp.east_vel(:,k) =nmedian(ens.east_vel ,vels(1),2); + adcp.north_vel(:,k) =nmedian(ens.north_vel,vels(1),2); + adcp.vert_vel(:,k) =nmedian(ens.vert_vel ,vels(2),2); + adcp.error_vel(:,k) =nmedian(ens.error_vel,vels(3),2); + end; + + adcp.corr(:,:,k) =nmean(ens.corr,3); % added correlation RKD 9/00 + adcp.status(:,:,k) =nmean(ens.status,3); + + adcp.intens(:,:,k) =nmean(ens.intens,3); + + adcp.bt_range(:,k) =nmean(ens.bt_range,2); + adcp.bt_vel(:,k) =nmean(ens.bt_vel,2); + + switch cfg.sourceprog, + case 'WINRIVER', + adcp.nav_longitude(k)=nmean(ens.slongitude); + adcp.nav_latitude(k)=nmean(ens.slatitude); + case 'VMDAS', + adcp.nav_smtime(k) =ens.smtime(1); + adcp.nav_emtime(k) =ens.emtime(end); + adcp.nav_slatitude(k)=ens.slatitude(1); + adcp.nav_elatitude(k)=ens.elatitude(end); + adcp.nav_slongitude(k)=ens.slongitude(1); + adcp.nav_elongitude(k)=ens.elongitude(end); + end; +end; + +fprintf('\n'); +fclose(fd); + + +%------------------------------------- +function hdr=rd_hdr(fd); +% Read config data + +cfgid=fread(fd,1,'uint16'); +if cfgid~=hex2dec('7F7F'), + error(['File ID is ' dec2hex(cfgid) ' not 7F7F - data corrupted or not a BB/WH raw file?']); +end; + +hdr=rd_hdrseg(fd); + +%------------------------------------- +function cfg=rd_fix(fd); +% Read config data + +cfgid=fread(fd,1,'uint16'); +if cfgid~=hex2dec('0000'), + warning(['Fixed header ID ' cfgid 'incorrect - data corrupted or not a BB/WH raw file?']); +end; + +cfg=rd_fixseg(fd); + + + +%-------------------------------------- +function [hdr,nbyte]=rd_hdrseg(fd); +% Reads a Header + +hdr.nbyte =fread(fd,1,'int16'); +fseek(fd,1,'cof'); +ndat=fread(fd,1,'int8'); +hdr.dat_offsets =fread(fd,ndat,'int16'); +nbyte=4+ndat*2; + +%------------------------------------- +function opt=getopt(val,varargin); +% Returns one of a list (0=first in varargin, etc.) +if val+1>length(varargin), + opt='unknown'; +else + opt=varargin{val+1}; +end; + +% +%------------------------------------- +function [cfg,nbyte]=rd_fixseg(fd); +% Reads the configuration data from the fixed leader + +%%disp(fread(fd,10,'uint8')) +%%fseek(fd,-10,'cof'); + +cfg.name='wh-adcp'; +cfg.sourceprog='instrument'; % default - depending on what data blocks are + % around we can modify this later in rd_buffer. +cfg.prog_ver =fread(fd,1,'uint8')+fread(fd,1,'uint8')/100; + +if fix(cfg.prog_ver)==4 | fix(cfg.prog_ver)==5, + cfg.name='bb-adcp'; +elseif fix(cfg.prog_ver)==8 | fix(cfg.prog_ver)==16, + cfg.name='wh-adcp'; +else + cfg.name='unrecognized firmware version' ; +end; + +config =fread(fd,2,'uint8'); % Coded stuff +cfg.config =[dec2base(config(2),2,8) '-' dec2base(config(1),2,8)]; + cfg.beam_angle =getopt(bitand(config(2),3),15,20,30); + cfg.beam_freq =getopt(bitand(config(1),7),75,150,300,600,1200,2400); + cfg.beam_pattern =getopt(bitand(config(1),8)==8,'concave','convex'); % 1=convex,0=concave + cfg.orientation =getopt(bitand(config(1),128)==128,'down','up'); % 1=up,0=down +cfg.simflag =getopt(fread(fd,1,'uint8'),'real','simulated'); % Flag for simulated data +fseek(fd,1,'cof'); +cfg.n_beams =fread(fd,1,'uint8'); +cfg.n_cells =fread(fd,1,'uint8'); +cfg.pings_per_ensemble=fread(fd,1,'uint16'); +cfg.cell_size =fread(fd,1,'uint16')*.01; % meters +cfg.blank =fread(fd,1,'uint16')*.01; % meters +cfg.prof_mode =fread(fd,1,'uint8'); % +cfg.corr_threshold =fread(fd,1,'uint8'); +cfg.n_codereps =fread(fd,1,'uint8'); +cfg.min_pgood =fread(fd,1,'uint8'); +cfg.evel_threshold =fread(fd,1,'uint16'); +cfg.time_between_ping_groups=sum(fread(fd,3,'uint8').*[60 1 .01]'); % seconds +coord_sys =fread(fd,1,'uint8'); % Lots of bit-mapped info + cfg.coord=dec2base(coord_sys,2,8); + cfg.coord_sys =getopt(bitand(bitshift(coord_sys,-3),3),'beam','instrument','ship','earth'); + cfg.use_pitchroll =getopt(bitand(coord_sys,4)==4,'no','yes'); + cfg.use_3beam =getopt(bitand(coord_sys,2)==2,'no','yes'); + cfg.bin_mapping =getopt(bitand(coord_sys,1)==1,'no','yes'); +cfg.xducer_misalign=fread(fd,1,'int16')*.01; % degrees +cfg.magnetic_var =fread(fd,1,'int16')*.01; % degrees +cfg.sensors_src =dec2base(fread(fd,1,'uint8'),2,8); +cfg.sensors_avail =dec2base(fread(fd,1,'uint8'),2,8); +cfg.bin1_dist =fread(fd,1,'uint16')*.01; % meters +cfg.xmit_pulse =fread(fd,1,'uint16')*.01; % meters +cfg.water_ref_cells=fread(fd,2,'uint8'); +cfg.fls_target_threshold =fread(fd,1,'uint8'); +fseek(fd,1,'cof'); +cfg.xmit_lag =fread(fd,1,'uint16')*.01; % meters +nbyte=40; + +if cfg.prog_ver>=8.14, % Added CPU serial number with v8.14 + cfg.serialnum =fread(fd,8,'uint8'); + nbyte=nbyte+8; +end; + +if cfg.prog_ver>=8.24, % Added 2 more bytes with v8.24 firmware + cfg.sysbandwidth =fread(fd,2,'uint8'); + nbyte=nbyte+2; +end; + +if cfg.prog_ver>=16.05, % Added 1 more bytes with v16.05 firmware + cfg.syspower =fread(fd,1,'uint8'); + nbyte=nbyte+1; +end; + +% It is useful to have this precomputed. + +cfg.ranges=cfg.bin1_dist+[0:cfg.n_cells-1]'*cfg.cell_size; +if cfg.orientation==1, cfg.ranges=-cfg.ranges; end + + +%----------------------------- +function [ens,hdr,cfg]=rd_buffer(fd,num_av); + +% To save it being re-initialized every time. +global ens hdr + +% A fudge to try and read files not handled quite right. +global FIXOFFSET SOURCE + +% If num_av<0 we are reading only 1 element and initializing +if num_av<0 | isempty(ens), + FIXOFFSET=0; + SOURCE=0; % 0=instrument, 1=VMDAS, 2=WINRIVER + n=abs(num_av); + pos=ftell(fd); + hdr=rd_hdr(fd); + cfg=rd_fix(fd); + fseek(fd,pos,'bof'); + clear global ens + global ens + + ens=struct('number',zeros(1,n),'rtc',zeros(7,n),'BIT',zeros(1,n),'ssp',zeros(1,n),'depth',zeros(1,n),'pitch',zeros(1,n),... + 'roll',zeros(1,n),'heading',zeros(1,n),'temperature',zeros(1,n),'salinity',zeros(1,n),... + 'mpt',zeros(1,n),'heading_std',zeros(1,n),'pitch_std',zeros(1,n),... + 'roll_std',zeros(1,n),'adc',zeros(8,n),'error_status_wd',zeros(1,n),... + 'pressure',zeros(1,n),'pressure_std',zeros(1,n),... + 'east_vel',zeros(cfg.n_cells,n),'north_vel',zeros(cfg.n_cells,n),'vert_vel',zeros(cfg.n_cells,n),... + 'error_vel',zeros(cfg.n_cells,n),'intens',zeros(cfg.n_cells,4,n),'percent',zeros(cfg.n_cells,4,n),... + 'corr',zeros(cfg.n_cells,4,n),'status',zeros(cfg.n_cells,4,n),'bt_range',zeros(4,n),'bt_vel',zeros(4,n),... + 'smtime',zeros(1,n),'emtime',zeros(1,n),'slatitude',zeros(1,n),... + 'slongitude',zeros(1,n),'elatitude',zeros(1,n),'elongitude',zeros(1,n),... + 'flags',zeros(1,n)); + num_av=abs(num_av); +end; + +k=0; +while k' id1]); + end; + startpos=ftell(fd)-2; % Starting position. + + + % Read the # data types. + [hdr,nbyte]=rd_hdrseg(fd); + byte_offset=nbyte+2; +%%disp(length(hdr.dat_offsets)) + % Read all the data types. + for n=1:length(hdr.dat_offsets), + + id=fread(fd,1,'uint16'); +%% fprintf('ID=%s\n',dec2hex(id,4)); + + % handle all the various segments of data. Note that since I read the IDs as a two + % byte number in little-endian order the high and low bytes are exchanged compared to + % the values given in the manual. + % + + switch dec2hex(id,4), + case '0000', % Fixed leader + [cfg,nbyte]=rd_fixseg(fd); + nbyte=nbyte+2; + + case '0080' % Variable Leader + k=k+1; + ens.number(k) =fread(fd,1,'uint16'); + ens.rtc(:,k) =fread(fd,7,'uint8'); + ens.number(k) =ens.number(k)+65536*fread(fd,1,'uint8'); + ens.BIT(k) =fread(fd,1,'uint16'); + ens.ssp(k) =fread(fd,1,'uint16'); + ens.depth(k) =fread(fd,1,'uint16')*.1; % meters + ens.heading(k) =fread(fd,1,'uint16')*.01; % degrees + ens.pitch(k) =fread(fd,1,'int16')*.01; % degrees + ens.roll(k) =fread(fd,1,'int16')*.01; % degrees + ens.salinity(k) =fread(fd,1,'int16'); % PSU + ens.temperature(k) =fread(fd,1,'int16')*.01; % Deg C + ens.mpt(k) =sum(fread(fd,3,'uint8').*[60 1 .01]'); % seconds + ens.heading_std(k) =fread(fd,1,'uint8'); % degrees + ens.pitch_std(k) =fread(fd,1,'int8')*.1; % degrees + ens.roll_std(k) =fread(fd,1,'int8')*.1; % degrees + ens.adc(:,k) =fread(fd,8,'uint8'); + nbyte=2+40; + + if strcmp(cfg.name,'bb-adcp'), + + if cfg.prog_ver>=5.55, + fseek(fd,15,'cof'); % 14 zeros and one byte for number WM4 bytes + cent=fread(fd,1,'uint8'); % possibly also for 5.55-5.58 but + ens.rtc(:,k)=fread(fd,7,'uint8'); % I have no data to test. + ens.rtc(1,k)=ens.rtc(1,k)+cent*100; + nbyte=nbyte+15+8; + end; + + elseif strcmp(cfg.name,'wh-adcp'), % for WH versions. + + ens.error_status_wd(k)=fread(fd,1,'uint32'); + nbyte=nbyte+4;; + + if cfg.prog_ver>=8.13, % Added pressure sensor stuff in 8.13 + fseek(fd,2,'cof'); + ens.pressure(k) =fread(fd,1,'uint32'); + ens.pressure_std(k) =fread(fd,1,'uint32'); + nbyte=nbyte+10; + end; + + if cfg.prog_ver>8.24, % Spare byte added 8.24 + fseek(fd,1,'cof'); + nbyte=nbyte+1; + end; + + if cfg.prog_ver>=16.05, % Added more fields with century in clock 16.05 + cent=fread(fd,1,'uint8'); + ens.rtc(:,k)=fread(fd,7,'uint8'); + ens.rtc(1,k)=ens.rtc(1,k)+cent*100; + nbyte=nbyte+8; + end; + end; + + case '0100', % Velocities + vels=fread(fd,[4 cfg.n_cells],'int16')'*.001; % m/s + ens.east_vel(:,k) =vels(:,1); + ens.north_vel(:,k)=vels(:,2); + ens.vert_vel(:,k) =vels(:,3); + ens.error_vel(:,k)=vels(:,4); + nbyte=2+4*cfg.n_cells*2; + + case '0200', % Correlations + ens.corr(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; + nbyte=2+4*cfg.n_cells; + + case '0300', % Echo Intensities + ens.intens(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; + nbyte=2+4*cfg.n_cells; + + case '0400', % Percent good + ens.percent(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; + nbyte=2+4*cfg.n_cells; + + case '0500', % Status + % Note in one case with a 4.25 firmware SC-BB, it seems like + % this block was actually two bytes short! + ens.status(:,:,k) =fread(fd,[4 cfg.n_cells],'uint8')'; + nbyte=2+4*cfg.n_cells; + + case '0600', % Bottom track + % In WINRIVER GPS data is tucked into here in odd ways, as long + % as GPS is enabled. + if SOURCE==2, + fseek(fd,2,'cof'); + long1=fread(fd,1,'uint16'); + fseek(fd,6,'cof'); + cfac=180/2^31; + ens.slatitude(k) =fread(fd,1,'int32')*cfac; + else + fseek(fd,14,'cof'); % Skip over a bunch of stuff + end; + ens.bt_range(:,k)=fread(fd,4,'uint16')*.01; % + ens.bt_vel(:,k) =fread(fd,4,'int16'); + if SOURCE==2, + fseek(fd,12+2,'cof'); + ens.slongitude(k)=(long1+65536*fread(fd,1,'uint16'))*cfac; + if ens.slongitude(k)>180, ens.slongitude(k)=ens.slongitude(k)-360; end; + fseek(fd,71-33-16,'cof'); + nbyte=2+68; + else + fseek(fd,71-33,'cof'); + nbyte=2+68; + end; + if cfg.prog_ver>=5.3, % Version 4.05 firmware seems to be missing these last 11 bytes. + fseek(fd,78-71,'cof'); + ens.bt_range(:,k)=ens.bt_range(:,k)+fread(fd,4,'uint8')*655.36; + nbyte=nbyte+11; + if cfg.prog_ver>=16, % RDI documentation claims these extra bytes were added in v 8.17 + fseek(fd,4,'cof'); % but they don't appear in my 8.33 data. + nbyte=nbyte+4; + end; + end; + +% The raw files produced by VMDAS contain a binary navigation data +% block. + + case '2000', % Something from VMDAS. + cfg.sourceprog='VMDAS'; + SOURCE=1; + utim =fread(fd,4,'uint8'); + mtime =datenum(utim(3)+utim(4)*256,utim(2),utim(1)); + ens.smtime(k) =mtime+fread(fd,1,'uint32')/8640000; + fseek(fd,4,'cof'); + cfac=180/2^31; + ens.slatitude(k) =fread(fd,1,'int32')*cfac; + ens.slongitude(k) =fread(fd,1,'int32')*cfac; + ens.emtime(k) =mtime+fread(fd,1,'uint32')/8640000; + ens.elatitude(k) =fread(fd,1,'int32')*cfac; + ens.elongitude(k) =fread(fd,1,'int32')*cfac; + fseek(fd,12,'cof'); + ens.flags(k) =fread(fd,1,'uint16'); + fseek(fd,30,'cof'); + nbyte=2+76; + +% The following blocks come from WINRIVER files, they aparently contain +% the raw NMEA data received from a serial port. +% +% Note that for WINRIVER files somewhat decoded data is also available +% tucked into the bottom track block. + + case '2100', % $xxDBT (Winriver addition) 38 + cfg.sourceprog='WINRIVER'; + SOURCE=2; + str=fread(fd,38,'uchar')'; + nbyte=2+38; + + case '2101', % $xxGGA (Winriver addition) 94 in maanual but 97 seems to work + cfg.sourceprog='WINRIVER'; + SOURCE=2; + str=fread(fd,97,'uchar')'; + nbyte=2+97; + % disp(setstr(str(1:80))); + + case '2102', % $xxVTG (Winriver addition) 45 + cfg.sourceprog='WINRIVER'; + SOURCE=2; + str=fread(fd,45,'uchar')'; + nbyte=2+45; +% disp(setstr(str)); + + case '2103', % $xxGSA (Winriver addition) 60 + cfg.sourceprog='WINRIVER'; + SOURCE=2; + str=fread(fd,60,'uchar')'; +% disp(setstr(str)); + nbyte=2+60; + + case '2104', %xxHDT or HDG (Winriver addition) 38 + cfg.sourceprog='WINRIVER'; + SOURCE=2; + str=fread(fd,38,'uchar')'; +% disp(setstr(str)); + nbyte=2+38; + + + + case '0701', % Number of good pings + fseek(fd,4*cfg.n_cells,'cof'); + nbyte=2+4*cfg.n_cells; + + case '0702', % Sum of squared velocities + fseek(fd,4*cfg.n_cells,'cof'); + nbyte=2+4*cfg.n_cells; + + case '0703', % Sum of velocities + fseek(fd,4*cfg.n_cells,'cof'); + nbyte=2+4*cfg.n_cells; + +% These blocks were implemented for 5-beam systems + + case '0A00', % Beam 5 velocity (not implemented) + fseek(fd,cfg.n_cells,'cof'); + nbyte=2+cfg.n_cells; + + case '0301', % Beam 5 Number of good pings (not implemented) + fseek(fd,cfg.n_cells,'cof'); + nbyte=2+cfg.n_cells; + + case '0302', % Beam 5 Sum of squared velocities (not implemented) + fseek(fd,cfg.n_cells,'cof'); + nbyte=2+cfg.n_cells; + + case '0303', % Beam 5 Sum of velocities (not implemented) + fseek(fd,cfg.n_cells,'cof'); + nbyte=2+cfg.n_cells; + + case '020C', % Ambient sound profile (not implemented) + fseek(fd,4,'cof'); + nbyte=2+4; + + otherwise, + + fprintf('Unrecognized ID code: %s\n',dec2hex(id,4)); + nbyte=2; + %% ens=-1; + %% return; + + + end; + + % here I adjust the number of bytes so I am sure to begin + % reading at the next valid offset. If everything is working right I shouldn't have + % to do this but every so often firware changes result in some differences. + + %%fprintf('#bytes is %d, original offset is %d\n',nbyte,byte_offset); + byte_offset=byte_offset+nbyte; + + if n=16.05, + % fseek(fd,2,'cof'); + %end; + +end; + +% Blank out stuff bigger than error velocity +% big_err=abs(ens.error_vel)>.2; +big_err=0; + +% Blank out invalid data +ens.east_vel(ens.east_vel==-32.768 | big_err)=NaN; +ens.north_vel(ens.north_vel==-32.768 | big_err)=NaN; +ens.vert_vel(ens.vert_vel==-32.768 | big_err)=NaN; +ens.error_vel(ens.error_vel==-32.768 | big_err)=NaN; + + + + +%-------------------------------------- +function y=nmedian(x,window,dim); +% Copied from median but with handling of NaN different. + +if nargin==2, + dim = min(find(size(x)~=1)); + if isempty(dim), dim = 1; end +end + +siz = [size(x) ones(1,dim-ndims(x))]; +n = size(x,dim); + +% Permute and reshape so that DIM becomes the row dimension of a 2-D array +perm = [dim:max(length(size(x)),dim) 1:dim-1]; +x = reshape(permute(x,perm),n,prod(siz)/n); + +% Sort along first dimension +x = sort(x,1); +[n1,n2]=size(x); + +if n1==1, + y=x; +else + if n2==1, + kk=sum(finite(x),1); + if kk>0, + x1=x(max(fix(kk/2),1)); + x2=x(max(ceil(kk/2),1)); + x(abs(x-(x1+x2)/2)>window)=NaN; + end; + x = sort(x,1); + kk=sum(finite(x),1); + x(isnan(x))=0; + y=NaN; + if kk>0, + y=sum(x)/kk; + end; + else + kk=sum(finite(x),1); + ll=kkwindow)=NaN; + x = sort(x,1); + kk=sum(finite(x),1); + x(isnan(x))=0; + y=NaN+ones(1,n2); + if any(kk), + y(kk>0)=sum(x(:,kk>0))./kk(kk>0); + end; + end; +end; + +% Permute and reshape back +siz(dim) = 1; +y = ipermute(reshape(y,siz(perm)),perm); + +%-------------------------------------- +function y=nmean(x,dim); +% R_NMEAN Computes the mean of matrix ignoring NaN +% values +% R_NMEAN(X,DIM) takes the mean along the dimension DIM of X. +% + +kk=finite(x); +x(~kk)=0; + +if nargin==1, + % Determine which dimension SUM will use + dim = min(find(size(x)~=1)); + if isempty(dim), dim = 1; end +end; + +if dim>length(size(x)), + y=x; % For matlab 5.0 only!!! Later versions have a fixed 'sum' +else + ndat=sum(kk,dim); + indat=ndat==0; + ndat(indat)=1; % If there are no good data then it doesn't matter what + % we average by - and this avoid div-by-zero warnings. + + y = sum(x,dim)./ndat; + y(indat)=NaN; +end; + + + + + + + + + + + + + + + + + + + + + + + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/specmultiplot_compare.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/specmultiplot_compare.m (revision 225) @@ -1,0 +1,151 @@ +function [Winfo]=specmultiplot_compare(dateinfo1,dateinfo2,timestep); +%where dateinfo1 and 2 are the strings of the first and last date extension +%of the pressure,range,etc files and timestep is the time in hours between +%each burst + +%This function takes the pressure, range, orbit and sysinfo files created +%in python and outputs a Winfo data structure with the sig wave height, +%peak period, direction of peak period and dominant dir. It also generates +%polar plots and 2d freq and directional plots of a variety of different +%estimation methods, resolutions and the wavesmon output. + + +%first set up the time vector going from dateinfo1 to dateinfo2 +Winfo.time=[]; + +date1=datevec(dateinfo1, 'yymmddHHMM'); +date2=datevec(dateinfo2,'yymmddHHMM'); + +if date1 == date2 + Winfo.time=[datenum(date1)]; +else + Winfo.time=[datenum(date1)]; + newdate=date1; + while datenum(newdate) ~= datenum(date2) + newdate=newdate+[0 0 0 timestep 0 0]; + Winfo.time=[horzcat(Winfo.time,datenum(newdate))]; + end +end + + +%set up time, which is Winfo.time as date str in the yymmddHHMM format +time=datestr(Winfo.time, 'yymmddHHMM'); + +%set up data structure for wave info +Winfo.setup={'EMEP UVW','IMLM UVW','EMEP range','IMLM range','EMEP radial','IMLM radial','wavesmon'}'; +Winfo.hsig=[]; +Winfo.hconf=[]; +Winfo.peakP=[]; +Winfo.dirP=[]; +Winfo.Ddir=[]; +Winfo.Spectrum.EMEPuvw=[]; +Winfo.Spectrum.IMLMuvw=[]; +Winfo.Spectrum.EMEPrange=[]; +Winfo.Spectrum.IMLMrange=[]; +Winfo.Spectrum.EMEPradial=[]; +Winfo.Spectrum.IMLMradial=[]; +Winfo.Spectrum.wavesmon=[]; + +%Load the data and run the script +for i=1:length(time(:,1)) + dateinfo=time(i,:); + + pressure=strcat('pressure_',dateinfo,'.txt'); + range=strcat('range_',dateinfo,'.txt'); + orbit=strcat('orbit_',dateinfo,'.txt'); + sysinfo=strcat('sysinfo_',dateinfo,'.txt'); + spec=strcat('DSpec',dateinfo,'.txt'); + + pressure=load(pressure); + range=load(range); + orbit=load(orbit); + sysinfo=load(sysinfo); + spec=load(spec); + + %set up data with uvw and pressure, freq at 0.01 and dir at 2 + [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,1); + + %run diwasp to generate this spectrum + [E_uvw_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now for IMLM + EP.method='IMLM'; + EP.iter=3; + [I_uvw_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %set up data with ranges, freq and dir at default + [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,2); + + % run diwasp to generate this spectrum with EMEP + [E_range_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now with IMLM + EP.method='IMLM'; + EP.iter=3; + [I_range_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %set up data with radial velocities, freq and dir at default + [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,3); + + % run diwasp to generate this spectrum with EMEP + [E_radial_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now with IMLM + EP.method='IMLM'; + EP.iter=3; + [I_radial_F01_D2, EPout]=dirspec(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %Use waveplot to plot the polar, freq and dir plots of the spectra + + [E_UVW_WI,I_UVW_WI,E_range_WI,I_range_WI,wmon_WI,fig1,fig2]=waveplot(E_uvw_F01_D2,I_uvw_F01_D2,E_range_F01_D2,I_range_F01_D2,spec,sysinfo); + + saveas(fig1,['polar1_' dateinfo '.fig']); + saveas(fig2,['dirfreq1_' dateinfo '.fig']); + + [E_radial_WI,I_radial_WI,fig5,fig6]=radialwaveplot(E_radial_F01_D2,I_radial_F01_D2,spec,sysinfo); + + saveas(fig5,['polar3_' dateinfo '.fig']); + saveas(fig6,['dirfreq3_' dateinfo '.fig']); + + close all; + + %Make sure wavesmon spectrum is formatted right before outputting, change to m^2/Hz/deg + wmon.S=spec/(360*1000*1000); + + %Fill up the Winfo data structure + + hsig=[vertcat(E_UVW_WI.hsig,I_UVW_WI.hsig,E_range_WI.hsig,I_range_WI.hsig,E_radial_WI.hsig,I_radial_WI.hsig,wmon_WI.hsig)]; + hconf=[vertcat(E_UVW_WI.hconf,I_UVW_WI.hconf,E_range_WI.hconf,I_range_WI.hconf,E_radial_WI.hconf,I_radial_WI.hconf,[NaN NaN])]; + peakP=[vertcat(E_UVW_WI.tp,I_UVW_WI.tp,E_range_WI.tp,I_range_WI.tp,E_radial_WI.tp,I_radial_WI.tp,wmon_WI.tp)]; + dirP=[vertcat(E_UVW_WI.dtp,I_UVW_WI.dtp,E_range_WI.dtp,I_range_WI.dtp,E_radial_WI.dtp,I_radial_WI.dtp,wmon_WI.dtp)]; + Ddir=[vertcat(E_UVW_WI.dp,I_UVW_WI.dp,E_range_WI.dp,I_range_WI.dp,E_radial_WI.dp,I_radial_WI.dp,wmon_WI.dp)]; + + + Winfo.hsig=[horzcat(Winfo.hsig,hsig)]; + Winfo.hconf=[horzcat(Winfo.hconf,hconf)]; + Winfo.peakP=[horzcat(Winfo.peakP,peakP)]; + Winfo.dirP=[horzcat(Winfo.dirP,dirP)]; + Winfo.Ddir=[horzcat(Winfo.Ddir,Ddir)]; + Winfo.Spectrum.EMEPuvw=[cat(3,Winfo.Spectrum.EMEPuvw,E_uvw_F01_D2.S)]; + Winfo.Spectrum.IMLMuvw=[cat(3,Winfo.Spectrum.IMLMuvw,I_uvw_F01_D2.S)]; + Winfo.Spectrum.EMEPrange=[cat(3,Winfo.Spectrum.EMEPrange,E_range_F01_D2.S)]; + Winfo.Spectrum.IMLMrange=[cat(3,Winfo.Spectrum.IMLMrange,I_range_F01_D2.S)]; + Winfo.Spectrum.EMEPradial=[cat(3,Winfo.Spectrum.EMEPradial,E_radial_F01_D2.S)]; + Winfo.Spectrum.IMLMradial=[cat(3,Winfo.Spectrum.IMLMradial,I_radial_F01_D2.S)]; + Winfo.Spectrum.wavesmon=[cat(3,Winfo.Spectrum.wavesmon,wmon.S)]; + +end + +%now create the time series plots of the wave info +[fig_sigh,fig_pp,fig_dp,fig_dd]=Winfo_plot(Winfo); + +saveas(fig_sigh,['sigh_' dateinfo '.fig']); +saveas(fig_pp,['peakp_' dateinfo '.fig']); +saveas(fig_dp,['dirpeak_' dateinfo '.fig']); +saveas(fig_dd,['domdir_' dateinfo '.fig']); + +close all; + + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/specmultiplot_wfreqdirs.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/specmultiplot_wfreqdirs.m (revision 225) @@ -1,0 +1,148 @@ +function [Winfo]=specmultiplot(dateinfo1,dateinfo2,timestep); +%where dateinfo1 and 2 are the strings of the first and last date extension +%of the pressure,range,etc files and timestep is the time in hours between +%each burst + +%This function takes the pressure, range, orbit and sysinfo files created +%in python and outputs a Winfo data structure with the sig wave height, +%peak period, direction of peak period and dominant dir. It also generates +%polar plots and 2d freq and directional plots of a variety of different +%estimation methods, resolutions and the wavesmon output. + + +%first set up the time vector going from dateinfo1 to dateinfo2 +Winfo.time=[]; + +date1=datevec(dateinfo1, 'yymmddHHMM'); +date2=datevec(dateinfo2,'yymmddHHMM'); + +if date1 == date2 + Winfo.time=[datenum(date1)]; +else + Winfo.time=[datenum(date1)]; + newdate=date1; + while datenum(newdate) ~= datenum(date2) + newdate=newdate+[0 0 0 timestep 0 0]; + Winfo.time=[horzcat(Winfo.time,datenum(newdate))]; + end +end + + +%set up time, which is Winfo.time as date str in the yymmddHHMM format +time=datestr(Winfo.time, 'yymmddHHMM'); + +%set up data structure for wave info +Winfo.setup={'EMEP UVW','EMEP UVW F005','EMEP UVW D01','IMLM UVW','IMLM UVW F005','IMLM UVW D01','EMEP range','IMLM range','EMEP radial','IMLM radial','wavesmon'}'; +Winfo.hsig=[]; +Winfo.peakP=[]; +Winfo.dirP=[]; +Winfo.Ddir=[]; + +%Load the data and run the script +for i=1:length(time(:,1)) + dateinfo=time(i,:); + + pressure=strcat('pressure_',dateinfo,'.txt'); + range=strcat('range_',dateinfo,'.txt'); + orbit=strcat('orbit_',dateinfo,'.txt'); + sysinfo=strcat('sysinfo_',dateinfo,'.txt'); + spec=strcat('DSpec',dateinfo,'.txt'); + + pressure=load(pressure); + range=load(range); + orbit=load(orbit); + sysinfo=load(sysinfo); + spec=load(spec); + + %set up data with uvw and pressure, freq at 0.01 and dir at 2 + [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,1); + + %run diwasp to generate this spectrum + [E_uvw_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now for IMLM + EP.method='IMLM'; + EP.iter=3; + [I_uvw_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now for IMLM with increased Freq resolution + SM.freqs=[0.005:0.005:0.4]; + [I_uvw_F005_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now for IMLM with increased Dir resolution + SM.freqs=[0.01:0.01:0.4]; + SM.dirs=[-180:1:180]; + [I_uvw_F01_D1, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now for EMEP with increased Freq res and then Dir res + EP.method='EMEP'; + EP.iter=100; + SM.freqs=[0.005:0.005:0.4]; + SM.dirs=[-180:2:180]; + [E_uvw_F005_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + SM.freqs=[0.01:0.01:0.4]; + SM.dirs=[-180:1:180]; + [E_uvw_F01_D1, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + + %set up data with ranges, freq and dir at default + [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,2); + + % run diwasp to generate this spectrum with EMEP + [E_range_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now with IMLM + EP.method='IMLM'; + EP.iter=3; + [I_range_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %set up data with radial velocities, freq and dir at default + [ID,SM,EP]=radialtouvw(pressure,range,orbit,sysinfo,3); + + % run diwasp to generate this spectrum with EMEP + [E_radial_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %now with IMLM + EP.method='IMLM'; + EP.iter=3; + [I_radial_F01_D2, EPout]=dirspectest(ID,SM,EP,{'PLOTTYPE',0,'MESSAGE',0}); + + %Use waveplot to plot the polar, freq and dir plots of the spectra + + [E_UVW_WI,I_UVW_WI,E_range_WI,I_range_WI,wmon_WI,fig1,fig2]=waveplot(E_uvw_F01_D2,I_uvw_F01_D2,E_range_F01_D2,I_range_F01_D2,spec,sysinfo); + + saveas(fig1,['polar1_' dateinfo '.fig']); + saveas(fig2,['dirfreq1_' dateinfo '.fig']); + + [E_UVW_F_WI,E_UVW_D_WI,I_UVW_F_WI,I_UVW_D_WI,fig3,fig4]=waveplot2(E_uvw_F01_D2,I_uvw_F01_D2,E_uvw_F005_D2,I_uvw_F005_D2,E_uvw_F01_D1,I_uvw_F01_D1,sysinfo); + + saveas(fig3,['polar2_' dateinfo '.fig']); + saveas(fig4,['dirfreq2_' dateinfo '.fig']); + + [E_radial_WI,I_radial_WI,fig5,fig6]=radialwaveplot(E_radial_F01_D2,I_radial_F01_D2,spec,sysinfo); + + saveas(fig5,['polar3_' dateinfo '.fig']); + saveas(fig6,['dirfreq3_' dateinfo '.fig']); + + close all; + + %Fill up the Winfo data structure + + hsig=[vertcat(E_UVW_WI.hsig,E_UVW_F_WI.hsig,E_UVW_D_WI.hsig,I_UVW_WI.hsig,I_UVW_F_WI.hsig,I_UVW_D_WI.hsig,E_range_WI.hsig,I_range_WI.hsig,E_radial_WI.hsig,I_radial_WI.hsig,wmon_WI.hsig)]; + peakP=[vertcat(E_UVW_WI.tp,E_UVW_F_WI.tp,E_UVW_D_WI.tp,I_UVW_WI.tp,I_UVW_F_WI.tp,I_UVW_D_WI.tp,E_range_WI.tp,I_range_WI.tp,E_radial_WI.tp,I_radial_WI.tp,wmon_WI.tp)]; + dirP=[vertcat(E_UVW_WI.dtp,E_UVW_F_WI.dtp,E_UVW_D_WI.dtp,I_UVW_WI.dtp,I_UVW_F_WI.dtp,I_UVW_D_WI.dtp,E_range_WI.dtp,I_range_WI.dtp,E_radial_WI.dtp,I_radial_WI.dtp,wmon_WI.dtp)]; + Ddir=[vertcat(E_UVW_WI.dp,E_UVW_F_WI.dp,E_UVW_D_WI.dp,I_UVW_WI.dp,I_UVW_F_WI.dp,I_UVW_D_WI.dp,E_range_WI.dp,I_range_WI.dp,E_radial_WI.dp,I_radial_WI.dp,wmon_WI.dp)]; + + Winfo.hsig=[horzcat(Winfo.hsig,hsig)]; + Winfo.peakP=[horzcat(Winfo.peakP,peakP)]; + Winfo.dirP=[horzcat(Winfo.dirP,dirP)]; + Winfo.Ddir=[horzcat(Winfo.Ddir,Ddir)]; + +end + +% change Winfo.time back to a matlab datenum + +%Winfo.time=datenum(Winfo.time); + + Index: DPWavesProc/trunk/DPWavesProc/test_code/test_code_readme.txt =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/test_code_readme.txt (revision 225) @@ -1,0 +1,5 @@ +This folder contains random code used to test DPWavesProc, and for comparing the DPWavesProc output with Wavesmon and Nortek Quickwave. This code is for test work ONLY and should not be included in any realease. + +Greg Dusek +Marine Sciences +UNC CH Index: DPWavesProc/trunk/DPWavesProc/test_code/waveplot2.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/waveplot2.m (revision 225) @@ -1,0 +1,310 @@ +function [E_UVW_F_WI,E_UVW_D_WI,I_UVW_F_WI,I_UVW_D_WI,fig3,fig4]=waveplot2(EMEP,IMLM,freqE,freqI,dirE,dirI,sysinfo) + +%make sure to load the EMEP, IMLM and wavesmon samples +%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') +%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') + +%what is the magnetic variation to nearest degree +magvar=10; + +%what is the start angle +heading=sysinfo(18,:); +heading=heading/100; +sangle=heading+magvar; + +%what is the frequency and dir resolution for those generated in DIWASP +freqres=0.01; +freqresH=0.005; +freqs=[0.01:0.01:.4]; +freqsH=[0.005:0.005:0.4]; +dirres=2; +dirresH=1; +dirs=[-180:2:180]; +dirsH=[-180:1:180]; + +%set up the directions +adj_angle=90-sangle+360+180; + +% plot the spectrum generated through DIWASP +scrsz = get(0,'ScreenSize'); +fig3=figure('Position',[scrsz]); +subplot(2,3,1); +subplotspec(EMEP,4); +title('EMEP UVW'); + +subplot(2,3,2); +subplotspec(freqE,4); +title('EMEP UVW, freq = 0.005'); + +subplot(2,3,3); +subplotspec(dirE,4); +title('EMEP UVW, dir res = 1'); + +subplot(2,3,4); +subplotspec(IMLM,4); +title('IMLM UVW'); + +subplot(2,3,5); +subplotspec(freqI,4); +title('IMLM UVW, freq = 0.005'); + +subplot(2,3,6); +subplotspec(dirI,4); +title('IMLM UVW, dir res = 1'); + +%calculate just the dir energy spectrum on a single graph + +EMEPdir=sum(EMEP.S)*freqres; +IMLMdir=sum(real(IMLM.S))*freqres; +freqEdir=sum(freqE.S)*freqresH; +dirEdir=sum(dirE.S)*freqres; +freqIdir=sum(real(freqI.S))*freqresH; +dirIdir=sum(real(dirI.S))*freqres; + +%calculate just the frequency energy spectrum +EMEPfreq=sum(EMEP.S')*dirres; +IMLMfreq=sum(real(IMLM.S)')*dirres; +freqEfreq=sum(freqE.S')*dirres; +dirEfreq=sum(dirE.S')*dirresH; +freqIfreq=sum(real(freqI.S)')*dirres; +dirIfreq=sum(real(dirI.S)')*dirresH; + +%plot the directional energy spectrum +fig4=figure('Position',[scrsz]); +subplot(1,2,1); +plot(dirs,EMEPdir,'b'); +hold on +plot(dirs,freqEdir,'r'); +plot(dirsH,dirEdir,'g'); +axis(axis); +plot(dirs,IMLMdir,'c'); +plot(dirs,freqIdir,'m'); +plot(dirsH,dirIdir,'k'); + + +legend('EMEP uvw','EMEP uvw freq=0.005','EMEP uvw dir=1','IMLM uvw','IMLM uvw freq=0.005','IMLM uvw dir=1','location','best'); +title('directional wave spectrum integrated over frequency'); +xlabel('axis angle (degrees true)'); +ylabel('m^2 / hz'); + +%plot the frequency energy spectrum +subplot(1,2,2); +plot(freqs,EMEPfreq,'b'); +hold on +plot(freqsH,freqEfreq,'r'); +plot(freqs,dirEfreq,'g'); +plot(freqs,IMLMfreq,'c'); +plot(freqsH,freqIfreq,'m'); +plot(freqs,dirIfreq,'k'); +legend('EMEP uvw','EMEP uvw freq=0.005','EMEP uvw dir=1','IMLM uvw','IMLM uvw freq=0.005','IMLM uvw dir=1','location','best'); +title('directional wave spectrum integrated over direction'); +xlabel('frequency in Hz'); +ylabel('m^2 / deg'); + +% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ + +%For EMEP uvw + +%calculate the 0,1,2 moments +m0=sum(EMEPfreq*freqres); +m1=sum(freqs.*EMEPfreq*freqres); +m2=sum((freqs.^2).*EMEPfreq*freqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(EMEPfreq); +Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(EMEP.S(I,:))); +DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(EMEPdir); +Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP uvw']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, EMEP.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, EMEP.xaxisdir))]); +disp([' ']); + +% For IMLM uvw + +%calculate the 0,1,2 moments +m0=sum(IMLMfreq*freqres); +m1=sum(freqs.*IMLMfreq*freqres); +m2=sum((freqs.^2).*IMLMfreq*freqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(IMLMfreq); +Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(IMLM.S(I,:))); +DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(IMLMdir); +Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM uvw']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, IMLM.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, IMLM.xaxisdir))]); +disp([' ']); + +% for EMEP freq=0.005 + +%calculate the 0,1,2 moments +m0=sum(freqEfreq*freqresH); +m1=sum(freqsH.*freqEfreq*freqresH); +m2=sum((freqsH.^2).*freqEfreq*freqresH); +% Calculate the Sig wave height +E_UVW_F_Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(freqEfreq); +E_UVW_F_Tp=1/(freqsH(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(freqE.S(I,:))); +E_UVW_F_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(freqEdir); +E_UVW_F_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP UVW freq=0.005']); +disp(['SigH (meters): ' num2str(E_UVW_F_Hsig)]); +disp(['peak period (seconds): ' num2str(E_UVW_F_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(E_UVW_F_DTp, freqE.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(E_UVW_F_Dp, freqE.xaxisdir))]); +disp([' ']); + +E_UVW_F_WI.hsig=E_UVW_F_Hsig; +E_UVW_F_WI.tp=E_UVW_F_Tp; +E_UVW_F_WI.dtp=compangle(E_UVW_F_DTp, freqE.xaxisdir); +E_UVW_F_WI.dp=compangle(E_UVW_F_Dp, freqE.xaxisdir); + +%for EMEP uvw dir=1 + +%calculate the 0,1,2 moments +m0=sum(dirEfreq*freqres); +m1=sum(freqs.*dirEfreq*freqres); +m2=sum((freqs.^2).*dirEfreq*freqres); +% Calculate the Sig wave height +E_UVW_D_Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(dirEfreq); +E_UVW_D_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(dirE.S(I,:))); +E_UVW_D_DTp=dirsH(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(dirEdir); +E_UVW_D_Dp=dirsH(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP UVW dir=1']); +disp(['SigH (meters): ' num2str(E_UVW_D_Hsig)]); +disp(['peak period (seconds): ' num2str(E_UVW_D_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(E_UVW_D_DTp, dirE.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(E_UVW_D_Dp, dirE.xaxisdir))]); +disp([' ']); + +E_UVW_D_WI.hsig=E_UVW_D_Hsig; +E_UVW_D_WI.tp=E_UVW_D_Tp; +E_UVW_D_WI.dtp=compangle(E_UVW_D_DTp, dirE.xaxisdir); +E_UVW_D_WI.dp=compangle(E_UVW_D_Dp, dirE.xaxisdir); + +% for IMLM freq=0.005 + +%calculate the 0,1,2 moments +m0=sum(freqIfreq*freqresH); +m1=sum(freqsH.*freqIfreq*freqresH); +m2=sum((freqsH.^2).*freqIfreq*freqresH); +% Calculate the Sig wave height +I_UVW_F_Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(freqIfreq); +I_UVW_F_Tp=1/(freqsH(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(freqI.S(I,:))); +I_UVW_F_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(freqIdir); +I_UVW_F_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM UVW freq=0.005']); +disp(['SigH (meters): ' num2str(I_UVW_F_Hsig)]); +disp(['peak period (seconds): ' num2str(I_UVW_F_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(I_UVW_F_DTp, freqI.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(I_UVW_F_Dp, freqI.xaxisdir))]); +disp([' ']); + +I_UVW_F_WI.hsig=I_UVW_F_Hsig; +I_UVW_F_WI.tp=I_UVW_F_Tp; +I_UVW_F_WI.dtp=compangle(I_UVW_F_DTp, freqI.xaxisdir); +I_UVW_F_WI.dp=compangle(I_UVW_F_Dp, freqI.xaxisdir); + +%for IMLM uvw dir=1 + +%calculate the 0,1,2 moments +m0=sum(dirIfreq*freqres); +m1=sum(freqs.*dirIfreq*freqres); +m2=sum((freqs.^2).*dirIfreq*freqres); +% Calculate the Sig wave height +I_UVW_D_Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(dirIfreq); +I_UVW_D_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(dirI.S(I,:))); +I_UVW_D_DTp=dirsH(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(dirIdir); +I_UVW_D_Dp=dirsH(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM UVW dir=1']); +disp(['SigH (meters): ' num2str(I_UVW_D_Hsig)]); +disp(['peak period (seconds): ' num2str(I_UVW_D_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(I_UVW_D_DTp, dirI.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(I_UVW_D_Dp, dirI.xaxisdir))]); +disp([' ']); + +I_UVW_D_WI.hsig=I_UVW_D_Hsig; +I_UVW_D_WI.tp=I_UVW_D_Tp; +I_UVW_D_WI.dtp=compangle(I_UVW_D_DTp, freqI.xaxisdir); +I_UVW_D_WI.dp=compangle(I_UVW_D_Dp, freqI.xaxisdir); + +%function to change from axis angles to compass bearings + +function angle=compangle(angle,xaxisdir) +angle=xaxisdir*ones(size(angle))-angle; +angle=angle+360*(angle<0); +angle=angle-360*(angle>360); + + + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/waveplot3.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/waveplot3.m (revision 225) @@ -1,0 +1,262 @@ +function waveplot3(EMEP,IMLM,rangeE,rangeI,spec) + +%make sure to load the EMEP, IMLM and wavesmon samples +%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') +%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') + +%set up the wavesmon data in a structure + +%what is the magnetic variation to nearest degree +magvar=10; + +%first change to m^2/Hz/deg +wmon.S=spec/(360*1000*1000); + +%what is the start angle +sangle=281+magvar; + +%what is the frequency and dir resolution for those generated in DIWASP +freqres=0.01; +freqs=[0.01:0.01:.4]; +dirres=2; +dirs=[-180:2:180]; + +%set up the directions +adj_angle=90-sangle+360+180; +wmon.dirs=[adj_angle:-4:-(356-adj_angle)]; +wmondirres=4; +wmon.xaxisdir=90; +wmon.freqs=[0.00781250:0.00781250:1]; +wmonfreqres=0.00781250; + +% plot the spectrum generated through DIWASP + +subplot(2,3,1); +subplotspec(EMEP.SMout,4); +title('EMEP Range'); + +subplot(2,3,2); +subplotspec(IMLM.SMout,4); +title('IMLM Range'); + +subplot(2,3,3); +subplotspec(wmon,4); +title('Wavesmon output'); + +subplot(2,3,4); +subplotspec(rangeE.SMout,4); +title('EMEP Range cpsd'); + +subplot(2,3,5); +subplotspec(rangeI.SMout,4); +title('IMLM Range cpsd'); + +%calculate just the dir energy spectrum on a single graph + +EMEPdir=sum(EMEP.SMout.S)*freqres; +IMLMdir=sum(real(IMLM.SMout.S))*freqres; +EMEPrangedir=sum(rangeE.SMout.S)*freqres; +IMLMrangedir=sum(real(rangeI.SMout.S))*freqres; +wmondir=sum(wmon.S)*wmonfreqres; + +%calculate just the frequency energy spectrum +EMEPfreq=sum(EMEP.SMout.S')*dirres; +IMLMfreq=sum(real(IMLM.SMout.S)')*dirres; +EMEPrangefreq=sum(rangeE.SMout.S')*dirres; +IMLMrangefreq=sum(real(rangeI.SMout.S)')*dirres; +wmonfreq=sum(wmon.S')*wmondirres; + +%plot the directional energy spectrum +figure; +subplot(1,2,1); +plot(dirs,EMEPdir,'b'); +hold on +plot(dirs,EMEPrangedir,'r'); +plot(dirs,IMLMrangedir,'g'); +%need to make sure the wmon plot has the same x-axis as the others +Aindex=find(wmon.dirs > 180); +Bindex=find(wmon.dirs <181); +wmon.dirs(Aindex)=wmon.dirs(Aindex)-360; + +plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); +plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); +axis(axis); +plot(dirs,IMLMdir,'c'); +legend('EMEP range','EMEP range cpsd','IMLM range cpsd','wavesmon','','IMLM range'); +title('directional wave spectrum integrated over frequency'); +xlabel('axis angle (degrees true)'); +ylabel('m^2 / deg'); + +%plot the frequency energy spectrum +subplot(1,2,2); +plot(freqs,EMEPfreq,'b'); +hold on +plot(freqs,EMEPrangefreq,'r'); +plot(freqs,IMLMrangefreq,'g'); +plot(wmon.freqs,wmonfreq,'k'); +axis(axis); +plot(freqs,IMLMfreq,'c'); +legend('EMEP range','EMEP range cpsd','IMLM range cpsd','wavesmon','IMLM range'); +title('directional wave spectrum integrated over direction'); +xlabel('frequency in Hz'); +ylabel('m^2 / hz'); + +% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ + +%For EMEP uvw + +%calculate the 0,1,2 moments +m0=sum(EMEPfreq*freqres); +m1=sum(freqs.*EMEPfreq*freqres); +m2=sum((freqs.^2).*EMEPfreq*freqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(EMEPfreq); +Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(EMEP.SMout.S(I,:))); +DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(EMEPdir); +Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP range']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, EMEP.SMout.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, EMEP.SMout.xaxisdir))]); +disp([' ']); + +% For IMLM uvw + +%calculate the 0,1,2 moments +m0=sum(IMLMfreq*freqres); +m1=sum(freqs.*IMLMfreq*freqres); +m2=sum((freqs.^2).*IMLMfreq*freqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(IMLMfreq); +Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(IMLM.SMout.S(I,:))); +DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(IMLMdir); +Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM range']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, IMLM.SMout.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, IMLM.SMout.xaxisdir))]); +disp([' ']); + +% for Range of EMEP + +%calculate the 0,1,2 moments +m0=sum(EMEPrangefreq*freqres); +m1=sum(freqs.*EMEPrangefreq*freqres); +m2=sum((freqs.^2).*EMEPrangefreq*freqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(EMEPrangefreq); +Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(rangeE.SMout.S(I,:))); +DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(EMEPrangedir); +Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP range cpsd']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, rangeE.SMout.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, rangeE.SMout.xaxisdir))]); +disp([' ']); + +%for Range of IMLM + +%calculate the 0,1,2 moments +m0=sum(IMLMrangefreq*freqres); +m1=sum(freqs.*IMLMrangefreq*freqres); +m2=sum((freqs.^2).*IMLMrangefreq*freqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(IMLMrangefreq); +Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(rangeI.SMout.S(I,:))); +DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(IMLMrangedir); +Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM range cpsd']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, rangeI.SMout.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, rangeI.SMout.xaxisdir))]); +disp([' ']); + +% for wavesmon + +%calculate the 0,1,2 moments +m0=sum(wmonfreq*wmonfreqres); +m1=sum(wmon.freqs.*wmonfreq*wmonfreqres); +m2=sum((wmon.freqs.^2).*wmonfreq*wmonfreqres); +% Calculate the Sig wave height +Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(wmonfreq); +Tp=1/(wmon.freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(wmon.S(I,:))); +DTp=wmon.dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(wmondir); +Dp=wmon.dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['Wavesmon output']); +disp(['SigH (meters): ' num2str(Hsig)]); +disp(['peak period (seconds): ' num2str(Tp)]); +disp(['Dir of peak period: ' num2str(compangle(DTp, wmon.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(Dp, wmon.xaxisdir))]); +disp([' ']); + + +%function to change from axis angles to compass bearings + +function angle=compangle(angle,xaxisdir) +angle=xaxisdir*ones(size(angle))-angle; +angle=angle+360*(angle<0); +angle=angle-360*(angle>360); + + + + + Index: DPWavesProc/trunk/DPWavesProc/test_code/waveplot_compare.m =================================================================== --- (revision ) +++ DPWavesProc/trunk/DPWavesProc/test_code/waveplot_compare.m (revision 225) @@ -1,0 +1,339 @@ +function [E_UVW_WI,I_UVW_WI,E_range_WI,I_range_WI,wmon_WI,fig1,fig2]=waveplot(EMEP,IMLM,rangeE,rangeI,spec,sysinfo) + +%make sure to load the EMEP, IMLM and wavesmon samples +%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') +%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') + +%set up the wavesmon data in a structure + +%what is the magnetic variation to nearest degree +magvar=-10; + +%first change to m^2/Hz/deg +wmon.S=spec/(360*1000*1000); + +%what is the start angle +heading=sysinfo(18,:); +heading=heading/100; +sangle=heading+magvar; + +%what is the frequency and dir resolution for those generated in DIWASP +freqres=0.01; +freqs=[0.01:0.01:.4]; +dirres=2; +dirs=[-180:2:180]; + +%set up the directions +adj_angle=90-sangle+360+180; +wmon.dirs=[adj_angle:-4:-(356-adj_angle)]; +wmondirres=4; +wmon.xaxisdir=90; +wmon.freqs=[0.00781250:0.00781250:1]; +wmonfreqres=0.00781250; + +% plot the spectrum generated through DIWASP + +scrsz = get(0,'ScreenSize'); +fig1=figure('Position',[scrsz]); +subplot(2,3,1); +subplotspec(EMEP,4); +title('EMEP uvw'); + +subplot(2,3,2); +subplotspec(IMLM,4); +title('IMLM uvw'); + +subplot(2,3,3); +subplotspec(wmon,4); +title('Wavesmon output'); + +subplot(2,3,4); +subplotspec(rangeE,4); +title('EMEP Range'); + +subplot(2,3,5); +subplotspec(rangeI,4); +title('IMLM Range'); + +%calculate just the dir energy spectrum on a single graph + +EMEPdir=sum(EMEP.S)*freqres; +IMLMdir=sum(real(IMLM.S))*freqres; +EMEPrangedir=sum(rangeE.S)*freqres; +IMLMrangedir=sum(real(rangeI.S))*freqres; +wmondir=sum(wmon.S)*wmonfreqres; + +%calculate just the frequency energy spectrum +EMEPfreq=sum(EMEP.S')*dirres; +IMLMfreq=sum(real(IMLM.S)')*dirres; +EMEPrangefreq=sum(rangeE.S')*dirres; +IMLMrangefreq=sum(real(rangeI.S)')*dirres; +wmonfreq=sum(wmon.S')*wmondirres; + +%Compute the coefficient for the upper and lower error bounds for the power +%spectrum assuming 95% confidence. Added on 9/17/08 +degF=EMEP.degF; +chiUp=chi2inv(.975,degF); +chiLow=chi2inv(.025,degF); +coeffUp=degF/chiLow; +coeffLow=degF/chiUp; + +%Find the maximum for the directional spectrum so we can set up the proper +%x-axis +[maxvalue,maxindex] = max(EMEPdir); +maxdir=dirs(maxindex); +% set up the x-axis for all of the spectra depending on the max +if ((100 < maxdir) | (maxdir < -100)); + %for diwasp spectra + index1=find(dirs < 0); + index2=find(dirs > -1); + dirs(index1)=dirs(index1) +360; + %for wavesmon + Aindex=find(wmon.dirs < 0); + Bindex=find((-1 < wmon.dirs) & (wmon.dirs < 361)); + Bindex2=find(wmon.dirs > 360); + wmon.dirs(Bindex2)=wmon.dirs(Bindex2)-360; + wmon.dirs(Aindex)=wmon.dirs(Aindex)+360; + %plot the directional energy spectrum + fig2=figure('Position',[scrsz]); + subplot(1,2,1); + h1 = plot(dirs(index2),EMEPdir(index2),'b'); + hold on + h1a= plot(dirs(index1),EMEPdir(index1),'b'); + h2 = plot(dirs(index2),EMEPrangedir(index2),'r'); + h2a= plot(dirs(index1),EMEPrangedir(index1),'r'); + h3 = plot(dirs(index2),IMLMrangedir(index2),'g'); + h3a= plot(dirs(index1),IMLMrangedir(index1),'g'); + %plot the wavesmon data + h4 = plot(wmon.dirs(Bindex2),wmondir(Bindex2),'k'); + h4a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); + h4b= plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); + axis(axis); + h5 = plot(dirs(index2),IMLMdir(index2),'c'); + h5a= plot(dirs(index1),IMLMdir(index1),'c'); + +else + %for diwasp spectra do nothing + + %for wavesmon + Aindex=find(wmon.dirs > 180); + Bindex=find(wmon.dirs < 181); + wmon.dirs(Aindex)=wmon.dirs(Aindex)-360; + %plot the directional energy spectrum + fig2=figure('Position',[scrsz]); + subplot(1,2,1); + h1 = plot(dirs,EMEPdir,'b'); + hold on + h2 = plot(dirs,EMEPrangedir,'r'); + h3 = plot(dirs,IMLMrangedir,'g'); + %plot the wavesmon data + h4 = plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); + h4a = plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); + axis(axis); + h5 = plot(dirs,IMLMdir,'c'); +end + +legend([h1, h2, h3, h4, h5],'EMEP uvw','EMEP range','IMLM range','wavesmon','IMLM uvw','location','best'); +title('directional wave spectrum integrated over frequency'); +xlabel('axis angle (degrees true)'); +ylabel('m^2 / deg'); + +%plot the frequency energy spectrum +subplot(1,2,2); +plot(freqs,EMEPfreq,'b'); +hold on +plot(freqs,EMEPrangefreq,'r'); +plot(freqs,IMLMrangefreq,'g'); +plot(wmon.freqs,wmonfreq,'k'); +axis(axis); +plot(freqs,IMLMfreq,'c'); +legend('EMEP uvw','EMEP range','IMLM range','wavesmon','IMLM uvw','location','best'); +title('directional wave spectrum integrated over direction'); +xlabel('frequency in Hz'); +ylabel('m^2 / hz'); + +% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ + +%For EMEP uvw +% Calculate the Sig wave height +EMEP_UVW_Hsig=Hsig(EMEP); +%Use the function HsigConf.m to calculate the sigH confidence limits +EMEP_HsConf=HsigConf(EMEP); + +% Calculate the peak period Tp +[P,I]=max(EMEPfreq); +EMEP_UVW_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(EMEP.S(I,:))); +EMEP_UVW_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(EMEPdir); +EMEP_UVW_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP uvw']); +disp(['SigH (meters): ' num2str(EMEP_UVW_Hsig)]); +disp(['SigH 95% confidence limits: ' num2str(EMEP_HsConf)]); +disp(['peak period (seconds): ' num2str(EMEP_UVW_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(EMEP_UVW_DTp, EMEP.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(EMEP_UVW_Dp, EMEP.xaxisdir))]); +disp([' ']); + +E_UVW_WI.hsig=EMEP_UVW_Hsig; +E_UVW_WI.hconf=EMEP_HsConf; +E_UVW_WI.tp=EMEP_UVW_Tp; +E_UVW_WI.dtp=compangle(EMEP_UVW_DTp, EMEP.xaxisdir); +E_UVW_WI.dp=compangle(EMEP_UVW_Dp, EMEP.xaxisdir); + + +% For IMLM uvw + +% Calculate the Sig wave height +IMLM_UVW_Hsig=Hsig(IMLM); +%Use the function HsigConf.m to calculate the sigH confidence limits +IMLM_HsConf=HsigConf(IMLM); + +% Calculate the peak period Tp +[P,I]=max(IMLMfreq); +IMLM_UVW_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(IMLM.S(I,:))); +IMLM_UVW_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(IMLMdir); +IMLM_UVW_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM uvw']); +disp(['SigH (meters): ' num2str(IMLM_UVW_Hsig)]); +disp(['SigH 95% confidence limits: ' num2str(IMLM_HsConf)]); +disp(['peak period (seconds): ' num2str(IMLM_UVW_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(IMLM_UVW_DTp, IMLM.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(IMLM_UVW_Dp, IMLM.xaxisdir))]); +disp([' ']); + +I_UVW_WI.hsig=IMLM_UVW_Hsig; +I_UVW_WI.hconf=IMLM_HsConf; +I_UVW_WI.tp=IMLM_UVW_Tp; +I_UVW_WI.dtp=compangle(IMLM_UVW_DTp, IMLM.xaxisdir); +I_UVW_WI.dp=compangle(IMLM_UVW_Dp, IMLM.xaxisdir); + +% for Range of EMEP + +% Calculate the Sig wave height +EMEP_range_Hsig=Hsig(rangeE); +%Use the function HsigConf.m to calculate the sigH confidence limits +EMEP_range_HsConf=HsigConf(rangeE); + +% Calculate the peak period Tp +[P,I]=max(EMEPrangefreq); +EMEP_range_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(rangeE.S(I,:))); +EMEP_range_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(EMEPrangedir); +EMEP_range_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['EMEP range']); +disp(['SigH (meters): ' num2str(EMEP_range_Hsig)]); +disp(['SigH 95% confidence limits: ' num2str(EMEP_range_HsConf)]); +disp(['peak period (seconds): ' num2str(EMEP_range_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(EMEP_range_DTp, rangeE.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(EMEP_range_Dp, rangeE.xaxisdir))]); +disp([' ']); + +E_range_WI.hsig=EMEP_range_Hsig; +E_range_WI.hconf=EMEP_range_HsConf; +E_range_WI.tp=EMEP_range_Tp; +E_range_WI.dtp=compangle(EMEP_range_DTp, rangeE.xaxisdir); +E_range_WI.dp=compangle(EMEP_range_Dp, rangeE.xaxisdir); + + +%for Range of IMLM + +% Calculate the Sig wave height +IMLM_range_Hsig=Hsig(rangeI); +%Use the function HsigConf.m to calculate the sigH confidence limits +IMLM_range_HsConf=HsigConf(rangeI); + +% Calculate the peak period Tp +[P,I]=max(IMLMrangefreq); +IMLM_range_Tp=1/(freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(rangeI.S(I,:))); +IMLM_range_DTp=dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(IMLMrangedir); +IMLM_range_Dp=dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['IMLM range']); +disp(['SigH (meters): ' num2str(IMLM_range_Hsig)]); +disp(['SigH 95% confidence limits: ' num2str(IMLM_range_HsConf)]); +disp(['peak period (seconds): ' num2str(IMLM_range_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(IMLM_range_DTp, rangeI.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(IMLM_range_Dp, rangeI.xaxisdir))]); +disp([' ']); + +I_range_WI.hsig=IMLM_range_Hsig; +I_range_WI.hconf=IMLM_range_HsConf; +I_range_WI.tp=IMLM_range_Tp; +I_range_WI.dtp=compangle(IMLM_range_DTp, rangeI.xaxisdir); +I_range_WI.dp=compangle(IMLM_range_Dp, rangeI.xaxisdir); + +% for wavesmon + +%calculate the 0,1,2 moments +m0=sum(wmonfreq*wmonfreqres); +m1=sum(wmon.freqs.*wmonfreq*wmonfreqres); +m2=sum((wmon.freqs.^2).*wmonfreq*wmonfreqres); +% Calculate the Sig wave height +wmon_Hsig=4*sqrt(m0); + +% Calculate the peak period Tp +[P,I]=max(wmonfreq); +wmon_Tp=1/(wmon.freqs(I)); + +%Calculate the Direction of the peak period DTp +[P,I]=max(real(wmon.S(I,:))); +wmon_DTp=wmon.dirs(I); + +%Calculate the Dominant Direction Dp +[P,I]=max(wmondir); +wmon_Dp=wmon.dirs(I); + +%Display on the screen the SigH,Tp,Dp,DTp +disp(['Wavesmon output']); +disp(['SigH (meters): ' num2str(wmon_Hsig)]); +disp(['peak period (seconds): ' num2str(wmon_Tp)]); +disp(['Dir of peak period: ' num2str(compangle(wmon_DTp, wmon.xaxisdir))]); +disp(['Dominant Direction: ' num2str(compangle(wmon_Dp, wmon.xaxisdir))]); +disp([' ']); + +wmon_WI.hsig=wmon_Hsig; +wmon_WI.tp=wmon_Tp; +wmon_WI.dtp=compangle(wmon_DTp, wmon.xaxisdir); +wmon_WI.dp=compangle(wmon_Dp, wmon.xaxisdir); + + +%function to change from axis angles to compass bearings + +function angle=compangle(angle,xaxisdir) +angle=xaxisdir*ones(size(angle))-angle; +angle=angle+360*(angle<0); +angle=angle-360*(angle>360); + + + + + Index: DPWavesProc/trunk/DPWavesProc/waveplot2.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/waveplot2.m (revision 168) +++ (revision ) @@ -1,310 +1,0 @@ -function [E_UVW_F_WI,E_UVW_D_WI,I_UVW_F_WI,I_UVW_D_WI,fig3,fig4]=waveplot2(EMEP,IMLM,freqE,freqI,dirE,dirI,sysinfo) - -%make sure to load the EMEP, IMLM and wavesmon samples -%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') -%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') - -%what is the magnetic variation to nearest degree -magvar=10; - -%what is the start angle -heading=sysinfo(18,:); -heading=heading/100; -sangle=heading+magvar; - -%what is the frequency and dir resolution for those generated in DIWASP -freqres=0.01; -freqresH=0.005; -freqs=[0.01:0.01:.4]; -freqsH=[0.005:0.005:0.4]; -dirres=2; -dirresH=1; -dirs=[-180:2:180]; -dirsH=[-180:1:180]; - -%set up the directions -adj_angle=90-sangle+360+180; - -% plot the spectrum generated through DIWASP -scrsz = get(0,'ScreenSize'); -fig3=figure('Position',[scrsz]); -subplot(2,3,1); -subplotspec(EMEP,4); -title('EMEP UVW'); - -subplot(2,3,2); -subplotspec(freqE,4); -title('EMEP UVW, freq = 0.005'); - -subplot(2,3,3); -subplotspec(dirE,4); -title('EMEP UVW, dir res = 1'); - -subplot(2,3,4); -subplotspec(IMLM,4); -title('IMLM UVW'); - -subplot(2,3,5); -subplotspec(freqI,4); -title('IMLM UVW, freq = 0.005'); - -subplot(2,3,6); -subplotspec(dirI,4); -title('IMLM UVW, dir res = 1'); - -%calculate just the dir energy spectrum on a single graph - -EMEPdir=sum(EMEP.S)*freqres; -IMLMdir=sum(real(IMLM.S))*freqres; -freqEdir=sum(freqE.S)*freqresH; -dirEdir=sum(dirE.S)*freqres; -freqIdir=sum(real(freqI.S))*freqresH; -dirIdir=sum(real(dirI.S))*freqres; - -%calculate just the frequency energy spectrum -EMEPfreq=sum(EMEP.S')*dirres; -IMLMfreq=sum(real(IMLM.S)')*dirres; -freqEfreq=sum(freqE.S')*dirres; -dirEfreq=sum(dirE.S')*dirresH; -freqIfreq=sum(real(freqI.S)')*dirres; -dirIfreq=sum(real(dirI.S)')*dirresH; - -%plot the directional energy spectrum -fig4=figure('Position',[scrsz]); -subplot(1,2,1); -plot(dirs,EMEPdir,'b'); -hold on -plot(dirs,freqEdir,'r'); -plot(dirsH,dirEdir,'g'); -axis(axis); -plot(dirs,IMLMdir,'c'); -plot(dirs,freqIdir,'m'); -plot(dirsH,dirIdir,'k'); - - -legend('EMEP uvw','EMEP uvw freq=0.005','EMEP uvw dir=1','IMLM uvw','IMLM uvw freq=0.005','IMLM uvw dir=1','location','best'); -title('directional wave spectrum integrated over frequency'); -xlabel('axis angle (degrees true)'); -ylabel('m^2 / hz'); - -%plot the frequency energy spectrum -subplot(1,2,2); -plot(freqs,EMEPfreq,'b'); -hold on -plot(freqsH,freqEfreq,'r'); -plot(freqs,dirEfreq,'g'); -plot(freqs,IMLMfreq,'c'); -plot(freqsH,freqIfreq,'m'); -plot(freqs,dirIfreq,'k'); -legend('EMEP uvw','EMEP uvw freq=0.005','EMEP uvw dir=1','IMLM uvw','IMLM uvw freq=0.005','IMLM uvw dir=1','location','best'); -title('directional wave spectrum integrated over direction'); -xlabel('frequency in Hz'); -ylabel('m^2 / deg'); - -% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ - -%For EMEP uvw - -%calculate the 0,1,2 moments -m0=sum(EMEPfreq*freqres); -m1=sum(freqs.*EMEPfreq*freqres); -m2=sum((freqs.^2).*EMEPfreq*freqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(EMEPfreq); -Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(EMEP.S(I,:))); -DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(EMEPdir); -Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP uvw']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, EMEP.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, EMEP.xaxisdir))]); -disp([' ']); - -% For IMLM uvw - -%calculate the 0,1,2 moments -m0=sum(IMLMfreq*freqres); -m1=sum(freqs.*IMLMfreq*freqres); -m2=sum((freqs.^2).*IMLMfreq*freqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(IMLMfreq); -Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(IMLM.S(I,:))); -DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(IMLMdir); -Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM uvw']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, IMLM.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, IMLM.xaxisdir))]); -disp([' ']); - -% for EMEP freq=0.005 - -%calculate the 0,1,2 moments -m0=sum(freqEfreq*freqresH); -m1=sum(freqsH.*freqEfreq*freqresH); -m2=sum((freqsH.^2).*freqEfreq*freqresH); -% Calculate the Sig wave height -E_UVW_F_Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(freqEfreq); -E_UVW_F_Tp=1/(freqsH(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(freqE.S(I,:))); -E_UVW_F_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(freqEdir); -E_UVW_F_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP UVW freq=0.005']); -disp(['SigH (meters): ' num2str(E_UVW_F_Hsig)]); -disp(['peak period (seconds): ' num2str(E_UVW_F_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(E_UVW_F_DTp, freqE.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(E_UVW_F_Dp, freqE.xaxisdir))]); -disp([' ']); - -E_UVW_F_WI.hsig=E_UVW_F_Hsig; -E_UVW_F_WI.tp=E_UVW_F_Tp; -E_UVW_F_WI.dtp=compangle(E_UVW_F_DTp, freqE.xaxisdir); -E_UVW_F_WI.dp=compangle(E_UVW_F_Dp, freqE.xaxisdir); - -%for EMEP uvw dir=1 - -%calculate the 0,1,2 moments -m0=sum(dirEfreq*freqres); -m1=sum(freqs.*dirEfreq*freqres); -m2=sum((freqs.^2).*dirEfreq*freqres); -% Calculate the Sig wave height -E_UVW_D_Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(dirEfreq); -E_UVW_D_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(dirE.S(I,:))); -E_UVW_D_DTp=dirsH(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(dirEdir); -E_UVW_D_Dp=dirsH(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP UVW dir=1']); -disp(['SigH (meters): ' num2str(E_UVW_D_Hsig)]); -disp(['peak period (seconds): ' num2str(E_UVW_D_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(E_UVW_D_DTp, dirE.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(E_UVW_D_Dp, dirE.xaxisdir))]); -disp([' ']); - -E_UVW_D_WI.hsig=E_UVW_D_Hsig; -E_UVW_D_WI.tp=E_UVW_D_Tp; -E_UVW_D_WI.dtp=compangle(E_UVW_D_DTp, dirE.xaxisdir); -E_UVW_D_WI.dp=compangle(E_UVW_D_Dp, dirE.xaxisdir); - -% for IMLM freq=0.005 - -%calculate the 0,1,2 moments -m0=sum(freqIfreq*freqresH); -m1=sum(freqsH.*freqIfreq*freqresH); -m2=sum((freqsH.^2).*freqIfreq*freqresH); -% Calculate the Sig wave height -I_UVW_F_Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(freqIfreq); -I_UVW_F_Tp=1/(freqsH(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(freqI.S(I,:))); -I_UVW_F_DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(freqIdir); -I_UVW_F_Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM UVW freq=0.005']); -disp(['SigH (meters): ' num2str(I_UVW_F_Hsig)]); -disp(['peak period (seconds): ' num2str(I_UVW_F_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(I_UVW_F_DTp, freqI.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(I_UVW_F_Dp, freqI.xaxisdir))]); -disp([' ']); - -I_UVW_F_WI.hsig=I_UVW_F_Hsig; -I_UVW_F_WI.tp=I_UVW_F_Tp; -I_UVW_F_WI.dtp=compangle(I_UVW_F_DTp, freqI.xaxisdir); -I_UVW_F_WI.dp=compangle(I_UVW_F_Dp, freqI.xaxisdir); - -%for IMLM uvw dir=1 - -%calculate the 0,1,2 moments -m0=sum(dirIfreq*freqres); -m1=sum(freqs.*dirIfreq*freqres); -m2=sum((freqs.^2).*dirIfreq*freqres); -% Calculate the Sig wave height -I_UVW_D_Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(dirIfreq); -I_UVW_D_Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(dirI.S(I,:))); -I_UVW_D_DTp=dirsH(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(dirIdir); -I_UVW_D_Dp=dirsH(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM UVW dir=1']); -disp(['SigH (meters): ' num2str(I_UVW_D_Hsig)]); -disp(['peak period (seconds): ' num2str(I_UVW_D_Tp)]); -disp(['Dir of peak period: ' num2str(compangle(I_UVW_D_DTp, dirI.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(I_UVW_D_Dp, dirI.xaxisdir))]); -disp([' ']); - -I_UVW_D_WI.hsig=I_UVW_D_Hsig; -I_UVW_D_WI.tp=I_UVW_D_Tp; -I_UVW_D_WI.dtp=compangle(I_UVW_D_DTp, freqI.xaxisdir); -I_UVW_D_WI.dp=compangle(I_UVW_D_Dp, freqI.xaxisdir); - -%function to change from axis angles to compass bearings - -function angle=compangle(angle,xaxisdir) -angle=xaxisdir*ones(size(angle))-angle; -angle=angle+360*(angle<0); -angle=angle-360*(angle>360); - - - - - Index: DPWavesProc/trunk/DPWavesProc/waveplot3.m =================================================================== --- DPWavesProc/trunk/DPWavesProc/waveplot3.m (revision 168) +++ (revision ) @@ -1,262 +1,0 @@ -function waveplot3(EMEP,IMLM,rangeE,rangeI,spec) - -%make sure to load the EMEP, IMLM and wavesmon samples -%EMEP=load('emep'), IMLM=load('imlm'), spec=load('wavesmon') -%rangeE=load('EMEP_range'), rangeI=load('IMLM_range') - -%set up the wavesmon data in a structure - -%what is the magnetic variation to nearest degree -magvar=10; - -%first change to m^2/Hz/deg -wmon.S=spec/(360*1000*1000); - -%what is the start angle -sangle=281+magvar; - -%what is the frequency and dir resolution for those generated in DIWASP -freqres=0.01; -freqs=[0.01:0.01:.4]; -dirres=2; -dirs=[-180:2:180]; - -%set up the directions -adj_angle=90-sangle+360+180; -wmon.dirs=[adj_angle:-4:-(356-adj_angle)]; -wmondirres=4; -wmon.xaxisdir=90; -wmon.freqs=[0.00781250:0.00781250:1]; -wmonfreqres=0.00781250; - -% plot the spectrum generated through DIWASP - -subplot(2,3,1); -subplotspec(EMEP.SMout,4); -title('EMEP Range'); - -subplot(2,3,2); -subplotspec(IMLM.SMout,4); -title('IMLM Range'); - -subplot(2,3,3); -subplotspec(wmon,4); -title('Wavesmon output'); - -subplot(2,3,4); -subplotspec(rangeE.SMout,4); -title('EMEP Range cpsd'); - -subplot(2,3,5); -subplotspec(rangeI.SMout,4); -title('IMLM Range cpsd'); - -%calculate just the dir energy spectrum on a single graph - -EMEPdir=sum(EMEP.SMout.S)*freqres; -IMLMdir=sum(real(IMLM.SMout.S))*freqres; -EMEPrangedir=sum(rangeE.SMout.S)*freqres; -IMLMrangedir=sum(real(rangeI.SMout.S))*freqres; -wmondir=sum(wmon.S)*wmonfreqres; - -%calculate just the frequency energy spectrum -EMEPfreq=sum(EMEP.SMout.S')*dirres; -IMLMfreq=sum(real(IMLM.SMout.S)')*dirres; -EMEPrangefreq=sum(rangeE.SMout.S')*dirres; -IMLMrangefreq=sum(real(rangeI.SMout.S)')*dirres; -wmonfreq=sum(wmon.S')*wmondirres; - -%plot the directional energy spectrum -figure; -subplot(1,2,1); -plot(dirs,EMEPdir,'b'); -hold on -plot(dirs,EMEPrangedir,'r'); -plot(dirs,IMLMrangedir,'g'); -%need to make sure the wmon plot has the same x-axis as the others -Aindex=find(wmon.dirs > 180); -Bindex=find(wmon.dirs <181); -wmon.dirs(Aindex)=wmon.dirs(Aindex)-360; - -plot(wmon.dirs(Aindex),wmondir(Aindex),'k'); -plot(wmon.dirs(Bindex),wmondir(Bindex),'k'); -axis(axis); -plot(dirs,IMLMdir,'c'); -legend('EMEP range','EMEP range cpsd','IMLM range cpsd','wavesmon','','IMLM range'); -title('directional wave spectrum integrated over frequency'); -xlabel('axis angle (degrees true)'); -ylabel('m^2 / deg'); - -%plot the frequency energy spectrum -subplot(1,2,2); -plot(freqs,EMEPfreq,'b'); -hold on -plot(freqs,EMEPrangefreq,'r'); -plot(freqs,IMLMrangefreq,'g'); -plot(wmon.freqs,wmonfreq,'k'); -axis(axis); -plot(freqs,IMLMfreq,'c'); -legend('EMEP range','EMEP range cpsd','IMLM range cpsd','wavesmon','IMLM range'); -title('directional wave spectrum integrated over direction'); -xlabel('frequency in Hz'); -ylabel('m^2 / hz'); - -% ______Calculate and display the wave parameters SigH, Tp, Dp,DTp_______ - -%For EMEP uvw - -%calculate the 0,1,2 moments -m0=sum(EMEPfreq*freqres); -m1=sum(freqs.*EMEPfreq*freqres); -m2=sum((freqs.^2).*EMEPfreq*freqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(EMEPfreq); -Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(EMEP.SMout.S(I,:))); -DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(EMEPdir); -Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP range']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, EMEP.SMout.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, EMEP.SMout.xaxisdir))]); -disp([' ']); - -% For IMLM uvw - -%calculate the 0,1,2 moments -m0=sum(IMLMfreq*freqres); -m1=sum(freqs.*IMLMfreq*freqres); -m2=sum((freqs.^2).*IMLMfreq*freqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(IMLMfreq); -Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(IMLM.SMout.S(I,:))); -DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(IMLMdir); -Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM range']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, IMLM.SMout.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, IMLM.SMout.xaxisdir))]); -disp([' ']); - -% for Range of EMEP - -%calculate the 0,1,2 moments -m0=sum(EMEPrangefreq*freqres); -m1=sum(freqs.*EMEPrangefreq*freqres); -m2=sum((freqs.^2).*EMEPrangefreq*freqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(EMEPrangefreq); -Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(rangeE.SMout.S(I,:))); -DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(EMEPrangedir); -Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['EMEP range cpsd']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, rangeE.SMout.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, rangeE.SMout.xaxisdir))]); -disp([' ']); - -%for Range of IMLM - -%calculate the 0,1,2 moments -m0=sum(IMLMrangefreq*freqres); -m1=sum(freqs.*IMLMrangefreq*freqres); -m2=sum((freqs.^2).*IMLMrangefreq*freqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(IMLMrangefreq); -Tp=1/(freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(rangeI.SMout.S(I,:))); -DTp=dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(IMLMrangedir); -Dp=dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['IMLM range cpsd']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, rangeI.SMout.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, rangeI.SMout.xaxisdir))]); -disp([' ']); - -% for wavesmon - -%calculate the 0,1,2 moments -m0=sum(wmonfreq*wmonfreqres); -m1=sum(wmon.freqs.*wmonfreq*wmonfreqres); -m2=sum((wmon.freqs.^2).*wmonfreq*wmonfreqres); -% Calculate the Sig wave height -Hsig=4*sqrt(m0); - -% Calculate the peak period Tp -[P,I]=max(wmonfreq); -Tp=1/(wmon.freqs(I)); - -%Calculate the Direction of the peak period DTp -[P,I]=max(real(wmon.S(I,:))); -DTp=wmon.dirs(I); - -%Calculate the Dominant Direction Dp -[P,I]=max(wmondir); -Dp=wmon.dirs(I); - -%Display on the screen the SigH,Tp,Dp,DTp -disp(['Wavesmon output']); -disp(['SigH (meters): ' num2str(Hsig)]); -disp(['peak period (seconds): ' num2str(Tp)]); -disp(['Dir of peak period: ' num2str(compangle(DTp, wmon.xaxisdir))]); -disp(['Dominant Direction: ' num2str(compangle(Dp, wmon.xaxisdir))]); -disp([' ']); - - -%function to change from axis angles to compass bearings - -function angle=compangle(angle,xaxisdir) -angle=xaxisdir*ones(size(angle))-angle; -angle=angle+360*(angle<0); -angle=angle-360*(angle>360); - - - - -