text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: workspaces
using AWS.Compat
using AWS.UUIDs

"""
    associate_connection_alias(alias_id, resource_id)
    associate_connection_alias(alias_id, resource_id, params::Dict{String,<:Any})

Associates the specified connection alias with the specified directory to enable
cross-Region redirection. For more information, see  Cross-Region Redirection for Amazon
WorkSpaces.  Before performing this operation, call  DescribeConnectionAliases to make sure
that the current state of the connection alias is CREATED.

# Arguments
- `alias_id`: The identifier of the connection alias.
- `resource_id`: The identifier of the directory to associate the connection alias with.

"""
associate_connection_alias(AliasId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("AssociateConnectionAlias", Dict{String, Any}("AliasId"=>AliasId, "ResourceId"=>ResourceId); aws_config=aws_config)
associate_connection_alias(AliasId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("AssociateConnectionAlias", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AliasId"=>AliasId, "ResourceId"=>ResourceId), params)); aws_config=aws_config)

"""
    associate_ip_groups(directory_id, group_ids)
    associate_ip_groups(directory_id, group_ids, params::Dict{String,<:Any})

Associates the specified IP access control group with the specified directory.

# Arguments
- `directory_id`: The identifier of the directory.
- `group_ids`: The identifiers of one or more IP access control groups.

"""
associate_ip_groups(DirectoryId, GroupIds; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("AssociateIpGroups", Dict{String, Any}("DirectoryId"=>DirectoryId, "GroupIds"=>GroupIds); aws_config=aws_config)
associate_ip_groups(DirectoryId, GroupIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("AssociateIpGroups", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DirectoryId"=>DirectoryId, "GroupIds"=>GroupIds), params)); aws_config=aws_config)

"""
    authorize_ip_rules(group_id, user_rules)
    authorize_ip_rules(group_id, user_rules, params::Dict{String,<:Any})

Adds one or more rules to the specified IP access control group. This action gives users
permission to access their WorkSpaces from the CIDR address ranges specified in the rules.

# Arguments
- `group_id`: The identifier of the group.
- `user_rules`: The rules to add to the group.

"""
authorize_ip_rules(GroupId, UserRules; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("AuthorizeIpRules", Dict{String, Any}("GroupId"=>GroupId, "UserRules"=>UserRules); aws_config=aws_config)
authorize_ip_rules(GroupId, UserRules, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("AuthorizeIpRules", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GroupId"=>GroupId, "UserRules"=>UserRules), params)); aws_config=aws_config)

"""
    copy_workspace_image(name, source_image_id, source_region)
    copy_workspace_image(name, source_image_id, source_region, params::Dict{String,<:Any})

Copies the specified image from the specified Region to the current Region. For more
information about copying images, see  Copy a Custom WorkSpaces Image.  In the China
(Ningxia) Region, you can copy images only within the same Region. In the AWS GovCloud
(US-West) Region, to copy images to and from other AWS Regions, contact AWS Support.
Before copying a shared image, be sure to verify that it has been shared from the correct
AWS account. To determine if an image has been shared and to see the AWS account ID that
owns an image, use the DescribeWorkSpaceImages and DescribeWorkspaceImagePermissions API
operations.

# Arguments
- `name`: The name of the image.
- `source_image_id`: The identifier of the source image.
- `source_region`: The identifier of the source Region.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description of the image.
- `"Tags"`: The tags for the image.
"""
copy_workspace_image(Name, SourceImageId, SourceRegion; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CopyWorkspaceImage", Dict{String, Any}("Name"=>Name, "SourceImageId"=>SourceImageId, "SourceRegion"=>SourceRegion); aws_config=aws_config)
copy_workspace_image(Name, SourceImageId, SourceRegion, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CopyWorkspaceImage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name, "SourceImageId"=>SourceImageId, "SourceRegion"=>SourceRegion), params)); aws_config=aws_config)

"""
    create_connection_alias(connection_string)
    create_connection_alias(connection_string, params::Dict{String,<:Any})

Creates the specified connection alias for use with cross-Region redirection. For more
information, see  Cross-Region Redirection for Amazon WorkSpaces.

# Arguments
- `connection_string`: A connection string in the form of a fully qualified domain name
  (FQDN), such as www.example.com.  After you create a connection string, it is always
  associated to your AWS account. You cannot recreate the same connection string with a
  different account, even if you delete all instances of it from the original account. The
  connection string is globally reserved for your account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Tags"`: The tags to associate with the connection alias.
"""
create_connection_alias(ConnectionString; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateConnectionAlias", Dict{String, Any}("ConnectionString"=>ConnectionString); aws_config=aws_config)
create_connection_alias(ConnectionString, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateConnectionAlias", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ConnectionString"=>ConnectionString), params)); aws_config=aws_config)

"""
    create_ip_group(group_name)
    create_ip_group(group_name, params::Dict{String,<:Any})

Creates an IP access control group. An IP access control group provides you with the
ability to control the IP addresses from which users are allowed to access their
WorkSpaces. To specify the CIDR address ranges, add rules to your IP access control group
and then associate the group with your directory. You can add rules when you create the
group or at any time using AuthorizeIpRules. There is a default IP access control group
associated with your directory. If you don't associate an IP access control group with your
directory, the default group is used. The default group includes a default rule that allows
users to access their WorkSpaces from anywhere. You cannot modify the default IP access
control group for your directory.

# Arguments
- `group_name`: The name of the group.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"GroupDesc"`: The description of the group.
- `"Tags"`: The tags. Each WorkSpaces resource can have a maximum of 50 tags.
- `"UserRules"`: The rules to add to the group.
"""
create_ip_group(GroupName; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateIpGroup", Dict{String, Any}("GroupName"=>GroupName); aws_config=aws_config)
create_ip_group(GroupName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateIpGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GroupName"=>GroupName), params)); aws_config=aws_config)

"""
    create_tags(resource_id, tags)
    create_tags(resource_id, tags, params::Dict{String,<:Any})

Creates the specified tags for the specified WorkSpaces resource.

# Arguments
- `resource_id`: The identifier of the WorkSpaces resource. The supported resource types
  are WorkSpaces, registered directories, images, custom bundles, IP access control groups,
  and connection aliases.
- `tags`: The tags. Each WorkSpaces resource can have a maximum of 50 tags.

"""
create_tags(ResourceId, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateTags", Dict{String, Any}("ResourceId"=>ResourceId, "Tags"=>Tags); aws_config=aws_config)
create_tags(ResourceId, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "Tags"=>Tags), params)); aws_config=aws_config)

"""
    create_workspace_bundle(bundle_description, bundle_name, compute_type, image_id, user_storage)
    create_workspace_bundle(bundle_description, bundle_name, compute_type, image_id, user_storage, params::Dict{String,<:Any})

Creates the specified WorkSpace bundle. For more information about creating WorkSpace
bundles, see  Create a Custom WorkSpaces Image and Bundle.

# Arguments
- `bundle_description`: The description of the bundle.
- `bundle_name`: The name of the bundle.
- `compute_type`:
- `image_id`: The identifier of the image that is used to create the bundle.
- `user_storage`:

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"RootStorage"`:
- `"Tags"`: The tags associated with the bundle.  To add tags at the same time when you're
  creating the bundle, you must create an IAM policy that grants your IAM user permissions to
  use workspaces:CreateTags.
"""
create_workspace_bundle(BundleDescription, BundleName, ComputeType, ImageId, UserStorage; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateWorkspaceBundle", Dict{String, Any}("BundleDescription"=>BundleDescription, "BundleName"=>BundleName, "ComputeType"=>ComputeType, "ImageId"=>ImageId, "UserStorage"=>UserStorage); aws_config=aws_config)
create_workspace_bundle(BundleDescription, BundleName, ComputeType, ImageId, UserStorage, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateWorkspaceBundle", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BundleDescription"=>BundleDescription, "BundleName"=>BundleName, "ComputeType"=>ComputeType, "ImageId"=>ImageId, "UserStorage"=>UserStorage), params)); aws_config=aws_config)

"""
    create_workspaces(workspaces)
    create_workspaces(workspaces, params::Dict{String,<:Any})

Creates one or more WorkSpaces. This operation is asynchronous and returns before the
WorkSpaces are created.

# Arguments
- `workspaces`: The WorkSpaces to create. You can specify up to 25 WorkSpaces.

"""
create_workspaces(Workspaces; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateWorkspaces", Dict{String, Any}("Workspaces"=>Workspaces); aws_config=aws_config)
create_workspaces(Workspaces, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("CreateWorkspaces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Workspaces"=>Workspaces), params)); aws_config=aws_config)

"""
    delete_connection_alias(alias_id)
    delete_connection_alias(alias_id, params::Dict{String,<:Any})

Deletes the specified connection alias. For more information, see  Cross-Region Redirection
for Amazon WorkSpaces.   If you will no longer be using a fully qualified domain name
(FQDN) as the registration code for your WorkSpaces users, you must take certain
precautions to prevent potential security issues. For more information, see  Security
Considerations if You Stop Using Cross-Region Redirection.   To delete a connection alias
that has been shared, the shared account must first disassociate the connection alias from
any directories it has been associated with. Then you must unshare the connection alias
from the account it has been shared with. You can delete a connection alias only after it
is no longer shared with any accounts or associated with any directories.

# Arguments
- `alias_id`: The identifier of the connection alias to delete.

"""
delete_connection_alias(AliasId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteConnectionAlias", Dict{String, Any}("AliasId"=>AliasId); aws_config=aws_config)
delete_connection_alias(AliasId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteConnectionAlias", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AliasId"=>AliasId), params)); aws_config=aws_config)

"""
    delete_ip_group(group_id)
    delete_ip_group(group_id, params::Dict{String,<:Any})

Deletes the specified IP access control group. You cannot delete an IP access control group
that is associated with a directory.

# Arguments
- `group_id`: The identifier of the IP access control group.

"""
delete_ip_group(GroupId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteIpGroup", Dict{String, Any}("GroupId"=>GroupId); aws_config=aws_config)
delete_ip_group(GroupId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteIpGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GroupId"=>GroupId), params)); aws_config=aws_config)

"""
    delete_tags(resource_id, tag_keys)
    delete_tags(resource_id, tag_keys, params::Dict{String,<:Any})

Deletes the specified tags from the specified WorkSpaces resource.

# Arguments
- `resource_id`: The identifier of the WorkSpaces resource. The supported resource types
  are WorkSpaces, registered directories, images, custom bundles, IP access control groups,
  and connection aliases.
- `tag_keys`: The tag keys.

"""
delete_tags(ResourceId, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteTags", Dict{String, Any}("ResourceId"=>ResourceId, "TagKeys"=>TagKeys); aws_config=aws_config)
delete_tags(ResourceId, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "TagKeys"=>TagKeys), params)); aws_config=aws_config)

"""
    delete_workspace_bundle()
    delete_workspace_bundle(params::Dict{String,<:Any})

Deletes the specified WorkSpace bundle. For more information about deleting WorkSpace
bundles, see  Delete a Custom WorkSpaces Bundle or Image.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BundleId"`: The identifier of the bundle.
"""
delete_workspace_bundle(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteWorkspaceBundle"; aws_config=aws_config)
delete_workspace_bundle(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteWorkspaceBundle", params; aws_config=aws_config)

"""
    delete_workspace_image(image_id)
    delete_workspace_image(image_id, params::Dict{String,<:Any})

Deletes the specified image from your account. To delete an image, you must first delete
any bundles that are associated with the image and unshare the image if it is shared with
other accounts.

# Arguments
- `image_id`: The identifier of the image.

"""
delete_workspace_image(ImageId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteWorkspaceImage", Dict{String, Any}("ImageId"=>ImageId); aws_config=aws_config)
delete_workspace_image(ImageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeleteWorkspaceImage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ImageId"=>ImageId), params)); aws_config=aws_config)

"""
    deregister_workspace_directory(directory_id)
    deregister_workspace_directory(directory_id, params::Dict{String,<:Any})

Deregisters the specified directory. This operation is asynchronous and returns before the
WorkSpace directory is deregistered. If any WorkSpaces are registered to this directory,
you must remove them before you can deregister the directory.  Simple AD and AD Connector
are made available to you free of charge to use with WorkSpaces. If there are no WorkSpaces
being used with your Simple AD or AD Connector directory for 30 consecutive days, this
directory will be automatically deregistered for use with Amazon WorkSpaces, and you will
be charged for this directory as per the AWS Directory Services pricing terms. To delete
empty directories, see  Delete the Directory for Your WorkSpaces. If you delete your Simple
AD or AD Connector directory, you can always create a new one when you want to start using
WorkSpaces again.

# Arguments
- `directory_id`: The identifier of the directory. If any WorkSpaces are registered to this
  directory, you must remove them before you deregister the directory, or you will receive an
  OperationNotSupportedException error.

"""
deregister_workspace_directory(DirectoryId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeregisterWorkspaceDirectory", Dict{String, Any}("DirectoryId"=>DirectoryId); aws_config=aws_config)
deregister_workspace_directory(DirectoryId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DeregisterWorkspaceDirectory", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DirectoryId"=>DirectoryId), params)); aws_config=aws_config)

"""
    describe_account()
    describe_account(params::Dict{String,<:Any})

Retrieves a list that describes the configuration of Bring Your Own License (BYOL) for the
specified account.

"""
describe_account(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeAccount"; aws_config=aws_config)
describe_account(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeAccount", params; aws_config=aws_config)

"""
    describe_account_modifications()
    describe_account_modifications(params::Dict{String,<:Any})

Retrieves a list that describes modifications to the configuration of Bring Your Own
License (BYOL) for the specified account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
"""
describe_account_modifications(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeAccountModifications"; aws_config=aws_config)
describe_account_modifications(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeAccountModifications", params; aws_config=aws_config)

"""
    describe_client_properties(resource_ids)
    describe_client_properties(resource_ids, params::Dict{String,<:Any})

Retrieves a list that describes one or more specified Amazon WorkSpaces clients.

# Arguments
- `resource_ids`: The resource identifier, in the form of directory IDs.

"""
describe_client_properties(ResourceIds; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeClientProperties", Dict{String, Any}("ResourceIds"=>ResourceIds); aws_config=aws_config)
describe_client_properties(ResourceIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeClientProperties", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceIds"=>ResourceIds), params)); aws_config=aws_config)

"""
    describe_connection_alias_permissions(alias_id)
    describe_connection_alias_permissions(alias_id, params::Dict{String,<:Any})

Describes the permissions that the owner of a connection alias has granted to another AWS
account for the specified connection alias. For more information, see  Cross-Region
Redirection for Amazon WorkSpaces.

# Arguments
- `alias_id`: The identifier of the connection alias.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
"""
describe_connection_alias_permissions(AliasId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeConnectionAliasPermissions", Dict{String, Any}("AliasId"=>AliasId); aws_config=aws_config)
describe_connection_alias_permissions(AliasId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeConnectionAliasPermissions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AliasId"=>AliasId), params)); aws_config=aws_config)

"""
    describe_connection_aliases()
    describe_connection_aliases(params::Dict{String,<:Any})

Retrieves a list that describes the connection aliases used for cross-Region redirection.
For more information, see  Cross-Region Redirection for Amazon WorkSpaces.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AliasIds"`: The identifiers of the connection aliases to describe.
- `"Limit"`: The maximum number of connection aliases to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
- `"ResourceId"`: The identifier of the directory associated with the connection alias.
"""
describe_connection_aliases(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeConnectionAliases"; aws_config=aws_config)
describe_connection_aliases(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeConnectionAliases", params; aws_config=aws_config)

"""
    describe_ip_groups()
    describe_ip_groups(params::Dict{String,<:Any})

Describes one or more of your IP access control groups.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"GroupIds"`: The identifiers of one or more IP access control groups.
- `"MaxResults"`: The maximum number of items to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
"""
describe_ip_groups(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeIpGroups"; aws_config=aws_config)
describe_ip_groups(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeIpGroups", params; aws_config=aws_config)

"""
    describe_tags(resource_id)
    describe_tags(resource_id, params::Dict{String,<:Any})

Describes the specified tags for the specified WorkSpaces resource.

# Arguments
- `resource_id`: The identifier of the WorkSpaces resource. The supported resource types
  are WorkSpaces, registered directories, images, custom bundles, IP access control groups,
  and connection aliases.

"""
describe_tags(ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeTags", Dict{String, Any}("ResourceId"=>ResourceId); aws_config=aws_config)
describe_tags(ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId), params)); aws_config=aws_config)

"""
    describe_workspace_bundles()
    describe_workspace_bundles(params::Dict{String,<:Any})

Retrieves a list that describes the available WorkSpace bundles. You can filter the results
using either bundle ID or owner, but not both.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BundleIds"`: The identifiers of the bundles. You cannot combine this parameter with any
  other filter.
- `"NextToken"`: The token for the next set of results. (You received this token from a
  previous call.)
- `"Owner"`: The owner of the bundles. You cannot combine this parameter with any other
  filter. To describe the bundles provided by AWS, specify AMAZON. To describe the bundles
  that belong to your account, don't specify a value.
"""
describe_workspace_bundles(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceBundles"; aws_config=aws_config)
describe_workspace_bundles(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceBundles", params; aws_config=aws_config)

"""
    describe_workspace_directories()
    describe_workspace_directories(params::Dict{String,<:Any})

Describes the available directories that are registered with Amazon WorkSpaces.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DirectoryIds"`: The identifiers of the directories. If the value is null, all
  directories are retrieved.
- `"Limit"`: The maximum number of directories to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
"""
describe_workspace_directories(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceDirectories"; aws_config=aws_config)
describe_workspace_directories(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceDirectories", params; aws_config=aws_config)

"""
    describe_workspace_image_permissions(image_id)
    describe_workspace_image_permissions(image_id, params::Dict{String,<:Any})

Describes the permissions that the owner of an image has granted to other AWS accounts for
an image.

# Arguments
- `image_id`: The identifier of the image.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of items to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
"""
describe_workspace_image_permissions(ImageId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceImagePermissions", Dict{String, Any}("ImageId"=>ImageId); aws_config=aws_config)
describe_workspace_image_permissions(ImageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceImagePermissions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ImageId"=>ImageId), params)); aws_config=aws_config)

"""
    describe_workspace_images()
    describe_workspace_images(params::Dict{String,<:Any})

Retrieves a list that describes one or more specified images, if the image identifiers are
provided. Otherwise, all images in the account are described.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ImageIds"`: The identifier of the image.
- `"ImageType"`: The type (owned or shared) of the image.
- `"MaxResults"`: The maximum number of items to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
"""
describe_workspace_images(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceImages"; aws_config=aws_config)
describe_workspace_images(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceImages", params; aws_config=aws_config)

"""
    describe_workspace_snapshots(workspace_id)
    describe_workspace_snapshots(workspace_id, params::Dict{String,<:Any})

Describes the snapshots for the specified WorkSpace.

# Arguments
- `workspace_id`: The identifier of the WorkSpace.

"""
describe_workspace_snapshots(WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceSnapshots", Dict{String, Any}("WorkspaceId"=>WorkspaceId); aws_config=aws_config)
describe_workspace_snapshots(WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaceSnapshots", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("WorkspaceId"=>WorkspaceId), params)); aws_config=aws_config)

"""
    describe_workspaces()
    describe_workspaces(params::Dict{String,<:Any})

Describes the specified WorkSpaces. You can filter the results by using the bundle
identifier, directory identifier, or owner, but you can specify only one filter at a time.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BundleId"`: The identifier of the bundle. All WorkSpaces that are created from this
  bundle are retrieved. You cannot combine this parameter with any other filter.
- `"DirectoryId"`: The identifier of the directory. In addition, you can optionally specify
  a specific directory user (see UserName). You cannot combine this parameter with any other
  filter.
- `"Limit"`: The maximum number of items to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
- `"UserName"`: The name of the directory user. You must specify this parameter with
  DirectoryId.
- `"WorkspaceIds"`: The identifiers of the WorkSpaces. You cannot combine this parameter
  with any other filter. Because the CreateWorkspaces operation is asynchronous, the
  identifier it returns is not immediately available. If you immediately call
  DescribeWorkspaces with this identifier, no information is returned.
"""
describe_workspaces(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaces"; aws_config=aws_config)
describe_workspaces(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspaces", params; aws_config=aws_config)

"""
    describe_workspaces_connection_status()
    describe_workspaces_connection_status(params::Dict{String,<:Any})

Describes the connection status of the specified WorkSpaces.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
- `"WorkspaceIds"`: The identifiers of the WorkSpaces. You can specify up to 25 WorkSpaces.
"""
describe_workspaces_connection_status(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspacesConnectionStatus"; aws_config=aws_config)
describe_workspaces_connection_status(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DescribeWorkspacesConnectionStatus", params; aws_config=aws_config)

"""
    disassociate_connection_alias(alias_id)
    disassociate_connection_alias(alias_id, params::Dict{String,<:Any})

Disassociates a connection alias from a directory. Disassociating a connection alias
disables cross-Region redirection between two directories in different AWS Regions. For
more information, see  Cross-Region Redirection for Amazon WorkSpaces.  Before performing
this operation, call  DescribeConnectionAliases to make sure that the current state of the
connection alias is CREATED.

# Arguments
- `alias_id`: The identifier of the connection alias to disassociate.

"""
disassociate_connection_alias(AliasId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DisassociateConnectionAlias", Dict{String, Any}("AliasId"=>AliasId); aws_config=aws_config)
disassociate_connection_alias(AliasId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DisassociateConnectionAlias", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AliasId"=>AliasId), params)); aws_config=aws_config)

"""
    disassociate_ip_groups(directory_id, group_ids)
    disassociate_ip_groups(directory_id, group_ids, params::Dict{String,<:Any})

Disassociates the specified IP access control group from the specified directory.

# Arguments
- `directory_id`: The identifier of the directory.
- `group_ids`: The identifiers of one or more IP access control groups.

"""
disassociate_ip_groups(DirectoryId, GroupIds; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DisassociateIpGroups", Dict{String, Any}("DirectoryId"=>DirectoryId, "GroupIds"=>GroupIds); aws_config=aws_config)
disassociate_ip_groups(DirectoryId, GroupIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("DisassociateIpGroups", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DirectoryId"=>DirectoryId, "GroupIds"=>GroupIds), params)); aws_config=aws_config)

"""
    import_workspace_image(ec2_image_id, image_description, image_name, ingestion_process)
    import_workspace_image(ec2_image_id, image_description, image_name, ingestion_process, params::Dict{String,<:Any})

Imports the specified Windows 10 Bring Your Own License (BYOL) image into Amazon
WorkSpaces. The image must be an already licensed Amazon EC2 image that is in your AWS
account, and you must own the image. For more information about creating BYOL images, see
Bring Your Own Windows Desktop Licenses.

# Arguments
- `ec2_image_id`: The identifier of the EC2 image.
- `image_description`: The description of the WorkSpace image.
- `image_name`: The name of the WorkSpace image.
- `ingestion_process`: The ingestion process to be used when importing the image, depending
  on which protocol you want to use for your BYOL Workspace image, either PCoIP or WorkSpaces
  Streaming Protocol (WSP). To use WSP, specify a value that ends in _WSP. To use PCoIP,
  specify a value that does not end in _WSP.  For non-GPU-enabled bundles (bundles other than
  Graphics or GraphicsPro), specify BYOL_REGULAR or BYOL_REGULAR_WSP, depending on the
  protocol.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Applications"`: If specified, the version of Microsoft Office to subscribe to. Valid
  only for Windows 10 BYOL images. For more information about subscribing to Office for BYOL
  images, see  Bring Your Own Windows Desktop Licenses.  Although this parameter is an array,
  only one item is allowed at this time.
- `"Tags"`: The tags. Each WorkSpaces resource can have a maximum of 50 tags.
"""
import_workspace_image(Ec2ImageId, ImageDescription, ImageName, IngestionProcess; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ImportWorkspaceImage", Dict{String, Any}("Ec2ImageId"=>Ec2ImageId, "ImageDescription"=>ImageDescription, "ImageName"=>ImageName, "IngestionProcess"=>IngestionProcess); aws_config=aws_config)
import_workspace_image(Ec2ImageId, ImageDescription, ImageName, IngestionProcess, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ImportWorkspaceImage", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Ec2ImageId"=>Ec2ImageId, "ImageDescription"=>ImageDescription, "ImageName"=>ImageName, "IngestionProcess"=>IngestionProcess), params)); aws_config=aws_config)

"""
    list_available_management_cidr_ranges(management_cidr_range_constraint)
    list_available_management_cidr_ranges(management_cidr_range_constraint, params::Dict{String,<:Any})

Retrieves a list of IP address ranges, specified as IPv4 CIDR blocks, that you can use for
the network management interface when you enable Bring Your Own License (BYOL).  This
operation can be run only by AWS accounts that are enabled for BYOL. If your account isn't
enabled for BYOL, you'll receive an AccessDeniedException error. The management network
interface is connected to a secure Amazon WorkSpaces management network. It is used for
interactive streaming of the WorkSpace desktop to Amazon WorkSpaces clients, and to allow
Amazon WorkSpaces to manage the WorkSpace.

# Arguments
- `management_cidr_range_constraint`: The IP address range to search. Specify an IP address
  range that is compatible with your network and in CIDR notation (that is, specify the range
  as an IPv4 CIDR block).

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of items to return.
- `"NextToken"`: If you received a NextToken from a previous call that was paginated,
  provide this token to receive the next set of results.
"""
list_available_management_cidr_ranges(ManagementCidrRangeConstraint; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ListAvailableManagementCidrRanges", Dict{String, Any}("ManagementCidrRangeConstraint"=>ManagementCidrRangeConstraint); aws_config=aws_config)
list_available_management_cidr_ranges(ManagementCidrRangeConstraint, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ListAvailableManagementCidrRanges", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ManagementCidrRangeConstraint"=>ManagementCidrRangeConstraint), params)); aws_config=aws_config)

"""
    migrate_workspace(bundle_id, source_workspace_id)
    migrate_workspace(bundle_id, source_workspace_id, params::Dict{String,<:Any})

Migrates a WorkSpace from one operating system or bundle type to another, while retaining
the data on the user volume. The migration process recreates the WorkSpace by using a new
root volume from the target bundle image and the user volume from the last available
snapshot of the original WorkSpace. During migration, the original D:Users%USERNAME% user
profile folder is renamed to D:Users%USERNAME%MMddyyTHHmmss%.NotMigrated. A new
D:Users%USERNAME% folder is generated by the new OS. Certain files in the old user profile
are moved to the new user profile. For available migration scenarios, details about what
happens during migration, and best practices, see Migrate a WorkSpace.

# Arguments
- `bundle_id`: The identifier of the target bundle type to migrate the WorkSpace to.
- `source_workspace_id`: The identifier of the WorkSpace to migrate from.

"""
migrate_workspace(BundleId, SourceWorkspaceId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("MigrateWorkspace", Dict{String, Any}("BundleId"=>BundleId, "SourceWorkspaceId"=>SourceWorkspaceId); aws_config=aws_config)
migrate_workspace(BundleId, SourceWorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("MigrateWorkspace", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BundleId"=>BundleId, "SourceWorkspaceId"=>SourceWorkspaceId), params)); aws_config=aws_config)

"""
    modify_account()
    modify_account(params::Dict{String,<:Any})

Modifies the configuration of Bring Your Own License (BYOL) for the specified account.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DedicatedTenancyManagementCidrRange"`: The IP address range, specified as an IPv4 CIDR
  block, for the management network interface. Specify an IP address range that is compatible
  with your network and in CIDR notation (that is, specify the range as an IPv4 CIDR block).
  The CIDR block size must be /16 (for example, 203.0.113.25/16). It must also be specified
  as available by the ListAvailableManagementCidrRanges operation.
- `"DedicatedTenancySupport"`: The status of BYOL.
"""
modify_account(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyAccount"; aws_config=aws_config)
modify_account(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyAccount", params; aws_config=aws_config)

"""
    modify_client_properties(client_properties, resource_id)
    modify_client_properties(client_properties, resource_id, params::Dict{String,<:Any})

Modifies the properties of the specified Amazon WorkSpaces clients.

# Arguments
- `client_properties`: Information about the Amazon WorkSpaces client.
- `resource_id`: The resource identifiers, in the form of directory IDs.

"""
modify_client_properties(ClientProperties, ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyClientProperties", Dict{String, Any}("ClientProperties"=>ClientProperties, "ResourceId"=>ResourceId); aws_config=aws_config)
modify_client_properties(ClientProperties, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyClientProperties", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClientProperties"=>ClientProperties, "ResourceId"=>ResourceId), params)); aws_config=aws_config)

"""
    modify_selfservice_permissions(resource_id, selfservice_permissions)
    modify_selfservice_permissions(resource_id, selfservice_permissions, params::Dict{String,<:Any})

Modifies the self-service WorkSpace management capabilities for your users. For more
information, see Enable Self-Service WorkSpace Management Capabilities for Your Users.

# Arguments
- `resource_id`: The identifier of the directory.
- `selfservice_permissions`: The permissions to enable or disable self-service capabilities.

"""
modify_selfservice_permissions(ResourceId, SelfservicePermissions; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifySelfservicePermissions", Dict{String, Any}("ResourceId"=>ResourceId, "SelfservicePermissions"=>SelfservicePermissions); aws_config=aws_config)
modify_selfservice_permissions(ResourceId, SelfservicePermissions, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifySelfservicePermissions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "SelfservicePermissions"=>SelfservicePermissions), params)); aws_config=aws_config)

"""
    modify_workspace_access_properties(resource_id, workspace_access_properties)
    modify_workspace_access_properties(resource_id, workspace_access_properties, params::Dict{String,<:Any})

Specifies which devices and operating systems users can use to access their WorkSpaces. For
more information, see  Control Device Access.

# Arguments
- `resource_id`: The identifier of the directory.
- `workspace_access_properties`: The device types and operating systems to enable or
  disable for access.

"""
modify_workspace_access_properties(ResourceId, WorkspaceAccessProperties; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceAccessProperties", Dict{String, Any}("ResourceId"=>ResourceId, "WorkspaceAccessProperties"=>WorkspaceAccessProperties); aws_config=aws_config)
modify_workspace_access_properties(ResourceId, WorkspaceAccessProperties, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceAccessProperties", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "WorkspaceAccessProperties"=>WorkspaceAccessProperties), params)); aws_config=aws_config)

"""
    modify_workspace_creation_properties(resource_id, workspace_creation_properties)
    modify_workspace_creation_properties(resource_id, workspace_creation_properties, params::Dict{String,<:Any})

Modify the default properties used to create WorkSpaces.

# Arguments
- `resource_id`: The identifier of the directory.
- `workspace_creation_properties`: The default properties for creating WorkSpaces.

"""
modify_workspace_creation_properties(ResourceId, WorkspaceCreationProperties; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceCreationProperties", Dict{String, Any}("ResourceId"=>ResourceId, "WorkspaceCreationProperties"=>WorkspaceCreationProperties); aws_config=aws_config)
modify_workspace_creation_properties(ResourceId, WorkspaceCreationProperties, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceCreationProperties", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "WorkspaceCreationProperties"=>WorkspaceCreationProperties), params)); aws_config=aws_config)

"""
    modify_workspace_properties(workspace_id, workspace_properties)
    modify_workspace_properties(workspace_id, workspace_properties, params::Dict{String,<:Any})

Modifies the specified WorkSpace properties. For important information about how to modify
the size of the root and user volumes, see  Modify a WorkSpace.

# Arguments
- `workspace_id`: The identifier of the WorkSpace.
- `workspace_properties`: The properties of the WorkSpace.

"""
modify_workspace_properties(WorkspaceId, WorkspaceProperties; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceProperties", Dict{String, Any}("WorkspaceId"=>WorkspaceId, "WorkspaceProperties"=>WorkspaceProperties); aws_config=aws_config)
modify_workspace_properties(WorkspaceId, WorkspaceProperties, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceProperties", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("WorkspaceId"=>WorkspaceId, "WorkspaceProperties"=>WorkspaceProperties), params)); aws_config=aws_config)

"""
    modify_workspace_state(workspace_id, workspace_state)
    modify_workspace_state(workspace_id, workspace_state, params::Dict{String,<:Any})

Sets the state of the specified WorkSpace. To maintain a WorkSpace without being
interrupted, set the WorkSpace state to ADMIN_MAINTENANCE. WorkSpaces in this state do not
respond to requests to reboot, stop, start, rebuild, or restore. An AutoStop WorkSpace in
this state is not stopped. Users cannot log into a WorkSpace in the ADMIN_MAINTENANCE state.

# Arguments
- `workspace_id`: The identifier of the WorkSpace.
- `workspace_state`: The WorkSpace state.

"""
modify_workspace_state(WorkspaceId, WorkspaceState; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceState", Dict{String, Any}("WorkspaceId"=>WorkspaceId, "WorkspaceState"=>WorkspaceState); aws_config=aws_config)
modify_workspace_state(WorkspaceId, WorkspaceState, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("ModifyWorkspaceState", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("WorkspaceId"=>WorkspaceId, "WorkspaceState"=>WorkspaceState), params)); aws_config=aws_config)

"""
    reboot_workspaces(reboot_workspace_requests)
    reboot_workspaces(reboot_workspace_requests, params::Dict{String,<:Any})

Reboots the specified WorkSpaces. You cannot reboot a WorkSpace unless its state is
AVAILABLE or UNHEALTHY. This operation is asynchronous and returns before the WorkSpaces
have rebooted.

# Arguments
- `reboot_workspace_requests`: The WorkSpaces to reboot. You can specify up to 25
  WorkSpaces.

"""
reboot_workspaces(RebootWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RebootWorkspaces", Dict{String, Any}("RebootWorkspaceRequests"=>RebootWorkspaceRequests); aws_config=aws_config)
reboot_workspaces(RebootWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RebootWorkspaces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RebootWorkspaceRequests"=>RebootWorkspaceRequests), params)); aws_config=aws_config)

"""
    rebuild_workspaces(rebuild_workspace_requests)
    rebuild_workspaces(rebuild_workspace_requests, params::Dict{String,<:Any})

Rebuilds the specified WorkSpace. You cannot rebuild a WorkSpace unless its state is
AVAILABLE, ERROR, UNHEALTHY, STOPPED, or REBOOTING. Rebuilding a WorkSpace is a potentially
destructive action that can result in the loss of data. For more information, see Rebuild a
WorkSpace. This operation is asynchronous and returns before the WorkSpaces have been
completely rebuilt.

# Arguments
- `rebuild_workspace_requests`: The WorkSpace to rebuild. You can specify a single
  WorkSpace.

"""
rebuild_workspaces(RebuildWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RebuildWorkspaces", Dict{String, Any}("RebuildWorkspaceRequests"=>RebuildWorkspaceRequests); aws_config=aws_config)
rebuild_workspaces(RebuildWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RebuildWorkspaces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RebuildWorkspaceRequests"=>RebuildWorkspaceRequests), params)); aws_config=aws_config)

"""
    register_workspace_directory(directory_id, enable_work_docs)
    register_workspace_directory(directory_id, enable_work_docs, params::Dict{String,<:Any})

Registers the specified directory. This operation is asynchronous and returns before the
WorkSpace directory is registered. If this is the first time you are registering a
directory, you will need to create the workspaces_DefaultRole role before you can register
a directory. For more information, see  Creating the workspaces_DefaultRole Role.

# Arguments
- `directory_id`: The identifier of the directory. You cannot register a directory if it
  does not have a status of Active. If the directory does not have a status of Active, you
  will receive an InvalidResourceStateException error. If you have already registered the
  maximum number of directories that you can register with Amazon WorkSpaces, you will
  receive a ResourceLimitExceededException error. Deregister directories that you are not
  using for WorkSpaces, and try again.
- `enable_work_docs`: Indicates whether Amazon WorkDocs is enabled or disabled. If you have
  enabled this parameter and WorkDocs is not available in the Region, you will receive an
  OperationNotSupportedException error. Set EnableWorkDocs to disabled, and try again.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"EnableSelfService"`: Indicates whether self-service capabilities are enabled or
  disabled.
- `"SubnetIds"`: The identifiers of the subnets for your virtual private cloud (VPC). Make
  sure that the subnets are in supported Availability Zones. The subnets must also be in
  separate Availability Zones. If these conditions are not met, you will receive an
  OperationNotSupportedException error.
- `"Tags"`: The tags associated with the directory.
- `"Tenancy"`: Indicates whether your WorkSpace directory is dedicated or shared. To use
  Bring Your Own License (BYOL) images, this value must be set to DEDICATED and your AWS
  account must be enabled for BYOL. If your account has not been enabled for BYOL, you will
  receive an InvalidParameterValuesException error. For more information about BYOL images,
  see Bring Your Own Windows Desktop Images.
"""
register_workspace_directory(DirectoryId, EnableWorkDocs; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RegisterWorkspaceDirectory", Dict{String, Any}("DirectoryId"=>DirectoryId, "EnableWorkDocs"=>EnableWorkDocs); aws_config=aws_config)
register_workspace_directory(DirectoryId, EnableWorkDocs, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RegisterWorkspaceDirectory", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DirectoryId"=>DirectoryId, "EnableWorkDocs"=>EnableWorkDocs), params)); aws_config=aws_config)

"""
    restore_workspace(workspace_id)
    restore_workspace(workspace_id, params::Dict{String,<:Any})

Restores the specified WorkSpace to its last known healthy state. You cannot restore a
WorkSpace unless its state is  AVAILABLE, ERROR, UNHEALTHY, or STOPPED. Restoring a
WorkSpace is a potentially destructive action that can result in the loss of data. For more
information, see Restore a WorkSpace. This operation is asynchronous and returns before the
WorkSpace is completely restored.

# Arguments
- `workspace_id`: The identifier of the WorkSpace.

"""
restore_workspace(WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RestoreWorkspace", Dict{String, Any}("WorkspaceId"=>WorkspaceId); aws_config=aws_config)
restore_workspace(WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RestoreWorkspace", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("WorkspaceId"=>WorkspaceId), params)); aws_config=aws_config)

"""
    revoke_ip_rules(group_id, user_rules)
    revoke_ip_rules(group_id, user_rules, params::Dict{String,<:Any})

Removes one or more rules from the specified IP access control group.

# Arguments
- `group_id`: The identifier of the group.
- `user_rules`: The rules to remove from the group.

"""
revoke_ip_rules(GroupId, UserRules; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RevokeIpRules", Dict{String, Any}("GroupId"=>GroupId, "UserRules"=>UserRules); aws_config=aws_config)
revoke_ip_rules(GroupId, UserRules, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("RevokeIpRules", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GroupId"=>GroupId, "UserRules"=>UserRules), params)); aws_config=aws_config)

"""
    start_workspaces(start_workspace_requests)
    start_workspaces(start_workspace_requests, params::Dict{String,<:Any})

Starts the specified WorkSpaces. You cannot start a WorkSpace unless it has a running mode
of AutoStop and a state of STOPPED.

# Arguments
- `start_workspace_requests`: The WorkSpaces to start. You can specify up to 25 WorkSpaces.

"""
start_workspaces(StartWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("StartWorkspaces", Dict{String, Any}("StartWorkspaceRequests"=>StartWorkspaceRequests); aws_config=aws_config)
start_workspaces(StartWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("StartWorkspaces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("StartWorkspaceRequests"=>StartWorkspaceRequests), params)); aws_config=aws_config)

"""
    stop_workspaces(stop_workspace_requests)
    stop_workspaces(stop_workspace_requests, params::Dict{String,<:Any})

 Stops the specified WorkSpaces. You cannot stop a WorkSpace unless it has a running mode
of AutoStop and a state of AVAILABLE, IMPAIRED, UNHEALTHY, or ERROR.

# Arguments
- `stop_workspace_requests`: The WorkSpaces to stop. You can specify up to 25 WorkSpaces.

"""
stop_workspaces(StopWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("StopWorkspaces", Dict{String, Any}("StopWorkspaceRequests"=>StopWorkspaceRequests); aws_config=aws_config)
stop_workspaces(StopWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("StopWorkspaces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("StopWorkspaceRequests"=>StopWorkspaceRequests), params)); aws_config=aws_config)

"""
    terminate_workspaces(terminate_workspace_requests)
    terminate_workspaces(terminate_workspace_requests, params::Dict{String,<:Any})

Terminates the specified WorkSpaces.  Terminating a WorkSpace is a permanent action and
cannot be undone. The user's data is destroyed. If you need to archive any user data,
contact AWS Support before terminating the WorkSpace.  You can terminate a WorkSpace that
is in any state except SUSPENDED. This operation is asynchronous and returns before the
WorkSpaces have been completely terminated. After a WorkSpace is terminated, the TERMINATED
state is returned only briefly before the WorkSpace directory metadata is cleaned up, so
this state is rarely returned. To confirm that a WorkSpace is terminated, check for the
WorkSpace ID by using  DescribeWorkSpaces. If the WorkSpace ID isn't returned, then the
WorkSpace has been successfully terminated.  Simple AD and AD Connector are made available
to you free of charge to use with WorkSpaces. If there are no WorkSpaces being used with
your Simple AD or AD Connector directory for 30 consecutive days, this directory will be
automatically deregistered for use with Amazon WorkSpaces, and you will be charged for this
directory as per the AWS Directory Services pricing terms. To delete empty directories, see
 Delete the Directory for Your WorkSpaces. If you delete your Simple AD or AD Connector
directory, you can always create a new one when you want to start using WorkSpaces again.

# Arguments
- `terminate_workspace_requests`: The WorkSpaces to terminate. You can specify up to 25
  WorkSpaces.

"""
terminate_workspaces(TerminateWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("TerminateWorkspaces", Dict{String, Any}("TerminateWorkspaceRequests"=>TerminateWorkspaceRequests); aws_config=aws_config)
terminate_workspaces(TerminateWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("TerminateWorkspaces", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TerminateWorkspaceRequests"=>TerminateWorkspaceRequests), params)); aws_config=aws_config)

"""
    update_connection_alias_permission(alias_id, connection_alias_permission)
    update_connection_alias_permission(alias_id, connection_alias_permission, params::Dict{String,<:Any})

Shares or unshares a connection alias with one account by specifying whether that account
has permission to associate the connection alias with a directory. If the association
permission is granted, the connection alias is shared with that account. If the association
permission is revoked, the connection alias is unshared with the account. For more
information, see  Cross-Region Redirection for Amazon WorkSpaces.    Before performing this
operation, call  DescribeConnectionAliases to make sure that the current state of the
connection alias is CREATED.   To delete a connection alias that has been shared, the
shared account must first disassociate the connection alias from any directories it has
been associated with. Then you must unshare the connection alias from the account it has
been shared with. You can delete a connection alias only after it is no longer shared with
any accounts or associated with any directories.

# Arguments
- `alias_id`: The identifier of the connection alias that you want to update permissions
  for.
- `connection_alias_permission`: Indicates whether to share or unshare the connection alias
  with the specified AWS account.

"""
update_connection_alias_permission(AliasId, ConnectionAliasPermission; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateConnectionAliasPermission", Dict{String, Any}("AliasId"=>AliasId, "ConnectionAliasPermission"=>ConnectionAliasPermission); aws_config=aws_config)
update_connection_alias_permission(AliasId, ConnectionAliasPermission, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateConnectionAliasPermission", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AliasId"=>AliasId, "ConnectionAliasPermission"=>ConnectionAliasPermission), params)); aws_config=aws_config)

"""
    update_rules_of_ip_group(group_id, user_rules)
    update_rules_of_ip_group(group_id, user_rules, params::Dict{String,<:Any})

Replaces the current rules of the specified IP access control group with the specified
rules.

# Arguments
- `group_id`: The identifier of the group.
- `user_rules`: One or more rules.

"""
update_rules_of_ip_group(GroupId, UserRules; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateRulesOfIpGroup", Dict{String, Any}("GroupId"=>GroupId, "UserRules"=>UserRules); aws_config=aws_config)
update_rules_of_ip_group(GroupId, UserRules, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateRulesOfIpGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("GroupId"=>GroupId, "UserRules"=>UserRules), params)); aws_config=aws_config)

"""
    update_workspace_bundle()
    update_workspace_bundle(params::Dict{String,<:Any})

Updates a WorkSpace bundle with a new image. For more information about updating WorkSpace
bundles, see  Update a Custom WorkSpaces Bundle.  Existing WorkSpaces aren't automatically
updated when you update the bundle that they're based on. To update existing WorkSpaces
that are based on a bundle that you've updated, you must either rebuild the WorkSpaces or
delete and recreate them.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"BundleId"`: The identifier of the bundle.
- `"ImageId"`: The identifier of the image.
"""
update_workspace_bundle(; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateWorkspaceBundle"; aws_config=aws_config)
update_workspace_bundle(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateWorkspaceBundle", params; aws_config=aws_config)

"""
    update_workspace_image_permission(allow_copy_image, image_id, shared_account_id)
    update_workspace_image_permission(allow_copy_image, image_id, shared_account_id, params::Dict{String,<:Any})

Shares or unshares an image with one account in the same AWS Region by specifying whether
that account has permission to copy the image. If the copy image permission is granted, the
image is shared with that account. If the copy image permission is revoked, the image is
unshared with the account. After an image has been shared, the recipient account can copy
the image to other AWS Regions as needed.  In the China (Ningxia) Region, you can copy
images only within the same Region. In the AWS GovCloud (US-West) Region, to copy images to
and from other AWS Regions, contact AWS Support.  For more information about sharing
images, see  Share or Unshare a Custom WorkSpaces Image.    To delete an image that has
been shared, you must unshare the image before you delete it.   Sharing Bring Your Own
License (BYOL) images across AWS accounts isn't supported at this time in the AWS GovCloud
(US-West) Region. To share BYOL images across accounts in the AWS GovCloud (US-West)
Region, contact AWS Support.

# Arguments
- `allow_copy_image`: The permission to copy the image. This permission can be revoked only
  after an image has been shared.
- `image_id`: The identifier of the image.
- `shared_account_id`: The identifier of the AWS account to share or unshare the image
  with.  Before sharing the image, confirm that you are sharing to the correct AWS account
  ID.

"""
update_workspace_image_permission(AllowCopyImage, ImageId, SharedAccountId; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateWorkspaceImagePermission", Dict{String, Any}("AllowCopyImage"=>AllowCopyImage, "ImageId"=>ImageId, "SharedAccountId"=>SharedAccountId); aws_config=aws_config)
update_workspace_image_permission(AllowCopyImage, ImageId, SharedAccountId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = workspaces("UpdateWorkspaceImagePermission", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AllowCopyImage"=>AllowCopyImage, "ImageId"=>ImageId, "SharedAccountId"=>SharedAccountId), params)); aws_config=aws_config)


text:
using Flux
using Zygote
using MAT
#using Plots
using Statistics
using Distributions
using LinearAlgebra
using Random
using BSON
using JLD
using PyPlot
using CUDA
#using Base.Iterators: partition

NVol = 7 # number of volumes
#=
mf = matopen("/home/naxos2-raid1/maxiao/Projects/pTXDL/JuliaPrograms/ImageBasedDLForpTX.jl/Data/Data_processed_7Vol.mat")
Xtrain = read(mf, "Xtrain")
Ytrain = read(mf, "Ytrain")
close(mf)

for idx_subj = 1:size(Xtrain,5)
    Xtrain[:,:,:,:,idx_subj] = Xtrain[:,:,:,:,idx_subj]./maximum(Xtrain[:,:,:,:,idx_subj])
    Ytrain[:,:,:,:,idx_subj] = Ytrain[:,:,:,:,idx_subj]./maximum(Ytrain[:,:,:,:,idx_subj])
end

Xall = Xtrain
Yall = Ytrain

Xtrain = Xall[:,:,:,:,1:4]
Ytrain = Yall[:,:,:,:,1:4]

Sall = size(Xtrain)
Xtrain = reshape(Xtrain,Sall[1],Sall[2],1,Sall[3]*Sall[4]*Sall[5])

Sall = size(Ytrain)
Ytrain = reshape(Ytrain,Sall[1],Sall[2],1,Sall[3]*Sall[4]*Sall[5])

XValid = Xall[:,:,:,:,5]
YValid = Yall[:,:,:,:,5]

Xall = nothing;
Yall = nothing;

mf = matopen("/home/naxos2-raid1/maxiao/Projects/pTXDL/JuliaPrograms/ImageBasedDLForpTX.jl/Data/T1wBrain_processed.mat")
T1wBrain_resize_ds = read(mf, "T1wBrain_resize_ds")
close(mf)

for idx_subj = 1:size(T1wBrain_resize_ds,4)
    T1wBrain_resize_ds[:,:,:,idx_subj] = T1wBrain_resize_ds[:,:,:,idx_subj]./maximum(T1wBrain_resize_ds[:,:,:,idx_subj])
end

Xtrain_new = zeros(Float32,size(Xtrain,1),size(Xtrain,1),2,size(Xtrain,4))
Xtrain_new[:,:,1,:] = Xtrain
Xtrain_new[:,:,2,:] = reshape(repeat(T1wBrain_resize_ds[:,:,:,1:4],1,1,NVol,1),size(Xtrain,1),size(Xtrain,1),1,size(Xtrain,4))

Xtrain = Xtrain_new
Xtrain_new=nothing

Sall = size(XValid)
XValid = reshape(XValid,Sall[1],Sall[2],1,Sall[3]*Sall[4])
YValid = reshape(YValid,Sall[1],Sall[2],1,Sall[3]*Sall[4])

XValid_new = zeros(Float32,size(XValid,1),size(XValid,1),2,size(XValid,4))
XValid_new[:,:,1,:] = XValid
XValid_new[:,:,2,:] = reshape(repeat(T1wBrain_resize_ds[:,:,:,5],1,1,NVol),size(XValid,1),size(XValid,1),1,size(XValid,4))

XValid = XValid_new
XValid_new=nothing

#fig, ax = plt.subplots();PyPlot.gray();ax.imshow(abs.(Xtrain[:,:,1,1*100+50,1]))

JLD.save("Data/XYtrain_XYvalid_processed_7Vol_T1w.jld","Xtrain",Xtrain,"Ytrain",Ytrain,"XValid",XValid,"YValid",YValid)
=#

gpu_id = 1
CUDA.device!(gpu_id)

Xtrain = JLD.load("Data/XYtrain_XYvalid_processed_7Vol_T1w.jld","Xtrain")
Ytrain = JLD.load("Data/XYtrain_XYvalid_processed_7Vol_T1w.jld","Ytrain")
XValid = JLD.load("Data/XYtrain_XYvalid_processed_7Vol_T1w.jld","XValid")
YValid = JLD.load("Data/XYtrain_XYvalid_processed_7Vol_T1w.jld","YValid")

idx_shuffle = shuffle(collect(1:size(Xtrain,4)))
Xtrain = Xtrain[:,:,1,idx_shuffle]
Ytrain = Ytrain[:,:,:,idx_shuffle]

Xtrain = reshape(Xtrain,size(Xtrain,1),size(Xtrain,1),1,size(Xtrain,3))

Xtrain = gpu(Xtrain)
Ytrain = gpu(Ytrain)

batch_size = 10

train_loader = Flux.Data.DataLoader(Xtrain,Ytrain, batchsize=batch_size,shuffle=true)

XValid = XValid[:,:,1,:]
XValid = reshape(XValid,size(XValid,1),size(XValid,1),1,size(XValid,3))

XValid = gpu(XValid)
YValid = gpu(YValid)

channels_in=1
channels_out=1

# Unet define
function _random_normal(shape...)
  return Float32.(rand(Normal(0.f0,0.02f0),shape...))
end

expand_dims(x,n::Int) = reshape(x,ones(Int64,n)...,size(x)...)
function squeeze(x)
    if size(x)[end] != 1
        return dropdims(x, dims = tuple(findall(size(x) .== 1)...))
    else
        # For the case BATCH_SIZE = 1
        int_val = dropdims(x, dims = tuple(findall(size(x) .== 1)...))
        return reshape(int_val,size(int_val)...,1)
    end
end

BatchNormWrap(out_ch) = BatchNorm(out_ch)

UNetConvBlock(in_chs, out_chs, kernel = (3, 3)) =
    Chain(Conv(kernel, in_chs=>out_chs,pad = (1, 1);init=_random_normal),
	BatchNormWrap(out_chs),
	x->leakyrelu.(x,0.2f0))

ConvDown(in_chs,out_chs,kernel = (4,4)) =
  Chain(Conv(kernel,in_chs=>out_chs,pad=(1,1),stride=(2,2);init=_random_normal),
	BatchNormWrap(out_chs),
	x->leakyrelu.(x,0.2f0))

UNetUpBlock(in_chs, out_chs; kernel = (3, 3), p = 0.5f0) =
  Chain(x->leakyrelu.(x,0.2f0),
  	ConvTranspose((2, 2), in_chs=>out_chs,stride=(2, 2);init=_random_normal),
	BatchNormWrap(out_chs),
	Dropout(p))

u = Chain(
       UNetConvBlock(channels_in, 64),
       UNetConvBlock(64, 64), #op
       SkipConnection(Chain(ConvDown(64,64),
                            UNetConvBlock(64, 128),
                            UNetConvBlock(128, 128),#x1
                            SkipConnection(Chain(ConvDown(128,128),
		                                 UNetConvBlock(128, 256),
		                                 UNetConvBlock(256, 256),#x2
		                                 SkipConnection(Chain(ConvDown(256,256),
				                                      UNetConvBlock(256, 512),
				                                      UNetConvBlock(512, 512),#x3
				                                      SkipConnection(Chain(ConvDown(512,512),
					                                                   UNetConvBlock(512, 1024),#x4
					                                                   UNetConvBlock(1024, 1024),#up_x4
					                                                   UNetUpBlock(1024,512)),
					                                                   (mx,x)->cat(mx,x,dims=3)),
				                                      UNetConvBlock(1024, 512),
				                                      UNetConvBlock(512, 512),#up_x1
				                                      UNetUpBlock(512,256)),
				                                      (mx,x)->cat(mx,x,dims=3)),
                                                 UNetConvBlock(512, 256),
                                                 UNetConvBlock(256, 256),#up_x2
                                                 UNetUpBlock(256,128)),
                                                 (mx,x)->cat(mx,x,dims=3)),
                            UNetConvBlock(256, 128),
                            UNetConvBlock(128, 128),#up_x3
                            UNetUpBlock(128,64)),
                            (mx,x)->cat(mx,x,dims=3)),
       UNetConvBlock(128, 64),
       UNetConvBlock(64, 64),#up_x5
       Chain(x->leakyrelu.(x,0.2f0),Conv((1, 1), 64=>channels_out;init=_random_normal))
)

u = gpu(u)

#loss(x,y) = mean(abs,(u(x).-y))
loss(x,y) = mean((u(x).-y).^2)
validationloss() = mean(Flux.mse(u(XValid[:,:,:,(idx-1)*100+1:idx*100]),YValid[:,:,:,(idx-1)*100+1:idx*100]) for idx=1:round(Int,size(XValid,4)/100))
#validationloss() = mean(mean(abs,(u(XValid[:,:,:,(idx-1)*100+1:idx*100]).-YValid[:,:,:,(idx-1)*100+1:idx*100])) for idx=1:round(Int,size(XValid,4)/100))

opt = ADAM(0.001)

function my_custom_train!(loss, ps, data, opt)
    # training_loss is declared local so it will be available for logging outside the gradient calculation.
    local training_loss
    ps = Params(ps)
    for d in data
      if d isa AbstractArray{<:Number}
        gs = Flux.gradient(ps) do
          training_loss = loss(d)
          return training_loss
        end
      else
        gs = Flux.gradient(ps) do
          training_loss = loss(d...)
          return training_loss
        end
      end
      # Insert whatever code you want here that needs training_loss, e.g. logging.
      # logging_callback(training_loss)
      # Insert what ever code you want here that needs gradient.
      # E.g. logging with TensorBoardLogger.jl as histogram so you can see if it is becoming huge.
      #println("training_loss = ",training_loss,"; gradient[1] = ",gs[ps[1]],"; W1 = ",ps.order.data[1][1],"; b1 = ",ps.order.data[2][1])
      println("training_loss = ",training_loss)
      Flux.update!(opt, ps, gs)
      # Here you might like to check validation set accuracy, and break out to do early stopping.
    end
  end

loss_valid = zeros(30)
for epoch in 1:30
  learn_rate = 0.001*exp(log(0.1)/99*(epoch-1))
  opt = ADAM(learn_rate)
  @time Flux.train!(loss, Flux.params(u), train_loader, opt)
#  @time my_custom_train!(loss, Flux.params(u), train_loader, opt)
  #@time Flux.train!(loss, Flux.params(u), train_set, opt)
  #model = cpu(u)
  #BSON.@save string("Results/model_resnet_ptx_processed_7dir_gpu_epoch",string(epoch),".bson") model
  #u = gpu(model)
  loss_valid[epoch] = validationloss()
end
model = cpu(u)
BSON.@save string("Results/model_unet_ptx_processed_7Vol_gpu_epoch30.bson") model

#test

BSON.@load string("Results/model_unet_ptx_processed_7Vol_gpu_epoch30.bson") model
slc_list = collect(1:100)
dir_list = collect(1:NVol)
XtestOutput4write = zeros(size(XValid,1),size(XValid,2),length(slc_list),length(dir_list))

Xtest = zeros(Float32,size(XValid,1),size(XValid,2),1,1)
Ytest = zeros(Float32,size(XValid,1),size(XValid,2),1,1)
for idx_dir_test in 1:length(dir_list)
  for idx_slc_test in 1:length(slc_list)
    idx_test = idx_slc_test + (idx_dir_test-1)*100
    Xtest[:,:,:,1] = XValid[:,:,:,idx_test]
    #Ytest[:,:,1,1] = YValid[:,:,idx_slc_test,idx_dir_test]
    XtestOutput4write[:,:,idx_slc_test,idx_dir_test] = model(Xtest)
  end
end

file = matopen("Results/XValidOutput_subj5_processed_7Vol_gpu_unet_epoch30.mat", "w")
write(file, "XtestOutput4write", XtestOutput4write)
close(file)

# testing on training data
BSON.@load string("model_unet_ptx_processed_7dir_epoch",string(10),".bson") u
XValid = Xtrain[:,:,:,1:700]
XValid = reshape(XValid,size(XValid,1),size(XValid,2),100,7)
XtestOutput4write = zeros(size(XValid))

Xtest = zeros(Float32,size(XValid,1),size(XValid,2),1,1)
Ytest = zeros(Float32,size(XValid,1),size(XValid,2),1,1)
for idx_dir_test in 1:size(XValid,4)
  for idx_slc_test in 1:size(XValid,3)
    Xtest[:,:,1,1] = XValid[:,:,idx_slc_test,idx_dir_test]
    #Ytest[:,:,1,1] = YValid[:,:,idx_slc_test,idx_dir_test]
    XtestOutput4write[:,:,idx_slc_test,idx_dir_test] = u(Xtest)
  end
end

file = matopen("XValidOutput_traingsubj1_processed_7dir_epoch10.mat", "w")
write(file, "XtestOutput4write", XtestOutput4write)
close(file)

ext: jl


text:
#--------------------------------------
## LOAD PACKAGES
using RegNeuralDE, OrdinaryDiffEq, Flux, DiffEqFlux, Tracker, Random, Statistics
using YAML, Dates, BSON, NNlib
using CUDA
using RegNeuralDE: loglikelihood
using Flux.Optimise: update!
using Flux: @functor
using Tracker: TrackedReal, data
import Base.show

CUDA.allowscalar(false)
#--------------------------------------

#--------------------------------------
## CONFIGURATION
## Training Parameters
config_file = joinpath(pwd(), "experiments", "configs", "ffjord_gaussian.yml")
config = YAML.load_file(config_file)

Random.seed!(config["seed"])

hparams = config["hyperparameters"]
const BATCH_SIZE = hparams["batch_size"]
const REGULARIZE = hparams["regularize"]
EPOCHS = hparams["epochs"]
EXPERIMENT_LOGDIR =
    joinpath(pwd(), "results", "ffjord_gaussian", "$(string(now()))_$REGULARIZE")
MODEL_WEIGHTS = joinpath(EXPERIMENT_LOGDIR, "weights.bson")
FILENAME = joinpath(EXPERIMENT_LOGDIR, "results.yml")

# Create a directory to store the results
isdir(EXPERIMENT_LOGDIR) || mkpath(EXPERIMENT_LOGDIR)
cp(config_file, joinpath(EXPERIMENT_LOGDIR, "config.yml"))
#--------------------------------------

#--------------------------------------
# CUSTOM NN DYNAMICS
function NNlib.σ(x)
    t = CUDA.exp(-abs(x))
    ifelse(x ≥ 0, inv(1 + t), t / (1 + t))
end

NNlib.softplus(x) = ifelse(x > 0, x + CUDA.log1p(CUDA.exp(-x)), CUDA.log1p(CUDA.exp(x)))

_transpose(x) = permutedims(x, (2, 1))

struct ConcatSquashLinear{LW,LB,BW,BB,GW}
    layer_W::LW
    layer_B::LB
    bias_W::BW
    bias_B::BB
    gate_W::GW
end

ConcatSquashLinear(in_dims::Int, out_dims::Int) = ConcatSquashLinear(
    Flux.glorot_uniform(out_dims, in_dims),
    zeros(Float32, out_dims, 1),
    Flux.glorot_uniform(out_dims, 1),
    zeros(Float32, out_dims, 1),
    Flux.glorot_uniform(out_dims, 1),
)

@functor ConcatSquashLinear

(csl::ConcatSquashLinear)(x, t) =
    (csl.layer_W * x .+ csl.layer_B) .* σ.(csl.gate_W * t) .+ (csl.bias_W * t .+ csl.bias_B)

function forw_n_back(csl::ConcatSquashLinear, x, t)
    z1 = csl.layer_W * x .+ csl.layer_B
    z2 = σ.(csl.gate_W * t)
    z3 = csl.bias_W * t .+ csl.bias_B
    r = @. z1 * z2 + z3

    return r, e -> _transpose(csl.layer_W .* z2) * e
end

struct MLPDynamics{LW,LB,BW,BB,GW}
    csl1::ConcatSquashLinear{LW,LB,BW,BB,GW}
    csl2::ConcatSquashLinear{LW,LB,BW,BB,GW}
    csl3::ConcatSquashLinear{LW,LB,BW,BB,GW}
end

@functor MLPDynamics

MLPDynamics(in_dims::Int, hsize::Int) = MLPDynamics(
    ConcatSquashLinear(in_dims, hsize),
    ConcatSquashLinear(hsize, hsize),
    ConcatSquashLinear(hsize, in_dims),
)

function (nn::MLPDynamics)(x, t)
    _t = CUDA.ones(1, 1) .* t
    return nn.csl3(softplus.(nn.csl2(softplus.(nn.csl1(x, _t)), _t)), _t)
end

function forw_n_back(nn::MLPDynamics, x, t, e)
    _t = CUDA.ones(1, 1) .* t
    z1, back1 = forw_n_back(nn.csl1, x, _t)
    tz1 = softplus.(z1)
    z2, back2 = forw_n_back(nn.csl2, tz1, _t)
    tz2 = softplus.(z2)
    z3, back3 = forw_n_back(nn.csl3, tz2, _t)

    return z3, back1(σ.(z1) .* back2(σ.(z2) .* back3(e)))
end
#--------------------------------------

#--------------------------------------
## SETUP THE MODELS + DATASET + TRAINING UTILS
# Get the dataset
train_dataloader, test_dataloader =
    load_gaussian_mixture(BATCH_SIZE, x -> gpu(x), ngaussians = 6, nsamples = 2048)

nn_dynamics = MLPDynamics(2, 16) |> track |> gpu

ffjord = TrackedFFJORD(
    nn_dynamics,
    [0.0f0, 1.0f0],
    true,
    REGULARIZE,
    Tsit5(),
    save_everystep = false,
    reltol = 1.4f-8,
    abstol = 1.4f-8,
    save_start = false,
    dynamics = forw_n_back,
)

ps = Flux.trainable(ffjord)

opt = Flux.Optimise.Optimiser(WeightDecay(1e-5), ADAM(4e-2))

# Anneal the regularization so that it doesn't overpower the
# the main objective
λ₀ = 2.0f3
λ₁ = 1.0f3
k = log(λ₀ / λ₁) / EPOCHS
# Exponential Decay
λ_func(t) = λ₀ * exp(-k * t)

function loss_function(x, model, p; λᵣ = 1.0f2, notrack = false)
    logpx, r1, r2, nfe, sv = model(x, p)
    neg_log_likelihood = -mean(logpx)
    reg = REGULARIZE ? λᵣ * mean(sv.saveval) : 0.0f0
    total_loss = neg_log_likelihood + reg
    if !notrack
        ll_un = neg_log_likelihood |> untrack
        reg_un = reg |> untrack
        total_loss_un = total_loss |> untrack
        logger(
            false,
            Dict(
                "Total Loss" => total_loss_un,
                "Negative Log Likelihood" => ll_un,
                "Regularization" => reg_un,
            ),
        )
    end
    return total_loss
end
#--------------------------------------

#--------------------------------------
## LOGGING UTILITIES
nfe_counts = Vector{Float64}(undef, EPOCHS + 1)
train_loglikelihood = Vector{Float64}(undef, EPOCHS + 1)
test_loglikelihood = Vector{Float64}(undef, EPOCHS + 1)
train_runtimes = Vector{Float64}(undef, EPOCHS + 1)
inference_runtimes = Vector{Float64}(undef, EPOCHS + 1)
train_runtimes[1] = 0

logger = table_logger(
    [
        "Epoch Number",
        "NFE Count",
        "Train Log Likelihood",
        "Test Log Likelihood",
        "Train Runtime",
        "Inference Runtime",
    ],
    ["Total Loss", "Negative Log Likelihood", "Regularization"],
)
#--------------------------------------

#--------------------------------------
## RECORD DETAILS BEFORE TRAINING STARTS
const dummy_data = train_dataloader.data[:, 1:BATCH_SIZE] |> gpu
_start_time = time()
_logpx, _r1, _r2, _nfe, _sv = ffjord(dummy_data)
inference_runtimes[1] = time() - _start_time
train_runtimes[1] = 0.0
nfe_counts[1] = _nfe
train_loglikelihood[1] = data(loglikelihood(ffjord, train_dataloader))
test_loglikelihood[1] = data(loglikelihood(ffjord, test_dataloader))

logger(
    false,
    Dict(),
    0.0,
    nfe_counts[1],
    train_loglikelihood[1],
    test_loglikelihood[1],
    train_runtimes[1],
    inference_runtimes[1],
)
#--------------------------------------

#--------------------------------------
## WARMSTART THE GRADIENT COMPUTATION
Tracker.gradient(p -> loss_function(dummy_data, ffjord, p; notrack = true), ffjord.p)
#--------------------------------------

#--------------------------------------
## TRAINING
for epoch = 1:EPOCHS
    λᵣ = λ_func(epoch - 1)
    timing = 0

    for (i, x_) in enumerate(train_dataloader)
        x = x_ |> gpu

        start_time = time()
        gs = Tracker.gradient(p -> loss_function(x, ffjord, p; λᵣ = λᵣ), ps...)
        update_parameters!(ps, gs, opt)
        timing += time() - start_time

        x = nothing
        GC.gc(true)
    end

    # Record the time per epoch
    train_runtimes[epoch+1] = timing

    # Record the NFE count
    start_time = time()
    _, _, _, nfe, _ = ffjord(dummy_data)
    inference_runtimes[epoch+1] = time() - start_time
    nfe_counts[epoch+1] = nfe

    train_loglikelihood[epoch+1] = data(loglikelihood(ffjord, train_dataloader))
    test_loglikelihood[epoch+1] = data(loglikelihood(ffjord, test_dataloader))

    logger(
        false,
        Dict(),
        epoch,
        nfe_counts[epoch+1],
        train_loglikelihood[epoch+1],
        test_loglikelihood[epoch+1],
        train_runtimes[epoch+1],
        inference_runtimes[epoch+1],
    )
end
logger(true, Dict())

# Log the time to generate samples
timings = []
for i = 1:10
    t = time()
    sample(ffjord, 2, ps[1]; nsamples = BATCH_SIZE)
    push!(timings, time() - t)
end
println("Time for Sampling $(BATCH_SIZE) data points: $(minimum(timings)) s")
#--------------------------------------

#--------------------------------------
## STORE THE RESULTS
results = Dict(
    :nfe_counts => nfe_counts,
    :train_likelihood => train_loglikelihood,
    :test_likelihood => test_loglikelihood,
    :train_runtimes => train_runtimes,
    :inference_runtimes => inference_runtimes,
    :sampling_time => minimum(timings),
)

weights = Flux.params(ffjord) .|> cpu .|> untrack
BSON.@save MODEL_WEIGHTS weights

YAML.write_file(FILENAME, results)
#--------------------------------------


text:
#############################################################
# Define types
#############################################################
abstract type Model end  # General type for any model

# DDCbasic model type as described by Abbring and Klein
# Type gathers model parameters, and offers additional options (see below )
# Uses Parameters.jl, to define default values

@with_kw mutable struct DDCbasic <: Model
	supportX::Vector 		# Support points of profit state X_t
	Π::Matrix				# Transition matrix between profit states
	β::Vector				# Profit parameters
	δ::Vector				# Entry/exit cost parameters
	ρ::Float64 				# discount factor
	options = Options()		# Additional options
end

# Options structure gathering additional model/estimation options
@with_kw mutable struct Options
    # tolerance level for inner fixed point
	tol_fixed_point::Float64 = 1e-10
    # seed for data generation, and simulation
	seed::Int = 42
    # Optimization algorithm (default LBFGS() from Optim.jl)
    # For alternatives see Optimization.jl, which is used to
    # implement optimization routine
	algo = LBFGS()
    # Automatic differentiation package (see Optimization.jl for options)
	AD = Optimization.AutoForwardDiff()
end


text:
#=

  de Bruijn sequences in Julia.

  See http://en.wikipedia.org/wiki/De_Bruijn_sequence
  """
  In combinatorial mathematics, a de Bruijn sequence of order n on
  a size-k alphabet A is a cyclic sequence in which every possible
  length-n string on A occurs exactly once as a substring (i.e., as
  a contiguous subsequence). Such a sequence is denoted by B(k, n)
  and has length kn, which is also the number of distinct strings of
  length n on A. Each of these distinct strings, when taken as
  a substring of B(k, n), must start at a different position, because
  substrings starting at the same position are not distinct. Therefore,
  B(k, n) must have at least kn symbols. And since B(k, n) has exactly kn
  symbols, De Bruijn sequences are optimally short with respect to the
  property of containing every string of length n exactly once.
  """

  This is a port of the JavaScript version
  http://www.hakank.org/javascript_progs/debruijn.jl
  which is a a port of (a part of) the original C program with
  the following copyright:

    -----------------------------------------------------------------------------
    | C program to generate necklaces, Lyndon words, and De Bruijn              |
    | sequences.  The algorithm is CAT and is described in the book             |
    | "Combinatorial Generation."  This program, was obtained from the          |
    | (Combinatorial) Object Server, COS, at http://www.theory.csc.uvic.ca/~cos |
    | The inputs are n, the length of the string, k, the arity of the           |
    | string, and density, the maximum number of non-0's in the string.         |
    | The De Bruijn option doesn't make sense unless density >= n.              |
    | The program can be modified, translated to other languages, etc.,         |
    | so long as proper acknowledgement is given (author and source).           |
    | Programmer: Frank Ruskey (1994), translated to C by Joe Sawada            |
    -----------------------------------------------------------------------------

  Note: Two adjustments has been done to the algorithm cited above
  - adjusted to 1-based
  - moved the global variables to a dict ("s")

  Compare with my web based programs:
  - http://www.hakank.org/comb/debruijn.cgi
  - http://www.hakank.org/comb/deBruijnApplet.html
  - http://www.hakank.org/javascript_progs/debruijn.html

  Syntax:
    $ julia debruijn.jl <k> <n> <p>
      where
       n: the language: 0..n-1
       k: length of each sub sequence
       p: if a flatten version should be printed as well

  Examples:

    $ julia debruijn.jl 2 3 1
    args: [ 2, 3, 1 ]
    k: 2  n: 3 , i.e. language: 0..k-1 (0..1) and with string len n (3)
    0
    0 0 1
    0 1 1
    1

    As a flat sequence: 0 0 0 1 0 1 1 1 (0 0)
    L.length: 8
    length:  2 ** 3+3-1 =  8 + 2 = 10

    The port code / door lock sequence: digits 0..9 of length 4
    $ julia debruijn.jl 10 4 1
    args: [ 10, 4, 1 ]
    k: 10  n: 4 , i.e. language: 0..k-1 (0..9) and with string len n (4)
    0
    0 0 0 1
    0 0 0 2
    0 0 0 3
    0 0 0 4
    ...
    As a flat sequence: 0 0 0 0 1 0 0 0 2 0 0 0 3 0 0 0 4 0 0 0 5 0 0 0 6 0 0 0 7 0 0 0 8 0 0 0 9 0 0 1 1 0 0 1 2 0
    ...
    8 9 8 7 8 9 9 7 9 7 9 8 8 7 9 8 9 7 9 9 8 7 9 9 9 8 8 8 8 9 8 8 9 9 8 9 8 9 9 9 9 (0 0 0)
    L.Julia: julia0
    length: 10**4+4-1 = 10000 + 3 = 10003

    (See http://www.hakank.org/comb/debruijn_k_10_n_4.html )

  This program was created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#

include("jl_utils.jl")

function pp(str)
    print(join(str,""))
end

#
# debruijn(k=2,n=3,print_seq=1)
#
# k: language (0..k-1)
# n: string length
# print_seq: also print the sequence as a flat list?
#
#
# the door lock combination solution
# is k = 10, n = 4
# Also see: http://www.hakank.org/comb/debruijn_k_10_n_4.html
#
function debruijn(k=2,n=3,print_seq=1)

    println("k:$k n:$n i.e. language: 0..k-1 (0..$(k-1)) and with string len n ($n)")

    L = Int[]
    a = zeros(Int,n+2)

    # Variables to move around (instead of global variables)
    s = Dict(
        :k=>k,
        :n=>n,
        :L=>L,
        :a=>a,
    )

    Gen(1,1,0, s)
    L = s[:L] # get the changed version

    # print as a flat sequence
    if print_seq > 0
        pp("\nAs a flat sequence: ")
        pp(join(L," "))
        # and wrap the first n-1 items
        pp(" (")
        pp(join(L[1:n-1]," "))
        pp(")")
        println()
        println("L.length:",length(L))
    end
    println("length: k^n+n-1 = $(k^n) + $(n-1) = $(k^n+n-1)")

    return L
end

#
# When to print a digit
#
function Print(p,s)
    if s[:n] % p === 0
        for j in 1:p
            t = s[:a][j+1]
            push!(s[:L],t)
            pp(t)
            pp(" ")
        end
        println()
    end
end

function Gen(t, p, ones,s)
    n = s[:n]
    if ones <= n
        if t > n
            Print(p,s)
        else
            a = s[:a]; k = s[:k]
            a[t+1] = a[t-p+1]
            if a[t+1] > 0
                Gen(t+1,p,ones+1,s)
            else
                Gen(t+1,p,ones,s)
            end
            for j = a[t-p+1]+1:k-1
                a[t+1] = j
                Gen(t+1,t,ones+1,s)
            end
            s[:a] = a
        end
    end
end

args = parse.(Int,ARGS)

# For the door lock problem:
#  k = 10, n = 4

# k: language (0..k-1)
k = length(args)>0 ? args[1] : 2 # 10

# n: string length
n = length(args)>1 ? args[2] : 3 # 4

# also print the sequence as a flat list?
print_seq = length(args) > 2 ? args[3] : 1

L = debruijn(k, n, print_seq);

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank


text:
using DashBootstrapComponents

button_group = dbc_buttongroup(
    [dbc_button("Left"), dbc_button("Middle"), dbc_button("Right")]
);

max_stars_repo_name: harisbal/dash-bootstrap-components

max_issues_repo_name: harisbal/dash-bootstrap-components

max_forks_repo_name: harisbal/dash-bootstrap-components


text:
using MyPackage
using Test

@testset "MyPackage.jl" begin
    @test addone(2) == 3
end