Commit df2e03d8 authored by Kamal Nasser's avatar Kamal Nasser
Browse files

things

parent 6a04ad67
<component name="ProjectDictionaryState">
<dictionary name="nativ">
<words>
<w>detun</w>
</words>
</dictionary>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="E303" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="libraryTable">
<library name="R User Library">
<CLASSES />
<SOURCES />
</library>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7 (PyoPlayer_Project)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/rtscs - codebase1.iml" filepath="$PROJECT_DIR$/.idea/rtscs - codebase1.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 2.7 (PyoPlayer_Project)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="R User Library" level="project" />
<orderEntry type="library" name="R Skeletons" level="application" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>
\ No newline at end of file
......@@ -12,10 +12,12 @@ class PyoHandler:
self.s = pyo.Server(sr=48000, nchnls=2, buffersize=512, duplex=0, winhost="asio").boot()
self.s.start()
# each synth is a sin sound wave
self.synth = pyo.Sine(.4, mul=0.5, add=0.5)
self.synth2 = pyo.Sine(.4, mul=0.5, add=0.5).out(2)
self.synth3 = pyo.Sine(.4, mul=0.5, add=0.5).out(3)
self.synth4 = pyo.Sine(.4, mul=0.5, add=0.5).out(4)
#self.synth = pyo.SuperSaw()
self.synth = pyo.Sine()
self.synth2 = pyo.Sine(.2, mul=0.5, add=0.5).out(2)
self.synth3 = pyo.Sine(.2, mul=0.5, add=0.5).out(3)
#self.synth4 = pyo.Sine(.2, mul=0.5, add=0.5).out(4)
self.synth4 = pyo.SuperSaw()
def change_pyo(self, fr, bal, mul):
# change the pyo parameters:
......@@ -27,7 +29,7 @@ class PyoHandler:
self.synth.setFreq(fr)
self.synth.setMul(mul)
# adding more sin waves for the Y axis
self.synth2.setFreq(fr * 5 / 3)
self.synth2.setFreq(fr * 15 / 3)
self.synth3.setFreq(fr * 1.25)
self.synth4.setFreq(fr * 7 / 2)
# changing the amplitude of the waves according to position in Y axis
......
......@@ -7,9 +7,9 @@ import optirx_utils
DEFAULT_NOTE_DURATION_PRECISION = 0.125
# rh roll implemented for future use
DEFAULT_OPTITRACK_RANGES_DICT = {'x': (-3, 3), 'y': (1, 1.9), 'z': (-1, 1.7), 'rh_roll': (-80, 100)}
DEFAULT_RTSCS_PARAM_RANGES_DICT = {'frequency': (0, 1000), 'sins': (0, 0.5),
'amplitude': (0, 1), 'numerical_hint': (0, 1)}
DEFAULT_OPTITRACK_RANGES_DICT = {'x': (-1.5, 1.3), 'y': (0.0, 2.0), 'z': (-1.5, 1.7), 'rh_roll': (-180, 180)}
DEFAULT_RTSCS_PARAM_RANGES_DICT = {'frequency': (0, 600), 'sins': (0, 0.5),
'amplitude': (0.1, 1), 'numerical_hint': (0, 1)}
class OptitrackParamReceiver(BaseRtscsParamReceiver):
......
......@@ -2,6 +2,7 @@
A utility to help determine the desired bounding box of the space in which the system operator will be working,
and the extreme angles of rotation that the operator hand can be held and at which it is still detected by the cameras.
"""
from tabulate import tabulate
import time
import math
from rtscs_param_receivers.optitrack_param_receiver.optitrack_packet_receiver import OptitrackPacketReceiver
......@@ -11,6 +12,15 @@ import sys
minint = -sys.maxint - 1
maxint = sys.maxint
fns = {
"min": min,
"max": max,
}
totalNumbers = {
"max": [minint, minint, minint, minint],
"min": [maxint, maxint, maxint, maxint],
}
if __name__ == '__main__':
optritrack_packet_recv = OptitrackPacketReceiver('127.0.0.1') # adjust OptriTrack server IP if needed
optritrack_packet_recv.start()
......@@ -19,22 +29,18 @@ if __name__ == '__main__':
#print packet
rh = optirx_utils.get_first_rigid_body(packet)
totalNumbers = {
"min": [minint, minint, minint, minint],
"max": [maxint, maxint, maxint, maxint],
}
if rh is not None:
# mul by -1 to fix flipped coordinates if not fully compatible Motive calibration square
rh_position = rh.position
#rh_position = map(lambda coordinate: -1 * coordinate, rh.position)
rh_roll = math.degrees(optirx_utils.orientation2radians(rh.orientation)[0])
currentNumbers = rh_position + [rh_roll]
currentNumbers = list(rh_position) + [rh_roll]
for method in ["min", "max"]:
for idx, value in enumerate(currentNumbers, start=1):
totalNumbers[method][idx] = globals()[method](value, currentNumbers[idx])
for idx, value in enumerate(currentNumbers, start=0):
totalNumbers[method][idx] = fns[method](totalNumbers[method][idx], value)
print currentNumbers
print totalNumbers
#print(totalNumbers)
print '\n' * 20
print tabulate([totalNumbers["min"], totalNumbers["max"], currentNumbers], headers=["x", "y", "z", "roll"])
time.sleep(0.05)
# init for sext package
""" Setuptools extensions
nibabel uses these routines, and houses them, and installs them. nipy-proper
and dipy use them.
"""
""" distutils utilities for porting to python 3 within 2-compatible tree """
from __future__ import division, print_function, absolute_import
import sys
import re
try:
from distutils.command.build_py import build_py_2to3
except ImportError:
# 2.x - no parsing of code
from distutils.command.build_py import build_py
else: # Python 3
# Command to also apply 2to3 to doctests
from distutils import log
class build_py(build_py_2to3):
def run_2to3(self, files):
# Add doctest parsing; this stuff copied from distutils.utils in
# python 3.2 source
if not files:
return
fixer_names, options, explicit = (self.fixer_names,
self.options,
self.explicit)
# Make this class local, to delay import of 2to3
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
class DistutilsRefactoringTool(RefactoringTool):
def log_error(self, msg, *args, **kw):
log.error(msg, *args)
def log_message(self, msg, *args):
log.info(msg, *args)
def log_debug(self, msg, *args):
log.debug(msg, *args)
if fixer_names is None:
fixer_names = get_fixers_from_package('lib2to3.fixes')
r = DistutilsRefactoringTool(fixer_names, options=options)
r.refactor(files, write=True)
# Then doctests
r.refactor(files, write=True, doctests_only=True)
''' Distutils / setuptools helpers '''
import os
from os.path import join as pjoin, split as psplit, splitext
import sys
PY3 = sys.version_info[0] >= 3
if PY3:
string_types = str,
else:
string_types = basestring,
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
from distutils.version import LooseVersion
from distutils.command.build_py import build_py
from distutils.command.install_scripts import install_scripts
from distutils import log
def get_comrec_build(pkg_dir, build_cmd=build_py):
""" Return extended build command class for recording commit
The extended command tries to run git to find the current commit, getting
the empty string if it fails. It then writes the commit hash into a file
in the `pkg_dir` path, named ``COMMIT_INFO.txt``.
In due course this information can be used by the package after it is
installed, to tell you what commit it was installed from if known.
To make use of this system, you need a package with a COMMIT_INFO.txt file -
e.g. ``myproject/COMMIT_INFO.txt`` - that might well look like this::
# This is an ini file that may contain information about the code state
[commit hash]
# The line below may contain a valid hash if it has been substituted during 'git archive'
archive_subst_hash=$Format:%h$
# This line may be modified by the install process
install_hash=
The COMMIT_INFO file above is also designed to be used with git substitution
- so you probably also want a ``.gitattributes`` file in the root directory
of your working tree that contains something like this::
myproject/COMMIT_INFO.txt export-subst
That will cause the ``COMMIT_INFO.txt`` file to get filled in by ``git
archive`` - useful in case someone makes such an archive - for example with
via the github 'download source' button.
Although all the above will work as is, you might consider having something
like a ``get_info()`` function in your package to display the commit
information at the terminal. See the ``pkg_info.py`` module in the nipy
package for an example.
"""
class MyBuildPy(build_cmd):
''' Subclass to write commit data into installation tree '''
def run(self):
build_cmd.run(self)
import subprocess
proc = subprocess.Popen('git rev-parse --short HEAD',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
repo_commit, _ = proc.communicate()
# Fix for python 3
repo_commit = str(repo_commit)
# We write the installation commit even if it's empty
cfg_parser = ConfigParser()
cfg_parser.read(pjoin(pkg_dir, 'COMMIT_INFO.txt'))
cfg_parser.set('commit hash', 'install_hash', repo_commit)
out_pth = pjoin(self.build_lib, pkg_dir, 'COMMIT_INFO.txt')
cfg_parser.write(open(out_pth, 'wt'))
return MyBuildPy
def _add_append_key(in_dict, key, value):
""" Helper for appending dependencies to setuptools args """
# If in_dict[key] does not exist, create it
# If in_dict[key] is a string, make it len 1 list of strings
# Append value to in_dict[key] list
if key not in in_dict:
in_dict[key] = []
elif isinstance(in_dict[key], string_types):
in_dict[key] = [in_dict[key]]
in_dict[key].append(value)
# Dependency checks
def package_check(pkg_name, version=None,
optional=False,
checker=LooseVersion,
version_getter=None,
messages=None,
setuptools_args=None
):
''' Check if package `pkg_name` is present and has good enough version
Has two modes of operation. If `setuptools_args` is None (the default),
raise an error for missing non-optional dependencies and log warnings for
missing optional dependencies. If `setuptools_args` is a dict, then fill
``install_requires`` key value with any missing non-optional dependencies,
and the ``extras_requires`` key value with optional dependencies.
This allows us to work with and without setuptools. It also means we can
check for packages that have not been installed with setuptools to avoid
installing them again.
Parameters
----------
pkg_name : str
name of package as imported into python
version : {None, str}, optional
minimum version of the package that we require. If None, we don't
check the version. Default is None
optional : bool or str, optional
If ``bool(optional)`` is False, raise error for absent package or wrong
version; otherwise warn. If ``setuptools_args`` is not None, and
``bool(optional)`` is not False, then `optional` should be a string
giving the feature name for the ``extras_require`` argument to setup.
checker : callable, optional
callable with which to return comparable thing from version
string. Default is ``distutils.version.LooseVersion``
version_getter : {None, callable}:
Callable that takes `pkg_name` as argument, and returns the
package version string - as in::
``version = version_getter(pkg_name)``
If None, equivalent to::
mod = __import__(pkg_name); version = mod.__version__``
messages : None or dict, optional
dictionary giving output messages
setuptools_args : None or dict
If None, raise errors / warnings for missing non-optional / optional
dependencies. If dict fill key values ``install_requires`` and
``extras_require`` for non-optional and optional dependencies.
'''
setuptools_mode = not setuptools_args is None
optional_tf = bool(optional)
if version_getter is None:
def version_getter(pkg_name):
mod = __import__(pkg_name)
return mod.__version__
if messages is None:
messages = {}
msgs = {
'missing': 'Cannot import package "%s" - is it installed?',
'missing opt': 'Missing optional package "%s"',
'opt suffix' : '; you may get run-time errors',
'version too old': 'You have version %s of package "%s"'
' but we need version >= %s', }
msgs.update(messages)
status, have_version = _package_status(pkg_name,
version,
version_getter,
checker)
if status == 'satisfied':
return
if not setuptools_mode:
if status == 'missing':
if not optional_tf:
raise RuntimeError(msgs['missing'] % pkg_name)
log.warn(msgs['missing opt'] % pkg_name +
msgs['opt suffix'])
return
elif status == 'no-version':
raise RuntimeError('Cannot find version for %s' % pkg_name)
assert status == 'low-version'
if not optional_tf:
raise RuntimeError(msgs['version too old'] % (have_version,
pkg_name,
version))
log.warn(msgs['version too old'] % (have_version,
pkg_name,
version)
+ msgs['opt suffix'])
return
# setuptools mode
if optional_tf and not isinstance(optional, string_types):
raise RuntimeError('Not-False optional arg should be string')
dependency = pkg_name
if version:
dependency += '>=' + version
if optional_tf:
if not 'extras_require' in setuptools_args:
setuptools_args['extras_require'] = {}
_add_append_key(setuptools_args['extras_require'],
optional,
dependency)
return
_add_append_key(setuptools_args, 'install_requires', dependency)
return
def _package_status(pkg_name, version, version_getter, checker):
try:
__import__(pkg_name)
except ImportError:
return 'missing', None
if not version:
return 'satisfied', None
try:
have_version = version_getter(pkg_name)
except AttributeError:
return 'no-version', None
if checker(have_version) < checker(version):
return 'low-version', have_version
return 'satisfied', have_version
BAT_TEMPLATE = \
r"""@echo off
REM wrapper to use shebang first line of {FNAME}
set mypath=%~dp0
set pyscript="%mypath%{FNAME}"
set /p line1=<%pyscript%
if "%line1:~0,2%" == "#!" (goto :goodstart)
echo First line of %pyscript% does not start with "#!"
exit /b 1
:goodstart
set py_exe=%line1:~2%
call "%py_exe%" %pyscript% %*
"""
class install_scripts_bat(install_scripts):
""" Make scripts executable on Windows
Scripts are bare file names without extension on Unix, fitting (for example)
Debian rules. They identify as python scripts with the usual ``#!`` first
line. Unix recognizes and uses this first "shebang" line, but Windows does
not. So, on Windows only we add a ``.bat`` wrapper of name
``bare_script_name.bat`` to call ``bare_script_name`` using the python
interpreter from the #! first line of the script.
Notes
-----
See discussion at
https://matthew-brett.github.io/pydagogue/installing_scripts.html and
example at git://github.com/matthew-brett/myscripter.git for more
background.
"""
def run(self):
install_scripts.run(self)
if not os.name == "nt":
return
for filepath in self.get_outputs():
# If we can find an executable name in the #! top line of the script
# file, make .bat wrapper for script.
with open(filepath, 'rt') as fobj:
first_line = fobj.readline()
if not (first_line.startswith('#!') and
'python' in first_line.lower()):
log.info("No #!python executable found, skipping .bat "
"wrapper")
continue
pth, fname = psplit(filepath)
froot, ext = splitext(fname)
bat_file = pjoin(pth, froot + '.bat')
bat_contents = BAT_TEMPLATE.replace('{FNAME}', fname)
log.info("Making %s wrapper for %s" % (bat_file, filepath))
if self.dry_run:
continue
with open(bat_file, 'wt') as fobj:
fobj.write(bat_contents)
class Bunch(object):
def __init__(self, vars):
for key, name in vars.items():
if key.startswith('__'):
continue
self.__dict__[key] = name
def read_vars_from(ver_file):
""" Read variables from Python text file
Parameters
----------
ver_file : str
Filename of file to read
Returns
-------
info_vars : Bunch instance
Bunch object where variables read from `ver_file` appear as
attributes
"""
# Use exec for compabibility with Python 3
ns = {}
with open(ver_file, 'rt') as fobj:
exec(fobj.read(), ns)
return Bunch(ns)
''' Test package information in various install settings
The routines here install the package from source directories, zips or eggs, and
check these installations by running tests, checking version information,
looking for files that were not copied over.
The typical use for this module is as a Makefile target. For example, here are
the Makefile targets from nibabel::
# Check for files not installed
check-files:
$(PYTHON) -c 'from nisext.testers import check_files; check_files("nibabel")'
# Print out info for possible install methods
check-version-info:
$(PYTHON) -c 'from nisext.testers import info_from_here; info_from_here("nibabel")'
# Run tests from installed code
installed-tests:
$(PYTHON) -c 'from nisext.testers import tests_installed; tests_installed("nibabel")'
# Run tests from installed code
sdist-tests:
$(PYTHON) -c 'from nisext.testers import sdist_tests; sdist_tests("nibabel")'
# Run tests from binary egg
bdist-egg-tests:
$(PYTHON) -c 'from nisext.testers import bdist_egg_tests; bdist_egg_tests("nibabel")'
'''
from __future__ import print_function
import os
import sys
from os.path import join as pjoin, abspath
from glob import glob
import shutil
import tempfile
import zipfile
import re
from subprocess import Popen, PIPE
NEEDS_SHELL = os.name != 'nt'
PYTHON=sys.executable
HAVE_PUTENV = hasattr(os, 'putenv')
PY_LIB_SDIR = 'pylib'
def back_tick(cmd, ret_err=False, as_str=True):
""" Run command `cmd`, return stdout, or stdout, stderr if `ret_err`
Roughly equivalent to ``check_output`` in Python 2.7
Parameters
----------
cmd : str
command to execute
ret_err : bool, optional
If True, return stderr in addition to stdout. If False, just return
stdout
as_str : bool, optional
Whether to decode outputs to unicode string on exit.
Returns
-------
out : str or tuple
If `ret_err` is False, return stripped string containing stdout from
`cmd`. If `ret_err` is True, return tuple of (stdout, stderr) where
``stdout`` is the stripped stdout, and ``stderr`` is the stripped
stderr.
Raises
------
RuntimeError
if command returns non-zero exit code.
"""
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=NEEDS_SHELL)
out, err = proc.communicate()
retcode = proc.returncode
if retcode is None:
proc.terminate()
raise RuntimeError(cmd + ' process did not terminate')
if retcode != 0:
raise RuntimeError(cmd + ' process returned code %d' % retcode)
out = out.strip()
if as_str:
out = out.decode('latin-1')
if not ret_err:
return out
err = err.strip()