pax_global_header00006660000000000000000000000064117343253420014516gustar00rootroot0000000000000052 comment=18bf74416e47686a6417bab80c38e147e4988982 python-neuroshare-0.8.5/000077500000000000000000000000001173432534200152225ustar00rootroot00000000000000python-neuroshare-0.8.5/.gitignore000066400000000000000000000000771173432534200172160ustar00rootroot00000000000000*~ *.lock *.DS_Store *.swp *.out *.pyc *.so build/ *.egg-infopython-neuroshare-0.8.5/COPYING000066400000000000000000000636201173432534200162640ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it!python-neuroshare-0.8.5/README000066400000000000000000000051511173432534200161040ustar00rootroot00000000000000Python Bindings for Neuroshare ============================== The Neuroshare API is a standardized interface to access electrophysiology data stored in various different file formats. To do so, it uses format- specific shared libraries. Refer to the official website http://neuroshare.org for more information. The aim of this library is to provide a high level interface to the Neuroshare API, i.e. it focuses on API usability more then being a mere python version of the C API. Thus none of the original Neuroshare API calls are directly exposed but the interface is through python objects that resemble (more or less) the Neuroshare Entities. Installation ------------ The compile-time requirements for python-neuroshare are the 'setuptools' and the Python development files and a working C compiler (clang or gcc) and NumPy. For Debian based distributions, e.g. Ubuntu, this can easily be done with: $ sudo apt-get install clang python-setuptools \ python-dev python-numpy After that, python-neuroshare is installed with the following command: $ sudo python setup.py install Additional runtime dependencies: * The Neuroshare vendor DLLs for the specific data file(s)! Please refer to the following section for more information. Installation of vendor DLLs - - - - - - - - - - - - - - Python-neuroshare relies on the vendor specific DLLs to access data failes. Therefore the specific DLLs for each type of file must be downloaded and installed into one of the following locations: /usr/local/lib/neuroshare /usr/lib/neuroshare ~/.neuroshare A (possibly incomplete) list of the vendor specific DLLs can be obtained be obtained from the neuroshare website: http://neuroshare.sourceforge.net/DLLLinks.shtml Please note that you need the corresponding DLLs for your platform (e.g. Linux, 64-bit). If you find yourself in the situation that there is no DLL for your specific platform and you are either on a UNIX-like system you can use G-Node's very one nswineproxy component to use the Windows 32 bit DLLs. Please refer to the nswineproxy homepage for more information: https://github.com/G-Node/nswineproxy Usage ----- Opening a file: >> import neuroshare as ns >> fd = ns.File ("NeuroshareExample.mcd") Iterate over the entities in the file: >> for entity in fd.list_entities(): >> print entity.label, entity.entity_type >> ... do something else with entity ... Reporting Bugs & Submitting Patches ----------------------------------- Any bugs can and should be filed to the project's issue tracker at github: https://github.com/G-Node/python-neuroshare/issues python-neuroshare-0.8.5/capi/000077500000000000000000000000001173432534200161365ustar00rootroot00000000000000python-neuroshare-0.8.5/capi/nsAPIdllimp.h000066400000000000000000000520321173432534200204650ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2003 Neuroshare Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // A copy of the GNU Lesser General Public License can be obtained by writing to: // Free Software Foundation, Inc., // 59 Temple Place, Suite 330, // Boston, MA 02111-1307 // USA // // Contact information: // Angela Wang // CyberKinetics, Inc., // 391 G Chipeta Way // Salt Lake City, UT 84108 // USA // angela@bionictech.com // // Website: // www.neuroshare.org // // All other copyrights on this material are replaced by this license agreeement. // /////////////////////////////////////////////////////////////////////////////////////////////////// /* $Workfile: nsAPIdllimp.h $ */ // // File version : 1.0 // // Specification : based on Neuroshare API specification version 1.0 // // Description : This header file contains Neuroshare API function prototype delarations in // pointer form for importing Neuroshare function definitions from a DLL. // The file nsAPIdllimp.c contains C code to declare and load the functions. // // Authors : Shane Guillory, Angela Wang // /* $Date: 2/21/03 12:42p $ */ // /* $History: nsAPIdllimp.h $ // // ***************** Version 9 ***************** // User: Almut Date: 2/21/03 Time: 12:42p // Updated in $/Neuroshare/DLLTester // These headers now conform to Neuroshare API Spec 1.0 // // ***************** Version 1 ***************** // User: Angela Date: 2/21/03 Time: 11:45a // Created in $/Neuroshare/nsNEVLibrary // Version 1.0 Neuroshare Specifications // // ***************** Version 1 ***************** // User: Angela Date: 2/17/03 Time: 11:22a // Created in $/Neuroshare/nsNEVLibrary // Neuroshare API Ver 1.0 compliant header files // // ***************** Version 1 ***************** // User: Angela Date: 2/13/03 Time: 9:29a // Created in $/Neuroshare/nsNEVLibrary * * ***************** Version 8 ***************** * User: Angela Date: 1/14/03 Time: 9:44a * Updated in $/Neuroshare/nsNEVLibrary * * ***************** Version 7 ***************** * User: Angela Date: 1/10/03 Time: 12:15p * Updated in $/Neuroshare/nsNEVLibrary * Reword disclaimer * * ***************** Version 6 ***************** * User: Angela Date: 1/09/03 Time: 12:13p * Updated in $/Neuroshare/nsNEVLibrary * Changed some formatting of headers to look nicer * * ***************** Version 5 ***************** * User: Angela Date: 1/09/03 Time: 11:55a * Updated in $/Neuroshare/nsNEVLibrary * Added file headers, copyright, function headers v0.9b - Functions changed to use __stdcall calling convention for compatibility with Visual Basic. Function prototype declarations also changed to all-capital versions of the neuroshare function names. v0.9b - First public release.. */ /////////////////////////////////////////////////////////////////////////////////////////////////// // Standard include guards #ifndef NSAPIDLLIMP_H_INCLUDED #define NSAPIDLLIMP_H_INCLUDED #include "nsAPItypes.h" // Only need to specify "C" naming convention if using mixed C/C++ // It won't hurt if all C or all C++, so let's be safe #ifdef __cplusplus extern "C" { #endif #ifndef _WIN32 #define __stdcall #endif /////////////////////////////////////////////////////////////////////////////////////////////////// // // Definitions of function pointers // /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetLibraryInfo // // Purpose: // Retrieves information about the loaded API library // // Parameters: // ns_LIBRARYINFO *pLibraryInfo pointer to ns_LIBRARYINFO structure to receive information // uint32 dwLibraryInfoSize size in bytes of ns_LIBRARYINFO structure // // Return Values: // ns_OK ns_LIBIRARYINFO successfully retrieved // ns_LIBEERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETLIBRARYINFO) (ns_LIBRARYINFO *pLibraryInfo, uint32 dwLibraryInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_OpenFile // // Purpose: // Opens the data file and assigns a file handle for internal use by the library. // // Parameters: // char *pszFilename name of file to open // uint32 *hFile pointer to a file handle // // Return Values: // ns_OK ns_LIBIRARYINFO successfully retrieved // ns_TYPEERROR library unable to open file type // ns_FILEERROR file access or read error // ns_LIBEERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_OPENFILE) (const char *pszFilename, uint32 *hFile); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetFileInfo // // Purpose: // Retrieve general information about the data file // // Parameters: // uint32 hFile handle to NEV data file // ns_FILEINFO *pFileInfo pointer to ns_FILEINFO structure that receives data // uint32 dwFileInfoSize number of bytes returned in ns_FILEINFO // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_FILEERROR file access or read error // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETFILEINFO) (uint32 hFile, ns_FILEINFO *pFileInfo, uint32 dwFileInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_CloseFile // // Purpose: // Close the open data file // // Parameters: // uint32 hFile handle to NEV data file // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_CLOSEFILE) (uint32 hFile); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetEntityInfo // // Purpose: // Retrieve Entity information // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID entity ID // ns_ENTITYINFO *pEntityInfo pointer to ns_ENTITYINFO structure that receives information // uint32 dwEntityInfoSize number of bytes returned in ns_ENTITYINFO // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETENTITYINFO) (uint32 hFile, uint32 dwEntityID, ns_ENTITYINFO *pEntityInfo, uint32 dwEntityInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetEventInfo // // Purpose: // Retrieve information for Event entities. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Event entity ID // ns_EVENTINFO *pEventInfo pointer to ns_EVENTINFO structure to receive information // uint32 dwEventInfoSize number of bytes returned in ns_EVENTINFO // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalid entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETEVENTINFO) (uint32 hFile, uint32 dwEntityID, ns_EVENTINFO *pEventInfo, uint32 dwEventInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetEventData // // Purpose: // Retrieve the timestamp and Evevy entity data items. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Event entity ID // uint32 nIndex Event entity item number // double *pdTimeStamp pointer to double timestamp (in seconds) // void *pData pointer to data buffer to receive data // uint32 *pdwDataSize pointer to number of bytes of data retrieved into data buffer // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalie entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETEVENTDATA) (uint32 hFile, uint32 dwEntityID, uint32 nIndex, double *pdTimeStamp, void *pData, uint32 dwDataSize, uint32 *pdwDataRetSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetAnalogInfo // Purpose: // // Retrieve information for Analog entities // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Analog entity ID // ns_ANALOGINFO *pAnalogInfo pointer to ns_ANALOGINFO structure to receive data // uint32 dwAnalogInfoSize number of bytes returned in ns_ANALOGINFO // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalie entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETANALOGINFO) (uint32 hFile, uint32 dwEntityID, ns_ANALOGINFO *pAnalogInfo,uint32 dwAnalogInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetAnalogData // // Purpose: // Retrieve analog data in the buffer at pData. If possible, dwIndexCount, analog data values are // returned in the buffer. As there may be time gaps in the sequential values, the number of // continuously sampled data items is returned in pdwContCount. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Analog entity ID // uint32 dwStartIndex starting index to search for timestamp // uint32 dwIndexCount number of timestamps to retrieve // uint32 *pdwContCount pointer to count of the first non-sequential analog item // double *pData pointer of data buffer to receive data values // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalid entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETANALOGDATA) (uint32 hFile, uint32 dwEntityID, uint32 dwStartIndex, uint32 dwIndexCount, uint32 *pdwContCount, double *pData); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetSegmentInfo // // Purpose: // Retrieve information for Segment entities. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Segment entity ID // ns_SEGMENTINFO *pSegmentInfo pointer to ns_SEGMENTINFO structure to receive information // uint32 dwSegmentInfoSize size in bytes retrieved in ns_SEGMENTINFO structure // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY invalid or inappropriate entity identifier specified // ns_FILEERROR file access or read error // ns_LIBERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETSEGMENTINFO) (uint32 hFile, uint32 dwEntityID, ns_SEGMENTINFO *pSegmentInfo,uint32 dwSegmentInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetSegmentSourceInfo // // Purpose: // Retrieve information on the source, dwSourceID, generating segment entity dwEntityID. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Segment entity ID // uint32 dwSourceID entity ID of source /// ns_SEGSOURCEINFO *pSourceInfo pointer to ns_SEGSOURCEINFO structure to receive information // uint32 dwSourceInfoSize size in bytes retrieved in ns_SEGSOURCEINFO structure // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY invalid or inappropriate entity identifier specified // ns_FILEERROR file access or read error // ns_LIBERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETSEGMENTSOURCEINFO) (uint32 hFile, uint32 dwEntityID, uint32 dwSourceID, ns_SEGSOURCEINFO *pSourceInfo, uint32 dwSourceInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetSegmentData // // Purpose: // Retrieve segment data waveform and its timestamp. // The number of data points read is returned at pdwSampleCount. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Segment entity ID // int32 nIndex Segment item index to retrieve // double *pdTimeStamp pointer to timestamp to retrieve // double *pData pointer to data buffer to receive data // uint32 *pdwSampleCount pointer to number of data items retrieved // uint32 *pdwUnitID pointer to unit ID of Segment data // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY invalid or inappropriate entity identifier specified // ns_FILEERROR file access or read error // ns_LIBERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETSEGMENTDATA) (uint32 hFile, uint32 dwEntityID, int32 nIndex, double *pdTimeStamp, double *pdData, uint32 dwDataBufferSize, uint32 *pdwSampleCount, uint32 *pdwUnitID ); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetNeuralInfo // // Purpose: // Retrieve information on Neural Events. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Neural entity ID // ns_NEURALINFO *pNeuralInfo pointer to ns_NEURALINFO structure to receive information // uint32 dwNeuralInfoSize number of bytes returned in ns_NEURALINFO // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalid entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETNEURALINFO) (uint32 hFile, uint32 dwEntityID, ns_NEURALINFO *pNeuralInfo, uint32 dwNeuralInfoSize); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetNeuralData // // Purpose: // Retrieve requested number of Neural event timestamps (in sec) // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Neural event entity ID // uint32 dwStartIndex index of first Neural event item time to retrieve // uint32 dwIndexCount number of Neural event items to retrieve // double *pData pointer to buffer to receive times // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalie entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETNEURALDATA) (uint32 hFile, uint32 dwEntityID, uint32 dwStartIndex, uint32 dwIndexCount, double *pdData); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetIndexByTime // // Purpose: // // Given the time (sec), return the closest data item index, as specified by nFlag. // Finds the packet with the closest time to the requested time. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID entity ID to search for // uint32 dwSearchTimeStamp timestamp of item to search for // int32 nFlag position of item relative to the requested timestamp // uint32 *pdwIndex pointer to index of item to retrieve // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETINDEXBYTIME) (uint32 hFile, uint32 dwEntityID, double dTime, int32 nFlag, uint32 *pdwIndex); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetTimeByIndex // // Purpose: // // Given an index for an entity data item, return the time in seconds. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID entity ID to search for // uint32 dwIndex index of entity item to search for // double *pdTime time of entity to retrieve // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETTIMEBYINDEX) (uint32 hFile, uint32 dwEntityID, uint32 dwIndex, double *pdTime); /////////////////////////////////////////////////////////////////////////////////////////////////// // Define pointer to ns_GetLastErrorMsg // // Purpose: // Retrieve the most recent error text message // // Parameters: // char *pszMsgBuffer pointer to text buffer to receive error message // uint32 dwMsgBufferSize size in bytes of text buffer // // Return Values: // ns_OK function succeeded // ns_LIBERROR library error // // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef ns_RESULT (__stdcall *NS_GETLASTERRORMSG) (char *pszMsgBuffer, uint32 dwMsgBufferSize); ////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // The names of the function pointers are defined here to standardize its use // in the application. // // Function pointer variable names are defined in the host application. If these // names are to be defined differently, this section should be commented out. // #if 0 extern NS_GETLIBRARYINFO ns_GetLibraryInfo; extern NS_OPENFILE ns_OpenFile; extern NS_GETFILEINFO ns_GetFileInfo; extern NS_CLOSEFILE ns_CloseFile; extern NS_GETENTITYINFO ns_GetEntityInfo; extern NS_GETEVENTINFO ns_GetEventInfo; extern NS_GETEVENTDATA ns_GetEventData; extern NS_GETANALOGINFO ns_GetAnalogInfo; extern NS_GETANALOGDATA ns_GetAnalogData; extern NS_GETSEGMENTINFO ns_GetSegmentInfo; extern NS_GETSEGMENTSOURCEINFO ns_GetSegmentSourceInfo; extern NS_GETSEGMENTDATA ns_GetSegmentData; extern NS_GETNEURALINFO ns_GetNeuralInfo; extern NS_GETNEURALDATA ns_GetNeuralData; extern NS_GETINDEXBYTIME ns_GetIndexByTime; extern NS_GETTIMEBYINDEX ns_GetTimeByIndex; extern NS_GETLASTERRORMSG ns_GetLastErrorMsg; #endif #ifdef __cplusplus } #endif #endif // end of include guards python-neuroshare-0.8.5/capi/nsAPItypes.h000066400000000000000000000335231173432534200203540ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2003 Neuroshare Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // A copy of the GNU Lesser General Public License can be obtained by writing to: // Free Software Foundation, Inc., // 59 Temple Place, Suite 330, // Boston, MA 02111-1307 // USA // // Contact information: // Angela Wang // CyberKinetics, Inc., // 391 G Chipeta Way // Salt Lake City, UT 84108 // USA // angela@bionictech.com // // Website: // www.neuroshare.org // // All other copyrights on this material are replaced by this license agreeement. // /////////////////////////////////////////////////////////////////////////////////////////////////// /* $Workfile: nsAPItypes.h $ */ // // File version : 1.0 // // Specification : based on Neuroshare API specification version 1.0 // // Description : This header file contains C declarations for constants, types, // and structures defined in the Neuroshare API specification document // // Authors : Shane Guillory, Angela Wang // /* $Date: 2/21/03 12:42p $ */ // /* $History: nsAPItypes.h $ // // ***************** Version 6 ***************** // User: Almut Date: 2/21/03 Time: 12:42p // Updated in $/Neuroshare/DLLTester // These headers now conform to Neuroshare API Spec 1.0 // // ***************** Version 1 ***************** // User: Angela Date: 2/21/03 Time: 11:45a // Created in $/Neuroshare/nsNEVLibrary // Version 1.0 Neuroshare Specifications // // ***************** Version 1 ***************** // User: Angela Date: 2/17/03 Time: 11:22a // Created in $/Neuroshare/nsNEVLibrary // Neuroshare API Ver 1.0 compliant header files // // ***************** Version 1 ***************** // User: Angela Date: 2/13/03 Time: 9:29a // Created in $/Neuroshare/nsNEVLibrary * * ***************** Version 5 ***************** * User: Angela Date: 1/14/03 Time: 9:42a * Updated in $/Neuroshare/nsNEVLibrary * Fixed location of brackets in structures * * ***************** Version 4 ***************** * User: Angela Date: 1/10/03 Time: 12:13p * Updated in $/Neuroshare/nsNEVLibrary * Reword disclaimer * * ***************** Version 3 ***************** * User: Angela Date: 1/09/03 Time: 12:14p * Updated in $/Neuroshare/nsNEVLibrary * Add copyright, disclaimer and file header v0.9b - Functions changed to use __stdcall calling convention for compatibility with Visual Basic. Function prototype declarations also changed to all-capital versions of the neuroshare function names. v0.9b - First public release.. */ /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // // Additional Remarks // // - The members of the Neuroshare API structures are defined on 4-byte boundaries. Make sure to // compile all with 4-byte or smaller alignement // /////////////////////////////////////////////////////////////////////////////////////////////////// // Standard Include guards #ifndef NSAPITYPES_H_INCLUDED #define NSAPITYPES_H_INCLUDED #define ns_LIBVERSION 0100 // version 01.00 /////////////////////////////////////////////////////////////////////////////////////////////////// // // Fixed storage size definitions for declared variables // (includes conditional testing so that there is no clash with win32 headers) // /////////////////////////////////////////////////////////////////////////////////////////////////// #if defined(_MSC_VER) typedef signed __int8 int8; typedef unsigned __int8 uint8; typedef signed __int16 int16; typedef unsigned __int16 uint16; typedef signed __int32 int32; typedef unsigned __int32 uint32; #pragma pack(push) #pragma pack(4) // specify 4-byte structure alignment #else #include typedef int8_t int8; typedef uint8_t uint8; typedef int16_t int16; typedef uint16_t uint16; typedef int32_t int32; typedef uint32_t uint32; #endif /////////////////////////////////////////////////////////////////////////////////////////////////// // // Library Return Code Definitions // /////////////////////////////////////////////////////////////////////////////////////////////////// typedef int32 ns_RESULT; #define ns_OK 0 //Function Successful #define ns_LIBERROR -1 //Linked Library Error #define ns_TYPEERROR -2 //Library unable to open file type #define ns_FILEERROR -3 //File access or read Error #define ns_BADFILE -4 //Invalid file handle passed to function #define ns_BADENTITY -5 //Invalid or inappropriate entity identifier specified #define ns_BADSOURCE -6 //Invalid source identifier specified #define ns_BADINDEX -7 //Invalid entity index or index range specified /////////////////////////////////////////////////////////////////////////////////////////////////// // // Definitions of constants and flags // /////////////////////////////////////////////////////////////////////////////////////////////////// // Library description flags #define ns_LIBRARY_DEBUG 0x01 // includes debug info linkage #define ns_LIBRARY_MODIFIED 0x02 // file was patched or modified #define ns_LIBRARY_PRERELEASE 0x04 // pre-release or beta version #define ns_LIBRARY_SPECIALBUILD 0x08 // different from release version #define ns_LIBRARY_MULTITHREADED 0x10 // library is multithread safe //Definitions of Event Entity types #define ns_EVENT_TEXT 0 // null-terminated ascii text string #define ns_EVENT_CSV 1 // comma separated ascii text values #define ns_EVENT_BYTE 2 // 8-bit value #define ns_EVENT_WORD 3 // 16-bit value #define ns_EVENT_DWORD 4 // 32-bit value //Definitions of entity types in the structure ns_ENTITYINFO #define ns_ENTITY_UNKNOWN 0 // unknown entity type #define ns_ENTITY_EVENT 1 // Event entity #define ns_ENTITY_ANALOG 2 // Analog entity #define ns_ENTITY_SEGMENT 3 // Segment entity #define ns_ENTITY_NEURALEVENT 4 // Sorted Neural entity //Flags used for locating data entries #define ns_BEFORE -1 // less than or equal to specified time #define ns_CLOSEST 0 // closest time #define ns_AFTER +1 // greater than or equal to specified time /////////////////////////////////////////////////////////////////////////////////////////////////// // // DLL library version information functions // /////////////////////////////////////////////////////////////////////////////////////////////////// //File descriptor structure typedef struct { char szDescription[32]; // Text description of the file type or file family char szExtension[8]; // Extension used on PC, Linux, and Unix Platforms char szMacCodes[8]; // Application and Type Codes used on Mac Platforms char szMagicCode[16]; // Null-terminated code used at the file beginning } ns_FILEDESC; // Library information structure typedef struct { uint32 dwLibVersionMaj; // Major version number of library uint32 dwLibVersionMin; // Minor version number of library uint32 dwAPIVersionMaj; // Major version number of API uint32 dwAPIVersionMin; // Minor version number of API char szDescription[64]; // Text description of the library char szCreator[64]; // Name of library creator uint32 dwTime_Year; // Year of last modification date uint32 dwTime_Month; // Month (0-11; January = 0) of last modification date uint32 dwTime_Day; // Day of the month (1-31) of last modification date uint32 dwFlags; // Additional library flags uint32 dwMaxFiles; // Maximum number of files library can simultaneously open uint32 dwFileDescCount; // Number of valid description entries in the following array ns_FILEDESC FileDesc[16]; // Text descriptor of files that the DLL can interpret } ns_LIBRARYINFO; // File information structure (the time of file creation should be reported in GMT) typedef struct { char szFileType[32]; // Manufacturer's file type descriptor uint32 dwEntityCount; // Number of entities in the data file. double dTimeStampResolution; // Minimum timestamp resolution double dTimeSpan; // Time span covered by the data file in seconds char szAppName[64]; // Name of the application that created the file uint32 dwTime_Year; // Year the file was created uint32 dwTime_Month; // Month (0-11; January = 0) uint32 dwTime_DayofWeek; // Day of the week (0-6; Sunday = 0) uint32 dwTime_Day; // Day of the month (1-31) uint32 dwTime_Hour; // Hour since midnight (0-23) uint32 dwTime_Min; // Minute after the hour (0-59) uint32 dwTime_Sec; // Seconds after the minute (0-59) uint32 dwTime_MilliSec; // Milliseconds after the second (0-1000) char szFileComment[256]; // Comments embedded in the source file } ns_FILEINFO; // General entity information structure typedef struct { char szEntityLabel[32]; // Specifies the label or name of the entity uint32 dwEntityType; // One of the ns_ENTITY_* types defined above uint32 dwItemCount; // Number of data items for the specified entity in the file } ns_ENTITYINFO; // Event entity information structure typedef struct { uint32 dwEventType; // One of the ns_EVENT_* types defined above uint32 dwMinDataLength; // Minimum number of bytes that can be returned for an Event uint32 dwMaxDataLength; // Maximum number of bytes that can be returned for an Event char szCSVDesc[128]; // Description of the data fields for CSV Event Entities } ns_EVENTINFO; // Analog information structure typedef struct { double dSampleRate; // The sampling rate in Hz used to digitize the analog values double dMinVal; // Minimum possible value of the input signal double dMaxVal; // Maximum possible value of the input signal char szUnits[16]; // Specifies the recording units of measurement double dResolution; // Minimum resolvable step (.0000305 for a +/-1V 16-bit ADC) double dLocationX; // X coordinate in meters double dLocationY; // Y coordinate in meters double dLocationZ; // Z coordinate in meters double dLocationUser; // Additional position information (e.g. tetrode number) double dHighFreqCorner; // High frequency cutoff in Hz of the source signal filtering uint32 dwHighFreqOrder; // Order of the filter used for high frequency cutoff char szHighFilterType[16]; // Type of filter used for high frequency cutoff (text format) double dLowFreqCorner; // Low frequency cutoff in Hz of the source signal filtering uint32 dwLowFreqOrder; // Order of the filter used for low frequency cutoff char szLowFilterType[16]; // Type of filter used for low frequency cutoff (text format) char szProbeInfo[128]; // Additional text information about the signal source } ns_ANALOGINFO; //Segment Information structure typedef struct { uint32 dwSourceCount; // Number of sources in the Segment Entity, e.g. 4 for a tetrode uint32 dwMinSampleCount; // Minimum number of samples in each Segment data item uint32 dwMaxSampleCount; // Maximum number of samples in each Segment data item double dSampleRate; // The sampling rate in Hz used to digitize source signals char szUnits[32]; // Specifies the recording units of measurement } ns_SEGMENTINFO; // Segment source information structure typedef struct { double dMinVal; // Minimum possible value of the input signal double dMaxVal; // Maximum possible value of the input signal double dResolution; // Minimum input step size that can be resolved double dSubSampleShift; // Time diff btn timestamp and actual sampling time of source double dLocationX; // X coordinate of source in meters double dLocationY; // Y coordinate of source in meters double dLocationZ; // Z coordinate of source in meters double dLocationUser; // Additional position information (e.g tetrode number) double dHighFreqCorner; // High frequency cutoff in Hz of the source signal filtering uint32 dwHighFreqOrder; // Order of the filter used for high frequency cutoff char szHighFilterType[16]; // Type of filter used for high frequency cutoff (text format) double dLowFreqCorner; // Low frequency cutoff in Hz of the source signal filtering uint32 dwLowFreqOrder; // Order of the filter used for low frequency cutoff char szLowFilterType[16]; // Type of filter used for low frequency cutoff (text format) char szProbeInfo[128]; // Additional text information about the signal source } ns_SEGSOURCEINFO; // Neural Information structure typedef struct { uint32 dwSourceEntityID; // Optional ID number of a source entity uint32 dwSourceUnitID; // Optional sorted unit ID number used in the source entity char szProbeInfo[128]; // Additional probe text information or source entity label } ns_NEURALINFO; #if defined(_MSC_VER) # pragma pack(pop) #endif #endif python-neuroshare-0.8.5/capi/nspy_glue.c000066400000000000000000001030331173432534200203070ustar00rootroot00000000000000/* * Copyright © 2011 Christian Kellner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the licence, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Author: Christian Kellner */ #include #include #include #include #ifndef _WIN32 #include #include #else #define _WIN32_WINNT 0x0500 #define WINVER 0x0500 #define WIN32_LEAN_AND_MEAN #include #ifdef _MSC_VER # define _POSIX_ #endif #endif #include "nsAPItypes.h" #include "nsAPIdllimp.h" static PyObject *PgError; typedef struct { #ifdef _WIN32 HMODULE dl_handle; #else void *dl_handle; #endif NS_GETLIBRARYINFO GetLibraryInfo; NS_OPENFILE OpenFile; NS_CLOSEFILE CloseFile; NS_GETFILEINFO GetFileInfo; NS_GETENTITYINFO GetEntityInfo; NS_GETEVENTINFO GetEventInfo; NS_GETEVENTDATA GetEventData; NS_GETANALOGINFO GetAnalogInfo; NS_GETANALOGDATA GetAnalogData; NS_GETSEGMENTINFO GetSegmentInfo; NS_GETSEGMENTSOURCEINFO GetSegmentSourceInfo; NS_GETSEGMENTDATA GetSegmentData; NS_GETNEURALINFO GetNeuralInfo; NS_GETNEURALDATA GetNeuralData; NS_GETINDEXBYTIME GetIndexByTime; NS_GETTIMEBYINDEX GetTimeByIndex; NS_GETLASTERRORMSG GetLastErrorMsg; } NsLibrary; uint8 uint8_from_data (void *data, size_t data_len) { uint8 ret; if (data_len == 1) { uint8 *u8 = data; ret = *u8; } else if (data_len == 2) { ret = *(uint8 *) data; } else if (data_len == 4) { uint32 *u32; u32 = (uint32 *) data; ret = (uint8) *u32; } else { ret = 0; } return ret; } static uint16 uint16_from_data (void *data, size_t data_len) { uint16 ret; if (data_len == 1) { uint8 *u8 = data; ret = (uint16) *u8; } else if (data_len == 2) { ret = *(uint16 *) data; } else if (data_len == 4) { uint32 *u32; u32 = (uint32 *) data; ret = (uint16) *u32; } else { ret = 0; } return ret; } static uint32 uint32_from_data (void *data, size_t data_len) { uint16 ret; if (data_len == 1) { uint8 *u8 = data; ret = (uint32) *u8; } else if (data_len == 2) { uint16 *u16; u16 = (uint16 *) data; ret = (uint32) *u16; } else if (data_len == 4) { ret = *(uint32 *) data; } else { ret = 0; } return ret; } static int check_result_is_error (ns_RESULT res, NsLibrary *lib) { char buf[1024] = {0, }; ns_RESULT err_res; if (res == ns_OK) return 0; err_res = lib->GetLastErrorMsg (buf, sizeof (buf)); if (err_res == ns_OK) PyErr_Format (PgError, "Neuroshare-Error (%d): %s", res, buf); else PyErr_Format (PgError, "Internal Neuroshare-Error: %d", res); return 1; } static int dict_set_item_eat_ref (PyObject *dict, const char *string, PyObject *item) { int res; res = PyDict_SetItemString (dict, string, item); Py_DECREF (item); return res; } /* ************************************************************************** */ #ifndef _WIN32 #define GetProcAddress dlsym #endif #define PROC_ADDR(_struct, _function, _variable) \ _struct->_variable = (_function) GetProcAddress (_struct->dl_handle, "ns_" #_variable); \ if (_struct->_variable == NULL) \ { \ PyErr_Format (PgError, "Could not lookup function: %s", #_variable); \ return -1; \ } static int dl_assign_pointers (NsLibrary *lib) { PROC_ADDR (lib, NS_GETLIBRARYINFO, GetLibraryInfo); PROC_ADDR (lib, NS_OPENFILE, OpenFile); PROC_ADDR (lib, NS_CLOSEFILE, CloseFile); PROC_ADDR (lib, NS_GETFILEINFO, GetFileInfo); PROC_ADDR (lib, NS_GETENTITYINFO, GetEntityInfo); PROC_ADDR (lib, NS_GETEVENTINFO, GetEventInfo); PROC_ADDR (lib, NS_GETEVENTDATA, GetEventData); PROC_ADDR (lib, NS_GETANALOGINFO, GetAnalogInfo); PROC_ADDR (lib, NS_GETANALOGDATA, GetAnalogData); PROC_ADDR (lib, NS_GETSEGMENTINFO, GetSegmentInfo); PROC_ADDR (lib, NS_GETSEGMENTSOURCEINFO, GetSegmentSourceInfo); PROC_ADDR (lib, NS_GETSEGMENTDATA, GetSegmentData); PROC_ADDR (lib, NS_GETNEURALINFO, GetNeuralInfo); PROC_ADDR (lib, NS_GETNEURALDATA, GetNeuralData); PROC_ADDR (lib, NS_GETINDEXBYTIME, GetIndexByTime); PROC_ADDR (lib, NS_GETINDEXBYTIME, GetIndexByTime); PROC_ADDR (lib, NS_GETTIMEBYINDEX, GetTimeByIndex); PROC_ADDR (lib, NS_GETLASTERRORMSG, GetLastErrorMsg); return 0; } static void dl_set_error (const char *message) { #ifdef _WIN32 DWORD last_error; DWORD res; LPVOID buf_msg; char buf_str[1024] = {0,}; last_error = GetLastError (); res = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &buf_msg, 0, NULL); if (res > 0) res = WideCharToMultiByte (CP_ACP, 0, buf_msg, -1, buf_str, sizeof (buf_str), NULL, NULL); if (res == 0) _snprintf (buf_str, sizeof (buf_str), "%s", "Internal error"); PyErr_Format (PgError, "%s: %s", message, buf_str); LocalFree (buf_msg); #else PyErr_Format (PgError, "%s: %s", message, dlerror ()); #endif } #ifdef _WIN32 static int dl_load_library_win32 (const char *filename, NsLibrary *lib) { HMODULE handle; /* FIXME: set errors */ handle = LoadLibraryEx (filename, 0, 0); if (handle == NULL) return -1; lib->dl_handle = handle; return 0; } #else static int dl_load_library_unix (const char *filename, NsLibrary *lib) { int flags; void *dlh; flags = RTLD_NOW; dlh = dlopen (filename, flags); if (dlh == NULL) return -1; lib->dl_handle = dlh; return 0; } #endif static NsLibrary * dl_load_library (const char *filename) { int res; NsLibrary *lib; lib = malloc (sizeof (NsLibrary)); #ifdef _WIN32 res = dl_load_library_win32 (filename, lib); #else res = dl_load_library_unix (filename, lib); #endif if (res != 0) { dl_set_error ("Could not load library"); free (lib); lib = NULL; } return lib; } static int dl_unload_library (NsLibrary *lib) { int res; #ifdef _WIN32 res = ! FreeLibrary (lib->dl_handle); #else res = dlclose (lib->dl_handle); #endif if (res != 0) dl_set_error ("Could not unload library"); free (lib); return res; } static PyObject * library_open (PyObject *self, PyObject *args, PyObject *kwds) { NsLibrary *lib; PyObject *lib_handle; const char *filename; int res; if (!PyArg_ParseTuple (args, "s", &filename)) return NULL; lib = dl_load_library (filename); if (lib == NULL) return NULL; res = dl_assign_pointers (lib); if (res != 0) { dl_unload_library (lib); return NULL; } lib_handle = PyCObject_FromVoidPtr (lib, NULL); return lib_handle; } static PyObject * library_close (PyObject *self, PyObject *args, PyObject *kwds) { PyObject *cobj; NsLibrary *lib; int res; if (!PyArg_ParseTuple (args, "O", &cobj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj)) { PyErr_SetString (PyExc_TypeError, "Expected NsLibrary type"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); res = dl_unload_library (lib); if (res != 0) return NULL; Py_RETURN_NONE; } static PyObject * do_get_library_info (PyObject *self, PyObject *args, PyObject *kwds) { PyObject *cobj; PyObject *dict; NsLibrary *lib; ns_LIBRARYINFO info; ns_RESULT res; if (!PyArg_ParseTuple (args, "O", &cobj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj)) { PyErr_SetString (PyExc_TypeError, "Expected NsLibrary type"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); res = lib->GetLibraryInfo (&info, sizeof (info)); if (check_result_is_error (res, lib)) return NULL; dict = PyDict_New (); dict_set_item_eat_ref (dict, "Description", PyString_FromString (info.szDescription)); dict_set_item_eat_ref (dict, "Creator", PyString_FromString (info.szCreator)); dict_set_item_eat_ref (dict, "LibVersionMaj", PyInt_FromLong (info.dwLibVersionMaj)); dict_set_item_eat_ref (dict, "LibVersionMin", PyInt_FromLong (info.dwLibVersionMin)); dict_set_item_eat_ref (dict, "APIVersionMaj", PyInt_FromLong (info.dwAPIVersionMaj)); dict_set_item_eat_ref (dict, "APIVersionMin", PyInt_FromLong (info.dwAPIVersionMin)); dict_set_item_eat_ref (dict, "Time_Year", PyInt_FromLong (info.dwTime_Year)); dict_set_item_eat_ref (dict, "Time_Month", PyInt_FromLong (info.dwTime_Month)); dict_set_item_eat_ref (dict, "Time_Day", PyInt_FromLong (info.dwTime_Day)); dict_set_item_eat_ref (dict, "MaxFiles", PyInt_FromLong (info.dwMaxFiles)); return dict; } static ns_RESULT get_and_add_file_info (NsLibrary *lib, uint32 file_id, PyObject *dict) { ns_FILEINFO info; ns_RESULT res; res = lib->GetFileInfo (file_id, &info, sizeof (info)); if (res != ns_OK) return res; dict_set_item_eat_ref (dict, "FileType", PyString_FromString (info.szFileType)); dict_set_item_eat_ref (dict, "AppName", PyString_FromString (info.szAppName)); dict_set_item_eat_ref (dict, "FileComment", PyString_FromString (info.szFileComment)); dict_set_item_eat_ref (dict, "EntityCount", PyInt_FromLong (info.dwEntityCount)); dict_set_item_eat_ref (dict, "TimeStampResolution", PyFloat_FromDouble (info.dTimeStampResolution)); dict_set_item_eat_ref (dict, "TimeSpan", PyFloat_FromDouble (info.dTimeSpan)); dict_set_item_eat_ref (dict, "Time_Year", PyInt_FromLong (info.dwTime_Year)); dict_set_item_eat_ref (dict, "Time_Month", PyInt_FromLong (info.dwTime_Month)); dict_set_item_eat_ref (dict, "Time_Day", PyInt_FromLong (info.dwTime_Day)); dict_set_item_eat_ref (dict, "Time_Hour", PyInt_FromLong (info.dwTime_Hour)); dict_set_item_eat_ref (dict, "Time_Min", PyInt_FromLong (info.dwTime_Min)); dict_set_item_eat_ref (dict, "Time_Sec", PyInt_FromLong (info.dwTime_Sec)); dict_set_item_eat_ref (dict, "Time_MilliSec", PyInt_FromLong (info.dwTime_MilliSec)); return res; } static PyObject * do_open_file (PyObject *self, PyObject *args, PyObject *kwds) { const char *filename; PyObject *cobj; PyObject *tuple; PyObject *dict = NULL; NsLibrary *lib; ns_RESULT res; uint32 file_id; if (!PyArg_ParseTuple (args, "Os", &cobj, &filename)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj)) { PyErr_SetString (PyExc_TypeError, "Expected NsLibrary type"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); res = lib->OpenFile (filename, &file_id); if (res == ns_OK) { dict = PyDict_New (); res = get_and_add_file_info (lib, file_id, dict); } if (! check_result_is_error (res, lib)) { tuple = PyTuple_New (2); PyTuple_SetItem (tuple, 0, PyInt_FromLong (file_id)); PyTuple_SetItem (tuple, 1, dict); } else tuple = NULL; return tuple; } static PyObject * do_close_file (PyObject *self, PyObject *args, PyObject *kwds) { PyObject *cobj; PyObject *iobj; NsLibrary *lib; ns_RESULT res; uint32 file_id; if (!PyArg_ParseTuple (args, "OO", &cobj, &iobj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); res = lib->CloseFile (file_id); if (check_result_is_error (res, lib)) return NULL; Py_RETURN_NONE; } /* *********************************** */ /* entity infos */ static int get_and_add_event_info (NsLibrary *lib, uint32 file_id, uint32 entity_id, PyObject *dict) { ns_EVENTINFO info; ns_RESULT res; res = lib->GetEventInfo (file_id, entity_id, &info, sizeof (info)); if (res != ns_OK) return res; dict_set_item_eat_ref (dict, "EventType", PyInt_FromLong (info.dwEventType)); dict_set_item_eat_ref (dict, "MinDataLength", PyInt_FromLong (info.dwMinDataLength)); dict_set_item_eat_ref (dict, "MaxDataLength", PyInt_FromLong (info.dwMaxDataLength)); dict_set_item_eat_ref (dict, "CSVDesc", PyString_FromString (info.szCSVDesc)); return ns_OK; } static int get_and_add_analog_info (NsLibrary *lib, uint32 file_id, uint32 entity_id, PyObject *dict) { ns_ANALOGINFO info; ns_RESULT res; res = lib->GetAnalogInfo (file_id, entity_id, &info, sizeof (info)); if (res != ns_OK) return res; dict_set_item_eat_ref (dict, "SampleRate", PyFloat_FromDouble (info.dSampleRate)); dict_set_item_eat_ref (dict, "MinVal", PyFloat_FromDouble (info.dMinVal)); dict_set_item_eat_ref (dict, "MaxVal", PyFloat_FromDouble (info.dMaxVal)); dict_set_item_eat_ref (dict, "zUnits", PyString_FromString (info.szUnits)); dict_set_item_eat_ref (dict, "Resolution", PyFloat_FromDouble (info.dResolution)); dict_set_item_eat_ref (dict, "LocationX", PyFloat_FromDouble (info.dLocationX)); dict_set_item_eat_ref (dict, "LocationY", PyFloat_FromDouble (info.dLocationY)); dict_set_item_eat_ref (dict, "LocationZ", PyFloat_FromDouble (info.dLocationZ)); dict_set_item_eat_ref (dict, "LocationUser", PyFloat_FromDouble (info.dLocationUser)); dict_set_item_eat_ref (dict, "HighFreqCorner", PyFloat_FromDouble (info.dHighFreqCorner)); dict_set_item_eat_ref (dict, "HighFreqOrder", PyInt_FromLong (info.dwHighFreqOrder)); dict_set_item_eat_ref (dict, "HighFilterType", PyString_FromString (info.szHighFilterType)); dict_set_item_eat_ref (dict, "LowFreqCorner", PyFloat_FromDouble (info.dLowFreqCorner)); dict_set_item_eat_ref (dict, "LowFreqOrder", PyInt_FromLong (info.dwLowFreqOrder)); dict_set_item_eat_ref (dict, "LowFilterType", PyString_FromString (info.szLowFilterType)); dict_set_item_eat_ref (dict, "ProbeInfo", PyString_FromString (info.szProbeInfo)); return ns_OK; } static int get_and_add_segment_source_info (NsLibrary *lib, uint32 file_id, uint32 entity_id, uint32 source_id, PyObject *list) { ns_SEGSOURCEINFO info; ns_RESULT res; PyObject *dict; dict = PyDict_New (); PyList_SetItem (list, source_id, dict); res = lib->GetSegmentSourceInfo (file_id, entity_id, source_id, &info, sizeof (info)); if (res != ns_OK) return res; dict_set_item_eat_ref (dict, "MinVal", PyFloat_FromDouble (info.dMinVal)); dict_set_item_eat_ref (dict, "MaxVal", PyFloat_FromDouble (info.dMaxVal)); dict_set_item_eat_ref (dict, "SubSampleShift", PyFloat_FromDouble (info.dSubSampleShift)); dict_set_item_eat_ref (dict, "Resolution", PyFloat_FromDouble (info.dResolution)); dict_set_item_eat_ref (dict, "LocationX", PyFloat_FromDouble (info.dLocationX)); dict_set_item_eat_ref (dict, "LocationY", PyFloat_FromDouble (info.dLocationY)); dict_set_item_eat_ref (dict, "LocationZ", PyFloat_FromDouble (info.dLocationZ)); dict_set_item_eat_ref (dict, "LocationUser", PyFloat_FromDouble (info.dLocationUser)); dict_set_item_eat_ref (dict, "HighFreqCorner", PyFloat_FromDouble (info.dHighFreqCorner)); dict_set_item_eat_ref (dict, "HighFreqOrder", PyInt_FromLong (info.dwHighFreqOrder)); dict_set_item_eat_ref (dict, "HighFilterType", PyString_FromString (info.szHighFilterType)); dict_set_item_eat_ref (dict, "LowFreqCorner", PyFloat_FromDouble (info.dLowFreqCorner)); dict_set_item_eat_ref (dict, "LowFreqOrder", PyInt_FromLong (info.dwLowFreqOrder)); dict_set_item_eat_ref (dict, "LowFilterType", PyString_FromString (info.szLowFilterType)); dict_set_item_eat_ref (dict, "ProbeInfo", PyString_FromString (info.szProbeInfo)); return ns_OK; } static int get_and_add_segment_info (NsLibrary *lib, uint32 file_id, uint32 entity_id, PyObject *dict) { ns_SEGMENTINFO info; ns_RESULT res; PyObject *list; unsigned int i; res = lib->GetSegmentInfo (file_id, entity_id, &info, sizeof (info)); if (res != ns_OK) return res; dict_set_item_eat_ref (dict, "SourceCount", PyInt_FromLong (info.dwSourceCount)); dict_set_item_eat_ref (dict, "MinSampleCount", PyInt_FromLong (info.dwMinSampleCount)); dict_set_item_eat_ref (dict, "MaxSampleCount", PyInt_FromLong (info.dwMaxSampleCount)); dict_set_item_eat_ref (dict, "SampleRate", PyFloat_FromDouble (info.dSampleRate)); dict_set_item_eat_ref (dict, "Units", PyString_FromString (info.szUnits)); list = PyList_New (info.dwSourceCount); for (i = 0; i < info.dwSourceCount; i++) get_and_add_segment_source_info (lib, file_id, entity_id, i, list); dict_set_item_eat_ref (dict, "SourceInfos", list); return res; } static int get_and_add_neural_info (NsLibrary *lib, uint32 file_id, uint32 entity_id, PyObject *dict) { ns_NEURALINFO info; ns_RESULT res; res = lib->GetNeuralInfo (file_id, entity_id, &info, sizeof (info)); if (res != ns_OK) return res; dict_set_item_eat_ref (dict, "SourceEntityID", PyInt_FromLong (info.dwSourceEntityID)); dict_set_item_eat_ref (dict, "SourceUnitID", PyInt_FromLong (info.dwSourceUnitID)); dict_set_item_eat_ref (dict, "ProbeInfo", PyString_FromString (info.szProbeInfo)); return ns_OK; } static PyObject * get_times_for_entity (NsLibrary *lib, uint32 file_id, uint32 entity_id, uint32 index, uint32 length) { PyObject *array; ns_RESULT res; npy_intp dims[1]; double *data; int i; res = ns_OK; dims[0] = length; array = PyArray_New (&PyArray_Type, 1, dims, NPY_DOUBLE, NULL, NULL /* data */, 0 /* itemsize */, NPY_CARRAY, NULL); data = (double *) PyArray_DATA (array); for (i = 0; i < length; i++) { res = lib->GetTimeByIndex (file_id, entity_id, index + i, (data + i)); if (res != ns_OK) break; } if (check_result_is_error (res, lib)) { Py_DECREF (array); return NULL; } return array; } /* ************************************************************************** */ /* "public" API */ static PyObject * do_get_entity_info (PyObject *self, PyObject *args, PyObject *kwds) { ns_ENTITYINFO info; PyObject *cobj; PyObject *iobj, *id_obj; PyObject *dict; NsLibrary *lib; ns_RESULT res; uint32 file_id; uint32 entity_id; if (!PyArg_ParseTuple (args, "OOO", &cobj, &iobj, &id_obj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) || !PyInt_Check (id_obj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj); res = lib->GetEntityInfo (file_id, entity_id, &info, sizeof (info)); if (check_result_is_error (res, lib)) return NULL; dict = PyDict_New (); dict_set_item_eat_ref (dict, "EntityLabel", PyString_FromString (info.szEntityLabel)); dict_set_item_eat_ref (dict, "EntityType", PyInt_FromLong (info.dwEntityType)); dict_set_item_eat_ref (dict, "ItemCount", PyInt_FromLong (info.dwItemCount)); switch (info.dwEntityType) { case ns_ENTITY_EVENT: res = get_and_add_event_info (lib, file_id, entity_id, dict); break; case ns_ENTITY_ANALOG: res = get_and_add_analog_info (lib, file_id, entity_id, dict); break; case ns_ENTITY_SEGMENT: res = get_and_add_segment_info (lib, file_id, entity_id, dict); break; case ns_ENTITY_NEURALEVENT: res = get_and_add_neural_info (lib, file_id, entity_id, dict); break; } if (check_result_is_error (res, lib)) { Py_DECREF (dict); return NULL; } return dict; } /* ************************************ */ static PyObject * do_get_event_data (PyObject *self, PyObject *args, PyObject *kwds) { NsLibrary *lib; PyObject *cobj; PyObject *iobj, *id_obj, *idx_obj, *tp_obj, *sz_obj; PyObject *data_obj, *res_obj; uint32 file_id; uint32 entity_id; uint32 index; uint32 event_type; uint32 data_size; uint32 data_ret_size; double time_stamp; ns_RESULT res; void *buffer; if (!PyArg_ParseTuple (args, "OOOOOO", &cobj, &iobj, &id_obj, &idx_obj, &tp_obj, &sz_obj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) || !PyInt_Check (id_obj) || !PyInt_Check (idx_obj) || !PyInt_Check (tp_obj) || !PyInt_Check (sz_obj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj); index = (uint32) PyInt_AsUnsignedLongMask (idx_obj); event_type = (uint32) PyInt_AsUnsignedLongMask (tp_obj); data_size = (uint32) PyInt_AsUnsignedLongMask (sz_obj); /* ** */ buffer = malloc (data_size); res = lib->GetEventData (file_id, entity_id, index, &time_stamp, buffer, data_size, &data_ret_size); if (check_result_is_error (res, lib)) { free (buffer); return NULL; } switch (event_type) { case ns_EVENT_TEXT: case ns_EVENT_CSV: data_obj = PyString_FromStringAndSize (buffer, data_ret_size); break; case ns_EVENT_BYTE: data_obj = PyInt_FromLong (uint8_from_data (buffer, data_ret_size)); break; case ns_EVENT_WORD: data_obj = PyInt_FromLong (uint16_from_data (buffer, data_ret_size)); break; case ns_EVENT_DWORD: data_obj = PyInt_FromLong (uint32_from_data (buffer, data_ret_size)); break; default: Py_INCREF (Py_None); data_obj = Py_None; } res_obj = Py_BuildValue ("(d,O)", time_stamp, data_obj); free (buffer); return res_obj; } static PyObject * do_get_analog_data (PyObject *self, PyObject *args, PyObject *kwds) { NsLibrary *lib; PyObject *cobj; PyObject *iobj, *id_obj, *idx_obj, *sz_obj; PyObject *res_obj; PyObject *array; PyObject *times; uint32 file_id; uint32 entity_id; uint32 index; uint32 count; uint32 cont_count; ns_RESULT res; void *buffer; npy_intp dims[1]; if (!PyArg_ParseTuple (args, "OOOOO", &cobj, &iobj, &id_obj, &idx_obj, &sz_obj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) || !PyInt_Check (id_obj) || !PyInt_Check (idx_obj) || !PyInt_Check (sz_obj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj); index = (uint32) PyInt_AsUnsignedLongMask (idx_obj); count = (uint32) PyInt_AsUnsignedLongMask (sz_obj); /* ** */ dims[0] = count; //sample count array = PyArray_New (&PyArray_Type, 1, dims, NPY_DOUBLE, NULL, NULL /* data */, 0 /* itemsize */, NPY_CARRAY, NULL); buffer = PyArray_DATA (array); res = lib->GetAnalogData (file_id, entity_id, index, count, &cont_count, buffer); if (check_result_is_error (res, lib)) { Py_DECREF (array); return NULL; } times = get_times_for_entity (lib, file_id, entity_id, index, count); if (times == NULL) { Py_DECREF (array); return NULL; } res_obj = PyTuple_New (3); PyTuple_SetItem (res_obj, 0, array); PyTuple_SetItem (res_obj, 1, times); PyTuple_SetItem (res_obj, 2, PyInt_FromLong (cont_count)); return res_obj; } static PyObject * do_get_segment_data (PyObject *self, PyObject *args, PyObject *kwds) { NsLibrary *lib; PyObject *cobj; PyObject *iobj, *id_obj, *idx_obj, *sz_obj, *src_obj; PyObject *res_obj; PyObject *array; uint32 file_id; uint32 entity_id; uint32 index; uint32 count; uint32 sources; uint32 sample_count; uint32 uint_id; uint32 buffer_size; ns_RESULT res; double *buffer; npy_intp dims[2]; double time_stamp; if (!PyArg_ParseTuple (args, "OOOOOO", &cobj, &iobj, &id_obj, &idx_obj, &src_obj, &sz_obj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) || !PyInt_Check (id_obj) || !PyInt_Check (idx_obj) || !PyInt_Check (sz_obj) || !PyInt_Check (src_obj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj); index = (uint32) PyInt_AsUnsignedLongMask (idx_obj); count = (uint32) PyInt_AsUnsignedLongMask (sz_obj); sources = (uint32) PyInt_AsUnsignedLongMask (src_obj); /* ** */ dims[0] = sources; //source count dims[1] = count; //sample count array = PyArray_New (&PyArray_Type, 2, dims, NPY_DOUBLE, NULL, NULL /* data */, 0 /* itemsize */, 0, NULL); buffer = (double *) PyArray_DATA (array); buffer_size = (uint32) PyArray_NBYTES (array); res = lib->GetSegmentData (file_id, entity_id, index, &time_stamp, buffer, buffer_size, &sample_count, &uint_id); if (check_result_is_error (res, lib)) { Py_DECREF (array); return NULL; } res_obj = PyTuple_New (4); PyTuple_SetItem (res_obj, 0, array); PyTuple_SetItem (res_obj, 1, PyFloat_FromDouble (time_stamp)); PyTuple_SetItem (res_obj, 2, PyInt_FromLong (sample_count)); PyTuple_SetItem (res_obj, 3, PyInt_FromLong (uint_id)); return res_obj; } static PyObject * do_get_neural_data (PyObject *self, PyObject *args, PyObject *kwds) { NsLibrary *lib; PyObject *cobj; PyObject *iobj, *id_obj, *idx_obj, *sz_obj; PyObject *array; uint32 file_id; uint32 entity_id; uint32 index; uint32 index_count; ns_RESULT res; void *buffer; npy_intp dims[1]; if (!PyArg_ParseTuple (args, "OOOOO", &cobj, &iobj, &id_obj, &idx_obj, &sz_obj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) || !PyInt_Check (id_obj) || !PyInt_Check (idx_obj) || !PyInt_Check (sz_obj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj); index = (uint32) PyInt_AsUnsignedLongMask (idx_obj); index_count = (uint32) PyInt_AsUnsignedLongMask (sz_obj); /* ** */ dims[0] = index_count; array = PyArray_New (&PyArray_Type, 1, dims, NPY_DOUBLE, NULL, NULL /* data */, 0 /* itemsize */, NPY_CARRAY, NULL); buffer = PyArray_DATA (array); res = lib->GetNeuralData (file_id, entity_id, index, index_count, buffer); if (check_result_is_error (res, lib)) { Py_DECREF (array); return NULL; } return array; } static PyObject * do_get_index_by_time(PyObject *self, PyObject *args, PyObject *kwds) { NsLibrary *lib; PyObject *cobj; PyObject *iobj, *id_obj, *tp_obj, *fl_obj; double timepoint; uint32 file_id; uint32 entity_id; uint32 index; uint32 flags; ns_RESULT res; if (!PyArg_ParseTuple (args, "OOOOO", &cobj, &iobj, &id_obj, &tp_obj, &fl_obj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) || !PyInt_Check (id_obj) || !PyFloat_Check (tp_obj) || !PyInt_Check (fl_obj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj); timepoint = PyFloat_AsDouble (tp_obj); flags = (uint32) PyInt_AsUnsignedLongMask (fl_obj); res = lib->GetIndexByTime (file_id, entity_id, timepoint, flags, &index); if (check_result_is_error (res, lib)) return NULL; return PyInt_FromLong (index); } static PyObject * do_get_time_by_index (PyObject *self, PyObject *args, PyObject *kwds) { NsLibrary *lib; PyObject *cobj; PyObject *iobj, *id_obj, *idx_obj; uint32 file_id; uint32 entity_id; uint32 index; double timepoint; ns_RESULT res; if (!PyArg_ParseTuple (args, "OOOO", &cobj, &iobj, &id_obj, &idx_obj)) { PyErr_SetString (PyExc_StandardError, "Could not parse arguments"); return NULL; } if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) || !PyInt_Check (id_obj) || !PyInt_Check (idx_obj)) { PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)"); return NULL; } lib = PyCObject_AsVoidPtr (cobj); file_id = (uint32) PyInt_AsUnsignedLongMask (iobj); entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj); index = (uint32) PyInt_AsUnsignedLongMask (idx_obj); res = lib->GetTimeByIndex (file_id, entity_id, index, &timepoint); if (check_result_is_error (res, lib)) return NULL; return Py_BuildValue ("d", timepoint); } static PyMethodDef NativeMethods[] = { {"library_open", (PyCFunction) library_open, METH_VARARGS | METH_KEYWORDS, "Open a Neuroshare Library"}, {"library_close", (PyCFunction) library_close, METH_VARARGS | METH_KEYWORDS, "Close an open Neuroshare Library"}, {"_get_library_info", (PyCFunction) do_get_library_info, METH_VARARGS | METH_KEYWORDS, "Retrieves information about the loaded API library"}, {"_open_file", (PyCFunction) do_open_file, METH_VARARGS | METH_KEYWORDS, "Opens the data file and returns its file info."}, {"_close_file", (PyCFunction) do_close_file, METH_VARARGS | METH_KEYWORDS, "Close the open data file"}, {"_get_entity_info", (PyCFunction) do_get_entity_info, METH_VARARGS | METH_KEYWORDS, "Retrieve Entity (general and specific) information"}, {"_get_event_data", (PyCFunction) do_get_event_data, METH_VARARGS | METH_KEYWORDS, "Retrieve event data"}, {"_get_analog_data", (PyCFunction) do_get_analog_data, METH_VARARGS | METH_KEYWORDS, "Retrieve analog data"}, {"_get_segment_data", (PyCFunction) do_get_segment_data, METH_VARARGS | METH_KEYWORDS, "Retrieve segment data"}, {"_get_neural_data", (PyCFunction) do_get_neural_data, METH_VARARGS | METH_KEYWORDS, "Retrieve analog data"}, {"_get_time_by_index", (PyCFunction) do_get_time_by_index, METH_VARARGS | METH_KEYWORDS, "Timestamp of the index"}, {"_get_index_by_time", (PyCFunction) do_get_index_by_time, METH_VARARGS | METH_KEYWORDS, "Index by timepoint"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC init_capi(void) { PyObject *module; module = Py_InitModule ("neuroshare._capi", NativeMethods); if (module == NULL) return; PyModule_AddStringConstant (module, "__doc__", "neuroshare native (C) functions"); import_array (); PgError = PyErr_NewException ("_capi.error", NULL, NULL); Py_INCREF (PgError); PyModule_AddObject (module, "error", PgError); } python-neuroshare-0.8.5/neuroshare/000077500000000000000000000000001173432534200173755ustar00rootroot00000000000000python-neuroshare-0.8.5/neuroshare/AnalogEntity.py000066400000000000000000000032631173432534200223510ustar00rootroot00000000000000 from Entity import Entity class AnalogEntity(Entity): def __init__(self, nsfile, eid, info): super(AnalogEntity,self).__init__(eid, nsfile, info) @property def sample_rate(self): return self._info['SampleRate'] @property def min_value(self): return self._info['MinVal'] @property def max_value(self): return self._info['MaxVal'] @property def resolution(self): return self._info['Resolution'] @property def units(self): return self._info['Units'] @property def location_x(self): return self._info['LocationX'] @property def location_y(self): return self._info['LocationY'] @property def location_z(self): return self._info['LocationZ'] @property def location_user(self): return self._info['LocationUser'] @property def high_freq_corner(self): return self._info['HighFreqOrder'] @property def high_freq_order(self): return self._info['HighFreqOrder'] @property def high_filter_type(self): return self._info['HighFilterType'] @property def low_freq_corner(self): return self._info['LowFreqOrder'] @property def low_freq_order(self): return self._info['LowFreqOrder'] @property def low_filter_type(self): return self._info['LowFilterType'] @property def probe_info(self): return self._info['ProbeInfo'] def get_data (self, index=0, count=-1): if count < 0: count = self.item_count lib = self.file.library data = lib._get_analog_data (self, index, count) return data python-neuroshare-0.8.5/neuroshare/Entity.py000066400000000000000000000024501173432534200212240ustar00rootroot00000000000000 class EntityTime(object): Closest = 0 Before = -1 After = 1 class Entity(object): def __init__(self, entity_id, nsfile, entity_info): self._info = entity_info self._id = entity_id self._file = nsfile @property def id(self): """The entity id of this entity""" return self._id @property def file(self): """The underlying data file of this entity""" return self._file @property def metadata_raw(self): return self._info @property def label(self): """The label or name of the entity""" return self._info['EntityLabel'] @property def entity_type(self): """The type of the entity (of EntityType)""" return self._info['EntityType'] @property def item_count(self): """ Number of data items for the specified entity in the file""" return self._info['ItemCount'] def get_time_by_index(self, index): return self._file.library._get_time_by_index (self, index) def get_index_by_time(self, timepoint, position=EntityTime.Closest): return self._file.library._get_index_by_time (self, timepoint, position) class EntityType(object): Unkown = 0 Event = 1 Analog = 2 Segment = 3 Neural = 4 python-neuroshare-0.8.5/neuroshare/EventEntity.py000066400000000000000000000011721173432534200222260ustar00rootroot00000000000000 from Entity import * class EventEntity(Entity): EVENT_TEXT = 1 EVENT_CSV = 2 EVENT_BYTE = 3 EVENT_WORD = 4 EVENT_DWORD = 5 def __init__(self, nsfile, eid, info): super(EventEntity,self).__init__(eid, nsfile, info) @property def event_type(self): return self._info['EventType'] @property def csv_desc(self): return self._info['CSVDesc'] @property def max_data_length(self): return self._info['MaxDataLength'] def get_data (self, index): lib = self.file.library data = lib._get_event_data (self, index) return data python-neuroshare-0.8.5/neuroshare/File.py000066400000000000000000000061601173432534200206310ustar00rootroot00000000000000 from Library import * from Entity import * from EventEntity import * from AnalogEntity import * from SegmentEntity import * from NeuralEntity import * class EntityProxy(object): def __init__(self, nsfile): self._nsfile = nsfile def __getitem__(self, key): return self._nsfile.get_entity(key) def __iter__(self): for x in xrange (0, self._nsfile.entity_count): yield self[x] def __len__(self): return self._nsfile.entity_count class File(object): def __init__(self, filename, library=None): self._handle = None self._filename = filename if not library: library = load_library_for_file (filename) self._lib = library (handle, info) = self._lib._open_file (filename) self._handle = handle self._info = info self._eproxy = EntityProxy(self) def __del__(self): self.close () def close(self): if self._handle: self._lib._close_file (self) self._handle = None @property def library(self): return self._lib @property def file_type(self): pass @property def metadata_raw(self): return self._info @property def app_name(self): return self._info['AppName'] @property def comment(self): return self._info['FileComment'] @property def entity_count(self): return self._info['EntityCount'] @property def time_span(self): return self._info['TimeSpan'] @property def time_stamp_resolution(self): return self.info['TimeStampResolution'] @property def ctime(self): from datetime import datetime year = self._info['Time_Year'] month = self._info['Time_Month'] day = self._info['Time_Day'] hour = self._info['Time_Hour'] minute = self._info['Time_Min'] sec = self._info['Time_Sec'] millisec = self._info['Time_MilliSec'] msec = millisec * 1000 ct = datetime (year, month, day, hour, minute, sec, msec) return ct def get_entity(self, entity_id): info = self._lib._get_entity_info (self, entity_id) entity_type = info['EntityType'] if entity_type == EntityType.Event: entity = EventEntity(self, entity_id, info) elif entity_type == EntityType.Analog: entity = AnalogEntity(self, entity_id, info) elif entity_type == EntityType.Segment: entity = SegmentEntity(self, entity_id, info) elif entity_type == EntityType.Neural: entity = NeuralEntity(self, entity_id, info) else: return None #should not happen, throw exception? return entity def list_entities(self, start=0, end=-1): if end == -1: end = self.entity_count for x in xrange (start, end): yield self.get_entity(x) @property def entities(self): return self._eproxy @property def _get_handle(self): return self._handle def __repr__(self): return 'neuroshare.File(%r)' % (self._filename) python-neuroshare-0.8.5/neuroshare/Library.py000066400000000000000000000133561173432534200213630ustar00rootroot00000000000000import os import sys import _capi class ArgumentError(Exception): def __init__(self, arg, msg): self.arg = arg self.msg = msg def __str__(self): return "\"%s\": %s" % (self.arg, self.msg) class DLLException(Exception): def __init__(self, name, ext, lib=None): self.name = name self.ext = ext self.lib = lib class DLLTypeUnknown(DLLException): def __str__(self): return '"%s": Unknown library type.' % (self.ext) class DLLNotFound(DLLException): def __str__(self): return 'Vendor DLL "%s" could not be found' % (self.lib) def _find_dll(library_name): known_paths = ["~/.neuroshare", "/usr/lib/neuroshare", "/usr/local/lib/neuroshare"]; platform = sys.platform if platform.startswith('linux'): dll_suffix = "so" elif platform.startswith('darwin'): dll_suffix = "dylib" elif platform.startswith('win'): dll_suffix = "dll" else: dll_suffix = "error" dll_name = "%s.%s" % (library_name, dll_suffix) dt = os.path.join (os.getcwd (), dll_name) if os.path.lexists (dt): return dt for cur_path in known_paths: dt = os.path.join (os.path.expanduser (cur_path), dll_name) if os.path.lexists (dt): return dt return None def find_library_for_file(filename): dll_map = {"mcd" : "nsMCDLibrary", "plx": "nsPlxLibrary", "map": "nsAOLibrary", "nev": "nsNEVLibrary", "nex": "NeuroExplorerNeuroShareLibrary"} (root, ext) = os.path.splitext(filename) if not ext or not ext.startswith('.'): raise ArgumentError (filename, "Could find file extension"); ext = ext[1:] if not dll_map.has_key (ext): raise DLLTypeUnknown (root, ext) library_name = dll_map[ext] path = _find_dll (library_name) if not path: path = _find_dll ("nsWineLibrary") if not path: raise DLLNotFound (root, ext, library_name) return (library_name, path) def load_library_for_file(filename): return Library.for_file (filename) ### Library Implementation from File import File class Library(object): _loaded_libs = {} @classmethod def for_file(cls, filename): (name, path) = find_library_for_file (filename) if not cls._loaded_libs.has_key (name): lib = Library (name, path) cls._loaded_libs[name] = lib return cls._loaded_libs[name] def __init__(self, name, path): self._name = name self._path = path self._handle = _capi.library_open (path) self._open_files = [] self._info = _capi._get_library_info (self._handle) def _open_file(self, filename): (fh, file_info) = _capi._open_file (self._handle, filename) self._open_files.append (fh) return (fh, file_info) def _close_file(self, file): fh = file._handle _capi._close_file (self._handle, fh) self._open_files.remove (fh) def _get_entity_info(self, nsfile, entity_id): fh = nsfile._handle info = _capi._get_entity_info (self._handle, fh, entity_id) return info def _get_event_data(self, event, index): fh = event.file._handle entity_id = event.id event_type = event.event_type max_data_len = event.max_data_length data = _capi._get_event_data (self._handle, fh, entity_id, index, event_type, max_data_len) return data def _get_analog_data (self, analog, index, count): fh = analog.file._handle entity_id = analog.id data = _capi._get_analog_data (self._handle, fh, entity_id, index, count) return data def _get_segment_data (self, segment, index): fh = segment.file._handle entity_id = segment.id source_count = segment.source_count max_sample_count = segment.max_sample_count data = _capi._get_segment_data (self._handle, fh, entity_id, index, source_count, max_sample_count) return data def _get_neural_data (self, neural, index, count): fh = neural.file._handle entity_id = neural.id data = _capi._get_neural_data (self._handle, fh, entity_id, index, count) return data def _get_time_by_index (self, entity, index): fh = entity.file._handle entity_id = entity.id t = _capi._get_time_by_index(self._handle, fh, entity_id, index) return t def _get_index_by_time (self, entity, time, position): fh = entity.file._handle entity_id = entity.id idx = _capi._get_index_by_time (self._handle, fh, entity_id, time, position) return idx def __del__(self): _capi.library_close(self._handle) @property def metadata_raw(self): return self._info @property def creator(self): return self._info['Creator'] @property def description(self): return self._info['Description'] @property def api_version(self): major = self._info['APIVersionMaj'] minor = self._info['APIVersionMin'] return (major, minor) @property def library_version(self): major = self._info['LibVersionMaj'] minor = self._info['LibVersionMin'] return (major, minor) @property def max_files(self): return self._info['MaxFiles'] @property def mtime(self): from datetime import date year = self._info['Time_Year'] month = self._info['Time_Month'] day = self._info['Time_Day'] return date(year, month, day) @property def name(self): return self._name @property def path(self): return self._path python-neuroshare-0.8.5/neuroshare/NeuralEntity.py000066400000000000000000000011511173432534200223700ustar00rootroot00000000000000from Entity import * class NeuralEntity(Entity): def __init__(self, nsfile, eid, info): super(NeuralEntity,self).__init__(eid, nsfile, info) @property def probe_info(self): return self._info['ProbeInfo'] @property def source_entity_id(self): return self._info['SourceEntityID'] @property def source_unit_id(self): return self._info['SourceUnitID'] def get_data (self, index=0, count=-1): lib = self.file.library if count < 0: count = self.item_count data = lib._get_neural_data (self, index, count) return data python-neuroshare-0.8.5/neuroshare/SegmentEntity.py000066400000000000000000000053341173432534200225530ustar00rootroot00000000000000from Entity import * class SegmentSource(object): def __init__(self, segment, source_id, info): self._segment = segment self._source_id = source_id self._info = info @property def segment(self): return self._segment @property def id(self): return self._source_id @property def metadata_raw(self): return self._info @property def min_value(self): return self._info['MinVal'] @property def max_value(self): return self._info['MaxVal'] @property def resolution(self): return self._info['Resolution'] @property def sub_sample_shift(self): return self._info['SubSampleShift'] @property def location_x(self): return self._info['LocationX'] @property def location_y(self): return self._info['LocationY'] @property def location_z(self): return self._info['LocationZ'] @property def location_user(self): return self._info['LocationUser'] @property def high_freq_corner(self): return self._info['HighFreqOrder'] @property def high_freq_order(self): return self._info['HighFreqOrder'] @property def high_filter_type(self): return self._info['HighFilterType'] @property def low_freq_corner(self): return self._info['LowFreqOrder'] @property def low_freq_order(self): return self._info['LowFreqOrder'] @property def low_filter_type(self): return self._info['LowFilterType'] @property def probe_info(self): return self._info['ProbeInfo'] class SourcesBag(object): def __init__(self, segment, infos): self._infos = infos self._segment = segment def __getitem__(self, key): source_id = int (key) source_info = self._infos[source_id] return SegmentSource (self._segment, source_id, source_info) def __iter__(self): for x in range(0, len (self._infos)): yield self[x] class SegmentEntity(Entity): def __init__(self, nsfile, eid, info): from copy import copy self._source_infos = info['SourceInfos'] pure_info = copy(info) del pure_info['SourceInfos'] super(SegmentEntity,self).__init__(eid, nsfile, pure_info) @property def max_sample_count(self): return self._info['MaxSampleCount'] @property def source_count(self): return self._info['SourceCount'] @property def sources(self): return SourcesBag(self, self._source_infos) def get_data (self, index): lib = self.file.library data = lib._get_segment_data (self, index) return data python-neuroshare-0.8.5/neuroshare/__init__.py000066400000000000000000000004041173432534200215040ustar00rootroot00000000000000 from Library import Library from File import File from Entity import EntityType from Entity import Entity from EventEntity import EventEntity from AnalogEntity import AnalogEntity from SegmentEntity import SegmentEntity from NeuralEntity import NeuralEntity python-neuroshare-0.8.5/ns-convert000077500000000000000000000131701173432534200172500ustar00rootroot00000000000000#!/usr/bin/env python import os, sys import h5py import neuroshare as ns import numpy as np import getopt class ProgressIndicator(object): def __init__(self, offset=0): self._cur_value = offset def setup(self, max_value): self._max_value = max_value self.progress (self._max_value, 0) def __add__(self, other): self._cur_value += other self.progress (self._max_value, self._cur_value) return self def progress (self, max_value, cur_value): pass class Converter(object): def __init__(self, filepath, output=None, progress=None): if not output: (basefile, ext) = os.path.splitext (filepath) output = "%s.hdf5" % basefile nf = ns.File(filepath) h5 = h5py.File(output, 'w') self._nf = nf self._h5 = h5 self._groups = {} self.convert_map = {1 : self.convert_event, 2 : self.convert_analog, 3 : self.convert_segment, 4 : self.convert_neural} if not progress: progress = ProgressIndicator() self._progress = progress def get_group_for_type(self, entity_type): name_map = { 1 : 'Event', 2 : 'Analog', 3 : 'Segment', 4 : 'Neural'} if not self._groups.has_key(entity_type): name = name_map[entity_type] group = self._h5.create_group(name) self._groups[entity_type] = group return self._groups[entity_type] def convert(self): progress = self._progress progress.setup (len(self._nf.entities)) self.copy_metdata(self._h5, self._nf.metadata_raw) for entity in self._nf.entities: conv = self.convert_map[entity.entity_type] conv(entity) progress + 1 self._h5.close() def convert_event(self, event): dtype = self.dtype_by_event(event) nitems = event.item_count data = np.empty([nitems], dtype) for n in xrange(0, event.item_count): data[n] = event.get_data (n) group = self.get_group_for_type(event.entity_type) dset = group.create_dataset(event.label, data=data) self.copy_metdata(dset, event.metadata_raw) def convert_analog(self, analog): (data, times, ic) = analog.get_data () group = self.get_group_for_type(analog.entity_type) d_t = np.vstack((times, data)).T dset = group.create_dataset(analog.label, data=d_t) self.copy_metdata(dset, analog.metadata_raw) def convert_segment(self, segment): if not segment.item_count: return group = self.get_group_for_type(segment.entity_type) seg_group = group.create_group(segment.label) self.copy_metdata(seg_group, segment.metadata_raw) for index in xrange(0, segment.source_count): source = segment.sources[index] name = 'SourceInfo.%d.' % index self.copy_metdata(seg_group, source.metadata_raw, prefix=name) for index in xrange(0,segment.item_count): (data, timestamp, samples, unit) = segment.get_data (index) name = '%d - %f' % (index, timestamp) dset = seg_group.create_dataset(name, data=data.T) dset.attrs['Timestamp'] = timestamp dset.attrs['Unit'] = unit dset.attrs['Index'] = index def convert_neural(self, neural): data = neural.get_data () group = self._groups[neural.entity_type] name = "%d - %s" % (neural.id, neural.label) dset = group.create_dataset(name, data=data) self.copy_metdata(dset, neural.metadata_raw) def copy_metdata(self, target, metadata, prefix=None): for (key, value) in metadata.iteritems(): if prefix is not None: key = prefix + key target.attrs[key] = value def dtype_by_event(self, event): type_map = { ns.EventEntity.EVENT_TEXT : 's', ns.EventEntity.EVENT_CSV : 's', ns.EventEntity.EVENT_BYTE : 'b', ns.EventEntity.EVENT_WORD : 'h', ns.EventEntity.EVENT_DWORD : 'i'} val_type = type_map[event.event_type] if event.event_type < 2: val_type + event.max_data_length return np.dtype([('timestamp','d'),('value', val_type)]) class ConsoleIndicator(ProgressIndicator): def __init__(self): super(ConsoleIndicator, self).__init__() self._size = 60 def progress(self, max_value, cur_value): size = self._size prefix = "Converting" x = int (size*cur_value/max_value) msg = "%s [%s%s] %i/%i\r" % (prefix, "#"*x, "." * (size-x), cur_value, max_value) self._last_msg = msg sys.stdout.write(msg) sys.stdout.flush() def cleanup(self): sys.stdout.write('%s\r' % (' '*len(self._last_msg))) sys.stdout.flush() def main(argv): opts, rem = getopt.getopt(sys.argv[1:], 'o:', ['output=', 'version=', ]) output = None for opt, arg in opts: if opt in ("-o", "--output"): output = arg if len (rem) != 1: print "Wrong number of arguments" return -1; filename = rem[0] ci = ConsoleIndicator() converter = Converter(filename, output, progress=ci); converter.convert() ci.cleanup() return 0 if __name__ == "__main__": res = main(sys.argv[1:]) sys.exit(res) python-neuroshare-0.8.5/setup.py000077500000000000000000000036761173432534200167530ustar00rootroot00000000000000#!/usr/bin/env python """Python Bindings for Neuroshare --------------------------------- The Neuroshare API is a standardized interface to access electrophysiology data stored in various different file formats. To do so, it uses format- specific shared libraries. Refer to the official website http://neuroshare.org for more information. The aim of this library is to provide a high level interface to the Neuroshare API, i.e. it focuses on API usability more then being a mere python version of the C API. Thus none of the original Neuroshare API calls are directly exposed but the interface is through python objects that resemble (more or less) the Neuroshare Entities. """ from distutils.core import setup, Extension import setuptools from distutils.extension import Extension import numpy as np classifiers = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: C', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering', 'Topic :: Software Development :: Libraries :: Python Modules'] native_ext = Extension('neuroshare._capi', include_dirs = [np.get_include()], sources = ['capi/nspy_glue.c']) setup (name = 'neuroshare', version = '0.8.5', author = 'Christian Kellner', author_email = 'kellner@biologie.uni-muenchen.de', url = 'http://www.g-node.org/neuroshare-tools', keywords = ['neuroshare'], description = __doc__.split("\n")[0], long_description = "\n".join(__doc__.split("\n")[2:]), classifiers = classifiers, ext_modules = [native_ext], packages = ['neuroshare'], scripts = ['ns-convert'] )