Exemple #1
0
def check():
    """Settings"""
    """====================================================================="""
    new_dir = '../../../Data/invivo_converse/'
    setname = 'test1'
    filenum = 700  #less than 2400 if setname=='train', else less than 800
    """====================================================================="""

    startnum = {'train': 0, 'val': 2400, 'test1': 3200, 'test2': 4000}[setname]
    Dname,Sname,Lname=['Patch','S_est_f','L_est_f'] if setname=='test2'\
                    else ['patch_180','patch_180','patch_180']
    filenum = filenum + startnum
    player = Player()

    D = loadmat('%s/D_data/%s/D%d.mat' % (new_dir, setname, filenum))[Dname]
    S = loadmat('%s/fista/%s/S_fista%d.mat' %
                (new_dir, setname, filenum))[Sname]
    L = loadmat('%s/fista/%s/L_fista%d.mat' %
                (new_dir, setname, filenum))[Lname]
    D = D.reshape([32, 32, 20])
    S = S.reshape([32, 32, 20])
    L = L.reshape([32, 32, 20])

    player.play([D, S, L])
Exemple #2
0
# zTissue=ZoneTissue()
# 
# T=30
# shape=params_default['shape']
# Tissue=np.zeros([shape[0],shape[1],T],dtype=np.complex128)
# 
# for i in range(T):
#     Tissue[:,:,i]=zTissue.image()
#     zTissue.refresh()
#     
# player.play([Tissue])
# =============================================================================
params=params_default
params['shape']=(128,128)
sim=Simulator(params)
T=50

Sum,Bubbles,Tissues=sim.generate(T)

# =============================================================================
# Sum=Sum[0:32,0:32,:]
# Bubbles=Bubbles[0:32,0:32,:]
# Tissues=Tissues[0:32,0:32,:]
# 
# =============================================================================
player.play([Sum,Bubbles,Tissues],cmap='hot',note='abs')
#player.play([Sum],cmap='hot')
ang=np.unwrap(np.angle(Sum)*180/np.pi)


Exemple #3
0
cmap='hot'
"""========================================================================="""

#load model
net=ResNet3dC(gpu)

#device='cuda:0' if torch.cuda.is_available() else 'cpu'
device='cpu'
if mfile[-3:]=='pkl':
    state_dict=torch.load(mfile,map_location=device)
    #state_dict=delitems(state_dict)
    net.load_state_dict(state_dict)
else:
    net=torch.load(mfile)

#process        
process_dataset(net,data_dir,setname,patch_dir)
#display
if display:
    startnum={'train':0,'val':2400,'test1':3200,'test2':4000}[setname]
    Dname='Patch' if setname=='test2' else 'patch_180'
    D=loadmat('%s/D_data/%s/D%d.mat'%(data_dir,setname,startnum))[Dname]
    Si=loadmat('%s/data0.mat'%(patch_dir))['data']
    D=D.reshape([32,32,20])
    Si=Si.reshape([32,32,20])
    
    player=Player()
    player.play([D,Si],tit=['Input','Prediction'],
                cmap=cmap,note=note,minDB=minDB)
    
Exemple #4
0
    net.load_state_dict(state_dict)
else:
    net = torch.load(mfile)

#Processing
D, Sp = process_patch(net, data_dir, arange)
brow, erow, bcol, ecol, bt, et = arange
if Sfile[-3:] == 'mat':
    S = loadmat(Sfile)['vid'][brow:erow, bcol:ecol, bt:et]
else:
    S = np.load(Sfile)['arr_0'][brow:erow, bcol:ecol, bt:et]

#Display
player = Player()
player.play([D, Sp, S],
            cmap=cmap,
            note=note,
            tit=['Input', 'Prediction', 'Fista'])

#save as gif
if saveGif:
    mat2gif([D, Sp, S],
            save_gif_dir,
            cmap=cmap,
            note=note,
            tit=['Input', 'Prediction', 'Fista'],
            play=False)
#save the matrices
if saveMat:
    savemat(save_mat_dir, {'D': D, 'S': S, 'Sp': Sp})
Exemple #5
0
brow, erow, bcol, ecol, bt, et = arange
if Sfile[-3:] == 'mat':
    S = loadmat(Sfile)['vid'][brow:erow, bcol:ecol, bt:et]
else:
    S = np.load(Sfile)['arr_0'][brow:erow, bcol:ecol, bt:et]

if Lfile[-3:] == 'mat':
    L = loadmat(Lfile)['vid'][brow:erow, bcol:ecol, bt:et]
else:
    L = np.load(Lfile)['arr_0'][brow:erow, bcol:ecol, bt:et]

#Display
player = Player()
player.play(
    [D, S, L, None, Sp, Lp],
    cmap=cmap,
    note=note,
    tit=['Input', 'Fista S', 'Fista L', None, 'Prediction S', 'Prediction L'])

#save as gif
if saveGif:
    mat2gif([D, S, L, None, Sp, Lp],
            save_gif_dir,
            cmap=cmap,
            note=note,
            tit=[
                'Input', 'Fista S', 'Fista L', None, 'Prediction S',
                'Prediction L'
            ])
#save the matrices
if saveMat:
Exemple #6
0
    model=UnfoldedNet3dC(params_net)
    state_dict=torch.load(mfile,map_location=device)
    model.load_state_dict(state_dict)
else:
    model=torch.load(mfile)

#Processing
with torch.no_grad():
    data=np.load(data_dir)
    Sum,Bubbles,Tissue=data['arr_0'],data['arr_1'],data['arr_2']
    [Sum]=convert.np2torch([Sum],[form_in])
    predL,predS=model(Sum)
[predL,predS,Sum]=convert.torch2np([predL,predS,Sum],[form_out,form_out,form_out])

#Display
plt.close('all')
player=Player()
player.play([Sum,Bubbles,Tissue,None,predS,predL],note=note,cmap=cmap,
            tit=['Input','Ground Truth S','Ground Truth L',
                 None,'Prediction S','Prediction L'])

#Save gif
if saveGif:
    mat2gif([Sum,Bubbles,Tissue,None,predS,predL],save_gif_dir,
            note=note,cmap=cmap,
            tit=['Input','Ground Truth S','Ground Truth L',
                 None,'Prediction S','Prediction L'])
#Save matrix
if saveMat:
    savemat(save_mat_dir,{'D':Sum,'S':Bubbles,'L':Tissue,
                          'Sp':predS,'Lp':predL})
Exemple #7
0
shape=(128,128)
T=20
params['shape']=shape
rIter=int(shape[0]/32)
cIter=int(shape[1]/32)
player=Player()

nIter=int(numInst/shape[0]/shape[1]/T*32*32*20)

print('total iterations and instances: %d, %d'%(nIter,numInst))
numf=numstart
for i in range(nIter):
    print('current iteration: %d, file number: %d to %d'%(i,numf,numf+rIter*cIter))
    simtor=Simulator(params)
    Sum,Bubbles,Tissue=simtor.generate(T)
    for rr in range(rIter):
        for cc in range(cIter):
            D=Sum[rr*32:(rr+1)*32,cc*32:(cc+1)*32,0:20]
            S=Bubbles[rr*32:(rr+1)*32,cc*32:(cc+1)*32,0:20]
            L=Tissue[rr*32:(rr+1)*32,cc*32:(cc+1)*32,0:20]
            
            savemat(folder+'D_data/%s/D%d.mat'%(setname,numf),{Dname:D.reshape([32*32,20])})
            savemat(folder+'fista/%s/S_fista%d.mat'%(setname,numf),{Sname:S.reshape([32*32,20])})
            savemat(folder+'fista/%s/L_fista%d.mat'%(setname,numf),{Lname:L.reshape([32*32,20])})
            numf+=1
            
player.play([D,S,L],cmap='hot')
            
            

Exemple #8
0
device = 'cpu'
if mfile[-3:] == 'pkl':
    model = ResNet3dC(gpu)
    state_dict = torch.load(mfile, map_location=device)
    model.load_state_dict(state_dict)
else:
    model = torch.load(mfile)

#Processing
with torch.no_grad():
    data = np.load(data_dir)
    Sum, Bubbles = data['arr_0'], data['arr_1']
    [Sum] = convert.np2torch([Sum], [form_in])
    pred = model(Sum)
[predmv, Sum] = convert.torch2np([pred, Sum], [form_out, form_out])

#Display
plt.close('all')
player = Player()
player.play([Sum, predmv, Bubbles], note=note, cmap=cmap)

#Save gif
if saveGif:
    mat2gif([Sum, predmv, Bubbles],
            save_gif_dir,
            note=note,
            cmap=cmap,
            tit=['Input', 'Prediction', 'Ground Truth'])
#Save matrix
if saveMat:
    savemat(save_mat_dir, {'D': Sum, 'S': Bubbles, 'Sp': predmv})
Exemple #9
0
class Main(Process):

    playlist = None
    player = None
    state = None
    pt2314 = None

    channel = 0
    volume = 0
    buttons = 0

    icy_current_song = None

    last_channel = 0
    last_played_channel = 0
    last_volume = 0
    last_buttons = 0

    current_time = 0
    last_channel_changed_time = 0
    last_volume_changed_time = 0
    last_buttons_changed_time = 0
    last_currentsong_time = 0
    last_mpd_poll = 0
    need_save_state = False
    need_change_song = False
    need_change_buttons = False

    screen_size = None
    fps = None
    full_screen = False

    scene = None

    def __init__(self):

        self.screen_size = Config.default_screen_size
        self.fps = Config.fps
        self.full_screen = Config.full_screen

        os.environ["SDL_FBDEV"] = Config.fb_dev

        self.serv = HTTPServer(("0.0.0.0", 8000), HttpProcessor)
        thread = threading.Thread(target=self.serv.serve_forever)
        thread.daemon = True
        thread.start()

        super(Main, self).__init__()

    def begin(self):

        Program.set_mode(self.screen_size, self.full_screen, False)
        Program.set_fps(self.fps)
        pygame.mouse.set_visible(False)

        self.playlist = Playlist()

        self.player = Player()

        self.state = State()

        #print "State volume: {0}".format(self.state.volume)
        #print "State channel: {0}".format(self.state.channel)

        self.encoders_board = EncodersBoard(0x40, 0, 20, self.state.volume, 0,
                                            len(self.playlist.playlist) - 1,
                                            self.state.channel)

        self.pt2314 = PT2314()
        self.pt2314.setVolume(self.state.volume * 5)
        #self.pt2314.setAttenuation(0)
        self.pt2314.setBass(0)
        self.pt2314.setTreble(12)
        self.pt2314.selectChannel(0)
        self.pt2314.loudnessOn()
        self.pt2314.muteOff()
        time.sleep(0.1)

        self.last_volume = self.state.volume
        self.last_channel = self.state.channel
        self.last_played_channel = self.last_channel

        station_url = self.playlist.playlist[self.state.channel].url
        self.player.load("radio")
        self.player.play(self.state.channel)

        self.scene = AppRadio(self)

        while True:
            try:
                micro = self.get_micro()

                self.encoders_board.read()

                self.volume = self.encoders_board.get_value1()
                if self.volume > 20:
                    self.volume = 20
                    self.encoders_board.set_value1(self.volume)
                    self.encoders_board.set_max_value1(self.volume)
                    self.encoders_board.write()

                self.channel = self.encoders_board.get_value2()
                if self.channel > len(self.playlist.playlist) - 1:
                    self.channel = len(self.playlist.playlist) - 1
                    self.encoders_board.set_value2(self.channel)
                    self.encoders_board.set_max_value2(self.channel)
                    self.encoders_board.write()

                self.buttons = self.encoders_board.get_buttons()

                if self.last_volume != self.volume:
                    self.pt2314.setVolume(self.volume * 5)
                    self.last_volume = self.volume
                    self.last_volume_changed_time = micro

                if self.last_channel != self.channel:
                    self.last_channel = self.channel
                    self.last_channel_changed_time = micro

                if self.last_buttons != self.buttons and micro - self.last_buttons_changed_time > 100:
                    self.last_buttons = self.buttons
                    self.last_buttons_changed_time = micro
                    self.need_change_buttons = True

                if self.last_played_channel != self.channel and micro - self.last_channel_changed_time > 1000:
                    self.need_change_song = True

                if self.state.volume != self.volume and micro - self.last_volume_changed_time > 5000:
                    self.state.volume = self.volume
                    self.need_save_state = True

                if self.state.channel != self.channel and micro - self.last_channel_changed_time > 5000:
                    self.state.channel = self.channel
                    self.need_save_state = True

                if micro - self.last_currentsong_time > 1000:
                    self.icy_current_song = self.player.currentsong()
                    #print self.icy_current_song
                    self.last_currentsong_time = micro

                global ring_bell
                if ring_bell:
                    #print "Doorbell detected";
                    ring_bell = False
                    self.player.stop()
                    self.pt2314.setVolume(95)
                    os.system('mplayer ' + Config.bell)
                    time.sleep(0.5)
                    self.pt2314.setVolume(self.volume * 5)
                    self.need_change_song = True

                if self.need_change_song:
                    self.need_change_song = False
                    self.last_played_channel = self.channel
                    time.sleep(0.5)
                    self.player.play(self.channel)

                if self.need_save_state:
                    self.need_save_state = False
                    self.state.save()

                if self.need_change_buttons:
                    self.need_change_buttons = False
                    if (self.last_buttons & Config.BTN_POWER):
                        subprocess.call(["poweroff"])
                    if (self.last_buttons & Config.BTN_ALARM):
                        subprocess.call(["reboot"])

            except Exception:
                pass

            yield

    def get_micro(self):
        return int(round(time.time() * 1000))

    def get_current_time(self):
        return datetime.now().strftime("%H:%M")

    def unicodify(self, text, min_confidence=0.5):
        guess = chardet.detect(text)
        if guess["confidence"] < min_confidence:
            raise UnicodeDecodeError
        decoded = text.decode(guess["encoding"])
        return decoded

    def fetch_song_title(self):

        if self.icy_current_song is not None and self.icy_current_song != '':
            try:
                title = self.unicodify(self.icy_current_song)
                #title = self.icy_current_song
                return title.upper()
            except Exception as e:
                return ''
        else:
            return ''

    def fetch_station_title(self):
        station = self.playlist.playlist[self.channel]
        return station.name.upper()
Exemple #10
0
class Main(Process):

    playlist = None
    player = None
    state = None
    pt2314 = None

    channel = 0
    volume = 0
    buttons = 0

    icy_current_song = None

    last_channel = 0
    last_played_channel = 0
    last_volume = 0
    last_buttons = 0

    current_time = 0
    last_channel_changed_time = 0
    last_volume_changed_time = 0
    last_buttons_changed_time = 0
    last_currentsong_time = 0
    last_mpd_poll = 0
    need_save_state = False
    need_change_song = False
    need_change_buttons = False

    screen_size = None
    fps = None
    full_screen = False

    scene = None

    def __init__(self):

        self.screen_size = Config.default_screen_size
        self.fps = Config.fps
        self.full_screen = Config.full_screen

        os.environ["SDL_FBDEV"] = Config.fb_dev

	self.serv = HTTPServer( ("0.0.0.0", 8000), HttpProcessor)
        thread = threading.Thread(target = self.serv.serve_forever)
        thread.daemon = True
        thread.start()

        super(Main, self).__init__()

    def begin(self):

        Program.set_mode(self.screen_size, self.full_screen, False)
        Program.set_fps(self.fps)
        pygame.mouse.set_visible(False)

        self.playlist = Playlist()

        self.player = Player()

        self.state = State()

        #print "State volume: {0}".format(self.state.volume)
        #print "State channel: {0}".format(self.state.channel)

        self.encoders_board = EncodersBoard(0x40, 0, 20, self.state.volume, 0, len(self.playlist.playlist) - 1, self.state.channel);

        self.pt2314 = PT2314()
        self.pt2314.setVolume(self.state.volume*5)
	#self.pt2314.setAttenuation(0)
        self.pt2314.setBass(0)
        self.pt2314.setTreble(12)
        self.pt2314.selectChannel(0)
        self.pt2314.loudnessOn()
        self.pt2314.muteOff()
        time.sleep(0.1)

        self.last_volume = self.state.volume
        self.last_channel = self.state.channel
        self.last_played_channel = self.last_channel

        station_url = self.playlist.playlist[self.state.channel].url
        self.player.load("radio")
	self.player.play(self.state.channel)

        self.scene = AppRadio(self)

        while True:
            try:
                micro = self.get_micro()
                
                self.encoders_board.read()

                self.volume = self.encoders_board.get_value1()
                if self.volume > 20:
                    self.volume = 20
                    self.encoders_board.set_value1(self.volume)
                    self.encoders_board.set_max_value1(self.volume)
                    self.encoders_board.write()

                self.channel = self.encoders_board.get_value2()
                if self.channel > len(self.playlist.playlist) - 1:
                    self.channel = len(self.playlist.playlist) - 1
                    self.encoders_board.set_value2(self.channel)
                    self.encoders_board.set_max_value2(self.channel)
                    self.encoders_board.write()

                self.buttons = self.encoders_board.get_buttons()

                if self.last_volume != self.volume:
                    self.pt2314.setVolume(self.volume*5)
                    self.last_volume = self.volume
                    self.last_volume_changed_time = micro

                if self.last_channel != self.channel:
                    self.last_channel = self.channel
                    self.last_channel_changed_time = micro

                if self.last_buttons != self.buttons and micro - self.last_buttons_changed_time > 100:
                    self.last_buttons = self.buttons
                    self.last_buttons_changed_time = micro
                    self.need_change_buttons = True

                if self.last_played_channel != self.channel and micro - self.last_channel_changed_time > 1000:
                    self.need_change_song = True

                if self.state.volume != self.volume and micro - self.last_volume_changed_time > 5000:
                    self.state.volume = self.volume
                    self.need_save_state = True

                if self.state.channel != self.channel and micro - self.last_channel_changed_time > 5000:
                    self.state.channel = self.channel
                    self.need_save_state = True

		if micro - self.last_currentsong_time > 1000:
		    self.icy_current_song = self.player.currentsong()
		    #print self.icy_current_song
		    self.last_currentsong_time = micro

                global ring_bell
                if ring_bell:
                    #print "Doorbell detected";
                    ring_bell = False
                    self.player.stop()
                    self.pt2314.setVolume(95)
		    os.system('mplayer ' + Config.bell)
                    time.sleep(0.5)
                    self.pt2314.setVolume(self.volume*5)
                    self.need_change_song = True

                if self.need_change_song:
                    self.need_change_song = False
                    self.last_played_channel = self.channel
		    time.sleep(0.5)
		    self.player.play(self.channel)

                if self.need_save_state:
                    self.need_save_state = False
                    self.state.save()

		if self.need_change_buttons:
		    self.need_change_buttons = False
		    if (self.last_buttons & Config.BTN_POWER):
			subprocess.call(["poweroff"])
		    if (self.last_buttons & Config.BTN_ALARM):
			subprocess.call(["reboot"])

            except Exception:
                pass

            yield

    def get_micro(self):
        return int(round(time.time() * 1000))

    def get_current_time(self):
        return datetime.now().strftime("%H:%M")

    def unicodify(self, text, min_confidence=0.5):
        guess = chardet.detect(text)
        if guess["confidence"] < min_confidence:
            raise UnicodeDecodeError
        decoded = text.decode(guess["encoding"])
        return decoded

    def fetch_song_title(self):

        if self.icy_current_song is not None and self.icy_current_song != '':
	    try:
                title = self.unicodify(self.icy_current_song)
		#title = self.icy_current_song
                return title.upper()
            except Exception as e:
                return ''
        else:
            return ''

    def fetch_station_title(self):
        station = self.playlist.playlist[self.channel]
        return station.name.upper()