self.client.post.return_value = self.mock_response(
            "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.create("service_plan_guid", "organization_guid")

import json
import sys
import unittest
from functools import reduce
from http import HTTPStatus
from unittest.mock import patch

import cloudfoundry_client.main.main as main
from abstract_test_case import AbstractTestCase

class TestServicePlanVisibilities(unittest.TestCase, AbstractTestCase):
    @classmethod
    def setUpClass(cls):
        cls.mock_client_class()

    def setUp(self):
        self.build_client()

    def test_list(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities?q=space_guid%3Aspace_guid",
            HTTPStatus.OK,
            None,
            "v2",
            "service_plan_visibilities",
            "GET_response.json",
        )
        cpt = reduce(
            lambda increment, _: increment + 1, self.client.v2.service_plan_visibilities.list(space_guid="space_guid"), 0
        )
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertEqual(cpt, 1)

    def test_get(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_{id}_response.json"
        )
        result = self.client.v2.service_plan_visibilities.get("guid")
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertIsNotNone(result)

    def test_create(self):

        self.client.post.assert_called_with(
            self.client.post.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_update(self):
        self.client.put.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "PUT_{id}_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.update(
            "guid", service_plan_guid="service_plan_guid", organization_guid="organization_guid"
        )
        self.client.put.assert_called_with(
            self.client.put.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_delete(self):
        self.client.delete.return_value = self.mock_response("/v2/service_plan_visibilities/guid", HTTPStatus.NO_CONTENT, None)
        self.client.v2.service_plan_visibilities.remove("guid")
        self.client.delete.assert_called_with(self.client.delete.return_value.url)

    @patch.object(
        sys,
        "argv",
        [
            "main",
            "create_service_plan_visibility",
            json.dumps(dict(service_plan_guid="service-plan-id", organization_guid="organization-id")),
        ],
    )
    def test_main_create_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.post.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
            )
            main.main()
            self.client.post.assert_called_with(
                self.client.post.return_value.url,
                json=dict(service_plan_guid="service-plan-id", organization_guid="organization-id"),
            )

    @patch.object(sys, "argv", ["main", "list_service_plan_visibilities"])
    def test_main_list_service_plan_visibilities(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_response.json"
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "get_service_plan_visibility", "a353104b-1290-418c-bc03-0e647afd0853"])
    def test_main_get_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities/a353104b-1290-418c-bc03-0e647afd0853",
                HTTPStatus.OK,
                None,
                "v2",
                "service_plan_visibilities",
                "GET_{id}_response.json",
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "delete_service_plan_visibility", "906775ea-622e-4bc7-af5d-9aab3b652f81"])
    def test_main_delete_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.delete.return_value = self.mock_response(
                "/v2/service_plan_visibilities/906775ea-622e-4bc7-af5d-9aab3b652f81", HTTPStatus.NO_CONTENT, None
            )
            main.main()
            self.client.delete.assert_called_with(self.client.delete.return_value.url)


self.client.post.assert_called_with(
            self.client.post.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )

import json
import sys
import unittest
from functools import reduce
from http import HTTPStatus
from unittest.mock import patch

import cloudfoundry_client.main.main as main
from abstract_test_case import AbstractTestCase

class TestServicePlanVisibilities(unittest.TestCase, AbstractTestCase):
    @classmethod
    def setUpClass(cls):
        cls.mock_client_class()

    def setUp(self):
        self.build_client()

    def test_list(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities?q=space_guid%3Aspace_guid",
            HTTPStatus.OK,
            None,
            "v2",
            "service_plan_visibilities",
            "GET_response.json",
        )
        cpt = reduce(
            lambda increment, _: increment + 1, self.client.v2.service_plan_visibilities.list(space_guid="space_guid"), 0
        )
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertEqual(cpt, 1)

    def test_get(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_{id}_response.json"
        )
        result = self.client.v2.service_plan_visibilities.get("guid")
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertIsNotNone(result)

    def test_create(self):
        self.client.post.return_value = self.mock_response(
            "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.create("service_plan_guid", "organization_guid")

        self.assertIsNotNone(service_plan_visibilities)

    def test_update(self):
        self.client.put.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "PUT_{id}_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.update(
            "guid", service_plan_guid="service_plan_guid", organization_guid="organization_guid"
        )
        self.client.put.assert_called_with(
            self.client.put.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_delete(self):
        self.client.delete.return_value = self.mock_response("/v2/service_plan_visibilities/guid", HTTPStatus.NO_CONTENT, None)
        self.client.v2.service_plan_visibilities.remove("guid")
        self.client.delete.assert_called_with(self.client.delete.return_value.url)

    @patch.object(
        sys,
        "argv",
        [
            "main",
            "create_service_plan_visibility",
            json.dumps(dict(service_plan_guid="service-plan-id", organization_guid="organization-id")),
        ],
    )
    def test_main_create_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.post.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
            )
            main.main()
            self.client.post.assert_called_with(
                self.client.post.return_value.url,
                json=dict(service_plan_guid="service-plan-id", organization_guid="organization-id"),
            )

    @patch.object(sys, "argv", ["main", "list_service_plan_visibilities"])
    def test_main_list_service_plan_visibilities(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_response.json"
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "get_service_plan_visibility", "a353104b-1290-418c-bc03-0e647afd0853"])
    def test_main_get_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities/a353104b-1290-418c-bc03-0e647afd0853",
                HTTPStatus.OK,
                None,
                "v2",
                "service_plan_visibilities",
                "GET_{id}_response.json",
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "delete_service_plan_visibility", "906775ea-622e-4bc7-af5d-9aab3b652f81"])
    def test_main_delete_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.delete.return_value = self.mock_response(
                "/v2/service_plan_visibilities/906775ea-622e-4bc7-af5d-9aab3b652f81", HTTPStatus.NO_CONTENT, None
            )
            main.main()
            self.client.delete.assert_called_with(self.client.delete.return_value.url)


import json
import sys
import unittest
from functools import reduce
from http import HTTPStatus
from unittest.mock import patch

import cloudfoundry_client.main.main as main
from abstract_test_case import AbstractTestCase

class TestServicePlanVisibilities(unittest.TestCase, AbstractTestCase):
    @classmethod
    def setUpClass(cls):
        cls.mock_client_class()

    def setUp(self):
        self.build_client()

    def test_list(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities?q=space_guid%3Aspace_guid",
            HTTPStatus.OK,
            None,
            "v2",
            "service_plan_visibilities",
            "GET_response.json",
        )
        cpt = reduce(
            lambda increment, _: increment + 1, self.client.v2.service_plan_visibilities.list(space_guid="space_guid"), 0
        )
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertEqual(cpt, 1)

    def test_get(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_{id}_response.json"
        )
        result = self.client.v2.service_plan_visibilities.get("guid")
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertIsNotNone(result)

    def test_create(self):
        self.client.post.return_value = self.mock_response(
            "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.create("service_plan_guid", "organization_guid")
        self.client.post.assert_called_with(
            self.client.post.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )

    def test_update(self):
        self.client.put.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "PUT_{id}_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.update(
            "guid", service_plan_guid="service_plan_guid", organization_guid="organization_guid"
        )
        self.client.put.assert_called_with(
            self.client.put.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_delete(self):
        self.client.delete.return_value = self.mock_response("/v2/service_plan_visibilities/guid", HTTPStatus.NO_CONTENT, None)
        self.client.v2.service_plan_visibilities.remove("guid")
        self.client.delete.assert_called_with(self.client.delete.return_value.url)

    @patch.object(
        sys,
        "argv",
        [
            "main",
            "create_service_plan_visibility",
            json.dumps(dict(service_plan_guid="service-plan-id", organization_guid="organization-id")),
        ],
    )
    def test_main_create_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.post.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
            )
            main.main()
            self.client.post.assert_called_with(
                self.client.post.return_value.url,
                json=dict(service_plan_guid="service-plan-id", organization_guid="organization-id"),
            )

    @patch.object(sys, "argv", ["main", "list_service_plan_visibilities"])
    def test_main_list_service_plan_visibilities(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_response.json"
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "get_service_plan_visibility", "a353104b-1290-418c-bc03-0e647afd0853"])
    def test_main_get_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities/a353104b-1290-418c-bc03-0e647afd0853",
                HTTPStatus.OK,
                None,
                "v2",
                "service_plan_visibilities",
                "GET_{id}_response.json",
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "delete_service_plan_visibility", "906775ea-622e-4bc7-af5d-9aab3b652f81"])
    def test_main_delete_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.delete.return_value = self.mock_response(
                "/v2/service_plan_visibilities/906775ea-622e-4bc7-af5d-9aab3b652f81", HTTPStatus.NO_CONTENT, None
            )
            main.main()
            self.client.delete.assert_called_with(self.client.delete.return_value.url)


f.client.delete.return_value = self.mock_response("/v2/service_plan_visibilities/guid", HTTPStatus.NO_CONTENT, None)

import json
import sys
import unittest
from functools import reduce
from http import HTTPStatus
from unittest.mock import patch

import cloudfoundry_client.main.main as main
from abstract_test_case import AbstractTestCase

class TestServicePlanVisibilities(unittest.TestCase, AbstractTestCase):
    @classmethod
    def setUpClass(cls):
        cls.mock_client_class()

    def setUp(self):
        self.build_client()

    def test_list(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities?q=space_guid%3Aspace_guid",
            HTTPStatus.OK,
            None,
            "v2",
            "service_plan_visibilities",
            "GET_response.json",
        )
        cpt = reduce(
            lambda increment, _: increment + 1, self.client.v2.service_plan_visibilities.list(space_guid="space_guid"), 0
        )
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertEqual(cpt, 1)

    def test_get(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_{id}_response.json"
        )
        result = self.client.v2.service_plan_visibilities.get("guid")
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertIsNotNone(result)

    def test_create(self):
        self.client.post.return_value = self.mock_response(
            "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.create("service_plan_guid", "organization_guid")
        self.client.post.assert_called_with(
            self.client.post.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_update(self):
        self.client.put.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "PUT_{id}_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.update(
            "guid", service_plan_guid="service_plan_guid", organization_guid="organization_guid"
        )
        self.client.put.assert_called_with(
            self.client.put.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_delete(self):
        sel

        self.client.v2.service_plan_visibilities.remove("guid")
        self.client.delete.assert_called_with(self.client.delete.return_value.url)

    @patch.object(
        sys,
        "argv",
        [
            "main",
            "create_service_plan_visibility",
            json.dumps(dict(service_plan_guid="service-plan-id", organization_guid="organization-id")),
        ],
    )
    def test_main_create_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.post.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
            )
            main.main()
            self.client.post.assert_called_with(
                self.client.post.return_value.url,
                json=dict(service_plan_guid="service-plan-id", organization_guid="organization-id"),
            )

    @patch.object(sys, "argv", ["main", "list_service_plan_visibilities"])
    def test_main_list_service_plan_visibilities(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_response.json"
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "get_service_plan_visibility", "a353104b-1290-418c-bc03-0e647afd0853"])
    def test_main_get_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities/a353104b-1290-418c-bc03-0e647afd0853",
                HTTPStatus.OK,
                None,
                "v2",
                "service_plan_visibilities",
                "GET_{id}_response.json",
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "delete_service_plan_visibility", "906775ea-622e-4bc7-af5d-9aab3b652f81"])
    def test_main_delete_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.delete.return_value = self.mock_response(
                "/v2/service_plan_visibilities/906775ea-622e-4bc7-af5d-9aab3b652f81", HTTPStatus.NO_CONTENT, None
            )
            main.main()
            self.client.delete.assert_called_with(self.client.delete.return_value.url)


import json
import sys
import unittest
from functools import reduce
from http import HTTPStatus
from unittest.mock import patch

import cloudfoundry_client.main.main as main
from abstract_test_case import AbstractTestCase

class TestServicePlanVisibilities(unittest.TestCase, AbstractTestCase):
    @classmethod
    def setUpClass(cls):
        cls.mock_client_class()

    def setUp(self):
        self.build_client()

    def test_list(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities?q=space_guid%3Aspace_guid",
            HTTPStatus.OK,
            None,
            "v2",
            "service_plan_visibilities",
            "GET_response.json",
        )
        cpt = reduce(
            lambda increment, _: increment + 1, self.client.v2.service_plan_visibilities.list(space_guid="space_guid"), 0
        )
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertEqual(cpt, 1)

    def test_get(self):
        self.client.get.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_{id}_response.json"
        )
        result = self.client.v2.service_plan_visibilities.get("guid")
        self.client.get.assert_called_with(self.client.get.return_value.url)
        self.assertIsNotNone(result)

    def test_create(self):
        self.client.post.return_value = self.mock_response(
            "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.create("service_plan_guid", "organization_guid")
        self.client.post.assert_called_with(
            self.client.post.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_update(self):
        self.client.put.return_value = self.mock_response(
            "/v2/service_plan_visibilities/guid", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "PUT_{id}_response.json"
        )
        service_plan_visibilities = self.client.v2.service_plan_visibilities.update(
            "guid", service_plan_guid="service_plan_guid", organization_guid="organization_guid"
        )
        self.client.put.assert_called_with(
            self.client.put.return_value.url,
            json=dict(service_plan_guid="service_plan_guid", organization_guid="organization_guid"),
        )
        self.assertIsNotNone(service_plan_visibilities)

    def test_delete(self):
        self.client.delete.return_value = self.mock_response("/v2/service_plan_visibilities/guid", HTTPStatus.NO_CONTENT, None)
        self.client.v2.service_plan_visibilities.remove("guid")
        self.client.delete.assert_called_with(self.client.delete.return_value.url)

    @patch.object(
        sys,
        "argv",
        [
            "main",
            "create_service_plan_visibility",
            json.dumps(dict(service_plan_guid="service-plan-id", organization_guid="organization-id")),
        ],
    )
    def test_main_create_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.post.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.CREATED, None, "v2", "service_plan_visibilities", "POST_response.json"
            )
            main.main()
            self.client.post.assert_called_with(
                self.client.post.return_value.url,
                json=dict(service_plan_guid="service-plan-id", organization_guid="organization-id"),
            )

    @patch.object(sys, "argv", ["main", "list_service_plan_visibilities"])
    def test_main_list_service_plan_visibilities(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities", HTTPStatus.OK, None, "v2", "service_plan_visibilities", "GET_response.json"
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "get_service_plan_visibility", "a353104b-1290-418c-bc03-0e647afd0853"])
    def test_main_get_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.get.return_value = self.mock_response(
                "/v2/service_plan_visibilities/a353104b-1290-418c-bc03-0e647afd0853",
                HTTPStatus.OK,
                None,
                "v2",
                "service_plan_visibilities",
                "GET_{id}_response.json",
            )
            main.main()
            self.client.get.assert_called_with(self.client.get.return_value.url)

    @patch.object(sys, "argv", ["main", "delete_service_plan_visibility", "906775ea-622e-4bc7-af5d-9aab3b652f81"])
    def test_main_delete_service_plan_visibility(self):
        with patch("cloudfoundry_client.main.main.build_client_from_configuration", new=lambda: self.client):
            self.client.delete.r

eturn_value = self.mock_response(
                "/v2/service_plan_visibilities/906775ea-622e-4bc7-af5d-9aab3b652f81", HTTPStatus.NO_CONTENT, None
            )
            main.main()
            self.client.delete.assert_called_with(self.client.delete.return_value.url)


if MASK_ALGORITHM.lower() == 'intersection' or MASK_ALGORITHM.lower() == 'union':
    masks = glob.glob(os.path.join(MASKS_PATH, '*.tif'))
    print( os.path.join(MASKS_PATH, '*.tif') )
else:
    masks = glob.glob(os.path.join(MASKS_PATH, '*{}*.tif'.format(MASK_ALGORITHM)))
    print(os.path.join(MASKS_PATH, '*{}*.tif'.format(MASK_ALGORITHM)))

import os
import warnings
warnings.filterwarnings("ignore")

import glob
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
import keras
from keras import optimizers
from keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.python.keras import backend as K

import sys
import csv
import pandas as pd
from tqdm import tqdm
from sklearn.model_selection import train_test_split

from keras.preprocessing.image import ImageDataGenerator

# Schoeder, Murphy, Kumar-Roy, Intersection or Union
MASK_ALGORITHM = 'Intersection'

IMAGES_PATH = '/home/andre/tif_patches/patches/'
MASKS_PATH = '/home/andre/mask_patches/intersection/'
IMAGES_DATAFRAME = './dataset/images_masks.csv'

RANDOM_STATE = 42

print(len(masks))

with open(IMAGES_DATAFRAME, 'w') as f:
    writer = csv.writer(f, delimiter=',')

    for mask in tqdm(masks):
        _, mask_name = os.path.split(mask)

        if MASK_ALGORITHM.lower() == 'intersection' or MASK_ALGORITHM.lower() == 'union':
            image_name = mask_name
        else:
            image_name = mask_name.replace('_{}_'.format(MASK_ALGORITHM), '_')

        writer.writerow([image_name, mask_name])

train_ratio = 0.4
validation_ratio = 0.1
test_ratio = 0.5

df = pd.read_csv(IMAGES_DATAFRAME, header=None, names=['images', 'masks'])
images_df = df[ ['images'] ]
masks_df = df[ ['masks'] ]

x_train, x_test, y_train, y_test = train_test_split(images_df, masks_df, test_size=1 - train_ratio, random_state=RANDOM_STATE)
x_val, x_test, y_val, y_test = train_test_split(x_test, y_test, test_size=test_ratio/(test_ratio + validation_ratio), random_state=RANDOM_STATE)

print(len(df.index), len(x_train.index), len(x_val.index), len(x_test.index))

x_train.to_csv('./dataset/images_train.csv', index=False)
y_train.to_csv('./dataset/masks_train.csv', index=False)
x_val.to_csv('./dataset/images_val.csv', index=False)
y_val.to_csv('./dataset/masks_val.csv', index=False)
x_test.to_csv('./dataset/images_test.csv', index=False)
y_test.to_csv('./dataset/masks_test.csv', index=False)


for mask in tqdm(masks):
        _, mask_name = os.path.split(mask)

        if MASK_ALGORITHM.lower() == 'intersection' or MASK_ALGORITHM.lower() == 'union':
            image_name = mask_name
        else:
            image_name = mask_name.replace('_{}_'.format(MASK_ALGORITHM), '_')

        writer.writerow([image_name, mask_name])

import os
import warnings
warnings.filterwarnings("ignore")

import glob
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
import keras
from keras import optimizers
from keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.python.keras import backend as K

import sys
import csv
import pandas as pd
from tqdm import tqdm
from sklearn.model_selection import train_test_split

from keras.preprocessing.image import ImageDataGenerator

# Schoeder, Murphy, Kumar-Roy, Intersection or Union
MASK_ALGORITHM = 'Intersection'

IMAGES_PATH = '/home/andre/tif_patches/patches/'
MASKS_PATH = '/home/andre/mask_patches/intersection/'
IMAGES_DATAFRAME = './dataset/images_masks.csv'

RANDOM_STATE = 42

if MASK_ALGORITHM.lower() == 'intersection' or MASK_ALGORITHM.lower() == 'union':
    masks = glob.glob(os.path.join(MASKS_PATH, '*.tif'))
    print( os.path.join(MASKS_PATH, '*.tif') )
else:
    masks = glob.glob(os.path.join(MASKS_PATH, '*{}*.tif'.format(MASK_ALGORITHM)))
    print(os.path.join(MASKS_PATH, '*{}*.tif'.format(MASK_ALGORITHM)))

print(len(masks))

with open(IMAGES_DATAFRAME, 'w') as f:
    writer = csv.writer(f, delimiter=',')

train_ratio = 0.4
validation_ratio = 0.1
test_ratio = 0.5

df = pd.read_csv(IMAGES_DATAFRAME, header=None, names=['images', 'masks'])
images_df = df[ ['images'] ]
masks_df = df[ ['masks'] ]

x_train, x_test, y_train, y_test = train_test_split(images_df, masks_df, test_size=1 - train_ratio, random_state=RANDOM_STATE)
x_val, x_test, y_val, y_test = train_test_split(x_test, y_test, test_size=test_ratio/(test_ratio + validation_ratio), random_state=RANDOM_STATE)

print(len(df.index), len(x_train.index), len(x_val.index), len(x_test.index))

x_train.to_csv('./dataset/images_train.csv', index=False)
y_train.to_csv('./dataset/masks_train.csv', index=False)
x_val.to_csv('./dataset/images_val.csv', index=False)
y_val.to_csv('./dataset/masks_val.csv', index=False)
x_test.to_csv('./dataset/images_test.csv', index=False)
y_test.to_csv('./dataset/masks_test.csv', index=False)


import os
import warnings
warnings.filterwarnings("ignore")

import glob
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
import keras
from keras import optimizers
from keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.python.keras import backend as K

import sys
import csv
import pandas as pd
from tqdm import tqdm
from sklearn.model_selection import train_test_split

from keras.preprocessing.image import ImageDataGenerator

# Schoeder, Murphy, Kumar-Roy, Intersection or Union
MASK_ALGORITHM = 'Intersection'

IMAGES_PATH = '/home/andre/tif_patches/patches/'
MASKS_PATH = '/home/andre/mask_patches/intersection/'
IMAGES_DATAFRAME = './dataset/images_masks.csv'

RANDOM_STATE = 42

if MASK_ALGORITHM.lower() == 'intersection' or MASK_ALGORITHM.lower() == 'union':
    masks = glob.glob(os.path.join(MASKS_PATH, '*.tif'))
    print( os.path.join(MASKS_PATH, '*.tif') )
else:
    masks = glob.glob(os.path.join(MASKS_PATH, '*{}*.tif'.format(MASK_ALGORITHM)))
    print(os.path.join(MASKS_PATH, '*{}*.tif'.format(MASK_ALGORITHM)))

print(len(masks))

with open(IMAGES_DATAFRAME, 'w') as f:
    writer = csv.writer(f, delimiter=',')

    for mask in tqdm(masks):
        _, mask_name = os.path.split(mask)

        if MASK_ALGORITHM.lower() == 'intersection' or MASK_ALGORITHM.lower() == 'union':
            image_name = mask_name
        else:
            image_name = mask_name.replace('_{}_'.format(MASK_ALGORITHM), '_')

        writer.writerow([image_name, mask_name])

train_ratio = 0.4
validation_ratio = 0.1
test_ratio = 0.5

df = pd.read_csv(IMAGES_DATAFRAME, header=None, names=['images', 'masks'])
images_df = df[ ['images'] ]
masks_df = df[ ['masks'] ]

x_train, x_

test, y_train, y_test = train_test_split(images_df, masks_df, test_size=1 - train_ratio, random_state=RANDOM_STATE)
x_val, x_test, y_val, y_test = train_test_split(x_test, y_test, test_size=test_ratio/(test_ratio + validation_ratio), random_state=RANDOM_STATE)

print(len(df.index), len(x_train.index), len(x_val.index), len(x_test.index))

x_train.to_csv('./dataset/images_train.csv', index=False)
y_train.to_csv('./dataset/masks_train.csv', index=False)
x_val.to_csv('./dataset/images_val.csv', index=False)
y_val.to_csv('./dataset/masks_val.csv', index=False)
x_test.to_csv('./dataset/images_test.csv', index=False)
y_test.to_csv('./dataset/masks_test.csv', index=False)


from django.db import models

class MachineOperationsInfo(models.Model):
    number = models.Intege

rField(default=0, verbose_name=u'操作序号')
    person = models.CharField(default='', max_length=20, verbose_name=u'操作人用户名')
    time = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name=u'操作时间')
    sn_key = models.CharField(max_length=250, verbose_name=u'设备的唯一标识',unique=True)
    machine_type = models.CharField(max_length=20, verbose_name=u'设备类型')
    operation = models.TextField(default='', choices=((0, '增加'), (1, '删除'), (2, '修改')), verbose_name=u'操作内容')
    state = models.IntegerField(default=2, choices=((0, '已报废'), (1, '测试使用'), (2, '线上运行'), (3, '下线')),
                                verbose_name=u'设备使用状态')
    remark = models.TextField(default='', verbose_name=u'备注')

    class Meta:
        verbose_name = u'设备操作记录表'
        verbose_name_plural = verbose_name
        db_table = 'machineoperationsinfo'


# Created by TaoYuan on 2017/12/4 0004.
# @Remark  : Pyt


from __future__ import absolute_import, unicode_literals, division
from .parser import (Query, QuerySegment, NoopQuerySegment,
                     BinarySegm

entCombinator, UnarySegmentCombinator)

__all__ = [
    'Query',
    'QuerySegment',
    'NoopQuerySegment',
    'BinarySegmentCombinator',
    'UnarySegmentCombinator',
]


"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = nn.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):
        super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width
        self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)
        self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = nn.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x, output_size):

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):
        super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width
        self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)
        self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width

"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = nn.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x, output_size):
        out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):

        self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)
        self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)

"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = nn.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x, output_size):
        out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):
        super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width

        self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = nn.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x, output_size):
        out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):
        super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width
        self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(se

        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = nn.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x, output_size):
        out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):
        super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width
        self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)
        self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = nn.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x, output_size):
        out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):
        super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width
        self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)
        self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


"""
paper: GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing
file: model.py
about: model for GridDehazeNet
author: Xiaohong Liu
date: 01/08/19
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from residual_dense_block import RDB

class DownSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(DownSample, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, padding=(kernel_size-1)//2)
        self.conv2 = nn.Conv2d(in_channels, stride*in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.relu(self.conv2(out))
        return out

class UpSample(nn.Module):
    def __init__(self, in_channels, kernel_size=3, stride=2):
        super(UpSample, self).__init__()
        self.deconv = n

n.ConvTranspose2d(in_channels, in_channels, kernel_size, stride=stride, padding=1)
        self.conv = nn.Conv2d(in_channels, in_channels // stride, kernel_size, stride=1, padding=(kernel_size - 1) // 2)

    def forward(self, x, output_size):
        out = F.relu(self.deconv(x, output_size=output_size))
        out = F.relu(self.conv(out))
        return out

class GridDehazeNet(nn.Module):
    def __init__(self, in_channels=3, depth_rate=16, kernel_size=3, stride=2, height=3, width=6, num_dense_layer=4, growth_rate=16, attention=True):
        super(GridDehazeNet, self).__init__()
        self.rdb_module = nn.ModuleDict()
        self.upsample_module = nn.ModuleDict()
        self.downsample_module = nn.ModuleDict()
        self.height = height
        self.width = width
        self.stride = stride
        self.depth_rate = depth_rate
        self.coefficient = nn.Parameter(torch.Tensor(np.ones((height, width, 2, depth_rate*stride**(height-1)))), requires_grad=attention)
        self.conv_in = nn.Conv2d(in_channels, depth_rate, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.conv_out = nn.Conv2d(depth_rate, in_channels, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
        self.rdb_in = RDB(depth_rate, num_dense_layer, growth_rate)
        self.rdb_out = RDB(depth_rate, num_dense_layer, growth_rate)

        rdb_in_channels = depth_rate
        for i in range(height):
            for j in range(width - 1):
                self.rdb_module.update({'{}_{}'.format(i, j): RDB(rdb_in_channels, num_dense_layer, growth_rate)})
            rdb_in_channels *= stride

        _in_channels = depth_rate
        for i in range(height - 1):
            for j in range(width // 2):
                self.downsample_module.update({'{}_{}'.format(i, j): DownSample(_in_channels)})
            _in_channels *= stride

        for i in range(height - 2, -1, -1):
            for j in range(width // 2, width):
                self.upsample_module.update({'{}_{}'.format(i, j): UpSample(_in_channels)})
            _in_channels //= stride

    def forward(self, x):
        inp = self.conv_in(x)

        x_index = [[0 for _ in range(self.width)] for _ in range(self.height)]
        i, j = 0, 0

        x_index[0][0] = self.rdb_in(inp)

        for j in range(1, self.width // 2):
            x_index[0][j] = self.rdb_module['{}_{}'.format(0, j-1)](x_index[0][j-1])

        for i in range(1, self.height):
            x_index[i][0] = self.downsample_module['{}_{}'.format(i-1, 0)](x_index[i-1][0])

        for i in range(1, self.height):
            for j in range(1, self.width // 2):
                channel_num = int(2**(i-1)*self.stride*self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.downsample_module['{}_{}'.format(i-1, j)](x_index[i-1][j])

        x_index[i][j+1] = self.rdb_module['{}_{}'.format(i, j)](x_index[i][j])
        k = j

        for j in range(self.width // 2 + 1, self.width):
            x_index[i][j] = self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1])

        for i in range(self.height - 2, -1, -1):
            channel_num = int(2 ** (i-1) * self.stride * self.depth_rate)
            x_index[i][k+1] = self.coefficient[i, k+1, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, k)](x_index[i][k]) + \
                              self.coefficient[i, k+1, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, k+1)](x_index[i+1][k+1], x_index[i][k].size())

        for i in range(self.height - 2, -1, -1):
            for j in range(self.width // 2 + 1, self.width):
                channel_num = int(2 ** (i - 1) * self.stride * self.depth_rate)
                x_index[i][j] = self.coefficient[i, j, 0, :channel_num][None, :, None, None] * self.rdb_module['{}_{}'.format(i, j-1)](x_index[i][j-1]) + \
                                self.coefficient[i, j, 1, :channel_num][None, :, None, None] * self.upsample_module['{}_{}'.format(i, j)](x_index[i+1][j], x_index[i][j-1].size())

        out = self.rdb_out(x_index[i][j])
        out = F.relu(self.conv_out(out))

        return out


def send_message(
    ctx,
    aprs_login,
    aprs_password,
    no_ack,
    wait_response,
    raw,
    tocallsign,
    command,
):

import logging
import sys
import time

import aprslib
from aprslib.exceptions import LoginError
import click

import aprsd
from aprsd import cli_helper, client, messaging, packets

from ..aprsd import cli

LOG = logging.getLogger("APRSD")

@cli.command()
@cli_helper.add_options(cli_helper.common_options)
@click.option(
    "--aprs-login",
    envvar="APRS_LOGIN",
    show_envvar=True,
    help="What callsign to send the message from.",
)
@click.option(
    "--aprs-password",
    envvar="APRS_PASSWORD",
    show_envvar=True,
    help="the APRS-IS password for APRS_LOGIN",
)
@click.option(
    "--no-ack",
    "-n",
    is_flag=True,
    show_default=True,
    default=False,
    help="Don't wait for an ack, just sent it to APRS-IS and bail.",
)
@click.option(
    "--wait-response",
    "-w",
    is_flag=True,
    show_default=True,
    default=False,
    help="Wait for a response to the message?",
)
@click.option("--raw", default=None, help="Send a raw message.  Implies --no-ack")
@click.argument("tocallsign", required=True)
@click.argument("command", nargs=-1, required=True)
@click.pass_context
@cli_helper.process_standard_options

"""Send a message to a callsign via APRS_IS."""
    global got_ack, got_response
    config = ctx.obj["config"]
    quiet = ctx.obj["quiet"]

    if not aprs_login:
        click.echo("Must set --aprs_login or APRS_LOGIN")
        return

    if not aprs_password:
        click.echo("Must set --aprs-password or APRS_PASSWORD")
        return

    config["aprs"]["login"] = aprs_login
    config["aprs"]["password"] = aprs_password

    LOG.info(f"APRSD LISTEN Started version: {aprsd.__version__}")
    if type(command) is tuple:
        command = " ".join(command)
    if not quiet:
        if raw:
            LOG.info(f"L'{aprs_login}' R'{raw}'")
        else:
            LOG.info(f"L'{aprs_login}' To'{tocallsign}' C'{command}'")

    packets.PacketList(config=config)
    packets.WatchList(config=config)
    packets.SeenList(config=config)

    got_ack = False
    got_response = False

    def rx_packet(packet):
        global got_ack, got_response
        # LOG.debug("Got packet back {}".format(packet))
        resp = packet.get("response", None)
        if resp == "ack":
            ack_num = packet.get("msgNo")
            LOG.info(f"We got ack for our sent message {ack_num}")
            messaging.log_packet(packet)
            got_ack = True
        else:
            message = packet.get("message_text", None)
            fromcall = packet["from"]
            msg_number = packet.get("msgNo", "0")
            messaging.log_message(
                "Received Message",
                packet["raw"],
                message,
                fromcall=fromcall,
                ack=msg_number,
            )
            got_response = True
            # Send the ack back?
            ack = messaging.AckMessage(
                config["aprs"]["login"],
                fromcall,
                msg_id=msg_number,
            )
            ack.send_direct()

        if got_ack:
            if wait_response:
                if got_response:
                    sys.exit(0)
            else:
                sys.exit(0)

    try:
        client.ClientFactory.setup(config)
        client.factory.create().client
    except LoginError:
        sys.exit(-1)

    # Send a message
    # then we setup a consumer to rx messages
    # We should get an ack back as well as a new message
    # we should bail after we get the ack and send an ack back for the
    # message
    if raw:
        msg = messaging.RawMessage(raw)
        msg.send_direct()
        sys.exit(0)
    else:
        msg = messaging.TextMessage(aprs_login, tocallsign, command)
    msg.send_direct()

    if no_ack:
        sys.exit(0)

    try:
        # This will register a packet consumer with aprslib
        # When new packets come in the consumer will process
        # the packet
        aprs_client = client.factory.create().client
        aprs_client.consumer(rx_packet, raw=False)
    except aprslib.exceptions.ConnectionDrop:
        LOG.error("Connection dropped, reconnecting")
        time.sleep(5)
        # Force the deletion of the client object connected to aprs
        # This will cause a reconnect, next time client.get_client()
        aprs_client.reset()


global got_ack, got_response
        # LOG.debug("Got packet back {}".format(packet))

import logging
import sys
import time

import aprslib
from aprslib.exceptions import LoginError
import click

import aprsd
from aprsd import cli_helper, client, messaging, packets

from ..aprsd import cli

LOG = logging.getLogger("APRSD")

@cli.command()
@cli_helper.add_options(cli_helper.common_options)
@click.option(
    "--aprs-login",
    envvar="APRS_LOGIN",
    show_envvar=True,
    help="What callsign to send the message from.",
)
@click.option(
    "--aprs-password",
    envvar="APRS_PASSWORD",
    show_envvar=True,
    help="the APRS-IS password for APRS_LOGIN",
)
@click.option(
    "--no-ack",
    "-n",
    is_flag=True,
    show_default=True,
    default=False,
    help="Don't wait for an ack, just sent it to APRS-IS and bail.",
)
@click.option(
    "--wait-response",
    "-w",
    is_flag=True,
    show_default=True,
    default=False,
    help="Wait for a response to the message?",
)
@click.option("--raw", default=None, help="Send a raw message.  Implies --no-ack")
@click.argument("tocallsign", required=True)
@click.argument("command", nargs=-1, required=True)
@click.pass_context
@cli_helper.process_standard_options
def send_message(
    ctx,
    aprs_login,
    aprs_password,
    no_ack,
    wait_response,
    raw,
    tocallsign,
    command,
):
    """Send a message to a callsign via APRS_IS."""
    global got_ack, got_response
    config = ctx.obj["config"]
    quiet = ctx.obj["quiet"]

    if not aprs_login:
        click.echo("Must set --aprs_login or APRS_LOGIN")
        return

    if not aprs_password:
        click.echo("Must set --aprs-password or APRS_PASSWORD")
        return

    config["aprs"]["login"] = aprs_login
    config["aprs"]["password"] = aprs_password

    LOG.info(f"APRSD LISTEN Started version: {aprsd.__version__}")
    if type(command) is tuple:
        command = " ".join(command)
    if not quiet:
        if raw:
            LOG.info(f"L'{aprs_login}' R'{raw}'")
        else:
            LOG.info(f"L'{aprs_login}' To'{tocallsign}' C'{command}'")

    packets.PacketList(config=config)
    packets.WatchList(config=config)
    packets.SeenList(config=config)

    got_ack = False
    got_response = False

    def rx_packet(packet):

        resp = packet.get("response", None)
        if resp == "ack":
            ack_num = packet.get("msgNo")
            LOG.info(f"We got ack for our sent message {ack_num}")
            messaging.log_packet(packet)
            got_ack = True
        else:
            message = packet.get("message_text", None)
            fromcall = packet["from"]
            msg_number = packet.get("msgNo", "0")
            messaging.log_message(
                "Received Message",
                packet["raw"],
                message,
                fromcall=fromcall,
                ack=msg_number,
            )
            got_response = True
            # Send the ack back?
            ack = messaging.AckMessage(
                config["aprs"]["login"],
                fromcall,
                msg_id=msg_number,
            )
            ack.send_direct()

        if got_ack:
            if wait_response:
                if got_response:
                    sys.exit(0)
            else:
                sys.exit(0)

    try:
        client.ClientFactory.setup(config)
        client.factory.create().client
    except LoginError:
        sys.exit(-1)

    # Send a message
    # then we setup a consumer to rx messages
    # We should get an ack back as well as a new message
    # we should bail after we get the ack and send an ack back for the
    # message
    if raw:
        msg = messaging.RawMessage(raw)
        msg.send_direct()
        sys.exit(0)
    else:
        msg = messaging.TextMessage(aprs_login, tocallsign, command)
    msg.send_direct()

    if no_ack:
        sys.exit(0)

    try:
        # This will register a packet consumer with aprslib
        # When new packets come in the consumer will process
        # the packet
        aprs_client = client.factory.create().client
        aprs_client.consumer(rx_packet, raw=False)
    except aprslib.exceptions.ConnectionDrop:
        LOG.error("Connection dropped, reconnecting")
        time.sleep(5)
        # Force the deletion of the client object connected to aprs
        # This will cause a reconnect, next time client.get_client()
        aprs_client.reset()


import logging
import sys
import time

import aprslib
from aprslib.exceptions import LoginError
import click

import aprsd
from aprsd import cli_helper, client, messaging, packets

from ..aprsd import cli

LOG = logging.getLogger("APRSD")

@cli.command()
@cli_helper.add_options(cli_helper.common_options)
@click.option(
    "--aprs-login",
    envvar="APRS_LOGIN",
    show_envvar=True,
    help="What callsign to send the message from.",
)
@click.option(
    "--aprs-password",
    envvar="APRS_PASSWORD",
    show_envvar=True,
    help="the APRS-IS password for APRS_LOGIN",
)
@click.option(
    "--no-ack",
    "-n",
    is_flag=True,
    show_default=True,
    default=False,
    help="Don't wait for an ack, just sent it to APRS-IS and bail.",
)
@click.option(
    "--wait-response",
    "-w",
    is_flag=True,
    show_default=True,
    default=False,
    help="Wait for a response to the message?",
)
@click.option("--raw", default=None, help="Send a raw message.  Implies --no-ack")
@click.argument("tocallsign", required=True)
@click.argument("command", nargs=-1, required=True)
@click.pass_context
@cli_helper.process_standard_options
def send_message(
    ctx,
    aprs_login,
    aprs_password,
    no_ack,
    wait_response,
    raw,
    tocallsign,
    command,
):
    """Send a message to a callsign via APRS_IS."""
    global got_ack, got_response
    config = ctx.obj["config"]
    quiet = ctx.obj["quiet"]

    if not aprs_login:
        click.echo("Must set --aprs_login or APRS_LOGIN")
        return

    if not aprs_password:
        click.echo("Must set --aprs-password or APRS_PASSWORD")
        return

    config["aprs"]["login"] = aprs_login
    config["aprs"]["password"] = aprs_password

    LOG.info(f"APRSD LISTEN Started version: {aprsd.__version__}")
    if type(command) is tuple:
        command = " ".join(command)
    if not quiet:
        if raw:
            LOG.info(f"L'{aprs_login}' R'{raw}'")
        else:
            LOG.info(f"L'{aprs_login}' To'{tocallsign}' C'{command}'")

    packets.PacketList(config=config)
    packets.WatchList(config=config)
    packets.SeenList(config=config)

    got_ack = False
    got_response = False

    def rx_packet(packet):
        global got_ack, got_response
        # LOG.debug("Got packet back {}".format(packet))

        if resp == "ack":
            ack_num = packet.get("msgNo")
            LOG.info(f"We got ack for our sent message {ack_num}")
            messaging.log_packet(packet)
            got_ack = True
        else:
            message = packet.get("message_text", None)
            fromcall = packet["from"]
            msg_number = packet.get("msgNo", "0")
            messaging.log_message(
                "Received Message",
                packet["raw"],
                message,
                fromcall=fromcall,
                ack=msg_number,
            )
            got_response = True
            # Send the ack back?
            ack = messaging.AckMessage(
                config["aprs"]["login"],
                fromcall,
                msg_id=msg_number,
            )
            ack.send_direct()

        if got_ack:
            if wait_response:
                if got_response:
                    sys.exit(0)
            else:
                sys.exit(0)

    try:
        client.ClientFactory.setup(config)
        client.factory.create().client
    except LoginError:
        sys.exit(-1)

    # Send a message
    # then we setup a consumer to rx messages
    # We should get an ack back as well as a new message
    # we should bail after we get the ack and send an ack back for the
    # message
    if raw:
        msg = messaging.RawMessage(raw)
        msg.send_direct()
        sys.exit(0)
    else:
        msg = messaging.TextMessage(aprs_login, tocallsign, command)
    msg.send_direct()

    if no_ack:
        sys.exit(0)

    try:
        # This will register a packet consumer with aprslib
        # When new packets come in the consumer will process
        # the packet
        aprs_client = client.factory.create().client
        aprs_client.consumer(rx_packet, raw=False)
    except aprslib.exceptions.ConnectionDrop:
        LOG.error("Connection dropped, reconnecting")
        time.sleep(5)
        # Force the deletion of the client object connected to aprs
        # This will cause a reconnect, next time client.get_client()
        aprs_client.reset()


if resp == "ack":
            ack_num = packet.get("msgNo")
            LOG.info(f"We got ack for our sent message {ack_num}")
            messaging.log_packet(packet)
            got_ack = True
        else:
            message = packet.get("message_text", None)
            fromcall = packet["from"]
            msg_number = packet.get("msgNo", "0")
            messaging.log_message(
                "Received Message",
                packet["raw"],
                message,
                fromcall=fromcall,
                ack=msg_number,
            )
            got_response = True
            # Send the ack back?
            ack = messaging.AckMessage(
                config["aprs"]["login"],
                fromcall,
                msg_id=msg_number,
            )
            ack.send_direct()

        if got_ack:
            if wait_response:
                if got_response:
                    sys.exit(0)
            else:
                sys.exit(0)

import logging
import sys
import time

import aprslib
from aprslib.exceptions import LoginError
import click

import aprsd
from aprsd import cli_helper, client, messaging, packets

from ..aprsd import cli

LOG = logging.getLogger("APRSD")

@cli.command()
@cli_helper.add_options(cli_helper.common_options)
@click.option(
    "--aprs-login",
    envvar="APRS_LOGIN",
    show_envvar=True,
    help="What callsign to send the message from.",
)
@click.option(
    "--aprs-password",
    envvar="APRS_PASSWORD",
    show_envvar=True,
    help="the APRS-IS password for APRS_LOGIN",
)
@click.option(
    "--no-ack",
    "-n",
    is_flag=True,
    show_default=True,
    default=False,
    help="Don't wait for an ack, just sent it to APRS-IS and bail.",
)
@click.option(
    "--wait-response",
    "-w",
    is_flag=True,
    show_default=True,
    default=False,
    help="Wait for a response to the message?",
)
@click.option("--raw", default=None, help="Send a raw message.  Implies --no-ack")
@click.argument("tocallsign", required=True)
@click.argument("command", nargs=-1, required=True)
@click.pass_context
@cli_helper.process_standard_options
def send_message(
    ctx,
    aprs_login,
    aprs_password,
    no_ack,
    wait_response,
    raw,
    tocallsign,
    command,
):
    """Send a message to a callsign via APRS_IS."""
    global got_ack, got_response
    config = ctx.obj["config"]
    quiet = ctx.obj["quiet"]

    if not aprs_login:
        click.echo("Must set --aprs_login or APRS_LOGIN")
        return

    if not aprs_password:
        click.echo("Must set --aprs-password or APRS_PASSWORD")
        return

    config["aprs"]["login"] = aprs_login
    config["aprs"]["password"] = aprs_password

    LOG.info(f"APRSD LISTEN Started version: {aprsd.__version__}")
    if type(command) is tuple:
        command = " ".join(command)
    if not quiet:
        if raw:
            LOG.info(f"L'{aprs_login}' R'{raw}'")
        else:
            LOG.info(f"L'{aprs_login}' To'{tocallsign}' C'{command}'")

    packets.PacketList(config=config)
    packets.WatchList(config=config)
    packets.SeenList(config=config)

    got_ack = False
    got_response = False

    def rx_packet(packet):
        global got_ack, got_response
        # LOG.debug("Got packet back {}".format(packet))
        resp = packet.get("response", None)

    try:
        client.ClientFactory.setup(config)
        client.factory.create().client
    except LoginError:
        sys.exit(-1)

    # Send a message
    # then we setup a consumer to rx messages
    # We should get an ack back as well as a new message
    # we should bail after we get the ack and send an ack back for the
    # message
    if raw:
        msg = messaging.RawMessage(raw)
        msg.send_direct()
        sys.exit(0)
    else:
        msg = messaging.TextMessage(aprs_login, tocallsign, command)
    msg.send_direct()

    if no_ack:
        sys.exit(0)

    try:
        # This will register a packet consumer with aprslib
        # When new packets come in the consumer will process
        # the packet
        aprs_client = client.factory.create().client
        aprs_client.consumer(rx_packet, raw=False)
    except aprslib.exceptions.ConnectionDrop:
        LOG.error("Connection dropped, reconnecting")
        time.sleep(5)
        # Force the deletion of the client object connected to aprs
        # This will cause a reconnect, next time client.get_client()
        aprs_client.reset()