KL_demo.py 5.29 KB
Newer Older
Jakob Knollmueller's avatar
Jakob Knollmueller committed
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
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright(C) 2017-2018 Max-Planck-Society
# Author: Jakob Knollmueller
#
# Starblade is being developed at the Max-Planck-Institut fuer Astrophysik

import numpy as np
from astropy.io import fits
from matplotlib import pyplot as plt
from multiprocessing import Pool

import nifty4 as ift
from nifty4.library.nonlinearities import PositiveTanh


import starblade as sb
from starblade.starblade_energy import StarbladeEnergy
from starblade.starblade_kl import StarbladeKL

def power_update(KL_energy):
    power = 0.
    for energy in KL_energy.energy_list:
        power += ift.power_analyze(FFT.inverse_times(energy.s),
                                             binbounds=p_space.binbounds)
    power /= len(KL_energy.energy_list)
    return power

if __name__ == '__main__':
    #specifying location of the input file:
    path = 'data/hst_05195_01_wfpc2_f702w_pc_sci.fits'
    path = 'data/frame-u-006174-2-0094.fits'
    # path = 'data/frame-g-002821-6-0141.fits'
    path = 'data/frame-g-007812-6-0100.fits'
    path = 'data/frame-i-004874-3-0692.fits'

    # data = fits.open(path)[1].data
    data = fits.open(path)[0].data#[1000:,1250:]
    data -= data.min() - 0.001
    # data = np.exp(2*(1.-plt.imread('data/sdss.png').T[0]))
    # data = (plt.imread('data/m51_3.jpg').T[0])
    # data = (plt.imread('data/12_FBP.png').T[0])


    #
    # data = data.clip(min=0.001)


    data = np.ndarray.astype(data, float)
    vmin = np.log(data.min()+0.01)
    vmax = np.log(data.max())
    plt.imsave('data.png', np.log(data))
    postanh=PositiveTanh()
    alpha = 1.5
    s_space = ift.RGSpace(data.shape, distances=len(data.shape) * [1])
    h_space = s_space.get_default_codomain()
    data = ift.Field(s_space,val=data)
    FFT = ift.FFTOperator(h_space, target=s_space)
    binbounds = ift.PowerSpace.useful_binbounds(h_space, logarithmic = False)
    p_space = ift.PowerSpace(h_space, binbounds=binbounds)
    initial_spectrum = ift.power_analyze(FFT.inverse_times(ift.log(data)),
                                             binbounds=p_space.binbounds)
    initial_spectrum /= (p_space.k_lengths+1.)**4
    update_power = True

    initial_x = ift.Field(s_space, val=-1.)
    alpha = ift.Field(s_space, val=alpha)
    q = ift.Field(s_space, val=1e-30)
    ICI = ift.GradientNormController(iteration_limit=100,
                                     tol_abs_gradnorm=1e-3)
    inverter = ift.ConjugateGradient(controller=ICI)

    parameters = dict(data=data, power_spectrum=initial_spectrum,
                      alpha=alpha, q=q,
                      inverter=inverter, FFT=FFT,
                      newton_iterations=5, update_power=update_power)
    current_x = initial_x
    for i in range(10):
        Starblade = StarbladeEnergy(position=current_x, parameters=parameters)
        samples = []
        for i in range(3):
            sample = Starblade.curvature.inverse.draw_sample()
            samples.append(sample)
        problem = StarbladeKL(current_x, samples,parameters)

        controller = ift.GradientNormController(name="Newton",
                                                tol_abs_gradnorm=1e-5,
                                                iteration_limit=5)
        minimizer = ift.RelaxedNewton(controller=controller)
        problem, convergence = minimizer(problem)
        current_x = problem.position
        parameters['power_spectrum'] = power_update(problem)
        Starblade = StarbladeEnergy(position=current_x, parameters=parameters)

    # Starblade = sb.build_starblade(data, alpha=alpha)
    # for i in range(10):
    #     Starblade = sb.starblade_iteration(Starblade)
    #
    #     #plotting on logarithmic scale
        plt.imsave('diffuse_component.png', (Starblade.s).val,vmin=vmin, vmax=vmax)
        plt.imsave('pointlike_component.png', Starblade.u.val, vmin=vmin, vmax=vmax)
    Starblade = StarbladeEnergy(position=current_x, parameters=parameters)
    var = 0.
    mean = 0
    samps = 30
    for i in range(samps):
        sam = postanh(Starblade.position+Starblade.curvature.inverse.draw_sample())
        mean += sam
        var += sam**2

    var /= samps
    mean /= samps
    var -= mean**2
    mask = ift.sqrt(var) < 0.01 +0.
    plt.imsave('masked_points.png', mask.val * Starblade.u.val, vmin=vmin, vmax=vmax)
    plt.imsave('masked_diffuse.png', mask.val * Starblade.s.val)

    plt.imsave('std.png', np.log(np.sqrt(var.val)*data.val), vmin=-3.3)
    #     plt.figure()
    #     k_lenghts = Starblade.power_spectrum.domain[0].k_lengths
    #     plt.plot(k_lenghts, Starblade.power_spectrum.val)
    #     plt.title('power spectrum')
    #     plt.yscale('log')
    #     plt.xscale('log')
    #     plt.ylabel('power')
    #     plt.xscale('harmonic mode')
    #     plt.savefig('power_spectrum.png')