imicpe 0.0.9.6__tar.gz → 1.0.1__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.
Files changed (28) hide show
  1. {imicpe-0.0.9.6 → imicpe-1.0.1}/DESCRIPTION.md +0 -1
  2. {imicpe-0.0.9.6 → imicpe-1.0.1}/PKG-INFO +3 -2
  3. imicpe-1.0.1/README.md +127 -0
  4. {imicpe-0.0.9.6 → imicpe-1.0.1}/pyproject.toml +4 -2
  5. imicpe-1.0.1/src/imicpe/_version.py +1 -0
  6. imicpe-1.0.1/src/imicpe/cs/__init__.py +9 -0
  7. imicpe-1.0.1/src/imicpe/cs/l1.py +111 -0
  8. imicpe-1.0.1/src/imicpe/cs/masks.py +80 -0
  9. imicpe-1.0.1/src/imicpe/cs/metrics.py +7 -0
  10. imicpe-1.0.1/src/imicpe/cs/operators.py +307 -0
  11. imicpe-1.0.1/src/imicpe/cs/shepp_logan_phantom.py +21 -0
  12. imicpe-1.0.1/src/imicpe/cs/tikhonov.py +95 -0
  13. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe.egg-info/PKG-INFO +3 -2
  14. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe.egg-info/SOURCES.txt +7 -0
  15. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe.egg-info/requires.txt +2 -0
  16. imicpe-0.0.9.6/README.md +0 -93
  17. imicpe-0.0.9.6/src/imicpe/_version.py +0 -1
  18. {imicpe-0.0.9.6 → imicpe-1.0.1}/LICENSE +0 -0
  19. {imicpe-0.0.9.6 → imicpe-1.0.1}/setup.cfg +0 -0
  20. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe/__init__.py +0 -0
  21. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe/optim/__init__.py +0 -0
  22. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe/optim/metrics.py +0 -0
  23. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe/optim/operators.py +0 -0
  24. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe/optim/pnnDataset.py +0 -0
  25. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe/optim/pnnTrainer.py +0 -0
  26. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe/optim/pnnUtils.py +0 -0
  27. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe.egg-info/dependency_links.txt +0 -0
  28. {imicpe-0.0.9.6 → imicpe-1.0.1}/src/imicpe.egg-info/top_level.txt +0 -0
@@ -15,7 +15,6 @@ Developped and maintained for teaching usage only!
15
15
  # Usage example
16
16
 
17
17
  The example below uses the mse method available in the `optim.metrics` subpackage of `imicpe`.
18
- It requires `numpy.randn` to generate a gaussian distribution of N points.
19
18
 
20
19
  ```python
21
20
  import numpy as np
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: imicpe
3
- Version: 0.0.9.6
3
+ Version: 1.0.1
4
4
  Summary: Toolbox for Maths,Signal,Image Teaching @ CPE
5
5
  Author-email: Marion Foare <marion.foare@cpe.fr>, Eric Van Reeth <eric.vanreeth@cpe.fr>, Arthur Gautheron <arthur.gautheron@cpe.fr>
6
6
  License: MIT License
@@ -18,6 +18,8 @@ Requires-Dist: plotly
18
18
  Requires-Dist: torch
19
19
  Requires-Dist: torchvision
20
20
  Requires-Dist: tqdm
21
+ Requires-Dist: PyWavelets
22
+ Requires-Dist: scikit-image
21
23
 
22
24
 
23
25
  A toolbox used for practical sessions at [CPE Lyon](https://www.cpe.fr/).
@@ -36,7 +38,6 @@ Developped and maintained for teaching usage only!
36
38
  # Usage example
37
39
 
38
40
  The example below uses the mse method available in the `optim.metrics` subpackage of `imicpe`.
39
- It requires `numpy.randn` to generate a gaussian distribution of N points.
40
41
 
41
42
  ```python
42
43
  import numpy as np
imicpe-1.0.1/README.md ADDED
@@ -0,0 +1,127 @@
1
+ # Librairie Python IMICPE
2
+
3
+ Le dépôt de la librairie imicpe ainsi que la documentation associée sont disponibles ici :
4
+
5
+ - Dépôt : <https://gitlab.in2p3.fr/cpe/msi/toolbox_imi>
6
+ - Doc : <https://cpe.pages.in2p3.fr/msi/toolbox_imi>
7
+
8
+ Table des matières
9
+
10
+ > [Introduction](#introduction)<br/>
11
+ > [Créer un nouveau module dans une librairie](#cr%C3%A9er-un-nouveau-module-dans-une-librairie)<br/>
12
+ > [Ajouter une nouvelle librairie/dépendence nécessaire à la librairie](#ajouter-une-nouvelle-librairiedépendence-nécessaire-à-la-librairie)<br/>
13
+ > [Appeler une autre fonction de la librairie](#appeler-une-autre-fonction-de-la-librairie)<br/>
14
+ > [Ajouter/Mettre à jour une fonction existante dans un module](#ajoutermettre-à-jour-une-fonction-existante-dans-un-module)<br/>
15
+ >> [Déposer le code et générer une version de test disponible sur test.pypi.org](#d%C3%A9poser-le-code-et-g%C3%A9n%C3%A9rer-une-version-de-test-disponible-sur-testpypiorg)<br/>
16
+ >> [Déposer le code et générer une version de disponible sur pypi.org](#d%C3%A9poser-le-code-et-g%C3%A9n%C3%A9rer-une-version-de-disponible-sur-pypiorg)<br/>
17
+ >> [Déposer le code sans vouloir générer de version de la librairie](#d%C3%A9poser-le-code-sans-vouloir-g%C3%A9n%C3%A9rer-de-version-de-la-librairie)<br/>
18
+
19
+ ## Introduction
20
+
21
+ Certains outils d’intégration continue ont été installé sur le dépôt gitlab de chacune des librairies pour faciliter la génération de la documentation technique ainsi que la compilation de la librairie et son dépôt sur pypi.org ou test.pypi.org. Cependant, cela requiert quelques actions de votre part qui sont détaillées dans la suite du document.
22
+
23
+ ## Créer un nouveau module dans une librairie
24
+ Dans le dépôt git, vous trouverez l’arborescence suivante :<br/>
25
+ <img src="docs/images/arborescence.png"
26
+ alt="Arborescence Structure"
27
+ style="float: left; margin-right: 10px;" />
28
+ 1. [ ] Créez un nouveau dossier dans le dossier « src/nom de la libraire/_nom du module »_ (dans l’exemple ci-dessous le nouveau dossier se trouverait au même niveau que ssl, tns, tsa ou utils…)
29
+ 2. [ ] Pour que le contenu de ce nouveau dossier soit reconnu comme un nouveau module de la librairie, il est nécessaire que ce dossier contienne un fichier **\__init_\_.py** qui va lister le lien vers toutes les fonctions du module.
30
+ 3. [ ] Si vous souhaitez que la documentation de ce module soit automatiquement générée :
31
+ 1. Copier le fichier « docs/imicpe.optim.rst » et renommez le « imicpe._nom du module._rst ».
32
+ 2. Adapter le contenu du fichier.
33
+ 3. Editez le fichier « docs/imicpe.rst » en ajoutant « imicpe._nom du module »_ à la suite de la liste déjà existante dans ce fichier.
34
+ 4. Continuer en suivant les instructions de la partie suivante
35
+
36
+ ## Ajouter une nouvelle librairie/dépendence nécessaire à la librairie
37
+ 1. [ ] Identifier le nom de la librairie dans [Pypi](https://pypi.org)
38
+ 2. [ ] Ajouter le nom de la librairie à la liste `dependencies` du fichier *pyproject.toml*
39
+ 3. [ ] Ajouter le nom de la librairie au fichier *docs/requirements.txt*
40
+
41
+ ## Appeler une autre fonction de la librairie
42
+
43
+ Bien faire l'appel en chemin relatif du fichier qui importe la fonction.
44
+ **Par exemple, pour introduire une fonction dans un autre fichier du même dossier, écrire** `from .my_file import my_func`
45
+
46
+ ## Ajouter/Mettre à jour une fonction existante dans un module
47
+
48
+ Dans le dossier du module où vous souhaitez ajouter la fonction _myFunc_ :
49
+ 1. [ ] Créer un fichier _maFonction.py_ qui contiendra :
50
+ 1. Les imports nécessaires pour l’exécution des fonctions de ce fichier
51
+ 2. Une (ou plusieurs) fonction(s) python _myFunc_ (..)
52
+ 3. La doc string descriptive de la fonction qui respecte la nomenclature suivante
53
+ ````
54
+ def sptheo(Q, method, fenetre=None):
55
+ """
56
+ Calcule dans le cadre du TP Estimation spectrale :
57
+
58
+ - Gth : la valeur en dB de la DSPM du bruit blanc filtré entre 0 et 0,5.
59
+ - Gbiais : la valeur en dB de Gth convolué par la grandeur régissant le biais attaché à la 'method'.
60
+ - f : un vecteur fréquence réduite de même taille que Gth et Gbiais.
61
+
62
+ Parameters
63
+ ----------
64
+ Q : int
65
+ Pour 'simple', représente la longueur de l'échantillon analysé.
66
+ Pour 'moyenne' ou 'welch', représente la longueur d'une tranche.
67
+
68
+ method : {'simple', 'moyenne', 'welch'}
69
+ Méthode d'estimation spectrale à utiliser.
70
+
71
+ fenetre : str, optional
72
+ Nom de la fenêtre à utiliser si method='welch'. Ignoré pour 'simple' et 'moyenne'.
73
+
74
+ Returns
75
+ -------
76
+ Gth : ndarray
77
+ Valeur en dB de la DSPM du bruit blanc filtré entre 0 et 0,5.
78
+
79
+ Gbiais : ndarray
80
+ Valeur en dB de Gth convolué par la grandeur régissant le biais.
81
+
82
+ f : ndarray
83
+ Vecteur fréquence réduite.
84
+
85
+ Notes
86
+ -----
87
+ Cette fonction calcule différentes valeurs théoriques dans le cadre de l'estimation spectrale,
88
+ en fonction de la méthode choisie ('simple', 'moyenne' ou 'welch') et des paramètres associés.
89
+
90
+ Example
91
+ -------
92
+ >>> from msicpe.tsa import sptheo
93
+ >>> sptheo(1024, 'welch', 'hamming')
94
+ """
95
+
96
+ ````
97
+
98
+
99
+ 2. [ ] Editer le fichier **\__init_\_.py** du même dossier pour importer la fonction qui doit être accessible dans la librairie.
100
+
101
+
102
+ <i>Par exemple, si je veux que la fonction export_dat disponible dans le fichier export_dat.py soit accessible, je vais compléter le fichier_ **\__init_\_.py** de la façon suivante :</i>
103
+
104
+ ```
105
+ from .export_dat import export_dat
106
+ ```
107
+
108
+ 3. [ ] Il faut maintenant déposer le code sur le dépôt git. Trois options s’offrent à vous :
109
+ \- Déposer le code et générer une version de test disponible sur test.pypi.org<br/>
110
+ \- Déposer le code et générer une version de disponible sur pypi.org<br/>
111
+ \- Déposer le code sans vouloir générer de version de la librairie
112
+
113
+ ### Déposer le code et générer une version de test disponible sur test.pypi.org
114
+
115
+ - [ ] Modifier le fichier **version.txt** situé à la racine du dépôt et indiquer une suite de chiffre supérieure à celle disponible sur <https://test.pypi.org/simple/imicpe/>
116
+ - [ ] Faites un simple commit & push
117
+ - [ ] La doc sera mise à jour et d’ici quelques minutes (~5 min) il y aura une nouvelle version de la librairie qui sera disponible sur <https://test.pypi.org/simple/imicpe/>
118
+
119
+ ### Déposer le code et générer une version de disponible sur pypi.org
120
+
121
+ - [ ] Faites un simple commit & push
122
+ - [ ] Sur le repo, créer un tag de la dernière version du git (en suivant la numérotation croissante existante).
123
+ - [ ] La doc sera mise à jour et d’ici quelques minutes (~5 min) il y aura une nouvelle version de la librairie qui sera disponible sur <https://pypi.org/project/imicpe/>
124
+
125
+ ### Déposer le code sans vouloir générer de version de la librairie
126
+
127
+ - [ ] Faites un simple commit & push
@@ -9,12 +9,12 @@ build-backend = "setuptools.build_meta"
9
9
  where = ["src"]
10
10
 
11
11
  [tool.setuptools.package-data]
12
- mypkg = ["*.txt", "*.mat"]
12
+ mypkg = ["*.txt", "*.mat", "*.npy"]
13
13
 
14
14
  #[tool.setuptools_scm]
15
15
 
16
16
  [project]
17
- version="0.0.9.6"
17
+ version="1.0.1"
18
18
  name = "imicpe"
19
19
  authors = [
20
20
  { name="Marion Foare", email="marion.foare@cpe.fr" },
@@ -32,6 +32,8 @@ dependencies = [
32
32
  "torch",
33
33
  "torchvision",
34
34
  "tqdm",
35
+ "PyWavelets",
36
+ "scikit-image"
35
37
  ]
36
38
  classifiers = [
37
39
  "Programming Language :: Python :: 3",
@@ -0,0 +1 @@
1
+ __version__="1.0.1"
@@ -0,0 +1,9 @@
1
+ from .metrics import mse, snr
2
+ from .operators import fwt, iwt, fwt2, iwt2
3
+ from .tikhonov import tikhonov
4
+ from .l1 import l1
5
+ from .shepp_logan_phantom import phantom_shepp_logan
6
+ from .masks import mat2mask, starPattern, getAcquisitionImage #, sub2ind, ind2sub
7
+
8
+ import os
9
+ cameraman = os.path.join(os.path.dirname(__file__), 'cameraman.tif')
@@ -0,0 +1,111 @@
1
+
2
+ import numpy as np
3
+ from scipy import ndimage
4
+
5
+ from .operators import *
6
+ from tqdm import tqdm_notebook as tqdm
7
+
8
+ def l1(opreg,A,At,z,x0,lam):
9
+ """
10
+ l1 Algorithme Forward-Backward pour résoudre le problème
11
+ xhat = argmin ||Hx-z||_2^2 + lam.||Gx||_1
12
+ x
13
+
14
+ en particulier :
15
+ - le modèle LASSO si G = Id,
16
+ - le modèle TV si G = D (gradient) ou L (laplacien),
17
+
18
+ Args:
19
+ opreg (string) nom de l'opérateur G sur lequel opère la contrainte de parcimonie {'id', 'gradient', 'laplacien'}
20
+ A (fonction)
21
+ At (fonction)
22
+ z
23
+ x0 (numpy.ndarray)
24
+ lam (float)
25
+
26
+ Returns:
27
+ xhat (numpy.ndarray) solution du problème
28
+ loss (numpy.ndarray) évolution de la fonction de coût au cours des itérations
29
+ """
30
+
31
+ print('Running l1 model with ' +opreg+ ' sparsity constraint...\n\t')
32
+
33
+ ### init ###
34
+ dim = x0.ndim
35
+ match opreg:
36
+ case 'id':
37
+ G = Id
38
+ Gt = Id
39
+ case 'gradient':
40
+ G = D
41
+ Gt = Dt
42
+ case 'laplacien':
43
+ G = L
44
+ Gt = Lt
45
+
46
+ # operator norms
47
+ lipA = opNorm(A,At,dim,x0)
48
+ lipG = opNorm(G,Gt,dim,x0)
49
+
50
+ # cost functions
51
+ def f(x): # data fidelity
52
+ return np.sum(x**2)/2
53
+
54
+ def R(x): # regularization
55
+ return np.sum(np.abs(x))
56
+
57
+ def E(x,lam): # total cost
58
+ return f(A(x)-z) + lam*R(G(x))
59
+
60
+ # proximity operator
61
+ def proxl1(x,gam):
62
+ return x - np.maximum(np.minimum(x,gam*np.ones(x.shape)),-gam*np.ones(x.shape))
63
+
64
+ ### Algo ###
65
+ niter = 1e3; # max number of iterations
66
+ # model hyperparameters
67
+ mu = 5; # Bregman parameter (in [1,10], should not vary)
68
+
69
+ # algo hyperparameters
70
+ gamx = .9/(lipA**2 + mu*lipG**2); #.5e-1; # gradient descent step (x subproblem)
71
+ gamu = 1/mu; # proximal descent step (y subproblem)
72
+
73
+ # initialize variables
74
+ En = np.zeros((int(niter+1),),float) * np.nan
75
+ xn = x0 #np.random.standard_normal((z.shape))
76
+ un = G(xn) # splitting variable
77
+ bn = np.zeros(un.shape,float) # Bregman variable
78
+
79
+ En[0] = E(xn,lam)
80
+
81
+ # loop parameters
82
+ k = 0
83
+ tol = 1e-10
84
+ stop_crit = En[0]
85
+
86
+
87
+ with tqdm(total=niter) as pbar:
88
+ while (k < niter) and (stop_crit > tol):
89
+ # yn subproblem
90
+ Gxn = G(xn)
91
+ un = proxl1(un - gamu*mu*(un-Gxn-bn/mu) , lam*gamu)
92
+
93
+ # xn subproblem (relaxed): gradient descent step instead of GS iteration
94
+ xn = xn - gamx*( At(A(xn)-z) - mu*Gt(un-Gxn-bn/mu) )
95
+
96
+ # bn subproblem
97
+ bn = bn - mu*(un-G(xn))
98
+
99
+ # compute loss
100
+ En[k+1] = E(xn,lam)
101
+
102
+ # update loop parameters
103
+ stop_crit = (En[k] - En[k+1])/En[k]
104
+ k += 1
105
+ pbar.update(1)
106
+
107
+ pbar.close()
108
+ xhat = xn
109
+ loss = En
110
+
111
+ return xhat, loss
@@ -0,0 +1,80 @@
1
+
2
+ import numpy as np
3
+ from scipy import ndimage
4
+ import pywt
5
+
6
+
7
+ mat2mask = lambda mat, H, W, M: np.reshape(mat.T, (H, W, M))
8
+
9
+
10
+ def starPattern(N, M):
11
+ """
12
+ starPattern Génère un masque de taille NxN en étoile (tomographie) correspondant à M mesures.
13
+
14
+ Args:
15
+ N (int) Taille du masque
16
+ M (int) Nombre de mesures
17
+
18
+ Returns:
19
+ Amat (numpy.ndarray) Matrice d'acquisition
20
+ mask (numpy.ndarray) Masque
21
+ """
22
+
23
+
24
+ mask2mat = lambda mask: np.reshape(mask, (M, N**2))
25
+
26
+ H = int(N)
27
+ W = int(N)
28
+
29
+ n = int(N)
30
+ r = np.linspace(-1, 1, 3*n)*n
31
+
32
+ nrho = 2**4
33
+ R = np.round(np.linspace(-n/2, n/2, nrho))#.astype(int)
34
+
35
+ ntheta = M//nrho
36
+ T = np.linspace(0, np.pi, ntheta+1, endpoint=False)
37
+
38
+ mask = np.zeros((H, W, ntheta, nrho))
39
+ for itt in range(ntheta):
40
+ theta = T[itt]
41
+
42
+ for itr in range(nrho):
43
+ rho = R[itr]
44
+
45
+ x = np.round(r*np.cos(theta) + n/2 - rho*np.sin(theta))#.astype(int)
46
+ y = np.round(r*np.sin(theta) + n/2 + rho*np.cos(theta))#.astype(int)
47
+
48
+ valid = np.where((x >= 0) & (x < n) & (y >= 0) & (y < n))
49
+ x = x[valid].astype(int)
50
+ y = y[valid].astype(int)
51
+
52
+ tmpM = np.zeros((H, W))
53
+ tmpM[y, x] = 1
54
+
55
+ mask[:, :, itt, itr] = tmpM
56
+
57
+ mask = mask.reshape((H, W, M))
58
+ Amat = mask2mat(mask)
59
+
60
+ return Amat, mask
61
+
62
+
63
+ def getAcquisitionImage(x,mask):
64
+ _, _, Nmeasures = mask.shape
65
+
66
+ zim = np.sum(mask * np.tile(x[..., None], (1, 1, Nmeasures)), axis=2)
67
+ zim = zim / np.max(zim)
68
+
69
+ return zim
70
+
71
+
72
+
73
+ # def sub2ind(array_shape, rows, cols):
74
+ # ind = rows*array_shape[1] + cols
75
+ # return ind.astype(int)
76
+
77
+ # def ind2sub(array_shape, ind):
78
+ # rows = (ind.astype('int') / array_shape[1])
79
+ # cols = (ind.astype('int') % array_shape[1]) # or numpy.mod(ind.astype('int'), array_shape[1])
80
+ # return (int(rows), int(cols))
@@ -0,0 +1,7 @@
1
+ import numpy as np
2
+
3
+ def mse(I,ref):
4
+ return np.sum((I-ref)**2)/I.size
5
+
6
+ def snr(I,ref):
7
+ return 10* np.log10(np.sum(ref**2)/np.sum((I-ref)**2))
@@ -0,0 +1,307 @@
1
+
2
+ import numpy as np
3
+ from scipy import ndimage
4
+ import pywt
5
+
6
+
7
+ ############################################################
8
+ ## identity operator
9
+ ############################################################
10
+ def Id(x):
11
+ """
12
+ Opérateur identité
13
+
14
+ Args:
15
+ X (numpy.ndarray) signal 1D
16
+ ou: image non vectorisée 2D
17
+
18
+ Returns:
19
+ (numpy.ndarray) X
20
+ """
21
+
22
+ return x
23
+
24
+
25
+ ############################################################
26
+ ## differential forward and backward operators
27
+ ############################################################
28
+ # gradient
29
+ def D(x):
30
+ """
31
+ Calcule le gradient par différences finies à droite.
32
+ Autrement dit, D(x) calcule le produit matriciel Dx.
33
+
34
+ Args:
35
+ X (numpy.ndarray) signal 1D
36
+ ou: image non vectorisée 2D
37
+
38
+ Returns:
39
+ (numpy.ndarray) Gradient de X
40
+ """
41
+
42
+ if x.ndim == 1:
43
+ grad = np.concatenate((x[1:] - x[:-1], [0]))/2.
44
+
45
+ elif x.ndim == 2:
46
+ sz = x.shape
47
+ Dx_im = np.concatenate(( x[:,1:] - x[:,:-1] , np.zeros((sz[0],1)) ), axis=1)/ 2.
48
+ Dy_im = np.concatenate(( x[1:,:] - x[:-1,:] , np.zeros((1,sz[1])) ), axis=0)/ 2.
49
+
50
+ grad = np.array([Dx_im,Dy_im])
51
+ return grad
52
+
53
+ def Dt(x):
54
+ """
55
+ Calcule l’adjoint gradient par différences finies à droite.
56
+ Autrement dit, Dt(x) calcule le produit matriciel D'x.
57
+
58
+ Args:
59
+ X (numpy.ndarray) signal 1D
60
+ ou: image non vectorisée 2D
61
+
62
+ Returns:
63
+ (numpy.ndarray) Divergence de X
64
+ """
65
+
66
+ if x.ndim == 1:
67
+ div = - np.concatenate(([x[0]], x[1:-1] - x[:-2], [-x[-2]])) /2.
68
+
69
+ elif x.ndim == 3:
70
+ x1 = x[0]
71
+ x2 = x[1]
72
+ div = - np.concatenate((x1[:,[0]], x1[:,1:-1] - x1[:,:-2], -x1[:,[-2]]), axis=1) /2. \
73
+ - np.concatenate((x2[[0],:], x2[1:-1,:] - x2[:-2,:], -x2[[-2],:]), axis=0) /2.
74
+ return div
75
+
76
+ # laplacian
77
+ def L(x):
78
+ """
79
+ Calcule la dérivée seconde d’un signal, ou le laplacien dans le cas d’une image.
80
+ Autrement dit, L(x) calcule le produit matriciel Lx.
81
+
82
+ Args:
83
+ X (numpy.ndarray) signal 1D
84
+ ou: image non vectorisée 2D
85
+
86
+ Returns:
87
+ (numpy.ndarray) Laplacien de X
88
+ """
89
+
90
+ if x.ndim == 1:
91
+ ker = np.array([1, -2, 1])
92
+ #lap = np.convolve(x,ker,'same')
93
+ lap = ndimage.convolve1d(x,ker,mode='nearest')
94
+ elif x.ndim == 2:
95
+ ker = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) # V4
96
+ #ker = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]]) # V8
97
+ lap = ndimage.convolve(x,ker,mode='nearest')
98
+ return lap
99
+
100
+ def Lt(x):
101
+ """
102
+ Calcule l’adjoint du laplacien.
103
+ Autrement dit, Lt(x) calcule le produit matriciel L'x.
104
+
105
+ Args:
106
+ X (numpy.ndarray) signal 1D
107
+ ou: image non vectorisée 2D
108
+
109
+ Returns:
110
+ (numpy.ndarray) Adjoint du Laplacien de X
111
+ """
112
+
113
+ if x.ndim == 1:
114
+ ker = np.array([1, -2, 1])
115
+ #lap = np.correlate(x,ker,'same')
116
+ lap = ndimage.correlate1d(x,ker,mode='nearest')
117
+ elif x.ndim == 2:
118
+ ker = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) # V4
119
+ #ker = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]]) # V8
120
+ lap = ndimage.correlate(x,ker,mode='nearest')
121
+ return lap
122
+
123
+
124
+ ############################################################
125
+ ## Wavelet transforms
126
+ ############################################################
127
+ def fwt(x,wavelet,level):
128
+ """
129
+ Calcule la transformée en ondelettes directe 1D.
130
+
131
+ Args:
132
+ x (numpy.ndarray) signal 1D
133
+
134
+ Returns:
135
+ (numpy.ndarray) Vecteur des coefficients de la décomposition en ondelettes de x
136
+ """
137
+
138
+ dim = x.ndim
139
+
140
+ coeffs = pywt.wavedec(x, wavelet, level=level, mode="periodization")
141
+ coeff_arr, _, _ = pywt.ravel_coeffs(coeffs)
142
+
143
+ return coeff_arr
144
+
145
+
146
+ def iwt(x,wavelet,level):
147
+ """
148
+ Calcule la transformée en ondelettes inverse 1D.
149
+
150
+ Args:
151
+ x (numpy.ndarray) Vecteur des coefficients d'ondelettes
152
+ wavelet (string) Nom de l'ondelette mère (voir la librairie pywt)
153
+ level (int) Niveau de décompisition
154
+
155
+ Returns:
156
+ (numpy.ndarray) Signal correspondant aux coefficients d'ondelettes donnés par x
157
+ """
158
+
159
+ J = level
160
+ N = len(x)
161
+ _, coeffs_slices, coeffs_shapes = pywt.ravel_coeffs(pywt.wavedec(np.ones(N), wavelet=wavelet, level=J, mode='periodization'))
162
+
163
+ if coeffs_shapes is None:
164
+ # compute coeffs size at each level
165
+ sizes = [N // (2**j) for j in range(J, 0, -1)] + [N // (2**J)]
166
+
167
+ # coefficients splitting
168
+ start = 0
169
+ coeffs = []
170
+ for size in reversed(sizes):
171
+ coeffs.append(x[start:start + size])
172
+ start += size
173
+ else:
174
+ coeffs = pywt.unravel_coeffs(x, coeffs_slices, coeffs_shapes, output_format='wavedec')
175
+
176
+ # reconstruct corresponding signal
177
+ signal = pywt.waverec(coeffs, wavelet, mode="periodization")
178
+
179
+ return signal
180
+
181
+
182
+ def fwt2(x,wavelet,level):
183
+ """
184
+ Calcule la transformée en ondelettes directe 2D.
185
+
186
+ Args:
187
+ x (numpy.ndarray) image NON vectorisée 2D
188
+ wavelet (string) Nom de l'ondelette mère (voir la librairie pywt)
189
+ level (int) Niveau de décompisition
190
+
191
+ Returns:
192
+ (numpy.ndarray) Vecteur des coefficients de la décomposition en ondelettes de x
193
+ """
194
+
195
+ coeffs = pywt.wavedec2(x, wavelet, level=level, mode="periodization")
196
+ coeff_arr, _, _ = pywt.ravel_coeffs(coeffs)
197
+
198
+ return coeff_arr
199
+
200
+ def iwt2(x,wavelet,level):
201
+ """
202
+ Calcule la transformée en ondelettes inverse 2D.
203
+
204
+ Args:
205
+ x (numpy.ndarray) Vecteur des coefficients d'ondelettes
206
+ wavelet (string) Nom de l'ondelette mère (voir la librairie pywt)
207
+ level (int) Niveau de décompisition
208
+
209
+ Returns:
210
+ (numpy.ndarray) Image correspondante aux coefficients d'ondelettes donnés par x
211
+ """
212
+
213
+ J = level
214
+ N = len(x)
215
+
216
+ _, coeffs_slices, coeffs_shapes = pywt.ravel_coeffs(pywt.wavedec2(np.ones((int(np.sqrt(N)),int(np.sqrt(N)))), wavelet=wavelet, level=J, mode='periodization'))
217
+
218
+ coeffs = pywt.unravel_coeffs(x, coeffs_slices, coeffs_shapes,
219
+ output_format='wavedec2')
220
+
221
+ # reconstruct corresponding signal
222
+ image = pywt.waverec2(coeffs, wavelet, mode="periodization")
223
+
224
+ return image
225
+
226
+
227
+ ############################################################
228
+ ## Operator and matrix norm
229
+ ############################################################
230
+ def opNorm(op,opt,dim,xn):
231
+ """
232
+ Calcule la norme de l'opérateur OP, dont
233
+ l'opérateur transposé est OPT, en dimension DIM
234
+
235
+ Args:
236
+ OP (function) opérateur direct
237
+ OPT (function) opérateur adjoint
238
+ DIM (int) 1 or 2
239
+
240
+ Returns:
241
+ (float) norme de l'opérateur OP
242
+ """
243
+
244
+ def T(x):
245
+ return opt(op(x))
246
+
247
+ # match dim:
248
+ # case 1:
249
+ # xn = np.random.standard_normal((64))
250
+ # case 2:
251
+ # xn = np.random.standard_normal((64,64))
252
+
253
+ xnn = xn
254
+
255
+ n = np.zeros((1000,),float)
256
+ n[1] = 1
257
+ tol = 1e-4
258
+ rhon = n[1]+2*tol
259
+
260
+ k = 1
261
+ while abs(n[k]-rhon)/n[k] >= tol:
262
+ xn = T(xnn)
263
+ xnn = T(xn)
264
+
265
+ rhon = n[k]
266
+ n[k+1] = np.sum(xnn**2)/np.sum(xn**2)
267
+
268
+ k = k+1
269
+
270
+ N = n[k-1] + 1e-16
271
+ return 1.01* N**(.25) # sqrt(L) gives |||T|||=|||D'D||| ie |||D|||^2
272
+
273
+
274
+ def matNorm(M):
275
+ """
276
+ Calcule la norme de la matrice M
277
+
278
+ Args:
279
+ M (numpy.ndarray) matrice dont on souhaite calculer la norme
280
+
281
+ Returns:
282
+ (float) norme de la matrice M
283
+ """
284
+
285
+ def T(x):
286
+ return np.dot(M.T, np.dot(M,x))
287
+
288
+ xn = np.random.standard_normal((M.shape[1]))
289
+ xnn = xn
290
+
291
+ n = np.zeros((1000,),float)
292
+ n[1] = 1
293
+ tol = 1e-4
294
+ rhon = n[1]+2*tol
295
+
296
+ k = 1
297
+ while abs(n[k]-rhon)/n[k] >= tol:
298
+ xn = T(xnn)
299
+ xnn = T(xn)
300
+
301
+ rhon = n[k]
302
+ n[k+1] = np.sum(xnn**2)/np.sum(xn**2)
303
+
304
+ k = k+1
305
+
306
+ N = n[k-1] + 1e-16
307
+ return 1.01* N**(.25) # sqrt(L) gives |||T|||=|||D'D||| ie |||D|||^2
@@ -0,0 +1,21 @@
1
+
2
+ import numpy as np
3
+
4
+ from skimage.data import shepp_logan_phantom
5
+ from skimage.transform import rescale, resize
6
+
7
+ def phantom_shepp_logan(N):
8
+ """
9
+ phantom_shepp_logan Génère le phantom de Shepp-Logan 2D de taille NxN.
10
+
11
+ Args:
12
+ N (int) Taille du phantom
13
+
14
+ Returns:
15
+ (numpy.ndarray) Image du phantom
16
+ """
17
+ p = shepp_logan_phantom()
18
+ p = resize(p, (int(N),int(N)), anti_aliasing=False)
19
+ p[p<1e-10] = .1
20
+
21
+ return p
@@ -0,0 +1,95 @@
1
+
2
+ import numpy as np
3
+ from scipy import ndimage
4
+
5
+ from .operators import *
6
+ from tqdm import tqdm_notebook as tqdm
7
+
8
+ def tikhonov(opreg,A,At,z,x0,lam):
9
+ """
10
+ tikhonov Algorithme de descente de gradient pour résoudre le problème
11
+ xhat = argmin ||Hx-z||_2^2 + lam.||Gx||_2^2
12
+ x
13
+
14
+
15
+ Args:
16
+ opreg (string) nom de l'opérateur G sur lequel opère la contrainte de parcimonie {'id', 'gradient', 'laplacien'}
17
+ A (fonction)
18
+ At (fonction)
19
+ z
20
+ x0 (numpy.ndarray)
21
+ lam (float)
22
+
23
+ Returns:
24
+ xhat (numpy.ndarray) solution du problème
25
+ loss (numpy.ndarray) évolution de la fonction de coût au cours des itérations
26
+ """
27
+
28
+ print('Running Tikhonov model with ' +opreg+ ' sparsity constraint...\n\t')
29
+
30
+ ### init ###
31
+ dim = x0.ndim
32
+ match opreg:
33
+ case 'id':
34
+ G = Id
35
+ Gt = Id
36
+ case 'gradient':
37
+ G = D
38
+ Gt = Dt
39
+ case 'laplacien':
40
+ G = L
41
+ Gt = Lt
42
+
43
+ # operator norms
44
+ lipA = opNorm(A,At,dim,x0)
45
+ lipG = opNorm(G,Gt,dim,x0)
46
+
47
+ # cost functions
48
+ def f(x): # data fidelity
49
+ return np.sum(x**2)/2
50
+
51
+ def R(x): # regularization
52
+ return np.sum(x**2)/2
53
+
54
+ def E(x,lam): # total cost
55
+ return f(A(x)-z) + lam*R(G(x))
56
+
57
+ # proximity operator
58
+ def proxl1(x,gam):
59
+ return x - np.maximum(np.minimum(x,gam*np.ones(x.shape)),-gam*np.ones(x.shape))
60
+
61
+ ### Algo ###
62
+ niter = 1e3; # max number of iterations
63
+
64
+ # algo hyperparameters
65
+ gam = .9/(2*lipA**2 + 2*lam*lipG**2); # gradient descent step
66
+
67
+ # initialize variables
68
+ En = np.zeros((int(niter+1),),float) * np.nan
69
+ xn = x0 #np.random.standard_normal((z.shape))
70
+
71
+ En[0] = E(xn,lam)
72
+
73
+ # loop parameters
74
+ k = 0
75
+ tol = 1e-10
76
+ stop_crit = En[0]
77
+
78
+ with tqdm(total=niter) as pbar:
79
+ while (k < niter) and (stop_crit > tol):
80
+ # xn subproblem
81
+ xn = xn - 2*gam*(At(A(xn)-z) + lam*Gt(G(xn)))
82
+
83
+ # compute loss
84
+ En[k+1] = E(xn,lam)
85
+
86
+ # update loop parameters
87
+ stop_crit = (En[k] - En[k+1])/En[k]
88
+ k += 1
89
+ pbar.update(1)
90
+
91
+ pbar.close()
92
+ xhat = xn
93
+ loss = En
94
+
95
+ return xhat, loss
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: imicpe
3
- Version: 0.0.9.6
3
+ Version: 1.0.1
4
4
  Summary: Toolbox for Maths,Signal,Image Teaching @ CPE
5
5
  Author-email: Marion Foare <marion.foare@cpe.fr>, Eric Van Reeth <eric.vanreeth@cpe.fr>, Arthur Gautheron <arthur.gautheron@cpe.fr>
6
6
  License: MIT License
@@ -18,6 +18,8 @@ Requires-Dist: plotly
18
18
  Requires-Dist: torch
19
19
  Requires-Dist: torchvision
20
20
  Requires-Dist: tqdm
21
+ Requires-Dist: PyWavelets
22
+ Requires-Dist: scikit-image
21
23
 
22
24
 
23
25
  A toolbox used for practical sessions at [CPE Lyon](https://www.cpe.fr/).
@@ -36,7 +38,6 @@ Developped and maintained for teaching usage only!
36
38
  # Usage example
37
39
 
38
40
  The example below uses the mse method available in the `optim.metrics` subpackage of `imicpe`.
39
- It requires `numpy.randn` to generate a gaussian distribution of N points.
40
41
 
41
42
  ```python
42
43
  import numpy as np
@@ -9,6 +9,13 @@ src/imicpe.egg-info/SOURCES.txt
9
9
  src/imicpe.egg-info/dependency_links.txt
10
10
  src/imicpe.egg-info/requires.txt
11
11
  src/imicpe.egg-info/top_level.txt
12
+ src/imicpe/cs/__init__.py
13
+ src/imicpe/cs/l1.py
14
+ src/imicpe/cs/masks.py
15
+ src/imicpe/cs/metrics.py
16
+ src/imicpe/cs/operators.py
17
+ src/imicpe/cs/shepp_logan_phantom.py
18
+ src/imicpe/cs/tikhonov.py
12
19
  src/imicpe/optim/__init__.py
13
20
  src/imicpe/optim/metrics.py
14
21
  src/imicpe/optim/operators.py
@@ -4,3 +4,5 @@ plotly
4
4
  torch
5
5
  torchvision
6
6
  tqdm
7
+ PyWavelets
8
+ scikit-image
imicpe-0.0.9.6/README.md DELETED
@@ -1,93 +0,0 @@
1
- # toolbox
2
-
3
-
4
-
5
- ## Getting started
6
-
7
- To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
-
9
- Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
-
11
- ## Add your files
12
-
13
- - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14
- - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
15
-
16
- ```
17
- cd existing_repo
18
- git remote add origin https://gitlab.in2p3.fr/cpe/msi/toolbox.git
19
- git branch -M main
20
- git push -uf origin main
21
- ```
22
-
23
- ## Integrate with your tools
24
-
25
- - [ ] [Set up project integrations](https://gitlab.in2p3.fr/cpe/msi/toolbox/-/settings/integrations)
26
-
27
- ## Collaborate with your team
28
-
29
- - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30
- - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31
- - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32
- - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33
- - [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
34
-
35
- ## Test and Deploy
36
-
37
- Use the built-in continuous integration in GitLab.
38
-
39
- - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
40
- - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41
- - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42
- - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43
- - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
44
-
45
- ***
46
-
47
- # Editing this README
48
-
49
- When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
-
51
- ## Suggestions for a good README
52
-
53
- Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
54
-
55
- ## Name
56
- Choose a self-explaining name for your project.
57
-
58
- ## Description
59
- Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
60
-
61
- ## Badges
62
- On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
63
-
64
- ## Visuals
65
- Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
66
-
67
- ## Installation
68
- Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
69
-
70
- ## Usage
71
- Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
72
-
73
- ## Support
74
- Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
75
-
76
- ## Roadmap
77
- If you have ideas for releases in the future, it is a good idea to list them in the README.
78
-
79
- ## Contributing
80
- State if you are open to contributions and what your requirements are for accepting them.
81
-
82
- For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
83
-
84
- You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
85
-
86
- ## Authors and acknowledgment
87
- Show your appreciation to those who have contributed to the project.
88
-
89
- ## License
90
- For open source projects, say how it is licensed.
91
-
92
- ## Project status
93
- If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -1 +0,0 @@
1
- __version__="0.0.9.6"
File without changes
File without changes
File without changes