1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
/*! Library for reading and writing Seismic Analysis Code (SAC) files Reference: [SAC Manual](http://ds.iris.edu/files/sac-manual/) ``` use sacio::Sac; # use sacio::SacError; use sacio::SacString; let mut s = Sac::from_file("tests/file.sac")?; assert_eq!(s.mean_amp(), -0.09854721); assert_eq!(s.min_amp(), -1.56928); assert_eq!(s.max_amp(), 1.52064); s.y.iter_mut().for_each(|v| *v *= 2.0); s.extrema_amp(); assert_eq!(s.mean_amp(), -0.09854721 * 2.0); assert_eq!(s.min_amp(), -1.56928 * 2.0); assert_eq!(s.max_amp(), 1.52064 * 2.0); s.set_string(SacString::Network, "CI"); s.set_string(SacString::Station, "PAS"); s.set_string(SacString::Location, "10"); s.set_string(SacString::T1, "PKIKP"); s.set_string(SacString::T1, "SKJKS"); assert_eq!(s.dist_deg(), 3.3574646); s.to_file("tests/main.sac")?; # std::fs::remove_file("tests/main.sac")?; # Ok::<(), SacError>(()) ``` */ use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::path::Path; use std::io::prelude::*; use geographiclib::Geodesic; use chrono::Duration; use chrono::NaiveDateTime; use chrono::NaiveDate; use chrono::NaiveTime; use chrono::Datelike; use chrono::Timelike; use byteorder::{BigEndian, LittleEndian, WriteBytesExt, ReadBytesExt, NativeEndian}; mod enums; use enums::*; pub use enums::SacString; pub use enums::SacZeroTime; pub use enums::SacFileType; pub use enums::SacDataType; #[cfg(target_endian = "big")] type NonNativeEndian = LittleEndian; #[cfg(target_endian = "big")] type __NativeEndian = BigEndian; #[cfg(target_endian = "little")] type NonNativeEndian = BigEndian; #[cfg(target_endian = "little")] type __NativeEndian = LittleEndian; //const HEADER_SIZE : usize = 632; const SAC_INT_UNDEF : i32 = -12345; const SAC_FLOAT_UNDEF : f32 = -12345.0; const _SAC_STRING_UNDEF : &'static str = "-12345 "; #[inline] fn fis(x: f32) -> bool { x != SAC_FLOAT_UNDEF } #[macro_use] mod macros; mod eq; pub mod doc; /// Value containing an absolute or relative time pub enum TimeValue { /// Relative time in seconds Relative(Duration), /// Absolute time year-month-day, HH:MM:SS Absolute(NaiveDateTime), } /// Convert [u8] to Strings fn sac_u8_to_strings(s: &mut Sac) { sac_strings_pair!(s, u8_to_string); } /// Convert Strings into [u8] fn sac_strings_to_u8(s: &mut Sac) { sac_strings_pair!(s, string_to_u8); } /// Read a single data component fn sac_data_read_comp<T: Read>(file: &mut T, swap: bool, npts: usize) -> Result<Vec<f32>,SacError>{ let mut y = vec![0.0; npts]; if swap { file.read_f32_into::<NonNativeEndian>(&mut y)?; } else { file.read_f32_into::<NativeEndian>(&mut y)?; } Ok(y) } /// Read sac data from a file fn sac_data_read<T: Read>(file: &mut T, h: &mut Sac) -> Result<(),SacError>{ let npts = h.npts as usize; h.y = sac_data_read_comp(file, h.swap, npts)?; if h.ncomps() == 2 { h.x = sac_data_read_comp(file, h.swap, npts)?; } Ok(()) } /// Write a sac data to a file fn sac_data_write<F: Write>(file: &mut F, s: &mut Sac, npts: usize) -> Result<(),SacError> { if npts != s.y.len() { panic!("Inconsistent Data: npts [{}] != data len [{}]", npts, s.y.len()); } if s.swap { s.y.iter().map(|&y| file.write_f32::<NonNativeEndian>(y)) .collect::<Result<Vec<()>,_>>()?; } else { s.y.iter().map(|&y| file.write_f32::<NativeEndian>(y)) .collect::<Result<Vec<()>,_>>()?; } Ok(()) } /// Determine if the sac file is byte swapped fn sac_header_is_swapped<T: Read + Seek>(file: &mut T) -> Result<bool,SacError> { use std::io::SeekFrom; file.seek(SeekFrom::Start(70*4 + 6*4))?; let n = file.read_i32::<NativeEndian>()?; let swap = if n > 5 && n <= 8 { false } else { file.seek(SeekFrom::Start(70*4 + 6*4))?; let n = file.read_i32::<NonNativeEndian>()?; if n < 0 || n > 10 { panic!("Unknown file type: {}", n); } true }; file.seek(SeekFrom::Start(0))?; Ok(swap) } /// Read a sac file header fn sac_header_read<T: Read + Seek>(file: &mut T, h: &mut Sac) -> Result<(),SacError>{ use std::io::SeekFrom; h.swap = sac_header_is_swapped(file)?; file.seek(SeekFrom::Start(0))?; if h.swap { sac_reals!(h, file, NonNativeEndian, read_reals ); sac_ints!(h, file, NonNativeEndian, read_ints); } else { sac_reals!(h, file, NativeEndian, read_reals ); sac_ints!(h, file, NativeEndian, read_ints); } sac_u8_strings!(h, file, read_strings); Ok(()) } /// Write a sac file header fn sac_header_write<F: Write>(file: &mut F, s: &mut Sac) -> Result<(),SacError>{ if s.swap { sac_reals!(s, file, NonNativeEndian, write_reals ); sac_ints!(s, file, NonNativeEndian, write_ints); } else { sac_reals!(s, file, NativeEndian, write_reals ); sac_ints!(s, file, NativeEndian, write_ints); } sac_u8_strings!(s, file, write_strings); Ok(()) } use std::fmt; impl fmt::Debug for Sac { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "sac {{ file: {}, npts: {} }}", self.file, self.npts) } } /// Errors associated with Reading and Writing Sac Files #[derive(Debug)] pub enum SacError { NotSpectral, NotTime, NaN, BadLatitude, BadLongitude, BadAzimuth, BadInclination, Io(std::io::Error), BadKey, } /// Wrap an std::io::Error impl From<std::io::Error> for SacError { fn from(err: std::io::Error) -> Self { SacError::Io(err) } } fn duration_to_f64(dt: Duration) -> f64 { dt.num_seconds() as f64 + (dt.num_milliseconds() as f64 / 1_000.0) } fn time_from_parts(year: i32, doy: i32, hour: i32, min: i32, sec: i32, msec: i32) -> NaiveDateTime { NaiveDateTime::new(NaiveDate::from_yo(year, doy as u32), NaiveTime::from_hms_milli(hour as u32, min as u32, sec as u32, msec as u32)) } /// Sac Implementation impl Sac { /// Read a sac file /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.delta(), 0.01); /// # Ok::<(), SacError>(()) /// ``` pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Sac,SacError> { let file = File::open(path)?; let mut file = BufReader::new(file); Sac::read(&mut file) } /// Read a sac file from a buffer /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// // This simulates having the data already in memory /// let mut buf = std::fs::read("tests/file.sac")?; /// let mut rdr = std::io::Cursor::new(&mut buf); /// /// let s = Sac::read(&mut rdr)?; /// assert_eq!(s.delta(), 0.01); /// # Ok::<(), SacError>(()) /// ``` pub fn read<R: Read + Seek>(buf: &mut R) -> Result<Sac,SacError> { let mut s = Sac::new(); sac_header_read(buf, &mut s)?; sac_u8_to_strings(&mut s); sac_data_read(buf, &mut s)?; Ok(s) } /// Write a sac file /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let mut s = Sac::from_file("tests/file.sac")?; /// /// s.to_file("tests/to_file.sac")?; /// /// let s2 = Sac::from_file("tests/to_file.sac")?; /// assert_eq!(s.delta(), s2.delta()); /// assert_eq!(s.npts(), s2.npts()); /// /// # std::fs::remove_file("tests/to_file.sac")?; /// # Ok::<(), SacError>(()) /// ``` pub fn to_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(),SacError> { let file = File::create(path)?; let mut file = BufWriter::new(file); self.write(&mut file) } /// Write a sac file to a buffer /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let mut s = Sac::from_file("tests/file.sac")?; /// let mut buf = vec![]; /// s.write(&mut buf)?; /// /// let mut rdr = std::io::Cursor::new(&mut buf); /// let s2 = Sac::read(&mut rdr)?; /// assert_eq!(s.delta(), s2.delta()); /// assert_eq!(s.npts(), s2.npts()); /// # Ok::<(), SacError>(()) /// ``` /// Write a SAC file pub fn write<W: Write>(&mut self, buf: &mut W) -> Result<(),SacError> { let npts = self.npts as usize; sac_strings_to_u8(self); sac_header_write(buf, self)?; sac_data_write(buf, self, npts)?; Ok(()) } /// Determine if file is to be swapped on output /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let mut s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.swapped(), false); /// /// let mut s = Sac::from_file("tests/file.sac.swap")?; /// assert_eq!(s.swapped(), true); /// # Ok::<(), SacError>(()) /// ``` /// pub fn swapped(&self) -> bool { self.swap } /// Determine if file is to be swapped on output /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let mut s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.swapped(), false); /// /// s.set_swap(true); /// s.to_file("tests/set_swap.sac")?; /// /// let mut s = Sac::from_file("tests/set_swap.sac")?; /// assert_eq!(s.swapped(), true); /// /// # std::fs::remove_file("tests/set_swap.sac")?; /// # Ok::<(), SacError>(()) /// ``` /// pub fn set_swap(&mut self, swap: bool) { self.swap = swap; } /// Create an empty SAC file /// /// ``` /// use sacio::Sac; /// use sacio::SacString; /// use sacio::SacZeroTime; /// use sacio::SacFileType; /// use sacio::SacDataType; /// /// let s = Sac::new(); /// assert_eq!(s.delta(), -12345.0); /// assert_eq!(s.string(SacString::EventName), "-12345 "); /// assert_eq!(s.zero_time(), SacZeroTime::None); /// assert_eq!(s.file_type(), SacFileType::Time); /// assert_eq!(s.data_type(), SacDataType::None); /// /// assert_eq!(s.version(), 6); /// assert_eq!(s.station_polarity(), false); /// assert_eq!(s.mutability(), true); /// assert_eq!(s.calc_dist_az(), true); /// /// assert_eq!(s.npts(), 0); /// ``` pub fn new() -> Sac { let mut s0 : Sac = Sac { .. Default::default() }; sac_reals!(s0, f32_undef); sac_ints!(s0, i32_undef); sac_strings!(s0, str_undef); sac_u8_strings!(s0, u8s_undef); s0.iztype = SacZeroTime::None.into(); s0.iftype = SacFileType::Time.into(); s0.ievtyp = SacEventType::None.into(); s0.idep = SacDataType::None.into(); s0.nvhdr = 6; s0.lpspol = 0; s0.lovrok = 1; s0.lcalda = 1; s0.unused27 = 0; s0.npts = 0; s0.y = vec![]; s0.x = vec![]; s0 } /// Check if file is spectral /// ///``` /// use sacio::Sac; /// let s = Sac::from_amp(vec![0.,1.,2.], 0.0, 1.0); /// assert!( ! s.is_spectral() ); /// ``` pub fn is_spectral(&self) -> bool { match self.iftype.into() { SacFileType::Time | SacFileType::XY | SacFileType::XYZ => false, SacFileType::AmpPhase | SacFileType::RealImag => true, } } /// Check is file is a Real/Imaginary Pair /// /// use sacio::Sac; /// let s = Sac::from_amp(vec![0.,1.,2.],0.0, 1.0); /// assert!( ! s.is_real_imag() ); /// pub fn is_real_imag(&self) -> bool { self.iftype == SacFileType::RealImag.into() } /// Check if file is a Amplitude/Phase Pair /// /// use sacio::Sac; /// let s = Sac::from_amp(vec![0.,1.,2.],0.0, 1.0); /// assert!( ! s.is_amp_phase() ); /// pub fn is_amp_phase(&self) -> bool { self.iftype == SacFileType::AmpPhase.into() } /// Check if file is a time series file /// /// use sacio::Sac; /// let s = Sac::from_amp(vec![0.,1.,2.],0.0, 1.0); /// assert!( s.is_time() ); /// pub fn is_time(&self) -> bool { self.iftype == SacFileType::Time.into() } /// Get File type (iftype) /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// use sacio::SacFileType; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.file_type(), SacFileType::Time); /// # Ok::<(), SacError>(()) /// ``` /// pub fn file_type(&self) -> SacFileType { self.iftype.into() } /// Set File type (iftype) pub fn set_file_type(&mut self, file_type: SacFileType) { self.iftype = file_type.into(); } /// Determine the number of data components /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.ncomps(), 1); /// # Ok::<(), SacError>(()) /// ``` /// pub fn ncomps(&self) -> usize { match self.iftype.into() { SacFileType::Time | SacFileType::XY => { if self.evenly_spaced() { 1 } else { 2 } }, SacFileType::XYZ => 1, SacFileType::RealImag | SacFileType::AmpPhase => 2, } } /// Get number of data points /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.npts(), 1000); /// # Ok::<(), SacError>(()) /// ``` /// pub fn npts(&self) -> i32 { self.npts } /// Get Header Version /// /// Should be 6 /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.version(), 6); /// # Ok::<(), SacError>(()) /// ``` /// pub fn version(&self) -> i32 { self.nvhdr } /// Get Reference Time /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// use chrono::{NaiveDateTime, NaiveDate, NaiveTime}; /// /// let s = Sac::from_file("tests/file.sac")?; /// let date = NaiveDate::from_yo(1981, 88); /// let time = NaiveTime::from_hms_milli(10, 38, 14, 0); /// assert_eq!(s.time(), NaiveDateTime::new(date, time)); /// # Ok::<(), SacError>(()) /// ``` /// pub fn time(&self) -> NaiveDateTime { time_from_parts(self.nzyear, self.nzjday, self.nzhour, self.nzmin, self.nzsec, self.nzmsec) } /// Set Refernce Time /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// use chrono::{NaiveDateTime, NaiveDate, NaiveTime}; /// /// let mut s = Sac::from_file("tests/file.sac")?; /// let date = NaiveDate::from_yo(1984, 29); /// let time = NaiveTime::from_hms_milli(15, 12, 59, 456); /// let when = NaiveDateTime::new(date, time); /// s.set_time(when); /// /// assert_eq!(s.time(), when); /// # Ok::<(), SacError>(()) /// ``` /// pub fn set_time(&mut self, time: NaiveDateTime) { self.nzyear = time.year(); self.nzjday = time.ordinal() as i32; self.nzhour = time.hour() as i32; self.nzmin = time.minute() as i32; self.nzsec = time.second() as i32; self.nzmsec = time.nanosecond() as i32 / 1_000_000; } /// Compute the maximum amplitude /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.calc_max_amp(), s.max_amp()); /// # Ok::<(), SacError>(()) /// ``` /// pub fn calc_max_amp(&self) -> f32 { let mut vmax = self.y[0]; for v in self.y.iter() { if *v > vmax { vmax = *v; } } vmax } /// Compute the minimum amplitude /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.calc_min_amp(), s.min_amp()); /// # Ok::<(), SacError>(()) /// ``` /// pub fn calc_min_amp(&self) -> f32 { let mut vmin = self.y[0]; for v in self.y.iter() { if *v < vmin { vmin = *v; } } vmin } /// Compute the mean amplitude /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.calc_mean_amp(), s.mean_amp()); /// # Ok::<(), SacError>(()) /// ``` /// pub fn calc_mean_amp(&self) -> f32 { let vmean : f64 = self.y.iter().map(|x| *x as f64).sum(); (vmean / self.npts as f64) as f32 } /// Compute and set min, man and mean amplitudes of the y component /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let mut s = Sac::from_file("tests/file.sac")?; /// /// assert_eq!(s.mean_amp(), -0.09854721); /// assert_eq!(s.min_amp(), -1.56928); /// assert_eq!(s.max_amp(), 1.52064); /// /// s.y.iter_mut().for_each(|v| *v *= 2.0); /// /// s.extrema_amp(); /// /// assert_eq!(s.mean_amp(), -0.09854721 * 2.0); /// assert_eq!(s.min_amp(), -1.56928 * 2.0); /// assert_eq!(s.max_amp(), 1.52064 * 2.0); /// /// # Ok::<(), SacError>(()) /// ``` /// pub fn extrema_amp(&mut self) { self.depmax = self.calc_max_amp(); self.depmin = self.calc_min_amp(); self.depmen = self.calc_mean_amp(); } /// Compute and set extremas in x and y /// /// File Type | y-min | y-max | y-mean | x-min | x-max /// ----------------|---------|----------|----------|------------|------------- /// time / even | min(amp)| min(amp) | mean(amp)| b | e = b + (n-1)*dt /// time / uneven | min(amp)| min(amp) | mean(amp)| b = min(x) | e = max(x) /// general xy | min(amp)| min(amp) | mean(amp)| b | e = b + (n-1)*dt /// amp / phase | - | - | - | b = 0 | e = f_nyquist /// real/ imag | - | - | - | b = 0 | e = f_nyquist /// general xyz | - | - | - | - | - /// /// pub fn extrema(&mut self) { self.extrema_amp(); self.calc_be(); } fn calc_be(&mut self) { if self.evenly_spaced() { match self.iftype.into() { SacFileType::Time | SacFileType::XY => self.e = self.b + self.delta * ((self.npts-1) as f32), SacFileType::RealImag | SacFileType::AmpPhase => { let nfreq = if self.npts % 2 == 0 { self.npts / 2 } else { (self.npts - 1) / 2 }; self.e = self.b + self.delta * nfreq as f32; }, SacFileType::XYZ => {}, } } else if self.x.len() > 0 { let mut xmin = self.x[0]; let mut xmax = self.x[0]; for xi in self.x.iter() { if *xi < xmin { xmin = *xi; } } for xi in self.x.iter() { if *xi > xmax { xmax = *xi; } } self.b = xmin; self.e = xmax; } } /// Create a SAC File with new data, copying header values /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_file("tests/file.sac")?; /// /// let t = s.with_new_data(vec![0., 1., 0.0]); /// /// assert_eq!(t.min_amp(), 0.0); /// assert_eq!(t.max_amp(), 1.0); /// assert_eq!(t.npts(), 3); /// /// # Ok::<(), SacError>(()) /// ``` /// pub fn with_new_data(&self, y: Vec<f32>) -> Self { let mut s = self.clone(); s.y = y; s.npts = s.y.len() as i32; s.extrema(); s } /// Create new sac from data from amplitude, begin value, `b`, and sample rate, `dt` /// /// use sacio::Sac; /// let s = Sac::from_amp(vec![0., 1., 2.], 0.0, 0.1); /// assert!( s.is_time() ); /// assert!( s.y == &[0., 1., 2.] ); /// pub fn from_amp(y: Vec<f32>, b: f64, dt: f64) -> Sac { let mut s = Sac::new(); s.npts = y.len() as i32; s.delta = dt as f32; s.b = b as f32; s.y = y; s.iftype = SacFileType::Time.into(); s.leven = true as i32; s.extrema(); s } /// Determine if all data is finite, not NaN, inf /// /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// /// let s = Sac::from_amp(vec![0.,1.], 0.0, 1.0); /// assert_eq!(s.is_finite(), true); /// /// # Ok::<(), SacError>(()) /// ``` /// pub fn is_finite(&self) -> bool { self.y.iter().all(|x| x.is_finite() == true) } /// Get Zero Time Equivalent /// ``` /// use sacio::Sac; /// # use sacio::SacError; /// use sacio::SacZeroTime; /// /// let s = Sac::from_file("tests/file.sac")?; /// assert_eq!(s.zero_time(), SacZeroTime::B); /// /// # Ok::<(), SacError>(()) /// ``` pub fn zero_time(&self) -> SacZeroTime { self.iztype.into() } /// Get Station_polarity pub fn station_polarity(&self) -> bool { self.lpspol != 0 } /// Set Station polarity pub fn set_station_polarity(&mut self, flipped: bool) { self.lpspol = flipped as i32; } /// Determine is file is evenly spaced pub fn evenly_spaced(&self) -> bool { self.leven != 0 } /// Determine is file should calculate the distance and azimuth (lcalda) pub fn calc_dist_az(&self) -> bool { self.lcalda != 0 } /// Set if file should calculate the distance and azimuth (lcalda) pub fn set_calc_dist_az(&mut self, value: bool) { self.lcalda = value as i32; } /// Check is file can be overwritten (lovrok) pub fn mutability(&self) -> bool { self.lovrok != 0 } /// Set the file as mutable (lovrok) pub fn set_mutability(&mut self, value: bool) { self.lovrok = value as i32; } /// Get Event type (ievtyp) pub fn event_type(&self) -> SacEventType { self.ievtyp.into() } /// Set Event ytpe (ievtyp) pub fn set_event_type(&mut self, etype: SacEventType) { self.ievtyp = etype.into(); } /// Get Data Quality pub fn data_quality(&self) -> SacQuality { self.iqual.into() } /// Set Data Quality pub fn set_data_quality(&mut self, qual: SacQuality) { self.iqual = qual.into(); } /// Get Amplitude Type (idep) pub fn data_type(&self) -> SacDataType { self.idep.into() } /// Set synthetic flag (isynth) pub fn synthetic(&self) -> bool { self.isynth == 1 } /// Set synthetic flag (isynth) pub fn set_synthetic(&mut self, synth: bool) { self.isynth = if synth { 1 } else { 0 }; } /// Set Zero Time Type pub fn set_zero_time_type(&mut self, ztype: SacZeroTime) { self.iztype = ztype.into(); } /// Get Magnitude Type pub fn magnitude_type(&self) -> SacMagnitudeType { self.imagtyp.into() } /// Set Magnitude Type pub fn set_magnitude_type(&mut self, mag: SacMagnitudeType) { self.imagtyp = mag.into(); } /// Get Magnitude Source pub fn magnitude_source(&self) -> SacMagnitudeSource { self.imagsrc.into() } /// Set Magnitude Source pub fn set_magnitude_source(&mut self, magsrc: SacMagnitudeSource) { self.imagsrc = magsrc.into(); } /// Get Instrument Type /// /// This type is historical, you probably want SacStrings::Instrument /// pub fn instrument_type(&self) -> SacInstrument { self.iinst.into() } /// Set Instrument Type /// /// This type is historical, you probably want SacStrings::Instrument /// pub fn set_instrument_type(&mut self, itype: SacInstrument) { self.iinst = itype.into(); } /// Set Amplitude Type (idep) pub fn set_amp_type(&mut self, amp_type: SacDataType) { self.idep = amp_type.into(); } /// Compute Distance and Azimuth between station and event pub fn compute_dist_az(&mut self) { if ! self.calc_dist_az() { return; } if fis(self.stlo) && fis(self.stla) && fis(self.evlo) && fis(self.evla) { let g = Geodesic::wgs84(); let (a12, s12, az1, az2) = g.inverse(self.stla as f64, self.stlo as f64, self.evla as f64, self.evlo as f64); self.gcarc = a12 as f32; self.dist = (s12 / 1000.0) as f32; self.az = az1 as f32; self.baz = az2 as f32; } } /// Get event region pub fn event_region(&self) -> i32 { self.ievreg } /// Get station region pub fn station_region(&self) -> i32 { self.istreg } /// Update event and station regions /// /// This assumes the station and event locations are defined pub fn update_regions(&mut self) { use flinn_engdahl as fe; if fis(self.stlo) && fis(self.stla) { if let Ok(n) = fe::region_number(self.stla as f64, self.stlo as f64) { self.istreg = n as i32; } } if fis(self.evlo) && fis(self.evla) { if let Ok(n) = fe::region_number(self.evla as f64, self.evlo as f64) { self.ievreg = n as i32; } } } /// Get Current filename pub fn filename(&self) -> &str { &self.file } /// Set Filename pub fn set_filename(&mut self, filename: &str) { self.file = filename.to_string(); } pub fn id(&self, key: SacInt) -> i32 { match key { SacInt::OriginID => self.norid, SacInt::EventID => self.nevid, SacInt::WaveformID => self.nwfid, } } pub fn set_id(&mut self, key: SacInt, value: i32) { match key { SacInt::OriginID => self.norid = value, SacInt::EventID => self.nevid = value, SacInt::WaveformID => self.nwfid = value, } } pub fn string(&self, key: SacString) -> &str { match key { SacString::Station => &self.kstnm, SacString::EventName => &self.kevnm, SacString::Hole => &self.khole, SacString::Location => &self.khole, SacString::O => &self.ko, SacString::A => &self.ka, SacString::T0 => &self.kt0, SacString::T1 => &self.kt1, SacString::T2 => &self.kt2, SacString::T3 => &self.kt3, SacString::T4 => &self.kt4, SacString::T5 => &self.kt5, SacString::T6 => &self.kt6, SacString::T7 => &self.kt7, SacString::T8 => &self.kt8, SacString::T9 => &self.kt9, SacString::EventEnd => &self.kf, SacString::User0 => &self.kuser0, SacString::User1 => &self.kuser1, SacString::User2 => &self.kuser2, SacString::Component => &self.kcmpnm, SacString::Network => &self.knetwk, SacString::DateRead => &self.kdatrd, SacString::Instrument => &self.kinst, } } pub fn set_string(&mut self, key: SacString, value: &str) { let v = match key { SacString::Station => &mut self.kstnm, SacString::EventName => &mut self.kevnm, SacString::Hole => &mut self.khole, SacString::Location => &mut self.khole, SacString::O => &mut self.ko, SacString::A => &mut self.ka, SacString::T0 => &mut self.kt0, SacString::T1 => &mut self.kt1, SacString::T2 => &mut self.kt2, SacString::T3 => &mut self.kt3, SacString::T4 => &mut self.kt4, SacString::T5 => &mut self.kt5, SacString::T6 => &mut self.kt6, SacString::T7 => &mut self.kt7, SacString::T8 => &mut self.kt8, SacString::T9 => &mut self.kt9, SacString::EventEnd => &mut self.kf, SacString::User0 => &mut self.kuser0, SacString::User1 => &mut self.kuser1, SacString::User2 => &mut self.kuser2, SacString::Component => &mut self.kcmpnm, SacString::Network => &mut self.knetwk, SacString::DateRead => &mut self.kdatrd, SacString::Instrument => &mut self.kinst, }; *v = value.to_string(); } /// Get Sampling pub fn delta(&self) -> f32 { self.delta } /// Get Mean amplitude value pub fn mean_amp(&self) -> f32 { self.depmen } /// Get Minimum amplitude value pub fn min_amp(&self) -> f32 { self.depmin } /// Get Maximum amplitude value pub fn max_amp(&self) -> f32 { self.depmax } pub fn station_lat(&self) -> f32 { self.stla } pub fn station_lon(&self) -> f32 { self.stlo } pub fn station_elevation(&self) -> f32 { self.stel } pub fn event_lat(&self) -> f32 { self.evla } pub fn event_lon(&self) -> f32 { self.evlo } pub fn event_depth(&self) -> f32 { self.evdp } pub fn dist_km(&self) -> f32 { self.dist } pub fn dist_deg(&self) -> f32 { self.gcarc } pub fn az(&self) -> f32 { self.az } pub fn baz(&self) -> f32 { self.baz } pub fn set_station_location(&mut self, lat: f32, lon: f32, elev: f32) -> Result<(),SacError>{ if lat.abs() > 90.0 { return Err(SacError::BadLatitude); } if lon.abs() > 360.0 { return Err(SacError::BadLongitude); } self.stla = lat; self.stlo = lon; self.stel = elev; self.update_regions(); self.compute_dist_az(); Ok(()) } pub fn set_event_location(&mut self, lat: f32, lon: f32, depth: f32) -> Result<(),SacError>{ if lat.abs() > 90.0 { return Err(SacError::BadLatitude); } if lon.abs() > 360.0 { return Err(SacError::BadLongitude); } self.evla = lat; self.evlo = lon; self.evel = depth; self.update_regions(); self.compute_dist_az(); Ok(()) } /// Get Component Azimuth /// /// North is 0 degrees, with positive values rotating clockwise. /// This is a geographic coordinate system. /// /// Direction | Value /// ----------|------ /// North | 0 /// East | 90 /// South | 180 /// West | 270 or -90 /// pub fn cmpaz(&self) -> f32 { self.cmpaz } /// Set Component Azimuth /// /// Accepted must be between [-360, 360] /// pub fn set_cmpaz(&mut self, az: f32) -> Result<(),SacError> { if az.abs() > 360.0 { return Err(SacError::BadAzimuth); } self.cmpaz = az; Ok(()) } /// Get Component Inclination or Incident angle /// /// Values are defined from vertical /// /// Diretion | Value /// ------------|------ /// Vertical Up | 0 /// Horizontal | 90 /// pub fn cmpinc(&self) -> f32 { self.cmpaz } /// Set Component Inclination /// /// Values must be between [-180, 180] pub fn set_cmpinc(&mut self, inc: f32) -> Result<(),SacError> { if inc.abs() > 180.0 { return Err(SacError::BadInclination) } self.cmpinc = inc; Ok(()) } /// Get Beginning time value pub fn b(&self) -> f32 { self.b } /// Get Ending time value pub fn e(&self) -> f32 { self.e } /// Get Origin time value pub fn o(&self) -> f32 { self.o } /// Set beginning time value pub fn set_b(&mut self, time: TimeValue) { match time { TimeValue::Relative(v) => self.b = duration_to_f64(v) as f32, TimeValue::Absolute(v) => { // Requires knowledge of the reference time let dt = self.time() - v; self.b = duration_to_f64(dt) as f32; }, } self.calc_be(); } /// Set origin time value pub fn set_o(&mut self, time: TimeValue) { match time { TimeValue::Relative(v) => self.o = duration_to_f64(v) as f32, TimeValue::Absolute(v) => { // Requires knowledge of the reference time let dt = self.time() - v; self.o = duration_to_f64(dt) as f32; } } } } #[cfg(test)] mod tests { use super::*; #[test] fn create_time() { let mut s = Sac::from_amp(vec![0.,-1.,2.], 0.0, 1.0); s.file = format!("{}","create_time"); assert_eq!(s.depmin, -1.0); assert_eq!(s.depmax, 2.0); assert_eq!(s.b, 0.0); assert_eq!(s.delta, 1.0); assert_eq!(s.depmen, 1.0/3.0); assert_eq!(s.e, 2.0); //assert_eq!(s.iztype, SacZeroTime::B as i32); assert_eq!(s.iftype, SacFileType::Time.into()); assert_eq!(s.leven, true as i32); assert_eq!(s.nvhdr, 6); assert_eq!(s.y, vec![0.,-1.,2.0]); } #[test] fn test_finite_ok() { let s = Sac::from_amp(vec![1.,2.,3.], 0., 1.); assert!(s.is_finite()) } #[test] fn test_finite_pos_inf() { let s = Sac::from_amp(vec![1.,2.,1./0.], 0., 1.); assert!(!s.is_finite()) } #[test] fn test_finite_neg_inf() { let s = Sac::from_amp(vec![1.,2.,-1./0.], 0., 1.); assert!(!s.is_finite()) } #[test] fn read_file() { use std::path::Path; let mut s = Sac::from_file("tests/file.sac.swap").unwrap(); s.file = String::from("tests/file.sac.swap"); let mut s0 = Sac::new(); s0.file = String::from("tests/file.sac.swap true"); s0.set_time(time_from_parts(1981, 88, 10, 38, 14, 0)); s0.norid = 0; s0.nevid = 0; // Wow, this is kinda cheating s0.y = s.y.clone(); s0.lovrok = true as i32; s0.lpspol = true as i32; s0.lcalda = true as i32; s0.leven = true as i32; s0.unused27 = false as i32; s0.npts = 1000; s0.iftype = SacFileType::Time.into(); s0.idep = SacDataType::Volts as i32; s0.iztype = SacZeroTime::B as i32; s0.ievtyp = SacEventType::Aftershock as i32; s0.kstnm = format!("{:-8}", "CDV"); s0.kevnm = format!("{:-16}", "K8108838"); s0.delta = 0.01; s0.depmin = -1.56928; s0.depmax = 1.52064; s0.b = 9.459999; s0.e = 19.449999; s0.o = -41.43; s0.a = 10.464; s0.stla = 48.0; s0.stlo = -120.0; s0.evla = 48.0; s0.evlo = -125.0; s0.evdp = 15.0; s0.dist = 3.7306274e+02; s0.az = 8.814721e+01; s0.baz = 2.7185278e+02; s0.gcarc = 3.3574646e+00; s0.depmen = -9.8547176e-02; s0.cmpaz = 0.0; s0.cmpinc = 0.0; println!("compare s and s0"); assert_eq!(s,s0); println!("write file"); let path = Path::new("tests/tmp.sac"); s.to_file(path).unwrap(); println!("write file with long kevnm"); s.kevnm = format!("{}", "123456789012345678901234567890"); let path = Path::new("tests/tmp2.sac"); s.to_file(path).unwrap(); println!("write file with short kevnm"); s.kevnm = format!("{}", "12"); let path = Path::new("tests/tmp3.sac"); s.to_file(path).unwrap(); { for elem in s.y.iter_mut() { *elem += 1.0; } } } #[test] fn stringy() { let mut s = Sac::new(); s.set_string(SacString::Network, "IU"); assert!(s.string(SacString::Network) == "IU"); } } /// SAC file data and metadata /// #[derive(Default, Clone)] pub struct Sac { /// Dependent variable /// - Amplitude for time series data /// - Amplitude for Amplitude Phase data /// - Real for Real Imaginary data /// - Z for XYZ data /// - Y for XY data pub y: Vec<f32>, /// Indepenent variable, Time for time series data /// - Timing for time series data, only for uneven data /// - Phase for Amplitude Phase data /// - Imaginary for Real Imaginary data /// - X for XY data pub x: Vec<f32>, /// Filename of the Sac Data File pub file: String, /// If data is swapped from native byte order swap: bool, /// Time sampling delta: f32, /* RF time increment, sec */ /// Miniumum Value of y depmin: f32, /* minimum amplitude */ /// Maximum value of y depmax: f32, /* maximum amplitude */ scale: f32, /* amplitude scale factor */ odelta: f32, /* observed time inc */ /// Begin time value of the data b: f32, /* RD initial value, time */ /// End time value of the data e: f32, /* RD final value, time */ o: f32, /* event start, sec < nz. */ pub a: f32, /* 1st arrival time */ pub fmt: f32, /* internal use */ pub t0: f32, /* user-defined time pick */ pub t1: f32, /* user-defined time pick */ pub t2: f32, /* user-defined time pick */ pub t3: f32, /* user-defined time pick */ pub t4: f32, /* user-defined time pick */ pub t5: f32, /* user-defined time pick */ pub t6: f32, /* user-defined time pick */ pub t7: f32, /* user-defined time pick */ pub t8: f32, /* user-defined time pick */ pub t9: f32, /* user-defined time pick */ pub f: f32, /* event end, sec > nz */ pub resp0: f32, /* instrument respnse parm */ pub resp1: f32, /* instrument respnse parm */ pub resp2: f32, /* instrument respnse parm */ pub resp3: f32, /* instrument respnse parm */ pub resp4: f32, /* instrument respnse parm */ pub resp5: f32, /* instrument respnse parm */ pub resp6: f32, /* instrument respnse parm */ pub resp7: f32, /* instrument respnse parm */ pub resp8: f32, /* instrument respnse parm */ pub resp9: f32, /* instrument respnse parm */ stla: f32, /* T station latititude */ stlo: f32, /* T station longitude */ stel: f32, /* T station elevation, m */ stdp: f32, /* T station depth, m */ evla: f32, /* event latitude */ evlo: f32, /* event longitude */ evel: f32, /* event elevation */ evdp: f32, /* event depth */ pub mag: f32, /* reserved for future use */ pub user0: f32, /* available to user */ pub user1: f32, /* available to user */ pub user2: f32, /* available to user */ pub user3: f32, /* available to user */ pub user4: f32, /* available to user */ pub user5: f32, /* available to user */ pub user6: f32, /* available to user */ pub user7: f32, /* available to user */ pub user8: f32, /* available to user */ pub user9: f32, /* available to user */ dist: f32, /* stn-event distance, km */ az: f32, /* event-stn azimuth */ baz: f32, /* stn-event azimuth */ gcarc: f32, /* stn-event dist, degrees */ sb: f32, /* internal use */ sdelta: f32, /* internal use */ depmen: f32, /* mean value, amplitude */ cmpaz: f32, /* T component azimuth */ cmpinc: f32, /* T component inclination */ xminimum: f32, /* reserved for future use */ xmaximum: f32, /* reserved for future use */ yminimum: f32, /* reserved for future use */ ymaximum: f32, /* reserved for future use */ unused6: f32, /* reserved for future use */ unused7: f32, /* reserved for future use */ unused8: f32, /* reserved for future use */ unused9: f32, /* reserved for future use */ unused10: f32, /* reserved for future use */ unused11: f32, /* reserved for future use */ unused12: f32, /* reserved for future use */ nzyear: i32, /* F zero time of file, yr */ nzjday: i32, /* F zero time of file, day */ nzhour: i32, /* F zero time of file, hr */ nzmin: i32, /* F zero time of file, min */ nzsec: i32, /* F zero time of file, sec */ nzmsec: i32, /* F zero time of file, msec */ /// Header Version, Should be 6 nvhdr: i32, /* internal use */ norid: i32, /* origin ID */ nevid: i32, /* event ID */ /// Number of data points npts: i32, /* RF number of samples */ nsnpts: i32, /* internal use */ nwfid: i32, /* waveform ID */ nxsize: i32, /* reserved for future use */ nysize: i32, /* reserved for future use */ unused15: i32, /* reserved for future use */ /// file_type(), set_file_type(), is_amp_phase(), is_real_imag(), is_spectral() iftype: i32, /* RA type of file */ /// amp_type(), set_amp_type() idep: i32, /* type of amplitude */ iztype: i32, /* zero time equivalence */ unused16: i32, /* reserved for future use */ iinst: i32, /* recording instrument */ istreg: i32, /* stn geographic region */ ievreg: i32, /* event geographic region */ ievtyp: i32, /* event type */ iqual: i32, /* quality of data */ isynth: i32, /* synthetic data flag */ imagtyp: i32, /* reserved for future use */ imagsrc: i32, /* reserved for future use */ unused19: i32, /* reserved for future use */ unused20: i32, /* reserved for future use */ unused21: i32, /* reserved for future use */ unused22: i32, /* reserved for future use */ unused23: i32, /* reserved for future use */ unused24: i32, /* reserved for future use */ unused25: i32, /* reserved for future use */ unused26: i32, /* reserved for future use */ leven: i32, /* RA data-evenly-spaced flag */ lpspol: i32, /* station polarity flag */ lovrok: i32, /* overwrite permission */ lcalda: i32, /* calc distance, azimuth */ unused27: i32, /* reserved for future use */ u8_kstnm: [u8; 8], /* F station name */ u8_kevnm: [u8; 16], /* event name */ u8_khole: [u8; 8], /* man-made event name */ u8_ko: [u8; 8], /* event origin time id */ u8_ka: [u8; 8], /* 1st arrival time ident */ u8_kt0: [u8; 8], /* time pick 0 ident */ u8_kt1: [u8; 8], /* time pick 1 ident */ u8_kt2: [u8; 8], /* time pick 2 ident */ u8_kt3: [u8; 8], /* time pick 3 ident */ u8_kt4: [u8; 8], /* time pick 4 ident */ u8_kt5: [u8; 8], /* time pick 5 ident */ u8_kt6: [u8; 8], /* time pick 6 ident */ u8_kt7: [u8; 8], /* time pick 7 ident */ u8_kt8: [u8; 8], /* time pick 8 ident */ u8_kt9: [u8; 8], /* time pick 9 ident */ u8_kf: [u8; 8], /* end of event ident */ u8_kuser0: [u8; 8], /* available to user */ u8_kuser1: [u8; 8], /* available to user */ u8_kuser2: [u8; 8], /* available to user */ u8_kcmpnm: [u8; 8], /* F component name */ u8_knetwk: [u8; 8], /* network name */ u8_kdatrd: [u8; 8], /* date data read */ u8_kinst: [u8; 8], /* instrument name */ /* End of Tradiitonal Header */ kstnm: String, /* F station name */ kevnm: String, /* event name */ khole: String, /* man-made event name */ ko: String, /* event origin time id */ ka: String, /* 1st arrival time ident */ kt0: String, /* time pick 0 ident */ kt1: String, /* time pick 1 ident */ kt2: String, /* time pick 2 ident */ kt3: String, /* time pick 3 ident */ kt4: String, /* time pick 4 ident */ kt5: String, /* time pick 5 ident */ kt6: String, /* time pick 6 ident */ kt7: String, /* time pick 7 ident */ kt8: String, /* time pick 8 ident */ kt9: String, /* time pick 9 ident */ kf: String, /* end of event ident */ kuser0: String, /* available to user */ kuser1: String, /* available to user */ kuser2: String, /* available to user */ kcmpnm: String, /* F component name */ knetwk: String, /* network name */ kdatrd: String, /* date data read */ kinst: String, /* instrument name */ } /* /// String formatting of sac header data fn strfmt(s: &Sac, fmt: &str) -> String { let mut out = String::new(); let mut b = fmt.chars(); let t = s.time(); while let Some(p) = b.next() { if p == '%' { if let Some(p2) = b.next() { match p2 { '%' => out.push('%'), '+' => { if s.nzyear == SAC_INT_UNDEF || s.nzjday == SAC_INT_UNDEF || s.nzhour == SAC_INT_UNDEF || s.nzmin == SAC_INT_UNDEF || s.nzsec == SAC_INT_UNDEF { continue; } out += & strfmt(s, "%Y-%m-%dT%H:%M:%S.%f"); } 'Y' => vore!(s.nzyear, out, "{:04}", i), 'J' => vore!(s.nzjday, out, "{:02}", i), 'd' => vore!(t.ordinal(), out, "{:02}", i), 'm' => vore!(t.month(), out, "{:02}", i), 'H' => vore!(s.nzhour, out, "{:02}",i), 'M' => vore!(s.nzmin, out, "{:02}", i), 'S' => vore!(s.nzsec, out, "{:02}", i), 'f' => vore!(s.nzmsec, out, "{:03}", i), 'n' => out += vore!(&s.knetwk, c), 's' => out += vore!(&s.kstnm, c), 'l' => out += vore!(&s.khole, c), 'c' => out += vore!(&s.kcmpnm, c), 'I' => out += &strfmt(s, "%n.%s.%l.%c"), _ => {}, } } else { out.push(p); break; } } else { out.push(p); } } out } #[test] fn fmt() { println!("time"); let mut s = Sac::from_amp(vec![1.,2.,3.], 0.0, 1.0); println!("time"); let f = strfmt(&s, "thing"); println!("time"); assert_eq!(f, "thing"); let f = strfmt(&s, "thing%Y-%m-%dT%H:%M:%S"); assert_eq!(f, "thing--T::"); println!("time"); let f = strfmt(&s, "thing%+"); assert_eq!(f, "thing"); s.set_time(Time::new(1976, 27, 03, 23, 0, 23).unwrap()); let f = strfmt(&s, "thing%Y-%m-%dT%H:%M:%S"); assert_eq!(f, "thing1976-01-27T03:23:00"); let f = strfmt(&s, "thing%+"); assert_eq!(f, "thing1976-01-27T03:23:00.023"); let f = strfmt(&s, "thing%n%s%l%c"); assert_eq!(f, "thing"); let f = strfmt(&s, "thing%I"); assert_eq!(f, "thing..."); s.kstnm = "PAS".to_string(); s.knetwk = "CI".to_string(); s.khole= "00".to_string(); s.kcmpnm= "BHZ".to_string(); let f = strfmt(&s, "thing%n%s%l%c"); assert_eq!(f, "thingCIPAS00BHZ"); let f = strfmt(&s, "thing%I"); assert_eq!(f, "thingCI.PAS.00.BHZ"); let f = strfmt(&s, "thing%x"); assert_eq!(f, "thing"); s.stlo = 40.1234; } /// Value Or Empty (v_or_e) macro_rules! vore { ($x: expr, $out: expr, $f: expr, i) => { if $x as i32 != SAC_INT_UNDEF { $out += & format!($f, $x); } }; ($x: expr, $out: expr, $f: expr, f) => { if $x != SAC_FLOAT_UNDEF { $out += & format!($f, $x); } }; ($x: expr, c) => { if $x == SAC_STRING_UNDEF { "" } else { $x } } } */