File size: 10,921 Bytes
c5973f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
# coding: utf-8

import numpy as np
import h5py
import argparse
import random
import shutil
import os
import scipy.interpolate as si

from scipy.signal import gaussian
from itertools import product

from typing import Tuple

def generate_sound_speed(shape = [1152, 512],
        c_ref: float = 1500., c_min: float = 1300., c_max: float = 1800.,
        atn_min: float = 0.05, atn_max: float = 0.15,
        max_ell: int = 6, max_lines: int = 4) -> Tuple[np.ndarray, np.ndarray]:
    """[summary]
    Generate a random speed of sound and attenuation map with up to max_ell ellipses and max_lines straight reflectors

    Args:
        shape (list, optional): [description]. Defaults to [1152, 512].
        c_ref (float, optional): [description]. Defaults to 1500..
        c_min (float, optional): [description]. Defaults to 1300..
        c_max (float, optional): [description]. Defaults to 1800..
        atn_min (float, optional): [description]. Defaults to 0.05.
        atn_max (float, optional): [description]. Defaults to 0.15.
        max_ell (int, optional): [description]. Defaults to 6.
        max_lines (int, optional): [description]. Defaults to 4.

    Returns:
        [type]: [description]
    """

    while True:
        n_ell = np.random.randint(max_ell + 1)
        n_lines = np.random.randint(max_lines + 1)

        if n_ell + n_lines > 0:
            break

    ell_type = np.array([0,] * n_ell + [1,] * n_lines)[np.random.permutation(n_ell + n_lines)]
    c = np.random.rand(n_ell + n_lines + 1) * (c_max - c_min) + c_min
    atn = np.random.rand(n_ell + n_lines + 1) * (atn_max - atn_min) + atn_min

    ell_params = np.random.rand(5, n_ell); # x0, y0, a, b, \theta in columns

    ell_params[0, :] = ell_params[0, :] * shape[-1]
    ell_params[1, :] = ell_params[1, :] * shape[-2]
    ell_params[2, :] = ell_params[2, :] * shape[-1];
    ell_params[3, :] = ell_params[3, :] * shape[-2];
    ell_params[4, :] = (ell_params[4, :] - 0.5) * np.pi / 4;

    line_params = np.random.rand(2, n_lines); # Angle and offset

    line_params[0, :] = (line_params[0, :] - 0.5) * np.pi / 6;
    line_params[1, :] = line_params[1, :] * (shape[-2] - 68) + 68

    sound_speed = np.empty(shape[-2:], dtype=np.single)
    sound_speed[...] = c[-1]
    alpha_coeff = np.empty(shape[-2:], dtype=np.single)
    alpha_coeff[...] = atn[-1]

    i_ellp = 0
    i_lines = 0

    X, Y = np.meshgrid(range(shape[-1]), range(shape[-2]))

    for i,t in enumerate(ell_type):
        if t == 0:
            # elipse
            x0 = np.array([ell_params[0, i_ellp], ell_params[1, i_ellp]])
            a  = np.array([ell_params[2, i_ellp], ell_params[3, i_ellp]])

            th = ell_params[4, i_ellp]
            ath = np.abs(th)

            R = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])
            aR = np.array([[np.cos(ath), -np.sin(ath)], [np.sin(ath), np.cos(ath)]])

            toff = aR.dot(a)[1]

            if x0[1] - toff < 68:
                x0[1] = 68 + toff

            x = X - x0[0]
            y = Y - x0[1]

            u = np.cos(th) * x - np.sin(th) * y
            v = np.sin(th) * x + np.cos(th) * y

            sound_speed[(u / ell_params[2, i_ellp]) ** 2 + (v / min(ell_params[3, i_ellp], ell_params[1, i_ellp] - 68)) ** 2 < 1] = c[i]
            alpha_coeff[(u / ell_params[2, i_ellp]) ** 2 + (v / min(ell_params[3, i_ellp], ell_params[1, i_ellp] - 68)) ** 2 < 1] = atn[i]

            i_ellp += 1
        else:
            # plane
            th =  line_params[0, i_lines]
            off = line_params[1, i_lines]

            if off - shape[-1] * np.tan(np.abs(th)) < 68:
                off = shape[-1] * np.tan(np.abs(th)) + 68

            sound_speed[X * np.sin(th) + (Y - off) * np.cos(th) > 0] = c[i]
            alpha_coeff[X * np.sin(th) + (Y - off) * np.cos(th) > 0] = atn[i]

            i_lines += 1

    return sound_speed, alpha_coeff


def generate_density(shape: tuple = [1152, 1152],
    d_ref: float = 900.,
    n_spec: float = -1.,
    spec_amp: float = 0.1) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Generate a speckle map in the density domain, including the x and y derivatives


    Args:
        shape (_type_, optional): shape of output map. Defaults to [1152, 1152]
        d_ref (float, optional): reference density (kg / m^3). Defaults to 900
        n_spec (float, optional): speckle density. Defaults to -1
        spec_amp (float, optional): speckle amplitude. Defaults to 0.1

    Returns:
        _type_: _description_
    """

    if n_spec < 0:
        n_spec = shape[-1] * shape[-2] * (2. / 64.)

    t_n_spec = int(np.round(n_spec * (10 - np.random.rand() * 8) * 0.1))

    speckle = np.zeros((shape[-2] - 48 - 68, shape[-1] - 48*2), np.single)
    speckle.reshape(-1,1)[np.random.permutation(speckle.size)[:t_n_spec]] = d_ref * (np.random.rand(t_n_spec, 1) - 1/3) * spec_amp

    rho0 = np.empty(shape[-2:], dtype=np.single)
    rho0[...] = d_ref

    rho0[68:-48, 48:-48] += speckle

    rho0_sgx = np.empty_like(rho0)
    rho0_sgx[:,:-1] = (rho0[:,:-1] + rho0[:,1:]) * 0.5
    rho0_sgx[:,-1] = rho0[:,-1]

    rho0_sgy = np.empty_like(rho0)
    rho0_sgy[:-1,:] = (rho0[:-1,:] + rho0[1:,:]) * 0.5
    rho0_sgy[-1,:] = rho0[-1,:]

    return rho0, rho0_sgx, rho0_sgy


def generate_pulse(center_freq=5e6, n_periods=4.4, sampling_freq=40e6):
        samples_per_cycle = sampling_freq / center_freq
        n_samples = np.ceil(samples_per_cycle * n_periods + 1)

        signal = np.sin(np.arange(n_samples, dtype=np.float32) / samples_per_cycle * 2 * np.pi) * gaussian(n_samples, (n_samples - 1) / 6).astype(np.single)

        return signal


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('input', help='reference file')
    parser.add_argument('--device',      '-d', type=int, default=0, help='cuda device to use')
    parser.add_argument('--frequencies', '-f', type=float, nargs='+', default=[5e6, 2.5e6],
        help='at which frequencies to run the simulation')
    parser.add_argument('--offsets',     '-o', type=int, nargs='+', default=[-32, -24, -16, -8, 0, 8, 16, 24, 32],
        help='list of (signed) offsets to use with respect to center, in elements. Angles will be calculated from offsets')
    parser.add_argument('--n_periods', '-p', type=float, default=5.0,
        help='how many periods to use for the pulse')
    parser.add_argument('--ref_offset',  '-r', type=int, default=59 * 1152 + (1152 - (128 + 127) * 4) // 2 + 32 * 2 * 4,
        help='reference offset in entries (where to start offset 0) - default: line 60, element 33, remember the kerf')
    parser.add_argument('--ref_speed',  '-s', type=float, default=1540,
        help='reference speed under which to computer angle')

    args = parser.parse_args()

    hash = f'{random.getrandbits(128):x}'

    tmp_input = f'tmp_input_{hash}.h5'
    tmp_output = f'tmp_output_{hash}.h5'
    sim_result = f'sim_result_{hash}.h5'

    # costs an additional copy but solves problem of opening file multiple times in parallel
    shutil.copyfile(args.input, tmp_input)

    try:
        with h5py.File(tmp_input, 'r+') as f_i:
            shape = np.squeeze(f_i['c0'][()]).shape
            dt = f_i['dt'][0,0,0]
            dx = f_i['dx'][0,0,0]

            c0, alpha_coeff = generate_sound_speed(shape)
            rho0, rho0_sgx, rho0_sgy = generate_density(shape)

            f_i['c0'][...] = c0
            f_i['alpha_coeff'][...] = alpha_coeff

            f_i['rho0'][...] = rho0
            f_i['rho0_sgx'][...] = rho0_sgx
            f_i['rho0_sgy'][...] = rho0_sgy

            # # Also record receive traces
            # smi = np.tile(np.array(f_i['sensor_mask_index']), (1,1,2))
            # smi[...,smi.shape[-1]//2:] += 1152 * (1152 - 60)
            # del f_i['sensor_mask_index']
            # f_i["sensor_mask_index"] = smi
            # f_i["sensor_mask_index"].attrs["data_type"] = np.string_(b"long")
            # f_i["sensor_mask_index"].attrs["domain_type"] = np.string_(b"real")

        with h5py.File(sim_result, 'w') as f_o:
            f_o.create_dataset(f'c0', data=c0, compression="gzip", compression_opts=9)
            f_o.create_dataset(f'alpha_coeff', data=alpha_coeff, compression="gzip", compression_opts=9)
            f_o.create_dataset(f'f', data=np.array(args.frequencies))
            f_o.create_dataset(f'offsets', data=np.array(args.offsets))

        for frequency, offset in product(args.frequencies, args.offsets):
            # TODO: deal with offsets / angles
            w = 127 * 4
            o = offset * 8
            dn = w * o / np.sqrt(64 * o ** 2 + 4 * w ** 2) * (dx / dt) / args.ref_speed

            pulse = generate_pulse(center_freq=frequency, n_periods=args.n_periods, sampling_freq=1.0/dt) * 1e-7

            signal = np.zeros((1, int(np.ceil(np.abs(dn))) + len(pulse), 127 * 4), dtype=np.single)
            for i in range(127 * 4):
                signal[0, int(np.round(-dn * i / 507 if o < 0 else dn - dn * i / 507)) + np.arange(len(pulse)), i] = pulse

            with h5py.File(tmp_input, 'r+') as f_i:
                del f_i["u_source_index"]
                f_i["u_source_index"] = (np.arange((64 + 63) * 4, dtype=np.uint64) + args.ref_offset + offset * 8).reshape(1, 1, -1).astype(np.uint64)
                f_i["u_source_index"].attrs["data_type"] = np.string_(b"long")
                f_i["u_source_index"].attrs["domain_type"] = np.string_(b"real")

                del f_i["uy_source_input"]
                f_i["uy_source_input"] = signal
                f_i["uy_source_input"].attrs["data_type"] = np.string_(b"float")
                f_i["uy_source_input"].attrs["domain_type"] = np.string_(b"real")

                f_i["uy_source_flag"][:] = signal.shape[1]

            os.system(f'../../scripts/kspaceFirstOrder-CUDA -r 20 -t 8 -g {args.device} -i {tmp_input} -o {tmp_output}')

            with h5py.File(tmp_output, 'r+') as f_t:
                p = np.squeeze(f_t['p'][()]).T

            p = 0.35 * (p[0::4,:] + p[3::4,:]) + 0.95 * (p[1::4,:] + p[2::4,:])
            T = (p.shape[1] - 1) * dt

            x_orig = np.linspace(0,T,p.shape[1])
            x_out = np.arange(0,T,1/40e6)

            p_out = si.interp1d(x_orig, p, kind='linear', copy=False, bounds_error=False, fill_value=0, assume_sorted=True)(x_out).astype(np.float32)

            with h5py.File(sim_result, 'r+') as f_o:
                f_o.create_dataset(f'p_f{frequency/1e6}_o{offset}', data=p_out, compression="gzip", compression_opts=9)
    except Exception as e:
        print(f"Error : {e.args[0]}")
        os.system(f'rm {sim_result}')

    try:
        os.system(f'rm {tmp_input}')
    except Exception as e:
        print(f"Error removing {tmp_input} : {e.args[0]}")

    try:
        os.system(f'rm {tmp_output}')
    except Exception as e:
        print(f"Error removing {tmp_output} : {e.args[0]}")