Пример #1
0
 def test_empty_tree(self):
     node = None
     self.tree = Tree(node)
     self.answer = "The tree is empty!"
     self.assertEqual(self.tree.print_tree(), self.answer)
Пример #2
0
class MarvinConfig(object):
    ''' Global Marvin Configuration

    The global configuration of Marvin.  Use the config object to globally set options for
    your Marvin session.

    Parameters:
        release (str):
            The release version of the MaNGA data you want to use.  Either MPL or DR.
        access (str):
            The type of access Marvin is allowed.  Either public or collab.
        download (bool):
            Set to turn on downloading of objects with sdss_access
        use_sentry (bool):
            Set to turn on/off the Sentry error logging.  Default is True.
        add_github_message (bool):
            Set to turn on/off the additional Github Issue message in MarvinErrors. Default is True.
        drpall (str):
            The location to your DRPall file, based on which release you have set.
        mode (str):
            The current mode of Marvin.  Either 'auto', 'remote', or 'local'. Default is 'auto'
        sasurl (str):
            The url of the Marvin API on the Utah Science Archive Server (SAS)
        urlmap (dict):
            A dictionary containing the API routing information used by Marvin
        xyorig (str):
            Globally set the origin point for all your spaxel selections.  Either 'center' or 'lower'.
            Default is 'center'
    '''
    def __init__(self):

        self._custom_config = None
        self._drpall = None
        self._inapp = False

        self._urlmap = None
        self._xyorig = None

        self._release = None

        self.vermode = None
        self.download = False
        self.use_sentry = True
        self.add_github_message = True
        self._allowed_releases = {}

        # Allow DAP queries
        self._allow_DAP_queries = False

        # perform some checks
        self._load_defaults()
        self._check_access()
        self._check_config()
        self._setDbConfig()

        # setup some paths
        self._plantTree()
        self._checkSDSSAccess()
        self._check_manga_dirs()
        self.setDefaultDrpAll()

    def _load_defaults(self):
        ''' Loads marvin configuration parameters

        Loads Marvin config parameters from the default marvin.yml file
        located in /data and merges with the user config parameters in
        ~/.marvin/marvin.yml

        '''
        with open(os.path.join(os.path.dirname(__file__), 'data/marvin.yml'), 'r') as f:
            config = yaml.load(f, Loader=get_yaml_loader())
        user_config_path = os.path.expanduser('~/.marvin/marvin.yml')
        if os.path.exists(user_config_path):
            with open(user_config_path, 'r') as f:
                config = merge(yaml.load(f, Loader=get_yaml_loader()), config)

        # update any matching Config values
        for key, value in config.items():
            if hasattr(self, key):
                self.__setattr__(key, value)

        self._custom_config = config

    def _checkPaths(self, name):
        ''' Check for the necessary path existence.

            This should only run if someone already has TREE_DIR installed
            but somehow does not have a SAS_BASE_DIR, MANGA_SPECTRO_REDUX, or
            MANGA_SPECTRO_ANALYSIS directory
        '''

        # set the access work path
        workpath = 'mangawork' if self.access == 'collab' else self.release.lower()

        name = name.upper()
        if name not in os.environ:
            if name == 'SAS_BASE_DIR':
                path_dir = os.path.expanduser('~/sas')
            elif name == 'MANGA_SPECTRO_REDUX':
                path_dir = os.path.join(os.path.abspath(os.environ['SAS_BASE_DIR']), '{0}/manga/spectro/redux'.format(workpath))
            elif name == 'MANGA_SPECTRO_ANALYSIS':
                path_dir = os.path.join(os.path.abspath(os.environ['SAS_BASE_DIR']), '{0}/manga/spectro/analysis'.format(workpath))

            if not os.path.exists(path_dir):
                warnings.warn('no {0}_DIR found. Creating it in {1}'.format(name, path_dir))
                os.makedirs(path_dir)
            os.environ[name] = path_dir

    @staticmethod
    def set_custom_path(name, path):
        ''' Set a temporary custom environment variable path

        Custom define a new environment variable in the current
        os session.  Puts it in your os.environ.  To permanently
        set a custom variable, use your .bashrc or .cshrc file.

        Parameters:
            name (str):
                The name of the environment variable
            path (str):
                The file path
        '''
        name = name.upper()
        os.environ[name] = path

    def _check_access(self):
        """Makes sure there is a valid netrc."""

        autocheck = self._custom_config.get('check_access', None)
        token = self._custom_config.get('use_token', None)

        if autocheck:
            try:
                valid_netrc = bconfig._check_netrc()
            except BrainError as e:
                pass
            else:
                # if it's valid, then auto set to collaboration
                if valid_netrc:
                    self.access = 'collab'

            # check for a valid login token in the marvin config
            if token and isinstance(token, six.string_types):
                self.token = token

    def _check_manga_dirs(self):
        """Check if $SAS_BASE_DIR and MANGA dirs are defined.
           If they are not, creates and defines them.
        """

        self._checkPaths('SAS_BASE_DIR')
        self._checkPaths('MANGA_SPECTRO_REDUX')
        self._checkPaths('MANGA_SPECTRO_ANALYSIS')

    def setDefaultDrpAll(self, drpver=None):
        """Tries to set the default location of drpall.

        Sets the drpall attribute to the location of your DRPall file, based on the
        drpver.  If drpver not set, it is extracted from the release attribute.  It sets the
        location based on the MANGA_SPECTRO_REDUX environment variable

        Parameters:
            drpver (str):
                The DRP version to set.  Defaults to the version corresponding to config.release.
        """

        if not drpver:
            drpver, __ = self.lookUpVersions(self.release)
        self.drpall = self._getDrpAllPath(drpver)

    def _getDrpAllPath(self, drpver):
        """Returns the default path for drpall, give a certain ``drpver``."""

        if 'MANGA_SPECTRO_REDUX' in os.environ and drpver:
            return os.path.join(os.environ['MANGA_SPECTRO_REDUX'], str(drpver),
                                'drpall-{0}.fits'.format(drpver))
        else:
            raise MarvinError('Must have the MANGA_SPECTRO_REDUX environment variable set')

############ Brain Config overrides ############
# These are configuration parameter defined in Brain.bconfig. We need
# to be able to modify them during run time, so we define properties and
# setters to do that from Marvin.config.

    @property
    def mode(self):
        return bconfig.mode

    @mode.setter
    def mode(self, value):
        bconfig.mode = value

    @property
    def sasurl(self):
        return bconfig.sasurl

    @sasurl.setter
    def sasurl(self, value):
        bconfig.sasurl = value

    @property
    def release(self):
        return self._release

    @release.setter
    def release(self, value):
        value = value.upper()
        if value not in self._allowed_releases:
            raise MarvinError('trying to set an invalid release version. Valid releases are: {0}'
                              .format(', '.join(self._allowed_releases)))

        # set the new release and possibly replant the tree
        with self._replant_tree(value) as val:
            self._release = val

        if 'MANGA_SPECTRO_REDUX' in os.environ:
            drpver, __ = self.lookUpVersions(value)
            self.drpall = self._getDrpAllPath(drpver)

    @property
    def access(self):
        return bconfig.access

    @access.setter
    def access(self, value):
        bconfig.access = value

        # update and recheck the releases
        self._check_config()

    @property
    def session_id(self):
        return bconfig.session_id

    @session_id.setter
    def session_id(self, value):
        bconfig.session_id = value

    @property
    def _traceback(self):
        return bconfig.traceback

    @_traceback.setter
    def _traceback(self, value):
        bconfig.traceback = value

    @property
    def compression(self):
        return bconfig.compression

    @compression.setter
    def compression(self, value):
        bconfig.compression = value

    @property
    def token(self):
        return bconfig.token

    @token.setter
    def token(self, value):
        bconfig.token = value

#################################################

    @property
    def urlmap(self):
        """Retrieves the URLMap the first time it is needed."""

        if self._urlmap is None or (isinstance(self._urlmap, dict) and len(self._urlmap) == 0):
            try:
                response = Interaction('/marvin/api/general/getroutemap', request_type='get', auth='netrc')
            except Exception as e:
                warnings.warn('Cannot retrieve URLMap. Remote functionality will not work: {0}'.format(e),
                              MarvinUserWarning)
                self.urlmap = URLMapDict()
            else:
                self.urlmap = response.getRouteMap()

        return self._urlmap

    @urlmap.setter
    def urlmap(self, value):
        """Manually sets the URLMap."""
        self._urlmap = value
        arg_validate.urlmap = self._urlmap

    @property
    def xyorig(self):
        if not self._xyorig:
            self._xyorig = 'center'

        return self._xyorig

    @xyorig.setter
    def xyorig(self, value):

        assert value.lower() in ['center', 'lower'], 'xyorig must be center or lower.'

        self._xyorig = value.lower()

    @property
    def drpall(self):
        return self._drpall

    @drpall.setter
    def drpall(self, value):
        if os.path.exists(value):
            self._drpall = value
        else:
            self._drpall = None
            warnings.warn('path {0} cannot be found. Setting drpall to None.'
                          .format(value), MarvinUserWarning)

    def _setDbConfig(self):
        ''' Set the db configuration '''
        self.db = getDbMachine()

    def _update_releases(self):
        ''' Update the allowed releases based on access '''

        # define release dictionaries
        mpldict = {'MPL-8': ('v2_5_3', '2.3.0'),
                   'MPL-7': ('v2_4_3', '2.2.1'),
                   'MPL-6': ('v2_3_1', '2.1.3'),
                   'MPL-5': ('v2_0_1', '2.0.2'),
                   'MPL-4': ('v1_5_1', '1.1.1')}

        drdict = {'DR15': ('v2_4_3', '2.2.1')}

        # set the allowed releases based on access
        self._allowed_releases = {}
        if self.access == 'public':
            self._allowed_releases.update(drdict)
        elif self.access == 'collab':
            self._allowed_releases.update(drdict)
            self._allowed_releases.update(mpldict)

        # create and sort the final OrderedDict
        relsorted = sorted(self._allowed_releases.items(), key=lambda p: p[1][0], reverse=True)
        self._allowed_releases = OrderedDict(relsorted)

    def _get_latest_release(self, mpl_only=None):
        ''' Get the latest release from allowed list '''

        if mpl_only:
            return [r for r in list(self._allowed_releases) if 'MPL' in r][0]

        return list(self._allowed_releases)[0]

    def _check_config(self):
        ''' Check the release in the config '''

        # update the allowed releases
        self._update_releases()

        # check for a default release from the custom config
        default = 'default_release' in self._custom_config and self._custom_config['default_release']

        # Check for release version and if in allowed list
        latest = self._get_latest_release(mpl_only=self.access == 'collab')
        if not self.release:
            if default:
                self.setRelease(self._custom_config['default_release'])
            else:
                log.info('No release version set. Setting default to {0}'.format(latest))
                self.setRelease(latest)
        elif self.release and self.release not in self._allowed_releases:
            # this toggles to latest DR when switching to public
            warnings.warn('Release {0} is not in the allowed releases.  '
                          'Switching to {1}'.format(self.release, latest), MarvinUserWarning)

            self.setRelease(latest)

    def setRelease(self, version=None):
        """Set the release version.

        Parameters:
            version (str):
                The MPL/DR version to set, in form of MPL-X or DRXX.

        Example:
            >>> config.setRelease('MPL-4')
            >>> config.setRelease('DR13')

        """

        # if no version is set, pull the latest one by default
        if not version:
            version = self._get_latest_release()

        version = version.upper()
        self.release = version

    def setMPL(self, mplver):
        """As :func:`setRelease` but check that the version is an MPL."""

        assert 'MPL' in mplver.upper(), 'Must specify an MPL-X version!'
        self.setRelease(mplver)

    def setDR(self, drver):
        """As :func:`setRelease` but check that the version is a DR."""

        assert 'DR' in drver.upper(), 'Must specify a DRXX version!'
        self.setRelease(drver)

    def lookUpVersions(self, release=None):
        """Retrieve the DRP and DAP versions that make up a release version.

        Parameters:
            release (str or None):
                The release version. If ``None``, uses the currently set
                ``release`` value.

        Returns:
            drpver, dapver (tuple):
                A tuple of strings of the DRP and DAP versions according
                to the input MPL version

        """

        release = release or self.release

        try:
            drpver, dapver = self._allowed_releases[release]
        except KeyError:
            raise MarvinError('MPL/DR version {0} not found in lookup table. '
                              'No associated DRP/DAP versions. '
                              'Should they be added?  Check for typos.'.format(release))

        return drpver, dapver

    def lookUpRelease(self, drpver):
        """Retrieve the release version for a given DRP version

        Parameters:
            drpver (str):
                The DRP version to use
        Returns:
            release (str):
                The release version according to the input DRP version
        """

        # Flip the mpldict
        verdict = {val[0]: key for key, val in self._allowed_releases.items()}

        try:
            release = verdict[drpver]
        except KeyError:
            raise MarvinError('DRP version {0} not found in lookup table. '
                              'No associated MPL version. Should one be added?  '
                              'Check for typos.'.format(drpver))

        return release

    def switchSasUrl(self, sasmode='utah', ngrokid=None, port=5000, test=False,
                     base=None, public=None):
        ''' Switches the API SAS url config attribute

        Easily switch the sasurl configuration variable between
        utah and local.  utah sets it to the real API.  Local switches to
        use localhost.

        Parameters:
            sasmode ({'utah', 'local'}):
                the SAS mode to switch to.  Default is Utah
            ngrokid (str):
                The ngrok id to use when using a 'localhost' sas mode.
                This assumes localhost server is being broadcast by ngrok
            port (int):
                The port of your localhost server
            test (bool):
                If ``True``, sets the Utah sasurl to the test production, test/marvin
            base (str):
                The name of the marvin base.  Gets appended to main url.  Defaults to "marvin"
            public (bool):
                If ``True``, sets the API url to the public domain
        '''
        assert sasmode in ['utah', 'local'], 'SAS mode can only be utah or local'
        base = base if base else os.environ.get('MARVIN_BASE', 'marvin')
        test_domain = 'https://lore.sdss.utah.edu/'
        if sasmode == 'local':
            if ngrokid:
                self.sasurl = 'http://{0}.ngrok.io/'.format(ngrokid)
            else:
                self.sasurl = 'http://localhost:{0}/'.format(port)
        elif sasmode == 'utah':
            # sort out the domain name
            if public:
                domain = test_domain if test else bconfig.public_api_url
                if test:
                    domain = '{0}{1}'.format(domain, 'public/')
                else:
                    domain = re.sub(r'(dr[0-9]{1,2})', self._release.lower(), domain)
            else:
                domain = test_domain if test else bconfig.collab_api_url

            url = os.path.join(domain)
            self.sasurl = url

            # get a new urlmap (need to do for vetting)
            self._urlmap = None
            #__ = self.urlmap

            # marvin_base = 'test/{0}/'.format(base) if test else '{0}/'.format(base)
            # if public:
            #     base_url = re.sub(r'(dr[0-9]{1,2})', self._release.lower(), bconfig.public_api_url)
            #     public_api = os.path.join(base_url, marvin_base)
            #     self.sasurl = public_api
            #     self._authtype = None
            # else:
            #     self.sasurl = os.path.join(bconfig.collab_api_url, marvin_base)
            #     self._authtype = 'token'

    def forceDbOff(self):
        ''' Force the database to be turned off '''
        config.db = None
        from marvin import marvindb
        if marvindb:
            marvindb.forceDbOff()

    def forceDbOn(self):
        ''' Force the database to be reconnected '''
        self._setDbConfig()
        from marvin import marvindb
        if marvindb:
            marvindb.forceDbOn(dbtype=self.db)

    def _addExternal(self, name):
        ''' Adds an external product into the path '''
        assert isinstance(name, str), 'name must be a string'
        externdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'extern', name)
        extern_envvar = '{0}_DIR'.format(name.upper())
        os.environ[extern_envvar] = externdir
        pypath = os.path.join(externdir, 'python')
        if os.path.isdir(pypath):
            sys.path.append(pypath)
        else:
            warnings.warn('Python path for external product {0} does not exist'.format(name))

    def _plantTree(self):
        ''' Sets up the sdss tree product root '''

        tree_config = 'sdsswork' if self.access == 'collab' and 'MPL' in self.release else self.release.lower()

        # testing always using the python Tree as override
        # if 'TREE_DIR' not in os.environ:
        # set up tree using marvin's extern package
        self._addExternal('tree')
        try:
            from tree.tree import Tree
        except ImportError:
            self._tree = None
        else:
            self._tree = Tree(key='MANGA', config=tree_config)

    def _checkSDSSAccess(self):
        ''' Checks the client sdss_access setup '''
        if 'SDSS_ACCESS_DIR' not in os.environ:
            # set up sdss_access using marvin's extern package
            self._addExternal('sdss_access')
            try:
                from sdss_access.path import Path
            except ImportError:
                Path = None
            else:
                self._sdss_access_isloaded = True

    @contextlib.contextmanager
    def _replant_tree(self, value):
        ''' Replants the tree based on release/access toggling

        Context manager for use when setting a new release

        Replants the tree only when
        - A release is different than the previous value
        - Toggling to public access from sdsswork
        - Toggling to collab access from non-sdsswork
        - Toggling between DR releases
        - Toggling between DR and MPL releases

        Parameters:
            value (str):
                A new release
        '''

        # switch between public and collab access
        if hasattr(self, '_tree'):
            tocollab = self.access == 'collab' and self._tree.config_name != 'sdsswork'
            topublic = self.access == 'public' and self._tree.config_name == 'sdsswork'

        # switch trees based on release

        # check if release is different
        is_different = self._release and value != self._release

        # remove and return similar characters from value in self._release
        if self._release:
            similar = re.sub('[^{0}]'.format(self._release.replace('-', '\-')), '', value)
            # are we still a DR?
            stilldr = 'DR' in similar
            # are we still an MPL?
            stillmpl = 'MPL' in similar
            # have we changed releases?
            relchange = stilldr is False and stillmpl is False

        # yield the value (a release)
        yield value

        # check if the tree isn't set up or _release is None
        # this should only occur during the initial imports
        nullinit = not hasattr(self, '_tree') or self._release is None

        # set tree_config
        tree_config = 'sdsswork' if 'MPL' in value else value.lower() if 'DR' in value else None

        # replant the tree
        if is_different and not nullinit:
            if (relchange and self.access == 'collab') or stilldr or topublic or tocollab:
                self._tree.replant_tree(tree_config)

        # switch the API url depending on release
        if 'MPL' in value:
            self.switchSasUrl('utah')
        elif 'DR' in value:
            self.switchSasUrl('utah', public=True)

    def login(self, refresh=None):
        ''' Login with netrc credentials to receive an API token

        Copy this token into the "use_token" parameter in your
        custom marvin.yml file to ensure preserve authentication
        across iPython user sessions.

        Parameters:
            refresh (bool):
                Set to True to refresh a login to receive a new token

        '''

        assert config.access == 'collab', 'You must have collaboration access to login.'

        # do nothing if token already generated
        if self.token and not refresh:
            return

        valid_netrc = bconfig._check_netrc()
        if valid_netrc:
            # get login info for api.sdss.org
            user, password = bconfig._read_netrc('api.sdss.org')
            data = {'username': user, 'password': password}

            # send token request
            url = self.urlmap['api']['login']['url']
            try:
                resp = Interaction(url, params=data, auth='netrc')
            except Exception as e:
                raise MarvinError('Error getting login token. {0}'.format(e))
            else:
                self.token = resp.results['access_token']
Пример #3
0
 def test_grand_child(self):
     tree = Tree("Electronics")
Пример #4
0
 def test_tree_add_child_already_in_tree(self):
     tree = Tree()
     tree.add_child(5)
     tree.add_child(2)
     tree.add_child(4)
     self.assertEqual(tree.add_child(2), False)
Пример #5
0
 def test_empty_tree(self):
     tree = Tree()
     self.assertIsNone(tree.root)
     self.assertIsNone(tree.display_preorder())
Пример #6
0
 def test_delete_node_without_child(self):
     tree = Tree()
     tree.add_child(5)
     tree.add_child(1)
     tree.add_child(4)
     tree.add_child(7)
     tree.add_child(9)
     tree.add_child(6)
     tree.add_child(8)
     self.assertEqual(tree.display_preorder(), [5, 1, 4, 7, 6, 9, 8])
     self.assertEqual(tree.display_inorder(), [1, 4, 5, 6, 7, 8, 9])
     tree.delete(4)
     self.assertEqual(tree.display_preorder(), [5, 1, 7, 6, 9, 8])
     self.assertEqual(tree.display_inorder(), [1, 5, 6, 7, 8, 9])
     tree.delete(8)
     self.assertEqual(tree.display_preorder(), [5, 1, 7, 6, 9])
     self.assertEqual(tree.display_inorder(), [1, 5, 6, 7, 9])
Пример #7
0
 def test_delete_node_with_children(self):
     tree = Tree()
     tree.add_child(5)
     tree.add_child(1)
     tree.add_child(4)
     tree.add_child(7)
     tree.add_child(9)
     tree.add_child(6)
     tree.add_child(8)
     self.assertEqual(tree.display_preorder(), [5, 1, 4, 7, 6, 9, 8])
     tree.delete(7)
     self.assertEqual(tree.display_preorder(), [5, 1, 4, 8, 6, 9])
     tree.delete(8)
     self.assertEqual(tree.display_preorder(), [5, 1, 4, 9, 6])
Пример #8
0
 def test_load_with_update(self, tree, dr):
     assert 'sdsswork' in tree.environ['default']['name']
     assert 'mangawork' in tree.environ['MANGA']['manga_root']
     tree = Tree(config=dr, update=True)
     self._assert_paths(tree, dr=dr)
Пример #9
0
 def test_1(self):
     self.test = Node(3, None, None)
     self.answer = [[3]]
     assert Tree(self.test).printTree() == self.answer
Пример #10
0
def tree():
    t = Tree()
    yield t
    t = None
Пример #11
0
 def test_load_dr_config(self, dr):
     t = Tree(config=dr)
     assert dr == t.environ['default']['name']
Пример #12
0
 def __init__(self):
     # 区块链
     self.block_chain = BlockChain()
     # 索引树
     self.tree = Tree()
Пример #13
0
 def test2(self):
     c = Node(3, None, None)
     b = Node(2, c, None)
     a = Node(1, b, None)
     tree2 = Tree(a)
     assert tree2.print_tree() == self.answer2
Пример #14
0
 def test1(self):
     a = Node(1, None, None)
     tree1 = Tree(a)
     assert tree1.print_tree() == self.answer1
Пример #15
0
# declare shared hyper parameters
max_depth = 100
min_samples = 10


tree_clf = DecisionTreeClassifier(max_depth=max_depth, min_samples_leaf=min_samples)
tree_clf.fit(X,y)
sk_tree_graph = export_graphviz(tree_clf,
                                out_file=None,
                                class_names=iris.target_names,
                                rounded=True,
                                filled=True)
# build tree graph for sklearn model
folder = os.path.dirname(__file__)
sk_tree_source = Source(sk_tree_graph,
                        filename='skl_treebag.gv',
                        directory=folder+'\images',
                        format='png')
sk_tree_source.render()


# my tree class
t = Tree(max_depth=max_depth, min_node_points=min_samples)
Xme = X
Yme = np.atleast_2d(y).T
t.train(Xme, Yme)

build_graph(t, '.\images')

print(t.predict(np.array([1,7])))
Пример #16
0
    def test_binary_tree_1(self):

        a = node(1, None, None)
        t = Tree(a)

        assert (t.print_binary_tree()) == ['1']
Пример #17
0
 def test_tree_root(self):
     tree = Tree()
     tree.add_child(5)
     self.assertEqual(tree.root.value, 5)
Пример #18
0
class TestTree(unittest.TestCase):
    def setUp(self):
        # Four test cases
        t21 = Node(4, None, None)
        t22 = Node(5, None, None)
        t23 = Node(6, None, None)
        t24 = Node(7, None, None)
        t11 = Node(2, t21, t22)
        t12 = Node(3, t23, t24)
        root_1 = Node(1, t11, t12)
        self.test_1 = Tree(root_1)

        n3 = Node(4, None, None)
        n2 = Node(3, n3, None)
        n1 = Node(2, n2, None)
        root_2 = Node(1, n1, None)
        self.test_2 = Tree(root_2)

        root_3 = Node(1, None, None)
        self.test_3 = Tree(root_3)

        n5 = Node(9, None, None)
        n4 = Node(8, None, n5)
        n3 = Node(7, n4, None)
        n2 = Node(6, None, None)
        n1 = Node(5, None, n2)
        root_4 = Node(4, n1, n3)
        self.test_4 = Tree(root_4)

    def test_case_1(self):

        tree_list = self.test_1.print_tree()
        assert np.all(
            np.array(tree_list) == np.array(
                [['|', '|', '|', '1', '|', '|', '|'],
                 ['|', '2', '|', '|', '|', '3', '|'],
                 ['4', '|', '5', '|', '6', '|', '7']]))

    def test_case_2(self):

        tree_list = self.test_2.print_tree()
        assert np.all(
            np.array(tree_list) == np.array([['|'] * 7 + ['1'] +
                                             ['|'] * 7, ['|'] * 3 + ['2'] +
                                             ['|'] * 11, ['|'] + ['3'] +
                                             ['|'] * 13, ['4'] + ['|'] * 14]))

    def test_case_3(self):

        tree_list = self.test_3.print_tree()
        assert np.all(np.array(tree_list) == np.array(['1']))

    def test_case_4(self):

        tree_list = self.test_4.print_tree()
        assert np.all(
            np.array(tree_list) == np.array([['|'] * 7 + ['4'] +
                                             ['|'] * 7, ['|'] * 3 + ['5'] +
                                             ['|'] * 7 + ['7'] +
                                             ['|'] * 3, ['|'] * 5 + ['6'] +
                                             ['|'] * 3 + ['8'] +
                                             ['|'] * 5, ['|'] * 10 + ['9'] +
                                             ['|'] * 4]))
Пример #19
0
 def test_add_child(self):
     tree = Tree()
     tree.add_child(5)
     self.assertEqual(tree.add_child(2), True)
Пример #20
0
 def test_1(self):
     t = Tree(Node(1, None, None))
     assert t.print_tree() == [['1']]
Пример #21
0
 def test_tree_add_children(self):
     tree = Tree()
     tree.add_child(5)
     tree.add_child(2)
     tree.add_child(4)
     self.assertEqual(tree.display_preorder()[1:], [2, 4])
Пример #22
0
import numpy as np
from tree.node import Node
from tree.tree import Tree

x = np.random.random((100, 10))
y = np.atleast_2d(np.random.randint(1, size=100)).T

N = Tree()
N.train(x, y)

x_test = np.random.random((1, 10))
result = N.predict(x=x_test)

print(result)
Пример #23
0
 def test_display_inorder(self):
     tree = Tree()
     tree.add_child(5)
     tree.add_child(2)
     tree.add_child(1)
     tree.add_child(4)
     tree.add_child(7)
     tree.add_child(9)
     tree.add_child(6)
     tree.add_child(0)
     tree.add_child(8)
     tree.add_child(3)
     self.assertEqual(tree.display_inorder(),
                      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Пример #24
0
from tree.tree import Tree

# Create new tree
tree = Tree()

tree.add_value(5)
tree.add_value(4)
tree.add_value(6)
tree.add_value(1)
tree.add_value(7)
tree.add_value(10)

print("Tree:")

print(tree)
print("Count: ", tree.get_count())
print("Sum: ", tree.get_sum())
print("Levels: ", tree.get_levels())
print("Avg: ", tree.get_avg())
print("Inorder traversal: ", tree.get_inorder_traversal())
print("Median: ", tree.get_median())
print("Find node with value 6", tree.find(6))
Пример #25
0
 def test_display_postorder(self):
     tree = Tree()
     tree.add_child(5)
     tree.add_child(2)
     tree.add_child(1)
     tree.add_child(4)
     tree.add_child(7)
     tree.add_child(9)
     tree.add_child(6)
     tree.add_child(0)
     tree.add_child(8)
     tree.add_child(3)
     self.assertEqual(tree.display_postorder(),
                      [5, 7, 9, 8, 6, 2, 4, 3, 1, 0])
Пример #26
0
 def test_tree2(self):
     node = Node(3, Node(9, 22, 105), Node(554, 10, 0))
     tree = Tree(node)
     assert tree.printTree() == [["|", "|", "|", "3", "|", "|", "|"],
                                 ["|", "9", "|", "|", "|", "554", "|"],
                                 ["22", "|", "105", "|", "10", "|", "0"]]
Пример #27
0
 def test_add_child(self):
     tree = Tree("Electronics")
     tree.add_child("laptop")
     tree.add_child("cellphone")
     tree.add_child("tv")
     self.assertIsNotNone(tree.children)
Пример #28
0
 def test_tree1(self):
     node = Node(5, None, None)
     tree = Tree(node)
     assert tree.printTree() == [["5"]]
Пример #29
0
 def test_leaf_node(self):
     tree = Tree("Electronics")
Пример #30
0
 def test_case_1(self):
     node = Node(1, None, None)
     self.tree = Tree(node)
     self.answer = [[1]]
     assert self.tree.print_tree() == self.answer