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

"""
    AddInstanceFleet()

Adds an instance fleet to a running cluster.  The instance fleet configuration is available only in Amazon EMR versions 4.8.0 and later, excluding 5.0.x.

# Required Parameters
- `ClusterId`: The unique identifier of the cluster.
- `InstanceFleet`: Specifies the configuration of the instance fleet.

"""
add_instance_fleet(ClusterId, InstanceFleet; aws_config::AWSConfig=global_aws_config()) = emr("AddInstanceFleet", Dict{String, Any}("ClusterId"=>ClusterId, "InstanceFleet"=>InstanceFleet); aws_config=aws_config)
add_instance_fleet(ClusterId, InstanceFleet, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("AddInstanceFleet", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId, "InstanceFleet"=>InstanceFleet), args)); aws_config=aws_config)

"""
    AddInstanceGroups()

Adds one or more instance groups to a running cluster.

# Required Parameters
- `InstanceGroups`: Instance groups to add.
- `JobFlowId`: Job flow in which to add the instance groups.

"""
add_instance_groups(InstanceGroups, JobFlowId; aws_config::AWSConfig=global_aws_config()) = emr("AddInstanceGroups", Dict{String, Any}("InstanceGroups"=>InstanceGroups, "JobFlowId"=>JobFlowId); aws_config=aws_config)
add_instance_groups(InstanceGroups, JobFlowId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("AddInstanceGroups", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("InstanceGroups"=>InstanceGroups, "JobFlowId"=>JobFlowId), args)); aws_config=aws_config)

"""
    AddJobFlowSteps()

AddJobFlowSteps adds new steps to a running cluster. A maximum of 256 steps are allowed in each job flow. If your cluster is long-running (such as a Hive data warehouse) or complex, you may require more than 256 steps to process your data. You can bypass the 256-step limitation in various ways, including using SSH to connect to the master node and submitting queries directly to the software running on the master node, such as Hive and Hadoop. For more information on how to do this, see Add More than 256 Steps to a Cluster in the Amazon EMR Management Guide. A step specifies the location of a JAR file stored either on the master node of the cluster or in Amazon S3. Each step is performed by the main function of the main class of the JAR file. The main class can be specified either in the manifest of the JAR or by using the MainFunction parameter of the step. Amazon EMR executes each step in the order listed. For a step to be considered complete, the main function must exit with a zero exit code and all Hadoop jobs started while the step was running must have completed and run successfully. You can only add steps to a cluster that is in one of the following states: STARTING, BOOTSTRAPPING, RUNNING, or WAITING.

# Required Parameters
- `JobFlowId`: A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can also be obtained from ListClusters.
- `Steps`:  A list of StepConfig to be executed by the job flow.

"""
add_job_flow_steps(JobFlowId, Steps; aws_config::AWSConfig=global_aws_config()) = emr("AddJobFlowSteps", Dict{String, Any}("JobFlowId"=>JobFlowId, "Steps"=>Steps); aws_config=aws_config)
add_job_flow_steps(JobFlowId, Steps, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("AddJobFlowSteps", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("JobFlowId"=>JobFlowId, "Steps"=>Steps), args)); aws_config=aws_config)

"""
    AddTags()

Adds tags to an Amazon EMR resource. Tags make it easier to associate clusters in various ways, such as grouping clusters to track your Amazon EMR resource allocation costs. For more information, see Tag Clusters.

# Required Parameters
- `ResourceId`: The Amazon EMR resource identifier to which tags will be added. This value must be a cluster identifier.
- `Tags`: A list of tags to associate with a cluster and propagate to EC2 instances. Tags are user-defined key-value pairs that consist of a required key string with a maximum of 128 characters, and an optional value string with a maximum of 256 characters.

"""
add_tags(ResourceId, Tags; aws_config::AWSConfig=global_aws_config()) = emr("AddTags", Dict{String, Any}("ResourceId"=>ResourceId, "Tags"=>Tags); aws_config=aws_config)
add_tags(ResourceId, Tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("AddTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "Tags"=>Tags), args)); aws_config=aws_config)

"""
    CancelSteps()

Cancels a pending step or steps in a running cluster. Available only in Amazon EMR versions 4.8.0 and later, excluding version 5.0.0. A maximum of 256 steps are allowed in each CancelSteps request. CancelSteps is idempotent but asynchronous; it does not guarantee that a step will be canceled, even if the request is successfully submitted. You can only cancel steps that are in a PENDING state.

# Required Parameters
- `ClusterId`: The ClusterID for the specified steps that will be canceled. Use RunJobFlow and ListClusters to get ClusterIDs.
- `StepIds`: The list of StepIDs to cancel. Use ListSteps to get steps and their states for the specified cluster.

# Optional Parameters
- `StepCancellationOption`: The option to choose to cancel RUNNING steps. By default, the value is SEND_INTERRUPT.
"""
cancel_steps(ClusterId, StepIds; aws_config::AWSConfig=global_aws_config()) = emr("CancelSteps", Dict{String, Any}("ClusterId"=>ClusterId, "StepIds"=>StepIds); aws_config=aws_config)
cancel_steps(ClusterId, StepIds, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("CancelSteps", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId, "StepIds"=>StepIds), args)); aws_config=aws_config)

"""
    CreateSecurityConfiguration()

Creates a security configuration, which is stored in the service and can be specified when a cluster is created.

# Required Parameters
- `Name`: The name of the security configuration.
- `SecurityConfiguration`: The security configuration details in JSON format. For JSON parameters and examples, see Use Security Configurations to Set Up Cluster Security in the Amazon EMR Management Guide.

"""
create_security_configuration(Name, SecurityConfiguration; aws_config::AWSConfig=global_aws_config()) = emr("CreateSecurityConfiguration", Dict{String, Any}("Name"=>Name, "SecurityConfiguration"=>SecurityConfiguration); aws_config=aws_config)
create_security_configuration(Name, SecurityConfiguration, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("CreateSecurityConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name, "SecurityConfiguration"=>SecurityConfiguration), args)); aws_config=aws_config)

"""
    CreateStudio()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Creates a new Amazon EMR Studio.

# Required Parameters
- `AuthMode`: Specifies whether the Studio authenticates users using single sign-on (SSO) or IAM. Amazon EMR Studio currently only supports SSO authentication.
- `EngineSecurityGroupId`: The ID of the Amazon EMR Studio Engine security group. The Engine security group allows inbound network traffic from the Workspace security group, and it must be in the same VPC specified by VpcId.
- `Name`: A descriptive name for the Amazon EMR Studio.
- `ServiceRole`: The IAM role that will be assumed by the Amazon EMR Studio. The service role provides a way for Amazon EMR Studio to interoperate with other AWS services.
- `SubnetIds`: A list of subnet IDs to associate with the Studio. The subnets must belong to the VPC specified by VpcId. Studio users can create a Workspace in any of the specified subnets.
- `UserRole`: The IAM user role that will be assumed by users and groups logged in to a Studio. The permissions attached to this IAM role can be scoped down for each user or group using session policies.
- `VpcId`: The ID of the Amazon Virtual Private Cloud (Amazon VPC) to associate with the Studio.
- `WorkspaceSecurityGroupId`: The ID of the Amazon EMR Studio Workspace security group. The Workspace security group allows outbound network traffic to resources in the Engine security group, and it must be in the same VPC specified by VpcId.

# Optional Parameters
- `DefaultS3Location`: The default Amazon S3 location to back up EMR Studio Workspaces and notebook files. A Studio user can select an alternative Amazon S3 location when creating a Workspace.
- `Description`: A detailed description of the Studio.
- `Tags`: A list of tags to associate with the Studio. Tags are user-defined key-value pairs that consist of a required key string with a maximum of 128 characters, and an optional value string with a maximum of 256 characters.
"""
create_studio(AuthMode, EngineSecurityGroupId, Name, ServiceRole, SubnetIds, UserRole, VpcId, WorkspaceSecurityGroupId; aws_config::AWSConfig=global_aws_config()) = emr("CreateStudio", Dict{String, Any}("AuthMode"=>AuthMode, "EngineSecurityGroupId"=>EngineSecurityGroupId, "Name"=>Name, "ServiceRole"=>ServiceRole, "SubnetIds"=>SubnetIds, "UserRole"=>UserRole, "VpcId"=>VpcId, "WorkspaceSecurityGroupId"=>WorkspaceSecurityGroupId); aws_config=aws_config)
create_studio(AuthMode, EngineSecurityGroupId, Name, ServiceRole, SubnetIds, UserRole, VpcId, WorkspaceSecurityGroupId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("CreateStudio", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AuthMode"=>AuthMode, "EngineSecurityGroupId"=>EngineSecurityGroupId, "Name"=>Name, "ServiceRole"=>ServiceRole, "SubnetIds"=>SubnetIds, "UserRole"=>UserRole, "VpcId"=>VpcId, "WorkspaceSecurityGroupId"=>WorkspaceSecurityGroupId), args)); aws_config=aws_config)

"""
    CreateStudioSessionMapping()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Maps a user or group to the Amazon EMR Studio specified by StudioId, and applies a session policy to refine Studio permissions for that user or group.

# Required Parameters
- `IdentityType`: Specifies whether the identity to map to the Studio is a user or a group.
- `SessionPolicyArn`: The Amazon Resource Name (ARN) for the session policy that will be applied to the user or group. Session policies refine Studio user permissions without the need to use multiple IAM user roles.
- `StudioId`: The ID of the Amazon EMR Studio to which the user or group will be mapped.

# Optional Parameters
- `IdentityId`: The globally unique identifier (GUID) of the user or group from the AWS SSO Identity Store. For more information, see UserId and GroupId in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
- `IdentityName`: The name of the user or group. For more information, see UserName and DisplayName in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
"""
create_studio_session_mapping(IdentityType, SessionPolicyArn, StudioId; aws_config::AWSConfig=global_aws_config()) = emr("CreateStudioSessionMapping", Dict{String, Any}("IdentityType"=>IdentityType, "SessionPolicyArn"=>SessionPolicyArn, "StudioId"=>StudioId); aws_config=aws_config)
create_studio_session_mapping(IdentityType, SessionPolicyArn, StudioId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("CreateStudioSessionMapping", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IdentityType"=>IdentityType, "SessionPolicyArn"=>SessionPolicyArn, "StudioId"=>StudioId), args)); aws_config=aws_config)

"""
    DeleteSecurityConfiguration()

Deletes a security configuration.

# Required Parameters
- `Name`: The name of the security configuration.

"""
delete_security_configuration(Name; aws_config::AWSConfig=global_aws_config()) = emr("DeleteSecurityConfiguration", Dict{String, Any}("Name"=>Name); aws_config=aws_config)
delete_security_configuration(Name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DeleteSecurityConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name), args)); aws_config=aws_config)

"""
    DeleteStudio()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Removes an Amazon EMR Studio from the Studio metadata store.

# Required Parameters
- `StudioId`: The ID of the Amazon EMR Studio.

"""
delete_studio(StudioId; aws_config::AWSConfig=global_aws_config()) = emr("DeleteStudio", Dict{String, Any}("StudioId"=>StudioId); aws_config=aws_config)
delete_studio(StudioId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DeleteStudio", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("StudioId"=>StudioId), args)); aws_config=aws_config)

"""
    DeleteStudioSessionMapping()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Removes a user or group from an Amazon EMR Studio.

# Required Parameters
- `IdentityType`: Specifies whether the identity to delete from the Studio is a user or a group.
- `StudioId`: The ID of the Amazon EMR Studio.

# Optional Parameters
- `IdentityId`: The globally unique identifier (GUID) of the user or group to remove from the Amazon EMR Studio. For more information, see UserId and GroupId in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
- `IdentityName`: The name of the user name or group to remove from the Studio. For more information, see UserName and DisplayName in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
"""
delete_studio_session_mapping(IdentityType, StudioId; aws_config::AWSConfig=global_aws_config()) = emr("DeleteStudioSessionMapping", Dict{String, Any}("IdentityType"=>IdentityType, "StudioId"=>StudioId); aws_config=aws_config)
delete_studio_session_mapping(IdentityType, StudioId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DeleteStudioSessionMapping", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IdentityType"=>IdentityType, "StudioId"=>StudioId), args)); aws_config=aws_config)

"""
    DescribeCluster()

Provides cluster-level details including status, hardware and software configuration, VPC settings, and so on.

# Required Parameters
- `ClusterId`: The identifier of the cluster to describe.

"""
describe_cluster(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("DescribeCluster", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
describe_cluster(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DescribeCluster", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    DescribeJobFlows()

This API is no longer supported and will eventually be removed. We recommend you use ListClusters, DescribeCluster, ListSteps, ListInstanceGroups and ListBootstrapActions instead. DescribeJobFlows returns a list of job flows that match all of the supplied parameters. The parameters can include a list of job flow IDs, job flow states, and restrictions on job flow creation date and time. Regardless of supplied parameters, only job flows created within the last two months are returned. If no parameters are supplied, then job flows matching either of the following criteria are returned:   Job flows created and completed in the last two weeks    Job flows created within the last two months that are in one of the following states: RUNNING, WAITING, SHUTTING_DOWN, STARTING    Amazon EMR can return a maximum of 512 job flow descriptions.

# Optional Parameters
- `CreatedAfter`: Return only job flows created after this date and time.
- `CreatedBefore`: Return only job flows created before this date and time.
- `JobFlowIds`: Return only job flows whose job flow ID is contained in this list.
- `JobFlowStates`: Return only job flows whose state is contained in this list.
"""
describe_job_flows(; aws_config::AWSConfig=global_aws_config()) = emr("DescribeJobFlows"; aws_config=aws_config)
describe_job_flows(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DescribeJobFlows", args; aws_config=aws_config)

"""
    DescribeNotebookExecution()

Provides details of a notebook execution.

# Required Parameters
- `NotebookExecutionId`: The unique identifier of the notebook execution.

"""
describe_notebook_execution(NotebookExecutionId; aws_config::AWSConfig=global_aws_config()) = emr("DescribeNotebookExecution", Dict{String, Any}("NotebookExecutionId"=>NotebookExecutionId); aws_config=aws_config)
describe_notebook_execution(NotebookExecutionId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DescribeNotebookExecution", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("NotebookExecutionId"=>NotebookExecutionId), args)); aws_config=aws_config)

"""
    DescribeSecurityConfiguration()

Provides the details of a security configuration by returning the configuration JSON.

# Required Parameters
- `Name`: The name of the security configuration.

"""
describe_security_configuration(Name; aws_config::AWSConfig=global_aws_config()) = emr("DescribeSecurityConfiguration", Dict{String, Any}("Name"=>Name); aws_config=aws_config)
describe_security_configuration(Name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DescribeSecurityConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name), args)); aws_config=aws_config)

"""
    DescribeStep()

Provides more detail about the cluster step.

# Required Parameters
- `ClusterId`: The identifier of the cluster with steps to describe.
- `StepId`: The identifier of the step to describe.

"""
describe_step(ClusterId, StepId; aws_config::AWSConfig=global_aws_config()) = emr("DescribeStep", Dict{String, Any}("ClusterId"=>ClusterId, "StepId"=>StepId); aws_config=aws_config)
describe_step(ClusterId, StepId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DescribeStep", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId, "StepId"=>StepId), args)); aws_config=aws_config)

"""
    DescribeStudio()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Returns details for the specified Amazon EMR Studio including ID, Name, VPC, Studio access URL, and so on.

# Required Parameters
- `StudioId`: The Amazon EMR Studio ID.

"""
describe_studio(StudioId; aws_config::AWSConfig=global_aws_config()) = emr("DescribeStudio", Dict{String, Any}("StudioId"=>StudioId); aws_config=aws_config)
describe_studio(StudioId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("DescribeStudio", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("StudioId"=>StudioId), args)); aws_config=aws_config)

"""
    GetBlockPublicAccessConfiguration()

Returns the Amazon EMR block public access configuration for your AWS account in the current Region. For more information see Configure Block Public Access for Amazon EMR in the Amazon EMR Management Guide.

"""
get_block_public_access_configuration(; aws_config::AWSConfig=global_aws_config()) = emr("GetBlockPublicAccessConfiguration"; aws_config=aws_config)
get_block_public_access_configuration(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("GetBlockPublicAccessConfiguration", args; aws_config=aws_config)

"""
    GetManagedScalingPolicy()

Fetches the attached managed scaling policy for an Amazon EMR cluster.

# Required Parameters
- `ClusterId`: Specifies the ID of the cluster for which the managed scaling policy will be fetched.

"""
get_managed_scaling_policy(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("GetManagedScalingPolicy", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
get_managed_scaling_policy(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("GetManagedScalingPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    GetStudioSessionMapping()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Fetches mapping details for the specified Amazon EMR Studio and identity (user or group).

# Required Parameters
- `IdentityType`: Specifies whether the identity to fetch is a user or a group.
- `StudioId`: The ID of the Amazon EMR Studio.

# Optional Parameters
- `IdentityId`: The globally unique identifier (GUID) of the user or group. For more information, see UserId and GroupId in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
- `IdentityName`: The name of the user or group to fetch. For more information, see UserName and DisplayName in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
"""
get_studio_session_mapping(IdentityType, StudioId; aws_config::AWSConfig=global_aws_config()) = emr("GetStudioSessionMapping", Dict{String, Any}("IdentityType"=>IdentityType, "StudioId"=>StudioId); aws_config=aws_config)
get_studio_session_mapping(IdentityType, StudioId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("GetStudioSessionMapping", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IdentityType"=>IdentityType, "StudioId"=>StudioId), args)); aws_config=aws_config)

"""
    ListBootstrapActions()

Provides information about the bootstrap actions associated with a cluster.

# Required Parameters
- `ClusterId`: The cluster identifier for the bootstrap actions to list.

# Optional Parameters
- `Marker`: The pagination token that indicates the next set of results to retrieve.
"""
list_bootstrap_actions(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("ListBootstrapActions", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
list_bootstrap_actions(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListBootstrapActions", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    ListClusters()

Provides the status of all clusters visible to this AWS account. Allows you to filter the list of clusters based on certain criteria; for example, filtering by cluster creation date and time or by status. This call returns a maximum of 50 clusters per call, but returns a marker to track the paging of the cluster list across multiple ListClusters calls.

# Optional Parameters
- `ClusterStates`: The cluster state filters to apply when listing clusters.
- `CreatedAfter`: The creation date and time beginning value filter for listing clusters.
- `CreatedBefore`: The creation date and time end value filter for listing clusters.
- `Marker`: The pagination token that indicates the next set of results to retrieve.
"""
list_clusters(; aws_config::AWSConfig=global_aws_config()) = emr("ListClusters"; aws_config=aws_config)
list_clusters(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListClusters", args; aws_config=aws_config)

"""
    ListInstanceFleets()

Lists all available details about the instance fleets in a cluster.  The instance fleet configuration is available only in Amazon EMR versions 4.8.0 and later, excluding 5.0.x versions.

# Required Parameters
- `ClusterId`: The unique identifier of the cluster.

# Optional Parameters
- `Marker`: The pagination token that indicates the next set of results to retrieve.
"""
list_instance_fleets(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("ListInstanceFleets", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
list_instance_fleets(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListInstanceFleets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    ListInstanceGroups()

Provides all available details about the instance groups in a cluster.

# Required Parameters
- `ClusterId`: The identifier of the cluster for which to list the instance groups.

# Optional Parameters
- `Marker`: The pagination token that indicates the next set of results to retrieve.
"""
list_instance_groups(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("ListInstanceGroups", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
list_instance_groups(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListInstanceGroups", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    ListInstances()

Provides information for all active EC2 instances and EC2 instances terminated in the last 30 days, up to a maximum of 2,000. EC2 instances in any of the following states are considered active: AWAITING_FULFILLMENT, PROVISIONING, BOOTSTRAPPING, RUNNING.

# Required Parameters
- `ClusterId`: The identifier of the cluster for which to list the instances.

# Optional Parameters
- `InstanceFleetId`: The unique identifier of the instance fleet.
- `InstanceFleetType`: The node type of the instance fleet. For example MASTER, CORE, or TASK.
- `InstanceGroupId`: The identifier of the instance group for which to list the instances.
- `InstanceGroupTypes`: The type of instance group for which to list the instances.
- `InstanceStates`: A list of instance states that will filter the instances returned with this request.
- `Marker`: The pagination token that indicates the next set of results to retrieve.
"""
list_instances(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("ListInstances", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
list_instances(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListInstances", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    ListNotebookExecutions()

Provides summaries of all notebook executions. You can filter the list based on multiple criteria such as status, time range, and editor id. Returns a maximum of 50 notebook executions and a marker to track the paging of a longer notebook execution list across multiple ListNotebookExecution calls.

# Optional Parameters
- `EditorId`: The unique ID of the editor associated with the notebook execution.
- `From`: The beginning of time range filter for listing notebook executions. The default is the timestamp of 30 days ago.
- `Marker`: The pagination token, returned by a previous ListNotebookExecutions call, that indicates the start of the list for this ListNotebookExecutions call.
- `Status`: The status filter for listing notebook executions.    START_PENDING indicates that the cluster has received the execution request but execution has not begun.    STARTING indicates that the execution is starting on the cluster.    RUNNING indicates that the execution is being processed by the cluster.    FINISHING indicates that execution processing is in the final stages.    FINISHED indicates that the execution has completed without error.    FAILING indicates that the execution is failing and will not finish successfully.    FAILED indicates that the execution failed.    STOP_PENDING indicates that the cluster has received a StopNotebookExecution request and the stop is pending.    STOPPING indicates that the cluster is in the process of stopping the execution as a result of a StopNotebookExecution request.    STOPPED indicates that the execution stopped because of a StopNotebookExecution request.
- `To`: The end of time range filter for listing notebook executions. The default is the current timestamp.
"""
list_notebook_executions(; aws_config::AWSConfig=global_aws_config()) = emr("ListNotebookExecutions"; aws_config=aws_config)
list_notebook_executions(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListNotebookExecutions", args; aws_config=aws_config)

"""
    ListSecurityConfigurations()

Lists all the security configurations visible to this account, providing their creation dates and times, and their names. This call returns a maximum of 50 clusters per call, but returns a marker to track the paging of the cluster list across multiple ListSecurityConfigurations calls.

# Optional Parameters
- `Marker`: The pagination token that indicates the set of results to retrieve.
"""
list_security_configurations(; aws_config::AWSConfig=global_aws_config()) = emr("ListSecurityConfigurations"; aws_config=aws_config)
list_security_configurations(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListSecurityConfigurations", args; aws_config=aws_config)

"""
    ListSteps()

Provides a list of steps for the cluster in reverse order unless you specify stepIds with the request of filter by StepStates. You can specify a maximum of ten stepIDs.

# Required Parameters
- `ClusterId`: The identifier of the cluster for which to list the steps.

# Optional Parameters
- `Marker`: The pagination token that indicates the next set of results to retrieve.
- `StepIds`: The filter to limit the step list based on the identifier of the steps. You can specify a maximum of ten Step IDs. The character constraint applies to the overall length of the array.
- `StepStates`: The filter to limit the step list based on certain states.
"""
list_steps(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("ListSteps", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
list_steps(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListSteps", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    ListStudioSessionMappings()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Returns a list of all user or group session mappings for the EMR Studio specified by StudioId.

# Optional Parameters
- `IdentityType`: Specifies whether to return session mappings for users or groups. If not specified, the results include session mapping details for both users and groups.
- `Marker`: The pagination token that indicates the set of results to retrieve.
- `StudioId`: The ID of the Amazon EMR Studio.
"""
list_studio_session_mappings(; aws_config::AWSConfig=global_aws_config()) = emr("ListStudioSessionMappings"; aws_config=aws_config)
list_studio_session_mappings(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListStudioSessionMappings", args; aws_config=aws_config)

"""
    ListStudios()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Returns a list of all Amazon EMR Studios associated with the AWS account. The list includes details such as ID, Studio Access URL, and creation time for each Studio.

# Optional Parameters
- `Marker`: The pagination token that indicates the set of results to retrieve.
"""
list_studios(; aws_config::AWSConfig=global_aws_config()) = emr("ListStudios"; aws_config=aws_config)
list_studios(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ListStudios", args; aws_config=aws_config)

"""
    ModifyCluster()

Modifies the number of steps that can be executed concurrently for the cluster specified using ClusterID.

# Required Parameters
- `ClusterId`: The unique identifier of the cluster.

# Optional Parameters
- `StepConcurrencyLevel`: The number of steps that can be executed concurrently. You can specify a maximum of 256 steps.
"""
modify_cluster(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("ModifyCluster", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
modify_cluster(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ModifyCluster", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    ModifyInstanceFleet()

Modifies the target On-Demand and target Spot capacities for the instance fleet with the specified InstanceFleetID within the cluster specified using ClusterID. The call either succeeds or fails atomically.  The instance fleet configuration is available only in Amazon EMR versions 4.8.0 and later, excluding 5.0.x versions.

# Required Parameters
- `ClusterId`: The unique identifier of the cluster.
- `InstanceFleet`: The unique identifier of the instance fleet.

"""
modify_instance_fleet(ClusterId, InstanceFleet; aws_config::AWSConfig=global_aws_config()) = emr("ModifyInstanceFleet", Dict{String, Any}("ClusterId"=>ClusterId, "InstanceFleet"=>InstanceFleet); aws_config=aws_config)
modify_instance_fleet(ClusterId, InstanceFleet, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ModifyInstanceFleet", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId, "InstanceFleet"=>InstanceFleet), args)); aws_config=aws_config)

"""
    ModifyInstanceGroups()

ModifyInstanceGroups modifies the number of nodes and configuration settings of an instance group. The input parameters include the new target instance count for the group and the instance group ID. The call will either succeed or fail atomically.

# Optional Parameters
- `ClusterId`: The ID of the cluster to which the instance group belongs.
- `InstanceGroups`: Instance groups to change.
"""
modify_instance_groups(; aws_config::AWSConfig=global_aws_config()) = emr("ModifyInstanceGroups"; aws_config=aws_config)
modify_instance_groups(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("ModifyInstanceGroups", args; aws_config=aws_config)

"""
    PutAutoScalingPolicy()

Creates or updates an automatic scaling policy for a core instance group or task instance group in an Amazon EMR cluster. The automatic scaling policy defines how an instance group dynamically adds and terminates EC2 instances in response to the value of a CloudWatch metric.

# Required Parameters
- `AutoScalingPolicy`: Specifies the definition of the automatic scaling policy.
- `ClusterId`: Specifies the ID of a cluster. The instance group to which the automatic scaling policy is applied is within this cluster.
- `InstanceGroupId`: Specifies the ID of the instance group to which the automatic scaling policy is applied.

"""
put_auto_scaling_policy(AutoScalingPolicy, ClusterId, InstanceGroupId; aws_config::AWSConfig=global_aws_config()) = emr("PutAutoScalingPolicy", Dict{String, Any}("AutoScalingPolicy"=>AutoScalingPolicy, "ClusterId"=>ClusterId, "InstanceGroupId"=>InstanceGroupId); aws_config=aws_config)
put_auto_scaling_policy(AutoScalingPolicy, ClusterId, InstanceGroupId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("PutAutoScalingPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AutoScalingPolicy"=>AutoScalingPolicy, "ClusterId"=>ClusterId, "InstanceGroupId"=>InstanceGroupId), args)); aws_config=aws_config)

"""
    PutBlockPublicAccessConfiguration()

Creates or updates an Amazon EMR block public access configuration for your AWS account in the current Region. For more information see Configure Block Public Access for Amazon EMR in the Amazon EMR Management Guide.

# Required Parameters
- `BlockPublicAccessConfiguration`: A configuration for Amazon EMR block public access. The configuration applies to all clusters created in your account for the current Region. The configuration specifies whether block public access is enabled. If block public access is enabled, security groups associated with the cluster cannot have rules that allow inbound traffic from 0.0.0.0/0 or ::/0 on a port, unless the port is specified as an exception using PermittedPublicSecurityGroupRuleRanges in the BlockPublicAccessConfiguration. By default, Port 22 (SSH) is an exception, and public access is allowed on this port. You can change this by updating BlockPublicSecurityGroupRules to remove the exception.  For accounts that created clusters in a Region before November 25, 2019, block public access is disabled by default in that Region. To use this feature, you must manually enable and configure it. For accounts that did not create an EMR cluster in a Region before this date, block public access is enabled by default in that Region.

"""
put_block_public_access_configuration(BlockPublicAccessConfiguration; aws_config::AWSConfig=global_aws_config()) = emr("PutBlockPublicAccessConfiguration", Dict{String, Any}("BlockPublicAccessConfiguration"=>BlockPublicAccessConfiguration); aws_config=aws_config)
put_block_public_access_configuration(BlockPublicAccessConfiguration, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("PutBlockPublicAccessConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BlockPublicAccessConfiguration"=>BlockPublicAccessConfiguration), args)); aws_config=aws_config)

"""
    PutManagedScalingPolicy()

Creates or updates a managed scaling policy for an Amazon EMR cluster. The managed scaling policy defines the limits for resources, such as EC2 instances that can be added or terminated from a cluster. The policy only applies to the core and task nodes. The master node cannot be scaled after initial configuration.

# Required Parameters
- `ClusterId`: Specifies the ID of an EMR cluster where the managed scaling policy is attached.
- `ManagedScalingPolicy`: Specifies the constraints for the managed scaling policy.

"""
put_managed_scaling_policy(ClusterId, ManagedScalingPolicy; aws_config::AWSConfig=global_aws_config()) = emr("PutManagedScalingPolicy", Dict{String, Any}("ClusterId"=>ClusterId, "ManagedScalingPolicy"=>ManagedScalingPolicy); aws_config=aws_config)
put_managed_scaling_policy(ClusterId, ManagedScalingPolicy, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("PutManagedScalingPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId, "ManagedScalingPolicy"=>ManagedScalingPolicy), args)); aws_config=aws_config)

"""
    RemoveAutoScalingPolicy()

Removes an automatic scaling policy from a specified instance group within an EMR cluster.

# Required Parameters
- `ClusterId`: Specifies the ID of a cluster. The instance group to which the automatic scaling policy is applied is within this cluster.
- `InstanceGroupId`: Specifies the ID of the instance group to which the scaling policy is applied.

"""
remove_auto_scaling_policy(ClusterId, InstanceGroupId; aws_config::AWSConfig=global_aws_config()) = emr("RemoveAutoScalingPolicy", Dict{String, Any}("ClusterId"=>ClusterId, "InstanceGroupId"=>InstanceGroupId); aws_config=aws_config)
remove_auto_scaling_policy(ClusterId, InstanceGroupId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("RemoveAutoScalingPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId, "InstanceGroupId"=>InstanceGroupId), args)); aws_config=aws_config)

"""
    RemoveManagedScalingPolicy()

 Removes a managed scaling policy from a specified EMR cluster.

# Required Parameters
- `ClusterId`:  Specifies the ID of the cluster from which the managed scaling policy will be removed.

"""
remove_managed_scaling_policy(ClusterId; aws_config::AWSConfig=global_aws_config()) = emr("RemoveManagedScalingPolicy", Dict{String, Any}("ClusterId"=>ClusterId); aws_config=aws_config)
remove_managed_scaling_policy(ClusterId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("RemoveManagedScalingPolicy", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ClusterId"=>ClusterId), args)); aws_config=aws_config)

"""
    RemoveTags()

Removes tags from an Amazon EMR resource. Tags make it easier to associate clusters in various ways, such as grouping clusters to track your Amazon EMR resource allocation costs. For more information, see Tag Clusters.  The following example removes the stack tag with value Prod from a cluster:

# Required Parameters
- `ResourceId`: The Amazon EMR resource identifier from which tags will be removed. This value must be a cluster identifier.
- `TagKeys`: A list of tag keys to remove from a resource.

"""
remove_tags(ResourceId, TagKeys; aws_config::AWSConfig=global_aws_config()) = emr("RemoveTags", Dict{String, Any}("ResourceId"=>ResourceId, "TagKeys"=>TagKeys); aws_config=aws_config)
remove_tags(ResourceId, TagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("RemoveTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "TagKeys"=>TagKeys), args)); aws_config=aws_config)

"""
    RunJobFlow()

RunJobFlow creates and starts running a new cluster (job flow). The cluster runs the steps specified. After the steps complete, the cluster stops and the HDFS partition is lost. To prevent loss of data, configure the last step of the job flow to store results in Amazon S3. If the JobFlowInstancesConfig KeepJobFlowAliveWhenNoSteps parameter is set to TRUE, the cluster transitions to the WAITING state rather than shutting down after the steps have completed.  For additional protection, you can set the JobFlowInstancesConfig TerminationProtected parameter to TRUE to lock the cluster and prevent it from being terminated by API call, user intervention, or in the event of a job flow error. A maximum of 256 steps are allowed in each job flow. If your cluster is long-running (such as a Hive data warehouse) or complex, you may require more than 256 steps to process your data. You can bypass the 256-step limitation in various ways, including using the SSH shell to connect to the master node and submitting queries directly to the software running on the master node, such as Hive and Hadoop. For more information on how to do this, see Add More than 256 Steps to a Cluster in the Amazon EMR Management Guide. For long running clusters, we recommend that you periodically store your results.  The instance fleets configuration is available only in Amazon EMR versions 4.8.0 and later, excluding 5.0.x versions. The RunJobFlow request can contain InstanceFleets parameters or InstanceGroups parameters, but not both.

# Required Parameters
- `Instances`: A specification of the number and type of Amazon EC2 instances.
- `Name`: The name of the job flow.

# Optional Parameters
- `AdditionalInfo`: A JSON string for selecting additional features.
- `AmiVersion`: Applies only to Amazon EMR AMI versions 3.x and 2.x. For Amazon EMR releases 4.0 and later, ReleaseLabel is used. To specify a custom AMI, use CustomAmiID.
- `Applications`: Applies to Amazon EMR releases 4.0 and later. A case-insensitive list of applications for Amazon EMR to install and configure when launching the cluster. For a list of applications available for each Amazon EMR release version, see the Amazon EMR Release Guide.
- `AutoScalingRole`: An IAM role for automatic scaling policies. The default role is EMR_AutoScaling_DefaultRole. The IAM role provides permissions that the automatic scaling feature requires to launch and terminate EC2 instances in an instance group.
- `BootstrapActions`: A list of bootstrap actions to run before Hadoop starts on the cluster nodes.
- `Configurations`: For Amazon EMR releases 4.0 and later. The list of configurations supplied for the EMR cluster you are creating.
- `CustomAmiId`: Available only in Amazon EMR version 5.7.0 and later. The ID of a custom Amazon EBS-backed Linux AMI. If specified, Amazon EMR uses this AMI when it launches cluster EC2 instances. For more information about custom AMIs in Amazon EMR, see Using a Custom AMI in the Amazon EMR Management Guide. If omitted, the cluster uses the base Linux AMI for the ReleaseLabel specified. For Amazon EMR versions 2.x and 3.x, use AmiVersion instead. For information about creating a custom AMI, see Creating an Amazon EBS-Backed Linux AMI in the Amazon Elastic Compute Cloud User Guide for Linux Instances. For information about finding an AMI ID, see Finding a Linux AMI.
- `EbsRootVolumeSize`: The size, in GiB, of the Amazon EBS root device volume of the Linux AMI that is used for each EC2 instance. Available in Amazon EMR version 4.x and later.
- `JobFlowRole`: Also called instance profile and EC2 role. An IAM role for an EMR cluster. The EC2 instances of the cluster assume this role. The default role is EMR_EC2_DefaultRole. In order to use the default role, you must have already created it using the CLI or console.
- `KerberosAttributes`: Attributes for Kerberos configuration when Kerberos authentication is enabled using a security configuration. For more information see Use Kerberos Authentication in the Amazon EMR Management Guide.
- `LogEncryptionKmsKeyId`: The AWS KMS customer master key (CMK) used for encrypting log files. If a value is not provided, the logs remain encrypted by AES-256. This attribute is only available with Amazon EMR version 5.30.0 and later, excluding Amazon EMR 6.0.0.
- `LogUri`: The location in Amazon S3 to write the log files of the job flow. If a value is not provided, logs are not created.
- `ManagedScalingPolicy`:  The specified managed scaling policy for an Amazon EMR cluster.
- `NewSupportedProducts`:  For Amazon EMR releases 3.x and 2.x. For Amazon EMR releases 4.x and later, use Applications.  A list of strings that indicates third-party software to use with the job flow that accepts a user argument list. EMR accepts and forwards the argument list to the corresponding installation script as bootstrap action arguments. For more information, see \"Launch a Job Flow on the MapR Distribution for Hadoop\" in the Amazon EMR Developer Guide. Supported values are:   \"mapr-m3\" - launch the cluster using MapR M3 Edition.   \"mapr-m5\" - launch the cluster using MapR M5 Edition.   \"mapr\" with the user arguments specifying \"--edition,m3\" or \"--edition,m5\" - launch the job flow using MapR M3 or M5 Edition respectively.   \"mapr-m7\" - launch the cluster using MapR M7 Edition.   \"hunk\" - launch the cluster with the Hunk Big Data Analtics Platform.   \"hue\"- launch the cluster with Hue installed.   \"spark\" - launch the cluster with Apache Spark installed.   \"ganglia\" - launch the cluster with the Ganglia Monitoring System installed.
- `PlacementGroupConfigs`: The specified placement group configuration for an Amazon EMR cluster.
- `ReleaseLabel`: The Amazon EMR release label, which determines the version of open-source application packages installed on the cluster. Release labels are in the form emr-x.x.x, where x.x.x is an Amazon EMR release version such as emr-5.14.0. For more information about Amazon EMR release versions and included application versions and features, see https://docs.aws.amazon.com/emr/latest/ReleaseGuide/. The release label applies only to Amazon EMR releases version 4.0 and later. Earlier versions use AmiVersion.
- `RepoUpgradeOnBoot`: Applies only when CustomAmiID is used. Specifies which updates from the Amazon Linux AMI package repositories to apply automatically when the instance boots using the AMI. If omitted, the default is SECURITY, which indicates that only security updates are applied. If NONE is specified, no updates are applied, and all updates must be applied manually.
- `ScaleDownBehavior`: Specifies the way that individual Amazon EC2 instances terminate when an automatic scale-in activity occurs or an instance group is resized. TERMINATE_AT_INSTANCE_HOUR indicates that Amazon EMR terminates nodes at the instance-hour boundary, regardless of when the request to terminate the instance was submitted. This option is only available with Amazon EMR 5.1.0 and later and is the default for clusters created using that version. TERMINATE_AT_TASK_COMPLETION indicates that Amazon EMR adds nodes to a deny list and drains tasks from nodes before terminating the Amazon EC2 instances, regardless of the instance-hour boundary. With either behavior, Amazon EMR removes the least active nodes first and blocks instance termination if it could lead to HDFS corruption. TERMINATE_AT_TASK_COMPLETION available only in Amazon EMR version 4.1.0 and later, and is the default for versions of Amazon EMR earlier than 5.1.0.
- `SecurityConfiguration`: The name of a security configuration to apply to the cluster.
- `ServiceRole`: The IAM role that will be assumed by the Amazon EMR service to access AWS resources on your behalf.
- `StepConcurrencyLevel`: Specifies the number of steps that can be executed concurrently. The default value is 1. The maximum value is 256.
- `Steps`: A list of steps to run.
- `SupportedProducts`:  For Amazon EMR releases 3.x and 2.x. For Amazon EMR releases 4.x and later, use Applications.  A list of strings that indicates third-party software to use. For more information, see the Amazon EMR Developer Guide. Currently supported values are:   \"mapr-m3\" - launch the job flow using MapR M3 Edition.   \"mapr-m5\" - launch the job flow using MapR M5 Edition.
- `Tags`: A list of tags to associate with a cluster and propagate to Amazon EC2 instances.
- `VisibleToAllUsers`: A value of true indicates that all IAM users in the AWS account can perform cluster actions if they have the proper IAM policy permissions. This is the default. A value of false indicates that only the IAM user who created the cluster can perform actions.
"""
run_job_flow(Instances, Name; aws_config::AWSConfig=global_aws_config()) = emr("RunJobFlow", Dict{String, Any}("Instances"=>Instances, "Name"=>Name); aws_config=aws_config)
run_job_flow(Instances, Name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("RunJobFlow", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Instances"=>Instances, "Name"=>Name), args)); aws_config=aws_config)

"""
    SetTerminationProtection()

SetTerminationProtection locks a cluster (job flow) so the EC2 instances in the cluster cannot be terminated by user intervention, an API call, or in the event of a job-flow error. The cluster still terminates upon successful completion of the job flow. Calling SetTerminationProtection on a cluster is similar to calling the Amazon EC2 DisableAPITermination API on all EC2 instances in a cluster.  SetTerminationProtection is used to prevent accidental termination of a cluster and to ensure that in the event of an error, the instances persist so that you can recover any data stored in their ephemeral instance storage.  To terminate a cluster that has been locked by setting SetTerminationProtection to true, you must first unlock the job flow by a subsequent call to SetTerminationProtection in which you set the value to false.   For more information, seeManaging Cluster Termination in the Amazon EMR Management Guide.

# Required Parameters
- `JobFlowIds`:  A list of strings that uniquely identify the clusters to protect. This identifier is returned by RunJobFlow and can also be obtained from DescribeJobFlows .
- `TerminationProtected`: A Boolean that indicates whether to protect the cluster and prevent the Amazon EC2 instances in the cluster from shutting down due to API calls, user intervention, or job-flow error.

"""
set_termination_protection(JobFlowIds, TerminationProtected; aws_config::AWSConfig=global_aws_config()) = emr("SetTerminationProtection", Dict{String, Any}("JobFlowIds"=>JobFlowIds, "TerminationProtected"=>TerminationProtected); aws_config=aws_config)
set_termination_protection(JobFlowIds, TerminationProtected, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("SetTerminationProtection", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("JobFlowIds"=>JobFlowIds, "TerminationProtected"=>TerminationProtected), args)); aws_config=aws_config)

"""
    SetVisibleToAllUsers()

Sets the ClusterVisibleToAllUsers value, which determines whether the cluster is visible to all IAM users of the AWS account associated with the cluster. Only the IAM user who created the cluster or the AWS account root user can call this action. The default value, true, indicates that all IAM users in the AWS account can perform cluster actions if they have the proper IAM policy permissions. If set to false, only the IAM user that created the cluster can perform actions. This action works on running clusters. You can override the default true setting when you create a cluster by using the VisibleToAllUsers parameter with RunJobFlow.

# Required Parameters
- `JobFlowIds`: The unique identifier of the job flow (cluster).
- `VisibleToAllUsers`: A value of true indicates that all IAM users in the AWS account can perform cluster actions if they have the proper IAM policy permissions. This is the default. A value of false indicates that only the IAM user who created the cluster can perform actions.

"""
set_visible_to_all_users(JobFlowIds, VisibleToAllUsers; aws_config::AWSConfig=global_aws_config()) = emr("SetVisibleToAllUsers", Dict{String, Any}("JobFlowIds"=>JobFlowIds, "VisibleToAllUsers"=>VisibleToAllUsers); aws_config=aws_config)
set_visible_to_all_users(JobFlowIds, VisibleToAllUsers, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("SetVisibleToAllUsers", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("JobFlowIds"=>JobFlowIds, "VisibleToAllUsers"=>VisibleToAllUsers), args)); aws_config=aws_config)

"""
    StartNotebookExecution()

Starts a notebook execution.

# Required Parameters
- `EditorId`: The unique identifier of the EMR Notebook to use for notebook execution.
- `ExecutionEngine`: Specifies the execution engine (cluster) that runs the notebook execution.
- `RelativePath`: The path and file name of the notebook file for this execution, relative to the path specified for the EMR Notebook. For example, if you specify a path of s3://MyBucket/MyNotebooks when you create an EMR Notebook for a notebook with an ID of e-ABCDEFGHIJK1234567890ABCD (the EditorID of this request), and you specify a RelativePath of my_notebook_executions/notebook_execution.ipynb, the location of the file for the notebook execution is s3://MyBucket/MyNotebooks/e-ABCDEFGHIJK1234567890ABCD/my_notebook_executions/notebook_execution.ipynb.
- `ServiceRole`: The name or ARN of the IAM role that is used as the service role for Amazon EMR (the EMR role) for the notebook execution.

# Optional Parameters
- `NotebookExecutionName`: An optional name for the notebook execution.
- `NotebookInstanceSecurityGroupId`: The unique identifier of the Amazon EC2 security group to associate with the EMR Notebook for this notebook execution.
- `NotebookParams`: Input parameters in JSON format passed to the EMR Notebook at runtime for execution.
- `Tags`: A list of tags associated with a notebook execution. Tags are user-defined key-value pairs that consist of a required key string with a maximum of 128 characters and an optional value string with a maximum of 256 characters.
"""
start_notebook_execution(EditorId, ExecutionEngine, RelativePath, ServiceRole; aws_config::AWSConfig=global_aws_config()) = emr("StartNotebookExecution", Dict{String, Any}("EditorId"=>EditorId, "ExecutionEngine"=>ExecutionEngine, "RelativePath"=>RelativePath, "ServiceRole"=>ServiceRole); aws_config=aws_config)
start_notebook_execution(EditorId, ExecutionEngine, RelativePath, ServiceRole, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("StartNotebookExecution", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EditorId"=>EditorId, "ExecutionEngine"=>ExecutionEngine, "RelativePath"=>RelativePath, "ServiceRole"=>ServiceRole), args)); aws_config=aws_config)

"""
    StopNotebookExecution()

Stops a notebook execution.

# Required Parameters
- `NotebookExecutionId`: The unique identifier of the notebook execution.

"""
stop_notebook_execution(NotebookExecutionId; aws_config::AWSConfig=global_aws_config()) = emr("StopNotebookExecution", Dict{String, Any}("NotebookExecutionId"=>NotebookExecutionId); aws_config=aws_config)
stop_notebook_execution(NotebookExecutionId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("StopNotebookExecution", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("NotebookExecutionId"=>NotebookExecutionId), args)); aws_config=aws_config)

"""
    TerminateJobFlows()

TerminateJobFlows shuts a list of clusters (job flows) down. When a job flow is shut down, any step not yet completed is canceled and the EC2 instances on which the cluster is running are stopped. Any log files not already saved are uploaded to Amazon S3 if a LogUri was specified when the cluster was created. The maximum number of clusters allowed is 10. The call to TerminateJobFlows is asynchronous. Depending on the configuration of the cluster, it may take up to 1-5 minutes for the cluster to completely terminate and release allocated resources, such as Amazon EC2 instances.

# Required Parameters
- `JobFlowIds`: A list of job flows to be shut down.

"""
terminate_job_flows(JobFlowIds; aws_config::AWSConfig=global_aws_config()) = emr("TerminateJobFlows", Dict{String, Any}("JobFlowIds"=>JobFlowIds); aws_config=aws_config)
terminate_job_flows(JobFlowIds, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("TerminateJobFlows", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("JobFlowIds"=>JobFlowIds), args)); aws_config=aws_config)

"""
    UpdateStudioSessionMapping()

 The Amazon EMR Studio APIs are in preview release for Amazon EMR and are subject to change.  Updates the session policy attached to the user or group for the specified Amazon EMR Studio.

# Required Parameters
- `IdentityType`: Specifies whether the identity to update is a user or a group.
- `SessionPolicyArn`: The Amazon Resource Name (ARN) of the session policy to associate with the specified user or group.
- `StudioId`: The ID of the EMR Studio.

# Optional Parameters
- `IdentityId`: The globally unique identifier (GUID) of the user or group. For more information, see UserId and GroupId in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
- `IdentityName`: The name of the user or group to update. For more information, see UserName and DisplayName in the AWS SSO Identity Store API Reference. Either IdentityName or IdentityId must be specified.
"""
update_studio_session_mapping(IdentityType, SessionPolicyArn, StudioId; aws_config::AWSConfig=global_aws_config()) = emr("UpdateStudioSessionMapping", Dict{String, Any}("IdentityType"=>IdentityType, "SessionPolicyArn"=>SessionPolicyArn, "StudioId"=>StudioId); aws_config=aws_config)
update_studio_session_mapping(IdentityType, SessionPolicyArn, StudioId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = emr("UpdateStudioSessionMapping", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IdentityType"=>IdentityType, "SessionPolicyArn"=>SessionPolicyArn, "StudioId"=>StudioId), args)); aws_config=aws_config)


text:
using BinDeps

@BinDeps.setup

libjamsd = library_dependency("libjamsd", aliases=["jamsd"])

# Download binaries from hosted location
bin_prefix = "https://nullptr.fr/lib"

# TODO with latest Julia
if VERSION < v"0.7"
    iswin   = is_windows()
    islinux = is_linux()
    isapple = is_apple()
else
    iswin   = Sys.iswindows()
    islinux = Sys.islinux()
    isapple = Sys.isapple()
end

# TODO remove all is(win|linux|apple) and just have a switch on sys.ARCH?

if iswin
    if Sys.ARCH == :x86_64
        provides(Binaries, URI("$bin_prefix-win64/libjamsd.tar.xz"), libjamsd, os = :Windows)
    elseif Sys.ARCH == :i686
        provides(Binaries, URI("$bin_prefix-win32/libjamsd.tar.xz"), libjamsd, os = :Windows)
    end
end

if islinux
    if Sys.ARCH == :x86_64
        provides(Binaries, URI("$bin_prefix-x86_64-linux-gnu/libjamsd.tar.xz"), libjamsd, os = :Linux)
    end
end

if isapple
    if Sys.ARCH == :x86_64
        provides(Binaries, URI("$bin_prefix-macosx/libjamsd.tar.xz"), libjamsd, os = :Darwin)
    end
end

@BinDeps.install Dict(:libjamsd => :libjamsd)

ext: jl


text:
using OscillatoryIntegralsODE
using Documenter

DocMeta.setdocmeta!(OscillatoryIntegralsODE, :DocTestSetup, :(using OscillatoryIntegralsODE); recursive=true)

makedocs(;
    modules=[OscillatoryIntegralsODE],
    authors="Zack Li",
    repo="https://github.com/xzackli/OscillatoryIntegralsODE.jl/blob/{commit}{path}#{line}",
    sitename="OscillatoryIntegralsODE.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://xzackli.github.io/OscillatoryIntegralsODE.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
        "Background" => "background.md",
        "Usage" => "usage.md",
        "API" => "api_index.md"
    ],
)

deploydocs(;
    repo="github.com/xzackli/OscillatoryIntegralsODE.jl",
    devbranch = "main"
)

max_stars_repo_name: xzackli/OscillatoryIntegralsODE

max_issues_repo_name: xzackli/OscillatoryIntegralsODE

max_forks_repo_name: xzackli/OscillatoryIntegralsODE


text:
using BinaryBuilder

# Collection of sources required to build LibHealpix
sources = [
    "https://downloads.sourceforge.net/project/healpix/Healpix_3.31/Healpix_3.31_2016Aug26.tar.gz" =>
    "ddf437442b6d5ae7d75c9afaafc4ec43921f903c976e25db3c5ed5185a181542",

]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir
cd Healpix_3.31/src/C/autotools
autoreconf --install
./configure --prefix=$prefix --host=$target
make -j
make install
cd $WORKSPACE/srcdir
cd Healpix_3.31/src/cxx/autotools
autoreconf --install
./configure --prefix=$prefix --host=$target
make -j
make install

"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [
    BinaryProvider.Linux(:i686, :glibc, :blank_abi),
    BinaryProvider.Linux(:aarch64, :glibc, :blank_abi),
    BinaryProvider.Linux(:powerpc64le, :glibc, :blank_abi),
    BinaryProvider.Linux(:armv7l, :glibc, :eabihf),
    BinaryProvider.MacOS(:x86_64, :blank_libc, :blank_abi),
    BinaryProvider.Linux(:x86_64, :glibc, :blank_abi)
]

# The products that we will ensure are always built
products(prefix) = [
    LibraryProduct(prefix, "libhealpix_cxx", :libhealpix_cxx),
    LibraryProduct(prefix, "libchealpix", :libchealpix)
]

# Dependencies that must be installed before this package can be built
dependencies = [
    "https://github.com/JuliaAstro/CFITSIOBuilder/releases/download/v3.440-1/build.jl"
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, "LibHealpix", sources, script, platforms, products, dependencies)

max_stars_repo_name: mweastwood/LibHealpixBuilder

max_issues_repo_name: mweastwood/LibHealpixBuilder

max_forks_repo_name: mweastwood/LibHealpixBuilder


text:
udc_inclusions_library = Set(("CIRCLE", "CAPSULE", "RECTANGLE", "ELLIPSE",))
prc_inclusions_library = Set(("SPHERE", "SPHERO_CYLINDER", "BOX", "ELLIPSOID", "SPHEROID", "OBLATE_SPHEROID", "PROLATE_SPHEROID"))

@with_kw struct BBox2D <: FieldVector{4,Float64}
    xlb::Float64 = -1.0
    ylb::Float64 = -1.0
    xub::Float64 = 1.0
    yub::Float64 = 1.0
    @assert xub >= xlb "While creating 2D bounding box:
     x_max(=$xub) < x_min(=$xlb) is found, please ensure x_max > x_min."
    @assert yub >= ylb "While creating 2D bounding box:
     y_max < y_min is found, please ensure y_max > y_min."
end

@with_kw struct BBox3D <: FieldVector{6,Float64}
    xlb::Float64 = -1.0
    ylb::Float64 = -1.0
    zlb::Float64 = -1.0
    xub::Float64 = 1.0
    yub::Float64 = 1.0
    zub::Float64 = 1.0
    @assert xub >= xlb "While creating 3D bounding box:
     x_max < x_min is found, please ensure x_max > x_min."
    @assert yub >= ylb "While creating 3D bounding box:
     y_max < y_min is found, please ensure y_max > y_min."
    @assert zub >= zlb "While creating 3D bounding box:
     z_max < z_min is found, please ensure z_max > z_min."
end

buffer_bbox(bb::BBox2D, buffer::Float64) = bb .+ (buffer .* (-1.0, -1.0, 1.0, 1.0))
buffer_bbox(bb::BBox3D, buffer::Float64) = bb .+ (buffer .* (-1.0, -1.0, -1.0, 1.0, 1.0, 1.0))

side_lengths(bbx::BBox2D) = (bbx.xub - bbx.xlb, bbx.yub - bbx.ylb)
side_lengths(bbx::BBox3D) = (bbx.xub - bbx.xlb, bbx.yub - bbx.ylb, bbx.zub - bbx.zlb)

abstract type AbstractUnitCell end

@with_kw struct UDC2D <: AbstractUnitCell
    bbox::BBox2D
    inclusions::Dict{String, Matrix{Float64}}
    @assert issubset(uppercase.(keys(inclusions)), udc_inclusions_library)
end

@with_kw struct UDC3D <: AbstractUnitCell
    bbox::BBox3D
    inclusions::Dict{String, Matrix{Float64}}
    @assert issubset(uppercase.(keys(inclusions)), udc_inclusions_library)
end

@with_kw struct PRC <: AbstractUnitCell
    bbox::BBox3D
    inclusions::Dict{String, Matrix{Float64}}
    @assert issubset(uppercase.(keys(inclusions)), prc_inclusions_library)
end

const UDC = Union{UDC2D, UDC3D}
const UnitCell3D = Union{UDC3D, PRC}

side_lengths(uc::AbstractUnitCell) = side_lengths(uc.bbox)

dimension(uc::AbstractUnitCell) = begin
    if isa(uc, UDC2D)
        return 2
    elseif isa(uc, UnitCell3D)
        return 3
    end
end

function buffer_bbox(
    uc::UnitCell3D,
    identifier::Symbol=:ALL,
    ϵ::Float64=1e-06,
)
    ucbb = uc.bbox
    aϵ = abs(ϵ)
    if identifier == :ALL
        return uc.bbox .+ [-ϵ, -ϵ, -ϵ, ϵ, ϵ, ϵ]
    elseif identifier == :XLB
        return BBox3D(ucbb.xlb-aϵ, ucbb.ylb-ϵ, ucbb.zlb-ϵ, ucbb.xlb+aϵ, ucbb.yub+ϵ, ucbb.zub+ϵ)
    elseif identifier == :YLB
        return BBox3D(ucbb.xlb-ϵ, ucbb.ylb-aϵ, ucbb.zlb-ϵ, ucbb.xub+ϵ, ucbb.ylb+aϵ, ucbb.zub+ϵ)
    elseif identifier == :ZLB
        return BBox3D(ucbb.xlb-ϵ, ucbb.ylb-ϵ, ucbb.zlb-aϵ, ucbb.xub+ϵ, ucbb.yub+ϵ, ucbb.zlb+aϵ)
    elseif identifier == :XUB
        return BBox3D(ucbb.xub-aϵ, ucbb.ylb-ϵ, ucbb.zlb-ϵ, ucbb.xub+aϵ, ucbb.yub+ϵ, ucbb.zub+ϵ)
    elseif identifier == :YUB
        return BBox3D(ucbb.xlb-ϵ, ucbb.yub-aϵ, ucbb.zlb-ϵ, ucbb.xub+ϵ, ucbb.yub+aϵ, ucbb.zub+ϵ)
    elseif identifier == :ZUB
        return BBox3D(ucbb.xlb-ϵ, ucbb.ylb-ϵ, ucbb.zub-aϵ, ucbb.xub+ϵ, ucbb.yub+ϵ, ucbb.zub+aϵ)
    # IDEA if required, write bboxes for edges too...!
    end
end


text:
"""
Assumes input file is uniref90 (genefamilies)
"""
function humann2_regroup(df::DataFrame, kind::String="ec")
    in_path = tempname()
    out_path = tempname()
    CSV.write(in_path, df)
    run(```
        humann2_regroup_table -i $in_path -g uniref90_$kind -o $out_path
        ```)

    new_df = CSV.File(out_path) |> DataFrame
    return new_df[1]
end

function humann2_rename(df::DataFrame, kind::String="ec")
    in_path = tempname()
    out_path = tempname()
    CSV.write(in_path, df[[1]], delim='\t')
    run(```
        humann2_rename_table -i $in_path -n $kind -o $out_path
        ```)
    new_df = CSV.File(out_path, delim='\t') |> DataFrame
    return new_df[1]
end

function humann2_barplots(df::DataFrame, metadata::AbstractArray{<:AbstractString,1}, outpath::String)
    length(metadata) == size(df, 2) - 1 || @error "Must have metadata for each column"
    nostrat = df[map(x-> !occursin(r"\|", x), df[1]), 1]
    for p in nostrat
        pwy = match(r"^[\w.]+", p).match
        @debug pwy
        filt = [occursin(Regex("^$pwy\\b"), x) for x in df[1]]
        current = df[filt, :]
        @debug "Size of $p dataframe" size(current)
        if size(current, 1) < 3
            @info "Only 1 classified species for $p, skipping"
            continue
        end
        @info "plotting $p"

        BiobakeryUtils.humann2_barplot(current, metadata, outpath)
    end
end

function humann2_barplot(df::AbstractDataFrame, metadata::AbstractArray{<:AbstractString,1}, outpath::AbstractString)
    sum(x-> !occursin(r"\|", x), df[1]) == 1 || @error "Multipl unstratified rows in dataframe"
    matches = map(x-> match(r"^([^:|]+):?([^|]+)?", x),  df[1])
    all(x-> !isa(x, Nothing), matches) || @error "something is wrong!"
    @debug "Getting unique"
    ecs = unique([String(x.captures[1]) for x in matches])
    length(ecs) == 1 || @error "Multiple ecs found in df"
    ec = ecs[1]

    metadf = DataFrame(metadata=["metadatum"])
    metadf = hcat(metadf, DataFrame([names(df[2:end])[i]=>metadata[i] for i in eachindex(metadata)]...))
    @debug "opening file"
    fl_path = tempname()
    outfl = open(fl_path, "w")
    CSV.write(outfl, metadf, delim='\t')
    CSV.write(outfl, df, append=true, delim='\t')
    close(outfl)
    @debug "file closed"

    out = joinpath(outpath, "$ec.png")
    @debug "humann2_barplot --i $fl_path -o $out --focal-feature $ec --focal-metadatum metadatum --last-metadatum metadatum --sort sum metadata"
    run(```
        humann2_barplot --i $fl_path -o "$out" --focal-feature "$ec" --focal-metadatum metadatum --last-metadatum metadatum --sort sum metadata
        ```)

end


text:
using RosDataProcess
using PyPlot

ts = range(-10pi, stop=10pi, length=500)

a = TimeSeries(sin, ts)
b = select_times(x -> -2pi <= x <= 2pi, a)

plot(a)
figure()
plot(b)

max_stars_repo_name: mcorah/RosDataProcess

max_issues_repo_name: mcorah/RosDataProcess

max_forks_repo_name: mcorah/RosDataProcess


text:
# SPDX-License-Identifier: MIT

"""
    AbstractGamma{D} <: Distribution

Abstract type for Gamma distribution implementations.
"""
abstract type AbstractGamma{D} <: Distribution end

function DefaultGammaParameter(α, β)
    DefaultParameter(vcat(-β, α))
end

"""
    mutable struct Gamma{D} <: AbstractGamma
        param::P where P <: AbstractParameter
    end

Set of `D` independent Gamma distributions.

# Constructors

    Gamma(α, β)

where `α` and `β` are the shape and rate parameters of the
distribution.

# Examples
```jldoctest
julia> Gamma([1.0, 1.0], [2.0, 2.0])
Gamma{2}:
  α = [1.0, 1.0]
  β = [2.0, 2.0]
```
"""
mutable struct Gamma{D} <: AbstractGamma{D}
    param::P where P <: AbstractParameter
end

function Gamma(α::AbstractVector{T}, β::AbstractVector{T}) where T
    D = length(α)
    param = DefaultGammaParameter(α, β)
    Gamma{D}(param)
end

#######################################################################
# Distribution interface

basemeasure(::AbstractGamma, x) = -sum(log, x)

function lognorm(g::AbstractGamma{D}, η = naturalform(g.param)) where D
    η₁, η₂ = η[1:D], η[D+1:end]
    sum(loggamma_dot(η₂) - η₂ .* log.(-η₁))
end

function gradlognorm(g::AbstractGamma)
    α, β = stdparam(g, naturalform(g.param))
    vcat(α ./ β, digamma.(α) .- log.(β))
end

function sample(g::AbstractGamma{D}, size) where D
    retval = similar(g.α, D, size)
    α, β = Array(g.α), Array(g.β)
    for i in 1:length(α)
        g_ = Dists.Gamma(α[i], 1/β[i])
        retval[i, :] = Dists.rand(g_, size)
    end
    retval
end

splitgrad(g::AbstractGamma{D}, μ) where D = μ[1:D], μ[D+1:end]

stats(::Gamma, x) = vcat(x, log.(x))

function stdparam(g::AbstractGamma{D},
                  η::AbstractVector{T} = naturalform(g.param)) where {T,D}
    α = η[D+1:end]
    β = -η[1:D]
    (α = α, β = β)
end

max_stars_repo_name: lucasondel/ExpFamilyDistributions-jl

max_issues_repo_name: BUTSpeechFIT/ExpFamilyDistributions

max_forks_repo_name: lucasondel/ExpFamilyDistributions


text:
#############################################################################
#Copyright (c) 2016 Charles Le Losq
#
#The MIT License (MIT)
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the #Software without restriction, including without limitation the rights to use, copy, #modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, #and to permit persons to whom the Software is furnished to do so, subject to the #following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, #INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
#############################################################################

VERSION >= v"0.4.0" && __precompile__()

module Spectra

using StatsBase
using PyPlot
using LsqFit
using PyCall
using Dierckx
using Ipopt
using JuMP

# For PyCall modules
const preprocessing = PyNULL()
const grid_search = PyNULL()
const cross_validation = PyNULL()
const decomposition = PyNULL()
const kernel_ridge = PyNULL()
const svm = PyNULL()
const gaussian_process = PyNULL()
const linear_model = PyNULL()

# some initial setup for calling the GCVSPL.f library
unixpath = "../deps/src/gcvspline/libgcvspl"
winpath = "../deps/bin$WORD_SIZE/libgcvspl" # let it there as an example but I did not tried yet any build on Windows... TODO
const gcvspl = joinpath(dirname(@__FILE__), @unix? unixpath : winpath)

function __init__()
    # Ensure library is available.
    if (Libdl.dlopen_e(gcvspl) == C_NULL)
        error("GCVSPL not properly installed. Run Pkg.build(\"Spectra\"). Windows auto-build is not setup, you might want to build the library manually.")
    end

	copy!(preprocessing, pyimport_conda("sklearn.preprocessing", "scikit-learn"))
	copy!(grid_search, pyimport_conda("sklearn.grid_search", "scikit-learn"))
	copy!(cross_validation, pyimport_conda("sklearn.cross_validation", "scikit-learn"))
	copy!(decomposition, pyimport_conda("sklearn.decomposition", "scikit-learn"))
	copy!(kernel_ridge, pyimport_conda("sklearn.kernel_ridge", "scikit-learn"))
	copy!(svm, pyimport_conda("sklearn.svm","scikit-learn"))
	copy!(gaussian_process, pyimport_conda("sklearn.gaussian_process", "scikit-learn"))
	copy!(linear_model, pyimport_conda("sklearn.linear_model", "scikit-learn"))

end

include("diffusion.jl")
include("integrale.jl")
include("functions.jl")
include("baseline.jl")
include("bootstrap.jl")
include("tlcorrection.jl")
include("rameau.jl")
include("deprecated.jl")
include("ml_regressor.jl")
include("ctxremoval.jl")

#From integrale.jl
export trapz, gaussianarea

#From diffusion.jl
export peak_diffusion, model, IRdataprep

#From functions.jl
export poly, polyfit, gaussiennes, lorentziennes, pseudovoigts, pearson7, normal_dist, xshift_inversion, xshift_direct,xshift_correction

#From baseline.jl
export baseline

#From gcvspl.jl
export gcvspl, splderivative

#From bootstrap
export bootsample, bootperf

#From tlcorrection
export tlcorrection

#From rameau
export rameau

#From ml_regressor
export mlregressor

#From ctxremoval
export ctxremoval

end # module


text:
using DifferentialEquations, Plots, Printf

abstract type Model end
abstract type AbstractReactionNetwork end

struct Options
    saveat
    abstol::Float64
    reltol::Float64
end

Options(;saveat=[],abstol=1e-6,reltol=1e-3) = Options(saveat,abstol,reltol)

struct ReactionMatrix{P} <: AbstractReactionNetwork
    sto_mat::Matrix{Int}        # How does population change?
    compute_rates::Function     # output should be same length as sto_mat
    rate_params::P              # To be fed into compute_rates function
end

struct ReactionNetwork{P} <: AbstractReactionNetwork
    sto_mat::Vector{Vector{Int}}    # How does population change?
    compute_rates::Function         # output should be same length as sto_mat
    rate_params::P                  # To be fed into compute_rates function
end

struct StochasticModel{T<:Number,R<:AbstractReactionNetwork}
    current_time::T
    current_population::Vector{T}
    rn::R
end

struct DeterministicModel{P,T,U<:Number} <: Model
    ODEmodel::Function              # Deterministic version of the Model
    initial_population::Vector{T}
    params::P                       # Parameters to be fed to the ODEmodel
    stochastic_threshold::Number    # When to switch to/from the StochasticModel
    progression_threshold::Number   # A factor that determines progression
    time_domain::Tuple{U,U}         # Max length of simulation. (typically (0, tf) where tf is final time)
    options::Options
end

DeterministicModel(ode,init_pop,pars,sto_thres,prog_thres,time_domain) = begin
    DeterministicModel( ode,
                        init_pop,
                        pars,
                        sto_thres,
                        prog_thres,
                        time_domain,
                        Options()
                        )
end

mutable struct Solution{T<:Number,U}
    time_array::Vector{T}
    population_array::U
    patient_outcome::String
    in_stochastic_region::Bool      # Modification to ODE if in this region
    stochastic_compartment::Vector{Int}
end

Solution(time::Number,pop) = Solution([time],[pop],"Unknown",false,Vector{Int}())
Solution(time::Vector{<:Number},pop,is_stochastic::Bool) = Solution(time,pop,"Unknown",is_stochastic,[3])
Solution(ode,is_stochastic::Bool) = Solution(ode.t,ode.u,"Unknown",is_stochastic,[3])

function update_solution!(sol::Solution,ode)

    push!(sol.time_array,ode.t[2:end]...)
    push!(sol.population_array,ode.u[2:end]...)

end

"""
    plot(sol;stride,linecolor,label)

# Arguments
- `sol::Solution`:  The structure returned by simulate.
- `stride::Int`:    The number of steps to skip when plotting.
- `linecolor`:      Specifies the color of each population (e.g. [:red :blue]).
- `label`:          Specifies the name of each population (e.g. ["red" "blue"]).

"""
function Plots.plot(sol::Solution;stride::Int=1,linecolor=:black,label=nothing,
    yaxis=:normal,legend=:bottomleft,small_value::Float64=1e-3)

    t = sol.time_array[1:stride:end]
    u = hcat(sol.population_array[1:stride:end]...)'
    u[u.==0] .= small_value

    plot(
        t,
        u,
        linecolor=linecolor,
        label=label,
        legend=legend,
        yaxis=yaxis
        )

end

"find_event(rates) computes a tuple of the population rates for simulate."
function find_event(rates)

    # Get total to compute time to next event
    rate_total = sum(rates)

    # Compute tau (time till next event)
    τ = -log(rand())/rate_total

    # Normalize rates to determine which event occurs
    cum_rate = cumsum(rates./rate_total)

    # Roll the dice
    roll = rand()

    # find out which individual process occurred
    which_event = findfirst(x-> x >= roll,cum_rate)

    return τ, which_event

end

function simulate_single_event(sm::StochasticModel)

    rates = sm.rn.compute_rates(sm.current_time,sm.current_population,sm.rn.rate_params)

    if sum(rates) == 0.0
        @warn "zero propagation!"
        return Inf,nothing
    end

    τ, which_event = find_event(rates)

    return τ, which_event

end

### FIXME ###
function round!(s::Solution)
    s.population_array[end][s.stochastic_compartment] = round.(s.population_array[end][s.stochastic_compartment])
end

function printsol(s::Solution)

    println("t = $(s.time_array[end]), B = $(s.population_array[end][3])")

end

function deterministic_step(dm::Model,sol::Solution)

    saveat_callback = (length(dm.options.saveat)==0) ? false : true

    # Check to see if the tumor has entered the stochastic regime
    enter_stochastic_region(u,t,integrator) = dm.stochastic_threshold-u[3]
    affect!(integrator) = begin
        sol.in_stochastic_region = true
        sol.stochastic_compartment = [3]
        terminate!(integrator)
    end
    cb1 = ContinuousCallback(enter_stochastic_region,affect!,nothing,save_positions=(false,saveat_callback))

    # Check to see when the tumor exceeds some c*original size. We define
    # this as progression and assume the third compartment is the tumor compartment...
    # Potentially we can use a component array instead so we don't need to track the compartment
    progression(u,t,integrator) = dm.progression_threshold - u[3]
    affect2!(integrator) = begin
        sol.patient_outcome = "progression"
        terminate!(integrator)
    end

    cb2 = ContinuousCallback(progression,affect2!,save_positions=(false,saveat_callback))

    cb3 = nothing
    progress_check = false
	if progress_check
		print_time(integrator) = @printf("t = %.2f, B = %.2f\n",integrator.t,integrator.u[3])
		cb3 = PeriodicCallback(print_time, 1.0,save_positions=(false,false))
	end

    # Group the callbacks and solve the ODE
    cbset = CallbackSet(cb1,cb2,cb3)

    prob = ODEProblem(dm.ODEmodel,dm.initial_population,dm.time_domain,dm.params)

    odesol = solve(prob,Tsit5(),callback=cbset,abstol=dm.options.abstol,reltol=dm.options.reltol,
    saveat=dm.options.saveat)

    return odesol

end

function simulate(dm::Model,rn::ReactionNetwork)

    sol = Solution(dm.time_domain[1],dm.initial_population)

    # FIXME: We initially assume that the system is deterministic
    odesol = deterministic_step(dm,sol)

    # Update the solution struct
    update_solution!(sol,odesol)

    if sol.in_stochastic_region
        round!(sol)
    end

    current_time = sol.time_array[end]
    current_pop = sol.population_array[end]

    while current_time < dm.time_domain[end] && sol.patient_outcome != "progression"

        # printsol(sol)

        if sol.in_stochastic_region
            # Build the stochastic model
            sm = StochasticModel(current_time,current_pop,rn)

            # Get time to simulate forward and what occurs
            τ, which_event = simulate_single_event(sm)

            newparams = (in_stochastic_region = sol.in_stochastic_region, modelparams = dm.params.modelparams)

            # Simulate forward the deterministic components to the new time τ
            dm_2 = DeterministicModel(dm.ODEmodel,
                                        current_pop,
                                        newparams,
                                        dm.stochastic_threshold,
                                        dm.progression_threshold,
                                        (current_time,current_time+τ),
                                        dm.options)

            odesol = deterministic_step(dm_2,sol)

            # solution with stochastic component and update time array
            # Update the solution struct
            update_solution!(sol,odesol)
            sol.population_array[end] += rn.sto_mat[which_event]
            current_pop = sol.population_array[end]
            current_time += τ

        else

            newparams = (in_stochastic_region = sol.in_stochastic_region, modelparams = dm.params.modelparams)

            # Simulate forward the deterministic components to the new time τ
            dm_2 = DeterministicModel(dm.ODEmodel,
                                        current_pop,
                                        newparams,
                                        dm.stochastic_threshold,
                                        dm.progression_threshold,
                                        (current_time,dm.time_domain[end]),
                                        dm.options)

            odesol = deterministic_step(dm_2,sol)

            # solution with stochastic component and update time array
            # Update the solution struct
            update_solution!(sol,odesol)

            if sol.in_stochastic_region
                round!(sol)
            end

            current_pop = sol.population_array[end]
            current_time = sol.time_array[end]

        end

        if current_pop[3] > dm.stochastic_threshold
            sol.in_stochastic_region = false
        end

        if floor(current_pop[3]) == 0.0
            sol.patient_outcome = "cure"
            break
        end

    end

    return sol

end

max_stars_repo_name: gregorykimmel/HybridModel

max_issues_repo_name: gregorykimmel/HybridModel

max_forks_repo_name: gregorykimmel/HybridModel


text:
#= -------------------------------------------------------------------------
# @file pose_plots.jl
#
# @date 10/06/16 22:10:53
# @author Martin Noblia
# @email martin.noblia@openmailbox.org
#
# @brief
# A small example generate a n number of Pose2D and plot it
# @detail
#
  Licence:
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License

---------------------------------------------------------------------------=#
using Robotics
# generate 50 random Pose2D in [-3,3]
v = generate_random_pose(50, -3:3)
# plot all Pose2D in one figure
plot_frame(v)

max_stars_repo_name: elsuizo/Robot

max_issues_repo_name: elsuizo/Robot

max_forks_repo_name: elsuizo/Robot


text:
### MCJob

abstract type MCJob end

abstract type GibbsJob <: MCJob end

# Set defaults for possibly unspecified output options

function augment_variable_outopts!(outopts::Dict)
  destination = get!(outopts, :destination, :nstate)

  if destination != :none
    if !haskey(outopts, :monitor)
      outopts[:monitor] = [:value]
    end

    if destination == :iostream
      if !haskey(outopts, :filepath)
        outopts[:filepath] = ""
      end

      if !haskey(outopts, :filesuffix)
        outopts[:filesuffix] = "csv"
      end

      if !haskey(outopts, :flush)
        outopts[:flush] = false
      end
    end
  end
end

augment_variable_outopts!(outopts::Vector{Dict{K, V}}) where {K, V} = map(augment_variable_outopts!, outopts)

function augment_parameter_outopts!(outopts::Dict)
  augment_variable_outopts!(outopts)

  if outopts[:destination] != :none
    if !haskey(outopts, :diagnostics)
      outopts[:diagnostics] = Symbol[]
    end
  end
end

augment_parameter_outopts!(outopts::Vector{Dict{K, V}}) where {K, V} = map(augment_parameter_outopts!, outopts)

# initialize_output() needs to be defined for custom variable state or NState input arguments
# Thus multiple dispatch allows to extend the code base to accommodate new variable states or NStates

function initialize_output(state::BasicUnvVariableState, n::Integer, outopts::Dict)
  local output::Union{VariableNState, VariableIOStream, Void}

  if outopts[:destination] == :nstate
    output = BasicUnvVariableNState(n, eltype(state))
  elseif outopts[:destination] == :iostream
    output = BasicVariableIOStream(
      (),
      n,
      filepath=outopts[:filepath],
      filesuffix=outopts[:filesuffix],
      mode="w"
    )
  elseif outopts[:destination] == :none
    output = nothing
  else
    error(":destination must be set to :nstate or :iostream or :none, got $(outopts[:destination])")
  end

  output
end

function initialize_output(state::BasicMuvVariableState, n::Integer, outopts::Dict)
  local output::Union{VariableNState, VariableIOStream, Void}

  if outopts[:destination] == :nstate
    output = BasicMuvVariableNState(state.size, n, eltype(state))
  elseif outopts[:destination] == :iostream
    output = BasicVariableIOStream(
      (state.size,),
      n,
      filepath=outopts[:filepath],
      filesuffix=outopts[:filesuffix],
      mode="w"
    )
  elseif outopts[:destination] == :none
    output = nothing
  else
    error(":destination must be set to :nstate or :iostream or :none, got $(outopts[:destination])")
  end

  output
end

function initialize_output(state::BasicMavVariableState, n::Integer, outopts::Dict)
  local output::Union{VariableNState, VariableIOStream, Void}

  if outopts[:destination] == :nstate
    output = BasicMavVariableNState(state.size, n, eltype(state))
  elseif outopts[:destination] == :iostream
    output = BasicVariableIOStream(
      state.size,
      n,
      filepath=outopts[:filepath],
      filesuffix=outopts[:filesuffix],
      mode="w"
    )
  elseif outopts[:destination] == :none
    output = nothing
  else
    error(":destination must be set to :nstate or :iostream or :none, got $(outopts[:destination])")
  end

  output
end

function initialize_output(state::BasicDiscUnvParameterState, n::Integer, outopts::Dict)
  local output::Union{VariableNState, VariableIOStream, Void}

  if outopts[:destination] == :nstate
    output = BasicDiscUnvParameterNState(n, outopts[:monitor], outopts[:diagnostics], eltype(state)...)
  elseif outopts[:destination] == :iostream
    output = BasicDiscParamIOStream(
      (),
      n,
      outopts[:monitor],
      filepath=outopts[:filepath],
      filesuffix=outopts[:filesuffix],
      diagnostickeys=outopts[:diagnostics],
      mode="w"
    )
  elseif outopts[:destination] == :none
    output = nothing
  else
    error(":destination must be set to :nstate or :iostream or :none, got $(outopts[:destination])")
  end

  output
end

function initialize_output(state::BasicDiscMuvParameterState, n::Integer, outopts::Dict)
  local output::Union{VariableNState, VariableIOStream, Void}

  if outopts[:destination] == :nstate
    output = BasicDiscMuvParameterNState(state.size, n, outopts[:monitor], outopts[:diagnostics], eltype(state)...)
  elseif outopts[:destination] == :iostream
    output = BasicDiscParamIOStream(
      (state.size,),
      n,
      outopts[:monitor],
      filepath=outopts[:filepath],
      filesuffix=outopts[:filesuffix],
      diagnostickeys=outopts[:diagnostics],
      mode="w"
    )
  elseif outopts[:destination] == :none
    output = nothing
  else
    error(":destination must be set to :nstate or :iostream or :none, got $(outopts[:destination])")
  end

  output
end

function initialize_output(state::BasicContUnvParameterState, n::Integer, outopts::Dict)
  local output::Union{VariableNState, VariableIOStream, Void}

  if outopts[:destination] == :nstate
    output = BasicContUnvParameterNState(n, outopts[:monitor], outopts[:diagnostics], eltype(state))
  elseif outopts[:destination] == :iostream
    output = BasicContParamIOStream(
      (),
      n,
      outopts[:monitor],
      filepath=outopts[:filepath],
      filesuffix=outopts[:filesuffix],
      diagnostickeys=outopts[:diagnostics],
      mode="w"
    )
  elseif outopts[:destination] == :none
    output = nothing
  else
    error(":destination must be set to :nstate or :iostream or :none, got $(outopts[:destination])")
  end

  output
end

function initialize_output(state::BasicContMuvParameterState, n::Integer, outopts::Dict)
  local output::Union{VariableNState, VariableIOStream, Void}

  if outopts[:destination] == :nstate
    output = BasicContMuvParameterNState(state.size, n, outopts[:monitor], outopts[:diagnostics], eltype(state))
  elseif outopts[:destination] == :iostream
    output = BasicContParamIOStream(
      (state.size,),
      n,
      outopts[:monitor],
      filepath=outopts[:filepath],
      filesuffix=outopts[:filesuffix],
      diagnostickeys=outopts[:diagnostics],
      mode="w"
    )
  elseif outopts[:destination] == :none
    output = nothing
  else
    error(":destination must be set to :nstate or :iostream or :none, got $(outopts[:destination])")
  end

  output
end

run(job::Vector{J}) where {J<:MCJob} = map(run, job)


text:
const ArrayLike = Union{AbstractArray, Tuple}
const StringLike = Union{AbstractString, Symbol}

function cycle(v::AbstractVector, i::Int)
    ax = axes(v, 1)
    return v[first(ax) + mod(i - first(ax), length(ax))]
end

"""
    iscontinuous(v::AbstractArray)

Determine whether `v` should be treated as a continuous or categorical vector.
"""
iscontinuous(::AbstractArray) = false
iscontinuous(::AbstractArray{<:Number}) = true
iscontinuous(::AbstractArray{<:Union{Date, DateTime}}) = true

isaxis2d(::Axis) = true
isaxis2d(::Any) = false
isaxis2d(ae::AxisEntries) = isaxis2d(Axis(ae))

for sym in [:hidexdecorations!, :hideydecorations!, :hidedecorations!]
    @eval function $sym(ae::AxisEntries; kwargs...)
        axis = Axis(ae)
        isaxis2d(axis) && $sym(axis; kwargs...)
    end
end

for sym in [:linkxaxes!, :linkyaxes!, :linkaxes!]
    @eval function $sym(ae::AxisEntries, aes::AxisEntries...)
        axs = filter(isaxis2d, map(Axis, (ae, aes...)))
        isempty(axs) || $sym(axs...)
    end
end

function hideinnerdecorations!(aes::Matrix{AxisEntries})
    options = (label=true, ticks=true, minorticks=true, grid=false, minorgrid=false)
    foreach(ae -> hidexdecorations!(ae; options...), aes[1:end-1, :])
    foreach(ae -> hideydecorations!(ae; options...), aes[:, 2:end])
end

function deleteemptyaxes!(aes::Matrix{AxisEntries})
    for ae in aes
        if isempty(ae.entries)
            delete!(Axis(ae))
        end
    end
end

extend_extrema((l1, u1), (l2, u2)) = min(l1, l2), max(u1, u2)

push_different!(v, val) = !isempty(v) && isequal(last(v), val) || push!(v, val)

function mergesorted(v1, v2)
    issorted(v1) && issorted(v2) || throw(ArgumentError("arguments must be sorted"))
    T = promote_type(eltype(v1), eltype(v2))
    v = sizehint!(T[], length(v1) + length(v2))
    i1, i2 = 1, 1
    while i2 ≤ length(v2)
        while i1 ≤ length(v1) && isless(v1[i1], v2[i2])
            push_different!(v, v1[i1])
            i1 += 1
        end
        push_different!(v, v2[i2])
        i2 += 1
    end
    while i1 ≤ length(v1)
        push_different!(v, v1[i1])
        i1 += 1
    end
    return v
end

function assert_equal(a, b)
    @assert a == b
    return a
end

function unnest(arr::AbstractArray{<:AbstractArray})
    inner_size = mapreduce(size, assert_equal, arr)
    outer_size = size(arr)
    flattened = reduce(vcat, map(vec, vec(arr)))
    return reshape(flattened, inner_size..., outer_size...)
end

unnest(arr::NTuple{<:Any, <:AbstractArray}) = unnest(collect(arr))

adjust_index(rg1, rg2, idx::Integer) = idx in rg2 ? idx : only(rg2)
adjust_index(rg1, rg2, idxs::AbstractArray) = map(idx -> adjust_index(rg1, rg2, idx), idxs)
adjust_index(rg1, rg2, ::Colon) = rg1 == rg2 ? Colon() : fill(only(rg2), length(rg1))

maybewrap(x::ArrayLike) = x
maybewrap(x) = fill(x)

unwrap(x) = x
unwrap(x::AbstractArray{<:Any, 0}) = x[]

function resizetocontent!(fig::Figure)
    figsize = size(fig.scene)
    sz = map((Col(), Row()), figsize) do dir, currentsize
        inferredsize = determinedirsize(fig.layout, dir)
        return ceil(Int, something(inferredsize, currentsize))
    end
    sz == figsize || resize!(fig.scene, sz)
    return fig
end

function resizetocontent!(fg::FigureGrid)
    resizetocontent!(fg.figure)
    return fg
end


text:
immutable UpperBound98 <: Cut{2}; groups; end
export UpperBound98

function getcut(prob::Problem, vars::Variables, ::UpperBound98, i, j)
	ubˣ, ubʸ = prob.wub, prob.hub
	Lˣ, Lʸ = prob.W, prob.H

	(cˣ,cʸ,ℓˣ,ℓʸ,_,_,_,zˣ,zʸ) = unpack(vars)

	@LinearConstraints(begin
		cˣ[i] + ubˣ[j]*(1-zˣ[j,i]) ≥ 0.5ℓˣ[i] + ℓˣ[j]
		cˣ[i] + ubˣ[j]*(1-zˣ[j,i]) ≥ 0.5ℓˣ[i] + ℓˣ[j]
		cˣ[j] + ubˣ[i]*(1-zˣ[i,j]) ≥ 0.5ℓˣ[j] + ℓˣ[i]
		cˣ[j] + ubˣ[i]*(1-zˣ[i,j]) ≥ 0.5ℓˣ[j] + ℓˣ[i]
		cʸ[i] + ubʸ[j]*(1-zʸ[j,i]) ≥ 0.5ℓʸ[i] + ℓʸ[j]
		cʸ[i] + ubʸ[j]*(1-zʸ[j,i]) ≥ 0.5ℓʸ[i] + ℓʸ[j]
		cʸ[j] + ubʸ[i]*(1-zʸ[i,j]) ≥ 0.5ℓʸ[j] + ℓʸ[i]
		cʸ[j] + ubʸ[i]*(1-zʸ[i,j]) ≥ 0.5ℓʸ[j] + ℓʸ[i]
	end)
end

immutable UpperBound108 <: Cut{2}; groups; end
export UpperBound108

function getcut{U<:Union{Unary,Partition4Bit}}(prob::Problem, vars::Variables{U}, ::UpperBound108, i, j)
	ubˣ, ubʸ = prob.wub, prob.hub
	Lˣ, Lʸ = prob.W, prob.H

	(_,_,ℓˣ,ℓʸ,_,_,_,zˣ,zʸ) = unpack(vars)

	cuts = LinearConstraint[]
	if ubˣ[i] + ubˣ[j] > Lˣ
		push!(cuts, @LinearConstraint(zʸ[i,j] + zʸ[j,i] ≥ (ℓˣ[i]+ℓˣ[j]-Lˣ) / (ubˣ[i]+ubˣ[j]-Lˣ)))
	end
	if ubʸ[i] + ubʸ[j] > Lʸ
		push!(cuts, @LinearConstraint(zˣ[i,j] + zˣ[j,i] ≥ (ℓʸ[i]+ℓʸ[j]-Lʸ) / (ubʸ[i]+ubʸ[j]-Lʸ)))
	end
	return cuts
end


text:
# ---
# title: Supervised Simplified FuzzyARTMAP (SFAM) Example
# id: sfam_iris
# cover: ../assets/artmap.png
# date: 2021-11-30
# author: "[Sasha Petrenko](https://github.com/AP6YC)"
# julia: 1.6
# description: This demo shows how to use a Simplified FuzzyARTMAP (SFAM) module to conduct supervised learning on the Iris dataset.
# ---

# SFAM is a supervised algorithm by definition, so we use it to map a set of features to a set of supervisory labels.
# We will do so by training and testing on the ubiquitous Iris dataset and seeing how well the SFAM module generalizes the data.

# We begin with importing AdaptiveResonance for the ART modules and MLDatasets for some data utilities.
using AdaptiveResonance # ART
using MLDatasets        # Iris dataset
using MLDataUtils       # Shuffling and splitting
using Printf            # Formatted number printing

# We will download the Iris dataset for its small size and benchmark use for clustering algorithms.
Iris.download(i_accept_the_terms_of_use=true)
features, labels = Iris.features(), Iris.labels()

# Because the MLDatasets package gives us Iris labels as strings, we will use the `MLDataUtils.convertlabel` method with the `MLLabelUtils.LabelEnc.Indices` type to get a list of integers representing each class:
labels = convertlabel(LabelEnc.Indices{Int}, labels)
unique(labels)

# Next, we will create a train/test split with the `MLDataUtils.stratifiedobs` utility:
(X_train, y_train), (X_test, y_test) = stratifiedobs((features, labels))

# Now, we can create our SFAM module.
# We'll do so with the default contstructor, though the module itself has many options that can be altered during instantiation.

## Create the SFAM module
art = SFAM()

## Change the match tracking parameter after instantiation
art.opts.epsilon = 1e-2

# We can train the model in batch mode upon the data and supervisory labels.
# We do so by directly passing the integer vector of labels to the training method.
# Just as in other modules, we can extract the SFAM's prescribed labels from the training method, which should match up to the training labels as we will see later.

## Train in supervised mode by directly passing the labels.
y_hat_train = train!(art, X_train, y_train)
println("Training labels: ",  size(y_hat_train), " ", typeof(y_hat_train))

# We can classify the testing data to see how we generalize.
# At the same time, we can see the effect of getting the best-matching unit in the case of complete mismatch (see the docs on [Mismatch vs. BMU](@ref mismatch-bmu))

## Classify both ways
y_hat = AdaptiveResonance.classify(art, X_test)
y_hat_bmu = AdaptiveResonance.classify(art, X_test, get_bmu=true)

## Check the shape and type of the output labels
println("Testing labels: ",  size(y_hat), " ", typeof(y_hat))
println("Testing labels with bmu: ",  size(y_hat_bmu), " ", typeof(y_hat_bmu))

# Finally, we can calculate the performances (number correct over total) of the model upon all three regimes:
# 1. Training data
# 2. Testing data
# 2. Testing data with `get_bmu=true`

## Calculate performance on training data, testing data, and with get_bmu
perf_train = performance(y_hat_train, y_train)
perf_test = performance(y_hat, y_test)
perf_test_bmu = performance(y_hat_bmu, y_test)

## Format each performance number for comparison
@printf "Training performance: %.4f\n" perf_train
@printf "Testing performance: %.4f\n" perf_test
@printf "Best-matching unit testing performance: %.4f\n" perf_test_bmu