CCTorch 0.1.3__tar.gz → 0.1.4.dev1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: CCTorch
3
+ Version: 0.1.4.dev1
4
+ Description-Content-Type: text/markdown
5
+ Requires-Dist: torch
6
+ Requires-Dist: torchvision
7
+ Requires-Dist: torchaudio
8
+ Requires-Dist: h5py
9
+ Requires-Dist: matplotlib
10
+ Requires-Dist: numpy
11
+ Requires-Dist: pandas
12
+ Requires-Dist: pyarrow
13
+ Requires-Dist: obspy
14
+ Requires-Dist: fsspec
15
+ Requires-Dist: scipy
16
+ Requires-Dist: scikit-learn
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: zarr
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: requires-dist
22
+
23
+ Cross-Correlation using Pytorch
@@ -6,9 +6,12 @@ CCTorch.egg-info/requires.txt
6
6
  CCTorch.egg-info/top_level.txt
7
7
  cctorch/__init__.py
8
8
  cctorch/data.py
9
+ cctorch/distributed.py
9
10
  cctorch/model.py
11
+ cctorch/run.py
10
12
  cctorch/transforms.py
11
13
  cctorch/utils.py
12
14
  tests/test_dtcc.py
15
+ tests/test_peaks.py
13
16
  tests/test_qtm.py
14
17
  tests/test_template_matching.py
@@ -1,7 +1,14 @@
1
1
  torch
2
2
  torchvision
3
+ torchaudio
3
4
  h5py
4
5
  matplotlib
6
+ numpy
5
7
  pandas
8
+ pyarrow
6
9
  obspy
7
10
  fsspec
11
+ scipy
12
+ scikit-learn
13
+ tqdm
14
+ zarr
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: CCTorch
3
+ Version: 0.1.4.dev1
4
+ Description-Content-Type: text/markdown
5
+ Requires-Dist: torch
6
+ Requires-Dist: torchvision
7
+ Requires-Dist: torchaudio
8
+ Requires-Dist: h5py
9
+ Requires-Dist: matplotlib
10
+ Requires-Dist: numpy
11
+ Requires-Dist: pandas
12
+ Requires-Dist: pyarrow
13
+ Requires-Dist: obspy
14
+ Requires-Dist: fsspec
15
+ Requires-Dist: scipy
16
+ Requires-Dist: scikit-learn
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: zarr
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: requires-dist
22
+
23
+ Cross-Correlation using Pytorch
@@ -255,7 +255,7 @@ class CCIterableDataset(IterableDataset):
255
255
  """
256
256
  Assume pair_list is a list of pairs of event indices
257
257
  """
258
- pair_list = np.loadtxt(pair_list, delimiter=",", dtype=np.int64)
258
+ pair_list = np.load(pair_list) if pair_list.endswith(".npy") else np.loadtxt(pair_list, delimiter=",", dtype=np.int64) # (n, 2) int64
259
259
  # For TEST
260
260
  # pair_list = np.array(list(itertools.product(range(6000), range(6000))))
261
261
  # pair_list = pair_list[pair_list[:, 0] < pair_list[:, 1]]
@@ -266,8 +266,8 @@ class CCIterableDataset(IterableDataset):
266
266
  print(f"Number of pairs: {total_pairs}, list1: {len(unique_row)}, list2: {len(unique_col)}")
267
267
 
268
268
  rows, cols = pair_list[:, 0], pair_list[:, 1]
269
- data = [True] * len(pair_list)
270
- shape = (max(rows) + 1, max(cols) + 1)
269
+ data = np.ones(len(pair_list), dtype=bool)
270
+ shape = (rows.max() + 1, cols.max() + 1)
271
271
  pair_matrix = coo_matrix((data, (rows, cols)), shape=shape, dtype=bool)
272
272
  pair_matrix = pair_matrix.tocsr()
273
273
 
@@ -312,7 +312,36 @@ class CCIterableDataset(IterableDataset):
312
312
  num_workers = worker_info.num_workers
313
313
  worker_id = worker_info.id
314
314
 
315
- return iter(self.sample(self.block_index[worker_id::num_workers]))
315
+ block_index = self.block_index[worker_id::num_workers]
316
+ if self.mode == "CC" and self.data_format1 == "memmap":
317
+ return iter(self.sample_templates(block_index))
318
+ return iter(self.sample(block_index))
319
+
320
+ def sample_templates(self, block_index):
321
+ """CC of template pairs from one memmap: a batch is one index operation per side, no loop over pairs"""
322
+ for i, j in block_index:
323
+ templates = info = None # free the previous block before loading the next
324
+ row_index, col_index = self.group1[i], self.group2[j]
325
+ rows = self.row_matrix[row_index, :][:, col_index].tocoo().data
326
+ cols = self.col_matrix[row_index, :][:, col_index].tocoo().data
327
+
328
+ ## the block's picks, sorted so the memmap is read in ascending offset
329
+ picks, local = np.unique(np.concatenate([rows, cols]), return_inverse=True)
330
+ local = local.reshape(2, -1) # position in the block of each pair's two picks
331
+ templates = torch.as_tensor(self.templates[picks], dtype=self.dtype).to(self.device) # (npick, nc, nx, nt)
332
+ info = {key: self.data_list1.loc[picks, key].values for key in ("idx_eve", "idx_sta", "phase_type")}
333
+ info["traveltime"] = self.traveltime[picks]
334
+ if self.template_mask is not None:
335
+ info["template_mask"] = self.template_mask[picks]
336
+
337
+ for k in range(0, len(rows), self.batch_size):
338
+ batch = []
339
+ for index in local[:, k : k + self.batch_size]:
340
+ data = templates[torch.from_numpy(index)] # (nb, nc, nx, nt), a copy
341
+ if self.transforms is not None:
342
+ data = self.transforms(data)
343
+ batch.append({"data": data, "index": picks[index], "info": {key: x[index] for key, x in info.items()}})
344
+ yield tuple(batch)
316
345
 
317
346
  def cache_data(self, local_dict, ii, to_device=False):
318
347
  if self.data_list1.loc[ii, "file_name"] not in local_dict:
@@ -401,6 +430,15 @@ class CCIterableDataset(IterableDataset):
401
430
  "time_before": self.time_before[self.data_list1.loc[ii, "phase_type"]],
402
431
  },
403
432
  }
433
+ ## Same mask the second stream attaches below. It has to be set on
434
+ ## both, because local_dict is keyed by index and shared between the
435
+ ## streams: in CC mode they read the same template.dat, so whichever
436
+ ## stream reaches an index first decides whether the cached entry
437
+ ## carries the key, and a batch that mixes the two then fails to
438
+ ## collate. Which pairs land together is decided by the pair list,
439
+ ## so this stays hidden until the ordering changes.
440
+ if self.template_mask is not None:
441
+ meta1["info"]["template_mask"] = self.template_mask[ii]
404
442
  data = torch.tensor(meta1["data"], dtype=self.dtype).to(self.device)
405
443
  if self.transforms is not None:
406
444
  data = self.transforms(data)
@@ -0,0 +1,308 @@
1
+ import datetime
2
+ import errno
3
+ import os
4
+ import queue
5
+ import time
6
+ from collections import defaultdict, deque
7
+ from concurrent.futures import ThreadPoolExecutor
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+
12
+
13
+ class LimitedThreadPoolExecutor(ThreadPoolExecutor):
14
+ def __init__(self, max_workers=None, queue_size=16):
15
+ super().__init__(max_workers)
16
+ self._work_queue = queue.Queue(maxsize=queue_size)
17
+
18
+
19
+ class SmoothedValue:
20
+ """Track a series of values and provide access to smoothed values over a
21
+ window or the global series average.
22
+ """
23
+
24
+ def __init__(self, window_size=20, fmt=None):
25
+ if fmt is None:
26
+ fmt = "{median:.4f} ({global_avg:.4f})"
27
+ self.deque = deque(maxlen=window_size)
28
+ self.total = 0.0
29
+ self.count = 0
30
+ self.fmt = fmt
31
+
32
+ def update(self, value, n=1):
33
+ self.deque.append(value)
34
+ self.count += n
35
+ self.total += value * n
36
+
37
+ def synchronize_between_processes(self):
38
+ """
39
+ Warning: does not synchronize the deque!
40
+ """
41
+ t = reduce_across_processes([self.count, self.total])
42
+ t = t.tolist()
43
+ self.count = int(t[0])
44
+ self.total = t[1]
45
+
46
+ @property
47
+ def median(self):
48
+ d = torch.tensor(list(self.deque))
49
+ return d.median().item()
50
+
51
+ @property
52
+ def avg(self):
53
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
54
+ return d.mean().item()
55
+
56
+ @property
57
+ def global_avg(self):
58
+ return self.total / self.count
59
+
60
+ @property
61
+ def max(self):
62
+ return max(self.deque)
63
+
64
+ @property
65
+ def value(self):
66
+ return self.deque[-1]
67
+
68
+ def __str__(self):
69
+ return self.fmt.format(
70
+ median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value
71
+ )
72
+
73
+
74
+ class ConfusionMatrix:
75
+ def __init__(self, num_classes):
76
+ self.num_classes = num_classes
77
+ self.mat = None
78
+
79
+ def update(self, a, b):
80
+ n = self.num_classes
81
+ if self.mat is None:
82
+ self.mat = torch.zeros((n, n), dtype=torch.int64, device=a.device)
83
+ with torch.inference_mode():
84
+ k = (a >= 0) & (a < n)
85
+ inds = n * a[k].to(torch.int64) + b[k]
86
+ self.mat += torch.bincount(inds, minlength=n**2).reshape(n, n)
87
+
88
+ def reset(self):
89
+ self.mat.zero_()
90
+
91
+ def compute(self):
92
+ h = self.mat.float()
93
+ acc_global = torch.diag(h).sum() / h.sum()
94
+ acc = torch.diag(h) / h.sum(1)
95
+ iu = torch.diag(h) / (h.sum(1) + h.sum(0) - torch.diag(h))
96
+ return acc_global, acc, iu
97
+
98
+ def reduce_from_all_processes(self):
99
+ reduce_across_processes(self.mat)
100
+
101
+ def __str__(self):
102
+ acc_global, acc, iu = self.compute()
103
+ return ("global correct: {:.1f}\naverage row correct: {}\nIoU: {}\nmean IoU: {:.1f}").format(
104
+ acc_global.item() * 100,
105
+ [f"{i:.1f}" for i in (acc * 100).tolist()],
106
+ [f"{i:.1f}" for i in (iu * 100).tolist()],
107
+ iu.mean().item() * 100,
108
+ )
109
+
110
+
111
+ class MetricLogger:
112
+ def __init__(self, delimiter="\t"):
113
+ self.meters = defaultdict(SmoothedValue)
114
+ self.delimiter = delimiter
115
+
116
+ def update(self, **kwargs):
117
+ for k, v in kwargs.items():
118
+ if isinstance(v, torch.Tensor):
119
+ v = v.item()
120
+ if not isinstance(v, (float, int)):
121
+ raise TypeError(
122
+ f"This method expects the value of the input arguments to be of type float or int, instead got {type(v)}"
123
+ )
124
+ self.meters[k].update(v)
125
+
126
+ def __getattr__(self, attr):
127
+ if attr in self.meters:
128
+ return self.meters[attr]
129
+ if attr in self.__dict__:
130
+ return self.__dict__[attr]
131
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
132
+
133
+ def __str__(self):
134
+ loss_str = []
135
+ for name, meter in self.meters.items():
136
+ loss_str.append(f"{name}: {str(meter)}")
137
+ return self.delimiter.join(loss_str)
138
+
139
+ def synchronize_between_processes(self):
140
+ for meter in self.meters.values():
141
+ meter.synchronize_between_processes()
142
+
143
+ def add_meter(self, name, meter):
144
+ self.meters[name] = meter
145
+
146
+ def log_every(self, iterable, print_freq, header=None):
147
+ i = 0
148
+ if not header:
149
+ header = ""
150
+ start_time = time.time()
151
+ end = time.time()
152
+ iter_time = SmoothedValue(fmt="{avg:.4f}")
153
+ data_time = SmoothedValue(fmt="{avg:.4f}")
154
+ space_fmt = ":" + str(len(str(len(iterable)))) + "d"
155
+ if torch.cuda.is_available():
156
+ log_msg = self.delimiter.join(
157
+ [
158
+ header,
159
+ "[{0" + space_fmt + "}/{1}]",
160
+ "eta: {eta}",
161
+ "{meters}",
162
+ "time: {time}",
163
+ "data: {data}",
164
+ "max mem: {memory:.0f}",
165
+ ]
166
+ )
167
+ else:
168
+ log_msg = self.delimiter.join(
169
+ [header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}"]
170
+ )
171
+ MB = 1024.0 * 1024.0
172
+ for obj in iterable:
173
+ data_time.update(time.time() - end)
174
+ yield obj
175
+ iter_time.update(time.time() - end)
176
+ if i % print_freq == 0:
177
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
178
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
179
+ if torch.cuda.is_available():
180
+ print(
181
+ log_msg.format(
182
+ i,
183
+ len(iterable),
184
+ eta=eta_string,
185
+ meters=str(self),
186
+ time=str(iter_time),
187
+ data=str(data_time),
188
+ memory=torch.cuda.max_memory_allocated() / MB,
189
+ )
190
+ )
191
+ else:
192
+ print(
193
+ log_msg.format(
194
+ i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)
195
+ )
196
+ )
197
+ i += 1
198
+ end = time.time()
199
+ total_time = time.time() - start_time
200
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
201
+ print(f"{header} Total time: {total_time_str}")
202
+
203
+
204
+ def cat_list(images, fill_value=0):
205
+ max_size = tuple(max(s) for s in zip(*[img.shape for img in images]))
206
+ batch_shape = (len(images),) + max_size
207
+ batched_imgs = images[0].new(*batch_shape).fill_(fill_value)
208
+ for img, pad_img in zip(images, batched_imgs):
209
+ pad_img[..., : img.shape[-2], : img.shape[-1]].copy_(img)
210
+ return batched_imgs
211
+
212
+
213
+ def collate_fn(batch):
214
+ images, targets = list(zip(*batch))
215
+ batched_imgs = cat_list(images, fill_value=0)
216
+ batched_targets = cat_list(targets, fill_value=255)
217
+ return batched_imgs, batched_targets
218
+
219
+
220
+ def mkdir(path):
221
+ try:
222
+ os.makedirs(path)
223
+ except OSError as e:
224
+ if e.errno != errno.EEXIST:
225
+ raise
226
+
227
+
228
+ def setup_for_distributed(is_master):
229
+ """
230
+ This function disables printing when not in master process
231
+ """
232
+ import builtins as __builtin__
233
+
234
+ builtin_print = __builtin__.print
235
+
236
+ def print(*args, **kwargs):
237
+ force = kwargs.pop("force", False)
238
+ if is_master or force:
239
+ builtin_print(*args, **kwargs)
240
+
241
+ __builtin__.print = print
242
+
243
+
244
+ def is_dist_avail_and_initialized():
245
+ if not dist.is_available():
246
+ return False
247
+ if not dist.is_initialized():
248
+ return False
249
+ return True
250
+
251
+
252
+ def get_world_size():
253
+ if not is_dist_avail_and_initialized():
254
+ return 1
255
+ return dist.get_world_size()
256
+
257
+
258
+ def get_rank():
259
+ if not is_dist_avail_and_initialized():
260
+ return 0
261
+ return dist.get_rank()
262
+
263
+
264
+ def is_main_process():
265
+ return get_rank() == 0
266
+
267
+
268
+ def save_on_master(*args, **kwargs):
269
+ if is_main_process():
270
+ torch.save(*args, **kwargs)
271
+
272
+
273
+ def init_distributed_mode(args):
274
+ if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
275
+ args.rank = int(os.environ["RANK"])
276
+ args.world_size = int(os.environ["WORLD_SIZE"])
277
+ args.gpu = int(os.environ["LOCAL_RANK"])
278
+ elif "SLURM_PROCID" in os.environ:
279
+ args.rank = int(os.environ["SLURM_PROCID"])
280
+ args.gpu = args.rank % torch.cuda.device_count()
281
+ elif hasattr(args, "rank"):
282
+ pass
283
+ else:
284
+ print("Not using distributed mode")
285
+ args.distributed = False
286
+ return
287
+
288
+ args.distributed = True
289
+
290
+ torch.cuda.set_device(args.gpu)
291
+ args.dist_backend = "nccl"
292
+ print(f"| distributed init (rank {args.rank}): {args.dist_url}", flush=True)
293
+ torch.distributed.init_process_group(
294
+ backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank
295
+ )
296
+ torch.distributed.barrier()
297
+ setup_for_distributed(args.rank == 0)
298
+
299
+
300
+ def reduce_across_processes(val):
301
+ if not is_dist_avail_and_initialized():
302
+ # nothing to sync, but we still convert to tensor for consistency with the distributed case.
303
+ return torch.tensor(val)
304
+
305
+ t = torch.tensor(val, device="cuda")
306
+ dist.barrier()
307
+ dist.all_reduce(t)
308
+ return t