-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnote.txt
More file actions
523 lines (451 loc) · 24.3 KB
/
note.txt
File metadata and controls
523 lines (451 loc) · 24.3 KB
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
________________________________________________________________________________
>>> import hdf5
>>> import scipy.io
>>> A = scipy.io.loadmat('test.mat')
>>> A
{'__version__': '1.0', '__globals__': [], '__header__': b'MATLAB 5.0 MAT-file, Platform: MACI64, Created on: Thu Nov 24 09:42:20 2016', 'A': array([[1, 2],
[3, 4]], dtype=uint8)}
>>> A = scipy.io.loadmat('testv7.3.mat')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/io/matlab/mio.py", line 134, in loadmat
MR = mat_reader_factory(file_name, appendmat, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/io/matlab/mio.py", line 64, in mat_reader_factory
raise NotImplementedError('Please use HDF reader for matlab v7.3 files')
NotImplementedError: Please use HDF reader for matlab v7.3 files
CI-joint une solution, pas forcément élégante mais je ne connais pas bien le format hdf5 qui est très puissant et dispose de beaucoup de fonctionnalités.
Pour plus d'infos cf http://www.h5py.org
>>> import h5py
>>> f = h5py.File('testv7.3.mat')
>>> f
<HDF5 file "testv7.3.mat" (mode r+)>
>>> list(f) # en gros, permet de récupèrer les noms des variables dans une liste, défini par le résultat de la fonction d'itération de la classe h5py.File
['A', 'B']
>>> print(A)
<HDF5 dataset "A": shape (2, 2), type "<f8">
>>> A = numpy.array(f['A']) # conversion implicite des datasets de h5py en array.
>>> print(A)
array([[ 1., 3.],
[ 2., 4.]])
________________________________________________________________________________
________________________________________________________________________________
numpy.savez()
numpy.load()
Si on alloue pas une variable avec le load, ça nous dit juste que ça a mis quelque chose en mémoire. Après je ne sais pas comment récupérer ce qu'il y a à cet endroit... (cf id() si vous voulez en savoir plus)
>>> A = numpy.array([[1, 2], [3, 4]])
>>> numpy.savez('test', A)
>>> del(A)
>>> numpy.load('test.npz')
<numpy.lib.npyio.NpzFile object at 0x101c50d68>
>>> b = numpy.load('test.npz')
>>> b.keys()
['arr_0']
>>> b['arr_0']
array([[1, 2],
[3, 4]])
________________________________________________________________________________
________________________________________________________________________________
Calling matlab function in Python
voir ici :
https://fr.mathworks.com/help/matlab/matlab_external/call-matlab-functions-from-python.html
________________________________________________________________________________
________________________________________________________________________________
Calling matlab from Python
voir ici :
https://fr.mathworks.com/help/matlab/matlab_external/call-matlab-functions-from-python.html
Sinon pour lancer un process matlab à partir de python je vous donne un bout de code en vrac que j'ai développé, qui fonctionne sous mac ou windows... c'est certainement améliorable.
matlab_param = ' -nojvm -nodisplay -nodesktop -r '
command_ffn = os.path.join(param["TRIAL_PATHNAME"],
param["FMRI_PATHNAME"], param["FMRI_NIFTI"])
command_ffnres = param["RES_NAME"]
path_res = os.path.join('..', 'Matlab', 'res', param["RES_NAME"])
if not(os.path.exists(path_res)):
os.mkdir(path_res)
if platform == 'darwin':
matlab_command = (
"\"cd('../Matlab/'); extract_data_from_atlas({\'" +
command_ffn + "\', \'" + command_ffnres + "\'}, 7); exit" + "\"")
# matlab_command = (
# "\"cd('../Matlab/'); extract_data_from_atlas({\'" +
# command_ffn + "\', \'" + command_ffnres + "\'}, 6); exit" + "\"")
# matlab_command = ('"cd(\'../Matlab/\');disp(pwd);exit"')
else :
matlab_command = (
"\"cd('../Matlab/'); extract_data_from_atlas({\'" +
command_ffn + "\', \'" + command_ffnres + "\'}, 12); exit" +
"\"")
str_shell = MATLAB_COMMAND + matlab_param + matlab_command
try :
p = subprocess.Popen(str_shell)
# print(p)
except Exception as e :
print(e)
return None
________________________________________________________________________________
________________________________________________________________________________
Pour les échanges entre thread en C et thread en python par buffers, je ne suis pas sur d'avoir compris la question:
cf les pistes suivantes (buffer, thread, subprocess):
https://docs.python.org/3/library/io.html?highlight=io#module-io
https://docs.python.org/3/library/threading.html?highlight=thread#module-threading
https://docs.python.org/3/library/subprocess.html?highlight=subprocess#module-subprocess
________________________________________________________________________________
________________________________________________________________________________
# Difference '==' versus 'is'
See http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python
## To retain
'==' test for value equality (same value)
'is' test for reference equality (same object)
The _unexpected thing_ is that Python creates some references for small int values from -5 to 256.
>>> a = 200
>>> b = 200
>>> a is b
True
but
>>> a = 500
>>> b = 500
>>> a is b
False
________________________________________________________________________________
________________________________________________________________________________
# Evaluation of scripts when using 'from module import *'
Yes !
If the module contains
print('abc')
The import will display 'abc':
>>> from module import *
abc
________________________________________________________________________________
________________________________________________________________________________
pydoc -g in windows command shell ?
Prefer this command that will work in any shell (unix windows mac):
python -m pydoc -p 1234
the option -m for python indicate to execute -m to 'run library module as a script (terminates option list)'
For other details see:
https://docs.python.org/3/library/pydoc.html
and in the shell for options of the python command:
python -h
________________________________________________________________________________
________________________________________________________________________________
20161116
20161123
abbes.kacem@cstb.fr, jan.warnking@univ-grenoble-alpes.fr, Olivier Montigon <olivier.montigon@univ-grenoble-alpes.fr>, chhayarith.heng-uy@gipsa-lab.fr, Polina.Timofeeva@gipsa-lab.fr, Christophe Savariaux <christophe.savariaux@gipsa-lab.grenoble-inp.fr>, pierre.baraduc@gipsa-lab.fr, Paul.Galloux@ujf-grenoble.fr, Kevin Parisot <kevin.parisot@gipsa-lab.grenoble-inp.fr>
Chantal Delon-Martin <chantal.delon@univ-grenoble-alpes.fr>
201602
Coriandre Vilain
2015
Gelu, Pierre.Granjon,
________________________________________________________________________________
________________________________________________________________________________
% Historique
CWI: 1989-1995
Centrum voor Wiskunde en Informatica (CWI)
Guido von Rossum Fan Monty Python
OS amoeba accès difficile en shell
langage ABC (langage de script)
< ABC (syntaxe et indentation)
< Modula-3 (gestion des exceptions),
< langage C
< UNIX 5.
02/1991: 0.9.06 déposé sur Usenet alt.sources
python 1.2
CNRI: 1995-1999
CNRI, Reston, E.U.
Grail7 : navigateur internet utilisant Tk.
1999 : projet Computer Programming for Everybody (CP4E) (CNRI, DARPA).
Python comme langage d'enseignement de la programmation.
Création de l'IDLE (Integrated Development Language En)
python 1.6 en 1999
BeOpen.com: 1999 - 2000
compatibilité GPL (General Public Licence)
création de la branche pythonLabs
Python Software Foundation Digital Creations: 2000
python2.1 changement licence PSF dérivé Apache Software Foundation (oo, svn, commons plutôt java) (http://www.apache.org).
Python 3.0 en 2008 (modif librairie standard, classes d'objets)
Source (wikipedia)
Au CWI[modifier]
A la fin des années 1980, le programmeur Guido van Rossum participe au développement du langage de programmation ABC au Centrum voor Wiskunde en Informatica (CWI) d'Amsterdam, aux Pays-Bas. Il travaillait alors dans l’équipe du système d’exploitation Amoeba dont les appels systèmes étaient difficilement interfaçables avec le bourne shell utilisé comme interface utilisateur. Il estime alors qu’un langage de script inspiré d’ABC pourrait être intéressant comme interpréteur de commandes pour Amoeba3.
En 1989, profitant d’une semaine de vacances durant les fêtes de Noël, il utilise son ordinateur personnel4 pour écrire la première version du langage. Fan de la série télévisée des Monty Python, il décide de baptiser ce projet Python. Il s’est principalement inspiré d’ABC, par exemple pour l’indentation comme syntaxe ou les types de haut niveau mais aussi de Modula-3 pour la gestion des exceptions, du langage C et des outils UNIX5.
Durant l’année suivante, le langage commence à être adopté par l’équipe du projet Amoeba, Guido poursuivant son développement principalement pendant son temps libre. En février 1991, la première version publique, numérotée 0.9.06, est postée sur le forum Usenet alt.sources. La dernière version sortie au CWI fut Python 1.2
Au CNRI[modifier]
En 1995, Van Rossum continua son travail sur Python au CNRI (en) à Reston, aux États-Unis, où il sortit plusieurs versions du logiciel.
À partir d'août 1995, l'équipe Python travaille au CNRI sur Grail7 un navigateur web utilisant Tk. Il est l'équivalent pour Python du navigateur HotJava, permettant d'exécuter des applets dans un environnement sécurisé. La première version publique, disponible en novembre, est la 0.28. Il a entraîné le développement de modules pour la bibliothèque standard comme rexec9, htmllib ou urllib10. La version 0.6 sera la dernière de Grail; elle est publiée en avril 199911.
En 1999, le projet Computer Programming for Everybody (CP4E) est lancé avec collaboration entre le CNRI et la DARPA. Il s'agit d'utiliser Python comme langage d'enseignement de la programmation. Cette initiative conduira à la création de l'environnement de développement IDLE. Les subventions fournies par la DARPA ne suffisant pas à pérenniser le projet, Guido doit quitter le CNRI12. Python 1.6 fut la dernière version sortie au CNRI.
À BeOpen[modifier]
Après la sortie de Python 1.6, et après que Van Rossum eut quitté le CNRI pour travailler avec des développeurs de logiciels commerciaux, le CNRI et la Free Software Foundation collaborèrent pour modifier la licence de Python afin de la rendre compatible avec la GPL. Python 1.6.1 est essentiellement le même que Python 1.6 avec quelques correctifs mineurs et la nouvelle licence compatible GPL.
En 2000, l'équipe principale de développement de Python déménagea à BeOpen.com pour former l'équipe PythonLabs de BeOpen. Python 2.0 fut la seule version sortie à BeOpen.com. Après cette version, Guido Van Rossum et les autres développeurs de PythonLabs rejoignirent Digital Creations.
Andrew M. Kuchling a publié en décembre 199913 un texte nommé python warts14 qui synthétise les griefs les plus fréquents exprimés à l'encontre du langage. Ce document aura une influence certaine sur les développements futurs du langage15.
La Python Software Foundation[modifier]
Python 2.1 fut une version dérivée de Python 1.6.1, ainsi que de Python 2.0. Sa licence fut renommée Python Software Foundation License. Tout code, documentation et spécification ajouté, depuis la sortie de Python 2.1 alpha, est détenu par la Python Software Foundation (PSF), une association sans but lucratif fondée en 2001, modelée d'après l'Apache Software Foundation.
Afin de réparer certains défauts du langage (ex: orientation objet avec deux types de classes), et pour nettoyer la bibliothèque standard de ses éléments obsolètes et redondants, Python a choisi de casser la compatibilité ascendante dans la nouvelle version majeure : Python 3.0, publié en décembre 2008. Cette version a été suivie rapidement par une version 3.1 qui corrige les erreurs de jeunesse de la version 3.0 en la rendant directement obsolète.
Amoeba: a distributed operating system for the 1990s,
G Van Rossum et al. 1990
A description is given of the Amoeba distributed operating system, which appears to users as a centralized system but has the speed, fault tolerance, security safeguards, and flexibility required for the 1990s. The Amoeba software is based on objects. Objects are managed by server processes and named using capabilities chosen randomly from a sparse name space. Amoeba has a unique, fast file system split into two parts: the bullet service stores immutable files contiguously on the disk; the directory service gives capabilities symbolic names and handles replication and atomicity, eliminating the need for a separate transaction management system. To bridge the gap with existing systems, Amoeba has a Unix emulation facility consisting of a library of Unix system call routines that make calls to the various Amoeba server processes
python tutorial, G. van Rossum, F.L. Drake 1995
python library reference, G. van Rossum, F.L. Drake, 1995
python programming language, G. van Rossum, 1994
The ABC structure editor. Structure-based editing for the ABC programming environment, L.G.L.T. Meertens, S. Pemberton, G. van Rossum, 1992
exemple ABC :
PUT 0 IN count
FOR di, dj IN neighbours:
IF (i+di, j+dj) in keys c:
PUT count+c[i+di, j+dj] IN count
SELECT:
count = 3 OR count+c[i, j] = 3:
PUT 1 IN n[i, j]
ELSE:
PUT 0 IN n[i, j]
Guido van Rossum
31 janvier 1956 (57 ans)
Développeur néerlandais
Créateur Python
Benevolent Dictator for Life (« dictateur bienveillant à vie »)
1982 : M. Sc
Développeurs ABC
1991 : Python 0.9.06
1999 : Grail
2002 : Prix pour le développement du logiciel libre 2001 décerné par la Free Software Foundation (FSF)
2005-2012 : Google (python)
2013 : Dropbox
Guido van Rossum (31 janvier 1956 (57 ans)) est un développeur néerlandais, connu pour être le créateur et leader du projet du langage de programmation Python.
Au sein de la communauté pythonienne, il est considéré comme un Benevolent Dictator for Life (« dictateur bienveillant à vie »), ce qui signifie qu'il continue à suivre le développement de Python et qu'il prend des décisions lorsque c'est nécessaire.
Il est également l'auteur du navigateur web programmé entièrement en Python nommé Grail (qui n'a pas été actualisé depuis 1999), en référence au film Monty Python and the Holy Grail.
Il a fait ses études au Centre de Mathématiques de l’Université d'Amsterdam, obtenant son master en 1982.
Il fit partie des développeurs du langage ABC.
En 2002, il a reçu le Prix pour le développement du logiciel libre 2001 décerné par la FSF, lors de la FOSDEM de Bruxelles, pour récompenser son travail.
Fin 2005, il a été engagé par Google pour travailler sur Python.
En décembre 2012, il quitte Google pour rejoindre Dropbox à partir du 1er janvier 20131.
% duck typing
% decorators
% url syntaxe
% configuration locale et server.
svn checkout svn+ssh://gbecq@scm.forge.imag.fr/var/lib/gforge/chroot/scmrepos/svn/pycics/trunk
svn add --depth=empty presentationPython/
svn add presentationPython/presentationPython.tex
svn add presentationPython/command.tex
svn add presentationPython/main.tex
svn add presentationPython/fig/
svn add presentationPython/frame.tex
svn add --depth=infinity presentationPython/example/
commit -m "ajout présentationPython"
svn status
svn update
svn commit -m "message"
to avoid problem relative to
svnserve: warning: cannot set LC_CTYPE locale
svnserve: warning: environment variable LANG is fr_FR.UTF-8
svnserve: warning: please check that your locale name is correct
put in console:
export LC_ALL=C
svn checkout svn+ssh://lebihan@scm.forge.imag.fr/var/lib/gforge/chroot/scmrepos/svn/pycics/trunk
se mettre dans le répertoire contenant le /trunk /branches /tags
svn update
1. Mettre à jour votre copie de travail.
• svn update
2. Faire des changements.
• svn add
• svn delete
• svn copy
• svn move
3. Examiner les changements effectués.
• svn status
• svn diff
4. Éventuellement annuler des changements.
• svn revert
5. Résoudre les conflits (fusionner les modifications).
• svn update
• svn resolve
6. Propager les changements.
• svn commit
________________________________________________________________________________
________________________________________________________________________________
\section{test LSTLISTING}
\begin{frame}[fragile]
\begin{pythonConsole}
\\ 'a'bc def
% 'a'bc def
# 'a'bc def
""" abc def """
abc def
£'a'£
// 'a'
\end{pythonConsole}
\end{frame}
________________________________________________________________________________
________________________________________________________________________________
Faire une comparaison array versus matrix and vector.
matlab multiplication versus numpy multiplication.
________________________________________________________________________________
________________________________________________________________________________
package et module
passage des fonctions lors de l'import du package __init__.py
documentation du paquet dans le __init__.py
help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES METHODS SPECIALATTRIBUTES
BACKQUOTES ELLIPSIS MODULES SPECIALIDENTIFIERS
BASICMETHODS EXCEPTIONS NAMESPACES SPECIALMETHODS
BINARY EXECUTION NONE STRINGMETHODS
BITWISE EXPRESSIONS NUMBERMETHODS STRINGS
BOOLEAN FILES NUMBERS SUBSCRIPTS
CALLABLEMETHODS FLOAT OBJECTS TRACEBACKS
CALLS FORMATTING OPERATORS TRUTHVALUE
CLASSES FRAMEOBJECTS PACKAGES TUPLELITERALS
CODEOBJECTS FRAMES POWER TUPLES
COERCIONS FUNCTIONS PRECEDENCE TYPEOBJECTS
COMPARISON IDENTIFIERS PRINTING TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS1
Integrated Development Environment for Python
help(numpy)
Provides
1. An array object of arbitrary homogeneous items
2. Fast mathematical operations over arrays
3. Linear Algebra, Fourier Transforms, Random Number Generation
________________________________________________________________________________
________________________________________________________________________________
import imp
%load_ext autoreload,
%autoreload 2
%matplotlib inline
________________________________________________________________________________
________________________________________________________________________________
Passage de paramètres
args, kargs
________________________________________________________________________________
________________________________________________________________________________
NumPy (numerical python) is a module which was created allow efficient numerical calculations on multi-dimensional arrays of numbers from within Python. It is derived from the merger of two earlier modules named Numeric and Numarray. The actual work is done by calls to routines written in the Fortran and C languages.
indexing
slicing
broadcasting
________________________________________________________________________________
________________________________________________________________________________
produit de tableaux
numpy.inner
numpy.outer
etc
________________________________________________________________________________
________________________________________________________________________________
Dimension, axis and reshaping
x.ndim
x.shape
x.reshape
x.mean(axis=0)
________________________________________________________________________________
________________________________________________________________________________
passage de paramètres
*args, **kwargs
________________________________________________________________________________
________________________________________________________________________________
vérification des arguments
assert()
________________________________________________________________________________
________________________________________________________________________________
debugging
bon vieux print
pdb
pdb.set_trace()
________________________________________________________________________________
________________________________________________________________________________
Documenting pydoc and docstrings
pydoc
pydoc -g
docstring:
def f(x):
"""
first line
blahblah f()
"""
# abc
y = 2 * x
"""
blah
blah
"""
return y
help(f)
________________________________________________________________________________
________________________________________________________________________________
portée, namespace et autres
x = numpy.array([1., 2., 3., 4., 5.])
y = numpy.array([3., 2., 1., 0., 5.])
a = numpy.array([[1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.]])
a = numpy.arange(0, 5)
b = numpy.array([a, 2 * a, 3 * a, 4 * a])
c = numpy.array([b, 2 * b, 3 * b, 4 * a])
________________________________________________________________________________
________________________________________________________________________________
forme entre parenthèse :
permet d'aller à la ligne.
()
\begin{frame}
\begin{pythonConsole}
>> (1
... +2
... +3
... +4)
10
>>> ('abc' +
... 'def' +
... 'ghi')
'abcdefghi'
\end{pythonConsole}
\end{frame}
________________________________________________________________________________
________________________________________________________________________________
Comprehension list
liste itérateur
générateur
?
à développer ?
xrange object ?
return
yield
________________________________________________________________________________
________________________________________________________________________________
check logiciel indent
avec tab ou 4(x) espaces
________________________________________________________________________________
________________________________________________________________________________
import imp
imp.reload()
________________________________________________________________________________
________________________________________________________________________________
Dans la console
dans matlab
_ python
________________________________________________________________________________
________________________________________________________________________________
``a``
*a*
* item
_title_
''
________________________________________________________________________________
________________________________________________________________________________
Parler de ?
import doctest
doctest.testmod()
________________________________________________________________________________
________________________________________________________________________________
Anaconda 366 Mo (mail to fill)
pythonxy 813 Mo (no adress to fill)
canopy https://www.enthought.com/downloads/ pas accessible depuis un poste étudiant (information to fill)
________________________________________________________________________________
________________________________________________________________________________
As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=...) and str(b, encoding=...), respectively.
________________________________________________________________________________