Exemple #1
0
 def takeshifts(self, k, j):
     n = self.fgridshape[0]//2
     shifts = cp.zeros(
         [self.nangles, self.boxshape.shape[0], 2], dtype='float32')
     for ang in range(self.nangles):
         for l in range(self.boxshape.shape[0]):
             # use any point in the box [-8,-12] - example
             xrm = cp.array(
                 [[-8/self.boxshape[l, 0], -12/self.boxshape[l, 1]]])
             xrm1 = xrm.copy()
             # switch to the first box coordinate system
             xrm = util.rotate(xrm, self.theta[ang])
             xrm += cp.array([[0.5*k, 0.5*j]])
             xrm = util.rotate(xrm, -self.theta[ang])
             xrm[0, 0] *= self.boxshape[l, 0]
             xrm[0, 1] *= self.boxshape[l, 1]
             # find closest point in the first region
             xrm = cp.round(xrm)
             #print(f'{ang},{l},closest point in the first box {xrm=}')
             # return to the current box coordinate system
             xrm[0, 0] /= self.boxshape[l, 0]
             xrm[0, 1] /= self.boxshape[l, 1]
             xrm = util.rotate(xrm, self.theta[ang])
             xrm -= cp.array([[0.5*k, 0.5*j]])
             xrm = util.rotate(xrm, -self.theta[ang])
             # shift in space
             shifts[ang, l] = xrm[0]-xrm1[0]
     return shifts
def round(x: Array, /) -> Array:
    """
    Array API compatible wrapper for :py:func:`np.round <numpy.round>`.

    See its docstring for more information.
    """
    if x.dtype not in _numeric_dtypes:
        raise TypeError("Only numeric dtypes are allowed in round")
    return Array._new(np.round(x._array))
Exemple #3
0
 def mergecoeffs(self,coeffs):
     for l in range(self.boxshape.shape[0]):
         y = cp.arange(-self.boxshape[l, 0]//2,self.boxshape[l, 0]//2)/self.boxshape[l, 0]
         x = cp.arange(-self.boxshape[l, 1]//2,self.boxshape[l, 1]//2)/self.boxshape[l, 1]
         [y, x] = cp.meshgrid(y, x, indexing='ij')
         yx = cp.array([y.flatten(), x.flatten()]).astype('float32').swapaxes(0, 1)
         # create a big array for all coeffs with coordinates of the first region
         coeffsall = np.zeros([len(coeffs)*len(coeffs[0])*self.boxshape[l, 0], len(
             coeffs)*len(coeffs[0])*self.boxshape[l, 1]], dtype='complex64')# could be done smaller
         for ang in range(self.nangles):                
             # fill the big array
             coeffsall[:] = 0
             for k in range(len(coeffs)):
                 for j in range(len(coeffs[0])):
                     # switch to the first box coordinate system
                     xrm = util.rotate(yx, self.theta[ang])
                     xrm += cp.array([[0.5*k, 0.5*j]])
                     xrm = util.rotate(xrm, -self.theta[ang])
                     xrm[:, 0] *= self.boxshape[l, 0]
                     xrm[:, 1] *= self.boxshape[l, 1]
                     # find closest point in the first region
                     xrm = cp.round(xrm).astype('int32').get()                        
                     coeffsall[coeffsall.shape[0]//2+xrm[:, 0],
                               coeffsall.shape[1]//2+xrm[:, 1]] += coeffs[k][j][l][ang].flatten()
             # broadcast from the big array                                  
             for k in range(len(coeffs)):
                 for j in range(len(coeffs[0])):
                     xrm = util.rotate(yx, self.theta[ang])
                     # switch to the first box coordinate system                        
                     xrm += cp.array([[0.5*k, 0.5*j]])
                     xrm = util.rotate(xrm, -self.theta[ang])
                     xrm[:, 0] *= self.boxshape[l, 0]
                     xrm[:, 1] *= self.boxshape[l, 1]
                     # find closest point in the first region
                     xrm = cp.round(xrm).astype('int32').get()
                     coeffs[k][j][l][ang] = coeffsall[coeffsall.shape[0]//2+xrm[:, 0],coeffsall.shape[1]//2+xrm[:, 1]].reshape(self.boxshape[l]) 
     return coeffs                
Exemple #4
0
    accuracy = 0
    now = time.time()
    for sample in range(samples):
        loss, dW1, dW2, dW3 = train(Xtr2[sample], W1, W2, W3, pad)
#        print("\nnp.sum(np.abs(dW1)): %s" % np.sum(np.abs(dW1)))
#        print("np.sum(np.abs(dW2)): %s" % np.sum(np.abs(dW2)))
#        print("np.sum(np.abs(dW3)): %s" % np.sum(np.abs(dW3)))
#        print("Propability of correct class: %s" % probs[sample, Ytr[sample]])
        accuracy += probs[sample, Ytr[sample]]
        data_loss += loss
        W1 -= dW1 * 20 * learning_rate
        W2 -= dW2 * learning_rate
        W3 -= dW3 * learning_rate
    
    cifar10.plotWeights(W1)
    print("Epoch %s took %ss" % (epoch, np.round(time.time() - now, 2)))

    accuracy_over_time.append(accuracy/samples)
    data_loss /= samples
    loss_over_time.append(data_loss)
#    print("\nData Loss: %s" % data_loss)
    dscores = np.copy(probs)
    dscores[range(samples), Ytr[:samples]] -= 1
    # print("dscores:\n%s" % np.round(dscores, 3))
    if(epoch > 7 & epoch % 5 == 0):
        learning_rate *= 0.5

plt.figure(1)
plt.grid(True)
plt.plot(np.arange(len(loss_over_time)), loss_over_time, '-',
         label='data_loss')
Exemple #5
0
def soft_mask(v, voxel_size, num_subunit_residues,
              helical_repeat_distance=None, repeats_to_include=0,
              filter_resolution=20, expansion_factor=1.2, 
              expansion_radius=0, print_progress=True, return_mask=False):

    full_expansion_radius = expansion_radius + filter_resolution/2

# avg AA mol wt. in g/mol, density in g/cm3
    avg_aa_molwt = 110
    protein_density = 1.4

# 2
    print helical_repeat_distance
    v_thresh = np.zeros(v.shape)
    v_thresh[:] = v[:]

    sz = np.array(v.shape).astype(int)

    total_molwt = num_subunit_residues*avg_aa_molwt/6.023e23
    if helical_repeat_distance != None:
        total_molwt = total_molwt * sz[2]*voxel_size / helical_repeat_distance
    total_vol = np.prod(sz) * voxel_size**3                  # vol in A3
    mol_vol = total_molwt/protein_density / (1.0e-24)        # vol in A3
    mol_vol_frac = mol_vol/total_vol
    target_vol_frac = mol_vol_frac*expansion_factor

    thresh = find_binary_threshold(v_thresh, target_vol_frac)
    true_frac = (0.0 + np.sum(v_thresh >= thresh)) / v_thresh.size

    if repeats_to_include != 0:
        zdim = np.round(repeats_to_include * helical_repeat_distance/voxel_size)
    else:
        zdim = sz[2]

    if zdim > sz[2] - 4*np.ceil(filter_resolution/voxel_size):
        zdim = sz[2] - 4*np.ceil(filter_resolution/voxel_size)

    zdim = zdim.astype(int)

    v_thresh[:,:,0:np.floor(sz[2]/2).astype(int) - np.floor(zdim/2).astype(int)] = 0
    v_thresh[:,:,np.floor(sz[2]/2).astype(int) - np.floor(zdim/2).astype(int) + 1 + zdim - 1:] = 0
    v_thresh[v_thresh < thresh] = 0

    if print_progress:
        print 'Target volume fraction: {}'.format(target_vol_frac)
        print 'Achieved volume fraction: {}'.format(true_frac)
        print 'Designated threshold: {}'.format(thresh)

    progress_bar = tqdm(total=5)

    v_thresh = fftpack.fftn(v_thresh)
    progress_bar.update(1)
# 3
    cosmask_filter = np.fft.fftshift(spherical_cosmask(sz, 0, np.ceil(filter_resolution/voxel_size)))
    cosmask_filter = fftpack.fftn(cosmask_filter) / np.sum(cosmask_filter)
    progress_bar.update(1)

    v_thresh = v_thresh * cosmask_filter
    v_thresh = fftpack.ifftn(v_thresh)
    progress_bar.update(1)
    v_thresh = np.real(v_thresh)
    v_thresh[np.abs(v_thresh) < 10*np.finfo(type(v_thresh.ravel()[0])).eps] = 0

    v_thresh[v_thresh != 0] = 1

# The extent of blurring is equal to the diameter of the cosmask sphere; 
#  if we want this to equal the expected falloff for filter_resolution, 
#  we therefore need to divide filter_res by 4 to get the 
#  desired radius for spherical_cosmask.

    v_thresh = fftpack.fftn(v_thresh)
    progress_bar.update(1)

    v_thresh = v_thresh * cosmask_filter
    v_thresh = fftpack.ifftn(v_thresh)
    progress_bar.update(1)
    v_thresh = np.real(v_thresh)
    v_thresh[np.abs(v_thresh) < 10*np.finfo(type(v_thresh.ravel()[0])).eps] = 0

    if return_mask:
        v[:,:,:] = v_thresh
    else:
        v *= v_thresh

    return v_thresh
Exemple #6
0
def Calc(field_data, P1, P2, pulse_info_list):
    """
    main calc
    P : sound pressure
    n : time step
    i : x-axis
    j : y-axis
    d : density
    v : sound speed
    dx : spatial resolution
    dt : time resolution

    P[n+1](i,j) = 2P[n](i,j) - P[n-1](i,j)+d(i,j)*(v(i,j)**2*dt**2/dx**2)
    """
    tim = 0
    width = field_data.width
    height = field_data.height
    if gpu_flag:
        density = cp.round(field_data.density_arr, 2)
        alpha = cp.round((sound_speed_list["air"] * dt / dx) ** 2, 2)
    else:
        density = np.round(field_data.density_arr, 2)
        alpha = np.round((sound_speed_list["air"] * dt / dx) ** 2, 2)
    velocity = field_data.velocity_arr
    # alpha = np.round((velocity[1:width - 1, 1:height - 1] * dt / dx)** 2, 2)

    BAT = bat.Bat()
    # test
    directivity_list = []
    for pulse_info in pulse_info_list:
        print(f"-----calc with emit pulse{pulse_info}-----")
        receive_points = BAT.set_position(pulse_info)
        time_start = time.perf_counter()
        ims = []
        tim_list = []
        emit_list = []
        for i in range(nmax):
            print("step:{}".format(i))
            P2 = BAT.emit_pulse(i, P2, density)
            # if i < sig_duration:
            #     P2[pulse_info[0], pulse_info[1]
            #        ] = P2[pulse_info[0], pulse_info[1]] + sig

            P1[1:width - 1, 1:height - 1] = (
                2*P2[1:width - 1, 1:height - 1]
                - P1[1:width - 1, 1:height - 1]
                + alpha * density[1:width - 1, 1:height - 1]
                * (P2[2:width, 1: height - 1]/density[2:width, 1: height - 1]
                   + P2[: width - 2, 1: height - 1] /
                   density[: width - 2, 1: height - 1]
                   + P2[1: width - 1, 2:height]/density[1: width - 1, 2:height]
                   + P2[1: width - 1, : height - 2] /
                   density[1: width - 1, : height - 2]
                   )
                - 4 * alpha * P2[1: width - 1, 1: height - 1]
            )
            P1 = field_data.update(P2, P1)
            BAT.get_echo(P1, P2, density)
            tim_list.append(i * dt)
            emit_list.append(P2[pulse_info[0], pulse_info[1]])
            if debug_flag and i % savestep == 0:
                im = MakeFigure(P1, pulse_info, receive_points, field_data)
                ims.append([im])
            P1, P2 = P2, P1
        with open(f"{pulse_info}.csv", "w") as f:
            writer = csv.writer(f)
            writer.writerow(["time", "emit", "right_echo", "left_echo"])
            tim_list = np.array(tim_list)[:, np.newaxis]
            emit_list = np.array(emit_list)[:, np.newaxis]
            echo_r = np.array(BAT.echo_right_ear)[:, np.newaxis]
            echo_l = np.array(BAT.echo_left_ear)[:, np.newaxis]
            target_data = np.hstack([tim_list, emit_list, echo_r, echo_l])
            writer.writerows(target_data)
        time_end = time.perf_counter()
        tim = time_end - time_start
        print(f"calc time:{np.round(tim,2)}[s]")
        # plt.plot(BAT.echo_right_ear, label=f"{pulse_info[2]}")

        # directivity test
        # directivity_list.append([pulse_info[2], np.nanmax(BAT.echo_right_ear)])
        # plt.plot(BAT.echo_left_ear, label="p1")
        # plt.plot(receive_test)
        ims_list.append(ims)
    # plt.plot(receive_left)
    # plt.show()
    # emit_power = max(abs(np.array(receive_points[-1])))
    # for idx, receive_point in enumerate(receive_points[:-1]):
    #     recived_wave_arr = abs(np.array(receive_point))
    #     recived_wave_max = max(recived_wave_arr)
    #     recived_wave_log = 20 * np.log(recived_wave_arr / emit_power)
    #     recived_max_log = 20 * np.log(recived_wave_max / emit_power)
    #     plt.scatter(N_list[idx][0], recived_max_log, label=f"{idx}")

    # # plt.ylim(-200, 0)
    # # plt.subplots_adjust(right=0.1)
    # plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)
    # plt.xlabel("N")
    # plt.ylabel("P [dB]")
    # plt.savefig("recived_wave_diffraction_N.png",bbox_inches='tight', pad_inches=0)
    # plt.plot(BAT.echo_left_ear, label="no_directivity")

    # # test
    # ax1 = plt.subplot(111, projection="polar")
    # ax1.set_theta_direction(-1)
    # ax1.set_rlabel_position(0)
    # ax1.set_xticks(np.pi / 180. * np.linspace(0, 360, 12, endpoint=False))
    # ax1.spines['polar'].set_color('darkgray')
    # # plt.ylim(-60.1, 5)
    # for directivity_data in directivity_list:
    #     ax1.scatter(directivity_data[0] * np.pi / 180, directivity_data[1])
    # plt.rcParams['font.family'] = 'Times New Roman'
    # plt.rcParams['font.size'] = 12
    # plt.legend()
    # plt.show()
    # plt.savefig("echo.png")
    return ims_list
Exemple #7
0
 def round(val):
     return cp.round(val)
Exemple #8
0
    def filter(self,eventpackage, compelted, lastposition):
        #if self.davisT[-1] < (self.LEDT[-1] + self.slidestep/2):
        #    return
        #else:
        #EventStream = [eventX,eventY,eventT,eventPol,eventPixel,eventOccurrence]
        eventX = eventpackage[0]
        eventY = eventpackage[1]
        eventT = eventpackage[2]
        eventPol = eventpackage[3]
        eventPixel = eventpackage[4]
        noisePixel = eventpackage[6]
        #eventOccurrence = EventStream[:,6]
        if (compelted >= 10):
            self.evidTime = cp.ones(shape=(self.xPixelResol,self.yPixelResol))*self.initEvid
        for pixel in eventPixel:
            if (compelted >= 10)and(cp.linalg.norm(pixel-lastposition) >= 25)and(self.lostflag == 0):
                self.evidTime[pixel[0], pixel[1]] = 0
                continue
                #pass
            pixelPol = eventPol[(eventX == pixel[0])&(eventY == pixel[1])]
            pixelT = eventT[(eventX == pixel[0])&(eventY == pixel[1])]
            pixelState = cp.append(self.state[pixel[0], pixel[1]], pixelPol[0:-1])
            self.state[pixel[0], pixel[1]] = pixelPol[-1]

            transition = pixelPol[1:] - pixelPol[0:-1]
            trans01time = pixelT[cp.append(cp.array([False]),transition==1)]
            trans10time = pixelT[cp.append(cp.array([False]),transition==-1)]
            hyperInterval = cp.append(trans01time[1:]-trans01time[0:-1],trans10time[1:]-trans10time[0:-1])

            if len(hyperInterval)==0:
                continue
            '''
            if len(pixelTransTime) == 1:
                pixelLastTime = cp.array([self.lastTransTime[pixel[0], pixel[1], pixelPol[transition][0]]])
                self.lastTransTime[pixel[0], pixel[1], pixelPol[transition][0]] = pixelTransTime[0]
            elif len(pixelTransTime) > 1:
                pixelLastTime = cp.append([self.lastTransTime[pixel[0], pixel[1], pixelPol[transition][0]], self.lastTransTime[pixel[0], pixel[1], pixelPol[transition][1]]], pixelTransTime[0:-2])
                self.lastTransTime[pixel[0], pixel[1], [pixelPol[transition][-2], pixelPol[transition][-1]]] = pixelTransTime[[-2, -1]]
                hyperInterval = pixelTransTime - pixelLastTime
            '''
            tmpInterval = self.covarLEDInterval - abs(hyperInterval - self.meanInterval)
            #indLED = tmpInterval > 0 #Intervals which locate between mean-covar and mean+covar are valid
            hyperInterval = cp.delete(hyperInterval,cp.where(tmpInterval <= 0))
            self.evidTime[pixel[0], pixel[1]] = self.evidTime[pixel[0], pixel[1]] + cp.sum(100/(cp.sqrt(2*cp.pi)*self.covarLEDInterval)*cp.exp((hyperInterval - self.meanInterval)**2/(-2*self.covarLEDInterval**2)))
            #self.evidTime[pixel[0], pixel[1]] = self.evidTime[pixel[0], pixel[1]] + cp.sum(indLED*((self.meanLEDPeakRatio*tmpInterval)/self.covarLEDInterval))#sustitute triangle for normal distribution

        tmpEvid = self.evidTime
        tmpEvid[noisePixel[:,0],noisePixel[:,1]] = self.initEvid
        self.evidTime = tmpEvid
        self.weightParticleTime = self.evidTime[self.setParticleCoord[:,0].astype(cp.int64),self.setParticleCoord[:,1].astype(cp.int64)]   
        sumWeightParticleTime = cp.sum(self.weightParticle, 0)
        #print(sumWeightParticleTime)
        
        indResample = 0.5 > sumWeightParticleTime
        if indResample:
            tmpIndValidPixel = cp.array(cp.where(self.evidTime>self.initEvid))
            tmpRaw = tmpIndValidPixel[0,:]
            tmpCol = tmpIndValidPixel[1,:]
            tmpIndLowWeight = cp.argsort(self.weightParticleTime)
            tmpIndLowWeight = cp.delete(tmpIndLowWeight,cp.arange(len(tmpRaw),len(tmpIndLowWeight)))
            self.setParticleCoord[tmpIndLowWeight,0] = tmpRaw
            self.setParticleCoord[tmpIndLowWeight,1] = tmpCol
            self.weightParticleTime[tmpIndLowWeight] = self.evidTime[tmpIndValidPixel[0],tmpIndValidPixel[1]]
            self.weightParticleLast = self.initWeight
        
        self.weightParticleTime = self.weightParticleTime/cp.sum(self.weightParticleTime)
       
        
        self.weightParticle = self.weightParticleLast * (self.weightParticleTime)
        self.weightParticle = self.weightParticle / cp.sum(self.weightParticle, 0)
        
        if 1/cp.sum(self.weightParticle**2) < self.resampleRatio*self.numParticles:
            index = cp.arange(2000)
            tmpIndParticle = cp.random.choice(a=index, size=self.numParticles, replace=True, p=self.weightParticle)
            self.weightParticle = self.initWeight
            self.setParticleCoord = self.setParticleCoord[tmpIndParticle.astype(cp.int64)]
        
        self.LEDPosition[0] = cp.sum(self.weightParticle*self.setParticleCoord[:,0])
        self.LEDPosition[1] = cp.sum(self.weightParticle*self.setParticleCoord[:,1])
        self.setParticleCoord = self.setParticleCoord + cp.random.normal(0,3, (self.numParticles,2))
        tmpSetParticleCoord = cp.round(self.setParticleCoord[:,0])
        tmpSetParticleCoord[tmpSetParticleCoord > (self.xPixelResol - 1)] = self.xPixelResol - 1
        self.setParticleCoord[:, 0] = tmpSetParticleCoord
        tmpSetParticleCoord = cp.round(self.setParticleCoord[:, 1])
        tmpSetParticleCoord[tmpSetParticleCoord > (self.yPixelResol - 1)] = self.yPixelResol - 1
        self.setParticleCoord[:, 1] = tmpSetParticleCoord
        self.setParticle = self.setParticleCoord[:, 0] * self.yPixelResol + self.setParticleCoord[:, 1]
        self.weightParticleLast = self.weightParticle
        self.lost[1:] = self.lost[:-1]
        self.lost[0] = cp.linalg.norm(self.LEDPosition-lastposition) <= 2
        if ((cp.sum(self.lost))>2):
            #self.lostflag = 1
            pass