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

using AWS.Compat
using AWS.UUIDs
"""
    AddTags()

Adds one or more tags to an object, up to a limit of 10. Each tag consists of a key and an optional value. If you add a tag using a key that is already associated with the ML object, AddTags updates the tag's value.

# Required Parameters
- `ResourceId`: The ID of the ML object to tag. For example, exampleModelId.
- `ResourceType`: The type of the ML object to tag.
- `Tags`: The key-value pairs to use to create tags. If you specify a key without specifying a value, Amazon ML creates a tag with the specified key and a value of null.

"""

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

"""
    CreateBatchPrediction()

Generates predictions for a group of observations. The observations to process exist in one or more data files referenced by a DataSource. This operation creates a new BatchPrediction, and uses an MLModel and the data files referenced by the DataSource as information sources.  CreateBatchPrediction is an asynchronous operation. In response to CreateBatchPrediction, Amazon Machine Learning (Amazon ML) immediately returns and sets the BatchPrediction status to PENDING. After the BatchPrediction completes, Amazon ML sets the status to COMPLETED.  You can poll for status updates by using the GetBatchPrediction operation and checking the Status parameter of the result. After the COMPLETED status appears, the results are available in the location specified by the OutputUri parameter.

# Required Parameters
- `BatchPredictionDataSourceId`: The ID of the DataSource that points to the group of observations to predict.
- `BatchPredictionId`: A user-supplied ID that uniquely identifies the BatchPrediction.
- `MLModelId`: The ID of the MLModel that will generate predictions for the group of observations.
- `OutputUri`: The location of an Amazon Simple Storage Service (Amazon S3) bucket or directory to store the batch prediction results. The following substrings are not allowed in the s3 key portion of the outputURI field: ':', '//', '/./', '/../'. Amazon ML needs permissions to store and retrieve the logs on your behalf. For information about how to set permissions, see the Amazon Machine Learning Developer Guide.

# Optional Parameters
- `BatchPredictionName`: A user-supplied name or description of the BatchPrediction. BatchPredictionName can only use the UTF-8 character set.
"""

create_batch_prediction(BatchPredictionDataSourceId, BatchPredictionId, MLModelId, OutputUri; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateBatchPrediction", Dict{String, Any}("BatchPredictionDataSourceId"=>BatchPredictionDataSourceId, "BatchPredictionId"=>BatchPredictionId, "MLModelId"=>MLModelId, "OutputUri"=>OutputUri); aws_config=aws_config)
create_batch_prediction(BatchPredictionDataSourceId, BatchPredictionId, MLModelId, OutputUri, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateBatchPrediction", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BatchPredictionDataSourceId"=>BatchPredictionDataSourceId, "BatchPredictionId"=>BatchPredictionId, "MLModelId"=>MLModelId, "OutputUri"=>OutputUri), args)); aws_config=aws_config)

"""
    CreateDataSourceFromRDS()

Creates a DataSource object from an  Amazon Relational Database Service (Amazon RDS). A DataSource references data that can be used to perform CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations. CreateDataSourceFromRDS is an asynchronous operation. In response to CreateDataSourceFromRDS, Amazon Machine Learning (Amazon ML) immediately returns and sets the DataSource status to PENDING. After the DataSource is created and ready for use, Amazon ML sets the Status parameter to COMPLETED. DataSource in the COMPLETED or PENDING state can be used only to perform >CreateMLModel>, CreateEvaluation, or CreateBatchPrediction operations.   If Amazon ML cannot accept the input source, it sets the Status parameter to FAILED and includes an error message in the Message attribute of the GetDataSource operation response.

# Required Parameters
- `DataSourceId`: A user-supplied ID that uniquely identifies the DataSource. Typically, an Amazon Resource Number (ARN) becomes the ID for a DataSource.
- `RDSData`: The data specification of an Amazon RDS DataSource:  DatabaseInformation -   DatabaseName - The name of the Amazon RDS database.  InstanceIdentifier  - A unique identifier for the Amazon RDS database instance.   DatabaseCredentials - AWS Identity and Access Management (IAM) credentials that are used to connect to the Amazon RDS database. ResourceRole - A role (DataPipelineDefaultResourceRole) assumed by an EC2 instance to carry out the copy task from Amazon RDS to Amazon Simple Storage Service (Amazon S3). For more information, see Role templates for data pipelines. ServiceRole - A role (DataPipelineDefaultRole) assumed by the AWS Data Pipeline service to monitor the progress of the copy task from Amazon RDS to Amazon S3. For more information, see Role templates for data pipelines. SecurityInfo - The security information to use to access an RDS DB instance. You need to set up appropriate ingress rules for the security entity IDs provided to allow access to the Amazon RDS instance. Specify a [SubnetId, SecurityGroupIds] pair for a VPC-based RDS DB instance. SelectSqlQuery - A query that is used to retrieve the observation data for the Datasource. S3StagingLocation - The Amazon S3 location for staging Amazon RDS data. The data retrieved from Amazon RDS using SelectSqlQuery is stored in this location. DataSchemaUri - The Amazon S3 location of the DataSchema. DataSchema - A JSON string representing the schema. This is not required if DataSchemaUri is specified.   DataRearrangement - A JSON string that represents the splitting and rearrangement requirements for the Datasource.    Sample -  \"{\"splitting\":{\"percentBegin\":10,\"percentEnd\":60}}\"
- `RoleARN`: The role that Amazon ML assumes on behalf of the user to create and activate a data pipeline in the user's account and copy data using the SelectSqlQuery query from Amazon RDS to Amazon S3.

# Optional Parameters
- `ComputeStatistics`: The compute statistics for a DataSource. The statistics are generated from the observation data referenced by a DataSource. Amazon ML uses the statistics internally during MLModel training. This parameter must be set to true if the DataSource needs to be used for MLModel training.
- `DataSourceName`: A user-supplied name or description of the DataSource.
"""

create_data_source_from_rds(DataSourceId, RDSData, RoleARN; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateDataSourceFromRDS", Dict{String, Any}("DataSourceId"=>DataSourceId, "RDSData"=>RDSData, "RoleARN"=>RoleARN); aws_config=aws_config)
create_data_source_from_rds(DataSourceId, RDSData, RoleARN, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateDataSourceFromRDS", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DataSourceId"=>DataSourceId, "RDSData"=>RDSData, "RoleARN"=>RoleARN), args)); aws_config=aws_config)

"""
    CreateDataSourceFromRedshift()

Creates a DataSource from a database hosted on an Amazon Redshift cluster. A DataSource references data that can be used to perform either CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations. CreateDataSourceFromRedshift is an asynchronous operation. In response to CreateDataSourceFromRedshift, Amazon Machine Learning (Amazon ML) immediately returns and sets the DataSource status to PENDING. After the DataSource is created and ready for use, Amazon ML sets the Status parameter to COMPLETED. DataSource in COMPLETED or PENDING states can be used to perform only CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations.   If Amazon ML can't accept the input source, it sets the Status parameter to FAILED and includes an error message in the Message attribute of the GetDataSource operation response.  The observations should be contained in the database hosted on an Amazon Redshift cluster and should be specified by a SelectSqlQuery query. Amazon ML executes an Unload command in Amazon Redshift to transfer the result set of the SelectSqlQuery query to S3StagingLocation. After the DataSource has been created, it's ready for use in evaluations and batch predictions. If you plan to use the DataSource to train an MLModel, the DataSource also requires a recipe. A recipe describes how each input variable will be used in training an MLModel. Will the variable be included or excluded from training? Will the variable be manipulated; for example, will it be combined with another variable or will it be split apart into word combinations? The recipe provides answers to these questions. You can't change an existing datasource, but you can copy and modify the settings from an existing Amazon Redshift datasource to create a new datasource. To do so, call GetDataSource for an existing datasource and copy the values to a CreateDataSource call. Change the settings that you want to change and make sure that all required fields have the appropriate values.

# Required Parameters
- `DataSourceId`: A user-supplied ID that uniquely identifies the DataSource.
- `DataSpec`: The data specification of an Amazon Redshift DataSource:  DatabaseInformation -   DatabaseName - The name of the Amazon Redshift database.    ClusterIdentifier - The unique ID for the Amazon Redshift cluster.  DatabaseCredentials - The AWS Identity and Access Management (IAM) credentials that are used to connect to the Amazon Redshift database. SelectSqlQuery - The query that is used to retrieve the observation data for the Datasource. S3StagingLocation - The Amazon Simple Storage Service (Amazon S3) location for staging Amazon Redshift data. The data retrieved from Amazon Redshift using the SelectSqlQuery query is stored in this location. DataSchemaUri - The Amazon S3 location of the DataSchema. DataSchema - A JSON string representing the schema. This is not required if DataSchemaUri is specified.   DataRearrangement - A JSON string that represents the splitting and rearrangement requirements for the DataSource.  Sample -  \"{\"splitting\":{\"percentBegin\":10,\"percentEnd\":60}}\"
- `RoleARN`: A fully specified role Amazon Resource Name (ARN). Amazon ML assumes the role on behalf of the user to create the following:    A security group to allow Amazon ML to execute the SelectSqlQuery query on an Amazon Redshift cluster An Amazon S3 bucket policy to grant Amazon ML read/write permissions on the S3StagingLocation

# Optional Parameters
- `ComputeStatistics`: The compute statistics for a DataSource. The statistics are generated from the observation data referenced by a DataSource. Amazon ML uses the statistics internally during MLModel training. This parameter must be set to true if the DataSource needs to be used for MLModel training.
- `DataSourceName`: A user-supplied name or description of the DataSource.
"""

create_data_source_from_redshift(DataSourceId, DataSpec, RoleARN; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateDataSourceFromRedshift", Dict{String, Any}("DataSourceId"=>DataSourceId, "DataSpec"=>DataSpec, "RoleARN"=>RoleARN); aws_config=aws_config)
create_data_source_from_redshift(DataSourceId, DataSpec, RoleARN, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateDataSourceFromRedshift", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DataSourceId"=>DataSourceId, "DataSpec"=>DataSpec, "RoleARN"=>RoleARN), args)); aws_config=aws_config)

"""
    CreateDataSourceFromS3()

Creates a DataSource object. A DataSource references data that can be used to perform CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations. CreateDataSourceFromS3 is an asynchronous operation. In response to CreateDataSourceFromS3, Amazon Machine Learning (Amazon ML) immediately returns and sets the DataSource status to PENDING. After the DataSource has been created and is ready for use, Amazon ML sets the Status parameter to COMPLETED. DataSource in the COMPLETED or PENDING state can be used to perform only CreateMLModel, CreateEvaluation or CreateBatchPrediction operations.   If Amazon ML can't accept the input source, it sets the Status parameter to FAILED and includes an error message in the Message attribute of the GetDataSource operation response.  The observation data used in a DataSource should be ready to use; that is, it should have a consistent structure, and missing data values should be kept to a minimum. The observation data must reside in one or more .csv files in an Amazon Simple Storage Service (Amazon S3) location, along with a schema that describes the data items by name and type. The same schema must be used for all of the data files referenced by the DataSource.  After the DataSource has been created, it's ready to use in evaluations and batch predictions. If you plan to use the DataSource to train an MLModel, the DataSource also needs a recipe. A recipe describes how each input variable will be used in training an MLModel. Will the variable be included or excluded from training? Will the variable be manipulated; for example, will it be combined with another variable or will it be split apart into word combinations? The recipe provides answers to these questions.

# Required Parameters
- `DataSourceId`: A user-supplied identifier that uniquely identifies the DataSource.
- `DataSpec`: The data specification of a DataSource:  DataLocationS3 - The Amazon S3 location of the observation data. DataSchemaLocationS3 - The Amazon S3 location of the DataSchema. DataSchema - A JSON string representing the schema. This is not required if DataSchemaUri is specified.   DataRearrangement - A JSON string that represents the splitting and rearrangement requirements for the Datasource.   Sample -  \"{\"splitting\":{\"percentBegin\":10,\"percentEnd\":60}}\"

# Optional Parameters
- `ComputeStatistics`: The compute statistics for a DataSource. The statistics are generated from the observation data referenced by a DataSource. Amazon ML uses the statistics internally during MLModel training. This parameter must be set to true if the DataSource needs to be used for MLModel training.
- `DataSourceName`: A user-supplied name or description of the DataSource.
"""

create_data_source_from_s3(DataSourceId, DataSpec; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateDataSourceFromS3", Dict{String, Any}("DataSourceId"=>DataSourceId, "DataSpec"=>DataSpec); aws_config=aws_config)
create_data_source_from_s3(DataSourceId, DataSpec, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateDataSourceFromS3", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DataSourceId"=>DataSourceId, "DataSpec"=>DataSpec), args)); aws_config=aws_config)

"""
    CreateEvaluation()

Creates a new Evaluation of an MLModel. An MLModel is evaluated on a set of observations associated to a DataSource. Like a DataSource for an MLModel, the DataSource for an Evaluation contains values for the Target Variable. The Evaluation compares the predicted result for each observation to the actual outcome and provides a summary so that you know how effective the MLModel functions on the test data. Evaluation generates a relevant performance metric, such as BinaryAUC, RegressionRMSE or MulticlassAvgFScore based on the corresponding MLModelType: BINARY, REGRESSION or MULTICLASS.  CreateEvaluation is an asynchronous operation. In response to CreateEvaluation, Amazon Machine Learning (Amazon ML) immediately returns and sets the evaluation status to PENDING. After the Evaluation is created and ready for use, Amazon ML sets the status to COMPLETED.  You can use the GetEvaluation operation to check progress of the evaluation during the creation operation.

# Required Parameters
- `EvaluationDataSourceId`: The ID of the DataSource for the evaluation. The schema of the DataSource must match the schema used to create the MLModel.
- `EvaluationId`: A user-supplied ID that uniquely identifies the Evaluation.
- `MLModelId`: The ID of the MLModel to evaluate. The schema used in creating the MLModel must match the schema of the DataSource used in the Evaluation.

# Optional Parameters
- `EvaluationName`: A user-supplied name or description of the Evaluation.
"""

create_evaluation(EvaluationDataSourceId, EvaluationId, MLModelId; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateEvaluation", Dict{String, Any}("EvaluationDataSourceId"=>EvaluationDataSourceId, "EvaluationId"=>EvaluationId, "MLModelId"=>MLModelId); aws_config=aws_config)
create_evaluation(EvaluationDataSourceId, EvaluationId, MLModelId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateEvaluation", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EvaluationDataSourceId"=>EvaluationDataSourceId, "EvaluationId"=>EvaluationId, "MLModelId"=>MLModelId), args)); aws_config=aws_config)

"""
    CreateMLModel()

Creates a new MLModel using the DataSource and the recipe as information sources.  An MLModel is nearly immutable. Users can update only the MLModelName and the ScoreThreshold in an MLModel without creating a new MLModel.  CreateMLModel is an asynchronous operation. In response to CreateMLModel, Amazon Machine Learning (Amazon ML) immediately returns and sets the MLModel status to PENDING. After the MLModel has been created and ready is for use, Amazon ML sets the status to COMPLETED.  You can use the GetMLModel operation to check the progress of the MLModel during the creation operation.  CreateMLModel requires a DataSource with computed statistics, which can be created by setting ComputeStatistics to true in CreateDataSourceFromRDS, CreateDataSourceFromS3, or CreateDataSourceFromRedshift operations.

# Required Parameters
- `MLModelId`: A user-supplied ID that uniquely identifies the MLModel.
- `MLModelType`: The category of supervised learning that this MLModel will address. Choose from the following types:  Choose REGRESSION if the MLModel will be used to predict a numeric value. Choose BINARY if the MLModel result has two possible values. Choose MULTICLASS if the MLModel result has a limited number of values.    For more information, see the Amazon Machine Learning Developer Guide.
- `TrainingDataSourceId`: The DataSource that points to the training data.

# Optional Parameters
- `MLModelName`: A user-supplied name or description of the MLModel.
- `Parameters`: A list of the training parameters in the MLModel. The list is implemented as a map of key-value pairs. The following is the current set of training parameters:    sgd.maxMLModelSizeInBytes - The maximum allowed size of the model. Depending on the input data, the size of the model might affect its performance.  The value is an integer that ranges from 100000 to 2147483648. The default value is 33554432.  sgd.maxPasses - The number of times that the training process traverses the observations to build the MLModel. The value is an integer that ranges from 1 to 10000. The default value is 10.  sgd.shuffleType - Whether Amazon ML shuffles the training data. Shuffling the data improves a model's ability to find the optimal solution for a variety of data types. The valid values are auto and none. The default value is none. We strongly recommend that you shuffle your data.   sgd.l1RegularizationAmount - The coefficient regularization L1 norm. It controls overfitting the data by penalizing large coefficients. This tends to drive coefficients to zero, resulting in a sparse feature set. If you use this parameter, start by specifying a small value, such as 1.0E-08. The value is a double that ranges from 0 to MAX_DOUBLE. The default is to not use L1 normalization. This parameter can't be used when L2 is specified. Use this parameter sparingly.   sgd.l2RegularizationAmount - The coefficient regularization L2 norm. It controls overfitting the data by penalizing large coefficients. This tends to drive coefficients to small, nonzero values. If you use this parameter, start by specifying a small value, such as 1.0E-08. The value is a double that ranges from 0 to MAX_DOUBLE. The default is to not use L2 normalization. This parameter can't be used when L1 is specified. Use this parameter sparingly.
- `Recipe`: The data recipe for creating the MLModel. You must specify either the recipe or its URI. If you don't specify a recipe or its URI, Amazon ML creates a default.
- `RecipeUri`: The Amazon Simple Storage Service (Amazon S3) location and file name that contains the MLModel recipe. You must specify either the recipe or its URI. If you don't specify a recipe or its URI, Amazon ML creates a default.
"""

create_mlmodel(MLModelId, MLModelType, TrainingDataSourceId; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateMLModel", Dict{String, Any}("MLModelId"=>MLModelId, "MLModelType"=>MLModelType, "TrainingDataSourceId"=>TrainingDataSourceId); aws_config=aws_config)
create_mlmodel(MLModelId, MLModelType, TrainingDataSourceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateMLModel", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MLModelId"=>MLModelId, "MLModelType"=>MLModelType, "TrainingDataSourceId"=>TrainingDataSourceId), args)); aws_config=aws_config)

"""
    CreateRealtimeEndpoint()

Creates a real-time endpoint for the MLModel. The endpoint contains the URI of the MLModel; that is, the location to send real-time prediction requests for the specified MLModel.

# Required Parameters
- `MLModelId`: The ID assigned to the MLModel during creation.

"""

create_realtime_endpoint(MLModelId; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateRealtimeEndpoint", Dict{String, Any}("MLModelId"=>MLModelId); aws_config=aws_config)
create_realtime_endpoint(MLModelId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("CreateRealtimeEndpoint", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MLModelId"=>MLModelId), args)); aws_config=aws_config)

"""
    DeleteBatchPrediction()

Assigns the DELETED status to a BatchPrediction, rendering it unusable. After using the DeleteBatchPrediction operation, you can use the GetBatchPrediction operation to verify that the status of the BatchPrediction changed to DELETED. Caution: The result of the DeleteBatchPrediction operation is irreversible.

# Required Parameters
- `BatchPredictionId`: A user-supplied ID that uniquely identifies the BatchPrediction.

"""

delete_batch_prediction(BatchPredictionId; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteBatchPrediction", Dict{String, Any}("BatchPredictionId"=>BatchPredictionId); aws_config=aws_config)
delete_batch_prediction(BatchPredictionId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteBatchPrediction", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BatchPredictionId"=>BatchPredictionId), args)); aws_config=aws_config)

"""
    DeleteDataSource()

Assigns the DELETED status to a DataSource, rendering it unusable. After using the DeleteDataSource operation, you can use the GetDataSource operation to verify that the status of the DataSource changed to DELETED. Caution: The results of the DeleteDataSource operation are irreversible.

# Required Parameters
- `DataSourceId`: A user-supplied ID that uniquely identifies the DataSource.

"""

delete_data_source(DataSourceId; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteDataSource", Dict{String, Any}("DataSourceId"=>DataSourceId); aws_config=aws_config)
delete_data_source(DataSourceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteDataSource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DataSourceId"=>DataSourceId), args)); aws_config=aws_config)

"""
    DeleteEvaluation()

Assigns the DELETED status to an Evaluation, rendering it unusable. After invoking the DeleteEvaluation operation, you can use the GetEvaluation operation to verify that the status of the Evaluation changed to DELETED. Caution The results of the DeleteEvaluation operation are irreversible.

# Required Parameters
- `EvaluationId`: A user-supplied ID that uniquely identifies the Evaluation to delete.

"""

delete_evaluation(EvaluationId; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteEvaluation", Dict{String, Any}("EvaluationId"=>EvaluationId); aws_config=aws_config)
delete_evaluation(EvaluationId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteEvaluation", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EvaluationId"=>EvaluationId), args)); aws_config=aws_config)

"""
    DeleteMLModel()

Assigns the DELETED status to an MLModel, rendering it unusable. After using the DeleteMLModel operation, you can use the GetMLModel operation to verify that the status of the MLModel changed to DELETED. Caution: The result of the DeleteMLModel operation is irreversible.

# Required Parameters
- `MLModelId`: A user-supplied ID that uniquely identifies the MLModel.

"""

delete_mlmodel(MLModelId; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteMLModel", Dict{String, Any}("MLModelId"=>MLModelId); aws_config=aws_config)
delete_mlmodel(MLModelId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteMLModel", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MLModelId"=>MLModelId), args)); aws_config=aws_config)

"""
    DeleteRealtimeEndpoint()

Deletes a real time endpoint of an MLModel.

# Required Parameters
- `MLModelId`: The ID assigned to the MLModel during creation.

"""

delete_realtime_endpoint(MLModelId; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteRealtimeEndpoint", Dict{String, Any}("MLModelId"=>MLModelId); aws_config=aws_config)
delete_realtime_endpoint(MLModelId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteRealtimeEndpoint", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MLModelId"=>MLModelId), args)); aws_config=aws_config)

"""
    DeleteTags()

Deletes the specified tags associated with an ML object. After this operation is complete, you can't recover deleted tags. If you specify a tag that doesn't exist, Amazon ML ignores it.

# Required Parameters
- `ResourceId`: The ID of the tagged ML object. For example, exampleModelId.
- `ResourceType`: The type of the tagged ML object.
- `TagKeys`: One or more tags to delete.

"""

delete_tags(ResourceId, ResourceType, TagKeys; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteTags", Dict{String, Any}("ResourceId"=>ResourceId, "ResourceType"=>ResourceType, "TagKeys"=>TagKeys); aws_config=aws_config)
delete_tags(ResourceId, ResourceType, TagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DeleteTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "ResourceType"=>ResourceType, "TagKeys"=>TagKeys), args)); aws_config=aws_config)

"""
    DescribeBatchPredictions()

Returns a list of BatchPrediction operations that match the search criteria in the request.

# Optional Parameters
- `EQ`: The equal to operator. The BatchPrediction results will have FilterVariable values that exactly match the value specified with EQ.
- `FilterVariable`: Use one of the following variables to filter a list of BatchPrediction:   CreatedAt - Sets the search criteria to the BatchPrediction creation date.  Status - Sets the search criteria to the BatchPrediction status.  Name - Sets the search criteria to the contents of the BatchPrediction  Name.  IAMUser - Sets the search criteria to the user account that invoked the BatchPrediction creation.  MLModelId - Sets the search criteria to the MLModel used in the BatchPrediction.  DataSourceId - Sets the search criteria to the DataSource used in the BatchPrediction.  DataURI - Sets the search criteria to the data file(s) used in the BatchPrediction. The URL can identify either a file or an Amazon Simple Storage Solution (Amazon S3) bucket or directory.
- `GE`: The greater than or equal to operator. The BatchPrediction results will have FilterVariable values that are greater than or equal to the value specified with GE.
- `GT`: The greater than operator. The BatchPrediction results will have FilterVariable values that are greater than the value specified with GT.
- `LE`: The less than or equal to operator. The BatchPrediction results will have FilterVariable values that are less than or equal to the value specified with LE.
- `LT`: The less than operator. The BatchPrediction results will have FilterVariable values that are less than the value specified with LT.
- `Limit`: The number of pages of information to include in the result. The range of acceptable values is 1 through 100. The default value is 100.
- `NE`: The not equal to operator. The BatchPrediction results will have FilterVariable values not equal to the value specified with NE.
- `NextToken`: An ID of the page in the paginated results.
- `Prefix`: A string that is found at the beginning of a variable, such as Name or Id. For example, a Batch Prediction operation could have the Name 2014-09-09-HolidayGiftMailer. To search for this BatchPrediction, select Name for the FilterVariable and any of the following strings for the Prefix:   2014-09 2014-09-09 2014-09-09-Holiday
- `SortOrder`: A two-value parameter that determines the sequence of the resulting list of MLModels.   asc - Arranges the list in ascending order (A-Z, 0-9).  dsc - Arranges the list in descending order (Z-A, 9-0).  Results are sorted by FilterVariable.
"""

describe_batch_predictions(; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeBatchPredictions"; aws_config=aws_config)
describe_batch_predictions(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeBatchPredictions", args; aws_config=aws_config)

"""
    DescribeDataSources()

Returns a list of DataSource that match the search criteria in the request.

# Optional Parameters
- `EQ`: The equal to operator. The DataSource results will have FilterVariable values that exactly match the value specified with EQ.
- `FilterVariable`: Use one of the following variables to filter a list of DataSource:   CreatedAt - Sets the search criteria to DataSource creation dates.  Status - Sets the search criteria to DataSource statuses.  Name - Sets the search criteria to the contents of DataSource   Name.  DataUri - Sets the search criteria to the URI of data files used to create the DataSource. The URI can identify either a file or an Amazon Simple Storage Service (Amazon S3) bucket or directory.  IAMUser - Sets the search criteria to the user account that invoked the DataSource creation.
- `GE`: The greater than or equal to operator. The DataSource results will have FilterVariable values that are greater than or equal to the value specified with GE.
- `GT`: The greater than operator. The DataSource results will have FilterVariable values that are greater than the value specified with GT.
- `LE`: The less than or equal to operator. The DataSource results will have FilterVariable values that are less than or equal to the value specified with LE.
- `LT`: The less than operator. The DataSource results will have FilterVariable values that are less than the value specified with LT.
- `Limit`:  The maximum number of DataSource to include in the result.
- `NE`: The not equal to operator. The DataSource results will have FilterVariable values not equal to the value specified with NE.
- `NextToken`: The ID of the page in the paginated results.
- `Prefix`: A string that is found at the beginning of a variable, such as Name or Id. For example, a DataSource could have the Name 2014-09-09-HolidayGiftMailer. To search for this DataSource, select Name for the FilterVariable and any of the following strings for the Prefix:   2014-09 2014-09-09 2014-09-09-Holiday
- `SortOrder`: A two-value parameter that determines the sequence of the resulting list of DataSource.   asc - Arranges the list in ascending order (A-Z, 0-9).  dsc - Arranges the list in descending order (Z-A, 9-0).  Results are sorted by FilterVariable.
"""

describe_data_sources(; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeDataSources"; aws_config=aws_config)
describe_data_sources(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeDataSources", args; aws_config=aws_config)

"""
    DescribeEvaluations()

Returns a list of DescribeEvaluations that match the search criteria in the request.

# Optional Parameters
- `EQ`: The equal to operator. The Evaluation results will have FilterVariable values that exactly match the value specified with EQ.
- `FilterVariable`: Use one of the following variable to filter a list of Evaluation objects:   CreatedAt - Sets the search criteria to the Evaluation creation date.  Status - Sets the search criteria to the Evaluation status.  Name - Sets the search criteria to the contents of Evaluation   Name.  IAMUser - Sets the search criteria to the user account that invoked an Evaluation.  MLModelId - Sets the search criteria to the MLModel that was evaluated.  DataSourceId - Sets the search criteria to the DataSource used in Evaluation.  DataUri - Sets the search criteria to the data file(s) used in Evaluation. The URL can identify either a file or an Amazon Simple Storage Solution (Amazon S3) bucket or directory.
- `GE`: The greater than or equal to operator. The Evaluation results will have FilterVariable values that are greater than or equal to the value specified with GE.
- `GT`: The greater than operator. The Evaluation results will have FilterVariable values that are greater than the value specified with GT.
- `LE`: The less than or equal to operator. The Evaluation results will have FilterVariable values that are less than or equal to the value specified with LE.
- `LT`: The less than operator. The Evaluation results will have FilterVariable values that are less than the value specified with LT.
- `Limit`:  The maximum number of Evaluation to include in the result.
- `NE`: The not equal to operator. The Evaluation results will have FilterVariable values not equal to the value specified with NE.
- `NextToken`: The ID of the page in the paginated results.
- `Prefix`: A string that is found at the beginning of a variable, such as Name or Id. For example, an Evaluation could have the Name 2014-09-09-HolidayGiftMailer. To search for this Evaluation, select Name for the FilterVariable and any of the following strings for the Prefix:   2014-09 2014-09-09 2014-09-09-Holiday
- `SortOrder`: A two-value parameter that determines the sequence of the resulting list of Evaluation.   asc - Arranges the list in ascending order (A-Z, 0-9).  dsc - Arranges the list in descending order (Z-A, 9-0).  Results are sorted by FilterVariable.
"""

describe_evaluations(; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeEvaluations"; aws_config=aws_config)
describe_evaluations(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeEvaluations", args; aws_config=aws_config)

"""
    DescribeMLModels()

Returns a list of MLModel that match the search criteria in the request.

# Optional Parameters
- `EQ`: The equal to operator. The MLModel results will have FilterVariable values that exactly match the value specified with EQ.
- `FilterVariable`: Use one of the following variables to filter a list of MLModel:   CreatedAt - Sets the search criteria to MLModel creation date.  Status - Sets the search criteria to MLModel status.  Name - Sets the search criteria to the contents of MLModel  Name.  IAMUser - Sets the search criteria to the user account that invoked the MLModel creation.  TrainingDataSourceId - Sets the search criteria to the DataSource used to train one or more MLModel.  RealtimeEndpointStatus - Sets the search criteria to the MLModel real-time endpoint status.  MLModelType - Sets the search criteria to MLModel type: binary, regression, or multi-class.  Algorithm - Sets the search criteria to the algorithm that the MLModel uses.  TrainingDataURI - Sets the search criteria to the data file(s) used in training a MLModel. The URL can identify either a file or an Amazon Simple Storage Service (Amazon S3) bucket or directory.
- `GE`: The greater than or equal to operator. The MLModel results will have FilterVariable values that are greater than or equal to the value specified with GE.
- `GT`: The greater than operator. The MLModel results will have FilterVariable values that are greater than the value specified with GT.
- `LE`: The less than or equal to operator. The MLModel results will have FilterVariable values that are less than or equal to the value specified with LE.
- `LT`: The less than operator. The MLModel results will have FilterVariable values that are less than the value specified with LT.
- `Limit`: The number of pages of information to include in the result. The range of acceptable values is 1 through 100. The default value is 100.
- `NE`: The not equal to operator. The MLModel results will have FilterVariable values not equal to the value specified with NE.
- `NextToken`: The ID of the page in the paginated results.
- `Prefix`: A string that is found at the beginning of a variable, such as Name or Id. For example, an MLModel could have the Name 2014-09-09-HolidayGiftMailer. To search for this MLModel, select Name for the FilterVariable and any of the following strings for the Prefix:   2014-09 2014-09-09 2014-09-09-Holiday
- `SortOrder`: A two-value parameter that determines the sequence of the resulting list of MLModel.   asc - Arranges the list in ascending order (A-Z, 0-9).  dsc - Arranges the list in descending order (Z-A, 9-0).  Results are sorted by FilterVariable.
"""

describe_mlmodels(; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeMLModels"; aws_config=aws_config)
describe_mlmodels(args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeMLModels", args; aws_config=aws_config)

"""
    DescribeTags()

Describes one or more of the tags for your Amazon ML object.

# Required Parameters
- `ResourceId`: The ID of the ML object. For example, exampleModelId.
- `ResourceType`: The type of the ML object.

"""

describe_tags(ResourceId, ResourceType; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeTags", Dict{String, Any}("ResourceId"=>ResourceId, "ResourceType"=>ResourceType); aws_config=aws_config)
describe_tags(ResourceId, ResourceType, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("DescribeTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceId"=>ResourceId, "ResourceType"=>ResourceType), args)); aws_config=aws_config)

"""
    GetBatchPrediction()

Returns a BatchPrediction that includes detailed metadata, status, and data file information for a Batch Prediction request.

# Required Parameters
- `BatchPredictionId`: An ID assigned to the BatchPrediction at creation.

"""

get_batch_prediction(BatchPredictionId; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetBatchPrediction", Dict{String, Any}("BatchPredictionId"=>BatchPredictionId); aws_config=aws_config)
get_batch_prediction(BatchPredictionId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetBatchPrediction", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BatchPredictionId"=>BatchPredictionId), args)); aws_config=aws_config)

"""
    GetDataSource()

Returns a DataSource that includes metadata and data file information, as well as the current status of the DataSource. GetDataSource provides results in normal or verbose format. The verbose format adds the schema description and the list of files pointed to by the DataSource to the normal format.

# Required Parameters
- `DataSourceId`: The ID assigned to the DataSource at creation.

# Optional Parameters
- `Verbose`: Specifies whether the GetDataSource operation should return DataSourceSchema. If true, DataSourceSchema is returned. If false, DataSourceSchema is not returned.
"""

get_data_source(DataSourceId; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetDataSource", Dict{String, Any}("DataSourceId"=>DataSourceId); aws_config=aws_config)
get_data_source(DataSourceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetDataSource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DataSourceId"=>DataSourceId), args)); aws_config=aws_config)

"""
    GetEvaluation()

Returns an Evaluation that includes metadata as well as the current status of the Evaluation.

# Required Parameters
- `EvaluationId`: The ID of the Evaluation to retrieve. The evaluation of each MLModel is recorded and cataloged. The ID provides the means to access the information.

"""

get_evaluation(EvaluationId; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetEvaluation", Dict{String, Any}("EvaluationId"=>EvaluationId); aws_config=aws_config)
get_evaluation(EvaluationId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetEvaluation", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EvaluationId"=>EvaluationId), args)); aws_config=aws_config)

"""
    GetMLModel()

Returns an MLModel that includes detailed metadata, data source information, and the current status of the MLModel. GetMLModel provides results in normal or verbose format.

# Required Parameters
- `MLModelId`: The ID assigned to the MLModel at creation.

# Optional Parameters
- `Verbose`: Specifies whether the GetMLModel operation should return Recipe. If true, Recipe is returned. If false, Recipe is not returned.
"""

get_mlmodel(MLModelId; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetMLModel", Dict{String, Any}("MLModelId"=>MLModelId); aws_config=aws_config)
get_mlmodel(MLModelId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("GetMLModel", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MLModelId"=>MLModelId), args)); aws_config=aws_config)

"""
    Predict()

Generates a prediction for the observation using the specified ML Model. Note Not all response parameters will be populated. Whether a response parameter is populated depends on the type of model requested.

# Required Parameters
- `MLModelId`: A unique identifier of the MLModel.
- `PredictEndpoint`:
- `Record`:

"""

predict(MLModelId, PredictEndpoint, Record; aws_config::AWSConfig=global_aws_config()) = machine_learning("Predict", Dict{String, Any}("MLModelId"=>MLModelId, "PredictEndpoint"=>PredictEndpoint, "Record"=>Record); aws_config=aws_config)
predict(MLModelId, PredictEndpoint, Record, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("Predict", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MLModelId"=>MLModelId, "PredictEndpoint"=>PredictEndpoint, "Record"=>Record), args)); aws_config=aws_config)

"""
    UpdateBatchPrediction()

Updates the BatchPredictionName of a BatchPrediction. You can use the GetBatchPrediction operation to view the contents of the updated data element.

# Required Parameters
- `BatchPredictionId`: The ID assigned to the BatchPrediction during creation.
- `BatchPredictionName`: A new user-supplied name or description of the BatchPrediction.

"""

update_batch_prediction(BatchPredictionId, BatchPredictionName; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateBatchPrediction", Dict{String, Any}("BatchPredictionId"=>BatchPredictionId, "BatchPredictionName"=>BatchPredictionName); aws_config=aws_config)
update_batch_prediction(BatchPredictionId, BatchPredictionName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateBatchPrediction", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("BatchPredictionId"=>BatchPredictionId, "BatchPredictionName"=>BatchPredictionName), args)); aws_config=aws_config)

"""
    UpdateDataSource()

Updates the DataSourceName of a DataSource. You can use the GetDataSource operation to view the contents of the updated data element.

# Required Parameters
- `DataSourceId`: The ID assigned to the DataSource during creation.
- `DataSourceName`: A new user-supplied name or description of the DataSource that will replace the current description.

"""

update_data_source(DataSourceId, DataSourceName; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateDataSource", Dict{String, Any}("DataSourceId"=>DataSourceId, "DataSourceName"=>DataSourceName); aws_config=aws_config)
update_data_source(DataSourceId, DataSourceName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateDataSource", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DataSourceId"=>DataSourceId, "DataSourceName"=>DataSourceName), args)); aws_config=aws_config)

"""
    UpdateEvaluation()

Updates the EvaluationName of an Evaluation. You can use the GetEvaluation operation to view the contents of the updated data element.

# Required Parameters
- `EvaluationId`: The ID assigned to the Evaluation during creation.
- `EvaluationName`: A new user-supplied name or description of the Evaluation that will replace the current content.

"""

update_evaluation(EvaluationId, EvaluationName; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateEvaluation", Dict{String, Any}("EvaluationId"=>EvaluationId, "EvaluationName"=>EvaluationName); aws_config=aws_config)
update_evaluation(EvaluationId, EvaluationName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateEvaluation", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EvaluationId"=>EvaluationId, "EvaluationName"=>EvaluationName), args)); aws_config=aws_config)

"""
    UpdateMLModel()

Updates the MLModelName and the ScoreThreshold of an MLModel. You can use the GetMLModel operation to view the contents of the updated data element.

# Required Parameters
- `MLModelId`: The ID assigned to the MLModel during creation.

# Optional Parameters
- `MLModelName`: A user-supplied name or description of the MLModel.
- `ScoreThreshold`: The ScoreThreshold used in binary classification MLModel that marks the boundary between a positive prediction and a negative prediction. Output values greater than or equal to the ScoreThreshold receive a positive result from the MLModel, such as true. Output values less than the ScoreThreshold receive a negative response from the MLModel, such as false.
"""

update_mlmodel(MLModelId; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateMLModel", Dict{String, Any}("MLModelId"=>MLModelId); aws_config=aws_config)
update_mlmodel(MLModelId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = machine_learning("UpdateMLModel", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MLModelId"=>MLModelId), args)); aws_config=aws_config)


text:
using SpecialFunctions

function test(f, α, u0, T, h)
    N=Int64(T/h)
end

ext: jl


text:
######### CmdStan optimize program example  ###########

using Compat, CmdStan, Test, Statistics

ProjDir = dirname(@__FILE__)
cd(ProjDir) do

  bernoulli = "
  data {
    int<lower=0> N;
    int<lower=0,upper=1> y[N];
  }
  parameters {
    real<lower=0,upper=1> theta;
  }
  model {
    theta ~ beta(1,1);
      y ~ bernoulli(theta);
  }
  "

  bernoullidata = [
    Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]),
    Dict("N" => 10, "y" => [0, 1, 0, 0, 0, 0, 1, 0, 0, 1]),
    Dict("N" => 10, "y" => [0, 0, 0, 0, 0, 0, 1, 0, 1, 1]),
    Dict("N" => 10, "y" => [0, 0, 0, 1, 0, 0, 0, 1, 0, 1])
  ]

  global stanmodel, rc, optim, cnames
  stanmodel = Stanmodel(Optimize(), name="bernoulli", model=bernoulli);

  rc, optim, cnames = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME);

  if rc == 0
    println()
    display(optim)
    println()
    println("Test round.(mean(optim[1][\"theta\"]), digits=1) ≈ 0.3")
    @test round.(mean(optim["theta"]), digits=1) ≈ 0.3
  end
end # cd


text:
using SpecialFunctions

"""
    black(F,K,s)

The Black function of standardised arguments:

    black(F,K,s) = F ⋅ Φ(log(F/K)/s + s/2) - K ⋅ Φ(log(F/K)/s - s/2)

This is the Black-Scholes price of a call option with spot price `F`, strike `K` and volatility `s`, assuming the discount rate `r` and carry rate `q` are zero, and the time to maturity is one.

This is monotonic increasing in `s`, with

    black(K,F,0) == max(F-K, 0)
    black(K,F,∞) == F

The corresponding put price is:

    black(K,F,s)

and so put-call parity implies:

    black(F,K,s) + K = black(K,F,s) + F

`black(F,K,s)` is the expectation of `max(exp(Y)-K,0)` where `Y` has a `Normal(log(F)-s^2/2, s)` distribution.

This can be used to compute the complementary CDF of the inverse Gaussian distribution with parameters `(λ,μ)` at `x` via,

    P[X > x] = black(1, exp(2λ/μ), 2*sqrt(λ/x))

This is largely based on the method of Jäckel (2015).

References

* Jäckel, P. (2015), Let's Be Rational. Wilmott, 2015(75): 40–53. doi:10.1002/wilm.10395

"""
function black(F,K,s)
    F > zero(F) && K > zero(K) && s ≥ 0 || throw(DomainError())
    if s == 0
        max(F-K,zero(K))
    else
        if K >= F
            x = -log(K/F)
            h = x/s
            t = s/2
            F * _black(h,t,K/F)
        else
            # use put-call parity
            x = -log(F/K)
            h = x/s
            t = s/2
            (F-K) + K * _black(h,t,F/K)
        end
    end
end

"""
    _black(h, t, K = exp(-2*h*t))

The black kernel function:

    Φ(h + t) - K*Φ(h - t)

where `K = exp(-2*h*t)` (this is provided as an extra argument, as it is typically known a priori.

Assumes `h <= 0`, `t >= 0` , which implies `K >= 1`.
"""
_black(h, t, K = exp(-2*h*t)) = _black_normcdf(h, t, K) # generic fallback

function _black(h::Float64, t::Float64, K::Float64=exp(-2*h*t))
    if h > -10 && t < 0.21022410381342865 # 2*eps()^(1/16)
        _black_small_t(h, t)
    elseif t > 0.85 - h
        _black_normcdf(h, t, K)
    else
        _black_erfcx(h, t)
    end
end

"""
    _black_normcdf(h, t, K=exp(-2*h*t))

Computes the black kernel function directly using the normal CDF.
"""
_black_normcdf(h, t, K=exp(-2*h*t)) = Φ(h+t) - K*Φ(h-t)

"""
    _black_erfcx(h, t)

Compute the black kernel function using the `erfcx` function:

    b  =  Φ(h+t) - exp(-2⋅h⋅t) ⋅ Φ(h-t)

          exp(-(h²+t²)/2)
       =  ---------------  ·  [ Φ(h+t)/ϕ(h+t) - Φ(h-t)/ϕ(h-t) ]
              √(2π)

       =  exp(-(h²+t²)/2) ⋅ [erfcx(-(h+t)/√2) - erfcx(-(h-t)/√2)]/2

"""
_black_erfcx(h,t) =
    exp(-(h+t)^2/2)*(erfcx(-invsqrt2*(h+t)) - erfcx(-invsqrt2*(h-t)))/2

"""
    _black_small_t(h, t)

Compute the black kernel function using Taylor series around `t=0`:

    b  =  Φ(h+t) - exp(-2⋅h⋅t) ⋅ Φ(h-t)

          exp(-(h²+t²)/2)
       =  ---------------  ·  [ Φ(h+t)/ϕ(h+t) - Φ(h-t)/ϕ(h-t) ]
              √(2π)

       =  exp(-(h²+t²)/2) ⋅ [erfcx(-(h+t)/√2) - erfcx(-(h-t)/√2)]/2

Using

    Y(h) = Φ(h)/φ(h) = √(π/2)·erfcx(-h/√2)
    a    = 1+h·Y(h)

Note that due to `h < 0`, and `h·Y(h) -> -1` (from above) as `h -> -∞`, we also have that `a > 0` and `a -> 0` as `h -> -∞`.
"""
function _black_small_t(h,t)
    a = 1+h*sqrthalfπ*erfcx(-invsqrt2*h)
    t2 = t*t
    h2 = h*h
    expansion = 2*t*(@horner(t2,
        a,
        @horner(h2,-1+3*a,a)/6,
        @horner(h2,-7+15*a,-1+10*a,a)/120,
        @horner(h2,-57+105*a,-18+105*a,-1+21*a,a)/5040,
        @horner(h2,-561+945*a,-285+1260*a,-33+378*a,-1+36*a,a)/362880,
        @horner(h2,-6555+10395*a,-4680+17325*a,-840+6930*a,-52+990*a,-1+55*a,a)/39916800,
        @horner(h2,-89055+135135*a,-82845+270270*a,-20370+135135*a,-1926+25740*a,-75+2145*a,-1+78*a,a)/6227020800))

    return invsqrt2π*exp(-(h+t)^2/2)*expansion
end

"""
    _cblack(h, t, K=exp(-2*h*t))

The complement of the black kernel function

    1 - _black(h, t, K)

"""
_cblack(h, t, K=exp(-2*h*t)) = Φ(-(h+t)) + K*Φ(h-t)

"""
    _black_vega(h, t)

The vega corresponding to the black kernel function:

    Φ(h + t) - K*Φ(h - t)

where `h = -log(K)/s` and `t = s/2`.
"""
_black_vega(h,t) = ϕ(h+t)


text:
"""
This module is responsible for managing an interactive conversation with a
user. Conversation messages are handled and resolved into BotActions which can
either continue the conversation or manipulate the bot's state in some way.
"""
module Interactive

using ..Edgar

include("./lex/LexRuntime.jl")
using .LexRuntime

"""
Handle a conversational message by resolving it into a bot action.
UserId is a unique id for the conversation. This could be a channel identifier,
a server identifyer, or an actual user identifier, whatever makes sense based
on the message's origin.
"""
function handle(message::AbstractString, userId::AbstractString)::BotAction
    response = LexRuntime.PostText(message, userId)
    @debug "got $response from Lex runtime service"

    handle_response(response)
end

"Typical case message handler."
function handle_response(response::LexResponse{<:DialogState, <:Intent})
    to_bot_action(response.message)
end

"Convert an empty/nonexistent message into a bot action."
to_bot_action(::Nothing) = NoAction()

"Convert an actual human-readable message into a bot action."
to_bot_action(message::Some{String}) = Reply(something(message))

"Fulfill a CreateTrial intent."
function handle_response(response::LexResponse{ReadyForFulfillment, CreateTrial})
    CreateTrialPost(
        trialname=response.slots["TrialTitle"],
        trialdate=response.slots["TrialDate"],
        trialtime=response.slots["TrialTime"]
    )
end

end # end Lex Module


text:
# Routines and Algorithms that are needed for Presolving.

"
--- Presolver Core ---
empty_row!          : Processes the empty row. Removes it or reports an Infeasibility
presolver!          : Traverses the active list of rows and detects if redundancies are found. Call approporiate functions to handle redundancies.
singleton_row!      : Processes the singleton row. Deletes the row and makes changes to the constraint matrix appropriately
other functions will be added here in the future."
function presolver!(verbose::Bool, p::Presolve_Problem, A::SparseMatrixCSC{Float64,Int64}, collb::Array{Float64,1},colub::Array{Float64,1}, c::Array{Float64,1}, rowlb::Array{Float64,1},rowub::Array{Float64,1})
    v = verbose
    v && println("PRESOLVE ROUTINES...............................")
    row = Presolve_Row()
    col = Presolve_Col()
    tmp = p.rowque

    while(tmp != nothing)
        row = tmp
        deque_row!(v,p,row)
        if(row.aij == nothing)
            empty_row!(v,p,row)
        else
            if(row.lb == row.ub)
                if(row.aij.row_next == row.aij)
                    singleton_row_eq!(v,p,row)
                else
                    forcing_constraints_eq!(v,p,row)
                end
            else
                if(row.lb == -Inf && row.ub == Inf)
                    free_row!(v,p,row)
                else
                    if(row.aij.row_next == row.aij)
                        singleton_row_ineq!(v,p,row)
                    else
                        forcing_constraints_ineq!(v,p,row)
                    end
                end
            end
        end
        if(tmp.next == tmp)
            tmp = nothing
        else
            tmp = tmp.next
        end
    end

    @show p.colque.j
    tmp = p.colque
    while(tmp != nothing)
        col = tmp
        #@show col.j
        deque_col!(v,p,col)
        if(col.aij == nothing)
            empty_col!(v,p,col)
        else
            if(col.l == col.u)
                fixed_col!(v,p,col)
            elseif(col.aij.col_next == col.aij)
                singleton_col!(v,p,row,true)
            end
        end
        if(tmp.next == tmp)
            tmp = nothing
        else
            tmp = tmp.next
        end
    end

    v && println("Making the reduced Problem")
    A,collb,colub,c,rowlb,rowub = make_new(v,p)
    return A,collb,colub,c,rowlb,rowub
end

function empty_row!(verbose::Bool, p::Presolve_Problem, row::Presolve_Row)
    # output notif
    v = verbose
    v && println("EMPTY ROW FOUND AT $(row.i)")

    # feasibility check
    if(row.lb > 0 || row.ub < 0 || row.lb > row.ub)
        error("Empty Row Infeasibility at row $row.i where the bounds are lb - $(row.lb), ub - $(row.ub)")
    else
        # fixing constraint primal y_i and dual (alpha-beta)_i.
        add_to_stack!(Empty_Row(row.i),p.independent_var,p.active_constr,p.pstack)
        # row is redundant now.
        remove_row!(v,p,row)
    end

    # output notif
    v && println("Exiting Empty Row")
end

function free_row!(verbose::Bool, p::Presolve_Problem, row::Presolve_Row)
    # making lin dep for constraint primal y_i
    v = verbose

    vec1 = Array{Int,1}()
    vec2 = Array{Float64,1}()

    tmp = row.aij
    while(tmp != nothing)
        push!(vec1,tmp.col.j)
        push!(vec2,tmp.aij)
        if(tmp.row_next != tmp)
            tmp = tmp.row_next
        else
            tmp = nothing
        end
    end
    l = Linear_Dependency(row.i,0.0,vec1,vec2)
    # fixing y_i and (alpha-beta)_i
    add_to_stack!(Free_Row(row.i,l),p.independent_var,p.active_constr,p.pstack)
    # row is redundant now.
    remove_row!(v,p,row)
end

function singleton_row_eq!(verbose::Bool, p::Presolve_Problem, row::Presolve_Row, has_bval::Bool)
    v = verbose

    matval = row.aij.val
    col = row.aij.col
    i = row.i
    j = col.j
    y_i = row.lb
    x_j = y_i/matval

    (x_j > col.u || x-j < col.l) && error("Primal Infeasibility in singleton_row $(row.i) with equality")

    add_to_stack!(Singleton_Row_Equality(i,j,x_j,y_i),p.independent_var,p.active_constr,p.pstack)
    remove_row!(v,p,row)
    col.l = col.u = xj
    fixed_col!(v,p,col)
end

function singleton_row_ineq!(verbose::Bool, p::Presolve_Problem, row::Presolve_Row, has_bval::Bool)
    v = verbose
    v && println("SINGlETON ROW FOUND AT $(row.i)")

    matval = row.aij.val
    col = row.aij.col
    i = row.i
    j = col.j

    if(matval > 0)
        l_new = row.lb / matval
        u_new = row.ub / matval
    else
        l_new = row.ub / matval
        u_new = row.lb / matval
    end

    (l_new > col.u || u_new < col.l) && error("Primal Infeasibility in singleton_row $(row.i) with double bound")

    if(l_new <= col.l && col.u <= u_new)
        row_bound = 1
    elseif(l_new <= col.l && col.u > u_new)
        row_bound = 2
    elseif(l_new > col.l && col.u <= u_new)
        row_bound = 3
    else
        row_bound = 4
    end

    vec1 = Array{Int,1}()
    vec2 = Array{Float64,1}()

    tmp = row.aij
    while(tmp != nothing)
        push!(vec1,tmp.col.j)
        push!(vec2,tmp.aij)
        if(tmp.row_next != tmp)
            tmp = tmp.row_next
        else
            tmp = nothing
        end
    end
    l = Linear_Dependency(row.i,0.0,vec1,vec2)

    col.l = max(col.l,l_new)
    col.u = min(col.u,u_new)
    add_to_stack!(Singleton_Row_Inequality(i,j,l,l_new,u_new,row_bound,matval),p.independent_var,p.active_constr,p.pstack)
    remove_row!(v,p,row)
end

function forcing_constraints_eq!(verbose::Bool, p::Presolve_Problem, row::Presolve_Row, has_bval::Bool)
    v = verbose

    tmp = row.aij
    # make g and h. traverse through each aij element in the row.
    g = 0
    h = 0
    while(tmp != nothing)
        if ((g == -Inf || g == +Inf) || (h == -Inf || h == +Inf))
            return
        end
        if(tmp.val < 0)
            g += tmp.val * tmp.col.u
            h += tmp.val * tmp.col.l
        else
            g += tmp.val * tmp.col.l
            h += tmp.val * tmp.col.u
        end

        if(tmp.row_next != tmp)
            tmp = tmp.row_next
        else
            tmp = nothing
        end
    end

    (h < row.lb || g > row.ub) && error("Infeasible problem in forcing constraints procedure")

    # analysis

    col_ind = Array{Int,1}()
    col_bound = Array{Int,1}()
    mat_val = Array{Float64,1}()
    if( g == row.ub )
        v && println("Found lower bound Forcing constraint at row $i")
        #we can fix all variables in this row to their lowerbound or upperbound.
        tmp = row.aij
        while(tmp != nothing)
            col = tmp.col
            push!(col_ind,col.j)
            push!(mat_val,tmp.val)
            if(tmp.val > 0)
                col.u = col.l
                push!(col_bound,-1)
            else
                col.l = col.u
                push!(col_bound,1)
            end
            fixed_col!(v,p,col)

            if(tmp.row_next != tmp)
                tmp = tmp.row_next
            else
                tmp = nothing
            end
        end
        add_to_stack!(Forcing_Row(row.i,col_ind,col_bound,mat_val,g),p.independent_var,p.active_constr,p.pstack)
        remove_row!(v,p,row)
    elseif( h == row.lb )
        v && println("Found upper bound Forcing constraint at row $i")
        #we can fix all variables in this row to their lowerbound or upperbound.
        tmp = row.aij
        while(tmp != nothing)
            col = tmp.col
            push!(col_ind,col.j)
            push!(mat_val,tmp.val)
            if(tmp.val > 0)
                col.l = col.u
                push!(col_bound,1)
            else
                col.u = col.l
                push!(col_bound,-1)
            end
            fixed_col!(v,p,col)
            if(tmp.row_next != tmp)
                tmp = tmp.row_next
            else
                tmp = nothing
            end
        end
        add_to_stack!(Forcing_Row(row.i,col_ind,col_bound,mat_val,h),p.independent_var,p.active_constr,p.pstack)
        remove_row!(v,p,row)
    elseif( g >= row.lb && h <= row.ub )
        # here we have g < ub and lb < h, If g is tighter than lb, update. If h is tighter than ub, update
        row.lb = -Inf
        row.ub = Inf
        free_row!(v,p,row)
    end
end

function empty_col!(v::Bool, p::Presolve_Problem, col::Presolve_Col)
    v = verbose
    v && println("EMPTY COL FOUND AT $(col.j)")

    if((col.c_val > 0 && col.l == -Inf) || (col.c_val < 0 && col.u == Inf))
        error("Dual Infeasibility from empty col at $(col.j)")
    end

    if(col.l == -Inf && col.u == Inf)
        x_j = 0
    elseif (col.l == -Inf)
        x_j = col.u
    elseif (col.u == Inf)
        x_j = col.l
    else
        if col.c_val >= 0
            x_j = col.l
        else
            x_j = col.u
        end
    end

    add_to_stack!(Empty_Col(col.j,x_j,col.c_val),p.independent_var,p.active_constr,p.pstack)
    # TODO.. accounting for constant term in the objective function
    remove_col!(v,p,p.dictcol[col.j])
end

function fixed_col!(v::Bool, p::Presolve_Problem, col::Presolve_Col)
    v = verbose
    v && println("FIXED COL FOUND AT $(col.j)")

    (col.l == -Inf || col.l == Inf) && error("Problem is unbounded due to variable $(col.j) in fixed col")

    vec1 = Array{Int,1}()
    vec2 = Array{Float64,1}()

    # need to substitute in the matrix whenever this variable occurs.
    fixed_val = col.l
    tmp = col.aij
    while(tmp != nothing)
        diff = fixed_val*tmp.val

        if(row.b_val != nothing)
            tmp.row.b_val -= diff
        end
        if(row.lb != -Inf)
            tmp.row.lb -= diff
        end
        if(row.ub != -Inf)
            tmp.row.ub -= diff
        end

        push!(vec1,tmp.row.i)
        push!(vec2,tmp.aij)

        if(tmp.col_next != tmp)
            tmp = tmp.col_next
        else
            tmp = nothing
        end
    end
    add_to_stack!(Fixed_Col(col.j,fixed_val,col.c,Linear_Dependency(col.j,0,vec1,vec2)),p.independent_var,p.active_constr,p.pstack)

    remove_col!(v,p,p.dictcol[col.j])
end

function singleton_col!(v::Bool, p::Presolve_Problem, col::Presolve_Col)
end

# TODO.. MANAGE THE return status to proper ones wrt MPB interface.


text:
export Flow, FlowMeta
export getmodel, getapproximation

# specify Flow factor node
struct Flow end
@node Flow Deterministic [ out, in ]

# specify abstract types for Flow building blocks
abstract type AbstractFlowModel end
abstract type AbstractCompiledFlowModel end
abstract type AbstractLayer end
abstract type AbstractLayerPlaceholder end
abstract type AbstractCouplingLayer <: AbstractLayer end
abstract type AbstractCouplingFlow end
abstract type AbstractCouplingFlowEmpty end
abstract type AbstractCouplingFlowPlaceholder end

# specify abstract types of nonlinear approximation
abstract type AbstractNonLinearApproximation end

@doc raw"""
The `FlowMeta` structure contains the meta data of the `Flow` factor node. More specifically, it contains the model of the `Flow` factor node. The `FlowMeta` structure can be constructed as `FlowMeta(model)`.
Make sure that the flow model has been compiled.

The `FlowMeta` structure is required for the `Flow` factor node and can be included with the Flow node as: ```
    y ~ Flow(x) where { meta = FlowMeta(...) }
```
"""
struct FlowMeta{T <: AbstractCompiledFlowModel, A <: AbstractNonLinearApproximation}
    model         :: T
    approximation :: A
end
default_meta(::Type{ Flow }) = error("The Flow node requires the meta flag to be explicitly specified. Please create a `FlowMeta` structure for this purpose and include it with the Flow node as: `y ~ Flow(x) where { meta = FlowMeta(...) }` ")

# include approximations
include("approximations/linearization.jl")
include("approximations/unscented.jl")

# structure constructors
function FlowMeta(model::T) where { T <: AbstractCompiledFlowModel }
    return FlowMeta(model, Linearization())
end

# get-functions for the FlowMeta structure
getmodel(meta::FlowMeta)         = meta.model
getapproximation(meta::FlowMeta) = meta.approximation

# include neural networks
include("coupling_flows/planar_flow.jl")
include("coupling_flows/radial_flow.jl")

# include layers
include("layers/additive_coupling_layer.jl")
include("layers/input_layer.jl")
include("layers/permutation_layer.jl")

# include models
include("flow_models/flow_model.jl")


text:
export HH3DSingleLayerTDBIO
export HH3DDoubleLayerTDBIO

# T: fieldtype
immutable HH3DSingleLayerTDBIO{T} <: RetardedPotential{T}
    "speed of light"
    speed_of_light::T
    "number of temporal differentiations"
    num_diffs
end

HH3DSingleLayerTDBIO(c) = HH3DSingleLayerTDBIO(c, 0)

# See: ?BEAST.quaddata for help
function quaddata(operator::HH3DSingleLayerTDBIO,
        test_local_space, trial_local_space, time_local_space,
        test_element, trial_element, time_element)

    quaddata(test_local_space, test_element, (3,))

end

# See: ?BEAST.quadrule for help
function quadrule(operator::HH3DSingleLayerTDBIO,
        test_local_space, trial_local_space, time_local_space,
        p, test_element, q, trial_element, r, time_element,
        quad_data)

    WiltonInts84Strat(quad_data[1,p])

end

function innerintegrals!(zlocal, operator::HH3DSingleLayerTDBIO,
        test_point, test_time,
        test_local_space, trial_local_space, time_local_space,
        test_element, trial_element, time_element,
        quad_rule, quad_weight)

    dx = quad_weight
    x = cartesian(test_point)
    n = normal(test_point)

    a = trial_element[1]
    ξ = x - dot(x -a, n) * n

    r = time_element[1]
    R = time_element[2]
    @assert r < R

    N = max(degree(time_local_space), 1)
    ∫G, = WiltonInts84.wiltonints(
        trial_element[1],
        trial_element[2],
        trial_element[3],
        x, r, R, Val{N-1})

    a = dx / (4*pi)
    D = operator.num_diffs
    @assert D == 0
    @assert numfunctions(test_local_space)  == 1
    @assert numfunctions(trial_local_space) == 1

    # aux fn to compute \int (t-R)^d / R
    @inline function tmRoR(d, t, iG)
        r = zero(t)
        for q in 0:d
            sgn = isodd(q) ? -1 : 1
            r += binomial(d,q) * sgn * t^(d-q) * iG[q+2]
        end
        r
    end

    for k in 1 : numfunctions(time_local_space)
        d = k - 1
        if d >= D
            q = 1
            for p in 0 : D-1
                q *= (d-p)
            end
            zlocal[1,1,k] += a * q * tmRoR(d-D, test_time, ∫G)
            # sgn = isodd(d) ? -1 : 1
            # zlocal[1,1,k] += a * sgn * q * ∫G[d+2-D]
        end
    end # k

end


text:
# # Model construction and modification

#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__/notebooks/@__NAME__.ipynb)
#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/notebooks/@__NAME__.ipynb)

# `COBREXA` can load models stored in `.mat`, `.json`, and `.xml` formats; and convert
# these into `StandardModel`s. However, it is also possible to construct models
# from scratch, and modify existing models. This will be demonstrated
# here.

# ## Model construction

# In `COBREXA`, model construction is primarily supported through `StandardModel`s.
# To begin, create an empty `StandardModel`.

using COBREXA

model = StandardModel("FirstModel") # assign model id = "FirstModel"

# Next, genes, metabolites and reactions need to be added to the model.

# ### Add genes to the model
gene_list = [Gene(string("g", num)) for num = 1:8]

#md # !!! warning "Warning: Don't accidentally overwrite the generic accessors"
#md #       It may be tempting to call a variable `genes`, `metabolites`, or
#md #       `reactions`. However, these names conflict with generic accessors
#md #       functions and will create problems downstream.

add_genes!(model, gene_list)

# ### Add metabolites to the model
metabolite_list = [Metabolite(string("m", num)) for num = 1:4]

metabolite_list[1].formula = "C6H12O6" # can edit metabolites, etc. directly

add_metabolites!(model, metabolite_list)

# ### Add reactions to the model

# There are two ways to create and add reactions to a model.
# These are using functions, or macros.

r_m1 = Reaction("EX_m1", Dict("m1" => -1.0), :bidirectional) # exchange reaction: m1 <-> (is the same as m1 ⟷ nothing)
r1 = Reaction("r1", Dict("m1" => -1.0, "m2" => 1.0), :forward)
r1.grr = [["g1", "g2"], ["g3"]] # add some gene reaction rules
r2 = Reaction("r2", Dict("m2" => -1.0, "m1" => 1.0), :backward)
r3 = Reaction("r3", Dict("m2" => -1.0, "m3" => 1.0), :bidirectional)

add_reactions!(model, [r1, r2, r3, r_m1]) # function approach

m1 = metabolite_list[1]
m2 = metabolite_list[2]
m3 = metabolite_list[3]
m4 = metabolite_list[4]

@add_reactions! model begin # macro approach
    "r4", m2 ⟶ m4, 0, 1000
    "r_m3", m3 ⟷ nothing, -1000, 1000
    "r_m4", m4 ⟶ nothing
    "r5", m4 ⟶ m2
end

model.reactions["r4"].grr = [["g5"], ["g6", "g7"], ["g8"]]

#md # !!! note "Note: Using reaction arrows"
#md #       `COBREXA` exports arrows that can be used to construct reactions.
#md #       Both the long and short arrows (`⟶ == →`) mean the same thing if they
#md #       point in the same direction.
#md #
#md #       These arrows are accessible by using the `LaTeX` completions built into
#md #       Julia. For example:
#md #       1. → is \rightarrow<tab>
#md #       2. ⟶ is \longrightarrow<tab>
#md #       3. ← is \leftarrow<tab>
#md #       4. ⟵ is \longleftarrow<tab>
#md #       5. ↔ is \leftrightarrow<tab>
#md #       6. ⟷ is \longleftrightarrow<tab>

# The constructed model can now be inspected.
model

# ## Modifying existing models

# It is also possible to modify a model by deleting certain genes.
# This is simply achieved by calling `remove_genes!`.

remove_genes!(model, ["g1", "g2"]; knockout_reactions = false)
model


text:
@testset "siteSelection.jl" begin

    data = CSO.dataset("cso_raw")
    ColSite = "Site"
    sites = ["4420-01D"]

    @testset "selectSite(df, Site, ColSite)" begin
        newDF = selectSite(data, site, ColSite)
        selectedSite = newDF[:, Symbol(ColSite)]

        #New Df contains only the selected sites
        @test length(unique(selectedSite)) == length(sites)

        #Ancient DF has not been changed
        @test nrow(data) != nrow(newDF)
    end

    @testset "selectSite!(df, Site, ColSite)" begin
        transformedDF = selectSite!(data, site, ColSite)
        selectedSite = transformedDF[:, Symbol(ColSite)]

        #Df contains only the selected site
        @test length(unique(selectedSite)) == length(sites)

        #Ancient DF has been changed
        @test nrow(data) == nrow(transformedDF)
    end

end

max_stars_repo_name: AlexLsn/CSO

max_issues_repo_name: AlexLsn/CSO

max_forks_repo_name: AlexLsn/CSO


text:
#! format: off

using PowerSystems
using TimeSeries

PowerSystems.download(PowerSystems.TestData; branch = "master")
base_dir = pkgdir(PowerSystems);

sys = System(joinpath(base_dir, "data", "psse_raw", "RTS-GMLC.RAW"));

sys

# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl

max_stars_repo_name: NREL-SIIP/Examples

max_issues_repo_name: NREL-SIIP/Examples

max_forks_repo_name: NREL-SIIP/Examples


text:
function calc_fan(dims...; mode = "fan_in")
  @assert mode in ["fan_in", "fan_out"]
  num_dims = length(dims)
  num_dims < 2 && throw("Number of dimensions should be more than 1!")

  fan_out = dims[1]
  fan_in = dims[2]
  # if num_dims > 2
  #   receptive_field = prod(dims[1:end-2])
  #   fan_in  *= receptive_field
  #   fan_out *= receptive_field
  # end

  mode == "fan_in" ? fan_in : fan_out
end

function calc_gain(nonlinearity, a = nothing)
  linear_fns = ["linear", "conv1d", "conv2d", "conv3d", "conv_transpose1d", "conv_transpose2d", "conv_transpose3d"]
  if nonlinearity in linear_fns || nonlinearity == "sigmoid" || nonlinearity == "σ"
    return 1.0
  elseif nonlinearity == "tanh"
    return 5.0 / 3
  elseif nonlinearity == "relu"
    return √2.0
  elseif nonlinearity == "leakyrelu"
    if a == nothing
      negative_slope = 0.01
    elseif !(a isa Bool) && a isa Integer || a isa AbstractFloat
      # true/false are instances of Integer, hence check above
      negative_slope = a
    else
      throw("negative_slope $a not a valid number.")
    end
    return √(2.0 / (1 + negative_slope ^ 2))
  else
    throw("Unsupported nonlinearity $nonlinearity.")
  end
end

function kaiming_uniform(dims...; a = 0, mode = "fan_in", nonlinearity = "leakyrelu")
  fan = calc_fan(dims...; mode = mode)
  gain = calc_gain(nonlinearity, a)
  (rand(dims...) .- 0.5) .* √(12.0 / fan) .* gain
end


text:
using ITensors,
      Test

@testset "Physics SiteSets" begin

  N = 10

  @testset "Spin Half Site" begin
    s = SpinHalfSite(3)
    @test hastags(ind(s),"Site")
    @test hastags(ind(s),"S=1/2")
    @test hastags(ind(s),"n=3")

    @test val(state(s,2)) == 2
    @test_throws ArgumentError state(s, "Fake")
  end

  @testset "Spin Half SiteSet" begin
    s = spinHalfSites(N)

    Sz5 = op(s,"Sz",5)
    @test hasinds(Sz5,s[5]',s[5])

    @test_throws ArgumentError op(s, "Fake", 2)
    @test Array(op(s,"S+",3),s[3]',s[3])  ≈ [ 0.0  1.0; 0.0  0.0]
    @test Array(op(s,"S-",4),s[4]',s[4])  ≈ [ 0.0  0.0; 1.0  0.0]
    @test Array(op(s,"Sx",2),s[2]',s[2])  ≈ [ 0.0  0.5; 0.5  0.0]
    @test Array(op(s,"iSy",2),s[2]',s[2]) ≈ [ 0.0  0.5;-0.5  0.0]
    @test Array(op(s,"Sy",2),s[2]',s[2])  ≈ [0.0  -0.5im; 0.5im  0.0]
    @test Array(op(s,"Sz",2),s[2]',s[2])  ≈ [ 0.5  0.0; 0.0 -0.5]
    @test Array(op(s,"projUp",2),s[2]',s[2])  ≈ [ 1.0  0.0; 0.0 0.0]
    @test Array(op(s,"projDn",2),s[2]',s[2])  ≈ [ 0.0  0.0; 0.0 1.0]
    @test Array(op(s,"Up",2),s[2])  ≈ [1.0,0.0]
    @test Array(op(s,"Dn",2),s[2])  ≈ [0.0,1.0]
  end

  @testset "Spin One Site" begin
    s = SpinOneSite(4)
    @test hastags(ind(s),"Site")
    @test hastags(ind(s),"S=1")
    @test hastags(ind(s),"n=4")

    @test val(state(s,3)) == 3
  end

  @testset "Spin One SiteSet" begin
    s = spinOneSites(N)

    Sz5 = op(s,"Sz",5)
    @test hasinds(Sz5,s[5]',s[5])

    @test_throws ArgumentError op(s, "Fake", 2)
    @test Array(op(s,"S+",3),s[3]',s[3]) ≈ [ 0 √2 0; 0 0 √2; 0 0 0]
    @test Array(op(s,"S-",3),s[3]',s[3]) ≈ [ 0 0 0; √2 0 0; 0.0 √2 0]
    @test Array(op(s,"Sx",3),s[3]',s[3]) ≈ [ 0 1/√2 0; 1/√2 0 1/√2; 0 1/√2 0]
    @test Array(op(s,"iSy",3),s[3]',s[3]) ≈ [ 0 1/√2 0; -1/√2 0 1/√2; 0 -1/√2 0]
    @test Array(op(s,"Sy",3),s[3]',s[3]) ≈ [ 0 -1/√2im 0; +1/√2im 0 -1/√2im; 0 +1/√2im 0]
    @test Array(op(s,"Sz",2),s[2]',s[2]) ≈ [1.0 0 0; 0 0 0; 0 0 -1.0]
    @test Array(op(s,"Sz2",2),s[2]',s[2]) ≈ [1.0 0 0; 0 0 0; 0 0 +1.0]
    @test Array(op(s,"Sx2",2),s[2]',s[2]) ≈ [0.5 0 0.5;0 1.0 0;0.5 0 0.5]
    @test Array(op(s,"Sy2",2),s[2]',s[2]) ≈ [0.5 0 -0.5;0 1.0 0;-0.5 0 0.5]
    @test Array(op(s,"projUp",2),s[2]',s[2]) ≈ [1.0 0 0;0 0 0;0 0 0]
    @test Array(op(s,"projZ0",2),s[2]',s[2]) ≈ [0 0 0;0 1.0 0;0 0 0]
    @test Array(op(s,"projDn",2),s[2]',s[2]) ≈ [0 0 0;0 0 0;0 0 1.0]
    @test Array(op(s,"XUp",2),s[2]) ≈ [0.5,im*√2,0.5]
    @test Array(op(s,"XZ0",2),s[2]) ≈ [im*√2,0,-im*√2]
    @test Array(op(s,"XDn",2),s[2]) ≈ [0.5,-im*√2,0.5]
  end

  @testset "Electron Site" begin
    s = ElectronSite(5)
    @test hastags(ind(s),"Site")
    @test hastags(ind(s),"Electron")
    @test hastags(ind(s),"n=5")

    @test val(state(s,4)) == 4
  end

  @testset "Electron SiteSet" begin
    s = electronSites(N)

    Nup5 = op(s,"Nup",5)
    @test hasinds(Nup5,s[5]',s[5])

    @test_throws ArgumentError op(s, "Fake", 2)
    Nup3 = Array(op(s,"Nup",3),s[3]',s[3])
    @test Nup3 ≈ [0. 0 0 0; 0 1 0 0; 0 0 0 0; 0 0 0 1]
    Ndn3 = Array(op(s,"Ndn",3),s[3]',s[3])
    @test Ndn3 ≈ [0. 0 0 0; 0 0 0 0; 0 0 1 0; 0 0 0 1]
    Ntot3 = Array(op(s,"Ntot",3),s[3]',s[3])
    @test Ntot3 ≈ [0. 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 2]
    Cup3 = Array(op(s,"Cup",3),s[3]',s[3])
    @test Cup3 ≈ [0. 1 0 0; 0 0 0 0; 0 0 0 1; 0 0 0 0]
    Cdagup3 = Array(op(s,"Cdagup",3),s[3]',s[3])
    @test Cdagup3 ≈ [0. 0 0 0; 1 0 0 0; 0 0 0 0; 0 0 1 0]
    Cdn3 = Array(op(s,"Cdn",3),s[3]',s[3])
    @test Cdn3 ≈ [0. 0 1 0; 0 0 0 1; 0 0 0 0; 0 0 0 0]
    Cdagdn3 = Array(op(s,"Cdagdn",3),s[3]',s[3])
    @test Cdagdn3 ≈ [0. 0 0 0; 0 0 0 0; 1 0 0 0; 0 1 0 0]
    F3 = Array(op(s,"F",3),s[3]',s[3])
    @test F3 ≈ [1. 0 0 0; 0 -1 0 0; 0 0 -1 0; 0 0 0 1]
    Fup3 = Array(op(s,"Fup",3),s[3]',s[3])
    @test Fup3 ≈ [1. 0 0 0; 0 -1 0 0; 0 0 1 0; 0 0 0 -1]
    Fdn3 = Array(op(s,"Fdn",3),s[3]',s[3])
    @test Fdn3 ≈ [1. 0 0 0; 0 1 0 0; 0 0 -1 0; 0 0 0 -1]
    Sz3 = Array(op(s,"Sz",3),s[3]',s[3])
    @test Sz3 ≈ [0. 0 0 0; 0 0.5 0 0; 0 0 -0.5 0; 0 0 0 0]
    Sx3 = Array(op(s,"Sx",3),s[3]',s[3])
    @test Sx3 ≈ [0. 0 0 0; 0 0 0.5 0; 0 0.5 0 0; 0 0 0 0]
    Sp3 = Array(op(s,"S+",3),s[3]',s[3])
    @test Sp3 ≈ [0. 0 0 0; 0 0 1 0; 0 0 0 0; 0 0 0 0]
    Sm3 = Array(op(s,"S-",3),s[3]',s[3])
    @test Sm3 ≈ [0. 0 0 0; 0 0 0 0; 0 1 0 0; 0 0 0 0]
    Sem = Array(op(s,"Emp",3),s[3])
    @test Sem ≈ [1.0; 0.0; 0.0; 0.0]
    Sup = Array(op(s,"Up",3),s[3])
    @test Sup ≈ [0.0; 1.0; 0.0; 0.0]
    Sdn = Array(op(s,"Dn",3),s[3])
    @test Sdn ≈ [0.0; 0.0; 1.0; 0.0]
    Supdn = Array(op(s,"UpDn",3),s[3])
    @test Supdn ≈ [0.0; 0.0; 0.0; 1.0]
  end

  @testset "tJ Site" begin
    s = tJSite(5)
    @test hastags(ind(s),"Site")
    @test hastags(ind(s),"tJ")
    @test hastags(ind(s),"n=5")

    @test val(state(s,3)) == 3
  end

  @testset "tJ SiteSet" begin
    s = tJSites(N)

    @test_throws ArgumentError op(s, "Fake", 2)
    Nup_2 = op(s,"Nup",2)
    @test Nup_2[2,2] ≈ 1.0
    Ndn_2 = op(s,"Ndn",2)
    @test Ndn_2[3,3] ≈ 1.0
    Ntot_2 = op(s,"Ntot",2)
    @test Ntot_2[2,2] ≈ 1.0
    @test Ntot_2[3,3] ≈ 1.0
    Cup3 = Array(op(s,"Cup",3),s[3]',s[3])
    @test Cup3 ≈ [0. 1 0; 0 0 0; 0 0 0]
    Cdup3 = Array(op(s,"Cdagup",3),s[3]',s[3])
    @test Cdup3 ≈ [0 0 0; 1. 0 0; 0 0 0]
    Cdn3 = Array(op(s,"Cdn",3),s[3]',s[3])
    @test Cdn3 ≈ [0. 0. 1; 0 0 0; 0 0 0]
    Cddn3 = Array(op(s,"Cdagdn",3),s[3]',s[3])
    @test Cddn3 ≈ [0 0 0; 0. 0 0; 1 0 0]
    FP3 = Array(op(s,"FP",3),s[3]',s[3])
    @test FP3 ≈ [1.0 0. 0; 0 -1.0 0; 0 0 -1.0]
    Fup3 = Array(op(s,"Fup",3),s[3]',s[3])
    @test Fup3 ≈ [1.0 0. 0; 0 -1.0 0; 0 0 1.0]
    Fdn3 = Array(op(s,"Fdn",3),s[3]',s[3])
    @test Fdn3 ≈ [1.0 0. 0; 0 1.0 0; 0 0 -1.0]
    Sz3 = Array(op(s,"Sz",3),s[3]',s[3])
    @test Sz3 ≈ [0.0 0. 0; 0 0.5 0; 0 0 -0.5]
    Sx3 = Array(op(s,"Sx",3),s[3]',s[3])
    @test Sx3 ≈ [0.0 0. 0; 0 0 1; 0 1 0]
    Sp3 = Array(op(s,"Splus",3),s[3]',s[3])
    @test Sp3 ≈ [0.0 0. 0; 0 0 1.0; 0 0 0]
    Sm3 = Array(op(s,"Sminus",3),s[3]',s[3])
    @test Sm3 ≈ [0.0 0. 0; 0 0 0; 0 1.0 0]
    Up3 = Array(op(s,"Up",3),s[3])
    @test Up3 ≈ [0.0; 1.0; 0]
    Dn3 = Array(op(s,"Dn",3),s[3])
    @test Dn3 ≈ [0.0; 0.0; 1.0]
    Em3 = Array(op(s,"Emp",3),s[3])
    @test Em3 ≈ [1.0; 0.0; 0.0]
  end
end


text:
function compute_seat_id(spec)
  front::UInt8 = 0
  back::UInt8 = 127
  left::UInt8 = 0
  right::UInt8 = 7
  for c in spec
    if c == 'F'
      back = div(back - front, 2) + front
    elseif c == 'B'
      front = div(back - front, 2) + front
    elseif c == 'L'
      right = div(right - left, 2) + left
    elseif c == 'R'
      left = div(right - left, 2) + left
    end
  end

  back * 8 + right
end

function find_seat(data)
  seats = sort(map(compute_seat_id, data))
  max_id = maximum(seats)
  seat_id = -1
  for (idx, seat) in enumerate(seats)
    if seats[idx + 1] == seat + 2
      seat_id = seat + 1
      break
    end
  end

  max_id, seat_id
end

function solve(data)
  println(@time find_seat(data))
end

data = readlines("input.txt")
solve(data)

max_stars_repo_name: wbthomason/advent

max_issues_repo_name: wbthomason/advent

max_forks_repo_name: wbthomason/advent


text:
module problem113

description = """
Non-bouncy numbers

Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
As n increases, the proportion of bouncy numbers below n increases such that there are only 12951 numbers below one-million that are not bouncy and only 277032 non-bouncy numbers below 10^10.

How many numbers below a googol (10^100) are not bouncy?
"""

# Count the number of non-bouncy numbers having a given number of digits
# This is sufficent to solve the problem of non-bouncy's less than 10^100, numDigits = 100
# Non-bouncy count is increasing + decreasing - flat (eg, 111, 222, 333)
function non_bouncy_count(numdigits :: Integer)
  return increasing(numdigits) + decreasing(numdigits) - 9*numdigits
end

# count of increasing numbers with maximum number of digits
# Solve this by tabulating numdigits vs maxDigit in number, table[3, 7] is number of 3-digit increasing numbers having max digit=7
# A pattern appears where i,j = i-1,j + i,j-1
# First row and first column are all 1's
function increasing(numDigits :: Integer)
  table = zeros(Int, numDigits, 9)
  table[1,:] = 1
  table[:,1] = 1
  for i = 2:numDigits
    for j = 2:9
      table[i,j] = table[i-1, j] + table[i, j-1]
    end
  end
  return sum(table)
end

# Similar to increasing, tabulate the solution, but requires some care because 0 can appear in a decreasing number,
# but zero is not counted as a single digit decreasing number.
# In this function, table[4, 8] is number of 4-digit increasing numbers with min digit = 9 (offset by 1 to accomodate 0)
function decreasing(numDigits :: Integer)
  table = zeros(Int, numDigits, 10)
  table[1, :] = 1
  table[1, 1] = 0 # zero is not counted
  table[:,10] = 1
  for i = 2:numDigits
    for j = 9:-1:1
      table[i, j] = table[i-1, j] + table[i, j+1]
    end
  end
  return sum(table)
end

using Base.Test
@test increasing(1) == 9
@test increasing(2) == 45 + 9
@test decreasing(1) == 9
@test decreasing(2) == 54 + 9
@test non_bouncy_count(6) == 12951
@test non_bouncy_count(10) == 277032

end

max_stars_repo_name: mbuhot/mbuhot-euler-solutions

max_issues_repo_name: mbuhot/mbuhot-euler-solutions

max_forks_repo_name: mbuhot/mbuhot-euler-solutions


text:
#### Common code and functions
#### "Slow organisms exhibit sudden population disappearances in a reddened world" by Greyson-Gaito, Gellner, & McCann.

function abpath()
    replace(@__DIR__, "scripts" => "")
end #function to create a absolute path as a character string

@with_kw mutable struct RozMacPar
    r = 2.0
    k = 3.0
    a = 1.1
    h = 0.8
    e = 0.7
    m = 0.4
    ε = 1.0
end

par_rozmac = RozMacPar()

function roz_mac_II!(du, u, p, t,)
    @unpack r, k, a, h, e, m, ε = p
    R, C = u
    du[1] = r * R * (1 - R / k) - a * R * C / (1 + a * h * R)
    du[2] = ε * ( e * a * R * C / (1 + a * h * R) - m * C )
    return
end #setting up the Rosenzweig-MacArthur model

function roz_mac_II(u, par)
    du = similar(u)
    roz_mac_II!(du, u, par, 0.0)
    return du
end #setting up the Rosenzweig-MacArthur model

function eq_II(p)
    @unpack r, a, k, h, m, e = p
    eq_II_R = m / (a * (e - h * m))
    eq_II_C = r * (a * h * k * eq_II_R - a * h * eq_II_R^2 + k - eq_II_R) / (a * k)
    return vcat(eq_II_R, eq_II_C)
end #calculating the interior equilibrium of the Rosenzweig-MacArthur model

randeq(x) = x * ( 1 + rand(Uniform(1e-7, 1e-6)))

jacmat(model, eq, par) = ForwardDiff.jacobian(eq -> model(eq, par), eq) #calculate the jacobian matrix

λ_stability(M) = maximum(real.(eigvals(M))) #calculate the maximum real eigenvalue

function roz_mac_res(R, C, p)
    @unpack r, k, h, a, m = p
    return r * R * (1 - R / k) - (a * R * C / (1 + a * h * R) )
end #returns the rate of change in resource

function roz_mac_con(R, C, eff, ep, p)
    @unpack h, a, m = p
    return ep * ( ( eff * a * R * C ) / (1 + a * h * R) - m * C )
end #returns the rate of change in consumer

function con_iso_roz_mac(p)
    @unpack m, a, h, e = p
    m / (a * (e - h * m))
end #calculate the consumer isocline

function res_iso_roz_mac(R, p)
    @unpack a, k, r, h = p
    r * (a * h * k * R - a * h * R^2 + k - R) / (a * k)
end #function to help calculate the resource isocline

function iso_plot(resrange, par)
    data = [res_iso_roz_mac(R, par) for R in resrange]
    plot(collect(resrange), data)
    return vlines(con_iso_roz_mac(par), 0, maximum(data)+(0.1* maximum(data)), colors="orange")
end #plots the resource and consumer isoclines for the Rosenzweig-MacArthur consumer-resource model

function roz_mac_plot(ep, eff, width, dens)
    resconrange = range(0, stop = 1.7, length=100)
    U = [roz_mac_res(R, C, par_rozmac) for C in resconrange, R in resconrange]
    V = [roz_mac_con(R, C, eff, ep, par_rozmac) for C in resconrange, R in resconrange]
    speed = sqrt.(U.^2 .+ V.^2)
    lw = width .* speed ./ maximum(speed) # Line Widths
    streamplot(collect(resconrange), collect(resconrange), U, V, density = dens, color = "k", linewidth = lw)
    return iso_plot(resconrange, RozMacPar(e = eff))
end #plots the streamplot for the Rosenzweig-MacArthur consumer-resource model with the isoclines

function noise_creation(r, len)
    white = rand(Normal(0.0, 0.01), Int64(len))
    intnoise = [white[1]]
    for i in 2:Int64(len)
        intnoise = append!(intnoise, r * intnoise[i-1] + white[i] )
    end
    c = std(white)/std(intnoise)
    meanintnoise = mean(intnoise)
    scalednoise = zeros(Int64(len))
    for i in 1:Int64(len)
        scalednoise[i] = c * (intnoise[i] - meanintnoise)
    end
    return scalednoise
end #produces noise with a certain autocorrelation. variance of the noise is scaled using method in Wichmann et al. 2005

function RozMac_pert(ep, eff, freq, r, seed, tsend, tvals)
    Random.seed!(seed)
    par = RozMacPar()
    par.ε = ep
    par.e = eff
    noise = noise_creation(r, tsend / freq)
    count = 1
    u0 = [eq_II(par)[1], eq_II(par)[2] + noise[1]]
    tspan = (0.0, tsend)

    function pert_cb2(integrator)
        count += 1
        if isapprox(integrator.u[2], 0.00000000; atol = 1e-8)
            integrator.u[2] = 0.00000000
        else
            integrator.u[2] = maximum([integrator.u[2] + noise[count], 0.0])
        end
    end

    cb = PeriodicCallback(pert_cb2, freq, initial_affect = false) #as of may 29th - initial_affect does not actually do the affect on the first time point
    prob = ODEProblem(roz_mac_II!, u0, tspan, par)
    sol = DifferentialEquations.solve(prob, callback = cb, reltol = 1e-8)
    return solend = sol(tvals)
end #function to numerically solve the Rosenzweig-MacArthur consumer-resource model with added noise to the consumer

function pert_timeseries_plot(ep, eff, freq, r, seed, tsend, tvals)
    sol = RozMac_pert(ep, eff, freq, r, seed, tsend, tvals)
    return plot(sol.t, sol.u)
end #plots the time series of the stochastically perturbed Rosenzweig-MacArthur consumer-resource model

function pert_consumer_timeseries_plot(ep, eff, freq, seed, tsend, tvals)
    sol = RozMac_pert(ep, eff, freq, r, seed, tsend, tvals)
    plot(sol.t, sol[2, :])
    return ylabel("Consumer biomass")
end #plots the consumer time series of the stochastically perturbed Rosenzweig-MacArthur consumer-resource model

function pert_phase_plot(ep, eff, freq, r, seed, tsend, tvals)
    sol = RozMac_pert(ep, eff, freq, r, seed, tsend, tvals)
    plot(sol[1, :], sol[2, :])
    xlabel("Resource")
    return ylabel("Consumer")
end #plots the time series of the stochastically perturbed Rosenzweig-MacArthur consumer-resource model

function prep_data(data, range)
    canard_prop = zeros(length(data))
    canard_plus_axial_prop = zeros(length(data))
    for i in 1:length(data)
        canard_prop[i] = data[i][1]
        canard_plus_axial_prop[i] = data[i][1] + data[i][2]
    end
    return DataFrame(xrange = range, canard = canard_prop, canard_plus_axial = canard_plus_axial_prop)
end #helper function to take data from canard finder simulations and convert to DataFrame

function transcrit_rozmac(p)
    @unpack a, k, h, m = p
    return h * m + m / (a * k)
end #calculate the efficiency parameter value where the transcritical bifurcation occurs

function hopf_rozmac(p)
    @unpack k, a, h, r, m= p
    R = k / 2 - 1 / (2 * a * h)
    return m / (R * a) + ( h * m)
end #calculate the efficiency parameter value where the Hopf bifurcation occurs

function converteff_prop_RCdivide(eff)
    hopf = hopf_rozmac(RozMacPar(e = eff))
    transcrit = transcrit_rozmac(RozMacPar(e = eff))
    hopf_minus_eff = hopf - eff
    propeff = hopf_minus_eff / (hopf-transcrit)
    finalprop = 1 .- propeff
    return finalprop
end #Function to convert efficiency value to effective proportion real value

function findRCdivide_epx(ep, hopf, transcrit)
    par = RozMacPar()
    par.ε = ep
    evals = transcrit:0.00005:hopf

    for (ei, eval) in enumerate(evals)
        par.e = eval
        equ = eq_II(par)
        eig1 = imag.(eigvals(jacmat(roz_mac_II, equ, par))[1])
        if eig1 < 0 || eig1 > 0
            return eval
            break
        end
    end
end #Function to calculate the proportion of real in efficiency "parameter space" (real/complex divide between the transcritical and Hopf bifurcation) for a single ε value.

function findRCdivide_epx_data()
    hopf = hopf_rozmac(RozMacPar())
    transcrit = transcrit_rozmac(RozMacPar())
    epvals = 0.001:0.001:100.0
    effRC = zeros(length(epvals))
    @threads for i in eachindex(epvals)
        @inbounds effRC[i] =  findRCdivide_epx(epvals[i], hopf, transcrit)
    end
    effRC_minus_hopf = hopf .- effRC
    effRC_propC = effRC_minus_hopf ./ (hopf-transcrit)
    effRC_propR = 1 .- effRC_propC
    return hcat(collect(1 ./epvals), effRC_propR)
end # Function to calculate the proportion of real in efficiency "parameter space" for multiple values of ε.

function quasicycle_data(ep, reps)
    lrange = 0:1:40
    ACFdata = Vector{Vector{Float64}}(undef,reps)
    avprep = zeros(reps)
    avfinal = zeros(length(lrange))
    @threads for i in 1:reps
        sol = RozMac_pert(ep, 0.6, 1.0, 0.0, i, 10000.0, 9000.0:1.0:10000.0)
        @inbounds ACFdata[i] = autocor(sol[2, 1:end], collect(lrange))
    end
    for j in 1:length(lrange)
        for l in 1:reps
        avprep[l] = ACFdata[l][j]
        end
        avfinal[j] = mean(avprep)
    end
    return avfinal
end #calculates the average ACF value for each lag point for a set of simulations of the Rosenzweig-MacArthur model with added stochasticity (where ε is 1.0)


text:
lada_dos()::String = numerify(executor(data["faker"]["phone_number"]["lada_dos"]))
lada_tres()::String = numerify(executor(data["faker"]["phone_number"]["lada_tres"]))
area_code()::String = numerify(executor(data["faker"]["phone_number"]["area_code"]))
exchange_code()::String = numerify(executor(data["faker"]["phone_number"]["exchange_code"]))
phone_number()::String = numerify(executor(data["faker"]["phone_number"]["formats"]))
cell_phone()::String = numerify(executor(data["faker"]["cell_phone"]["formats"]))


text:
# Struct Det 2D functor (4 methods) #

# Return V(x,y,ti)
function (a::SolveOutDet2D)(ti::AbstractFloat)
    t = findlast(x->x==ti,a.tsaved)
    return a.V[(t-1)*a.N+1:a.N*t,:]
end
(a::SolveOutDet2D)(i::Int) = a.V[(i-1)*a.N+1:a.N*i,:]

# Return V(xj,yk,ti)
function (a::SolveOutDet2D)(xj::AbstractFloat,yk::AbstractFloat,ti::AbstractFloat)
    t  = findlast(i->i==ti,a.tsaved)
    x  = findlast(j->j==xj,a.x)
    y  = findlast(k->k==yk,a.y)
    Vi = @view a.V[(t-1)*a.N+1:a.N*t,:] # solution at ti

    return Vi[x,y]
end
function (a::SolveOutDet2D)(j::Int,k::Int,i::Int)
    Vi = @view a.V[(i-1)*a.N+1:a.N*i,:]
    return Vi[j,k]
end

# Struct Sto 2D functor (8 methods) #

# Return V(x,y,ti,p)
function (a::SolveOutSto2D)(ti::AbstractFloat,p::Int)
    t = findlast(i->i==ti,a.tsaved)
    return a.V[(t-1)*a.N+1:a.N*t,:,p]
end
(a::SolveOutSto2D)(i::Int,p::Int) = a.V[(i-1)*a.N+1:a.N*i,:,p]

# Return Vmean(x,y,ti)
function (b::SolveOutSto2D)(ti::AbstractFloat)
    t = findlast(i->i==ti,b.tsaved)
    return b.meanV[(t-1)*b.N+1:b.N*t,:]
end
(b::SolveOutSto2D)(i::Int) = b.meanV[(i-1)*b.N+1:b.N*i,:]

# Return V(xj,yk,ti,p)
function (a::SolveOutSto2D)(xj::AbstractFloat,yk::AbstractFloat,ti::AbstractFloat,p::Int)
    t  = findlast(i->i==ti,a.tsaved)
    x  = findlast(j->j==xj,a.x)
    y  = findlast(k->k==yk,a.y)
    Vi = @view a.V[(t-1)*a.N+1:a.N*t,:,p]

    return Vi[x,y]
end
function (a::SolveOutSto2D)(j::Int,k::Int,i::Int,p::Int)
    Vi = @view a.V[(i-1)*a.N+1:a.N*i,:,p]
    return Vi[j,k]
end

# Return Vmean(xj,yk,ti)
function (b::SolveOutSto2D)(xj::AbstractFloat,yk::AbstractFloat,ti::AbstractFloat)
    t  = findlast(i->i==ti,b.tsaved)
    x  = findlast(j->j==xj,b.x)
    y  = findlast(k->k==yk,b.y)
    Vi = @view b.meanV[(t-1)*b.N+1:b.N*t,:]

    return Vi[x,y]
end
function (b::SolveOutSto2D)(j::Int,k::Int,i::Int)
    Vi = @view b.meanV[(i-1)*b.N+1:b.N*i,:]
    return Vi[j,k]
end


text:
function lfur_pv(X, c)
  #
  #
  q = size(X, 1);
  tmp = ((1:1:q)*pi).^2;
  cov_H0 = 1./tmp;
  chol_H0 = sqrt(cov_H0);
  chol_H0_inv = sqrt(1./cov_H0);
  X0 = chol_H0_inv.*X;
  cov_HA = Sigma_Compute2(0, c, 1, q)
  chol_HA_inv = chol(Hermitian(inv(cov_HA), :L));
  XA = chol_HA_inv*X;
  lfur = sum(X0.^2)/sum(XA.^2);
  # Generate 1000 draws under Ho for pvalue calculation
  nsim = 50000;
  Xsim = rand(Normal(0,1), q, nsim).*repmat(chol_H0, 1, nsim);
  X0sim = Xsim.*repmat(chol_H0_inv, 1, nsim);
  XAsim = chol_HA_inv*Xsim;
  nx = sum(X0sim.^2, 1);
  dx = sum(XAsim.^2, 1);
  lfur_sim = squeeze((nx./dx)',2);
  lfur_pvalue =  mean(lfur_sim.>=lfur)
  return lfur, lfur_pvalue
end


text:
module TreeKnit

# To remove eventually
# using DataFrames
# External modules
using Comonicon
# using LightGraphs
using Parameters
using Random
using Setfield
# Personal modules
using TreeTools

include("mcc_base.jl")
export naive_mccs, reduce_to_mcc, reduce_to_mcc!

include("mcc_splits.jl")

include("mcc_tools.jl")

include("mcc_IO.jl")
export read_mccs, write_mccs

include("resolving.jl")
export resolve!

include("SplitGraph/SplitGraph.jl")
using TreeKnit.SplitGraph

include("objects.jl")
export OptArgs

include("main.jl")
export computeMCCs, inferARG

include("SimpleReassortmentGraph/SimpleReassortmentGraph.jl")
import TreeKnit.SimpleReassortmentGraph: SRG
export SRG

include("Flu.jl")
export Flu

include("cli.jl")

# TreeTools re-exports for docs
import TreeTools: node2tree, parse_newick
export node2tree
export parse_newick

end # module

max_stars_repo_name: PierreBarrat/OldTreeKnit

max_issues_repo_name: PierreBarrat/OldTreeKnit

max_forks_repo_name: PierreBarrat/OldTreeKnit


text:
using LightGraphs, GraphIO
using StatsBase

function label_partition(g; k=8)
    unlabeled_nodes = Set(vertices(g));
    labeled_nodes = Set();
    finished_nodes = Set();
    labels = zeros(Int, nv(g));
    random_k_nodes = sample(vertices(g), k, replace=false);
    for (i, r) in enumerate(random_k_nodes)
        labels[r] = i;
        unlabeled_nodes = delete!(unlabeled_nodes, r)
        labeled_nodes = push!(labeled_nodes, r)
    end

    operations = 0
    while !isempty(unlabeled_nodes)
        for n in copy(labeled_nodes)
            n_neighbors = setdiff(Set(neighbors(g, n)), union(labeled_nodes, finished_nodes))
            operations += 1
            if !isempty(n_neighbors)
                neighbor = sample(collect(n_neighbors), 1)[1];
                labels[neighbor] = labels[n];
                unlabeled_nodes = delete!(unlabeled_nodes, neighbor);
                labeled_nodes = push!(labeled_nodes, neighbor);
                n_neighbors = delete!(n_neighbors, neighbor);
            end
            if isempty(n_neighbors)
                labeled_nodes = delete!(labeled_nodes, n);
                finished_nodes = push!(finished_nodes, n);
            end
        end
    end
    return labels
end

function graph_partition(g; k=8, c=10)
    best_partition = []
    best_modularity = -Inf
    for i in 1:c
        partitions = label_partition(g; k=k)
        partition_modularity = modularity(g, partitions)
#     println(partition_modularity)
        if (best_modularity < partition_modularity)
            best_partition = partitions
            best_modularity = partition_modularity
        end
    end
    return best_partition, best_modularity
end

max_stars_repo_name: aadimator/label-graph-partitioning

max_issues_repo_name: aadimator/label-graph-partitioning

max_forks_repo_name: aadimator/label-graph-partitioning