├── .gitignore
├── Images
├── VAME_Logo-1.png
├── behavior_structure_crop.gif
├── cuttree_vis.jpg
└── workflow.png
├── LICENSE
├── README.md
├── VAME.yaml
├── examples
├── convert_maDLC_csv_individual_csv.py
├── demo.py
└── video-1.csv
├── reinstall.sh
├── setup.py
└── vame
├── __init__.py
├── analysis
├── __init__.py
├── community_analysis.py
├── generative_functions.py
├── gif_creator.py
├── pose_segmentation.py
├── segment_behavior.py
├── tree_hierarchy.py
├── umap_visualization.py
└── videowriter.py
├── initialize_project
├── __init__.py
└── new.py
├── model
├── __init__.py
├── create_training.py
├── dataloader.py
├── evaluate.py
├── rnn_model.py
└── rnn_vae.py
└── util
├── __init__.py
├── align_egocentrical.py
├── auxiliary.py
├── csv_to_npy.py
└── gif_pose_helper.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | #lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log*.ckpt
55 | snapshot-*
56 |
57 | # Byte-compiled / optimized / DLL files
58 | __pycache__/
59 | *.py[cod]
60 | local_settings.py
61 |
62 | # Flask stuff:
63 | instance/
64 | .webassets-cache
65 |
66 | # Scrapy stuff:
67 | .scrapy
68 |
69 | # Sphinx documentation
70 | docs/_build/
71 |
72 | # PyBuilder
73 | target/
74 |
75 | # Jupyter Notebook
76 | .ipynb_checkpoints
77 |
78 | # pyenv
79 | .python-version
80 |
81 | # celery beat schedule file
82 | celerybeat-schedule
83 |
84 | # SageMath parsed files
85 | *.sage.py
86 |
87 | # dotenv
88 | .env
89 |
90 | # virtualenv
91 | .venv
92 | venv/
93 | ENV/
94 |
95 | # Spyder project settings
96 | .spyderproject
97 | .spyproject
98 |
99 | # Rope project settings
100 | .ropeproject
101 |
102 | # mkdocs documentation
103 | /site
104 |
105 | # mypy
106 | .mypy_cache/
107 |
--------------------------------------------------------------------------------
/Images/VAME_Logo-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LINCellularNeuroscience/VAME/b97a5180b7c1b78823f9c6ec55853e32f2bd16e5/Images/VAME_Logo-1.png
--------------------------------------------------------------------------------
/Images/behavior_structure_crop.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LINCellularNeuroscience/VAME/b97a5180b7c1b78823f9c6ec55853e32f2bd16e5/Images/behavior_structure_crop.gif
--------------------------------------------------------------------------------
/Images/cuttree_vis.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LINCellularNeuroscience/VAME/b97a5180b7c1b78823f9c6ec55853e32f2bd16e5/Images/cuttree_vis.jpg
--------------------------------------------------------------------------------
/Images/workflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LINCellularNeuroscience/VAME/b97a5180b7c1b78823f9c6ec55853e32f2bd16e5/Images/workflow.png
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | 
3 |
4 | # New maintained VAME repository
5 |
6 | This version of VAME is deprecated and no longer maintained, and is made available here as legacy code. VAME is now being maintained at its new home at [https://github.com/EthoML/VAME](https://github.com/EthoML/VAME). There, you will find updated documentation and additional packages. Users can also access a downloadable desktop app for VAME at [https://github.com/EthoML/vame-desktop](https://github.com/EthoML/vame-desktop).
7 |
8 | # VAME in a Nutshell
9 | VAME is a framework to cluster behavioral signals obtained from pose-estimation tools. It is a [PyTorch](https://pytorch.org/) based deep learning framework which leverages the power of recurrent neural networks (RNN) to model sequential data. In order to learn the underlying complex data distribution we use the RNN in a variational autoencoder setting to extract the latent state of the animal in every step of the input time series.
10 |
11 | 
12 |
13 | The workflow of VAME consists of 5 steps and we explain them in detail [here](https://github.com/LINCellularNeuroscience/VAME/wiki/1.-VAME-Workflow).
14 |
15 | ## Installation
16 | To get started we recommend using [Anaconda](https://www.anaconda.com/distribution/) with Python 3.6 or higher.
17 | Here, you can create a [virtual enviroment](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html) to store all the dependencies necessary for VAME. (you can also use the VAME.yaml file supplied here, byt simply openning the terminal, running `git clone https://github.com/LINCellularNeuroscience/VAME.git`, then type `cd VAME` then run: `conda env create -f VAME.yaml`).
18 |
19 | * Go to the locally cloned VAME directory and run `python setup.py install` in order to install VAME in your active conda environment.
20 | * Install the current stable Pytorch release using the OS-dependent instructions from the [Pytorch website](https://pytorch.org/get-started/locally/). Currently, VAME is tested on PyTorch 1.5. (Note, if you use the conda file we supply, PyTorch is already installed and you don't need to do this step.)
21 |
22 | ## Getting Started
23 | First, you should make sure that you have a GPU powerful enough to train deep learning networks. In our paper, we were using a single Nvidia GTX 1080 Ti GPU to train our network. A hardware guide can be found [here](https://timdettmers.com/2018/12/16/deep-learning-hardware-guide/). Once you have your hardware ready, try VAME following the [workflow guide](https://github.com/LINCellularNeuroscience/VAME/wiki/1.-VAME-Workflow).
24 |
25 | If you want to follow an example first you can download [video-1](https://drive.google.com/file/d/1w6OW9cN_-S30B7rOANvSaR9c3O5KeF0c/view?usp=sharing) here and find the .csv file in our [example](https://github.com/LINCellularNeuroscience/VAME/tree/master/examples) folder.
26 |
27 | ## News
28 | * November 2022: Finally the VAME paper is published! Check it out [on the publisher werbsite](https://www.nature.com/articles/s42003-022-04080-7). In comparison to the preprint version, there is also a practical workflow guide included with many useful instructions on how to use VAME.
29 | * March 2021: We are happy to release VAME 1.0 with a bunch of improvements and new features! These include the community analysis script, a model allowing generation of unseen datapoints, new visualization functions, as well as the much requested function to generate GIF sequences containing UMAP embeddings and trajectories together with the video of the behaving animal. Big thanks also to [@MMathisLab](https://github.com/MMathisLab) for contributing to the OS compatibility and usability of our code.
30 | * November 2020: We uploaded an egocentric alignment [script](https://github.com/LINCellularNeuroscience/VAME/blob/master/examples/align_demo.py) to allow more researcher to use VAME
31 | * October 2020: We updated our manuscript on [Biorxiv](https://www.biorxiv.org/content/10.1101/2020.05.14.095430v2)
32 | * May 2020: Our preprint "Identifying Behavioral Structure from Deep Variational Embeddings of Animal Motion" is out! [Read it on Biorxiv!](https://www.biorxiv.org/content/10.1101/2020.05.14.095430v1)
33 |
34 | ### Authors and Code Contributors
35 | VAME was developed by Kevin Luxem and Pavol Bauer.
36 |
37 | The development of VAME is heavily inspired by [DeepLabCut](https://github.com/DeepLabCut/DeepLabCut/).
38 | As such, the VAME project management codebase has been adapted from the DeepLabCut codebase.
39 | The DeepLabCut 2.0 toolbox is © A. & M.W. Mathis Labs [deeplabcut.org](http:\\deeplabcut.org), released under LGPL v3.0.
40 | The implementation of the VRAE model is partially adapted from the [Timeseries clustering](https://github.com/tejaslodaya/timeseries-clustering-vae) repository developed by [Tejas Lodaya](https://tejaslodaya.com).
41 |
42 | ### References
43 | VAME preprint: [Identifying Behavioral Structure from Deep Variational Embeddings of Animal Motion](https://www.biorxiv.org/content/10.1101/2020.05.14.095430v2)
44 | Kingma & Welling: [Auto-Encoding Variational Bayes](https://arxiv.org/abs/1312.6114)
45 | Pereira & Silveira: [Learning Representations from Healthcare Time Series Data for Unsupervised Anomaly Detection](https://www.joao-pereira.pt/publications/accepted_version_BigComp19.pdf)
46 |
47 | ### License: GPLv3
48 | See the [LICENSE file](../master/LICENSE) for the full statement.
49 |
50 | ### Code Reference (DOI)
51 | [](https://zenodo.org/badge/latestdoi/254593619)
52 |
--------------------------------------------------------------------------------
/VAME.yaml:
--------------------------------------------------------------------------------
1 | # VAME.yaml
2 | #
3 | # install: conda env create -f VAME.yaml
4 | # update: conda env update -f VAME.yaml
5 | name: VAME
6 | channels:
7 | - pytorch
8 | - defaults
9 | dependencies:
10 | - python=3.7
11 | - pip
12 | - torchvision
13 | - jupyter
14 | - nb_conda
15 | - pip:
16 | - pytest-shutil
17 | - scipy
18 | - numpy
19 | - matplotlib
20 | - pathlib
21 | - pandas
22 | - ruamel.yaml
23 | - sklearn
24 | - pyyaml
25 | - opencv-python-headless
26 | - h5py
27 | - umap-learn
28 | - networkx
29 | - tqdm
30 | - hmmlearn
31 |
--------------------------------------------------------------------------------
/examples/convert_maDLC_csv_individual_csv.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Mon Feb 7 10:20:44 2022
4 |
5 | @author: Charitha Omprakash, LIN Magdeburg, charitha.omprakash@lin-magdeburg.de
6 |
7 | This file converts a multi-animal DLC CSV to several single animal DLC files.
8 | Those can be used as input to run VAME.
9 | """
10 |
11 | import pandas, numpy as pd, np
12 | import os
13 | import glob
14 | from pathlib import Path
15 |
16 | def convert_multi_csv_to_individual_csv(csv_files_path):
17 | csvs = sorted(glob.glob(os.path.join(csv_files_path, '*.csv*')))
18 |
19 | for csv in csvs:
20 | fname = pd.read_csv(csv, header=[0,1,2], index_col=0, skiprows=1)
21 | individuals = fname.columns.get_level_values('individuals').unique()
22 | for ind in individuals:
23 | fname_temp = fname[ind]
24 | fname_temp_path = os.path.splitext(csv)[0] + '_' + ind + '.csv'
25 | fname_temp.to_csv(fname_temp_path, index=True, header=True)
26 |
--------------------------------------------------------------------------------
/examples/demo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import vame
13 |
14 | # These paths have to be set manually
15 | working_directory = '/YOUR/WORKING/DIRECTORY/'
16 | project='Your-VAME-Project'
17 | videos = ['/directory/to/your/video-1','/directory/to/your/video-2','...']
18 |
19 | # Initialize your project
20 | # Step 1.1:
21 | config = vame.init_new_project(project=project, videos=videos, working_directory=working_directory, videotype='.mp4')
22 |
23 | # After the inital creation of your project you can always access the config.yaml file
24 | # via specifying the path to your project
25 | config = '/YOUR/WORKING/DIRECTORY/Your-VAME-Project-Apr14-2020/config.yaml'
26 |
27 | # As our config.yaml is sometimes still changing a little due to updates, we have here a small function
28 | # to update your config.yaml to the current state. Be aware that this will overwrite your current config.yaml
29 | # and make sure to back up your version if you did parameter changes!
30 | vame.update_config(config)
31 |
32 | # Step 1.2:
33 | # Align your behavior videos egocentric and create training dataset:
34 | # pose_ref_index: list of reference coordinate indices for alignment
35 | # Example: 0: snout, 1: forehand_left, 2: forehand_right, 3: hindleft, 4: hindright, 5: tail
36 | vame.egocentric_alignment(config, pose_ref_index=[0,5])
37 |
38 | # If your experiment is by design egocentrical (e.g. head-fixed experiment on treadmill etc)
39 | # you can use the following to convert your .csv to a .npy array, ready to train vame on it
40 | vame.csv_to_numpy(config)
41 |
42 | # Step 1.3:
43 | # create the training set for the VAME model
44 | vame.create_trainset(config, check_parameter=False)
45 |
46 | # Step 2:
47 | # Train VAME:
48 | vame.train_model(config)
49 |
50 | # Step 3:
51 | # Evaluate model
52 | vame.evaluate_model(config)
53 |
54 | # Step 4:
55 | # Segment motifs/pose
56 | vame.pose_segmentation(config)
57 |
58 |
59 | #------------------------------------------------------------------------------
60 | #------------------------------------------------------------------------------
61 | # The following are optional choices to create motif videos, communities/hierarchies of behavior,
62 | # community videos
63 |
64 | # OPTIONIAL: Create motif videos to get insights about the fine grained poses
65 | vame.motif_videos(config, videoType='.mp4')
66 |
67 | # OPTIONAL: Create behavioural hierarchies via community detection
68 | vame.community(config, show_umap=False, cut_tree=2)
69 |
70 | # OPTIONAL: Create community videos to get insights about behavior on a hierarchical scale
71 | vame.community_videos(config)
72 |
73 | # OPTIONAL: Down projection of latent vectors and visualization via UMAP
74 | vame.visualization(config, label=None) #options: label: None, "motif", "community"
75 |
76 | # OPTIONAL: Use the generative model (reconstruction decoder) to sample from
77 | # the learned data distribution, reconstruct random real samples or visualize
78 | # the cluster center for validation
79 | vame.generative_model(config, mode="centers") #options: mode: "sampling", "reconstruction", "centers", "motifs"
80 |
81 | # OPTIONAL: Create a video of an egocentrically aligned mouse + path through
82 | # the community space (similar to our gif on github) to learn more about your representation
83 | # and have something cool to show around ;)
84 | # Note: This function is currently very slow. Once the frames are saved you can create a video
85 | # or gif via e.g. ImageJ or other tools
86 | vame.gif(config, pose_ref_index=[0,5], subtract_background=True, start=None,
87 | length=500, max_lag=30, label='community', file_format='.mp4', crop_size=(300,300))
88 |
--------------------------------------------------------------------------------
/reinstall.sh:
--------------------------------------------------------------------------------
1 | pip uninstall vame
2 | python3 setup.py sdist bdist_wheel
3 | pip install dist/vame-1.0-py3-none-any.whl
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 |
3 | with open("README.md", "r") as fh:
4 | long_description = fh.read()
5 |
6 | setup(
7 | name="vame",
8 | version='1.0',
9 | packages=find_packages(),
10 | entry_points={"console_scripts": "vame = vame:main"},
11 | author="K. Luxem & P. Bauer",
12 | description="Variational Animal Motion Embedding.",
13 | long_description=long_description,
14 | long_description_content_type="text/markdown",
15 | url="https://https://github.com/LINCellularNeuroscience/VAME/",
16 | setup_requires=[
17 | "pytest",
18 | ],
19 | install_requires=[
20 | "pytest-shutil",
21 | "scipy",
22 | "numpy",
23 | "matplotlib",
24 | "pathlib",
25 | "pandas",
26 | "ruamel.yaml",
27 | "sklearn",
28 | "pyyaml",
29 | "opencv-python",
30 | ],
31 | )
32 |
--------------------------------------------------------------------------------
/vame/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 | import sys
12 | sys.dont_write_bytecode = True
13 |
14 | from vame.initialize_project import init_new_project
15 | from vame.model import create_trainset
16 | from vame.model import train_model
17 | from vame.model import evaluate_model
18 | from vame.analysis import pose_segmentation
19 | from vame.analysis import motif_videos
20 | from vame.analysis import community
21 | from vame.analysis import community_videos
22 | from vame.analysis import visualization
23 | from vame.analysis import generative_model
24 | from vame.analysis import gif
25 | from vame.util.csv_to_npy import csv_to_numpy
26 | from vame.util.align_egocentrical import egocentric_alignment
27 | from vame.util import auxiliary
28 | from vame.util.auxiliary import update_config
29 |
30 |
--------------------------------------------------------------------------------
/vame/analysis/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 | import sys
12 | sys.dont_write_bytecode = True
13 |
14 | from vame.analysis.pose_segmentation import pose_segmentation
15 | from vame.analysis.videowriter import motif_videos, community_videos
16 | from vame.analysis.community_analysis import community
17 | from vame.analysis.umap_visualization import visualization
18 | from vame.analysis.generative_functions import generative_model
19 | from vame.analysis.gif_creator import gif
20 |
21 |
--------------------------------------------------------------------------------
/vame/analysis/community_analysis.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import umap
14 | import scipy
15 | import pickle
16 | import numpy as np
17 | from pathlib import Path
18 | import matplotlib.pyplot as plt
19 |
20 | from vame.util.auxiliary import read_config
21 | from vame.analysis.tree_hierarchy import graph_to_tree, draw_tree, traverse_tree_cutline
22 |
23 |
24 | def get_adjacency_matrix(labels, n_cluster):
25 | temp_matrix = np.zeros((n_cluster,n_cluster), dtype=np.float64)
26 | adjacency_matrix = np.zeros((n_cluster,n_cluster), dtype=np.float64)
27 | cntMat = np.zeros((n_cluster))
28 | steps = len(labels)
29 |
30 | for i in range(n_cluster):
31 | for k in range(steps-1):
32 | idx = labels[k]
33 | if idx == i:
34 | idx2 = labels[k+1]
35 | if idx == idx2:
36 | continue
37 | else:
38 | cntMat[idx2] = cntMat[idx2] +1
39 | temp_matrix[i] = cntMat
40 | cntMat = np.zeros((n_cluster))
41 |
42 | for k in range(steps-1):
43 | idx = labels[k]
44 | idx2 = labels[k+1]
45 | if idx == idx2:
46 | continue
47 | adjacency_matrix[idx,idx2] = 1
48 | adjacency_matrix[idx2,idx] = 1
49 |
50 | transition_matrix = get_transition_matrix(temp_matrix)
51 |
52 | return adjacency_matrix, transition_matrix, temp_matrix
53 |
54 |
55 | def get_transition_matrix(adjacency_matrix, threshold = 0.0):
56 | row_sum=adjacency_matrix.sum(axis=1)
57 | transition_matrix = adjacency_matrix/row_sum[:,np.newaxis]
58 | transition_matrix[transition_matrix <= threshold] = 0
59 | if np.any(np.isnan(transition_matrix)):
60 | transition_matrix=np.nan_to_num(transition_matrix)
61 | return transition_matrix
62 |
63 |
64 | def get_labels(cfg, files, model_name, n_cluster,parameterization):
65 | labels = []
66 | for file in files:
67 | path_to_file = os.path.join(cfg['project_path'],"results",file,model_name,parameterization+'-'+str(n_cluster),"")
68 | label = np.load(os.path.join(path_to_file,str(n_cluster)+'_km_label_'+file+'.npy'))
69 | labels.append(label)
70 | return labels
71 |
72 | def compute_transition_matrices(files, labels, n_cluster):
73 | transition_matrices = []
74 | for i, file in enumerate(files):
75 | adj, trans, mat = get_adjacency_matrix(labels[i], n_cluster)
76 | transition_matrices.append(trans)
77 | return transition_matrices
78 |
79 |
80 | def create_community_bag(files, labels, transition_matrices, cut_tree, n_cluster):
81 | # markov chain to tree -> community detection
82 | trees = []
83 | communities_all = []
84 | for i, file in enumerate(files):
85 | _, usage = np.unique(labels[i], return_counts=True)
86 | T = graph_to_tree(usage, transition_matrices[i], n_cluster, merge_sel=1)
87 | trees.append(T)
88 |
89 | if cut_tree != None:
90 | community_bag = traverse_tree_cutline(T,cutline=cut_tree)
91 | communities_all.append(community_bag)
92 | draw_tree(T)
93 | else:
94 | draw_tree(T)
95 | plt.pause(0.5)
96 | flag_1 = 'no'
97 | while flag_1 == 'no':
98 | cutline = int(input("Where do you want to cut the Tree? 0/1/2/3/..."))
99 | community_bag = traverse_tree_cutline(T,cutline=cutline)
100 | print(community_bag)
101 | flag_2 = input('\nAre all motifs in the list? (yes/no/restart)')
102 | if flag_2 == 'no':
103 | while flag_2 == 'no':
104 | add = input('Extend list or add in the end? (ext/end)')
105 | if add == "ext":
106 | motif_idx = int(input('Which motif number? '))
107 | list_idx = int(input('At which position in the list? (pythonic indexing starts at 0) '))
108 | community_bag[list_idx].append(motif_idx)
109 | if add == "end":
110 | motif_idx = int(input('Which motif number? '))
111 | community_bag.append([motif_idx])
112 | print(community_bag)
113 | flag_2 = input('\nAre all motifs in the list? (yes/no/restart)')
114 | if flag_2 == "restart":
115 | continue
116 | if flag_2 == 'yes':
117 | communities_all.append(community_bag)
118 | flag_1 = 'yes'
119 |
120 | return communities_all, trees
121 |
122 |
123 | def get_community_labels(files, labels, communities_all):
124 | # transform parameterized latent vector into communities
125 | community_labels_all = []
126 | for k, file in enumerate(files):
127 | num_comm = len(communities_all[k])
128 |
129 | community_labels = np.zeros_like(labels[k])
130 | for i in range(num_comm):
131 | clust = np.array(communities_all[k][i])
132 | for j in range(len(clust)):
133 | find_clust = np.where(labels[k] == clust[j])[0]
134 | community_labels[find_clust] = i
135 |
136 | community_labels = np.int64(scipy.signal.medfilt(community_labels, 7))
137 | community_labels_all.append(community_labels)
138 |
139 | return community_labels_all
140 |
141 |
142 | def umap_embedding(cfg, file, model_name, n_cluster,parameterization):
143 | reducer = umap.UMAP(n_components=2, min_dist=cfg['min_dist'], n_neighbors=cfg['n_neighbors'],
144 | random_state=cfg['random_state'])
145 |
146 | print("UMAP calculation for file %s" %file)
147 |
148 | folder = os.path.join(cfg['project_path'],"results",file,model_name,parameterization+'-'+str(n_cluster),"")
149 | latent_vector = np.load(os.path.join(folder,'latent_vector_'+file+'.npy'))
150 |
151 | num_points = cfg['num_points']
152 | if num_points > latent_vector.shape[0]:
153 | num_points = latent_vector.shape[0]
154 | print("Embedding %d data points.." %num_points)
155 |
156 | embed = reducer.fit_transform(latent_vector[:num_points,:])
157 |
158 | return embed
159 |
160 |
161 | def umap_vis(cfg, file, embed, community_labels_all):
162 | num_points = cfg['num_points']
163 | if num_points > community_labels_all.shape[0]:
164 | num_points = community_labels_all.shape[0]
165 | print("Embedding %d data points.." %num_points)
166 |
167 | num = np.unique(community_labels_all)
168 |
169 | fig = plt.figure(1)
170 | plt.scatter(embed[:,0], embed[:,1], c=community_labels_all[:num_points], cmap='Spectral', s=2, alpha=1)
171 | plt.colorbar(boundaries=np.arange(np.max(num)+2)-0.5).set_ticks(np.arange(np.max(num)+1))
172 | plt.gca().set_aspect('equal', 'datalim')
173 | plt.grid(False)
174 |
175 |
176 | def community(config, show_umap=False, cut_tree=None):
177 | config_file = Path(config).resolve()
178 | cfg = read_config(config_file)
179 | model_name = cfg['model_name']
180 | n_cluster = cfg['n_cluster']
181 | parameterization = cfg['parameterization']
182 |
183 | files = []
184 | if cfg['all_data'] == 'No':
185 | all_flag = input("Do you want to write motif videos for your entire dataset? \n"
186 | "If you only want to use a specific dataset type filename: \n"
187 | "yes/no/filename ")
188 | else:
189 | all_flag = 'yes'
190 |
191 | if all_flag == 'yes' or all_flag == 'Yes':
192 | for file in cfg['video_sets']:
193 | files.append(file)
194 |
195 | elif all_flag == 'no' or all_flag == 'No':
196 | for file in cfg['video_sets']:
197 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
198 | if use_file == 'yes':
199 | files.append(file)
200 | if use_file == 'no':
201 | continue
202 | else:
203 | files.append(all_flag)
204 |
205 | labels = get_labels(cfg, files, model_name, n_cluster,parameterization)
206 | transition_matrices = compute_transition_matrices(files, labels, n_cluster)
207 | communities_all, trees = create_community_bag(files, labels, transition_matrices, cut_tree, n_cluster)
208 | community_labels_all = get_community_labels(files, labels, communities_all)
209 |
210 | for idx, file in enumerate(files):
211 | path_to_file=os.path.join(cfg['project_path'],"results",file,model_name,parameterization+'-'+str(n_cluster),"")
212 | if not os.path.exists(os.path.join(path_to_file,"community")):
213 | os.mkdir(os.path.join(path_to_file,"community"))
214 |
215 | np.save(os.path.join(path_to_file,"community","transition_matrix_"+file+'.npy'),transition_matrices[idx])
216 | np.save(os.path.join(path_to_file,"community","community_label_"+file+'.npy'), community_labels_all[idx])
217 |
218 | with open(os.path.join(path_to_file,"community","hierarchy"+file+".pkl"), "wb") as fp: #Pickling
219 | pickle.dump(communities_all[idx], fp)
220 |
221 | if show_umap == True:
222 | embed = umap_embedding(cfg, file, model_name, n_cluster,parameterization)
223 | umap_vis(cfg, files, embed, community_labels_all[idx])
224 |
225 | # with open(os.path.join(path_to_file,"community","","hierarchy"+file+".txt"), "rb") as fp: # Unpickling
226 | # b = pickle.load(fp)
227 |
228 |
229 |
230 |
231 |
232 |
--------------------------------------------------------------------------------
/vame/analysis/generative_functions.py:
--------------------------------------------------------------------------------
1 | """
2 | Variational Animal Motion Embedding 1.0-alpha Toolbox
3 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
4 | Leibniz Institute for Neurobiology, Magdeburg, Germany
5 |
6 | https://github.com/LINCellularNeuroscience/VAME
7 | Licensed under GNU General Public License v3.0
8 | """
9 |
10 | import os
11 |
12 | import torch
13 | import numpy as np
14 | from pathlib import Path
15 | import matplotlib.pyplot as plt
16 | from sklearn.mixture import GaussianMixture
17 |
18 | from vame.util.auxiliary import read_config
19 | from vame.model.rnn_model import RNN_VAE
20 |
21 |
22 | def random_generative_samples_motif(cfg, model, latent_vector,labels,n_cluster):
23 | # Latent sampling and generative model
24 | time_window = cfg['time_window']
25 | for j in range(n_cluster):
26 |
27 | inds=np.where(labels==j)
28 | motif_latents=latent_vector[inds[0],:]
29 | gm = GaussianMixture(n_components=10).fit(motif_latents)
30 |
31 | # draw sample from GMM
32 | density_sample = gm.sample(10)
33 |
34 | # generate image via model decoder
35 | tensor_sample = torch.from_numpy(density_sample[0]).type('torch.FloatTensor').cuda()
36 | decoder_inputs = tensor_sample.unsqueeze(2).repeat(1, 1, time_window)
37 | decoder_inputs = decoder_inputs.permute(0,2,1)
38 |
39 | image_sample = model.decoder(decoder_inputs, tensor_sample)
40 | recon_sample = image_sample.cpu().detach().numpy()
41 |
42 |
43 | fig, axs = plt.subplots(2,5)
44 | for i in range(5):
45 | axs[0,i].plot(recon_sample[i,...])
46 | axs[1,i].plot(recon_sample[i+5,...])
47 | plt.suptitle('Generated samples for motif '+str(j))
48 |
49 | def random_generative_samples(cfg, model, latent_vector):
50 | # Latent sampling and generative model
51 | time_window = cfg['time_window']
52 | gm = GaussianMixture(n_components=10).fit(latent_vector)
53 |
54 | # draw sample from GMM
55 | density_sample = gm.sample(10)
56 |
57 | # generate image via model decoder
58 | tensor_sample = torch.from_numpy(density_sample[0]).type('torch.FloatTensor').cuda()
59 | decoder_inputs = tensor_sample.unsqueeze(2).repeat(1, 1, time_window)
60 | decoder_inputs = decoder_inputs.permute(0,2,1)
61 |
62 | image_sample = model.decoder(decoder_inputs, tensor_sample)
63 | recon_sample = image_sample.cpu().detach().numpy()
64 |
65 | fig, axs = plt.subplots(2,5)
66 | for i in range(5):
67 | axs[0,i].plot(recon_sample[i,...])
68 | axs[1,i].plot(recon_sample[i+5,...])
69 | plt.suptitle('Generated samples')
70 |
71 |
72 | def random_reconstruction_samples(cfg, model, latent_vector):
73 | # random samples for reconstruction
74 | time_window = cfg['time_window']
75 |
76 | rnd = np.random.choice(latent_vector.shape[0], 10)
77 | tensor_sample = torch.from_numpy(latent_vector[rnd]).type('torch.FloatTensor').cuda()
78 | decoder_inputs = tensor_sample.unsqueeze(2).repeat(1, 1, time_window)
79 | decoder_inputs = decoder_inputs.permute(0,2,1)
80 |
81 | image_sample = model.decoder(decoder_inputs, tensor_sample)
82 | recon_sample = image_sample.cpu().detach().numpy()
83 |
84 | fig, axs = plt.subplots(2,5)
85 | for i in range(5):
86 | axs[0,i].plot(recon_sample[i,...])
87 | axs[1,i].plot(recon_sample[i+5,...])
88 | plt.suptitle('Reconstructed samples')
89 |
90 |
91 | def visualize_cluster_center(cfg, model, cluster_center):
92 | #Cluster Center
93 | time_window = cfg['time_window']
94 | animal_centers = cluster_center
95 |
96 | tensor_sample = torch.from_numpy(animal_centers).type('torch.FloatTensor').cuda()
97 | decoder_inputs = tensor_sample.unsqueeze(2).repeat(1, 1, time_window)
98 | decoder_inputs = decoder_inputs.permute(0,2,1)
99 |
100 | image_sample = model.decoder(decoder_inputs, tensor_sample)
101 | recon_sample = image_sample.cpu().detach().numpy()
102 |
103 | num = animal_centers.shape[0]
104 | b = int(np.ceil(num / 5))
105 |
106 | fig, axs = plt.subplots(5,b)
107 | idx = 0
108 | for k in range(5):
109 | for i in range(b):
110 | axs[k,i].plot(recon_sample[idx,...])
111 | axs[k,i].set_title("Cluster %d" %idx)
112 | idx +=1
113 |
114 |
115 | def load_model(cfg, model_name):
116 | # load Model
117 | ZDIMS = cfg['zdims']
118 | FUTURE_DECODER = cfg['prediction_decoder']
119 | TEMPORAL_WINDOW = cfg['time_window']*2
120 | FUTURE_STEPS = cfg['prediction_steps']
121 |
122 | NUM_FEATURES = cfg['num_features']
123 | NUM_FEATURES = NUM_FEATURES - 2
124 |
125 | hidden_size_layer_1 = cfg['hidden_size_layer_1']
126 | hidden_size_layer_2 = cfg['hidden_size_layer_2']
127 | hidden_size_rec = cfg['hidden_size_rec']
128 | hidden_size_pred = cfg['hidden_size_pred']
129 | dropout_encoder = cfg['dropout_encoder']
130 | dropout_rec = cfg['dropout_rec']
131 | dropout_pred = cfg['dropout_pred']
132 | softplus = cfg['softplus']
133 |
134 | print('Load model... ')
135 | model = RNN_VAE(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
136 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
137 | dropout_rec, dropout_pred, softplus).cuda()
138 |
139 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],'model','best_model',model_name+'_'+cfg['Project']+'.pkl')))
140 | model.eval()
141 |
142 | return model
143 |
144 |
145 | def generative_model(config, mode="sampling"):
146 | config_file = Path(config).resolve()
147 | cfg = read_config(config_file)
148 | model_name = cfg['model_name']
149 | n_cluster = cfg['n_cluster']
150 |
151 | files = []
152 | if cfg['all_data'] == 'No':
153 | all_flag = input("Do you want to write motif videos for your entire dataset? \n"
154 | "If you only want to use a specific dataset type filename: \n"
155 | "yes/no/filename ")
156 | else:
157 | all_flag = 'yes'
158 |
159 | if all_flag == 'yes' or all_flag == 'Yes':
160 | for file in cfg['video_sets']:
161 | files.append(file)
162 |
163 | elif all_flag == 'no' or all_flag == 'No':
164 | for file in cfg['video_sets']:
165 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
166 | if use_file == 'yes':
167 | files.append(file)
168 | if use_file == 'no':
169 | continue
170 | else:
171 | files.append(all_flag)
172 |
173 |
174 | model = load_model(cfg, model_name)
175 |
176 | for file in files:
177 | path_to_file=os.path.join(cfg['project_path'],"results",file,model_name,'kmeans-'+str(n_cluster),"")
178 |
179 | if mode == "sampling":
180 | latent_vector = np.load(os.path.join(path_to_file,'latent_vector_'+file+'.npy'))
181 | random_generative_samples(cfg, model, latent_vector)
182 |
183 | if mode == "reconstruction":
184 | latent_vector = np.load(os.path.join(path_to_file,'latent_vector_'+file+'.npy'))
185 | random_reconstruction_samples(cfg, model, latent_vector)
186 |
187 | if mode == "centers":
188 | cluster_center = np.load(os.path.join(path_to_file,'cluster_center_'+file+'.npy'))
189 | visualize_cluster_center(cfg, model, cluster_center)
190 |
191 | if mode == "motifs":
192 | latent_vector = np.load(os.path.join(path_to_file,'latent_vector_'+file+'.npy'))
193 | labels = np.load(os.path.join(path_to_file,"",str(n_cluster)+'_km_label_'+file+'.npy'))
194 | random_generative_samples_motif(cfg, model, latent_vector,labels,n_cluster)
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
--------------------------------------------------------------------------------
/vame/analysis/gif_creator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import tqdm
14 | import umap
15 | import numpy as np
16 | from pathlib import Path
17 | import matplotlib
18 | from matplotlib import pyplot as plt
19 | from matplotlib.gridspec import GridSpec
20 | from vame.util.auxiliary import read_config
21 | from vame.util.gif_pose_helper import get_animal_frames
22 |
23 |
24 | def create_video(path_to_file, file, embed, clabel, frames, start, length, max_lag, num_points):
25 | # set matplotlib colormap
26 | cmap = matplotlib.cm.gray
27 | cmap_reversed = matplotlib.cm.get_cmap('gray_r')
28 |
29 | # this here generates every frame for your gif. The gif is lastly created by using ImageJ
30 | # the embed variable is my umap embedding, which is for the 2D case a 2xn dimensional vector
31 | fig = plt.figure()
32 | spec = GridSpec(ncols=2, nrows=1, width_ratios=[6, 3])
33 | ax1 = fig.add_subplot(spec[0])
34 | ax2 = fig.add_subplot(spec[1])
35 | ax2.axis('off')
36 | ax2.grid(False)
37 | lag = 0
38 | for i in tqdm.tqdm(range(length)):
39 | if i > max_lag:
40 | lag = i - max_lag
41 | ax1.cla()
42 | ax1.axis('off')
43 | ax1.grid(False)
44 | ax1.scatter(embed[:num_points,0], embed[:num_points,1], c=clabel[:num_points], cmap='Spectral', s=1, alpha=0.4)
45 | ax1.set_aspect('equal', 'datalim')
46 | ax1.plot(embed[start+lag:start+i,0], embed[start+lag:start+i,1],'.b-',alpha=.6, linewidth=2, markersize=4)
47 | ax1.plot(embed[start+i,0], embed[start+i,1], 'gx', markersize=4)
48 | frame = frames[i]
49 | ax2.imshow(frame, cmap=cmap_reversed)
50 | # ax2.set_title("Motif %d,\n Community: %s" % (lbl, motifs[lbl]), fontsize=10)
51 | fig.savefig(os.path.join(path_to_file,"gif_frames",file+'gif_%d.png') %i)
52 |
53 |
54 | def gif(config, pose_ref_index, subtract_background=True, start=None, length=500,
55 | max_lag=30, label='community', file_format='.mp4', crop_size=(300,300)):
56 |
57 | config_file = Path(config).resolve()
58 | cfg = read_config(config_file)
59 | model_name = cfg['model_name']
60 | n_cluster = cfg['n_cluster']
61 | param = cfg['parameterization']
62 |
63 | files = []
64 | if cfg['all_data'] == 'No':
65 | all_flag = input("Do you want to write motif videos for your entire dataset? \n"
66 | "If you only want to use a specific dataset type filename: \n"
67 | "yes/no/filename ")
68 | else:
69 | all_flag = 'yes'
70 |
71 | if all_flag == 'yes' or all_flag == 'Yes':
72 | for file in cfg['video_sets']:
73 | files.append(file)
74 |
75 | elif all_flag == 'no' or all_flag == 'No':
76 | for file in cfg['video_sets']:
77 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
78 | if use_file == 'yes':
79 | files.append(file)
80 | if use_file == 'no':
81 | continue
82 | else:
83 | files.append(all_flag)
84 |
85 |
86 | for file in files:
87 | path_to_file=os.path.join(cfg['project_path'],"results",file,model_name,param+'-'+str(n_cluster),"")
88 | if not os.path.exists(os.path.join(path_to_file,"gif_frames")):
89 | os.mkdir(os.path.join(path_to_file,"gif_frames"))
90 |
91 | embed = np.load(os.path.join(path_to_file,"community","umap_embedding_"+file+'.npy'))
92 |
93 | try:
94 | embed = np.load(os.path.join(path_to_file,"","community","","umap_embedding_"+file+".npy"))
95 | num_points = cfg['num_points']
96 | if num_points > embed.shape[0]:
97 | num_points = embed.shape[0]
98 | except:
99 | print("Compute embedding for file %s" %file)
100 | reducer = umap.UMAP(n_components=2, min_dist=cfg['min_dist'], n_neighbors=cfg['n_neighbors'],
101 | random_state=cfg['random_state'])
102 |
103 | latent_vector = np.load(os.path.join(path_to_file,"",'latent_vector_'+file+'.npy'))
104 |
105 | num_points = cfg['num_points']
106 | if num_points > latent_vector.shape[0]:
107 | num_points = latent_vector.shape[0]
108 | print("Embedding %d data points.." %num_points)
109 |
110 | embed = reducer.fit_transform(latent_vector[:num_points,:])
111 | np.save(os.path.join(path_to_file,"community","umap_embedding_"+file+'.npy'), embed)
112 |
113 | if label == "motif":
114 | umap_label = np.load(os.path.join(path_to_file,str(n_cluster)+"_km_label_"+file+'.npy'))
115 | elif label == "community":
116 | umap_label = np.load(os.path.join(path_to_file,"community","community_label_"+file+'.npy'))
117 | elif label == None:
118 | umap_label = None
119 |
120 | if start == None:
121 | start = np.random.choice(embed[:num_points].shape[0]-length)
122 | else:
123 | start = start
124 |
125 | frames = get_animal_frames(cfg, file, pose_ref_index, start, length, subtract_background, file_format, crop_size)
126 |
127 | create_video(path_to_file, file, embed, umap_label, frames, start, length, max_lag, num_points)
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 |
--------------------------------------------------------------------------------
/vame/analysis/pose_segmentation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import tqdm
14 | import torch
15 | import pickle
16 | import numpy as np
17 | from pathlib import Path
18 |
19 |
20 | from hmmlearn import hmm
21 | from sklearn.cluster import KMeans
22 |
23 | from vame.util.auxiliary import read_config
24 | from vame.model.rnn_model import RNN_VAE
25 |
26 |
27 | def load_model(cfg, model_name, fixed):
28 | use_gpu = torch.cuda.is_available()
29 | if use_gpu:
30 | pass
31 | else:
32 | torch.device("cpu")
33 |
34 | # load Model
35 | ZDIMS = cfg['zdims']
36 | FUTURE_DECODER = cfg['prediction_decoder']
37 | TEMPORAL_WINDOW = cfg['time_window']*2
38 | FUTURE_STEPS = cfg['prediction_steps']
39 | NUM_FEATURES = cfg['num_features']
40 | if fixed == False:
41 | NUM_FEATURES = NUM_FEATURES - 2
42 | hidden_size_layer_1 = cfg['hidden_size_layer_1']
43 | hidden_size_layer_2 = cfg['hidden_size_layer_2']
44 | hidden_size_rec = cfg['hidden_size_rec']
45 | hidden_size_pred = cfg['hidden_size_pred']
46 | dropout_encoder = cfg['dropout_encoder']
47 | dropout_rec = cfg['dropout_rec']
48 | dropout_pred = cfg['dropout_pred']
49 | softplus = cfg['softplus']
50 |
51 |
52 | if use_gpu:
53 | model = RNN_VAE(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
54 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
55 | dropout_rec, dropout_pred, softplus).cuda()
56 | else:
57 | model = RNN_VAE(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
58 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
59 | dropout_rec, dropout_pred, softplus).to()
60 |
61 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],'model','best_model',model_name+'_'+cfg['Project']+'.pkl')))
62 | model.eval()
63 |
64 | return model
65 |
66 |
67 | def embedd_latent_vectors(cfg, files, model, fixed):
68 | project_path = cfg['project_path']
69 | temp_win = cfg['time_window']
70 | num_features = cfg['num_features']
71 | if fixed == False:
72 | num_features = num_features - 2
73 |
74 | use_gpu = torch.cuda.is_available()
75 | if use_gpu:
76 | pass
77 | else:
78 | torch.device("cpu")
79 |
80 | latent_vector_files = []
81 |
82 | for file in files:
83 | print('Embedding of latent vector for file %s' %file)
84 | data = np.load(os.path.join(project_path,'data',file,file+'-PE-seq-clean.npy'))
85 | latent_vector_list = []
86 | with torch.no_grad():
87 | for i in tqdm.tqdm(range(data.shape[1] - temp_win)):
88 | # for i in tqdm.tqdm(range(10000)):
89 | data_sample_np = data[:,i:temp_win+i].T
90 | data_sample_np = np.reshape(data_sample_np, (1, temp_win, num_features))
91 | if use_gpu:
92 | h_n = model.encoder(torch.from_numpy(data_sample_np).type('torch.FloatTensor').cuda())
93 | else:
94 | h_n = model.encoder(torch.from_numpy(data_sample_np).type('torch.FloatTensor').to())
95 | mu, _, _ = model.lmbda(h_n)
96 | latent_vector_list.append(mu.cpu().data.numpy())
97 |
98 | latent_vector = np.concatenate(latent_vector_list, axis=0)
99 | latent_vector_files.append(latent_vector)
100 |
101 | return latent_vector_files
102 |
103 |
104 | def consecutive(data, stepsize=1):
105 | data = data[:]
106 | return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
107 |
108 |
109 | def get_motif_usage(label):
110 | motif_usage = np.unique(label, return_counts=True)
111 | cons = consecutive(motif_usage[0])
112 | if len(cons) != 1:
113 | usage_list = list(motif_usage[1])
114 | for i in range(len(cons)-1):
115 | a = cons[i+1][0]
116 | b = cons[i][-1]
117 | d = (a-b)-1
118 | for j in range(1,d+1):
119 | index = cons[i][-1]+j
120 | usage_list.insert(index,0)
121 | usage = np.array(usage_list)
122 | motif_usage = usage
123 | else:
124 | motif_usage = motif_usage[1]
125 |
126 | return motif_usage
127 |
128 |
129 | def same_parameterization(cfg, files, latent_vector_files, states, parameterization):
130 | random_state = cfg['random_state_kmeans']
131 | n_init = cfg['n_init_kmeans']
132 |
133 | labels = []
134 | cluster_centers = []
135 | motif_usages = []
136 |
137 | latent_vector_cat = np.concatenate(latent_vector_files, axis=0)
138 |
139 | if parameterization == "kmeans":
140 | print("Using kmeans as parameterization!")
141 | kmeans = KMeans(init='k-means++', n_clusters=states, random_state=42, n_init=20).fit(latent_vector_cat)
142 | clust_center = kmeans.cluster_centers_
143 | label = kmeans.predict(latent_vector_cat)
144 |
145 | elif parameterization == "hmm":
146 | if cfg['hmm_trained'] == False:
147 | print("Using a HMM as parameterization!")
148 | hmm_model = hmm.GaussianHMM(n_components=states, covariance_type="full", n_iter=100)
149 | hmm_model.fit(latent_vector_cat)
150 | label = hmm_model.predict(latent_vector_cat)
151 | save_data = os.path.join(cfg['project_path'], "results", "")
152 | with open(save_data+"hmm_trained.pkl", "wb") as file: pickle.dump(hmm_model, file)
153 | else:
154 | print("Using a pretrained HMM as parameterization!")
155 | save_data = os.path.join(cfg['project_path'], "results", "")
156 | with open(save_data+"hmm_trained.pkl", "rb") as file:
157 | hmm_model = pickle.load(file)
158 | label = hmm_model.predict(latent_vector_cat)
159 |
160 | idx = 0
161 | for i, file in enumerate(files):
162 | file_len = latent_vector_files[i].shape[0]
163 | labels.append(label[idx:idx+file_len])
164 | if parameterization == "kmeans":
165 | cluster_centers.append(clust_center)
166 |
167 | motif_usage = get_motif_usage(label[idx:idx+file_len])
168 | motif_usages.append(motif_usage)
169 | idx += file_len
170 |
171 | return labels, cluster_centers, motif_usages
172 |
173 |
174 | def individual_parameterization(cfg, files, latent_vector_files, cluster):
175 | random_state = cfg['random_state_kmeans: ']
176 | n_init = cfg['n_init_kmeans']
177 |
178 | labels = []
179 | cluster_centers = []
180 | motif_usages = []
181 | for i, file in enumerate(files):
182 | print(file)
183 | kmeans = KMeans(init='k-means++', n_clusters=cluster, random_state=random_state, n_init=n_init).fit(latent_vector_files[i])
184 | clust_center = kmeans.cluster_centers_
185 | label = kmeans.predict(latent_vector_files[i])
186 | motif_usage = get_motif_usage(label)
187 | motif_usages.append(motif_usage)
188 | labels.append(label)
189 | cluster_centers.append(clust_center)
190 |
191 | return labels, cluster_centers, motif_usages
192 |
193 |
194 | def pose_segmentation(config):
195 | config_file = Path(config).resolve()
196 | cfg = read_config(config_file)
197 | legacy = cfg['legacy']
198 | model_name = cfg['model_name']
199 | n_cluster = cfg['n_cluster']
200 | fixed = cfg['egocentric_data']
201 | parameterization = cfg['parameterization']
202 |
203 | print('Pose segmentation for VAME model: %s \n' %model_name)
204 |
205 | if legacy == True:
206 | from segment_behavior import behavior_segmentation
207 | behavior_segmentation(config, model_name=model_name, cluster_method='kmeans', n_cluster=n_cluster)
208 |
209 | else:
210 | ind_param = cfg['individual_parameterization']
211 |
212 | for folders in cfg['video_sets']:
213 | if not os.path.exists(os.path.join(cfg['project_path'],"results",folders,model_name,"")):
214 | os.mkdir(os.path.join(cfg['project_path'],"results",folders,model_name,""))
215 |
216 | files = []
217 | if cfg['all_data'] == 'No':
218 | all_flag = input("Do you want to qunatify your entire dataset? \n"
219 | "If you only want to use a specific dataset type filename: \n"
220 | "yes/no/filename ")
221 | file = all_flag
222 |
223 | else:
224 | all_flag = 'yes'
225 |
226 | if all_flag == 'yes' or all_flag == 'Yes':
227 | for file in cfg['video_sets']:
228 | files.append(file)
229 | elif all_flag == 'no' or all_flag == 'No':
230 | for file in cfg['video_sets']:
231 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
232 | if use_file == 'yes':
233 | files.append(file)
234 | if use_file == 'no':
235 | continue
236 | else:
237 | files.append(all_flag)
238 | # files.append("mouse-3-1")
239 | # file="mouse-3-1"
240 |
241 | use_gpu = torch.cuda.is_available()
242 | if use_gpu:
243 | print("Using CUDA")
244 | print('GPU active:',torch.cuda.is_available())
245 | print('GPU used:',torch.cuda.get_device_name(0))
246 | else:
247 | print("CUDA is not working! Attempting to use the CPU...")
248 | torch.device("cpu")
249 |
250 | if not os.path.exists(os.path.join(cfg['project_path'],"results",file,model_name, parameterization+'-'+str(n_cluster),"")):
251 | new = True
252 | # print("Hello1")
253 | model = load_model(cfg, model_name, fixed)
254 | latent_vectors = embedd_latent_vectors(cfg, files, model, fixed)
255 |
256 | if ind_param == False:
257 | print("For all animals the same parameterization of latent vectors is applied for %d cluster" %n_cluster)
258 | labels, cluster_center, motif_usages = same_parameterization(cfg, files, latent_vectors, n_cluster, parameterization)
259 | else:
260 | print("Individual parameterization of latent vectors for %d cluster" %n_cluster)
261 | labels, cluster_center, motif_usages = individual_parameterization(cfg, files, latent_vectors, n_cluster)
262 |
263 | else:
264 | print('\n'
265 | 'For model %s a latent vector embedding already exists. \n'
266 | 'Parameterization of latent vector with %d k-Means cluster' %(model_name, n_cluster))
267 |
268 | if os.path.exists(os.path.join(cfg['project_path'],"results",file,model_name, parameterization+'-'+str(n_cluster),"")):
269 | flag = input('WARNING: A parameterization for the chosen cluster size of the model already exists! \n'
270 | 'Do you want to continue? A new parameterization will be computed! (yes/no) ')
271 | else:
272 | flag = 'yes'
273 |
274 | if flag == 'yes':
275 | new = True
276 | latent_vectors = []
277 | for file in files:
278 | path_to_latent_vector = os.path.join(cfg['project_path'],"results",file,model_name, parameterization+'-'+str(n_cluster),"")
279 | latent_vector = np.load(os.path.join(path_to_latent_vector,'latent_vector_'+file+'.npy'))
280 | latent_vectors.append(latent_vector)
281 |
282 | if ind_param == False:
283 | print("For all animals the same parameterization of latent vectors is applied for %d cluster" %n_cluster)
284 | labels, cluster_center, motif_usages = same_parameterization(cfg, files, latent_vectors, n_cluster, parameterization)
285 | else:
286 | print("Individual parameterization of latent vectors for %d cluster" %n_cluster)
287 | labels, cluster_center, motif_usages = individual_parameterization(cfg, files, latent_vectors, n_cluster)
288 |
289 | else:
290 | print('No new parameterization has been calculated.')
291 | new = False
292 |
293 | # print("Hello2")
294 | if new == True:
295 | for idx, file in enumerate(files):
296 | print(os.path.join(cfg['project_path'],"results",file,"",model_name,parameterization+'-'+str(n_cluster),""))
297 | if not os.path.exists(os.path.join(cfg['project_path'],"results",file,model_name,parameterization+'-'+str(n_cluster),"")):
298 | try:
299 | os.mkdir(os.path.join(cfg['project_path'],"results",file,"",model_name,parameterization+'-'+str(n_cluster),""))
300 | except OSError as error:
301 | print(error)
302 |
303 | save_data = os.path.join(cfg['project_path'],"results",file,model_name,parameterization+'-'+str(n_cluster),"")
304 | np.save(os.path.join(save_data,str(n_cluster)+'_km_label_'+file), labels[idx])
305 | if parameterization=="kmeans":
306 | np.save(os.path.join(save_data,'cluster_center_'+file), cluster_center[idx])
307 | np.save(os.path.join(save_data,'latent_vector_'+file), latent_vectors[idx])
308 | np.save(os.path.join(save_data,'motif_usage_'+file), motif_usages[idx])
309 |
310 |
311 | print("You succesfully extracted motifs with VAME! From here, you can proceed running vame.motif_videos() ")
312 | # "to get an idea of the behavior captured by VAME. This will leave you with short snippets of certain movements."
313 | # "To get the full picture of the spatiotemporal dynamic we recommend applying our community approach afterwards.")
314 |
315 |
--------------------------------------------------------------------------------
/vame/analysis/segment_behavior.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import numpy as np
14 | from pathlib import Path
15 |
16 | import torch
17 | import scipy.signal
18 | from sklearn import mixture
19 | from sklearn.cluster import KMeans
20 |
21 | from vame.util.auxiliary import read_config
22 | from vame.model.rnn_vae import RNN_VAE
23 |
24 |
25 | def load_data(PROJECT_PATH, file, data):
26 | X = np.load(os.path.join(PROJECT_PATH,"data",file,"",file+data+'.npy'))
27 | mean = np.load(os.path.join(PROJECT_PATH,"data","train",'seq_mean.npy'))
28 | std = np.load(os.path.join(PROJECT_PATH,"data","train",'seq_std.npy'))
29 | X = (X-mean)/std
30 | return X
31 |
32 |
33 | def kmeans_clustering(context, n_clusters):
34 | kmeans = KMeans(init='k-means++',n_clusters=n_clusters, random_state=42,n_init=15).fit(context)
35 | return kmeans.predict(context)
36 |
37 |
38 | def gmm_clustering(context,n_components):
39 | GMM = mixture.GaussianMixture
40 | gmm = GMM(n_components=n_components,covariance_type='full').fit(context)
41 | return gmm.predict(context)
42 |
43 |
44 | def behavior_segmentation(config, model_name=None, cluster_method='kmeans', n_cluster=[30]):
45 |
46 | config_file = Path(config).resolve()
47 | cfg = read_config(config_file)
48 |
49 | for folders in cfg['video_sets']:
50 | if not os.path.exists(os.path.join(cfg['project_path'],"results",folders,"",model_name)):
51 | os.mkdir(os.path.join(cfg['project_path'],"results",folders,"",model_name))
52 |
53 | files = []
54 | if cfg['all_data'] == 'No':
55 | all_flag = input("Do you want to qunatify your entire dataset? \n"
56 | "If you only want to use a specific dataset type filename: \n"
57 | "yes/no/filename ")
58 | else:
59 | all_flag = 'yes'
60 |
61 | if all_flag == 'yes' or all_flag == 'Yes':
62 | for file in cfg['video_sets']:
63 | files.append(file)
64 | elif all_flag == 'no' or all_flag == 'No':
65 | for file in cfg['video_sets']:
66 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
67 | if use_file == 'yes':
68 | files.append(file)
69 | if use_file == 'no':
70 | continue
71 | else:
72 | files.append(all_flag)
73 |
74 |
75 | use_gpu = torch.cuda.is_available()
76 | if use_gpu:
77 | print("Using CUDA")
78 | print('GPU active:',torch.cuda.is_available())
79 | print('GPU used:',torch.cuda.get_device_name(0))
80 | else:
81 | print("CUDA is not working! Attempting to use the CPU...")
82 | torch.device("cpu")
83 |
84 | z, z_logger = temporal_quant(cfg, model_name, files, use_gpu)
85 | cluster_latent_space(cfg, files, z, z_logger, cluster_method, n_cluster, model_name)
86 |
87 |
88 | def temporal_quant(cfg, model_name, files, use_gpu):
89 |
90 | SEED = 19
91 | ZDIMS = cfg['zdims']
92 | FUTURE_DECODER = cfg['prediction_decoder']
93 | TEMPORAL_WINDOW = cfg['time_window']*2
94 | FUTURE_STEPS = cfg['prediction_steps']
95 | NUM_FEATURES = cfg['num_features']
96 | PROJECT_PATH = cfg['project_path']
97 | hidden_size_layer_1 = cfg['hidden_size_layer_1']
98 | hidden_size_layer_2 = cfg['hidden_size_layer_2']
99 | hidden_size_rec = cfg['hidden_size_rec']
100 | hidden_size_pred = cfg['hidden_size_pred']
101 | dropout_encoder = cfg['dropout_encoder']
102 | dropout_rec = cfg['dropout_rec']
103 | dropout_pred = cfg['dropout_pred']
104 | temp_win = int(TEMPORAL_WINDOW/2)
105 |
106 | if use_gpu:
107 | torch.cuda.manual_seed(SEED)
108 | model = RNN_VAE(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
109 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
110 | dropout_rec, dropout_pred).cuda()
111 | else:
112 | torch.cuda.manual_seed(SEED)
113 | model = RNN_VAE(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
114 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
115 | dropout_rec, dropout_pred).to()
116 |
117 | if cfg['snapshot'] == 'yes':
118 | if use_gpu:
119 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],"model","best_model","snapshots",model_name+'_'+cfg['Project']+'_epoch_'+cfg['snapshot_epoch']+'.pkl')))
120 | else:
121 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],"model","best_model","snapshots",model_name+'_'+cfg['Project']+'_epoch_'+cfg['snapshot_epoch']+'.pkl'),map_location=torch.device('cpu')))
122 | else:
123 | if use_gpu:
124 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],"model","best_model",model_name+'_'+cfg['Project']+'.pkl')))
125 | else:
126 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],"model","best_model",model_name+'_'+cfg['Project']+'.pkl'),map_location=torch.device('cpu')))
127 |
128 | model.eval()
129 |
130 | z_list = []
131 | z_logger = []
132 | logger = 0
133 | for file in files:
134 | print("Computing latent space for %s " %file)
135 | z_logger.append(logger)
136 |
137 |
138 | data=cfg['load_data']
139 | X = load_data(PROJECT_PATH, file, data)
140 |
141 | if X.shape[0] > X.shape[1]:
142 | X=X.T
143 |
144 | num_frames = len(X[0,:]) - temp_win
145 | window_start = int(temp_win/2)
146 | idx = int(temp_win/2)
147 | x_decoded = []
148 |
149 | with torch.no_grad():
150 | for i in range(num_frames):
151 | if idx >= num_frames:
152 | break
153 | data = X[:,idx-window_start:idx+window_start]
154 | data = np.reshape(data, (1,temp_win,NUM_FEATURES))
155 | if use_gpu:
156 | dataTorch = torch.from_numpy(data).type(torch.FloatTensor).cuda()
157 | else:
158 | dataTorch = torch.from_numpy(data).type(torch.FloatTensor).to()
159 | h_n = model.encoder(dataTorch)
160 | latent, _, _ = model.lmbda(h_n)
161 | z = latent.cpu().data.numpy()
162 | x_decoded.append(z)
163 | idx += 1
164 |
165 | z_temp = np.concatenate(x_decoded,axis=0)
166 | logger_temp = len(z_temp)
167 | logger += logger_temp
168 | z_list.append(z_temp)
169 |
170 | z_array= np.concatenate(z_list)
171 | z_logger.append(len(z_array))
172 |
173 | return z_array, z_logger
174 |
175 |
176 | def cluster_latent_space(cfg, files, z_data, z_logger, cluster_method, n_cluster, model_name):
177 |
178 | for cluster in n_cluster:
179 | if cluster_method == 'kmeans':
180 | print('Behavior segmentation via k-Means for %d cluster.' %cluster)
181 | data_labels = kmeans_clustering(z_data, n_clusters=cluster)
182 | data_labels = np.int64(scipy.signal.medfilt(data_labels, cfg['median_filter']))
183 |
184 | if cluster_method == 'GMM':
185 | print('Behavior segmentation via GMM.')
186 | data_labels = gmm_clustering(z_data, n_components=cluster)
187 | data_labels = np.int64(scipy.signal.medfilt(data_labels, cfg['median_filter']))
188 |
189 | for idx, file in enumerate(files):
190 | print("Segmentation for file %s..." %file )
191 | if not os.path.exists(os.path.join(cfg['project_path'],"results",file,"",model_name,"",cluster_method+'-'+str(cluster))):
192 | os.mkdir(os.path.join(cfg['project_path'],"results",file,"",model_name,"",cluster_method+'-'+str(cluster)))
193 |
194 | save_data = os.path.join(cfg['project_path'],"results",file,"",model_name,"")
195 | z_latent = z_data[z_logger[idx]:z_logger[idx+1],:]
196 | labels = data_labels[z_logger[idx]:z_logger[idx+1]]
197 |
198 |
199 | if cluster_method == 'kmeans':
200 | np.save(save_data+cluster_method+'-'+str(cluster)+'/'+str(cluster)+'_km_label_'+file, labels)
201 | np.save(save_data+cluster_method+'-'+str(cluster)+'/'+'latent_vector_'+file, z_latent)
202 |
203 | if cluster_method == 'GMM':
204 | np.save(save_data+cluster_method+'-'+str(cluster)+'/'+str(cluster)+'_gmm_label_'+file, labels)
205 | np.save(save_data+cluster_method+'-'+str(cluster)+'/'+'latent_vector_'+file, z_latent)
206 |
207 | if cluster_method == 'all':
208 | np.save(save_data+cluster_method+'-'+str(cluster)+'/'+str(cluster)+'_km_label_'+file, labels)
209 | np.save(save_data+cluster_method+'-'+str(cluster)+'/'+str(cluster)+'_gmm_label_'+file, labels)
210 | np.save(save_data+cluster_method+'-'+str(cluster)+'/'+'latent_vector_'+file, z_latent)
211 |
212 |
213 |
--------------------------------------------------------------------------------
/vame/analysis/tree_hierarchy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 |
13 | import numpy as np
14 | import networkx as nx
15 | import random
16 | from matplotlib import pyplot as plt
17 |
18 | def hierarchy_pos(G, root=None, width=.5, vert_gap = 0.2, vert_loc = 0, xcenter = 0.5):
19 |
20 | '''
21 | From Joel's answer at https://stackoverflow.com/a/29597209/2966723.
22 | '''
23 | if not nx.is_tree(G):
24 | raise TypeError('cannot use hierarchy_pos on a graph that is not a tree')
25 |
26 | if root is None:
27 | if isinstance(G, nx.DiGraph):
28 | root = next(iter(nx.topological_sort(G))) #allows back compatibility with nx version 1.11
29 | else:
30 | root = random.choice(list(G.nodes))
31 |
32 | def _hierarchy_pos(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5, pos = None, parent = None):
33 | if pos is None:
34 | pos = {root:(xcenter,vert_loc)}
35 | else:
36 | pos[root] = (xcenter, vert_loc)
37 | children = list(G.neighbors(root))
38 | if not isinstance(G, nx.DiGraph) and parent is not None:
39 | children.remove(parent)
40 | if len(children)!=0:
41 | dx = width/len(children)
42 | nextx = xcenter - width/2 - dx/2
43 | for child in children:
44 | nextx += dx
45 | pos = _hierarchy_pos(G,child, width = dx, vert_gap = vert_gap,
46 | vert_loc = vert_loc-vert_gap, xcenter=nextx,
47 | pos=pos, parent = root)
48 | return pos
49 |
50 |
51 | return _hierarchy_pos(G, root, width, vert_gap, vert_loc, xcenter)
52 |
53 |
54 | def merge_func(transition_matrix, n_cluster, motif_norm, merge_sel):
55 |
56 | if merge_sel == 0:
57 | # merge nodes with highest transition probability
58 | cost = np.max(transition_matrix)
59 | merge_nodes = np.where(cost == transition_matrix)
60 |
61 | if merge_sel == 1:
62 |
63 | cost_temp = 100
64 | for i in range(n_cluster):
65 | for j in range(n_cluster):
66 | try:
67 | cost = (motif_norm[i] + motif_norm[j]) / np.abs(transition_matrix[i,j] + transition_matrix[j,i] )
68 | except ZeroDivisionError:
69 | print("Error: Transition probabilities between motif "+str(i)+" and motif "+str(j)+ " are zero.")
70 | if cost <= cost_temp:
71 | cost_temp = cost
72 | merge_nodes = (np.array([i]), np.array([j]))
73 |
74 | return merge_nodes
75 |
76 |
77 | def graph_to_tree(motif_usage, transition_matrix, n_cluster, merge_sel=1):
78 |
79 | if merge_sel == 1:
80 | # motif_usage_temp = np.load(path_to_file+'/behavior_quantification/motif_usage.npy')
81 | motif_usage_temp = motif_usage
82 | motif_usage_temp_colsum = motif_usage_temp.sum(axis=0)
83 | motif_norm = motif_usage_temp/motif_usage_temp_colsum
84 | motif_norm_temp = motif_norm.copy()
85 | else:
86 | motif_norm_temp = None
87 |
88 | merging_nodes = []
89 | hierarchy_nodes = []
90 | trans_mat_temp = transition_matrix.copy()
91 | is_leaf = np.ones((n_cluster), dtype='int')
92 | node_label = []
93 | leaf_idx = []
94 |
95 | if np.any(transition_matrix.sum(axis=1) == 0):
96 | temp = np.where(transition_matrix.sum(axis=1)==0)
97 | reduction = len(temp) + 1
98 | else:
99 | reduction = 1
100 |
101 | for i in range(n_cluster-reduction):
102 |
103 | # max_tr = np.max(trans_mat_temp) #merge function
104 | # nodes = np.where(max_tr == trans_mat_temp)
105 | nodes = merge_func(trans_mat_temp, n_cluster, motif_norm_temp, merge_sel)
106 |
107 | if np.size(nodes) >= 2:
108 | nodes = np.array([nodes[0][0], nodes[1][0]])
109 |
110 | if is_leaf[nodes[0]] == 1:
111 | is_leaf[nodes[0]] = 0
112 | node_label.append('leaf_left_'+str(i))
113 | leaf_idx.append(1)
114 |
115 | elif is_leaf[nodes[0]] == 0:
116 | node_label.append('h_'+str(i)+'_'+str(nodes[0]))
117 | leaf_idx.append(0)
118 |
119 | if is_leaf[nodes[1]] == 1:
120 | is_leaf[nodes[1]] = 0
121 | node_label.append('leaf_right_'+str(i))
122 | hierarchy_nodes.append('h_'+str(i)+'_'+str(nodes[1]))
123 | leaf_idx.append(1)
124 |
125 | elif is_leaf[nodes[1]] == 0:
126 | node_label.append('h_'+str(i)+'_'+str(nodes[1]))
127 | hierarchy_nodes.append('h_'+str(i)+'_'+str(nodes[1]))
128 | leaf_idx.append(0)
129 |
130 | merging_nodes.append(nodes)
131 |
132 | node1_trans_x = trans_mat_temp[nodes[0],:]
133 | node2_trans_x = trans_mat_temp[nodes[1],:]
134 |
135 | node1_trans_y = trans_mat_temp[:,nodes[0]]
136 | node2_trans_y = trans_mat_temp[:,nodes[1]]
137 |
138 | new_node_trans_x = node1_trans_x + node2_trans_x
139 | new_node_trans_y = node1_trans_y + node2_trans_y
140 |
141 | trans_mat_temp[nodes[1],:] = new_node_trans_x
142 | trans_mat_temp[:,nodes[1]] = new_node_trans_y
143 |
144 | trans_mat_temp[nodes[0],:] = 0
145 | trans_mat_temp[:,nodes[0]] = 0
146 |
147 | trans_mat_temp[nodes[1],nodes[1]] = 0
148 |
149 | if merge_sel == 1:
150 | motif_norm_1 = motif_norm_temp[nodes[0]]
151 | motif_norm_2 = motif_norm_temp[nodes[1]]
152 |
153 | new_motif = motif_norm_1 + motif_norm_2
154 |
155 | motif_norm_temp[nodes[0]] = 0
156 | motif_norm_temp[nodes[1]] = 0
157 |
158 | motif_norm_temp[nodes[1]] = new_motif
159 |
160 | merge = np.array(merging_nodes)
161 | # merge = np.concatenate((merge),axis=1).T
162 |
163 | T = nx.Graph()
164 |
165 | T.add_node('Root')
166 | node_dict = {}
167 |
168 | if leaf_idx[-1] == 0:
169 | temp_node = 'h_'+str(merge[-1,1])+'_'+str(28)
170 | T.add_edge(temp_node, 'Root')
171 | node_dict[merge[-1,1]] = temp_node
172 |
173 | if leaf_idx[-1] == 1:
174 | T.add_edge(merge[-1,1], 'Root')
175 |
176 | if leaf_idx[-2] == 0:
177 | temp_node = 'h_'+str(merge[-1,0])+'_'+str(28)
178 | T.add_edge(temp_node, 'Root')
179 | node_dict[merge[-1,0]] = temp_node
180 |
181 | if leaf_idx[-2] == 1:
182 | T.add_edge(merge[-1,0], 'Root')
183 |
184 | idx = len(leaf_idx)-3
185 |
186 | if np.any(transition_matrix.sum(axis=1) == 0):
187 | temp = np.where(transition_matrix.sum(axis=1)==0)
188 | reduction = len(temp) + 2
189 | else:
190 | reduction = 2
191 |
192 | for i in range(n_cluster-reduction)[::-1]:
193 |
194 | if leaf_idx[idx-1] == 1:
195 | if merge[i,1] in node_dict:
196 | T.add_edge(merge[i,0], node_dict[merge[i,1]])
197 | else:
198 | T.add_edge(merge[i,0], temp_node)
199 |
200 | if leaf_idx[idx] == 1:
201 | if merge[i,1] in node_dict:
202 | T.add_edge(merge[i,1], node_dict[merge[i,1]])
203 | else:
204 | T.add_edge(merge[i,1], temp_node)
205 |
206 | if leaf_idx[idx] == 0:
207 | new_node = 'h_'+str(merge[i,1])+'_'+str(i)
208 | if merge[i,1] in node_dict:
209 | T.add_edge(node_dict[merge[i,1]], new_node)
210 | else:
211 | T.add_edge(temp_node, new_node)
212 | # node_dict[merge[i,1]] = new_node
213 |
214 | if leaf_idx[idx-1] == 1:
215 | temp_node = new_node
216 | node_dict[merge[i,1]] = new_node
217 | else:
218 | new_node_2 = 'h_'+str(merge[i,0])+'_'+str(i)
219 | # temp_node = 'h_'+str(merge[i,0])+'_'+str(i)
220 | T.add_edge(node_dict[merge[i,1]], new_node_2)
221 | # node_dict[merge[i,0]] = temp_node
222 | node_dict[merge[i,1]] = new_node
223 | node_dict[merge[i,0]] = new_node_2
224 | # temp_node = new_node
225 |
226 | elif leaf_idx[idx-1] == 0:
227 | new_node = 'h_'+str(merge[i,0])+'_'+str(i)
228 | if merge[i,1] in node_dict:
229 | T.add_edge(node_dict[merge[i,1]], new_node)
230 | else:
231 | T.add_edge(temp_node, new_node)
232 | node_dict[merge[i,0]] = new_node
233 |
234 | if leaf_idx[idx] == 1:
235 | temp_node = new_node
236 | else:
237 | new_node = 'h_'+str(merge[i,1])+'_'+str(i)
238 | T.add_edge(temp_node, new_node)
239 | node_dict[merge[i,1]] = new_node
240 | temp_node = new_node
241 |
242 | idx -= 2
243 |
244 | return T
245 |
246 |
247 | def draw_tree(T):
248 | # pos = nx.drawing.layout.fruchterman_reingold_layout(T)
249 | pos = hierarchy_pos(T,'Root',width=.5, vert_gap = 0.1, vert_loc = 0, xcenter = 50)
250 | fig = plt.figure(2)
251 | nx.draw_networkx(T, pos)
252 | figManager = plt.get_current_fig_manager()
253 | figManager.window.showMaximized()
254 |
255 |
256 | def traverse_tree(T, root_node=None):
257 | if root_node == None:
258 | node=['Root']
259 | else:
260 | node=[root_node]
261 | traverse_list = []
262 | traverse_preorder = '{'
263 |
264 | def _traverse_tree(T, node, traverse_preorder):
265 | traverse_preorder += str(node[0])
266 | traverse_list.append(node[0])
267 | children = list(T.neighbors(node[0]))
268 |
269 | if len(children) == 3:
270 | # print(children)
271 | for child in children:
272 | if child in traverse_list:
273 | # print(child)
274 | children.remove(child)
275 |
276 | if len(children) > 1:
277 | traverse_preorder += '{'
278 | traverse_preorder_temp = _traverse_tree(T, [children[0]], '')
279 | traverse_preorder += traverse_preorder_temp
280 |
281 | traverse_preorder += '}{'
282 |
283 | traverse_preorder_temp = _traverse_tree(T, [children[1]], '')
284 | traverse_preorder += traverse_preorder_temp
285 | traverse_preorder += '}'
286 |
287 | return traverse_preorder
288 |
289 | traverse_preorder = _traverse_tree(T, node, traverse_preorder)
290 | traverse_preorder += '}'
291 |
292 | return traverse_preorder
293 |
294 |
295 |
296 | def _traverse_tree(T, node, traverse_preorder,traverse_list):
297 | traverse_preorder += str(node[0])
298 | traverse_list.append(node[0])
299 | children = list(T.neighbors(node[0]))
300 |
301 | if len(children) == 3:
302 | # print(children)
303 | for child in children:
304 | if child in traverse_list:
305 | # print(child)
306 | children.remove(child)
307 |
308 | if len(children) > 1:
309 | traverse_preorder += '{'
310 | traverse_preorder_temp = _traverse_tree(T, [children[0]], '',traverse_list)
311 | traverse_preorder += traverse_preorder_temp
312 |
313 | traverse_preorder += '}{'
314 |
315 | traverse_preorder_temp = _traverse_tree(T, [children[1]], '',traverse_list)
316 | traverse_preorder += traverse_preorder_temp
317 | traverse_preorder += '}'
318 |
319 | return traverse_preorder
320 |
321 | def traverse_tree(T, root_node=None):
322 | if root_node == None:
323 | node=['Root']
324 | else:
325 | node=[root_node]
326 | traverse_list = []
327 | traverse_preorder = '{'
328 | traverse_preorder = _traverse_tree(T, node, traverse_preorder,traverse_list)
329 | traverse_preorder += '}'
330 |
331 | return traverse_preorder
332 |
333 |
334 | def _traverse_tree_cutline(T, node, traverse_list, cutline, level, community_bag, community_list=None):
335 | cmap = plt.get_cmap("tab10")
336 | traverse_list.append(node[0])
337 | if community_list is not None and type(node[0]) is not str:
338 | community_list.append(node[0])
339 | children = list(T.neighbors(node[0]))
340 |
341 | if len(children) == 3:
342 | # print(children)
343 | for child in children:
344 | if child in traverse_list:
345 | # print(child)
346 | children.remove(child)
347 |
348 | if len(children) > 1:
349 | if nx.shortest_path_length(T,'Root',node[0])==cutline:
350 | #create new list
351 | traverse_list1 = []
352 | traverse_list2 = []
353 | community_bag = _traverse_tree_cutline(T, [children[0]], traverse_list, cutline, level+1, community_bag, traverse_list1)
354 | community_bag = _traverse_tree_cutline(T, [children[1]], traverse_list, cutline, level+1, community_bag, traverse_list2)
355 | joined_list=traverse_list1+traverse_list2
356 | community_bag.append(joined_list)
357 | if type(node[0]) is not str: #append itself
358 | community_bag.append([node[0]])
359 | else:
360 | community_bag = _traverse_tree_cutline(T, [children[0]], traverse_list, cutline, level+1, community_bag, community_list)
361 | community_bag = _traverse_tree_cutline(T, [children[1]], traverse_list, cutline, level+1, community_bag, community_list)
362 |
363 | return community_bag
364 |
365 |
366 | def traverse_tree_cutline(T, root_node=None,cutline=2):
367 | if root_node == None:
368 | node=['Root']
369 | else:
370 | node=[root_node]
371 | traverse_list = []
372 | color_map = []
373 | community_bag=[]
374 | level = 0
375 | community_bag = _traverse_tree_cutline(T, node, traverse_list,cutline, level, color_map,community_bag)
376 |
377 | return community_bag
378 |
--------------------------------------------------------------------------------
/vame/analysis/umap_visualization.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import umap
14 | import numpy as np
15 | from pathlib import Path
16 | import matplotlib.pyplot as plt
17 | from matplotlib.gridspec import GridSpec
18 | from mpl_toolkits.mplot3d import Axes3D
19 |
20 | from vame.util.auxiliary import read_config
21 |
22 |
23 | def umap_vis(file, embed, num_points):
24 | fig = plt.figure(1)
25 | plt.scatter(embed[:num_points,0], embed[:num_points,1], s=2, alpha=.5)
26 | plt.gca().set_aspect('equal', 'datalim')
27 | plt.grid(False)
28 |
29 |
30 | def umap_label_vis(file, embed, label, n_cluster, num_points):
31 | fig = plt.figure(1)
32 | plt.scatter(embed[:num_points,0], embed[:num_points,1], c=label[:num_points], cmap='Spectral', s=2, alpha=.7)
33 | plt.colorbar(boundaries=np.arange(n_cluster+1)-0.5).set_ticks(np.arange(n_cluster))
34 | plt.gca().set_aspect('equal', 'datalim')
35 | plt.grid(False)
36 |
37 |
38 | def umap_vis_comm(file, embed, community_label, num_points):
39 | num = np.unique(community_label).shape[0]
40 | fig = plt.figure(1)
41 | plt.scatter(embed[:num_points,0], embed[:num_points,1], c=community_label[:num_points], cmap='Spectral', s=2, alpha=.7)
42 | plt.colorbar(boundaries=np.arange(num+1)-0.5).set_ticks(np.arange(num))
43 | plt.gca().set_aspect('equal', 'datalim')
44 | plt.grid(False)
45 |
46 |
47 | def visualization(config, label=None):
48 | config_file = Path(config).resolve()
49 | cfg = read_config(config_file)
50 | model_name = cfg['model_name']
51 | n_cluster = cfg['n_cluster']
52 | param = cfg['parameterization']
53 |
54 | files = []
55 | if cfg['all_data'] == 'No':
56 | all_flag = input("Do you want to write motif videos for your entire dataset? \n"
57 | "If you only want to use a specific dataset type filename: \n"
58 | "yes/no/filename ")
59 | else:
60 | all_flag = 'yes'
61 |
62 | if all_flag == 'yes' or all_flag == 'Yes':
63 | for file in cfg['video_sets']:
64 | files.append(file)
65 |
66 | elif all_flag == 'no' or all_flag == 'No':
67 | for file in cfg['video_sets']:
68 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
69 | if use_file == 'yes':
70 | files.append(file)
71 | if use_file == 'no':
72 | continue
73 | else:
74 | files.append(all_flag)
75 |
76 | for idx, file in enumerate(files):
77 | path_to_file=os.path.join(cfg['project_path'],"results",file,"",model_name,"",param+'-'+str(n_cluster))
78 |
79 | try:
80 | embed = np.load(os.path.join(path_to_file,"","community","","umap_embedding_"+file+".npy"))
81 | num_points = cfg['num_points']
82 | if num_points > embed.shape[0]:
83 | num_points = embed.shape[0]
84 | except:
85 | if not os.path.exists(os.path.join(path_to_file,"community")):
86 | os.mkdir(os.path.join(path_to_file,"community"))
87 | print("Compute embedding for file %s" %file)
88 | reducer = umap.UMAP(n_components=2, min_dist=cfg['min_dist'], n_neighbors=cfg['n_neighbors'],
89 | random_state=cfg['random_state'])
90 |
91 | latent_vector = np.load(os.path.join(path_to_file,"",'latent_vector_'+file+'.npy'))
92 |
93 | num_points = cfg['num_points']
94 | if num_points > latent_vector.shape[0]:
95 | num_points = latent_vector.shape[0]
96 | print("Embedding %d data points.." %num_points)
97 |
98 | embed = reducer.fit_transform(latent_vector[:num_points,:])
99 | np.save(os.path.join(path_to_file,"community","umap_embedding_"+file+'.npy'), embed)
100 |
101 | print("Visualizing %d data points.. " %num_points)
102 | if label == None:
103 | umap_vis(file, embed, num_points)
104 |
105 | if label == 'motif':
106 | motif_label = np.load(os.path.join(path_to_file,"",str(n_cluster)+'_km_label_'+file+'.npy'))
107 | umap_label_vis(file, embed, motif_label, n_cluster, num_points)
108 |
109 | if label == "community":
110 | community_label = np.load(os.path.join(path_to_file,"","community","","community_label_"+file+".npy"))
111 | umap_vis_comm(file, embed, community_label, num_points)
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/vame/analysis/videowriter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | from pathlib import Path
14 | import numpy as np
15 | import cv2 as cv
16 | import tqdm
17 |
18 | from vame.util.auxiliary import read_config
19 |
20 |
21 | def get_cluster_vid(cfg, path_to_file, file, n_cluster, videoType, flag):
22 | if flag == "motif":
23 | print("Motif videos getting created for "+file+" ...")
24 | labels = np.load(os.path.join(path_to_file,str(n_cluster)+'_km_label_'+file+'.npy'))
25 | if flag == "community":
26 | print("Community videos getting created for "+file+" ...")
27 | labels = np.load(os.path.join(path_to_file,"community",'community_label_'+file+'.npy'))
28 | capture = cv.VideoCapture(os.path.join(cfg['project_path'],"videos",file+videoType))
29 |
30 | if capture.isOpened():
31 | width = capture.get(cv.CAP_PROP_FRAME_WIDTH)
32 | height = capture.get(cv.CAP_PROP_FRAME_HEIGHT)
33 | # print('width, height:', width, height)
34 |
35 | fps = 25#capture.get(cv.CAP_PROP_FPS)
36 | # print('fps:', fps)
37 |
38 | cluster_start = cfg['time_window'] / 2
39 | for cluster in range(n_cluster):
40 | print('Cluster: %d' %(cluster))
41 | cluster_lbl = np.where(labels == cluster)
42 | cluster_lbl = cluster_lbl[0]
43 |
44 | if flag == "motif":
45 | output = os.path.join(path_to_file,"cluster_videos",file+'-motif_%d.avi' %cluster)
46 | if flag == "community":
47 | output = os.path.join(path_to_file,"community_videos",file+'-community_%d.avi' %cluster)
48 |
49 | video = cv.VideoWriter(output, cv.VideoWriter_fourcc('M','J','P','G'), fps, (int(width), int(height)))
50 |
51 | if len(cluster_lbl) < cfg['length_of_motif_video']:
52 | vid_length = len(cluster_lbl)
53 | else:
54 | vid_length = cfg['length_of_motif_video']
55 |
56 | for num in tqdm.tqdm(range(vid_length)):
57 | idx = cluster_lbl[num]
58 | capture.set(1,idx+cluster_start)
59 | ret, frame = capture.read()
60 | video.write(frame)
61 |
62 | video.release()
63 | capture.release()
64 |
65 |
66 | def motif_videos(config, videoType='.mp4'):
67 | config_file = Path(config).resolve()
68 | cfg = read_config(config_file)
69 | model_name = cfg['model_name']
70 | n_cluster = cfg['n_cluster']
71 | param = cfg['parameterization']
72 | flag = 'motif'
73 |
74 | files = []
75 | if cfg['all_data'] == 'No':
76 | all_flag = input("Do you want to write motif videos for your entire dataset? \n"
77 | "If you only want to use a specific dataset type filename: \n"
78 | "yes/no/filename ")
79 | else:
80 | all_flag = 'yes'
81 |
82 | if all_flag == 'yes' or all_flag == 'Yes':
83 | for file in cfg['video_sets']:
84 | files.append(file)
85 |
86 | elif all_flag == 'no' or all_flag == 'No':
87 | for file in cfg['video_sets']:
88 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
89 | if use_file == 'yes':
90 | files.append(file)
91 | if use_file == 'no':
92 | continue
93 | else:
94 | files.append(all_flag)
95 |
96 | print("Cluster size is: %d " %n_cluster)
97 | for file in files:
98 | path_to_file=os.path.join(cfg['project_path'],"results",file,model_name,param+'-'+str(n_cluster),"")
99 | if not os.path.exists(os.path.join(path_to_file,"cluster_videos")):
100 | os.mkdir(os.path.join(path_to_file,"cluster_videos"))
101 |
102 | get_cluster_vid(cfg, path_to_file, file, n_cluster, videoType, flag)
103 |
104 | print("All videos have been created!")
105 |
106 |
107 | def community_videos(config, videoType='.mp4'):
108 | config_file = Path(config).resolve()
109 | cfg = read_config(config_file)
110 | model_name = cfg['model_name']
111 | n_cluster = cfg['n_cluster']
112 | param = cfg['parameterization']
113 | flag = 'community'
114 |
115 | files = []
116 | if cfg['all_data'] == 'No':
117 | all_flag = input("Do you want to write motif videos for your entire dataset? \n"
118 | "If you only want to use a specific dataset type filename: \n"
119 | "yes/no/filename ")
120 | else:
121 | all_flag = 'yes'
122 |
123 | if all_flag == 'yes' or all_flag == 'Yes':
124 | for file in cfg['video_sets']:
125 | files.append(file)
126 |
127 | elif all_flag == 'no' or all_flag == 'No':
128 | for file in cfg['video_sets']:
129 | use_file = input("Do you want to quantify " + file + "? yes/no: ")
130 | if use_file == 'yes':
131 | files.append(file)
132 | if use_file == 'no':
133 | continue
134 | else:
135 | files.append(all_flag)
136 |
137 | print("Cluster size is: %d " %n_cluster)
138 | for file in files:
139 | path_to_file=os.path.join(cfg['project_path'],"results",file,model_name,param+'-'+str(n_cluster),"")
140 | if not os.path.exists(os.path.join(path_to_file,"community_videos")):
141 | os.mkdir(os.path.join(path_to_file,"community_videos"))
142 |
143 | get_cluster_vid(cfg, path_to_file, file, n_cluster, videoType, flag)
144 |
145 | print("All videos have been created!")
146 |
--------------------------------------------------------------------------------
/vame/initialize_project/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 | import sys
12 | sys.dont_write_bytecode = True
13 |
14 | from vame.initialize_project.new import init_new_project
15 |
--------------------------------------------------------------------------------
/vame/initialize_project/new.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 |
11 | The following code is adapted from:
12 |
13 | DeepLabCut2.0 Toolbox (deeplabcut.org)
14 | © A. & M. Mathis Labs
15 | https://github.com/AlexEMG/DeepLabCut
16 | Please see AUTHORS for contributors.
17 | https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS
18 | Licensed under GNU Lesser General Public License v3.0
19 | """
20 |
21 | import os
22 | from pathlib import Path
23 | import shutil
24 |
25 | def init_new_project(project, videos, working_directory=None, videotype='.mp4'):
26 | from datetime import datetime as dt
27 | from vame.util import auxiliary
28 | date = dt.today()
29 | month = date.strftime("%B")
30 | day = date.day
31 | year = date.year
32 | d = str(month[0:3]+str(day))
33 | date = dt.today().strftime('%Y-%m-%d')
34 |
35 | if working_directory == None:
36 | working_directory = '.'
37 |
38 | wd = Path(working_directory).resolve()
39 | project_name = '{pn}-{date}'.format(pn=project, date=d+'-'+str(year))
40 |
41 | project_path = wd / project_name
42 |
43 |
44 | if project_path.exists():
45 | print('Project "{}" already exists!'.format(project_path))
46 | return
47 |
48 | video_path = project_path / 'videos'
49 | data_path = project_path / 'data'
50 | results_path = project_path / 'results'
51 | model_path = project_path / 'model'
52 |
53 | for p in [video_path, data_path, results_path, model_path]:
54 | p.mkdir(parents=True)
55 | print('Created "{}"'.format(p))
56 |
57 | vids = []
58 | for i in videos:
59 | #Check if it is a folder
60 | if os.path.isdir(i):
61 | vids_in_dir = [os.path.join(i,vp) for vp in os.listdir(i) if videotype in vp]
62 | vids = vids + vids_in_dir
63 | if len(vids_in_dir)==0:
64 | print("No videos found in",i)
65 | print("Perhaps change the videotype, which is currently set to:", videotype)
66 | else:
67 | videos = vids
68 | print(len(vids_in_dir)," videos from the directory" ,i, "were added to the project.")
69 | else:
70 | if os.path.isfile(i):
71 | vids = vids + [i]
72 | videos = vids
73 |
74 |
75 | videos = [Path(vp) for vp in videos]
76 | video_names = []
77 | dirs_data = [data_path/Path(i.stem) for i in videos]
78 | for p in dirs_data:
79 | """
80 | Creates directory under data
81 | """
82 | p.mkdir(parents = True, exist_ok = True)
83 | video_names.append(p.stem)
84 |
85 | dirs_results = [results_path/Path(i.stem) for i in videos]
86 | for p in dirs_results:
87 | """
88 | Creates directory under results
89 | """
90 | p.mkdir(parents = True, exist_ok = True)
91 |
92 | destinations = [video_path.joinpath(vp.name) for vp in videos]
93 |
94 | os.mkdir(str(project_path)+'/'+'videos/pose_estimation/')
95 | os.mkdir(str(project_path)+'/model/pretrained_model')
96 |
97 | print("Copying the videos \n")
98 | for src, dst in zip(videos, destinations):
99 | shutil.copy(os.fspath(src),os.fspath(dst))
100 |
101 | cfg_file,ruamelFile = auxiliary.create_config_template()
102 | cfg_file
103 |
104 | cfg_file['Project']=str(project)
105 | cfg_file['project_path']=str(project_path)+'/'
106 | cfg_file['test_fraction']=0.1
107 | cfg_file['video_sets']=video_names
108 | cfg_file['all_data']='yes'
109 | cfg_file['load_data']='-PE-seq-clean'
110 | cfg_file['anneal_function']='linear'
111 | cfg_file['batch_size']=256
112 | cfg_file['max_epochs']=500
113 | cfg_file['transition_function']='GRU'
114 | cfg_file['beta']=1
115 | cfg_file['zdims']=30
116 | cfg_file['learning_rate']=5e-4
117 | cfg_file['time_window']=30
118 | cfg_file['prediction_decoder']=1
119 | cfg_file['prediction_steps']=15
120 | cfg_file['model_convergence']=50
121 | cfg_file['model_snapshot']=50
122 | cfg_file['num_features']=12
123 | cfg_file['savgol_filter']=True
124 | cfg_file['savgol_length']=5
125 | cfg_file['savgol_order']=2
126 | cfg_file['hidden_size_layer_1']=256
127 | cfg_file['hidden_size_layer_2']=256
128 | cfg_file['dropout_encoder']=0
129 | cfg_file['hidden_size_rec']=256
130 | cfg_file['dropout_rec']=0
131 | cfg_file['hidden_size_pred']=256
132 | cfg_file['dropout_pred']=0
133 | cfg_file['kl_start']=2
134 | cfg_file['annealtime']=4
135 | cfg_file['mse_reconstruction_reduction']='sum'
136 | cfg_file['mse_prediction_reduction']='sum'
137 | cfg_file['kmeans_loss']=cfg_file['zdims']
138 | cfg_file['kmeans_lambda']=0.1
139 | cfg_file['scheduler']=1
140 | cfg_file['length_of_motif_video'] = 1000
141 | cfg_file['noise'] = False
142 | cfg_file['scheduler_step_size'] = 100
143 | cfg_file['legacy'] = False
144 | cfg_file['individual_parameterization'] = False
145 | cfg_file['random_state_kmeans'] = 42
146 | cfg_file['n_init_kmeans'] = 15
147 | cfg_file['model_name']='VAME'
148 | cfg_file['n_cluster'] = 15
149 | cfg_file['pretrained_weights'] = False
150 | cfg_file['pretrained_model']='None'
151 | cfg_file['min_dist'] = 0.1
152 | cfg_file['n_neighbors'] = 200
153 | cfg_file['random_state'] = 42
154 | cfg_file['num_points'] = 30000
155 | cfg_file['scheduler_gamma'] = 0.2
156 | cfg_file['softplus'] = False
157 | cfg_file['pose_confidence'] = 0.99
158 | cfg_file['iqr_factor'] = 4
159 | cfg_file['robust'] = True
160 | cfg_file['beta_norm'] = False
161 | cfg_file['n_layers'] = 1
162 | cfg_file['axis'] = None
163 | cfg_file['parameterization'] = 'hmm'
164 | cfg_file['hmm_trained'] = False
165 |
166 | projconfigfile=os.path.join(str(project_path),'config.yaml')
167 | # Write dictionary to yaml config file
168 | auxiliary.write_config(projconfigfile,cfg_file)
169 |
170 | print('A VAME project has been created. \n')
171 | print('Now its time to prepare your data for VAME. '
172 | 'The first step is to move your pose .csv file (e.g. DeepLabCut .csv) into the '
173 | '//YOUR//VAME//PROJECT//videos//pose_estimation folder. From here you can call '
174 | 'either the function vame.egocentric_alignment() or if your data is by design egocentric '
175 | 'call vame.csv_to_numpy(). This will prepare the data in .csv into the right format to start '
176 | 'working with VAME.')
177 |
178 | return projconfigfile
179 |
--------------------------------------------------------------------------------
/vame/model/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import sys
13 | sys.dont_write_bytecode = True
14 |
15 | from vame.model.create_training import create_trainset
16 | from vame.model.dataloader import SEQUENCE_DATASET
17 | from vame.model.rnn_vae import train_model
18 | from vame.model.evaluate import evaluate_model
19 |
20 |
--------------------------------------------------------------------------------
/vame/model/create_training.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import numpy as np
14 | import pandas as pd
15 | from pathlib import Path
16 | import scipy.signal
17 | from scipy.stats import iqr
18 | import matplotlib.pyplot as plt
19 |
20 | from vame.util.auxiliary import read_config
21 |
22 |
23 | #Helper function to return indexes of nans
24 | def nan_helper(y):
25 | return np.isnan(y), lambda z: z.nonzero()[0]
26 |
27 | #Interpolates all nan values of given array
28 | def interpol(arr):
29 | y = np.transpose(arr)
30 | nans, x = nan_helper(y)
31 | y[nans]= np.interp(x(nans), x(~nans), y[~nans])
32 | arr = np.transpose(y)
33 | return arr
34 |
35 | def plot_check_parameter(cfg, iqr_val, num_frames, X_true, X_med, anchor_1, anchor_2):
36 | plot_X_orig = np.concatenate(X_true, axis=0).T
37 | plot_X_med = X_med.copy()
38 | iqr_cutoff = cfg['iqr_factor']*iqr_val
39 |
40 | plt.figure()
41 | plt.plot(plot_X_orig.T)
42 | plt.axhline(y=iqr_cutoff, color='r', linestyle='--', label="IQR cutoff")
43 | plt.axhline(y=-iqr_cutoff, color='r', linestyle='--')
44 | plt.title("Full Signal z-scored")
45 | plt.legend()
46 |
47 | if num_frames > 1000:
48 | rnd = np.random.choice(num_frames)
49 |
50 | plt.figure()
51 | plt.plot(plot_X_med[:,rnd:rnd+1000].T)
52 | plt.axhline(y=iqr_cutoff, color='r', linestyle='--', label="IQR cutoff")
53 | plt.axhline(y=-iqr_cutoff, color='r', linestyle='--')
54 | plt.title("Filtered signal z-scored")
55 | plt.legend()
56 |
57 | plt.figure()
58 | plt.plot(plot_X_orig[:,rnd:rnd+1000].T)
59 | plt.axhline(y=iqr_cutoff, color='r', linestyle='--', label="IQR cutoff")
60 | plt.axhline(y=-iqr_cutoff, color='r', linestyle='--')
61 | plt.title("Original signal z-scored")
62 | plt.legend()
63 |
64 | plt.figure()
65 | plt.plot(plot_X_orig[:,rnd:rnd+1000].T, 'g', alpha=0.5)
66 | plt.plot(plot_X_med[:,rnd:rnd+1000].T, '--m', alpha=0.6)
67 | plt.axhline(y=iqr_cutoff, color='r', linestyle='--', label="IQR cutoff")
68 | plt.axhline(y=-iqr_cutoff, color='r', linestyle='--')
69 | plt.title("Overlayed z-scored")
70 | plt.legend()
71 |
72 | # plot_X_orig = np.delete(plot_X_orig.T, anchor_1, 1)
73 | # plot_X_orig = np.delete(plot_X_orig, anchor_2, 1)
74 | # mse = (np.square(plot_X_orig[rnd:rnd+1000, :] - plot_X_med[:,rnd:rnd+1000].T)).mean(axis=0)
75 |
76 |
77 | else:
78 | plt.figure()
79 | plt.plot(plot_X_med.T)
80 | plt.axhline(y=iqr_cutoff, color='r', linestyle='--', label="IQR cutoff")
81 | plt.axhline(y=-iqr_cutoff, color='r', linestyle='--')
82 | plt.title("Filtered signal z-scored")
83 | plt.legend()
84 |
85 | plt.figure()
86 | plt.plot(plot_X_orig.T)
87 | plt.axhline(y=iqr_cutoff, color='r', linestyle='--', label="IQR cutoff")
88 | plt.axhline(y=-iqr_cutoff, color='r', linestyle='--')
89 | plt.title("Original signal z-scored")
90 | plt.legend()
91 |
92 | print("Please run the function with check_parameter=False if you are happy with the results")
93 |
94 | def traindata_aligned(cfg, files, testfraction, num_features, savgol_filter, check_parameter):
95 |
96 | X_train = []
97 | pos = []
98 | pos_temp = 0
99 | pos.append(0)
100 |
101 | if check_parameter == True:
102 | X_true = []
103 | files = [files[0]]
104 |
105 | for file in files:
106 | print("z-scoring of file %s" %file)
107 | path_to_file = os.path.join(cfg['project_path'],"data", file, file+'-PE-seq.npy')
108 | data = np.load(path_to_file)
109 |
110 | X_mean = np.mean(data,axis=None)
111 | X_std = np.std(data, axis=None)
112 | X_z = (data.T - X_mean) / X_std
113 |
114 | # Introducing artificial error spikes
115 | # rang = [1.5, 2, 2.5, 3, 3.5, 3, 3, 2.5, 2, 1.5]
116 | # for i in range(num_frames):
117 | # if i % 300 == 0:
118 | # rnd = np.random.choice(12,2)
119 | # for j in range(10):
120 | # X_z[i+j, rnd[0]] = X_z[i+j, rnd[0]] * rang[j]
121 | # X_z[i+j, rnd[1]] = X_z[i+j, rnd[1]] * rang[j]
122 |
123 | if check_parameter == True:
124 | X_z_copy = X_z.copy()
125 | X_true.append(X_z_copy)
126 |
127 | if cfg['robust'] == True:
128 | iqr_val = iqr(X_z)
129 | print("IQR value: %.2f, IQR cutoff: %.2f" %(iqr_val, cfg['iqr_factor']*iqr_val))
130 | for i in range(X_z.shape[0]):
131 | for marker in range(X_z.shape[1]):
132 | if X_z[i,marker] > cfg['iqr_factor']*iqr_val:
133 | X_z[i,marker] = np.nan
134 |
135 | elif X_z[i,marker] < -cfg['iqr_factor']*iqr_val:
136 | X_z[i,marker] = np.nan
137 |
138 | X_z = interpol(X_z)
139 |
140 | X_len = len(data.T)
141 | pos_temp += X_len
142 | pos.append(pos_temp)
143 | X_train.append(X_z)
144 |
145 | X = np.concatenate(X_train, axis=0)
146 | # X_std = np.std(X)
147 |
148 | detect_anchors = np.std(X.T, axis=1)
149 | sort_anchors = np.sort(detect_anchors)
150 | if sort_anchors[0] == sort_anchors[1]:
151 | anchors = np.where(detect_anchors == sort_anchors[0])[0]
152 | anchor_1_temp = anchors[0]
153 | anchor_2_temp = anchors[1]
154 |
155 | else:
156 | anchor_1_temp = int(np.where(detect_anchors == sort_anchors[0])[0])
157 | anchor_2_temp = int(np.where(detect_anchors == sort_anchors[1])[0])
158 |
159 | if anchor_1_temp > anchor_2_temp:
160 | anchor_1 = anchor_1_temp
161 | anchor_2 = anchor_2_temp
162 |
163 | else:
164 | anchor_1 = anchor_2_temp
165 | anchor_2 = anchor_1_temp
166 |
167 | X = np.delete(X, anchor_1, 1)
168 | X = np.delete(X, anchor_2, 1)
169 |
170 | X = X.T
171 |
172 | if savgol_filter:
173 | X_med = scipy.signal.savgol_filter(X, cfg['savgol_length'], cfg['savgol_order'])
174 | else:
175 | X_med = X
176 |
177 | num_frames = len(X_med.T)
178 | test = int(num_frames*testfraction)
179 |
180 | z_test =X_med[:,:test]
181 | z_train = X_med[:,test:]
182 |
183 | if check_parameter == True:
184 | plot_check_parameter(cfg, iqr_val, num_frames, X_true, X_med, anchor_1, anchor_2)
185 |
186 | else:
187 | #save numpy arrays the the test/train info:
188 | np.save(os.path.join(cfg['project_path'],"data", "train",'train_seq.npy'), z_train)
189 | np.save(os.path.join(cfg['project_path'],"data", "train", 'test_seq.npy'), z_test)
190 |
191 | for i, file in enumerate(files):
192 | np.save(os.path.join(cfg['project_path'],"data", file, file+'-PE-seq-clean.npy'), X_med[:,pos[i]:pos[i+1]])
193 |
194 | print('Lenght of train data: %d' %len(z_train.T))
195 | print('Lenght of test data: %d' %len(z_test.T))
196 |
197 |
198 | def traindata_fixed(cfg, files, testfraction, num_features, savgol_filter, check_parameter):
199 | X_train = []
200 | pos = []
201 | pos_temp = 0
202 | pos.append(0)
203 |
204 | if check_parameter == True:
205 | X_true = []
206 | rnd_file = np.random.choice(len(files))
207 | files = [files[0]]
208 |
209 | for file in files:
210 | print("z-scoring of file %s" %file)
211 | path_to_file = os.path.join(cfg['project_path'],"data", file, file+'-PE-seq.npy')
212 | data = np.load(path_to_file)
213 | X_mean = np.mean(data,axis=None)
214 | X_std = np.std(data, axis=None)
215 | X_z = (data.T - X_mean) / X_std
216 |
217 | if check_parameter == True:
218 | X_z_copy = X_z.copy()
219 | X_true.append(X_z_copy)
220 |
221 | if cfg['robust'] == True:
222 | iqr_val = iqr(X_z)
223 | print("IQR value: %.2f, IQR cutoff: %.2f" %(iqr_val, cfg['iqr_factor']*iqr_val))
224 | for i in range(X_z.shape[0]):
225 | for marker in range(X_z.shape[1]):
226 | if X_z[i,marker] > cfg['iqr_factor']*iqr_val:
227 | X_z[i,marker] = np.nan
228 |
229 | elif X_z[i,marker] < -cfg['iqr_factor']*iqr_val:
230 | X_z[i,marker] = np.nan
231 |
232 | X_z[i,:] = interpol(X_z[i,:])
233 |
234 | X_len = len(data.T)
235 | pos_temp += X_len
236 | pos.append(pos_temp)
237 | X_train.append(X_z)
238 |
239 | X = np.concatenate(X_train, axis=0).T
240 |
241 | if savgol_filter:
242 | X_med = scipy.signal.savgol_filter(X, cfg['savgol_length'], cfg['savgol_order'])
243 | else:
244 | X_med = X
245 |
246 | num_frames = len(X_med.T)
247 | test = int(num_frames*testfraction)
248 |
249 | z_test =X_med[:,:test]
250 | z_train = X_med[:,test:]
251 |
252 | if check_parameter == True:
253 | plot_check_parameter(cfg, iqr_val, num_frames, X_true, X_med)
254 |
255 | else:
256 | #save numpy arrays the the test/train info:
257 | np.save(os.path.join(cfg['project_path'],"data", "train",'train_seq.npy'), z_train)
258 | np.save(os.path.join(cfg['project_path'],"data", "train", 'test_seq.npy'), z_test)
259 |
260 | for i, file in enumerate(files):
261 | np.save(os.path.join(cfg['project_path'],"data", file, file+'-PE-seq-clean.npy'), X_med[:,pos[i]:pos[i+1]])
262 |
263 | print('Lenght of train data: %d' %len(z_train.T))
264 | print('Lenght of test data: %d' %len(z_test.T))
265 |
266 |
267 | def create_trainset(config, check_parameter=False):
268 | config_file = Path(config).resolve()
269 | cfg = read_config(config_file)
270 | legacy = cfg['legacy']
271 | fixed = cfg['egocentric_data']
272 |
273 | if not os.path.exists(os.path.join(cfg['project_path'],'data','train',"")):
274 | os.mkdir(os.path.join(cfg['project_path'],'data','train',""))
275 |
276 | files = []
277 | if cfg['all_data'] == 'No':
278 | for file in cfg['video_sets']:
279 | use_file = input("Do you want to train on " + file + "? yes/no: ")
280 | if use_file == 'yes':
281 | files.append(file)
282 | if use_file == 'no':
283 | continue
284 | else:
285 | for file in cfg['video_sets']:
286 | files.append(file)
287 |
288 | print("Creating training dataset...")
289 | if cfg['robust'] == True:
290 | print("Using robust setting to eliminate outliers! IQR factor: %d" %cfg['iqr_factor'])
291 |
292 | if fixed == False:
293 | print("Creating trainset from the vame.egocentrical_alignment() output ")
294 | traindata_aligned(cfg, files, cfg['test_fraction'], cfg['num_features'], cfg['savgol_filter'], check_parameter)
295 | else:
296 | print("Creating trainset from the vame.csv_to_numpy() output ")
297 | traindata_fixed(cfg, files, cfg['test_fraction'], cfg['num_features'], cfg['savgol_filter'], check_parameter)
298 |
299 | if check_parameter == False:
300 | print("A training and test set has been created. Next step: vame.train_model()")
301 |
--------------------------------------------------------------------------------
/vame/model/dataloader.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import torch
13 | from torch.utils.data.dataset import Dataset
14 | import numpy as np
15 | import os
16 |
17 |
18 | class SEQUENCE_DATASET(Dataset):
19 | def __init__(self,path_to_file,data,train,temporal_window):
20 | self.temporal_window = temporal_window
21 | self.X = np.load(path_to_file+data)
22 | if self.X.shape[0] > self.X.shape[1]:
23 | self.X=self.X.T
24 |
25 | self.data_points = len(self.X[0,:])
26 |
27 | if train and not os.path.exists(os.path.join(path_to_file,'seq_mean.npy')):
28 | print("Compute mean and std for temporal dataset.")
29 | self.mean = np.mean(self.X)
30 | self.std = np.std(self.X)
31 | np.save(path_to_file+'seq_mean.npy', self.mean)
32 | np.save(path_to_file+'seq_std.npy', self.std)
33 | else:
34 | self.mean = np.load(path_to_file+'seq_mean.npy')
35 | self.std = np.load(path_to_file+'seq_std.npy')
36 |
37 | if train:
38 | print('Initialize train data. Datapoints %d' %self.data_points)
39 | else:
40 | print('Initialize test data. Datapoints %d' %self.data_points)
41 |
42 | def __len__(self):
43 | return self.data_points
44 |
45 | def __getitem__(self, index):
46 | temp_window = self.temporal_window
47 |
48 | nf = self.data_points
49 | start = np.random.choice(nf-temp_window)
50 | end = start+temp_window
51 |
52 | sequence = self.X[:,start:end]
53 |
54 | sequence = (sequence-self.mean)/self.std
55 |
56 | return torch.from_numpy(sequence)
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/vame/model/evaluate.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import torch
14 | import numpy as np
15 | from pathlib import Path
16 | from matplotlib import pyplot as plt
17 | import torch.utils.data as Data
18 |
19 | from vame.util.auxiliary import read_config
20 | from vame.model.rnn_vae import RNN_VAE
21 | from vame.model.dataloader import SEQUENCE_DATASET
22 |
23 | use_gpu = torch.cuda.is_available()
24 | if use_gpu:
25 | pass
26 | else:
27 | torch.device("cpu")
28 |
29 |
30 | def plot_reconstruction(filepath, test_loader, seq_len_half, model, model_name,
31 | FUTURE_DECODER, FUTURE_STEPS, suffix=None):
32 | #x = test_loader.__iter__().next()
33 | dataiter = iter(test_loader)
34 | x = next(dataiter)
35 | x = x.permute(0,2,1)
36 | if use_gpu:
37 | data = x[:,:seq_len_half,:].type('torch.FloatTensor').cuda()
38 | data_fut = x[:,seq_len_half:seq_len_half+FUTURE_STEPS,:].type('torch.FloatTensor').cuda()
39 | else:
40 | data = x[:,:seq_len_half,:].type('torch.FloatTensor').to()
41 | data_fut = x[:,seq_len_half:seq_len_half+FUTURE_STEPS,:].type('torch.FloatTensor').to()
42 | if FUTURE_DECODER:
43 | x_tilde, future, latent, mu, logvar = model(data)
44 |
45 | fut_orig = data_fut.cpu()
46 | fut_orig = fut_orig.data.numpy()
47 | fut = future.cpu()
48 | fut = fut.detach().numpy()
49 |
50 | else:
51 | x_tilde, latent, mu, logvar = model(data)
52 |
53 | data_orig = data.cpu()
54 | data_orig = data_orig.data.numpy()
55 | data_tilde = x_tilde.cpu()
56 | data_tilde = data_tilde.detach().numpy()
57 |
58 | if FUTURE_DECODER:
59 | fig, axs = plt.subplots(2, 5)
60 | fig.suptitle('Reconstruction [top] and future prediction [bottom] of input sequence')
61 | for i in range(5):
62 | axs[0,i].plot(data_orig[i,...], color='k', label='Sequence Data')
63 | axs[0,i].plot(data_tilde[i,...], color='r', linestyle='dashed', label='Sequence Reconstruction')
64 |
65 | axs[1,i].plot(fut_orig[i,...], color='k')
66 | axs[1,i].plot(fut[i,...], color='r', linestyle='dashed')
67 | axs[0,0].set(xlabel='time steps', ylabel='reconstruction')
68 | axs[1,0].set(xlabel='time steps', ylabel='predction')
69 | fig.savefig(os.path.join(filepath,"evaluate",'Future_Reconstruction.png'))
70 |
71 | else:
72 | fig, ax1 = plt.subplots(1, 5)
73 | for i in range(5):
74 | fig.suptitle('Reconstruction of input sequence')
75 | ax1[i].plot(data_orig[i,...], color='k', label='Sequence Data')
76 | ax1[i].plot(data_tilde[i,...], color='r', linestyle='dashed', label='Sequence Reconstruction')
77 | fig.set_tight_layout(True)
78 | if not suffix:
79 | fig.savefig(os.path.join(filepath,'evaluate','Reconstruction_'+model_name+'.png'), bbox_inches='tight')
80 | elif suffix:
81 | fig.savefig(os.path.join(filepath,'evaluate','Reconstruction_'+model_name+'_'+suffix+'.png'), bbox_inches='tight')
82 |
83 |
84 | def plot_loss(cfg, filepath, model_name):
85 | basepath = os.path.join(cfg['project_path'],"model","model_losses")
86 | train_loss = np.load(os.path.join(basepath,'train_losses_'+model_name+'.npy'))
87 | test_loss = np.load(os.path.join(basepath,'test_losses_'+model_name+'.npy'))
88 | mse_loss_train = np.load(os.path.join(basepath,'mse_train_losses_'+model_name+'.npy'))
89 | mse_loss_test = np.load(os.path.join(basepath,'mse_test_losses_'+model_name+'.npy'))
90 | # km_loss = np.load(os.path.join(basepath,'kmeans_losses_'+model_name+'.npy'), allow_pickle=True)
91 | km_losses = np.load(os.path.join(basepath,'kmeans_losses_'+model_name+'.npy'))
92 | kl_loss = np.load(os.path.join(basepath,'kl_losses_'+model_name+'.npy'))
93 | fut_loss = np.load(os.path.join(basepath,'fut_losses_'+model_name+'.npy'))
94 |
95 | # km_losses = []
96 | # for i in range(len(km_loss)):
97 | # km = km_loss[i].cpu().detach().numpy()
98 | # km_losses.append(km)
99 |
100 | fig, (ax1) = plt.subplots(1, 1)
101 | fig.suptitle('Losses of our Model')
102 | ax1.set(xlabel='Epochs', ylabel='loss [log-scale]')
103 | ax1.set_yscale("log")
104 | ax1.plot(train_loss, label='Train-Loss')
105 | ax1.plot(test_loss, label='Test-Loss')
106 | ax1.plot(mse_loss_train, label='MSE-Train-Loss')
107 | ax1.plot(mse_loss_test, label='MSE-Test-Loss')
108 | ax1.plot(km_losses, label='KMeans-Loss')
109 | ax1.plot(kl_loss, label='KL-Loss')
110 | ax1.plot(fut_loss, label='Prediction-Loss')
111 | ax1.legend()
112 | #fig.savefig(filepath+'evaluate/'+'MSE-and-KL-Loss'+model_name+'.png')
113 | fig.savefig(os.path.join(filepath,"evaluate",'MSE-and-KL-Loss'+model_name+'.png'))
114 |
115 |
116 | def eval_temporal(cfg, use_gpu, model_name, fixed, snapshot=None, suffix=None):
117 | SEED = 19
118 | ZDIMS = cfg['zdims']
119 | FUTURE_DECODER = cfg['prediction_decoder']
120 | TEMPORAL_WINDOW = cfg['time_window']*2
121 | FUTURE_STEPS = cfg['prediction_steps']
122 | NUM_FEATURES = cfg['num_features']
123 | if fixed == False:
124 | NUM_FEATURES = NUM_FEATURES - 2
125 | TEST_BATCH_SIZE = 64
126 | PROJECT_PATH = cfg['project_path']
127 | hidden_size_layer_1 = cfg['hidden_size_layer_1']
128 | hidden_size_layer_2 = cfg['hidden_size_layer_2']
129 | hidden_size_rec = cfg['hidden_size_rec']
130 | hidden_size_pred = cfg['hidden_size_pred']
131 | dropout_encoder = cfg['dropout_encoder']
132 | dropout_rec = cfg['dropout_rec']
133 | dropout_pred = cfg['dropout_pred']
134 | softplus = cfg['softplus']
135 |
136 | filepath = os.path.join(cfg['project_path'],"model")
137 |
138 |
139 | seq_len_half = int(TEMPORAL_WINDOW/2)
140 | if use_gpu:
141 | torch.cuda.manual_seed(SEED)
142 | model = RNN_VAE(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
143 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
144 | dropout_rec, dropout_pred, softplus).cuda()
145 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],"model","best_model",model_name+'_'+cfg['Project']+'.pkl')))
146 | else:
147 | model = RNN_VAE(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
148 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
149 | dropout_rec, dropout_pred, softplus).to()
150 | if not snapshot:
151 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],"model","best_model",model_name+'_'+cfg['Project']+'.pkl'), map_location=torch.device('cpu')))
152 | elif snapshot:
153 | model.load_state_dict(torch.load(snapshot), map_location=torch.device('cpu'))
154 | model.eval() #toggle evaluation mode
155 |
156 | testset = SEQUENCE_DATASET(os.path.join(cfg['project_path'],"data", "train",""), data='test_seq.npy', train=False, temporal_window=TEMPORAL_WINDOW)
157 | test_loader = Data.DataLoader(testset, batch_size=TEST_BATCH_SIZE, shuffle=True, drop_last=True)
158 |
159 | if not snapshot:
160 | plot_reconstruction(filepath, test_loader, seq_len_half, model, model_name, FUTURE_DECODER, FUTURE_STEPS)#, suffix=suffix
161 | elif snapshot:
162 | plot_reconstruction(filepath, test_loader, seq_len_half, model, model_name, FUTURE_DECODER, FUTURE_STEPS, suffix=suffix)#,
163 | if use_gpu:
164 | plot_loss(cfg, filepath, model_name)
165 | else:
166 | plot_loss(cfg, filepath, model_name)
167 | # pass #note, loading of losses needs to be adapted for CPU use #TODO
168 |
169 |
170 | def evaluate_model(config, use_snapshots=False):
171 | """
172 | Evaluation of testset.
173 |
174 | Parameters
175 | ----------
176 | config : str
177 | Path to config file.
178 | model_name : str
179 | name of model (same as in config.yaml)
180 | use_snapshots : bool
181 | Whether to plot for all snapshots or only the best model.
182 | """
183 | config_file = Path(config).resolve()
184 | cfg = read_config(config_file)
185 | #legacy = cfg['legacy']
186 | model_name = cfg['model_name']
187 | fixed = cfg['egocentric_data']
188 |
189 | if not os.path.exists(os.path.join(cfg['project_path'],"model","evaluate")):
190 | os.mkdir(os.path.join(cfg['project_path'],"model","evaluate"))
191 |
192 | use_gpu = torch.cuda.is_available()
193 | if use_gpu:
194 | print("Using CUDA")
195 | print('GPU active:',torch.cuda.is_available())
196 | print('GPU used:',torch.cuda.get_device_name(0))
197 | else:
198 | torch.device("cpu")
199 | print("CUDA is not working, or a GPU is not found; using CPU!")
200 |
201 | print("\n\nEvaluation of %s model. \n" %model_name)
202 | if not use_snapshots:
203 | eval_temporal(cfg, use_gpu, model_name, fixed)#suffix=suffix
204 | elif use_snapshots:
205 | snapshots=os.listdir(os.path.join(cfg['project_path'],'model','best_model','snapshots'))
206 | for snap in snapshots:
207 | fullpath = os.path.join(cfg['project_path'],"model","best_model","snapshots",snap)
208 | epoch=snap.split('_')[-1]
209 | eval_temporal(cfg, use_gpu, model_name, fixed, snapshot=fullpath, suffix='snapshot'+str(epoch))
210 | #eval_temporal(cfg, use_gpu, model_name, legacy=legacy, suffix='bestModel')
211 |
212 | print("You can find the results of the evaluation in '/Your-VAME-Project-Apr30-2020/model/evaluate/' \n"
213 | "OPTIONS:\n"
214 | "- vame.pose_segmentation() to identify behavioral motifs.\n"
215 | "- re-run the model for further fine tuning. Check again with vame.evaluate_model()")
216 |
--------------------------------------------------------------------------------
/vame/model/rnn_model.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Variational Animal Motion Embedding 0.1 Toolbox
4 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
5 | Leibniz Institute for Neurobiology, Magdeburg, Germany
6 |
7 | https://github.com/LINCellularNeuroscience/VAME
8 | Licensed under GNU General Public License v3.0
9 |
10 | The Model is partially adapted from the Timeseries Clustering repository developed by Tejas Lodaya:
11 | https://github.com/tejaslodaya/timeseries-clustering-vae/blob/master/vrae/vrae.py
12 | """
13 |
14 |
15 | import torch
16 | from torch import nn
17 | from torch.autograd import Variable
18 |
19 |
20 | # NEW MODEL WITH SMALL ALTERATIONS
21 | """ MODEL """
22 |
23 | class Encoder(nn.Module):
24 | def __init__(self, NUM_FEATURES, hidden_size_layer_1, hidden_size_layer_2, dropout_encoder):
25 | super(Encoder, self).__init__()
26 |
27 | self.input_size = NUM_FEATURES
28 | self.hidden_size = hidden_size_layer_1
29 | self.hidden_size_2 = hidden_size_layer_2
30 | self.n_layers = 2
31 | self.dropout = dropout_encoder
32 | self.bidirectional = True
33 |
34 | self.encoder_rnn = nn.GRU(input_size=self.input_size, hidden_size=self.hidden_size, num_layers=self.n_layers,
35 | bias=True, batch_first=True, dropout=self.dropout, bidirectional=self.bidirectional)#UNRELEASED!
36 |
37 |
38 | self.hidden_factor = (2 if self.bidirectional else 1) * self.n_layers
39 |
40 | def forward(self, inputs):
41 | outputs_1, hidden_1 = self.encoder_rnn(inputs)#UNRELEASED!
42 |
43 | hidden = torch.cat((hidden_1[0,...], hidden_1[1,...], hidden_1[2,...], hidden_1[3,...]),1)
44 |
45 | return hidden
46 |
47 |
48 | class Lambda(nn.Module):
49 | def __init__(self,ZDIMS, hidden_size_layer_1, hidden_size_layer_2, softplus):
50 | super(Lambda, self).__init__()
51 |
52 | self.hid_dim = hidden_size_layer_1*4
53 | self.latent_length = ZDIMS
54 | self.softplus = softplus
55 |
56 | self.hidden_to_mean = nn.Linear(self.hid_dim, self.latent_length)
57 | self.hidden_to_logvar = nn.Linear(self.hid_dim, self.latent_length)
58 |
59 | if self.softplus == True:
60 | print("Using a softplus activation to ensures that the variance is parameterized as non-negative and activated by a smooth function")
61 | self.softplus_fn = nn.Softplus()
62 |
63 | def forward(self, hidden):
64 |
65 | self.mean = self.hidden_to_mean(hidden)
66 | if self.softplus == True:
67 | self.logvar = self.softplus_fn(self.hidden_to_logvar(hidden))
68 | else:
69 | self.logvar = self.hidden_to_logvar(hidden)
70 |
71 | if self.training:
72 | std = torch.exp(0.5 * self.logvar)
73 | eps = torch.randn_like(std)
74 | return eps.mul(std).add_(self.mean), self.mean, self.logvar
75 | else:
76 | return self.mean, self.mean, self.logvar
77 |
78 |
79 | class Decoder(nn.Module):
80 | def __init__(self,TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES, hidden_size_rec, dropout_rec):
81 | super(Decoder,self).__init__()
82 |
83 | self.num_features = NUM_FEATURES
84 | self.sequence_length = TEMPORAL_WINDOW
85 | self.hidden_size = hidden_size_rec
86 | self.latent_length = ZDIMS
87 | self.n_layers = 1
88 | self.dropout = dropout_rec
89 | self.bidirectional = True
90 |
91 | self.rnn_rec = nn.GRU(self.latent_length, hidden_size=self.hidden_size, num_layers=self.n_layers,
92 | bias=True, batch_first=True, dropout=self.dropout, bidirectional=self.bidirectional)
93 |
94 | self.hidden_factor = (2 if self.bidirectional else 1) * self.n_layers # NEW
95 |
96 | self.latent_to_hidden = nn.Linear(self.latent_length,self.hidden_size * self.hidden_factor) # NEW
97 | self.hidden_to_output = nn.Linear(self.hidden_size*(2 if self.bidirectional else 1), self.num_features)
98 |
99 | def forward(self, inputs, z):
100 | batch_size = inputs.size(0) # NEW
101 |
102 | hidden = self.latent_to_hidden(z) # NEW
103 |
104 | hidden = hidden.view(self.hidden_factor, batch_size, self.hidden_size) # NEW
105 |
106 | decoder_output, _ = self.rnn_rec(inputs, hidden)
107 | prediction = self.hidden_to_output(decoder_output)
108 |
109 | return prediction
110 |
111 |
112 | class Decoder_Future(nn.Module):
113 | def __init__(self,TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_STEPS, hidden_size_pred, dropout_pred):
114 | super(Decoder_Future,self).__init__()
115 |
116 | self.num_features = NUM_FEATURES
117 | self.future_steps = FUTURE_STEPS
118 | self.sequence_length = TEMPORAL_WINDOW
119 | self.hidden_size = hidden_size_pred
120 | self.latent_length = ZDIMS
121 | self.n_layers = 1
122 | self.dropout = dropout_pred
123 | self.bidirectional = True
124 |
125 | self.rnn_pred = nn.GRU(self.latent_length, hidden_size=self.hidden_size, num_layers=self.n_layers,
126 | bias=True, batch_first=True, dropout=self.dropout, bidirectional=self.bidirectional)
127 |
128 | self.hidden_factor = (2 if self.bidirectional else 1) * self.n_layers # NEW
129 |
130 | self.latent_to_hidden = nn.Linear(self.latent_length,self.hidden_size * self.hidden_factor)
131 | self.hidden_to_output = nn.Linear(self.hidden_size*2, self.num_features)
132 |
133 | def forward(self, inputs, z):
134 | batch_size = inputs.size(0)
135 |
136 | hidden = self.latent_to_hidden(z)
137 | hidden = hidden.view(self.hidden_factor, batch_size, self.hidden_size)
138 |
139 | inputs = inputs[:,:self.future_steps,:]
140 | decoder_output, _ = self.rnn_pred(inputs, hidden)
141 |
142 | prediction = self.hidden_to_output(decoder_output)
143 |
144 | return prediction
145 |
146 |
147 | class RNN_VAE(nn.Module):
148 | def __init__(self,TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
149 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
150 | dropout_rec, dropout_pred, softplus):
151 | super(RNN_VAE,self).__init__()
152 |
153 | self.FUTURE_DECODER = FUTURE_DECODER
154 | self.seq_len = int(TEMPORAL_WINDOW / 2)
155 | self.encoder = Encoder(NUM_FEATURES, hidden_size_layer_1, hidden_size_layer_2, dropout_encoder)
156 | self.lmbda = Lambda(ZDIMS, hidden_size_layer_1, hidden_size_layer_2, softplus)
157 | self.decoder = Decoder(self.seq_len,ZDIMS,NUM_FEATURES, hidden_size_rec, dropout_rec)
158 | if FUTURE_DECODER:
159 | self.decoder_future = Decoder_Future(self.seq_len,ZDIMS,NUM_FEATURES,FUTURE_STEPS, hidden_size_pred,
160 | dropout_pred)
161 |
162 | def forward(self,seq):
163 |
164 | """ Encode input sequence """
165 | h_n = self.encoder(seq)
166 |
167 | """ Compute the latent state via reparametrization trick """
168 | z, mu, logvar = self.lmbda(h_n)
169 | ins = z.unsqueeze(2).repeat(1, 1, self.seq_len)
170 | ins = ins.permute(0,2,1)
171 |
172 | """ Predict the future of the sequence from the latent state"""
173 | prediction = self.decoder(ins, z)
174 |
175 | if self.FUTURE_DECODER:
176 | future = self.decoder_future(ins, z)
177 | return prediction, future, z, mu, logvar
178 | else:
179 | return prediction, z, mu, logvar
180 |
181 |
182 | #----------------------------------------------------------------------------------------
183 | # LEGACY MODEL |
184 | #----------------------------------------------------------------------------------------
185 |
186 |
187 | """ MODEL """
188 | class Encoder_LEGACY(nn.Module):
189 | def __init__(self, NUM_FEATURES, hidden_size_layer_1, hidden_size_layer_2, dropout_encoder):
190 | super(Encoder_LEGACY, self).__init__()
191 |
192 | self.input_size = NUM_FEATURES
193 | self.hidden_size = hidden_size_layer_1
194 | self.hidden_size_2 = hidden_size_layer_2
195 | self.n_layers = 1
196 | self.dropout = dropout_encoder
197 |
198 | self.rnn_1 = nn.GRU(input_size=self.input_size, hidden_size=self.hidden_size, num_layers=self.n_layers,
199 | bias=True, batch_first=True, dropout=self.dropout, bidirectional=True)
200 |
201 | self.rnn_2 = nn.GRU(input_size=self.hidden_size*2, hidden_size=self.hidden_size_2, num_layers=self.n_layers,
202 | bias=True, batch_first=True, dropout=self.dropout, bidirectional=True)
203 |
204 | def forward(self, inputs):
205 | outputs_1, hidden_1 = self.rnn_1(inputs)
206 | outputs_2, hidden_2 = self.rnn_2(outputs_1)
207 |
208 | h_n_1 = torch.cat((hidden_1[0,...], hidden_1[1,...]), 1)
209 | h_n_2 = torch.cat((hidden_2[0,...], hidden_2[1,...]), 1)
210 |
211 | h_n = torch.cat((h_n_1, h_n_2), 1)
212 |
213 | return h_n
214 |
215 |
216 | class Lambda_LEGACY(nn.Module):
217 | def __init__(self,ZDIMS, hidden_size_layer_1, hidden_size_layer_2):
218 | super(Lambda_LEGACY, self).__init__()
219 |
220 | self.hid_dim = hidden_size_layer_1*2 + hidden_size_layer_2*2
221 | self.latent_length = ZDIMS
222 |
223 | self.hidden_to_linear = nn.Linear(self.hid_dim, self.hid_dim)
224 | self.hidden_to_mean = nn.Linear(self.hid_dim, self.latent_length)
225 | self.hidden_to_logvar = nn.Linear(self.hid_dim, self.latent_length)
226 |
227 | self.softplus = nn.Softplus()
228 |
229 | def forward(self, cell_output):
230 | self.latent_mean = self.hidden_to_mean(cell_output)
231 |
232 | # based on Pereira et al 2019:
233 | # "The SoftPlus function ensures that the variance is parameterized as non-negative and activated
234 | # by a smooth function
235 | self.latent_logvar = self.softplus(self.hidden_to_logvar(cell_output))
236 |
237 | if self.training:
238 | std = self.latent_logvar.mul(0.5).exp_()
239 | eps = Variable(std.data.new(std.size()).normal_())
240 | return eps.mul(std).add_(self.latent_mean), self.latent_mean, self.latent_logvar
241 | else:
242 | return self.latent_mean, self.latent_mean, self.latent_logvar
243 |
244 |
245 | class Decoder_LEGACY(nn.Module):
246 | def __init__(self,TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES, hidden_size_rec, dropout_rec):
247 | super(Decoder_LEGACY,self).__init__()
248 |
249 | self.num_features = NUM_FEATURES
250 | self.sequence_length = TEMPORAL_WINDOW
251 | self.hidden_size = hidden_size_rec
252 | self.latent_length = ZDIMS
253 | self.n_layers = 1
254 | self.dropout = dropout_rec
255 |
256 | self.rnn_rec = nn.GRU(self.latent_length, hidden_size=self.hidden_size, num_layers=self.n_layers,
257 | bias=True, batch_first=True, dropout=self.dropout, bidirectional=False)
258 |
259 | self.hidden_to_output = nn.Linear(self.hidden_size, self.num_features)
260 |
261 | def forward(self, inputs):
262 | decoder_output, _ = self.rnn_rec(inputs)
263 | prediction = self.hidden_to_output(decoder_output)
264 |
265 | return prediction
266 |
267 | class Decoder_Future_LEGACY(nn.Module):
268 | def __init__(self,TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_STEPS, hidden_size_pred, dropout_pred):
269 | super(Decoder_Future_LEGACY,self).__init__()
270 |
271 | self.num_features = NUM_FEATURES
272 | self.future_steps = FUTURE_STEPS
273 | self.sequence_length = TEMPORAL_WINDOW
274 | self.hidden_size = hidden_size_pred
275 | self.latent_length = ZDIMS
276 | self.n_layers = 1
277 | self.dropout = dropout_pred
278 |
279 | self.rnn_pred = nn.GRU(self.latent_length, hidden_size=self.hidden_size, num_layers=self.n_layers,
280 | bias=True, batch_first=True, dropout=self.dropout, bidirectional=True)
281 |
282 | self.hidden_to_output = nn.Linear(self.hidden_size*2, self.num_features)
283 |
284 | def forward(self, inputs):
285 | inputs = inputs[:,:self.future_steps,:]
286 | decoder_output, _ = self.rnn_pred(inputs)
287 | prediction = self.hidden_to_output(decoder_output)
288 |
289 | return prediction
290 |
291 |
292 | class RNN_VAE_LEGACY(nn.Module):
293 | def __init__(self,TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
294 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
295 | dropout_rec, dropout_pred, softplus):
296 | super(RNN_VAE_LEGACY,self).__init__()
297 |
298 | self.FUTURE_DECODER = FUTURE_DECODER
299 | self.seq_len = int(TEMPORAL_WINDOW / 2)
300 | self.encoder = Encoder_LEGACY(NUM_FEATURES, hidden_size_layer_1, hidden_size_layer_2, dropout_encoder)
301 | self.lmbda = Lambda_LEGACY(ZDIMS, hidden_size_layer_1, hidden_size_layer_2)
302 | self.decoder = Decoder_LEGACY(self.seq_len,ZDIMS,NUM_FEATURES, hidden_size_rec, dropout_rec)
303 | if FUTURE_DECODER:
304 | self.decoder_future = Decoder_Future_LEGACY(self.seq_len,ZDIMS,NUM_FEATURES,FUTURE_STEPS, hidden_size_pred,
305 | dropout_pred)
306 |
307 | def forward(self,seq):
308 |
309 | """ Encode input sequence """
310 | h_n = self.encoder(seq)
311 |
312 | """ Compute the latent state via reparametrization trick """
313 | latent, mu, logvar = self.lmbda(h_n)
314 | z = latent.unsqueeze(2).repeat(1, 1, self.seq_len)
315 | z = z.permute(0,2,1)
316 |
317 | """ Predict the future of the sequence from the latent state"""
318 | prediction = self.decoder(z)
319 |
320 | if self.FUTURE_DECODER:
321 | future = self.decoder_future(z)
322 | return prediction, future, latent, mu, logvar
323 | else:
324 | return prediction, latent, mu, logvar
325 |
326 |
--------------------------------------------------------------------------------
/vame/model/rnn_vae.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import torch
13 | from torch import nn
14 | import torch.utils.data as Data
15 | from torch.autograd import Variable
16 | from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau
17 |
18 | import os
19 | import numpy as np
20 | from pathlib import Path
21 |
22 | from vame.util.auxiliary import read_config
23 | from vame.model.dataloader import SEQUENCE_DATASET
24 | from vame.model.rnn_model import RNN_VAE, RNN_VAE_LEGACY
25 |
26 | # make sure torch uses cuda for GPU computing
27 | use_gpu = torch.cuda.is_available()
28 | if use_gpu:
29 | print("Using CUDA")
30 | print('GPU active:',torch.cuda.is_available())
31 | print('GPU used:',torch.cuda.get_device_name(0))
32 | else:
33 | torch.device("cpu")
34 |
35 | def reconstruction_loss(x, x_tilde, reduction):
36 | mse_loss = nn.MSELoss(reduction=reduction)
37 | rec_loss = mse_loss(x_tilde,x)
38 | return rec_loss
39 |
40 | def future_reconstruction_loss(x, x_tilde, reduction):
41 | mse_loss = nn.MSELoss(reduction=reduction)
42 | rec_loss = mse_loss(x_tilde,x)
43 | return rec_loss
44 |
45 | def cluster_loss(H, kloss, lmbda, batch_size):
46 | gram_matrix = (H.T @ H) / batch_size
47 | _ ,sv_2, _ = torch.svd(gram_matrix)
48 | sv = torch.sqrt(sv_2[:kloss])
49 | loss = torch.sum(sv)
50 | return lmbda*loss
51 |
52 |
53 | def kullback_leibler_loss(mu, logvar):
54 | # see Appendix B from VAE paper:
55 | # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
56 | # https://arxiv.org/abs/1312.6114
57 | # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
58 | # I'm using torch.mean() here as the sum() version depends on the size of the latent vector
59 | KLD = -0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())
60 | return KLD
61 |
62 |
63 | def kl_annealing(epoch, kl_start, annealtime, function):
64 | """
65 | Annealing of Kullback-Leibler loss to let the model learn first
66 | the reconstruction of the data before the KL loss term gets introduced.
67 | """
68 | if epoch > kl_start:
69 | if function == 'linear':
70 | new_weight = min(1, (epoch-kl_start)/(annealtime))
71 |
72 | elif function == 'sigmoid':
73 | new_weight = float(1/(1+np.exp(-0.9*(epoch-annealtime))))
74 | else:
75 | raise NotImplementedError('currently only "linear" and "sigmoid" are implemented')
76 |
77 | return new_weight
78 |
79 | else:
80 | new_weight = 0
81 | return new_weight
82 |
83 |
84 | def gaussian(ins, is_training, seq_len, std_n=0.8):
85 | if is_training:
86 | emp_std = ins.std(1)*std_n
87 | emp_std = emp_std.unsqueeze(2).repeat(1, 1, seq_len)
88 | emp_std = emp_std.permute(0,2,1)
89 | noise = Variable(ins.data.new(ins.size()).normal_(0, 1))
90 | return ins + (noise*emp_std)
91 | return ins
92 |
93 |
94 | def train(train_loader, epoch, model, optimizer, anneal_function, BETA, kl_start,
95 | annealtime, seq_len, future_decoder, future_steps, scheduler, mse_red,
96 | mse_pred, kloss, klmbda, bsize, noise):
97 | model.train() # toggle model to train mode
98 | train_loss = 0.0
99 | mse_loss = 0.0
100 | kullback_loss = 0.0
101 | kmeans_losses = 0.0
102 | fut_loss = 0.0
103 | loss = 0.0
104 | seq_len_half = int(seq_len / 2)
105 |
106 | for idx, data_item in enumerate(train_loader):
107 | data_item = Variable(data_item)
108 | data_item = data_item.permute(0,2,1)
109 |
110 | if use_gpu:
111 | data = data_item[:,:seq_len_half,:].type('torch.FloatTensor').cuda()
112 | fut = data_item[:,seq_len_half:seq_len_half+future_steps,:].type('torch.FloatTensor').cuda()
113 | else:
114 | data = data_item[:,:seq_len_half,:].type('torch.FloatTensor').to()
115 | fut = data_item[:,seq_len_half:seq_len_half+future_steps,:].type('torch.FloatTensor').to()
116 | if noise == True:
117 | data_gaussian = gaussian(data,True,seq_len_half)
118 | else:
119 | data_gaussian = data
120 |
121 | if future_decoder:
122 | data_tilde, future, latent, mu, logvar = model(data_gaussian)
123 |
124 | rec_loss = reconstruction_loss(data, data_tilde, mse_red)
125 | fut_rec_loss = future_reconstruction_loss(fut, future, mse_pred)
126 | kmeans_loss = cluster_loss(latent.T, kloss, klmbda, bsize)
127 | kl_loss = kullback_leibler_loss(mu, logvar)
128 | kl_weight = kl_annealing(epoch, kl_start, annealtime, anneal_function)
129 | loss = rec_loss + fut_rec_loss + BETA*kl_weight*kl_loss + kl_weight*kmeans_loss
130 | fut_loss += fut_rec_loss.item()
131 |
132 | else:
133 | data_tilde, latent, mu, logvar = model(data_gaussian)
134 |
135 | rec_loss = reconstruction_loss(data, data_tilde, mse_red)
136 | kl_loss = kullback_leibler_loss(mu, logvar)
137 | kmeans_loss = cluster_loss(latent.T, kloss, klmbda, bsize)
138 | kl_weight = kl_annealing(epoch, kl_start, annealtime, anneal_function)
139 | loss = rec_loss + BETA*kl_weight*kl_loss + kl_weight*kmeans_loss
140 |
141 | optimizer.zero_grad()
142 | loss.backward()
143 | optimizer.step()
144 |
145 | # torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm = 5)
146 |
147 | train_loss += loss.item()
148 | mse_loss += rec_loss.item()
149 | kullback_loss += kl_loss.item()
150 | kmeans_losses += kmeans_loss.item()
151 |
152 | # if idx % 1000 == 0:
153 | # print('Epoch: %d. loss: %.4f' %(epoch, loss.item()))
154 |
155 | scheduler.step(loss) #be sure scheduler is called before optimizer in >1.1 pytorch
156 |
157 | if future_decoder:
158 | print('Train loss: {:.3f}, MSE-Loss: {:.3f}, MSE-Future-Loss {:.3f}, KL-Loss: {:.3f}, Kmeans-Loss: {:.3f}, weight: {:.2f}'.format(train_loss / idx,
159 | mse_loss /idx, fut_loss/idx, BETA*kl_weight*kullback_loss/idx, kl_weight*kmeans_losses/idx, kl_weight))
160 | else:
161 | print('Train loss: {:.3f}, MSE-Loss: {:.3f}, KL-Loss: {:.3f}, Kmeans-Loss: {:.3f}, weight: {:.2f}'.format(train_loss / idx,
162 | mse_loss /idx, BETA*kl_weight*kullback_loss/idx, kl_weight*kmeans_losses/idx, kl_weight))
163 |
164 | return kl_weight, train_loss/idx, kl_weight*kmeans_losses/idx, kullback_loss/idx, mse_loss/idx, fut_loss/idx
165 |
166 |
167 | def test(test_loader, epoch, model, optimizer, BETA, kl_weight, seq_len, mse_red, kloss, klmbda, future_decoder, bsize):
168 | model.eval() # toggle model to inference mode
169 | test_loss = 0.0
170 | mse_loss = 0.0
171 | kullback_loss = 0.0
172 | kmeans_losses = 0.0
173 | loss = 0.0
174 | seq_len_half = int(seq_len / 2)
175 |
176 | with torch.no_grad():
177 | for idx, data_item in enumerate(test_loader):
178 | # we're only going to infer, so no autograd at all required
179 | data_item = Variable(data_item)
180 | data_item = data_item.permute(0,2,1)
181 | if use_gpu:
182 | data = data_item[:,:seq_len_half,:].type('torch.FloatTensor').cuda()
183 | else:
184 | data = data_item[:,:seq_len_half,:].type('torch.FloatTensor').to()
185 |
186 | if future_decoder:
187 | recon_images, _, latent, mu, logvar = model(data)
188 | rec_loss = reconstruction_loss(data, recon_images, mse_red)
189 | kl_loss = kullback_leibler_loss(mu, logvar)
190 | kmeans_loss = cluster_loss(latent.T, kloss, klmbda, bsize)
191 | loss = rec_loss + BETA*kl_weight*kl_loss+ kl_weight*kmeans_loss
192 |
193 | else:
194 | recon_images, latent, mu, logvar = model(data)
195 | rec_loss = reconstruction_loss(data, recon_images, mse_red)
196 | kl_loss = kullback_leibler_loss(mu, logvar)
197 | kmeans_loss = cluster_loss(latent.T, kloss, klmbda, bsize)
198 | loss = rec_loss + BETA*kl_weight*kl_loss + kl_weight*kmeans_loss
199 |
200 | # torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm = 5)
201 |
202 | test_loss += loss.item()
203 | mse_loss += rec_loss.item()
204 | kullback_loss += kl_loss.item()
205 | kmeans_losses += kmeans_loss
206 |
207 | print('Test loss: {:.3f}, MSE-Loss: {:.3f}, KL-Loss: {:.3f}, Kmeans-Loss: {:.3f}'.format(test_loss / idx,
208 | mse_loss /idx, BETA*kl_weight*kullback_loss/idx, kl_weight*kmeans_losses/idx))
209 |
210 | return mse_loss /idx, test_loss/idx, kl_weight*kmeans_losses
211 |
212 |
213 | def train_model(config):
214 | config_file = Path(config).resolve()
215 | cfg = read_config(config_file)
216 | legacy = cfg['legacy']
217 | model_name = cfg['model_name']
218 | pretrained_weights = cfg['pretrained_weights']
219 | pretrained_model = cfg['pretrained_model']
220 | fixed = cfg['egocentric_data']
221 |
222 | print("Train Variational Autoencoder - model name: %s \n" %model_name)
223 | if not os.path.exists(os.path.join(cfg['project_path'],'model','best_model',"")):
224 | os.mkdir(os.path.join(cfg['project_path'],'model','best_model',""))
225 | os.mkdir(os.path.join(cfg['project_path'],'model','best_model','snapshots',""))
226 | os.mkdir(os.path.join(cfg['project_path'],'model','model_losses',""))
227 |
228 | # make sure torch uses cuda for GPU computing
229 | use_gpu = torch.cuda.is_available()
230 | if use_gpu:
231 | print("Using CUDA")
232 | print('GPU active:',torch.cuda.is_available())
233 | print('GPU used: ',torch.cuda.get_device_name(0))
234 | else:
235 | torch.device("cpu")
236 | print("warning, a GPU was not found... proceeding with CPU (slow!) \n")
237 | #raise NotImplementedError('GPU Computing is required!')
238 |
239 | """ HYPERPARAMTERS """
240 | # General
241 | CUDA = use_gpu
242 | SEED = 19
243 | TRAIN_BATCH_SIZE = cfg['batch_size']
244 | TEST_BATCH_SIZE = int(cfg['batch_size']/4)
245 | EPOCHS = cfg['max_epochs']
246 | ZDIMS = cfg['zdims']
247 | BETA = cfg['beta']
248 | SNAPSHOT = cfg['model_snapshot']
249 | LEARNING_RATE = cfg['learning_rate']
250 | NUM_FEATURES = cfg['num_features']
251 | if fixed == False:
252 | NUM_FEATURES = NUM_FEATURES - 2
253 | TEMPORAL_WINDOW = cfg['time_window']*2
254 | FUTURE_DECODER = cfg['prediction_decoder']
255 | FUTURE_STEPS = cfg['prediction_steps']
256 |
257 | # RNN
258 | hidden_size_layer_1 = cfg['hidden_size_layer_1']
259 | hidden_size_layer_2 = cfg['hidden_size_layer_2']
260 | hidden_size_rec = cfg['hidden_size_rec']
261 | hidden_size_pred = cfg['hidden_size_pred']
262 | dropout_encoder = cfg['dropout_encoder']
263 | dropout_rec = cfg['dropout_rec']
264 | dropout_pred = cfg['dropout_pred']
265 | noise = cfg['noise']
266 | scheduler_step_size = cfg['scheduler_step_size']
267 | softplus = cfg['softplus']
268 |
269 | # Loss
270 | MSE_REC_REDUCTION = cfg['mse_reconstruction_reduction']
271 | MSE_PRED_REDUCTION = cfg['mse_prediction_reduction']
272 | KMEANS_LOSS = cfg['kmeans_loss']
273 | KMEANS_LAMBDA = cfg['kmeans_lambda']
274 | KL_START = cfg['kl_start']
275 | ANNEALTIME = cfg['annealtime']
276 | anneal_function = cfg['anneal_function']
277 | optimizer_scheduler = cfg['scheduler']
278 |
279 | BEST_LOSS = 999999
280 | convergence = 0
281 | print('Latent Dimensions: %d, Time window: %d, Batch Size: %d, Beta: %d, lr: %.4f\n' %(ZDIMS, cfg['time_window'], TRAIN_BATCH_SIZE, BETA, LEARNING_RATE))
282 |
283 | # simple logging of diverse losses
284 | train_losses = []
285 | test_losses = []
286 | kmeans_losses = []
287 | kl_losses = []
288 | weight_values = []
289 | mse_losses = []
290 | fut_losses = []
291 |
292 | torch.manual_seed(SEED)
293 |
294 | if legacy == False:
295 | RNN = RNN_VAE
296 | else:
297 | RNN = RNN_VAE_LEGACY
298 | if CUDA:
299 | torch.cuda.manual_seed(SEED)
300 | model = RNN(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
301 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
302 | dropout_rec, dropout_pred, softplus).cuda()
303 | else: #cpu support ...
304 | torch.cuda.manual_seed(SEED)
305 | model = RNN(TEMPORAL_WINDOW,ZDIMS,NUM_FEATURES,FUTURE_DECODER,FUTURE_STEPS, hidden_size_layer_1,
306 | hidden_size_layer_2, hidden_size_rec, hidden_size_pred, dropout_encoder,
307 | dropout_rec, dropout_pred, softplus).to()
308 |
309 | if pretrained_weights:
310 | try:
311 | print("Loading pretrained weights from model: %s\n" %os.path.join(cfg['project_path'],'model','best_model',pretrained_model+'_'+cfg['Project']+'.pkl'))
312 | model.load_state_dict(torch.load(os.path.join(cfg['project_path'],'model','best_model',pretrained_model+'_'+cfg['Project']+'.pkl')))
313 | KL_START = 0
314 | ANNEALTIME = 1
315 | except:
316 | print("No file found at %s\n" %os.path.join(cfg['project_path'],'model','best_model',pretrained_model+'_'+cfg['Project']+'.pkl'))
317 | try:
318 | print("Loading pretrained weights from %s\n" %pretrained_model)
319 | model.load_state_dict(torch.load(pretrained_model))
320 | KL_START = 0
321 | ANNEALTIME = 1
322 | except:
323 | print("Could not load pretrained model. Check file path in config.yaml.")
324 |
325 | """ DATASET """
326 | trainset = SEQUENCE_DATASET(os.path.join(cfg['project_path'],"data", "train",""), data='train_seq.npy', train=True, temporal_window=TEMPORAL_WINDOW)
327 | testset = SEQUENCE_DATASET(os.path.join(cfg['project_path'],"data", "train",""), data='test_seq.npy', train=False, temporal_window=TEMPORAL_WINDOW)
328 |
329 | train_loader = Data.DataLoader(trainset, batch_size=TRAIN_BATCH_SIZE, shuffle=True, drop_last=True)
330 | test_loader = Data.DataLoader(testset, batch_size=TEST_BATCH_SIZE, shuffle=True, drop_last=True)
331 |
332 | optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, amsgrad=True)
333 |
334 | if optimizer_scheduler:
335 | print('Scheduler step size: %d, Scheduler gamma: %.2f\n' %(scheduler_step_size, cfg['scheduler_gamma']))
336 | # Thanks to @alexcwsmith for the optimized scheduler contribution
337 | scheduler = ReduceLROnPlateau(optimizer, 'min', factor=cfg['scheduler_gamma'], patience=cfg['scheduler_step_size'], threshold=1e-3, threshold_mode='rel', verbose=True)
338 | else:
339 | scheduler = StepLR(optimizer, step_size=scheduler_step_size, gamma=1, last_epoch=-1)
340 |
341 | print("Start training... ")
342 | for epoch in range(1,EPOCHS):
343 | print("Epoch: %d" %epoch)
344 | weight, train_loss, km_loss, kl_loss, mse_loss, fut_loss = train(train_loader, epoch, model, optimizer,
345 | anneal_function, BETA, KL_START,
346 | ANNEALTIME, TEMPORAL_WINDOW, FUTURE_DECODER,
347 | FUTURE_STEPS, scheduler, MSE_REC_REDUCTION,
348 | MSE_PRED_REDUCTION, KMEANS_LOSS, KMEANS_LAMBDA,
349 | TRAIN_BATCH_SIZE, noise)
350 |
351 | current_loss, test_loss, test_list = test(test_loader, epoch, model, optimizer,
352 | BETA, weight, TEMPORAL_WINDOW, MSE_REC_REDUCTION,
353 | KMEANS_LOSS, KMEANS_LAMBDA, FUTURE_DECODER, TEST_BATCH_SIZE)
354 |
355 | # logging losses
356 | train_losses.append(train_loss)
357 | test_losses.append(test_loss)
358 | kmeans_losses.append(km_loss)
359 | kl_losses.append(kl_loss)
360 | weight_values.append(weight)
361 | mse_losses.append(mse_loss)
362 | fut_losses.append(fut_loss)
363 |
364 | # save best model
365 | if weight > 0.99 and current_loss <= BEST_LOSS:
366 | BEST_LOSS = current_loss
367 | print("Saving model!")
368 |
369 | if use_gpu:
370 | torch.save(model.state_dict(), os.path.join(cfg['project_path'],"model", "best_model",model_name+'_'+cfg['Project']+'.pkl'))
371 |
372 | else:
373 | torch.save(model.state_dict(), os.path.join(cfg['project_path'],"model", "best_model",model_name+'_'+cfg['Project']+'.pkl'))
374 |
375 | convergence = 0
376 | else:
377 | convergence += 1
378 |
379 | if epoch % SNAPSHOT == 0:
380 | print("Saving model snapshot!\n")
381 | torch.save(model.state_dict(), os.path.join(cfg['project_path'],'model','best_model','snapshots',model_name+'_'+cfg['Project']+'_epoch_'+str(epoch)+'.pkl'))
382 |
383 | if convergence > cfg['model_convergence']:
384 | print('Finished training...')
385 | print('Model converged. Please check your model with vame.evaluate_model(). \n'
386 | 'You can also re-run vame.trainmodel() to further improve your model. \n'
387 | 'Make sure to set _pretrained_weights_ in your config.yaml to "true" \n'
388 | 'and plug your current model name into _pretrained_model_. \n'
389 | 'Hint: Set "model_convergence" in your config.yaml to a higher value. \n'
390 | '\n'
391 | 'Next: \n'
392 | 'Use vame.pose_segmentation() to identify behavioral motifs in your dataset!')
393 | #return
394 | break
395 |
396 | # save logged losses
397 | np.save(os.path.join(cfg['project_path'],'model','model_losses','train_losses_'+model_name), train_losses)
398 | np.save(os.path.join(cfg['project_path'],'model','model_losses','test_losses_'+model_name), test_losses)
399 | np.save(os.path.join(cfg['project_path'],'model','model_losses','kmeans_losses_'+model_name), kmeans_losses)
400 | np.save(os.path.join(cfg['project_path'],'model','model_losses','kl_losses_'+model_name), kl_losses)
401 | np.save(os.path.join(cfg['project_path'],'model','model_losses','weight_values_'+model_name), weight_values)
402 | np.save(os.path.join(cfg['project_path'],'model','model_losses','mse_train_losses_'+model_name), mse_losses)
403 | np.save(os.path.join(cfg['project_path'],'model','model_losses','mse_test_losses_'+model_name), current_loss)
404 | np.save(os.path.join(cfg['project_path'],'model','model_losses','fut_losses_'+model_name), fut_losses)
405 |
406 | print("\n")
407 |
408 | if convergence < cfg['model_convergence']:
409 | print('Finished training...')
410 | print('Model seems to have not reached convergence. You may want to check your model \n'
411 | 'with vame.evaluate_model(). If your satisfied you can continue. \n'
412 | 'Use vame.pose_segmentation() to identify behavioral motifs! \n'
413 | 'OPTIONAL: You can re-run vame.train_model() to improve performance.')
414 |
--------------------------------------------------------------------------------
/vame/util/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 0.1 Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 | import sys
12 | sys.dont_write_bytecode = True
13 |
14 | from vame.util.auxiliary import *
15 |
--------------------------------------------------------------------------------
/vame/util/align_egocentrical.py:
--------------------------------------------------------------------------------
1 | """
2 | Variational Animal Motion Embedding 0.1 Toolbox
3 | © K. Luxem & J. Kürsch & P. Bauer, Department of Cellular Neuroscience
4 | Leibniz Institute for Neurobiology, Magdeburg, Germany
5 |
6 | https://github.com/LINCellularNeuroscience/VAME
7 | Licensed under GNU General Public License v3.0
8 | """
9 |
10 | import os
11 | import cv2 as cv
12 | import numpy as np
13 | import pandas as pd
14 | import tqdm
15 | import glob
16 |
17 | from pathlib import Path
18 | from vame.util.auxiliary import read_config
19 |
20 | #Returns cropped image using rect tuple
21 | def crop_and_flip(rect, src, points, ref_index):
22 | #Read out rect structures and convert
23 | center, size, theta = rect
24 | center, size = tuple(map(int, center)), tuple(map(int, size))
25 | #Get rotation matrix
26 | M = cv.getRotationMatrix2D(center, theta, 1)
27 |
28 | #shift DLC points
29 | x_diff = center[0] - size[0]//2
30 | y_diff = center[1] - size[1]//2
31 |
32 | dlc_points_shifted = []
33 |
34 | for i in points:
35 | point=cv.transform(np.array([[[i[0], i[1]]]]),M)[0][0]
36 |
37 | point[0] -= x_diff
38 | point[1] -= y_diff
39 |
40 | dlc_points_shifted.append(point)
41 |
42 | # Perform rotation on src image
43 | dst = cv.warpAffine(src.astype('float32'), M, src.shape[:2])
44 | out = cv.getRectSubPix(dst, size, center)
45 |
46 | #check if flipped correctly, otherwise flip again
47 | if dlc_points_shifted[ref_index[1]][0] >= dlc_points_shifted[ref_index[0]][0]:
48 | rect = ((size[0]//2,size[0]//2),size,180)
49 | center, size, theta = rect
50 | center, size = tuple(map(int, center)), tuple(map(int, size))
51 | #Get rotation matrix
52 | M = cv.getRotationMatrix2D(center, theta, 1)
53 |
54 |
55 | #shift DLC points
56 | x_diff = center[0] - size[0]//2
57 | y_diff = center[1] - size[1]//2
58 |
59 | points = dlc_points_shifted
60 | dlc_points_shifted = []
61 |
62 | for i in points:
63 | point=cv.transform(np.array([[[i[0], i[1]]]]),M)[0][0]
64 |
65 | point[0] -= x_diff
66 | point[1] -= y_diff
67 |
68 | dlc_points_shifted.append(point)
69 |
70 | # Perform rotation on src image
71 | dst = cv.warpAffine(out.astype('float32'), M, out.shape[:2])
72 | out = cv.getRectSubPix(dst, size, center)
73 |
74 | return out, dlc_points_shifted
75 |
76 |
77 | #Helper function to return indexes of nans
78 | def nan_helper(y):
79 | return np.isnan(y), lambda z: z.nonzero()[0]
80 |
81 |
82 | #Interpolates all nan values of given array
83 | def interpol(arr):
84 |
85 | y = np.transpose(arr)
86 |
87 | nans, x = nan_helper(y[0])
88 | y[0][nans]= np.interp(x(nans), x(~nans), y[0][~nans])
89 | nans, x = nan_helper(y[1])
90 | y[1][nans]= np.interp(x(nans), x(~nans), y[1][~nans])
91 |
92 | arr = np.transpose(y)
93 |
94 | return arr
95 |
96 | def background(path_to_file,filename,video_format='.mp4',num_frames=1000):
97 | """
98 | Compute background image from fixed camera
99 | """
100 | import scipy.ndimage
101 | capture = cv.VideoCapture(os.path.join(path_to_file,'videos',filename+video_format))
102 |
103 | if not capture.isOpened():
104 | raise Exception("Unable to open video file: {0}".format(os.path.join(path_to_file,'videos',filename+video_format)))
105 |
106 | frame_count = int(capture.get(cv.CAP_PROP_FRAME_COUNT))
107 | ret, frame = capture.read()
108 |
109 | height, width, _ = frame.shape
110 | frames = np.zeros((height,width,num_frames))
111 |
112 | for i in tqdm.tqdm(range(num_frames), disable=not True, desc='Compute background image for video %s' %filename):
113 | rand = np.random.choice(frame_count, replace=False)
114 | capture.set(1,rand)
115 | ret, frame = capture.read()
116 | gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
117 | frames[...,i] = gray
118 |
119 | print('Finishing up!')
120 | medFrame = np.median(frames,2)
121 | background = scipy.ndimage.median_filter(medFrame, (5,5))
122 |
123 | # np.save(path_to_file+'videos/'+'background/'+filename+'-background.npy',background)
124 |
125 | capture.release()
126 | return background
127 |
128 |
129 | def align_mouse(path_to_file,filename,video_format,crop_size, pose_list,
130 | pose_ref_index, confidence, pose_flip_ref,bg,frame_count,use_video=True):
131 |
132 | #returns: list of cropped images (if video is used) and list of cropped DLC points
133 | #
134 | #parameters:
135 | #path_to_file: directory
136 | #filename: name of video file without format
137 | #video_format: format of video file
138 | #crop_size: tuple of x and y crop size
139 | #dlc_list: list of arrays containg corresponding x and y DLC values
140 | #dlc_ref_index: indices of 2 lists in dlc_list to align mouse along
141 | #dlc_flip_ref: indices of 2 lists in dlc_list to flip mouse if flip was false
142 | #bg: background image to subtract
143 | #frame_count: number of frames to align
144 | #use_video: boolean if video should be cropped or DLC points only
145 |
146 | images = []
147 | points = []
148 |
149 | for i in pose_list:
150 | for j in i:
151 | if j[2] <= confidence:
152 | j[0],j[1] = np.nan, np.nan
153 |
154 |
155 | for i in pose_list:
156 | i = interpol(i)
157 |
158 | if use_video:
159 | capture = cv.VideoCapture(os.path.join(path_to_file,'videos',filename+video_format))
160 |
161 | if not capture.isOpened():
162 | raise Exception("Unable to open video file: {0}".format(os.path.join(path_to_file,'videos',filename+video_format)))
163 |
164 | for idx in tqdm.tqdm(range(frame_count), disable=not True, desc='Align frames'):
165 |
166 | if use_video:
167 | #Read frame
168 | try:
169 | ret, frame = capture.read()
170 | frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
171 | frame = frame - bg
172 | frame[frame <= 0] = 0
173 | except:
174 | print("Couldn't find a frame in capture.read(). #Frame: %d" %idx)
175 | continue
176 | else:
177 | frame=np.zeros((1,1))
178 |
179 | #Read coordinates and add border
180 | pose_list_bordered = []
181 |
182 | for i in pose_list:
183 | pose_list_bordered.append((int(i[idx][0]+crop_size[0]),int(i[idx][1]+crop_size[1])))
184 |
185 | img = cv.copyMakeBorder(frame, crop_size[1], crop_size[1], crop_size[0], crop_size[0], cv.BORDER_CONSTANT, 0)
186 |
187 | punkte = []
188 | for i in pose_ref_index:
189 | coord = []
190 | coord.append(pose_list_bordered[i][0])
191 | coord.append(pose_list_bordered[i][1])
192 | punkte.append(coord)
193 | punkte = [punkte]
194 | punkte = np.asarray(punkte)
195 |
196 | #calculate minimal rectangle around snout and tail
197 | rect = cv.minAreaRect(punkte)
198 |
199 | #change size in rect tuple structure to be equal to crop_size
200 | lst = list(rect)
201 | lst[1] = crop_size
202 | rect = tuple(lst)
203 |
204 | center, size, theta = rect
205 |
206 | #crop image
207 | out, shifted_points = crop_and_flip(rect, img,pose_list_bordered,pose_flip_ref)
208 |
209 | if use_video: #for memory optimization, just save images when video is used.
210 | images.append(out)
211 | points.append(shifted_points)
212 |
213 | if use_video:
214 | capture.release()
215 |
216 | time_series = np.zeros((len(pose_list)*2,frame_count))
217 | for i in range(frame_count):
218 | idx = 0
219 | for j in range(len(pose_list)):
220 | time_series[idx:idx+2,i] = points[i][j]
221 | idx += 2
222 |
223 | return images, points, time_series
224 |
225 |
226 | #play aligned video
227 | def play_aligned_video(a, n, frame_count):
228 | colors = [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(255,0,255),(0,255,255),(0,0,0),(255,255,255)]
229 |
230 | for i in range(frame_count):
231 | # Capture frame-by-frame
232 | ret, frame = True,a[i]
233 | if ret == True:
234 |
235 | # Display the resulting frame
236 | frame = cv.cvtColor(frame.astype('uint8')*255, cv.COLOR_GRAY2BGR)
237 | im_color = cv.applyColorMap(frame, cv.COLORMAP_JET)
238 |
239 | for c,j in enumerate(n[i]):
240 | cv.circle(im_color,(j[0], j[1]), 5, colors[c], -1)
241 |
242 | cv.imshow('Frame',im_color)
243 |
244 | # Press Q on keyboard to exit
245 | if cv.waitKey(25) & 0xFF == ord('q'):
246 | break
247 |
248 | # Break the loop
249 | else:
250 | break
251 | cv.destroyAllWindows()
252 |
253 |
254 | def alignment(path_to_file, filename, pose_ref_index, video_format, crop_size, confidence, use_video=False, check_video=False):
255 |
256 | #read out data
257 | dataFile = glob.glob(os.path.join(path_to_file,'videos','pose_estimation',filename+'*'))
258 | if len(dataFile)>1:
259 | raise AssertionError("Multiple data files match video {}".format(filename))
260 | else:
261 | dataFile=dataFile[0]
262 | if dataFile.endswith('.csv'):
263 | data = pd.read_csv(dataFile, skiprows = 2, index_col=0)
264 | elif dataFile.endswith('.h5'):
265 | data = pd.read_hdf(dataFile)
266 | data_mat = pd.DataFrame.to_numpy(data)
267 | # data_mat = data_mat[:,1:]
268 |
269 | # get the coordinates for alignment from data table
270 | pose_list = []
271 |
272 | for i in range(int(data_mat.shape[1]/3)):
273 | pose_list.append(data_mat[:,i*3:(i+1)*3])
274 |
275 | #list of reference coordinate indices for alignment
276 | #0: snout, 1: forehand_left, 2: forehand_right,
277 | #3: hindleft, 4: hindright, 5: tail
278 |
279 | pose_ref_index = pose_ref_index
280 |
281 | #list of 2 reference coordinate indices for avoiding flipping
282 | pose_flip_ref = pose_ref_index
283 |
284 | if use_video:
285 | #compute background
286 | bg = background(path_to_file,filename,video_format)
287 | capture = cv.VideoCapture(os.path.join(path_to_file,'videos',filename+video_format))
288 | if not capture.isOpened():
289 | raise Exception("Unable to open video file: {0}".format(os.path.join(path_to_file,'videos',filename+video_format)))
290 |
291 | frame_count = int(capture.get(cv.CAP_PROP_FRAME_COUNT))
292 | capture.release()
293 | else:
294 | bg = 0
295 | frame_count = len(data) # Change this to an abitrary number if you first want to test the code
296 |
297 |
298 | frames, n, time_series = align_mouse(path_to_file, filename, video_format, crop_size, pose_list, pose_ref_index,
299 | confidence, pose_flip_ref, bg, frame_count, use_video)
300 |
301 | if check_video:
302 | play_aligned_video(frames, n, frame_count)
303 |
304 | return time_series, frames
305 |
306 |
307 | def egocentric_alignment(config, pose_ref_index=[0,5], crop_size=(300,300), use_video=False, video_format='.mp4', check_video=False):
308 | """ Happy aligning """
309 | #config parameters
310 | config_file = Path(config).resolve()
311 | cfg = read_config(config_file)
312 |
313 | path_to_file = cfg['project_path']
314 | filename = cfg['video_sets']
315 | confidence = cfg['pose_confidence']
316 | video_format=video_format
317 | crop_size=crop_size
318 |
319 | if cfg['egocentric_data'] == True:
320 | raise ValueError("The config.yaml indicates that the data is not egocentric. Please check the parameter egocentric_data")
321 |
322 | # call function and save into your VAME data folder
323 | for file in filename:
324 | print("Aligning data %s, Pose confidence value: %.2f" %(file, confidence))
325 | egocentric_time_series, frames = alignment(path_to_file, file, pose_ref_index, video_format, crop_size,
326 | confidence, use_video=use_video, check_video=check_video)
327 | np.save(os.path.join(path_to_file,'data',file,file+'-PE-seq.npy'), egocentric_time_series)
328 | # np.save(os.path.join(path_to_file,'data/',file,"",file+'-PE-seq.npy', egocentric_time_series))
329 |
330 | print("Your data is now ine right format and you can call vame.create_trainset()")
331 |
332 |
--------------------------------------------------------------------------------
/vame/util/auxiliary.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 |
11 | The following code is adapted from:
12 |
13 | DeepLabCut2.0 Toolbox (deeplabcut.org)
14 | © A. & M. Mathis Labs
15 | https://github.com/AlexEMG/DeepLabCut
16 | Please see AUTHORS for contributors.
17 | https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS
18 | Licensed under GNU Lesser General Public License v3.0
19 | """
20 |
21 | import os, yaml
22 | from pathlib import Path
23 | import ruamel.yaml
24 |
25 |
26 | def create_config_template():
27 | """
28 | Creates a template for config.yaml file. This specific order is preserved while saving as yaml file.
29 | """
30 | import ruamel.yaml
31 | yaml_str = """\
32 | # Project configurations
33 | Project:
34 | model_name:
35 | n_cluster:
36 | pose_confidence:
37 | \n
38 | # Project path and videos
39 | project_path:
40 | video_sets:
41 | \n
42 | # Data
43 | all_data:
44 | \n
45 | # Creation of train set:
46 | egocentric_data:
47 | robust:
48 | iqr_factor:
49 | axis:
50 | savgol_filter:
51 | savgol_length:
52 | savgol_order:
53 | test_fraction:
54 | \n
55 | # RNN model general hyperparameter:
56 | pretrained_model:
57 | pretrained_weights:
58 | num_features:
59 | batch_size:
60 | max_epochs:
61 | model_snapshot:
62 | model_convergence:
63 | transition_function:
64 | beta:
65 | beta_norm:
66 | zdims:
67 | learning_rate:
68 | time_window:
69 | prediction_decoder:
70 | prediction_steps:
71 | noise:
72 | scheduler:
73 | scheduler_step_size:
74 | scheduler_gamma:
75 | #Note the optimal scheduler threshold below can vary greatly (from .1-.0001) between experiments.
76 | #You are encouraged to read the torch.optim.ReduceLROnPlateau docs to understand the threshold to use.
77 | scheduler_threshold:
78 | softplus:
79 | \n
80 | # Segmentation:
81 | parameterization:
82 | hmm_trained: False
83 | load_data:
84 | individual_parameterization:
85 | random_state_kmeans:
86 | n_init_kmeans:
87 | \n
88 | # Video writer:
89 | length_of_motif_video:
90 | \n
91 | # UMAP parameter:
92 | min_dist:
93 | n_neighbors:
94 | random_state:
95 | num_points:
96 | \n
97 | # ONLY CHANGE ANYTHING BELOW IF YOU ARE FAMILIAR WITH RNN MODELS
98 | # RNN encoder hyperparamter:
99 | hidden_size_layer_1:
100 | hidden_size_layer_2:
101 | dropout_encoder:
102 | \n
103 | # RNN reconstruction hyperparameter:
104 | hidden_size_rec:
105 | dropout_rec:
106 | n_layers:
107 | \n
108 | # RNN prediction hyperparamter:
109 | hidden_size_pred:
110 | dropout_pred:
111 | \n
112 | # RNN loss hyperparameter:
113 | mse_reconstruction_reduction:
114 | mse_prediction_reduction:
115 | kmeans_loss:
116 | kmeans_lambda:
117 | anneal_function:
118 | kl_start:
119 | annealtime:
120 | \n
121 | # Legacy mode
122 | legacy:
123 | """
124 | ruamelFile = ruamel.yaml.YAML()
125 | cfg_file = ruamelFile.load(yaml_str)
126 | return(cfg_file,ruamelFile)
127 |
128 |
129 | def read_config(configname):
130 | """
131 | Reads structured config file defining a project.
132 | """
133 | ruamelFile = ruamel.yaml.YAML()
134 | path = Path(configname)
135 | if os.path.exists(path):
136 | try:
137 | with open(path, "r") as f:
138 | cfg = ruamelFile.load(f)
139 | curr_dir = os.path.dirname(configname)
140 | if cfg["project_path"] != curr_dir:
141 | cfg["project_path"] = curr_dir
142 | write_config(configname, cfg)
143 | except Exception as err:
144 | if len(err.args) > 2:
145 | if (
146 | err.args[2]
147 | == "could not determine a constructor for the tag '!!python/tuple'"
148 | ):
149 | with open(path, "r") as ymlfile:
150 | cfg = yaml.load(ymlfile, Loader=yaml.SafeLoader)
151 | write_config(configname, cfg)
152 | else:
153 | raise
154 |
155 | else:
156 | raise FileNotFoundError(
157 | "Config file is not found. Please make sure that the file exists and/or that you passed the path of the config file correctly!"
158 | )
159 | return cfg
160 |
161 | def write_config(configname,cfg):
162 | """
163 | Write structured config file.
164 | """
165 | with open(configname, 'w') as cf:
166 | ruamelFile = ruamel.yaml.YAML()
167 | cfg_file,ruamelFile = create_config_template()
168 | for key in cfg.keys():
169 | cfg_file[key]=cfg[key]
170 |
171 | ruamelFile.dump(cfg_file, cf)
172 |
173 | def update_config(config):
174 | config_file = Path(config).resolve()
175 | cfg = read_config(config_file)
176 |
177 | project = cfg['Project']
178 | project_path = cfg['project_path']
179 | video_names = []
180 | for file in cfg['video_sets']:
181 | video_names.append(file)
182 |
183 | flag = input("ATTENTION! You are about to overwrite your current config.yaml. If you did changes, "
184 | "back up your current version and compare to the updated version. Do you want to continue? (yes/no)")
185 |
186 | if flag == 'yes':
187 | cfg_file,ruamelFile = create_config_template()
188 |
189 | cfg_file['Project']=str(project)
190 | cfg_file['project_path']=str(project_path)+'/'
191 | cfg_file['test_fraction']=.1
192 | cfg_file['video_sets']=video_names
193 | cfg_file['all_data']='yes'
194 | cfg_file['load_data']='-PE-seq-clean'
195 | cfg_file['anneal_function']='linear'
196 | cfg_file['batch_size']=256
197 | cfg_file['max_epochs']=500
198 | cfg_file['transition_function']='GRU'
199 | cfg_file['beta']=1
200 | cfg_file['zdims']=30
201 | cfg_file['learning_rate']=5e-4
202 | cfg_file['time_window']=30
203 | cfg_file['prediction_decoder']=1
204 | cfg_file['prediction_steps']=15
205 | cfg_file['model_convergence']=50
206 | cfg_file['model_snapshot']=50
207 | cfg_file['num_features']=12
208 | cfg_file['savgol_filter']=True
209 | cfg_file['savgol_length']=5
210 | cfg_file['savgol_order']=2
211 | cfg_file['hidden_size_layer_1']=256
212 | cfg_file['hidden_size_layer_2']=256
213 | cfg_file['dropout_encoder']=0
214 | cfg_file['hidden_size_rec']=256
215 | cfg_file['dropout_rec']=0
216 | cfg_file['hidden_size_pred']=256
217 | cfg_file['dropout_pred']=0
218 | cfg_file['kl_start']=2
219 | cfg_file['annealtime']=4
220 | cfg_file['mse_reconstruction_reduction']='sum'
221 | cfg_file['mse_prediction_reduction']='sum'
222 | cfg_file['kmeans_loss']=cfg_file['zdims']
223 | cfg_file['kmeans_lambda']=0.1
224 | cfg_file['scheduler']=1
225 | cfg_file['length_of_motif_video'] = 1000
226 | cfg_file['noise'] = False
227 | cfg_file['scheduler_step_size'] = 100
228 | cfg_file['legacy'] = False
229 | cfg_file['individual_parameterization'] = False
230 | cfg_file['random_state_kmeans'] = 42
231 | cfg_file['n_init_kmeans'] = 15
232 | cfg_file['model_name']='VAME'
233 | cfg_file['n_cluster'] = 15
234 | cfg_file['pretrained_weights'] = False
235 | cfg_file['pretrained_model']='None'
236 | cfg_file['min_dist'] = 0.1
237 | cfg_file['n_neighbors'] = 200
238 | cfg_file['random_state'] = 42
239 | cfg_file['num_points'] = 30000
240 | cfg_file['scheduler_gamma'] = 0.2
241 | cfg_file['scheduler_threshold'] = .1
242 | cfg_file['softplus'] = False
243 | cfg_file['pose_confidence'] = 0.99
244 | cfg_file['iqr_factor'] = 4
245 | cfg_file['robust'] = True
246 | cfg_file['beta_norm'] = False
247 | cfg_file['n_layers'] = 1
248 | cfg_file['axis'] = 'None'
249 | cfg_file['egocentric_data'] = True
250 | cfg_file['parameterization'] = 'kmeans'
251 |
252 | projconfigfile=os.path.join(str(project_path),'config.yaml')
253 | # Write dictionary to yaml config file
254 | write_config(projconfigfile,cfg_file)
255 |
256 | print("Your config.yaml has been updated.")
257 | else:
258 | print("No changes have been applied.")
259 |
--------------------------------------------------------------------------------
/vame/util/csv_to_npy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import numpy as np
14 | import pandas as pd
15 |
16 | from pathlib import Path
17 | from vame.util.auxiliary import read_config
18 |
19 |
20 | #Helper function to return indexes of nans
21 | def nan_helper(y):
22 | return np.isnan(y), lambda z: z.nonzero()[0]
23 |
24 | #Interpolates all nan values of given array
25 | def interpol(arr):
26 |
27 | y = np.transpose(arr)
28 |
29 | nans, x = nan_helper(y[0])
30 | y[0][nans]= np.interp(x(nans), x(~nans), y[0][~nans])
31 | nans, x = nan_helper(y[1])
32 | y[1][nans]= np.interp(x(nans), x(~nans), y[1][~nans])
33 |
34 | arr = np.transpose(y)
35 |
36 | return arr
37 |
38 | def csv_to_numpy(config):
39 | """
40 | This is a function to convert your pose-estimation.csv file to a numpy array.
41 |
42 | Note that this code is only useful for data which is a priori egocentric, i.e. head-fixed
43 | or otherwise restrained animals.
44 |
45 | example use:
46 | vame.csv_to_npy('pathto/your/config/yaml', 'path/toYourFolderwithCSV/')
47 | """
48 | config_file = Path(config).resolve()
49 | cfg = read_config(config_file)
50 |
51 | path_to_file = cfg['project_path']
52 | filename = cfg['video_sets']
53 | confidence = cfg['pose_confidence']
54 | if cfg['egocentric_data'] == False:
55 | raise ValueError("The config.yaml indicates that the data is not egocentric. Please check the parameter egocentric_data")
56 |
57 | for file in filename:
58 | print(file)
59 | # Read in your .csv file, skip the first two rows and create a numpy array
60 | data = pd.read_csv(os.path.join(path_to_file,"videos","pose_estimation",file+'.csv'), skiprows = 3, header=None)
61 | data_mat = pd.DataFrame.to_numpy(data)
62 | data_mat = data_mat[:,1:]
63 |
64 | pose_list = []
65 |
66 | # get the number of bodyparts, their x,y-position and the confidence from DeepLabCut
67 | for i in range(int(data_mat.shape[1]/3)):
68 | pose_list.append(data_mat[:,i*3:(i+1)*3])
69 |
70 | # find low confidence and set them to NaN
71 | for i in pose_list:
72 | for j in i:
73 | if j[2] <= confidence:
74 | j[0],j[1] = np.nan, np.nan
75 |
76 | # interpolate NaNs
77 | for i in pose_list:
78 | i = interpol(i)
79 |
80 | positions = np.concatenate(pose_list, axis=1)
81 | final_positions = np.zeros((data_mat.shape[0], int(data_mat.shape[1]/3)*2))
82 |
83 | jdx = 0
84 | idx = 0
85 | for i in range(int(data_mat.shape[1]/3)):
86 | final_positions[:,idx:idx+2] = positions[:,jdx:jdx+2]
87 | jdx += 3
88 | idx += 2
89 |
90 | # save the final_positions array with np.save()
91 | np.save(os.path.join(path_to_file,'data',file,file+"-PE-seq.npy"), final_positions.T)
92 | print("conversion from DeepLabCut csv to numpy complete...")
93 |
94 | print("Your data is now in right format and you can call vame.create_trainset()")
95 |
--------------------------------------------------------------------------------
/vame/util/gif_pose_helper.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Variational Animal Motion Embedding 1.0-alpha Toolbox
5 | © K. Luxem & P. Bauer, Department of Cellular Neuroscience
6 | Leibniz Institute for Neurobiology, Magdeburg, Germany
7 |
8 | https://github.com/LINCellularNeuroscience/VAME
9 | Licensed under GNU General Public License v3.0
10 | """
11 |
12 | import os
13 | import h5py
14 | import tqdm
15 | import scipy
16 | import cv2 as cv
17 | import numpy as np
18 | import pandas as pd
19 | import matplotlib.pyplot as plt
20 |
21 |
22 | #Returns cropped image using rect tuple
23 | def crop_and_flip(rect, src, points, ref_index):
24 | #Read out rect structures and convert
25 | center, size, theta = rect
26 | center, size = tuple(map(int, center)), tuple(map(int, size))
27 | #Get rotation matrix
28 | M = cv.getRotationMatrix2D(center, theta, 1)
29 |
30 | #shift DLC points
31 | x_diff = center[0] - size[0]//2
32 | y_diff = center[1] - size[1]//2
33 |
34 | dlc_points_shifted = []
35 |
36 | for i in points:
37 | point=cv.transform(np.array([[[i[0], i[1]]]]),M)[0][0]
38 |
39 | point[0] -= x_diff
40 | point[1] -= y_diff
41 |
42 | dlc_points_shifted.append(point)
43 |
44 | # Perform rotation on src image
45 | dst = cv.warpAffine(src.astype('float32'), M, src.shape[:2])
46 | out = cv.getRectSubPix(dst, size, center)
47 |
48 | #check if flipped correctly, otherwise flip again
49 | if dlc_points_shifted[ref_index[1]][0] >= dlc_points_shifted[ref_index[0]][0]:
50 | rect = ((size[0]//2,size[0]//2),size,180)
51 | center, size, theta = rect
52 | center, size = tuple(map(int, center)), tuple(map(int, size))
53 | #Get rotation matrix
54 | M = cv.getRotationMatrix2D(center, theta, 1)
55 |
56 |
57 | #shift DLC points
58 | x_diff = center[0] - size[0]//2
59 | y_diff = center[1] - size[1]//2
60 |
61 | points = dlc_points_shifted
62 | dlc_points_shifted = []
63 |
64 | for i in points:
65 | point=cv.transform(np.array([[[i[0], i[1]]]]),M)[0][0]
66 |
67 | point[0] -= x_diff
68 | point[1] -= y_diff
69 |
70 | dlc_points_shifted.append(point)
71 |
72 | # Perform rotation on src image
73 | dst = cv.warpAffine(out.astype('float32'), M, out.shape[:2])
74 | out = cv.getRectSubPix(dst, size, center)
75 |
76 | return out, dlc_points_shifted
77 |
78 |
79 | def background(path_to_file,filename,file_format='.mp4',num_frames=1000):
80 | """
81 | Compute background image from fixed camera
82 | """
83 |
84 | capture = cv.VideoCapture(os.path.join(path_to_file,"videos",filename+file_format))
85 |
86 | if not capture.isOpened():
87 | raise Exception("Unable to open video file: {0}".format(os.path.join(path_to_file,"videos",filename+file_format)))
88 |
89 | frame_count = int(capture.get(cv.CAP_PROP_FRAME_COUNT))
90 | ret, frame = capture.read()
91 |
92 | height, width, _ = frame.shape
93 | frames = np.zeros((height,width,num_frames))
94 |
95 | for i in tqdm.tqdm(range(num_frames), disable=not True, desc='Compute background image for video %s' %filename):
96 | rand = np.random.choice(frame_count, replace=False)
97 | capture.set(1,rand)
98 | ret, frame = capture.read()
99 | gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
100 | frames[...,i] = gray
101 |
102 | print('Finishing up!')
103 | medFrame = np.median(frames,2)
104 | background = scipy.ndimage.median_filter(medFrame, (5,5))
105 |
106 | np.save(os.path.join(path_to_file,"videos",filename+'-background.npy'),background)
107 |
108 | capture.release()
109 | return background
110 |
111 |
112 | def get_rotation_matrix(adjacent, opposite, crop_size=(300, 300)):
113 |
114 | tan_alpha = np.abs(opposite) / np.abs(adjacent)
115 | alpha = np.arctan(tan_alpha)
116 | alpha = np.rad2deg(alpha)
117 |
118 | if adjacent < 0 and opposite > 0:
119 | alpha = 180-alpha
120 |
121 | if adjacent < 0 and opposite < 0:
122 | alpha = -(180-alpha)
123 |
124 | if adjacent > 0 and opposite < 0:
125 | alpha = -alpha
126 |
127 | rot_mat = cv.getRotationMatrix2D((crop_size[0] // 2, crop_size[1] // 2),alpha, 1)
128 |
129 | return rot_mat
130 |
131 |
132 | #Helper function to return indexes of nans
133 | def nan_helper(y):
134 | return np.isnan(y), lambda z: z.nonzero()[0]
135 |
136 |
137 | #Interpolates all nan values of given array
138 | def interpol(arr):
139 |
140 | y = np.transpose(arr)
141 |
142 | nans, x = nan_helper(y[0])
143 | y[0][nans]= np.interp(x(nans), x(~nans), y[0][~nans])
144 | nans, x = nan_helper(y[1])
145 | y[1][nans]= np.interp(x(nans), x(~nans), y[1][~nans])
146 |
147 | arr = np.transpose(y)
148 |
149 | return arr
150 |
151 |
152 | def get_animal_frames(cfg, filename, pose_ref_index, start, length, subtract_background, file_format='.mp4', crop_size=(300, 300)):
153 | path_to_file = cfg['project_path']
154 | time_window = cfg['time_window']
155 | lag = int(time_window / 2)
156 | #read out data
157 | data = pd.read_csv(os.path.join(path_to_file,"videos","pose_estimation",filename+'.csv'), skiprows = 2)
158 | data_mat = pd.DataFrame.to_numpy(data)
159 | data_mat = data_mat[:,1:]
160 |
161 | # get the coordinates for alignment from data table
162 | pose_list = []
163 |
164 | for i in range(int(data_mat.shape[1]/3)):
165 | pose_list.append(data_mat[:,i*3:(i+1)*3])
166 |
167 | #list of reference coordinate indices for alignment
168 | #0: snout, 1: forehand_left, 2: forehand_right,
169 | #3: hindleft, 4: hindright, 5: tail
170 |
171 | pose_ref_index = pose_ref_index
172 |
173 | #list of 2 reference coordinate indices for avoiding flipping
174 | pose_flip_ref = pose_ref_index
175 |
176 | # compute background
177 | if subtract_background == True:
178 | try:
179 | print("Loading background image ...")
180 | bg = np.load(os.path.join(path_to_file,"videos",filename+'-background.npy'))
181 | except:
182 | print("Can't find background image... Calculate background image...")
183 | bg = background(path_to_file,filename, file_format)
184 |
185 | images = []
186 | points = []
187 |
188 | for i in pose_list:
189 | for j in i:
190 | if j[2] <= 0.8:
191 | j[0],j[1] = np.nan, np.nan
192 |
193 |
194 | for i in pose_list:
195 | i = interpol(i)
196 |
197 | capture = cv.VideoCapture(os.path.join(path_to_file,"videos",filename+file_format))
198 | if not capture.isOpened():
199 | raise Exception("Unable to open video file: {0}".format(os.path.join(path_to_file,"videos",filename++file_format)))
200 |
201 | for idx in tqdm.tqdm(range(length), disable=not True, desc='Align frames'):
202 | try:
203 | capture.set(1,idx+start+lag)
204 | ret, frame = capture.read()
205 | frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
206 | if subtract_background == True:
207 | frame = frame - bg
208 | frame[frame <= 0] = 0
209 | except:
210 | print("Couldn't find a frame in capture.read(). #Frame: %d" %idx+start+lag)
211 | continue
212 |
213 | #Read coordinates and add border
214 | pose_list_bordered = []
215 |
216 | for i in pose_list:
217 | pose_list_bordered.append((int(i[idx+start+lag][0]+crop_size[0]),int(i[idx+start+lag][1]+crop_size[1])))
218 |
219 | img = cv.copyMakeBorder(frame, crop_size[1], crop_size[1], crop_size[0], crop_size[0], cv.BORDER_CONSTANT, 0)
220 |
221 | punkte = []
222 | for i in pose_ref_index:
223 | coord = []
224 | coord.append(pose_list_bordered[i][0])
225 | coord.append(pose_list_bordered[i][1])
226 | punkte.append(coord)
227 | punkte = [punkte]
228 | punkte = np.asarray(punkte)
229 |
230 | #calculate minimal rectangle around snout and tail
231 | rect = cv.minAreaRect(punkte)
232 |
233 | #change size in rect tuple structure to be equal to crop_size
234 | lst = list(rect)
235 | lst[1] = crop_size
236 | rect = tuple(lst)
237 |
238 | center, size, theta = rect
239 |
240 | #crop image
241 | out, shifted_points = crop_and_flip(rect, img,pose_list_bordered,pose_flip_ref)
242 |
243 | images.append(out)
244 | points.append(shifted_points)
245 |
246 | capture.release()
247 | return images
248 |
--------------------------------------------------------------------------------