<commit_before>"""
This is Mopidy's MPD protocol implementation.

This is partly based upon the `MPD protocol documentation
<http://www.musicpd.org/doc/protocol/>`_, which is a useful resource, but it is
rather incomplete with regards to data formats, both for requests and
responses. Thus, we have had to talk a great deal with the the original `MPD
server <https://mpd.fandom.com/>`_ using telnet to get the details we need to
implement our own MPD server which is compatible with the numerous existing
`MPD clients <https://mpd.fandom.com/wiki/Clients>`_.
"""

from __future__ import absolute_import, unicode_literals

import inspect

from mopidy.mpd import exceptions

#: The MPD protocol uses UTF-8 for encoding all data.
ENCODING = 'UTF-8'

#: The MPD protocol uses ``\n`` as line terminator.
LINE_TERMINATOR = '\n'

#: The MPD protocol version is 0.19.0.
VERSION = '0.19.0'

def load_protocol_modules():
    """
    The protocol modules must be imported to get them registered in
    :attr:`commands`.
    """
    from . import (  # noqa
        audio_output, channels, command_list, connection, current_playlist,
        mount, music_db, playback, reflection, status, stickers,
        stored_playlists)

def INT(value):  # noqa: N802
    r"""Converts a value that matches [+-]?\d+ into an integer."""
    if value is None:
        raise ValueError('None is not a valid integer')
    # TODO: check for whitespace via value != value.strip()?
    return int(value)

def UINT(value):  # noqa: N802
    r"""Converts a value that matches \d+ into an integer."""
    if value is None:
        raise ValueError('None is not a valid integer')
    if not value.isdigit():
        raise ValueError('Only positive numbers are allowed')
    return int(value)

def FLOAT(value):  # noqa: N802
    r"""Converts a value that matches [+-]\d+(.\d+)? into a float."""
    if value is None:
        raise ValueError('None is not a valid float')
    return float(value)

def UFLOAT(value):  # noqa: N802
    r"""Converts a value that matches \d+(.\d+)? into a float."""
    if value is None:
        raise ValueError('None is not a valid float')
    value = float(value)
    if value < 0:
        raise ValueError('Only positive numbers are allowed')
    return value

def BOOL(value):  # noqa: N802
    """Convert the values 0 and 1 into booleans."""
    if value in ('1', '0'):
        return bool(int(value))
    raise ValueError('%r is not 0 or 1' % value)

def RANGE(value):  # noqa: N802
    """Convert a single integer or range spec into a slice

    ``n`` should become ``slice(n, n+1)``
    ``n:`` should become ``slice(n, None)``
    ``n:m`` should become ``slice(n, m)`` and ``m > n`` must hold
    """
    if ':' in value:
        start, stop = value.split(':', 1)
        start = UINT(start)
        if stop.strip():
            stop = UINT(stop)
            if start >= stop:
                raise ValueError('End must be larger than start')
        else:
            stop = None
    else:
        start = UINT(value)
        stop = start + 1
    return slice(start, stop)

class Commands(object):

    """Collection of MPD commands to expose to users.

    Normally used through the global instance which command handlers have been
    installed into.
    """

    def __init__(self):
        self.handlers = {}

    # TODO: consider removing auth_required and list_command in favour of
    # additional command instances to register in?
    def add(self, name, auth_required=True, list_command=True, **validators):
        """Create a decorator that registers a handler and validation rules.

        Additional keyword arguments are treated as converters/validators to
        apply to tokens converting them to proper Python types.

        Requirements for valid handlers:

        - must accept a context argument as the first arg.
        - may not use variable keyword arguments, ``**kwargs``.
        - may use variable arguments ``*args`` *or* a mix of required and
          optional arguments.

        Decorator returns the unwrapped function so that tests etc can use the
        functions with values with correct python types instead of strings.

        :param string name: Name of the command being registered.
        :param bool auth_required: If authorization is required.
        :param bool list_command: If command should be listed in reflection.
        """

        def wrapper(func):
            if name in self.handlers:
                raise ValueError('%s already registered' % name)

            args, varargs, keywords, defaults = inspect.getargspec(func)
            defaults = dict(zip(args[-len(defaults or []):], defaults or []))

            if not args and not varargs:
                raise TypeError('Handler must accept at least one argument.')

            if len(args) > 1 and varargs:
                raise TypeError(
                    '*args may not be combined with regular arguments')

            if not set(validators.keys()).issubset(args):
                raise TypeError('Validator for non-existent arg passed')

            if keywords:
                raise TypeError('**kwargs are not permitted')

            def validate(*args, **kwargs):
                if varargs:
                    return func(*args, **kwargs)

                try:
                    callargs = inspect.getcallargs(func, *args, **kwargs)
                except TypeError:
                    raise exceptions.MpdArgError(
                        'wrong number of arguments for "%s"' % name)

                for key, value in callargs.items():
                    default = defaults.get(key, object())
                    if key in validators and value != default:
                        try:
                            callargs[key] = validators[key](value)
                        except ValueError:
                            raise exceptions.MpdArgError('incorrect arguments')

                return func(**callargs)

            validate.auth_required = auth_required
            validate.list_command = list_command
            self.handlers[name] = validate
            return func
        return wrapper

    def call(self, tokens, context=None):
        """Find and run the handler registered for the given command.

        If the handler was registered with any converters/validators they will
        be run before calling the real handler.

        :param list tokens: List of tokens to process
        :param context: MPD context.
        :type context: :class:`~mopidy.mpd.dispatcher.MpdContext`
        """
        if not tokens:
            raise exceptions.MpdNoCommand()
        if tokens[0] not in self.handlers:
            raise exceptions.MpdUnknownCommand(command=tokens[0])
        return self.handlers[tokens[0]](context, *tokens[1:])

#: Global instance to install commands into
commands = Commands()
<commit_msg>py3: Fix ~100 test suite warnings<commit_after>"""
This is Mopidy's MPD protocol implementation.

This is partly based upon the `MPD protocol documentation
<http://www.musicpd.org/doc/protocol/>`_, which is a useful resource, but it is
rather incomplete with regards to data formats, both for requests and
responses. Thus, we have had to talk a great deal with the the original `MPD
server <https://mpd.fandom.com/>`_ using telnet to get the details we need to
implement our own MPD server which is compatible with the numerous existing
`MPD clients <https://mpd.fandom.com/wiki/Clients>`_.
"""

from __future__ import absolute_import, unicode_literals

import inspect

from mopidy import compat
from mopidy.mpd import exceptions

#: The MPD protocol uses UTF-8 for encoding all data.
ENCODING = 'UTF-8'

#: The MPD protocol uses ``\n`` as line terminator.
LINE_TERMINATOR = '\n'

#: The MPD protocol version is 0.19.0.
VERSION = '0.19.0'

def load_protocol_modules():
    """
    The protocol modules must be imported to get them registered in
    :attr:`commands`.
    """
    from . import (  # noqa
        audio_output, channels, command_list, connection, current_playlist,
        mount, music_db, playback, reflection, status, stickers,
        stored_playlists)

def INT(value):  # noqa: N802
    r"""Converts a value that matches [+-]?\d+ into an integer."""
    if value is None:
        raise ValueError('None is not a valid integer')
    # TODO: check for whitespace via value != value.strip()?
    return int(value)

def UINT(value):  # noqa: N802
    r"""Converts a value that matches \d+ into an integer."""
    if value is None:
        raise ValueError('None is not a valid integer')
    if not value.isdigit():
        raise ValueError('Only positive numbers are allowed')
    return int(value)

def FLOAT(value):  # noqa: N802
    r"""Converts a value that matches [+-]\d+(.\d+)? into a float."""
    if value is None:
        raise ValueError('None is not a valid float')
    return float(value)

def UFLOAT(value):  # noqa: N802
    r"""Converts a value that matches \d+(.\d+)? into a float."""
    if value is None:
        raise ValueError('None is not a valid float')
    value = float(value)
    if value < 0:
        raise ValueError('Only positive numbers are allowed')
    return value

def BOOL(value):  # noqa: N802
    """Convert the values 0 and 1 into booleans."""
    if value in ('1', '0'):
        return bool(int(value))
    raise ValueError('%r is not 0 or 1' % value)

def RANGE(value):  # noqa: N802
    """Convert a single integer or range spec into a slice

    ``n`` should become ``slice(n, n+1)``
    ``n:`` should become ``slice(n, None)``
    ``n:m`` should become ``slice(n, m)`` and ``m > n`` must hold
    """
    if ':' in value:
        start, stop = value.split(':', 1)
        start = UINT(start)
        if stop.strip():
            stop = UINT(stop)
            if start >= stop:
                raise ValueError('End must be larger than start')
        else:
            stop = None
    else:
        start = UINT(value)
        stop = start + 1
    return slice(start, stop)

class Commands(object):

    """Collection of MPD commands to expose to users.

    Normally used through the global instance which command handlers have been
    installed into.
    """

    def __init__(self):
        self.handlers = {}

    # TODO: consider removing auth_required and list_command in favour of
    # additional command instances to register in?
    def add(self, name, auth_required=True, list_command=True, **validators):
        """Create a decorator that registers a handler and validation rules.

        Additional keyword arguments are treated as converters/validators to
        apply to tokens converting them to proper Python types.

        Requirements for valid handlers:

        - must accept a context argument as the first arg.
        - may not use variable keyword arguments, ``**kwargs``.
        - may use variable arguments ``*args`` *or* a mix of required and
          optional arguments.

        Decorator returns the unwrapped function so that tests etc can use the
        functions with values with correct python types instead of strings.

        :param string name: Name of the command being registered.
        :param bool auth_required: If authorization is required.
        :param bool list_command: If command should be listed in reflection.
        """

        def wrapper(func):
            if name in self.handlers:
                raise ValueError('%s already registered' % name)

            if compat.PY2:
                spec = inspect.getargspec(func)
            else:
                spec = inspect.getfullargspec(func)
            defaults = dict(
                zip(spec.args[-len(spec.defaults or []):], spec.defaults or [])
            )

            if not spec.args and not spec.varargs:
                raise TypeError('Handler must accept at least one argument.')

            if len(spec.args) > 1 and spec.varargs:
                raise TypeError(
                    '*args may not be combined with regular arguments')

            if not set(validators.keys()).issubset(spec.args):
                raise TypeError('Validator for non-existent arg passed')

            if compat.PY2:
                if spec.keywords:
                    raise TypeError('Keyword arguments are not permitted')
            else:
                if spec.varkw or spec.kwonlyargs:
                    raise TypeError('Keyword arguments are not permitted')

            def validate(*args, **kwargs):
                if spec.varargs:
                    return func(*args, **kwargs)

                try:
                    callargs = inspect.getcallargs(func, *args, **kwargs)
                except TypeError:
                    raise exceptions.MpdArgError(
                        'wrong number of arguments for "%s"' % name)

                for key, value in callargs.items():
                    default = defaults.get(key, object())
                    if key in validators and value != default:
                        try:
                            callargs[key] = validators[key](value)
                        except ValueError:
                            raise exceptions.MpdArgError('incorrect arguments')

                return func(**callargs)

            validate.auth_required = auth_required
            validate.list_command = list_command
            self.handlers[name] = validate
            return func
        return wrapper

    def call(self, tokens, context=None):
        """Find and run the handler registered for the given command.

        If the handler was registered with any converters/validators they will
        be run before calling the real handler.

        :param list tokens: List of tokens to process
        :param context: MPD context.
        :type context: :class:`~mopidy.mpd.dispatcher.MpdContext`
        """
        if not tokens:
            raise exceptions.MpdNoCommand()
        if tokens[0] not in self.handlers:
            raise exceptions.MpdUnknownCommand(command=tokens[0])
        return self.handlers[tokens[0]](context, *tokens[1:])

#: Global instance to install commands into
commands = Commands()
<|endoftext|>


<commit_before>import webbrowser
import fresh_tomatoes

"""Defines the class movie to show the attributes of the movies represented by
by the multiple instances of the class"""
class Movie():
    def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
        self.title = movie_title
        self.storyline = movie_storyline
        self.poster_image_url = poster_image
        self.trailer_youtube_url = trailer_youtube

""" The attributes corresponds to the following outcome.
        self.title = Title of the movie
        self.storyline = A breif description of the movie
        self.poster_image_url = Cover Image sourced from external urls
        self.trailer_youtube_url = A trailer sourced from youtube """

def show_trailer(self):
        webbrowser.open(self.trailer_youtube_url)

""" Multiple instances of the Class Movie to represent the favorite movies;"""
toy_story = Movie("Toy Story",
                        "A story of a boy and his toys that come to life",
                        "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",
                        "https://www.youtube.com/watch?v=vwyZH85NQC4")

avatar = Movie("Avatar",
                     "A marine on an alien planet",
                     "http://www.impawards.com/2009/posters/avatar_xlg.jpg",
                     "https://www.youtube.com/watch?v=5PSNL1qE6VY")

interstellar = Movie("Interstellar",
                           "A group of astronauts who travel through a wormhole"
                           " in search of a new home for humanity.",
                           "https://upload.wikimedia.org/wikipedia/en/b/bc/Interstellar_film_poster.jpg",
                           "https://www.youtube.com/watch?v=zSWdZVtXT7E")

netaji = Movie("Netaji, The forgotten hero",
                     "The film depicts the life of the Indian independence leader"
                     " Subhas Chandra Bose",
                     "https://upload.wikimedia.org/wikipedia/en/f/f8/Bosefilm.jpg",
                     "https://www.youtube.com/watch?v=dfzCuNElusk")

lala_land = Movie("La La Land",
                        "A jazz pianist and an aspiring actress who meet and"
                        " fall in love in Los Angeles.",
                        "https://upload.wikimedia.org/wikipedia/en/a/ab/La_La_Land_%28film%29.png",
                        "https://www.youtube.com/watch?v=0pdqf4P9MB8")

inside_out = Movie("Inside Out",
                         "The film is set in the mind of a young girl named Riley"
                         " Andersen where five personified emotions; Joy, Sadness,"
                         " Anger, Fear and Disgust try to lead her through life",
                         "https://upload.wikimedia.org/wikipedia/en/0/0a/Inside_Out_%282015_film%29_poster.jpg",
                         "https://www.youtube.com/watch?v=yRUAzGQ3nSY")

movies = [toy_story, avatar, interstellar, netaji, lala_land, inside_out]

fresh_tomatoes.open_movies_page(movies)
<commit_msg>Update media.py<commit_after>import webbrowser
import fresh_tomatoes

class Movie():
    def __init__(self, movie_title, movie_storyline, poster_image,
                 trailer_youtube):
        self.title = movie_title
        self.storyline = movie_storyline
        self.poster_image_url = poster_image
        self.trailer_youtube_url = trailer_youtube

    def show_trailer(self):
        webbrowser.open(self.trailer_youtube_url)

toy_story = Movie("Toy Story",
                  "A story of a boy and his toys that come to life",
                  "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",   # noqa
                  "https://www.youtube.com/watch?v=vwyZH85NQC4")    # noqa

avatar = Movie("Avatar",
               "A marine on an alien planet",
               "http://www.impawards.com/2009/posters/avatar_xlg.jpg",  # noqa
               "https://www.youtube.com/watch?v=5PSNL1qE6VY")   # noqa

interstellar = Movie("Interstellar",
                     "A group of astronauts who travel through a wormhole"
                     " in search of a new home for humanity.",
                     "https://upload.wikimedia.org/wikipedia/en/b/bc/Interstellar_film_poster.jpg",  # noqa
                     "https://www.youtube.com/watch?v=zSWdZVtXT7E")     # noqa

netaji = Movie("Netaji, The forgotten hero",
               "The film depicts the life of the Indian independence leader"
               " Subhas Chandra Bose",
               "https://upload.wikimedia.org/wikipedia/en/f/f8/Bosefilm.jpg",   # noqa
               "https://www.youtube.com/watch?v=dfzCuNElusk")   # noqa

lala_land = Movie("La La Land",
                  "A jazz pianist and an aspiring actress who meet and"
                  " fall in love in Los Angeles.",
                  "https://upload.wikimedia.org/wikipedia/en/a/ab/La_La_Land_%28film%29.png",   # noqa
                  "https://www.youtube.com/watch?v=0pdqf4P9MB8")    # noqa

inside_out = Movie("Inside Out",
                   "The film is set in the mind of a young girl named Riley"
                   " Andersen where five personified emotions; Joy, Sadness,"
                   " Anger, Fear and Disgust try to lead her through life",
                   "https://upload.wikimedia.org/wikipedia/en/0/0a/Inside_Out_%282015_film%29_poster.jpg",  # noqa
                   "https://www.youtube.com/watch?v=yRUAzGQ3nSY")   # noqa

movies = [toy_story, avatar, interstellar, netaji, lala_land, inside_out]

fresh_tomatoes.open_movies_page(movies)
<|endoftext|>


<commit_before># All the individual config players have their own tests, but this tests the
# generic ConfigPlayer functionality
from collections import namedtuple

import mpf.core.config_validator
from mpf.assets.show import Show
from mpf.tests.MpfTestCase import MpfTestCase
from mpf.core.config_player import ConfigPlayer

PlayCall = namedtuple('PlayCall', 'settings key priority kwargs',
                      verbose=False)

class BananaPlayer(ConfigPlayer):
    config_file_section = 'banana_player'
    show_section = 'bananas'
    machine_collection_name = 'bananas'

    def __init__(self, machine):
        super().__init__(machine)
        self.machine.bananas = dict()
        self.machine.banana_play_calls = list()

    def play(self, settings, key=None, priority=0, **kwargs):
        self.machine.banana_play_calls.append(PlayCall(
            settings, key, priority, kwargs))

    def _clear(self, key):
        pass

    def get_express_config(self, value):
        return dict(banana=value)

    def get_full_config(self, value):
        return value

player_cls = BananaPlayer

class TestConfigPlayers(MpfTestCase):

    def getConfigFile(self):
        return 'test_config_players.yaml'

    def getMachinePath(self):
        return 'tests/machine_files/config_players/'

    def setUp(self):
        self.machine_config_patches['mpf']['config_players'] = dict()
        self.machine_config_patches['mpf']['config_players']['banana'] = \
            'mpf.tests.test_ConfigPlayers'

        self.add_to_config_validator('banana_player',
                                     dict(__valid_in__='machine, mode'))

        # Hack around globals in shows
        Show.next_id = 0

        super().setUp()

    def test_config_player(self):
        self.assertIn('bananas', ConfigPlayer.show_players)
        self.assertIn('banana_player', ConfigPlayer.config_file_players)

        # post events to make sure banana_player is called
        self.machine.events.post('event1')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings, {'bananas': {'express': {}}})
        self.assertEqual(play_call.key, None)
        self.assertEqual(play_call.kwargs, {})

        self.machine.events.post('event2')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings,
                         {'bananas': {'some': {'banana': 'key'}}})
        self.assertEqual(play_call.key, None)
        self.assertEqual(play_call.kwargs, {})  # todo

        self.machine.events.post('event3')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings,
                         {'bananas': {'this_banana': {'some': 'key'},
                                      'that_banana': {'some': 'key'}}})
        self.assertEqual(play_call.key, None)
        self.assertEqual(play_call.kwargs, {})  # todo

        # event5 is in mode1, so make sure it is not called now

        self.assertEqual(0, len(self.machine.banana_play_calls))

        self.machine.events.post('event5')
        self.advance_time_and_run()

        self.assertEqual(0, len(self.machine.banana_play_calls))

        # Start the mode, make sure the mode player enables
        self.machine.modes['mode1'].start()
        self.advance_time_and_run()

        self.machine.events.post('event5')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings, {'bananas': {'express': {}}})
        # Mode should be passed properly
        self.assertEqual(play_call.key, 'mode1')
        self.assertEqual(play_call.kwargs, {})  # todo

        # stop the mode, make sure the event doesn't fire
        self.machine.modes['mode1'].stop()
        self.advance_time_and_run()

        self.machine.events.post('event5')
        self.advance_time_and_run()

        self.assertEqual(0, len(self.machine.banana_play_calls))

        # Start a show
        self.machine.events.post('event4')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()
        self.assertEqual(play_call.settings, {'banana1': {'banana': 'express'}})
        self.assertEqual(play_call.key, 'show1.1')
        self.assertEqual(play_call.kwargs, {'show_tokens': {}})  # todo

        self.assertEqual(1, len(self.machine.show_controller.running_shows))

        # todo add tests for mode 1 show, make sure the mode is passed
        # todo make sure it stops when the mode ends, that banana clear is
        # called when it stops, and that it doesn't start again once the mode
        # is not running

    def test_empty_config_player_section(self):
        self.machine.modes.mode2.start()
        self.advance_time_and_run()
        self.machine.modes.mode2.stop()
        self.advance_time_and_run()
<commit_msg>dont check keys<commit_after># All the individual config players have their own tests, but this tests the
# generic ConfigPlayer functionality
from collections import namedtuple

import mpf.core.config_validator
from mpf.assets.show import Show
from mpf.tests.MpfTestCase import MpfTestCase
from mpf.core.config_player import ConfigPlayer

PlayCall = namedtuple('PlayCall', 'settings key priority kwargs',
                      verbose=False)

class BananaPlayer(ConfigPlayer):
    config_file_section = 'banana_player'
    show_section = 'bananas'
    machine_collection_name = 'bananas'

    def __init__(self, machine):
        super().__init__(machine)
        self.machine.bananas = dict()
        self.machine.banana_play_calls = list()

    def play(self, settings, context, key=None, priority=0, **kwargs):
        self.machine.banana_play_calls.append(PlayCall(
            settings, key, priority, kwargs))

    def _clear(self, key):
        pass

    def get_express_config(self, value):
        return dict(banana=value)

    def get_full_config(self, value):
        return value

player_cls = BananaPlayer

class TestConfigPlayers(MpfTestCase):

    def getConfigFile(self):
        return 'test_config_players.yaml'

    def getMachinePath(self):
        return 'tests/machine_files/config_players/'

    def setUp(self):
        self.machine_config_patches['mpf']['config_players'] = dict()
        self.machine_config_patches['mpf']['config_players']['banana'] = \
            'mpf.tests.test_ConfigPlayers'

        self.add_to_config_validator('banana_player',
                                     dict(__valid_in__='machine, mode'))

        # Hack around globals in shows
        Show.next_id = 0

        super().setUp()

    def test_config_player(self):
        self.assertIn('bananas', ConfigPlayer.show_players)
        self.assertIn('banana_player', ConfigPlayer.config_file_players)

        # post events to make sure banana_player is called
        self.machine.events.post('event1')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings, {'bananas': {'express': {}}})
        self.assertEqual(play_call.key, None)
        self.assertEqual(play_call.kwargs, {})

        self.machine.events.post('event2')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings,
                         {'bananas': {'some': {'banana': 'key'}}})
        self.assertEqual(play_call.key, None)
        self.assertEqual(play_call.kwargs, {})  # todo

        self.machine.events.post('event3')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings,
                         {'bananas': {'this_banana': {'some': 'key'},
                                      'that_banana': {'some': 'key'}}})
        self.assertEqual(play_call.key, None)
        self.assertEqual(play_call.kwargs, {})  # todo

        # event5 is in mode1, so make sure it is not called now

        self.assertEqual(0, len(self.machine.banana_play_calls))

        self.machine.events.post('event5')
        self.advance_time_and_run()

        self.assertEqual(0, len(self.machine.banana_play_calls))

        # Start the mode, make sure the mode player enables
        self.machine.modes['mode1'].start()
        self.advance_time_and_run()

        self.machine.events.post('event5')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()

        self.assertEqual(play_call.settings, {'bananas': {'express': {}}})
        # Mode should be passed properly
        # self.assertEqual(play_call.key, 'mode1')
        self.assertEqual(play_call.kwargs, {})  # todo

        # stop the mode, make sure the event doesn't fire
        self.machine.modes['mode1'].stop()
        self.advance_time_and_run()

        self.machine.events.post('event5')
        self.advance_time_and_run()

        self.assertEqual(0, len(self.machine.banana_play_calls))

        # Start a show
        self.machine.events.post('event4')
        self.advance_time_and_run()

        play_call = self.machine.banana_play_calls.pop()
        self.assertEqual(play_call.settings, {'banana1': {'banana': 'express'}})
        # self.assertEqual(play_call.key, 'show1.1')
        self.assertEqual(play_call.kwargs, {'show_tokens': {}})  # todo

        self.assertEqual(1, len(self.machine.show_controller.running_shows))

        # todo add tests for mode 1 show, make sure the mode is passed
        # todo make sure it stops when the mode ends, that banana clear is
        # called when it stops, and that it doesn't start again once the mode
        # is not running

    def test_empty_config_player_section(self):
        self.machine.modes.mode2.start()
        self.advance_time_and_run()
        self.machine.modes.mode2.stop()
        self.advance_time_and_run()
<|endoftext|>


<commit_before>from __future__ import unicode_literals

import datetime
import warnings

from django.conf import settings
from django.contrib.admin.templatetags.admin_list import (
    result_hidden_fields, result_headers)
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.contrib.admin.utils import (
    display_for_field, display_for_value, lookup_field)
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.template import Library
from django.core.urlresolvers import NoReverseMatch
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import get_language_bidi

register = Library()

MPTT_ADMIN_LEVEL_INDENT = getattr(settings, 'MPTT_ADMIN_LEVEL_INDENT', 10)
IS_GRAPPELLI_INSTALLED = True if 'grappelli' in settings.INSTALLED_APPS else False

###
# Ripped from contrib.admin (1.10)
def _coerce_field_name(field_name, field_index):
    """
    Coerce a field_name (which may be a callable) to a string.
    """
    if callable(field_name):
        if field_name.__name__ == '<lambda>':
            return 'lambda' + str(field_index)
        else:
            return field_name.__name__
    return field_name

def get_empty_value_display(cl):
    if hasattr(cl.model_admin, 'get_empty_value_display'):
        return cl.model_admin.get_empty_value_display()
    else:
        # Django < 1.9
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        return EMPTY_CHANGELIST_VALUE

###
# Ripped from contrib.admin's (1.10) items_for_result tag.
# The only difference is we're indenting nodes according to their level.
def mptt_items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """

    def link_in_col(is_first, field_name, cl):
        if cl.list_display_links is None:
            return False
        if is_first and not cl.list_display_links:
            return True
        return field_name in cl.list_display_links

    first = True
    pk = cl.lookup_opts.pk.attname

    # #### MPTT ADDITION START
    # figure out which field to indent
    mptt_indent_field = getattr(cl.model_admin, 'mptt_indent_field', None)
    if not mptt_indent_field:
        for field_name in cl.list_display:
            try:
                f = cl.lookup_opts.get_field(field_name)
            except models.FieldDoesNotExist:
                if (mptt_indent_field is None and
                        field_name != 'action_checkbox'):
                    mptt_indent_field = field_name
            else:
                # first model field, use this one
                mptt_indent_field = field_name
                break

    # figure out how much to indent
    mptt_level_indent = getattr(cl.model_admin, 'mptt_level_indent', MPTT_ADMIN_LEVEL_INDENT)
    # #### MPTT ADDITION END

    for field_index, field_name in enumerate(cl.list_display):
        # #### MPTT SUBSTITUTION START
        empty_value_display = get_empty_value_display(cl)
        # #### MPTT SUBSTITUTION END
        row_classes = ['field-%s' % _coerce_field_name(field_name, field_index)]
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, 'empty_value_display', empty_value_display)
            if f is None or f.auto_created:
                if field_name == 'action_checkbox':
                    row_classes = ['action-checkbox']
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                # #### MPTT SUBSTITUTION START
                try:
                    # Changed in Django 1.9, now takes 3 arguments
                    result_repr = display_for_value(
                        value, empty_value_display, boolean)
                except TypeError:
                    result_repr = display_for_value(value, boolean)
                # #### MPTT SUBSTITUTION END
                if allow_tags:
                    warnings.warn(
                        "Deprecated allow_tags attribute used on field {}. "
                        "Use django.utils.safestring.format_html(), "
                        "format_html_join(), or mark_safe() instead.".format(field_name),
                        RemovedInDjango20Warning
                    )
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                # #### MPTT SUBSTITUTION START
                try:
                    is_many_to_one = isinstance(
                        f.remote_field, models.ManyToOneRel)
                except AttributeError:
                    is_many_to_one = isinstance(f.rel, models.ManyToOneRel)
                if is_many_to_one:
                    # #### MPTT SUBSTITUTION END
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    # #### MPTT SUBSTITUTION START
                    try:
                        result_repr = display_for_field(value, f)
                    except TypeError:
                        # Changed in Django 1.9, now takes 3 arguments
                        result_repr = display_for_field(
                            value, f, empty_value_display)
                    # #### MPTT SUBSTITUTION END
                if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if force_text(result_repr) == '':
            result_repr = mark_safe(' ')
        row_class = mark_safe(' class="%s"' % ' '.join(row_classes))

        # #### MPTT ADDITION START
        if field_name == mptt_indent_field:
            level = getattr(result, result._mptt_meta.level_attr)
            padding_attr = mark_safe(' style="padding-%s:%spx"' % (
                'right' if get_language_bidi() else 'left',
                8 + mptt_level_indent * level))
        else:
            padding_attr = ''
        # #### MPTT ADDITION END

        # If list_display_links not defined, add the link tag to the first field
        if link_in_col(first, field_name, cl):
            table_tag = 'th' if first else 'td'
            first = False

            # Display link to the result's change_view if the url exists, else
            # display just the result's representation.
            try:
                url = cl.url_for_result(result)
            except NoReverseMatch:
                link_or_text = result_repr
            else:
                url = add_preserved_filters({'preserved_filters': cl.preserved_filters, 'opts': cl.opts}, url)
                # Convert the pk to something that can be used in Javascript.
                # Problem cases are long ints (23L) and non-ASCII strings.
                if cl.to_field:
                    attr = str(cl.to_field)
                else:
                    attr = pk
                value = result.serializable_value(attr)
                link_or_text = format_html(
                    '{}',
                    url,
                    format_html(
                        ' data-popup-opener="{}"', value
                    ) if cl.is_popup else '',
                    result_repr)

            # #### MPTT SUBSTITUTION START
            yield format_html('<{}{}{}>{}</{}>',
                              table_tag,
                              row_class,
                              padding_attr,
                              link_or_text,
                              table_tag)
            # #### MPTT SUBSTITUTION END
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if (form and field_name in form.fields and not (
                    field_name == cl.model._meta.pk.name and
                    form[cl.model._meta.pk.name].is_hidden)):
                bf = form[field_name]
                result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
            # #### MPTT SUBSTITUTION START
            yield format_html('{}	', row_class, padding_attr, result_repr)
            # #### MPTT SUBSTITUTION END
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield format_html('{}	', force_text(form[cl.model._meta.pk.name]))

def mptt_results(cl):
    if cl.formset:
        for res, form in zip(cl.result_list, cl.formset.forms):
            yield list(mptt_items_for_result(cl, res, form))
    else:
        for res in cl.result_list:
            yield list(mptt_items_for_result(cl, res, None))

def mptt_result_list(cl):
    """
    Displays the headers and data list together
    """
    return {'cl': cl,
            'result_hidden_fields': list(result_hidden_fields(cl)),
            'result_headers': list(result_headers(cl)),
            'results': list(mptt_results(cl))}

# custom template is merely so we can strip out sortable-ness from the column headers
# Based on admin/change_list_results.html (1.3.1)
if IS_GRAPPELLI_INSTALLED:
    mptt_result_list = register.inclusion_tag(
        "admin/grappelli_mptt_change_list_results.html")(mptt_result_list)
else:
    mptt_result_list = register.inclusion_tag(
        "admin/mptt_change_list_results.html")(mptt_result_list)
<commit_msg>Prevented DeprecationWarning with django.core.urlresolvers<commit_after>from __future__ import unicode_literals

import datetime
import warnings

from django.conf import settings
from django.contrib.admin.templatetags.admin_list import (
    result_hidden_fields, result_headers)
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.contrib.admin.utils import (
    display_for_field, display_for_value, lookup_field)
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.template import Library
try:
    from django.urls import NoReverseMatch
except ImportError:  # Django < 1.10 pragma: no cover
    from django.core.urlresolvers import NoReverseMatch
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import get_language_bidi

register = Library()

MPTT_ADMIN_LEVEL_INDENT = getattr(settings, 'MPTT_ADMIN_LEVEL_INDENT', 10)
IS_GRAPPELLI_INSTALLED = True if 'grappelli' in settings.INSTALLED_APPS else False

###
# Ripped from contrib.admin (1.10)
def _coerce_field_name(field_name, field_index):
    """
    Coerce a field_name (which may be a callable) to a string.
    """
    if callable(field_name):
        if field_name.__name__ == '<lambda>':
            return 'lambda' + str(field_index)
        else:
            return field_name.__name__
    return field_name

def get_empty_value_display(cl):
    if hasattr(cl.model_admin, 'get_empty_value_display'):
        return cl.model_admin.get_empty_value_display()
    else:
        # Django < 1.9
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        return EMPTY_CHANGELIST_VALUE

###
# Ripped from contrib.admin's (1.10) items_for_result tag.
# The only difference is we're indenting nodes according to their level.
def mptt_items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """

    def link_in_col(is_first, field_name, cl):
        if cl.list_display_links is None:
            return False
        if is_first and not cl.list_display_links:
            return True
        return field_name in cl.list_display_links

    first = True
    pk = cl.lookup_opts.pk.attname

    # #### MPTT ADDITION START
    # figure out which field to indent
    mptt_indent_field = getattr(cl.model_admin, 'mptt_indent_field', None)
    if not mptt_indent_field:
        for field_name in cl.list_display:
            try:
                f = cl.lookup_opts.get_field(field_name)
            except models.FieldDoesNotExist:
                if (mptt_indent_field is None and
                        field_name != 'action_checkbox'):
                    mptt_indent_field = field_name
            else:
                # first model field, use this one
                mptt_indent_field = field_name
                break

    # figure out how much to indent
    mptt_level_indent = getattr(cl.model_admin, 'mptt_level_indent', MPTT_ADMIN_LEVEL_INDENT)
    # #### MPTT ADDITION END

    for field_index, field_name in enumerate(cl.list_display):
        # #### MPTT SUBSTITUTION START
        empty_value_display = get_empty_value_display(cl)
        # #### MPTT SUBSTITUTION END
        row_classes = ['field-%s' % _coerce_field_name(field_name, field_index)]
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, 'empty_value_display', empty_value_display)
            if f is None or f.auto_created:
                if field_name == 'action_checkbox':
                    row_classes = ['action-checkbox']
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                # #### MPTT SUBSTITUTION START
                try:
                    # Changed in Django 1.9, now takes 3 arguments
                    result_repr = display_for_value(
                        value, empty_value_display, boolean)
                except TypeError:
                    result_repr = display_for_value(value, boolean)
                # #### MPTT SUBSTITUTION END
                if allow_tags:
                    warnings.warn(
                        "Deprecated allow_tags attribute used on field {}. "
                        "Use django.utils.safestring.format_html(), "
                        "format_html_join(), or mark_safe() instead.".format(field_name),
                        RemovedInDjango20Warning
                    )
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                # #### MPTT SUBSTITUTION START
                try:
                    is_many_to_one = isinstance(
                        f.remote_field, models.ManyToOneRel)
                except AttributeError:
                    is_many_to_one = isinstance(f.rel, models.ManyToOneRel)
                if is_many_to_one:
                    # #### MPTT SUBSTITUTION END
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    # #### MPTT SUBSTITUTION START
                    try:
                        result_repr = display_for_field(value, f)
                    except TypeError:
                        # Changed in Django 1.9, now takes 3 arguments
                        result_repr = display_for_field(
                            value, f, empty_value_display)
                    # #### MPTT SUBSTITUTION END
                if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if force_text(result_repr) == '':
            result_repr = mark_safe(' ')
        row_class = mark_safe(' class="%s"' % ' '.join(row_classes))

        # #### MPTT ADDITION START
        if field_name == mptt_indent_field:
            level = getattr(result, result._mptt_meta.level_attr)
            padding_attr = mark_safe(' style="padding-%s:%spx"' % (
                'right' if get_language_bidi() else 'left',
                8 + mptt_level_indent * level))
        else:
            padding_attr = ''
        # #### MPTT ADDITION END

        # If list_display_links not defined, add the link tag to the first field
        if link_in_col(first, field_name, cl):
            table_tag = 'th' if first else 'td'
            first = False

            # Display link to the result's change_view if the url exists, else
            # display just the result's representation.
            try:
                url = cl.url_for_result(result)
            except NoReverseMatch:
                link_or_text = result_repr
            else:
                url = add_preserved_filters({'preserved_filters': cl.preserved_filters, 'opts': cl.opts}, url)
                # Convert the pk to something that can be used in Javascript.
                # Problem cases are long ints (23L) and non-ASCII strings.
                if cl.to_field:
                    attr = str(cl.to_field)
                else:
                    attr = pk
                value = result.serializable_value(attr)
                link_or_text = format_html(
                    '{}',
                    url,
                    format_html(
                        ' data-popup-opener="{}"', value
                    ) if cl.is_popup else '',
                    result_repr)

            # #### MPTT SUBSTITUTION START
            yield format_html('<{}{}{}>{}</{}>',
                              table_tag,
                              row_class,
                              padding_attr,
                              link_or_text,
                              table_tag)
            # #### MPTT SUBSTITUTION END
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if (form and field_name in form.fields and not (
                    field_name == cl.model._meta.pk.name and
                    form[cl.model._meta.pk.name].is_hidden)):
                bf = form[field_name]
                result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
            # #### MPTT SUBSTITUTION START
            yield format_html('{}	', row_class, padding_attr, result_repr)
            # #### MPTT SUBSTITUTION END
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield format_html('{}	', force_text(form[cl.model._meta.pk.name]))

def mptt_results(cl):
    if cl.formset:
        for res, form in zip(cl.result_list, cl.formset.forms):
            yield list(mptt_items_for_result(cl, res, form))
    else:
        for res in cl.result_list:
            yield list(mptt_items_for_result(cl, res, None))

def mptt_result_list(cl):
    """
    Displays the headers and data list together
    """
    return {'cl': cl,
            'result_hidden_fields': list(result_hidden_fields(cl)),
            'result_headers': list(result_headers(cl)),
            'results': list(mptt_results(cl))}

# custom template is merely so we can strip out sortable-ness from the column headers
# Based on admin/change_list_results.html (1.3.1)
if IS_GRAPPELLI_INSTALLED:
    mptt_result_list = register.inclusion_tag(
        "admin/grappelli_mptt_change_list_results.html")(mptt_result_list)
else:
    mptt_result_list = register.inclusion_tag(
        "admin/mptt_change_list_results.html")(mptt_result_list)
<|endoftext|>


<commit_before>"""
=========================
Getting started with Dipy
=========================

In diffusion MRI (dMRI) usually use three types of files the a Nifti file with the
diffusion weighted data (*.nii.gz), and two text files one with b-values and
one for the b-vectors.

In Dipy we provide tools to load and process these files and we also provide
access to publically available datasets for those who haven't acquired yet
their own datasets.

With the followin commands we will download a dMRI dataset
"""

from dipy.data import fetch_sherbrooke_3shell
fetch_sherbrooke_3shell()

"""
By default these datasets will go in the .dipy folder inside your home directory.
Here is how you can access them.
"""

from os.path import expanduser, join
home = expanduser('~')

"""
``dname`` holds the directory name where the 3 files are in.
"""

dname = join(home, '.dipy', 'sherbrooke_3shell')

"""
Here, we show the complete filenames of the 3 files
"""

fdwi = join(dname, 'HARDI193.nii.gz')

print(fdwi)

fbval = join(dname, 'HARDI193.bval')

print(fbval)

fbvec = join(dname, 'HARDI193.bvec')

print(fbvec)

"""
/home/username/.dipy/sherbrooke_3shell/HARDI193.nii.gz

/home/username/.dipy/sherbrooke_3shell/HARDI193.bval

/home/username/.dipy/sherbrooke_3shell/HARDI193.bvec

Now, that we have the filenames we can start doing some processing

Lets, start first by loading the dMRI datasets. For this purpose we
can use nibabel.
"""

import nibabel as nib
img = nib.load(fdwi)
data = img.get_data()

"""
``data`` is a 4D array where the first 3 dimensions are the i, j, k voxel
positions and the last dimension is the number of non-weighted (S0s) and
diffusion waited volumes.

We can very easily check the size of ``data`` in the following way
"""

print(data.shape)

"""
``(128, 128, 60, 194)``

We can also check the dimensions of each voxel in the following way

"""

print(img.get_header().get_zooms()[:3])

"""
``(2.0, 2.0, 2.0)``

We can quickly visualize the results using ``matplotlib``. For example,
let's show here the middle axial slices of volume 0 and volume 10.
"""

import matplotlib.pyplot as plt

axial_middle = data.shape[2] / 2
plt.figure('Showing the datasets')
plt.subplot(1, 2, 1).set_axis_off()
plt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower')
plt.subplot(1, 2, 2).set_axis_off()
plt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower')
plt.show()
plt.savefig('data.png', bbox_inches='tight')

"""
.. figure:: data.png
   :align: center

   **Showing the middle axial without (left) and with (right) diffusion weighting**.

The next step is to load the b-values and b-vectors from the disk using
the function ``read_bvals_bvecs``.
"""

from dipy.io import read_bvals_bvecs
bvals, bvecs = read_bvals_bvecs(fbval, fbvec)

"""
In Dipy we use an object called GradientTable which holds all in good form all the
acquision specific parameters e.g. b-values, b-vectors, timings and others. To create this
object you can use the function ``gradient_table``.
"""

from dipy.core.gradients import gradient_table
gtab = gradient_table(bvals, bvecs)

"""
Finally, you can use ``gtab`` (the GradientTable object) to show some information about the
acquisition parameters
"""

print(gtab.info)

"""
B-values shape (193,)
         min 0.000000
         max 3500.000000
B-vectors shape (193, 3)
         min -0.964050
         max 0.999992

You, can also see the b-values using:
"""

print(gtab.bvals)

"""

::

    [    0.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.]

Or, for example the 10 first b-vectors using:
"""

print(gtab.bvecs[:10, :])

"""

::

    array([[ 0.        ,  0.        ,  0.        ],
           [ 0.999979  , -0.00504001, -0.00402795],
           [ 0.        ,  0.999992  , -0.00398794],
           [-0.0257055 ,  0.653861  , -0.756178  ],
           [ 0.589518  , -0.769236  , -0.246462  ],
           [-0.235785  , -0.529095  , -0.815147  ],
           [-0.893578  , -0.263559  , -0.363394  ],
           [ 0.79784   ,  0.133726  , -0.587851  ],
           [ 0.232937  ,  0.931884  , -0.278087  ],
           [ 0.93672   ,  0.144139  , -0.31903   ]])

``gtab`` can tell in which place in your dataset you had S0 volumes
(volumes which correspond to b-values of 0).
"""

S0s = data[:, :, :, gtab.b0s_mask]

"""
Here, we had only 1 S0 as we can see by looking at the dimension of S0s
"""

print(S0s.shape)

"""
``(128, 128, 60, 1)``

Just, for fun let's save this in a new Nifti1 file.
"""

nib.save(nib.Nifti1Image(S0s, img.get_affine()), 'HARDI193_S0.nii.gz')

"""
Now, that we learned how to load dMRI datasets we can start the analysis.
See example :ref:`example_reconst_dti` to learn how to create Tensors.
"""
<commit_msg>DOC: corrected some language mistakes and typos<commit_after>"""
=========================
Getting started with Dipy
=========================

In diffusion MRI (dMRI) usually we use three types of files, a Nifti file with the
diffusion weighted data (*.nii.gz), and two text files one with b-values and
one with the b-vectors.

In Dipy we provide tools to load and process these files and we also provide
access to publically available datasets for those who haven't acquired yet
their own datasets.

With the following commands we can download a dMRI dataset
"""

from dipy.data import fetch_sherbrooke_3shell
fetch_sherbrooke_3shell()

"""
By default these datasets will go in the .dipy folder inside your home directory.
Here is how you can access them.
"""

from os.path import expanduser, join
home = expanduser('~')

"""
``dname`` holds the directory name where the 3 files are in.
"""

dname = join(home, '.dipy', 'sherbrooke_3shell')

"""
Here, we show the complete filenames of the 3 files
"""

fdwi = join(dname, 'HARDI193.nii.gz')

print(fdwi)

fbval = join(dname, 'HARDI193.bval')

print(fbval)

fbvec = join(dname, 'HARDI193.bvec')

print(fbvec)

"""
``/home/username/.dipy/sherbrooke_3shell/HARDI193.nii.gz``

``/home/username/.dipy/sherbrooke_3shell/HARDI193.bval``

``/home/username/.dipy/sherbrooke_3shell/HARDI193.bvec``

Now, that we have their filenames we can start checking how these look like.

Let's start first by loading the dMRI datasets. For this purpose we can use
the Python module called ``nibabel``.
"""

import nibabel as nib
img = nib.load(fdwi)
data = img.get_data()

"""
``data`` is a 4D array where the first 3 dimensions are the i, j, k voxel
positions and the last dimension is the number of non-weighted (S0s) and
diffusion waited volumes.

We can very easily check the size of ``data`` in the following way:
"""

print(data.shape)

"""
``(128, 128, 60, 194)``

We can also check the dimensions of each voxel in the following way:
"""

print(img.get_header().get_zooms()[:3])

"""
``(2.0, 2.0, 2.0)``

We can quickly visualize the results using ``matplotlib``. For example,
let's show here the middle axial slices of volume 0 and volume 10.
"""

import matplotlib.pyplot as plt

axial_middle = data.shape[2] / 2
plt.figure('Showing the datasets')
plt.subplot(1, 2, 1).set_axis_off()
plt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower')
plt.subplot(1, 2, 2).set_axis_off()
plt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower')
plt.show()
plt.savefig('data.png', bbox_inches='tight')

"""
.. figure:: data.png
   :align: center

   **Showing the middle axial slice without (left) and with (right) diffusion weighting**.

The next step is to load the b-values and b-vectors from the disk using
the function ``read_bvals_bvecs``.
"""

from dipy.io import read_bvals_bvecs
bvals, bvecs = read_bvals_bvecs(fbval, fbvec)

"""
In Dipy, we use an object called ``GradientTable`` which holds in a form that
Dipy understands, all the acquision specific parameters, e.g. b-values,
b-vectors, timings and others. To create this object you can use the
function ``gradient_table``.
"""

from dipy.core.gradients import gradient_table
gtab = gradient_table(bvals, bvecs)

"""
Finally, you can use ``gtab`` (the GradientTable object) to show some information about the
acquisition parameters
"""

print(gtab.info)

"""
B-values shape (193,)
         min 0.000000
         max 3500.000000
B-vectors shape (193, 3)
         min -0.964050
         max 0.999992

You, can also see the b-values using:
"""

print(gtab.bvals)

"""

::

    [    0.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.  1000.
      1000.  1000.  1000.  1000.  1000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.
      2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  2000.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.  3500.
      3500.  3500.  3500.]

Or, for example the 10 first b-vectors using:
"""

print(gtab.bvecs[:10, :])

"""

::

    array([[ 0.        ,  0.        ,  0.        ],
           [ 0.999979  , -0.00504001, -0.00402795],
           [ 0.        ,  0.999992  , -0.00398794],
           [-0.0257055 ,  0.653861  , -0.756178  ],
           [ 0.589518  , -0.769236  , -0.246462  ],
           [-0.235785  , -0.529095  , -0.815147  ],
           [-0.893578  , -0.263559  , -0.363394  ],
           [ 0.79784   ,  0.133726  , -0.587851  ],
           [ 0.232937  ,  0.931884  , -0.278087  ],
           [ 0.93672   ,  0.144139  , -0.31903   ]])

``gtab`` can tell in which place in your dataset you had S0 volumes
(volumes which correspond to b-values of 0).
"""

S0s = data[:, :, :, gtab.b0s_mask]

"""
Here, we had only 1 S0 as we can verify by looking at the dimensions of S0s
"""

print(S0s.shape)

"""
``(128, 128, 60, 1)``

Just, for fun let's save this in a new Nifti file.
"""

nib.save(nib.Nifti1Image(S0s, img.get_affine()), 'HARDI193_S0.nii.gz')

"""
Now, that we learned how to load dMRI datasets we can start the analysis.
See example :ref:`example_reconst_dti` to learn how to create FA maps.
"""
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from openerp import fields, models, api

class Partner(models.Model):
    _inherit = 'res.partner'

    allocation_ids = fields.One2many('mqo.allocation', 'partner_id', string="Allocated Exercises")
    assignment_ids = fields.One2many('mqo.assignment', 'partner_id', string="Assigned Exercises")

    next_exercise_id = fields.Many2one(comodel_name='mqo.exercise', store=True, readonly=True, compute='_compute_next_exercise')

    @api.depends('allocation_ids')
    def _compute_next_allocation(self):
        for r in self:
            next_exercise_collection = []
            if r.allocation_ids:
                next_exercise_collection.append(r.allocation_ids[0].exercise_id)
            r.next_exercise_id = next_exercise_collection<commit_msg>Realised I hadn't correctly specified the function name.<commit_after># -*- coding: utf-8 -*-
from openerp import fields, models, api

class Partner(models.Model):
    _inherit = 'res.partner'

    allocation_ids = fields.One2many('mqo.allocation', 'partner_id', string="Allocated Exercises")
    assignment_ids = fields.One2many('mqo.assignment', 'partner_id', string="Assigned Exercises")

    next_exercise_id = fields.Many2one(comodel_name='mqo.allocation', store=True, readonly=True, compute='_compute_next_allocation')

    @api.depends('allocation_ids')
    def _compute_next_allocation(self):
        for r in self:
            next_allocation_collection = []
            if r.allocation_ids:
                next_allocation_collection.append(r.allocation_ids[0])
            r.next_exercise_id = next_allocation_collection<|endoftext|>


<commit_before>import numpy as np
# import nibabel as nib
from dipy.reconst.opt_msd import MultiShellResponse
from dipy.reconst.csdeconv import auto_response
from dipy.io import read_bvals_bvecs
from dipy.core.gradients import gradient_table
from dipy.segment.tissue import TissueClassifierHMRF
from dipy.io.image import load_nifti, save_nifti
from dipy.segment.mask import median_otsu
from dipy.sims.voxel import (single_tensor)
from dipy.reconst import shm
from dipy.data import default_sphere
from dipy.core.gradients import GradientTable
from dipy.denoise.nlmeans import nlmeans
from dipy.denoise.noise_estimate import estimate_sigma
import dipy.reconst.dti as dti
from dipy.reconst.opt_msd import MultiShellDeconvModel
from dipy.viz import window, actor
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')

def show_slicer_and_pick(data, affine):
    from dipy.viz import window, actor, ui

    im_actor = actor.slicer(data, affine)
    shape = data.shape

    renderer = window.Renderer()
    renderer.projection('parallel')
    show_m = window.ShowManager(renderer, size=(1200, 900))
    show_m.initialize()
    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    def change_slice_z(slider):
        z = int(np.round(slider.value))
        im_actor.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)
        show_m.ren.reset_camera()
        show_m.ren.reset_clipping_range()
        show_m.render()

    line_slider_z.on_change = change_slice_z

    label_position = ui.TextBlock2D(text='Position:')
    label_value = ui.TextBlock2D(text='Value:')
    result_position = ui.TextBlock2D(text='')
    result_value = ui.TextBlock2D(text='')

    panel_picking = ui.Panel2D(size=(250, 225),
                               position=(20, 20),
                               color=(0, 0, 0),
                               opacity=0.75,
                               align="left")

    panel_picking.add_element(label_position, (0.1, 0.55))
    panel_picking.add_element(label_value, (0.1, 0.25))
    panel_picking.add_element(result_position, (0.45, 0.55))
    panel_picking.add_element(result_value, (0.45, 0.25))
    panel_picking.add_element(line_slider_z, (0.1, 0.75))
    show_m.ren.add(panel_picking)

    def left_click_callback(obj, ev):
        """Get the value of the clicked voxel and show it in the panel."""
        event_pos = show_m.iren.GetEventPosition()

        obj.picker.Pick(event_pos[0],
                        event_pos[1],
                        0,
                        show_m.ren)

        i, j, k = obj.picker.GetPointIJK()
        result_position.message = '({}, {}, {})'.format(str(i), str(j), str(k))
        result_value.message = '%.8f' % data[i, j, k]

    im_actor.SetInterpolate(False)
    im_actor.AddObserver('LeftButtonPressEvent', left_click_callback, 1.0)

    show_m.ren.add(im_actor)
    show_m.ren.reset_camera()
    show_m.ren.reset_clipping_range()
    show_m.render()
    show_m.start()

# static file paths for experiments
fbvals = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fd0.neuro-dwi/dwi.bvals'
fbvecs = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fd0.neuro-dwi/dwi.bvecs'
fdwi = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fd0.neuro-dwi/dwi.nii.gz'
ft1 = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fcf.neuro-anat-t1w.acpc_aligned/t1.nii.gz'

t1, t1_affine = load_nifti(ft1)

dwi, dwi_affine = load_nifti(fdwi)
b0_mask, mask = median_otsu(dwi)

# t1[mask == 0] = 0

print("Data Loaded!")

"""
Now we will define the other two parameters for the segmentation algorithm.
We will segment three classes, namely corticospinal fluid (CSF), white matter
(WM) and gray matter (GM).
"""
nclass = 3
"""
Then, the smoothness factor of the segmentation. Good performance is achieved
with values between 0 and 0.5.
"""
beta = 0.1

# denoising
sigma = estimate_sigma(t1, True, N=4)

t1[mask == 0] = 0

t1_den = nlmeans(t1, sigma=sigma)

# save_nifti('t1_masked.nii.gz', t1, t1_affine)
# save_nifti('t1_class_masked.nii.gz', PVE, t1_affine)

bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
gtab = gradient_table(bvals, bvecs)

# fitting the model with DTI
tenmodel = dti.TensorModel(gtab)
tenfit = tenmodel.fit(dwi, mask)

# save_nifti('t1_denoised.nii.gz', t1_den, t1_affine)

# getting the mean diffusivities and FAs from DTI
FA = tenfit.fa
MD = tenfit.md

hmrf = TissueClassifierHMRF()
initial_segmentation, final_segmentation, PVE = hmrf.classify(t1_den, nclass,
                                                              beta)

csf = PVE[..., 0]
cgm = PVE[..., 1]

save_nifti('pve.nii.gz', PVE, dwi_affine)

indices_csf = np.where(((FA < 0.2) & (csf > 0.95)))
indices_cgm = np.where(((FA < 0.2) & (cgm > 0.95)))

selected_csf = np.zeros(FA.shape, dtype='bool')
selected_cgm = np.zeros(FA.shape, dtype='bool')

selected_csf[indices_csf] = True
selected_cgm[indices_cgm] = True

csf_md = np.mean(tenfit.md[selected_csf])
cgm_md = np.mean(tenfit.md[selected_cgm])

# save_nifti('selected_csf.nii.gz', selected_csf, dwi_affine)
# save_nifti('selected_cgm.nii.gz', selected_cgm, dwi_affine)

save_nifti('md.nii.gz', MD, dwi_affine)
save_nifti('fa.nii.gz', FA, dwi_affine)

# center = np.zeros(FA.shape)
# center[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75 - 10: 75 + 10] = 1
# save_nifti('center.nii.gz', center, dwi_affine)

# generating the autoresponse
dwi[mask == 0] = 0
response, ratio = auto_response(gtab, dwi, roi_radius=10, fa_thr=0.7)
evals_d = response[0]

def sim_response(sh_order=8, bvals=bvals, evals=evals_d, csf_md=csf_md,
                 gm_md=cgm_md):
    bvals = np.array(bvals, copy=True)
    evecs = np.zeros((3, 3))
    z = np.array([0, 0, 1.])
    evecs[:, 0] = z
    evecs[:2, 1:] = np.eye(2)

    n = np.arange(0, sh_order + 1, 2)
    m = np.zeros_like(n)

    big_sphere = default_sphere.subdivide()
    theta, phi = big_sphere.theta, big_sphere.phi

    B = shm.real_sph_harm(m, n, theta[:, None], phi[:, None])
    A = shm.real_sph_harm(0, 0, 0, 0)

    response = np.empty([len(bvals), len(n) + 2])
    for i, bvalue in enumerate(bvals):
        gtab = GradientTable(big_sphere.vertices * bvalue)
        wm_response = single_tensor(gtab, 1., evals, evecs, snr=None)
        response[i, 2:] = np.linalg.lstsq(B, wm_response)[0]

        response[i, 0] = np.exp(-bvalue * csf_md) / A
        response[i, 1] = np.exp(-bvalue * gm_md) / A

    return MultiShellResponse(response, sh_order, bvals)

response_msd = sim_response(sh_order=4, bvals=bvals, evals=evals_d,
                            csf_md=csf_md, gm_md=cgm_md)

msd_model = MultiShellDeconvModel(gtab, response_msd)

# data = dwi[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75: 75 + 10]
# data = dwi[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75: 75 + 10]

data = dwi[:, :, 68: 68 + 1]

# odf_mask[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75: 75 + 1] = 1

msd_fit = msd_model.fit(data)
msd_odf = msd_fit.odf(sphere)
fodf_spheres = actor.odf_slicer(msd_odf, sphere=sphere, scale=0.9, norm=True,
                                colormap='plasma')
interactive = True
ren = window.Renderer()
ren.add(fodf_spheres)

print('Saving illustration as msd_odfs.png')
window.record(ren, out_path='msd_odfs.png', size=(600, 600))
if interactive:
    window.show(ren)
<commit_msg>working one slice<commit_after>import numpy as np
from dipy.reconst.opt_msd import MultiShellResponse
from dipy.reconst.csdeconv import auto_response
from dipy.io import read_bvals_bvecs
from dipy.core.gradients import gradient_table
from dipy.segment.tissue import TissueClassifierHMRF
from dipy.io.image import load_nifti, save_nifti
from dipy.segment.mask import median_otsu
from dipy.sims.voxel import (single_tensor)
from dipy.reconst import shm
from dipy.data import default_sphere
from dipy.core.gradients import GradientTable
from dipy.denoise.nlmeans import nlmeans
from dipy.denoise.noise_estimate import estimate_sigma
import dipy.reconst.dti as dti
from dipy.reconst.opt_msd import MultiShellDeconvModel
from dipy.viz import window, actor
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')

def show_slicer_and_pick(data, affine):
    from dipy.viz import window, actor, ui

    im_actor = actor.slicer(data, affine)
    shape = data.shape

    renderer = window.Renderer()
    renderer.projection('parallel')
    show_m = window.ShowManager(renderer, size=(1200, 900))
    show_m.initialize()
    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    def change_slice_z(slider):
        z = int(np.round(slider.value))
        im_actor.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)
        show_m.ren.reset_camera()
        show_m.ren.reset_clipping_range()
        show_m.render()

    line_slider_z.on_change = change_slice_z

    label_position = ui.TextBlock2D(text='Position:')
    label_value = ui.TextBlock2D(text='Value:')
    result_position = ui.TextBlock2D(text='')
    result_value = ui.TextBlock2D(text='')

    panel_picking = ui.Panel2D(size=(250, 225),
                               position=(20, 20),
                               color=(0, 0, 0),
                               opacity=0.75,
                               align="left")

    panel_picking.add_element(label_position, (0.1, 0.55))
    panel_picking.add_element(label_value, (0.1, 0.25))
    panel_picking.add_element(result_position, (0.45, 0.55))
    panel_picking.add_element(result_value, (0.45, 0.25))
    panel_picking.add_element(line_slider_z, (0.1, 0.75))
    show_m.ren.add(panel_picking)

    def left_click_callback(obj, ev):
        """Get the value of the clicked voxel and show it in the panel."""
        event_pos = show_m.iren.GetEventPosition()

        obj.picker.Pick(event_pos[0],
                        event_pos[1],
                        0,
                        show_m.ren)

        i, j, k = obj.picker.GetPointIJK()
        result_position.message = '({}, {}, {})'.format(str(i), str(j), str(k))
        result_value.message = '%.8f' % data[i, j, k]

    im_actor.SetInterpolate(False)
    im_actor.AddObserver('LeftButtonPressEvent', left_click_callback, 1.0)

    show_m.ren.add(im_actor)
    show_m.ren.reset_camera()
    show_m.ren.reset_clipping_range()
    show_m.render()
    show_m.start()

# static file paths for experiments
fbvals = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fd0.neuro-dwi/dwi.bvals'
fbvecs = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fd0.neuro-dwi/dwi.bvecs'
fdwi = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fd0.neuro-dwi/dwi.nii.gz'
ft1 = '/home/shreyasfadnavis/Data/HCP/BL/sub-100408/598a2aa44258600aa3128fcf.neuro-anat-t1w.acpc_aligned/t1.nii.gz'

t1, t1_affine = load_nifti(ft1)

dwi, dwi_affine = load_nifti(fdwi)
b0_mask, mask = median_otsu(dwi)

# t1[mask == 0] = 0

print("Data Loaded!")

"""
Now we will define the other two parameters for the segmentation algorithm.
We will segment three classes, namely corticospinal fluid (CSF), white matter
(WM) and gray matter (GM).
"""
nclass = 3
"""
Then, the smoothness factor of the segmentation. Good performance is achieved
with values between 0 and 0.5.
"""
beta = 0.1

# denoising
sigma = estimate_sigma(t1, True, N=4)

t1[mask == 0] = 0

t1_den = nlmeans(t1, sigma=sigma)

# save_nifti('t1_masked.nii.gz', t1, t1_affine)
# save_nifti('t1_class_masked.nii.gz', PVE, t1_affine)

bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
gtab = gradient_table(bvals, bvecs)

# fitting the model with DTI
tenmodel = dti.TensorModel(gtab)
tenfit = tenmodel.fit(dwi, mask)

# save_nifti('t1_denoised.nii.gz', t1_den, t1_affine)

# getting the mean diffusivities and FAs from DTI
FA = tenfit.fa
MD = tenfit.md

hmrf = TissueClassifierHMRF()
initial_segmentation, final_segmentation, PVE = hmrf.classify(t1_den, nclass,
                                                              beta)

csf = PVE[..., 0]
cgm = PVE[..., 1]

save_nifti('pve.nii.gz', PVE, dwi_affine)

indices_csf = np.where(((FA < 0.2) & (csf > 0.95)))
indices_cgm = np.where(((FA < 0.2) & (cgm > 0.95)))

selected_csf = np.zeros(FA.shape, dtype='bool')
selected_cgm = np.zeros(FA.shape, dtype='bool')

selected_csf[indices_csf] = True
selected_cgm[indices_cgm] = True

csf_md = np.mean(tenfit.md[selected_csf])
cgm_md = np.mean(tenfit.md[selected_cgm])

# save_nifti('selected_csf.nii.gz', selected_csf, dwi_affine)
# save_nifti('selected_cgm.nii.gz', selected_cgm, dwi_affine)

save_nifti('md.nii.gz', MD, dwi_affine)
save_nifti('fa.nii.gz', FA, dwi_affine)

# center = np.zeros(FA.shape)
# center[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75 - 10: 75 + 10] = 1
# save_nifti('center.nii.gz', center, dwi_affine)

# generating the autoresponse
dwi[mask == 0] = 0
response, ratio = auto_response(gtab, dwi, roi_radius=10, fa_thr=0.7)
evals_d = response[0]

def sim_response(sh_order=8, bvals=bvals, evals=evals_d, csf_md=csf_md,
                 gm_md=cgm_md):
    bvals = np.array(bvals, copy=True)
    evecs = np.zeros((3, 3))
    z = np.array([0, 0, 1.])
    evecs[:, 0] = z
    evecs[:2, 1:] = np.eye(2)

    n = np.arange(0, sh_order + 1, 2)
    m = np.zeros_like(n)

    big_sphere = default_sphere.subdivide()
    theta, phi = big_sphere.theta, big_sphere.phi

    B = shm.real_sph_harm(m, n, theta[:, None], phi[:, None])
    A = shm.real_sph_harm(0, 0, 0, 0)

    response = np.empty([len(bvals), len(n) + 2])
    for i, bvalue in enumerate(bvals):
        gtab = GradientTable(big_sphere.vertices * bvalue)
        wm_response = single_tensor(gtab, 1., evals, evecs, snr=None)
        response[i, 2:] = np.linalg.lstsq(B, wm_response)[0]

        response[i, 0] = np.exp(-bvalue * csf_md) / A
        response[i, 1] = np.exp(-bvalue * gm_md) / A

    return MultiShellResponse(response, sh_order, bvals)

response_msd = sim_response(sh_order=4, bvals=bvals, evals=evals_d,
                            csf_md=csf_md, gm_md=cgm_md)

msd_model = MultiShellDeconvModel(gtab, response_msd)

# data = dwi[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75: 75 + 10]
# data = dwi[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75: 75 + 10]

data = dwi[:, :, 68: 68 + 1]
mask_tmp = mask[:, :, 68: 68 + 1]

# odf_mask[63 - 10: 63 + 10, 113 - 10: 113 + 10, 75: 75 + 1] = 1

msd_fit = msd_model.fit(data, mask_tmp)
msd_odf = msd_fit.odf(sphere)
fodf_spheres = actor.odf_slicer(msd_odf, mask=mask_tmp,
                                sphere=sphere, scale=0.7, norm=True,
                                colormap='plasma')
interactive = True
ren = window.Renderer()
ren.add(fodf_spheres)

print('Saving illustration as msd_odfs.png')
window.record(ren, out_path='msd_odfs.png', size=(600, 600), magnification=4)
if interactive:
    window.show(ren)
<|endoftext|>