licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
41266
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: worklink using AWS.Compat using AWS.UUIDs """ associate_domain(acm_certificate_arn, domain_name, fleet_arn) associate_domain(acm_certificate_arn, domain_name, fleet_arn, params::Dict{String,<:Any}) Specifies a domain to be associated to Amazon WorkLink. # Arguments - `acm_certificate_arn`: The ARN of an issued ACM certificate that is valid for the domain being associated. - `domain_name`: The fully qualified domain name (FQDN). - `fleet_arn`: The Amazon Resource Name (ARN) of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DisplayName"`: The name to display. """ function associate_domain( AcmCertificateArn, DomainName, FleetArn; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/associateDomain", Dict{String,Any}( "AcmCertificateArn" => AcmCertificateArn, "DomainName" => DomainName, "FleetArn" => FleetArn, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_domain( AcmCertificateArn, DomainName, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/associateDomain", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AcmCertificateArn" => AcmCertificateArn, "DomainName" => DomainName, "FleetArn" => FleetArn, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_website_authorization_provider(authorization_provider_type, fleet_arn) associate_website_authorization_provider(authorization_provider_type, fleet_arn, params::Dict{String,<:Any}) Associates a website authorization provider with a specified fleet. This is used to authorize users against associated websites in the company network. # Arguments - `authorization_provider_type`: The authorization provider type. - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DomainName"`: The domain name of the authorization provider. This applies only to SAML-based authorization providers. """ function associate_website_authorization_provider( AuthorizationProviderType, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/associateWebsiteAuthorizationProvider", Dict{String,Any}( "AuthorizationProviderType" => AuthorizationProviderType, "FleetArn" => FleetArn ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_website_authorization_provider( AuthorizationProviderType, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/associateWebsiteAuthorizationProvider", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AuthorizationProviderType" => AuthorizationProviderType, "FleetArn" => FleetArn, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_website_certificate_authority(certificate, fleet_arn) associate_website_certificate_authority(certificate, fleet_arn, params::Dict{String,<:Any}) Imports the root certificate of a certificate authority (CA) used to obtain TLS certificates used by associated websites within the company network. # Arguments - `certificate`: The root certificate of the CA. - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DisplayName"`: The certificate name to display. """ function associate_website_certificate_authority( Certificate, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/associateWebsiteCertificateAuthority", Dict{String,Any}("Certificate" => Certificate, "FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_website_certificate_authority( Certificate, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/associateWebsiteCertificateAuthority", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Certificate" => Certificate, "FleetArn" => FleetArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_fleet(fleet_name) create_fleet(fleet_name, params::Dict{String,<:Any}) Creates a fleet. A fleet consists of resources and the configuration that delivers associated websites to authorized users who download and set up the Amazon WorkLink app. # Arguments - `fleet_name`: A unique name for the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DisplayName"`: The fleet name to display. - `"OptimizeForEndUserLocation"`: The option to optimize for better performance by routing traffic through the closest AWS Region to users, which may be outside of your home Region. - `"Tags"`: The tags to add to the resource. A tag is a key-value pair. """ function create_fleet(FleetName; aws_config::AbstractAWSConfig=global_aws_config()) return worklink( "POST", "/createFleet", Dict{String,Any}("FleetName" => FleetName); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_fleet( FleetName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/createFleet", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetName" => FleetName), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_fleet(fleet_arn) delete_fleet(fleet_arn, params::Dict{String,<:Any}) Deletes a fleet. Prevents users from accessing previously associated websites. # Arguments - `fleet_arn`: The ARN of the fleet. """ function delete_fleet(FleetArn; aws_config::AbstractAWSConfig=global_aws_config()) return worklink( "POST", "/deleteFleet", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_fleet( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/deleteFleet", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_audit_stream_configuration(fleet_arn) describe_audit_stream_configuration(fleet_arn, params::Dict{String,<:Any}) Describes the configuration for delivering audit streams to the customer account. # Arguments - `fleet_arn`: The ARN of the fleet. """ function describe_audit_stream_configuration( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeAuditStreamConfiguration", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_audit_stream_configuration( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeAuditStreamConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_company_network_configuration(fleet_arn) describe_company_network_configuration(fleet_arn, params::Dict{String,<:Any}) Describes the networking configuration to access the internal websites associated with the specified fleet. # Arguments - `fleet_arn`: The ARN of the fleet. """ function describe_company_network_configuration( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeCompanyNetworkConfiguration", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_company_network_configuration( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeCompanyNetworkConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_device(device_id, fleet_arn) describe_device(device_id, fleet_arn, params::Dict{String,<:Any}) Provides information about a user's device. # Arguments - `device_id`: A unique identifier for a registered user's device. - `fleet_arn`: The ARN of the fleet. """ function describe_device( DeviceId, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeDevice", Dict{String,Any}("DeviceId" => DeviceId, "FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_device( DeviceId, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeDevice", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DeviceId" => DeviceId, "FleetArn" => FleetArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_device_policy_configuration(fleet_arn) describe_device_policy_configuration(fleet_arn, params::Dict{String,<:Any}) Describes the device policy configuration for the specified fleet. # Arguments - `fleet_arn`: The ARN of the fleet. """ function describe_device_policy_configuration( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeDevicePolicyConfiguration", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_device_policy_configuration( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeDevicePolicyConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_domain(domain_name, fleet_arn) describe_domain(domain_name, fleet_arn, params::Dict{String,<:Any}) Provides information about the domain. # Arguments - `domain_name`: The name of the domain. - `fleet_arn`: The ARN of the fleet. """ function describe_domain( DomainName, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeDomain", Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_domain( DomainName, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeDomain", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_fleet_metadata(fleet_arn) describe_fleet_metadata(fleet_arn, params::Dict{String,<:Any}) Provides basic information for the specified fleet, excluding identity provider, networking, and device configuration details. # Arguments - `fleet_arn`: The Amazon Resource Name (ARN) of the fleet. """ function describe_fleet_metadata( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeFleetMetadata", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_fleet_metadata( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeFleetMetadata", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_identity_provider_configuration(fleet_arn) describe_identity_provider_configuration(fleet_arn, params::Dict{String,<:Any}) Describes the identity provider configuration of the specified fleet. # Arguments - `fleet_arn`: The ARN of the fleet. """ function describe_identity_provider_configuration( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeIdentityProviderConfiguration", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_identity_provider_configuration( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeIdentityProviderConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_website_certificate_authority(fleet_arn, website_ca_id) describe_website_certificate_authority(fleet_arn, website_ca_id, params::Dict{String,<:Any}) Provides information about the certificate authority. # Arguments - `fleet_arn`: The ARN of the fleet. - `website_ca_id`: A unique identifier for the certificate authority. """ function describe_website_certificate_authority( FleetArn, WebsiteCaId; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/describeWebsiteCertificateAuthority", Dict{String,Any}("FleetArn" => FleetArn, "WebsiteCaId" => WebsiteCaId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_website_certificate_authority( FleetArn, WebsiteCaId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/describeWebsiteCertificateAuthority", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("FleetArn" => FleetArn, "WebsiteCaId" => WebsiteCaId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_domain(domain_name, fleet_arn) disassociate_domain(domain_name, fleet_arn, params::Dict{String,<:Any}) Disassociates a domain from Amazon WorkLink. End users lose the ability to access the domain with Amazon WorkLink. # Arguments - `domain_name`: The name of the domain. - `fleet_arn`: The ARN of the fleet. """ function disassociate_domain( DomainName, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/disassociateDomain", Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_domain( DomainName, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/disassociateDomain", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_website_authorization_provider(authorization_provider_id, fleet_arn) disassociate_website_authorization_provider(authorization_provider_id, fleet_arn, params::Dict{String,<:Any}) Disassociates a website authorization provider from a specified fleet. After the disassociation, users can't load any associated websites that require this authorization provider. # Arguments - `authorization_provider_id`: A unique identifier for the authorization provider. - `fleet_arn`: The ARN of the fleet. """ function disassociate_website_authorization_provider( AuthorizationProviderId, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/disassociateWebsiteAuthorizationProvider", Dict{String,Any}( "AuthorizationProviderId" => AuthorizationProviderId, "FleetArn" => FleetArn ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_website_authorization_provider( AuthorizationProviderId, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/disassociateWebsiteAuthorizationProvider", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AuthorizationProviderId" => AuthorizationProviderId, "FleetArn" => FleetArn, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_website_certificate_authority(fleet_arn, website_ca_id) disassociate_website_certificate_authority(fleet_arn, website_ca_id, params::Dict{String,<:Any}) Removes a certificate authority (CA). # Arguments - `fleet_arn`: The ARN of the fleet. - `website_ca_id`: A unique identifier for the CA. """ function disassociate_website_certificate_authority( FleetArn, WebsiteCaId; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/disassociateWebsiteCertificateAuthority", Dict{String,Any}("FleetArn" => FleetArn, "WebsiteCaId" => WebsiteCaId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_website_certificate_authority( FleetArn, WebsiteCaId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/disassociateWebsiteCertificateAuthority", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("FleetArn" => FleetArn, "WebsiteCaId" => WebsiteCaId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_devices(fleet_arn) list_devices(fleet_arn, params::Dict{String,<:Any}) Retrieves a list of devices registered with the specified fleet. # Arguments - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to be included in the next page. - `"NextToken"`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page. """ function list_devices(FleetArn; aws_config::AbstractAWSConfig=global_aws_config()) return worklink( "POST", "/listDevices", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_devices( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/listDevices", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_domains(fleet_arn) list_domains(fleet_arn, params::Dict{String,<:Any}) Retrieves a list of domains associated to a specified fleet. # Arguments - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to be included in the next page. - `"NextToken"`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page. """ function list_domains(FleetArn; aws_config::AbstractAWSConfig=global_aws_config()) return worklink( "POST", "/listDomains", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_domains( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/listDomains", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_fleets() list_fleets(params::Dict{String,<:Any}) Retrieves a list of fleets for the current account and Region. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to be included in the next page. - `"NextToken"`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page. """ function list_fleets(; aws_config::AbstractAWSConfig=global_aws_config()) return worklink( "POST", "/listFleets"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_fleets( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/listFleets", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_tags_for_resource(resource_arn) list_tags_for_resource(resource_arn, params::Dict{String,<:Any}) Retrieves a list of tags for the specified resource. # Arguments - `resource_arn`: The Amazon Resource Name (ARN) of the fleet. """ function list_tags_for_resource( ResourceArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "GET", "/tags/$(ResourceArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_tags_for_resource( ResourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "GET", "/tags/$(ResourceArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_website_authorization_providers(fleet_arn) list_website_authorization_providers(fleet_arn, params::Dict{String,<:Any}) Retrieves a list of website authorization providers associated with a specified fleet. # Arguments - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to be included in the next page. - `"NextToken"`: The pagination token to use to retrieve the next page of results for this operation. If this value is null, it retrieves the first page. """ function list_website_authorization_providers( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/listWebsiteAuthorizationProviders", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_website_authorization_providers( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/listWebsiteAuthorizationProviders", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_website_certificate_authorities(fleet_arn) list_website_certificate_authorities(fleet_arn, params::Dict{String,<:Any}) Retrieves a list of certificate authorities added for the current account and Region. # Arguments - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to be included in the next page. - `"NextToken"`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page. """ function list_website_certificate_authorities( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/listWebsiteCertificateAuthorities", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_website_certificate_authorities( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/listWebsiteCertificateAuthorities", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ restore_domain_access(domain_name, fleet_arn) restore_domain_access(domain_name, fleet_arn, params::Dict{String,<:Any}) Moves a domain to ACTIVE status if it was in the INACTIVE status. # Arguments - `domain_name`: The name of the domain. - `fleet_arn`: The ARN of the fleet. """ function restore_domain_access( DomainName, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/restoreDomainAccess", Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function restore_domain_access( DomainName, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/restoreDomainAccess", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ revoke_domain_access(domain_name, fleet_arn) revoke_domain_access(domain_name, fleet_arn, params::Dict{String,<:Any}) Moves a domain to INACTIVE status if it was in the ACTIVE status. # Arguments - `domain_name`: The name of the domain. - `fleet_arn`: The ARN of the fleet. """ function revoke_domain_access( DomainName, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/revokeDomainAccess", Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function revoke_domain_access( DomainName, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/revokeDomainAccess", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ sign_out_user(fleet_arn, username) sign_out_user(fleet_arn, username, params::Dict{String,<:Any}) Signs the user out from all of their devices. The user can sign in again if they have valid credentials. # Arguments - `fleet_arn`: The ARN of the fleet. - `username`: The name of the user. """ function sign_out_user( FleetArn, Username; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/signOutUser", Dict{String,Any}("FleetArn" => FleetArn, "Username" => Username); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function sign_out_user( FleetArn, Username, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/signOutUser", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("FleetArn" => FleetArn, "Username" => Username), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ tag_resource(resource_arn, tags) tag_resource(resource_arn, tags, params::Dict{String,<:Any}) Adds or overwrites one or more tags for the specified resource, such as a fleet. Each tag consists of a key and an optional value. If a resource already has a tag with the same key, this operation updates its value. # Arguments - `resource_arn`: The Amazon Resource Name (ARN) of the fleet. - `tags`: The tags to add to the resource. A tag is a key-value pair. """ function tag_resource(ResourceArn, Tags; aws_config::AbstractAWSConfig=global_aws_config()) return worklink( "POST", "/tags/$(ResourceArn)", Dict{String,Any}("Tags" => Tags); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function tag_resource( ResourceArn, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/tags/$(ResourceArn)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Tags" => Tags), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ untag_resource(resource_arn, tag_keys) untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any}) Removes one or more tags from the specified resource. # Arguments - `resource_arn`: The Amazon Resource Name (ARN) of the fleet. - `tag_keys`: The list of tag keys to remove from the resource. """ function untag_resource( ResourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "DELETE", "/tags/$(ResourceArn)", Dict{String,Any}("tagKeys" => tagKeys); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function untag_resource( ResourceArn, tagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "DELETE", "/tags/$(ResourceArn)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_audit_stream_configuration(fleet_arn) update_audit_stream_configuration(fleet_arn, params::Dict{String,<:Any}) Updates the audit stream configuration for the fleet. # Arguments - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"AuditStreamArn"`: The ARN of the Amazon Kinesis data stream that receives the audit events. """ function update_audit_stream_configuration( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/updateAuditStreamConfiguration", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_audit_stream_configuration( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/updateAuditStreamConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_company_network_configuration(fleet_arn, security_group_ids, subnet_ids, vpc_id) update_company_network_configuration(fleet_arn, security_group_ids, subnet_ids, vpc_id, params::Dict{String,<:Any}) Updates the company network configuration for the fleet. # Arguments - `fleet_arn`: The ARN of the fleet. - `security_group_ids`: The security groups associated with access to the provided subnets. - `subnet_ids`: The subnets used for X-ENI connections from Amazon WorkLink rendering containers. - `vpc_id`: The VPC with connectivity to associated websites. """ function update_company_network_configuration( FleetArn, SecurityGroupIds, SubnetIds, VpcId; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/updateCompanyNetworkConfiguration", Dict{String,Any}( "FleetArn" => FleetArn, "SecurityGroupIds" => SecurityGroupIds, "SubnetIds" => SubnetIds, "VpcId" => VpcId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_company_network_configuration( FleetArn, SecurityGroupIds, SubnetIds, VpcId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/updateCompanyNetworkConfiguration", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "FleetArn" => FleetArn, "SecurityGroupIds" => SecurityGroupIds, "SubnetIds" => SubnetIds, "VpcId" => VpcId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_device_policy_configuration(fleet_arn) update_device_policy_configuration(fleet_arn, params::Dict{String,<:Any}) Updates the device policy configuration for the fleet. # Arguments - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DeviceCaCertificate"`: The certificate chain, including intermediate certificates and the root certificate authority certificate used to issue device certificates. """ function update_device_policy_configuration( FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/updateDevicePolicyConfiguration", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_device_policy_configuration( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/updateDevicePolicyConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_domain_metadata(domain_name, fleet_arn) update_domain_metadata(domain_name, fleet_arn, params::Dict{String,<:Any}) Updates domain metadata, such as DisplayName. # Arguments - `domain_name`: The name of the domain. - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DisplayName"`: The name to display. """ function update_domain_metadata( DomainName, FleetArn; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/updateDomainMetadata", Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_domain_metadata( DomainName, FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/updateDomainMetadata", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DomainName" => DomainName, "FleetArn" => FleetArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_fleet_metadata(fleet_arn) update_fleet_metadata(fleet_arn, params::Dict{String,<:Any}) Updates fleet metadata, such as DisplayName. # Arguments - `fleet_arn`: The ARN of the fleet. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DisplayName"`: The fleet name to display. The existing DisplayName is unset if null is passed. - `"OptimizeForEndUserLocation"`: The option to optimize for better performance by routing traffic through the closest AWS Region to users, which may be outside of your home Region. """ function update_fleet_metadata(FleetArn; aws_config::AbstractAWSConfig=global_aws_config()) return worklink( "POST", "/UpdateFleetMetadata", Dict{String,Any}("FleetArn" => FleetArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_fleet_metadata( FleetArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/UpdateFleetMetadata", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("FleetArn" => FleetArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_identity_provider_configuration(fleet_arn, identity_provider_type) update_identity_provider_configuration(fleet_arn, identity_provider_type, params::Dict{String,<:Any}) Updates the identity provider configuration for the fleet. # Arguments - `fleet_arn`: The ARN of the fleet. - `identity_provider_type`: The type of identity provider. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"IdentityProviderSamlMetadata"`: The SAML metadata document provided by the customer’s identity provider. The existing IdentityProviderSamlMetadata is unset if null is passed. """ function update_identity_provider_configuration( FleetArn, IdentityProviderType; aws_config::AbstractAWSConfig=global_aws_config() ) return worklink( "POST", "/updateIdentityProviderConfiguration", Dict{String,Any}( "FleetArn" => FleetArn, "IdentityProviderType" => IdentityProviderType ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_identity_provider_configuration( FleetArn, IdentityProviderType, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return worklink( "POST", "/updateIdentityProviderConfiguration", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "FleetArn" => FleetArn, "IdentityProviderType" => IdentityProviderType ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
139573
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: workmail using AWS.Compat using AWS.UUIDs """ associate_delegate_to_resource(entity_id, organization_id, resource_id) associate_delegate_to_resource(entity_id, organization_id, resource_id, params::Dict{String,<:Any}) Adds a member (user or group) to the resource's set of delegates. # Arguments - `entity_id`: The member (user or group) to associate to the resource. The entity ID can accept UserId or GroupID, Username or Groupname, or email. Entity: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity: entity - `organization_id`: The organization under which the resource exists. - `resource_id`: The resource for which members (users or groups) are associated. The identifier can accept ResourceId, Resourcename, or email. The following identity formats are available: Resource ID: r-0123456789a0123456789b0123456789 Email address: [email protected] Resource name: resource """ function associate_delegate_to_resource( EntityId, OrganizationId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "AssociateDelegateToResource", Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId, "ResourceId" => ResourceId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_delegate_to_resource( EntityId, OrganizationId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "AssociateDelegateToResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId, "ResourceId" => ResourceId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_member_to_group(group_id, member_id, organization_id) associate_member_to_group(group_id, member_id, organization_id, params::Dict{String,<:Any}) Adds a member (user or group) to the group's set. # Arguments - `group_id`: The group to which the member (user or group) is associated. The identifier can accept GroupId, Groupname, or email. The following identity formats are available: Group ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Group name: group - `member_id`: The member (user or group) to associate to the group. The member ID can accept UserID or GroupId, Username or Groupname, or email. Member: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Member name: member - `organization_id`: The organization under which the group exists. """ function associate_member_to_group( GroupId, MemberId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "AssociateMemberToGroup", Dict{String,Any}( "GroupId" => GroupId, "MemberId" => MemberId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_member_to_group( GroupId, MemberId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "AssociateMemberToGroup", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "GroupId" => GroupId, "MemberId" => MemberId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ assume_impersonation_role(impersonation_role_id, organization_id) assume_impersonation_role(impersonation_role_id, organization_id, params::Dict{String,<:Any}) Assumes an impersonation role for the given WorkMail organization. This method returns an authentication token you can use to make impersonated calls. # Arguments - `impersonation_role_id`: The impersonation role ID to assume. - `organization_id`: The WorkMail organization under which the impersonation role will be assumed. """ function assume_impersonation_role( ImpersonationRoleId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "AssumeImpersonationRole", Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function assume_impersonation_role( ImpersonationRoleId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "AssumeImpersonationRole", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ cancel_mailbox_export_job(client_token, job_id, organization_id) cancel_mailbox_export_job(client_token, job_id, organization_id, params::Dict{String,<:Any}) Cancels a mailbox export job. If the mailbox export job is near completion, it might not be possible to cancel it. # Arguments - `client_token`: The idempotency token for the client request. - `job_id`: The job ID. - `organization_id`: The organization ID. """ function cancel_mailbox_export_job( ClientToken, JobId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CancelMailboxExportJob", Dict{String,Any}( "ClientToken" => ClientToken, "JobId" => JobId, "OrganizationId" => OrganizationId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function cancel_mailbox_export_job( ClientToken, JobId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CancelMailboxExportJob", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ClientToken" => ClientToken, "JobId" => JobId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_alias(alias, entity_id, organization_id) create_alias(alias, entity_id, organization_id, params::Dict{String,<:Any}) Adds an alias to the set of a given member (user or group) of WorkMail. # Arguments - `alias`: The alias to add to the member set. - `entity_id`: The member (user or group) to which this alias is added. - `organization_id`: The organization under which the member (user or group) exists. """ function create_alias( Alias, EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateAlias", Dict{String,Any}( "Alias" => Alias, "EntityId" => EntityId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_alias( Alias, EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CreateAlias", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Alias" => Alias, "EntityId" => EntityId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_availability_configuration(domain_name, organization_id) create_availability_configuration(domain_name, organization_id, params::Dict{String,<:Any}) Creates an AvailabilityConfiguration for the given WorkMail organization and domain. # Arguments - `domain_name`: The domain to which the provider applies. - `organization_id`: The WorkMail organization for which the AvailabilityConfiguration will be created. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: An idempotent token that ensures that an API request is executed only once. - `"EwsProvider"`: Exchange Web Services (EWS) availability provider definition. The request must contain exactly one provider definition, either EwsProvider or LambdaProvider. - `"LambdaProvider"`: Lambda availability provider definition. The request must contain exactly one provider definition, either EwsProvider or LambdaProvider. """ function create_availability_configuration( DomainName, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateAvailabilityConfiguration", Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_availability_configuration( DomainName, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CreateAvailabilityConfiguration", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_group(name, organization_id) create_group(name, organization_id, params::Dict{String,<:Any}) Creates a group that can be used in WorkMail by calling the RegisterToWorkMail operation. # Arguments - `name`: The name of the group. - `organization_id`: The organization under which the group is to be created. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"HiddenFromGlobalAddressList"`: If this parameter is enabled, the group will be hidden from the address book. """ function create_group( Name, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateGroup", Dict{String,Any}("Name" => Name, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_group( Name, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CreateGroup", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Name" => Name, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_impersonation_role(name, organization_id, rules, type) create_impersonation_role(name, organization_id, rules, type, params::Dict{String,<:Any}) Creates an impersonation role for the given WorkMail organization. Idempotency ensures that an API request completes no more than one time. With an idempotent request, if the original request completes successfully, any subsequent retries also complete successfully without performing any further actions. # Arguments - `name`: The name of the new impersonation role. - `organization_id`: The WorkMail organization to create the new impersonation role within. - `rules`: The list of rules for the impersonation role. - `type`: The impersonation role's type. The available impersonation role types are READ_ONLY or FULL_ACCESS. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: The idempotency token for the client request. - `"Description"`: The description of the new impersonation role. """ function create_impersonation_role( Name, OrganizationId, Rules, Type; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateImpersonationRole", Dict{String,Any}( "Name" => Name, "OrganizationId" => OrganizationId, "Rules" => Rules, "Type" => Type, "ClientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_impersonation_role( Name, OrganizationId, Rules, Type, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CreateImpersonationRole", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Name" => Name, "OrganizationId" => OrganizationId, "Rules" => Rules, "Type" => Type, "ClientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_mobile_device_access_rule(effect, name, organization_id) create_mobile_device_access_rule(effect, name, organization_id, params::Dict{String,<:Any}) Creates a new mobile device access rule for the specified WorkMail organization. # Arguments - `effect`: The effect of the rule when it matches. Allowed values are ALLOW or DENY. - `name`: The rule name. - `organization_id`: The WorkMail organization under which the rule will be created. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: The idempotency token for the client request. - `"Description"`: The rule description. - `"DeviceModels"`: Device models that the rule will match. - `"DeviceOperatingSystems"`: Device operating systems that the rule will match. - `"DeviceTypes"`: Device types that the rule will match. - `"DeviceUserAgents"`: Device user agents that the rule will match. - `"NotDeviceModels"`: Device models that the rule will not match. All other device models will match. - `"NotDeviceOperatingSystems"`: Device operating systems that the rule will not match. All other device operating systems will match. - `"NotDeviceTypes"`: Device types that the rule will not match. All other device types will match. - `"NotDeviceUserAgents"`: Device user agents that the rule will not match. All other device user agents will match. """ function create_mobile_device_access_rule( Effect, Name, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateMobileDeviceAccessRule", Dict{String,Any}( "Effect" => Effect, "Name" => Name, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_mobile_device_access_rule( Effect, Name, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CreateMobileDeviceAccessRule", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Effect" => Effect, "Name" => Name, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_organization(alias) create_organization(alias, params::Dict{String,<:Any}) Creates a new WorkMail organization. Optionally, you can choose to associate an existing AWS Directory Service directory with your organization. If an AWS Directory Service directory ID is specified, the organization alias must match the directory alias. If you choose not to associate an existing directory with your organization, then we create a new WorkMail directory for you. For more information, see Adding an organization in the WorkMail Administrator Guide. You can associate multiple email domains with an organization, then choose your default email domain from the WorkMail console. You can also associate a domain that is managed in an Amazon Route 53 public hosted zone. For more information, see Adding a domain and Choosing the default domain in the WorkMail Administrator Guide. Optionally, you can use a customer managed key from AWS Key Management Service (AWS KMS) to encrypt email for your organization. If you don't associate an AWS KMS key, WorkMail creates a default, AWS managed key for you. # Arguments - `alias`: The organization alias. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: The idempotency token associated with the request. - `"DirectoryId"`: The AWS Directory Service directory ID. - `"Domains"`: The email domains to associate with the organization. - `"EnableInteroperability"`: When true, allows organization interoperability between WorkMail and Microsoft Exchange. If true, you must include a AD Connector directory ID in the request. - `"KmsKeyArn"`: The Amazon Resource Name (ARN) of a customer managed key from AWS KMS. """ function create_organization(Alias; aws_config::AbstractAWSConfig=global_aws_config()) return workmail( "CreateOrganization", Dict{String,Any}("Alias" => Alias, "ClientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_organization( Alias, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateOrganization", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Alias" => Alias, "ClientToken" => string(uuid4())), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_resource(name, organization_id, type) create_resource(name, organization_id, type, params::Dict{String,<:Any}) Creates a new WorkMail resource. # Arguments - `name`: The name of the new resource. - `organization_id`: The identifier associated with the organization for which the resource is created. - `type`: The type of the new resource. The available types are equipment and room. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Description"`: Resource description. - `"HiddenFromGlobalAddressList"`: If this parameter is enabled, the resource will be hidden from the address book. """ function create_resource( Name, OrganizationId, Type; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateResource", Dict{String,Any}( "Name" => Name, "OrganizationId" => OrganizationId, "Type" => Type ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_resource( Name, OrganizationId, Type, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CreateResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Name" => Name, "OrganizationId" => OrganizationId, "Type" => Type ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_user(display_name, name, organization_id) create_user(display_name, name, organization_id, params::Dict{String,<:Any}) Creates a user who can be used in WorkMail by calling the RegisterToWorkMail operation. # Arguments - `display_name`: The display name for the new user. - `name`: The name for the new user. WorkMail directory user names have a maximum length of 64. All others have a maximum length of 20. - `organization_id`: The identifier of the organization for which the user is created. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"FirstName"`: The first name of the new user. - `"HiddenFromGlobalAddressList"`: If this parameter is enabled, the user will be hidden from the address book. - `"LastName"`: The last name of the new user. - `"Password"`: The password for the new user. - `"Role"`: The role of the new user. You cannot pass SYSTEM_USER or RESOURCE role in a single request. When a user role is not selected, the default role of USER is selected. """ function create_user( DisplayName, Name, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "CreateUser", Dict{String,Any}( "DisplayName" => DisplayName, "Name" => Name, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_user( DisplayName, Name, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "CreateUser", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DisplayName" => DisplayName, "Name" => Name, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_access_control_rule(name, organization_id) delete_access_control_rule(name, organization_id, params::Dict{String,<:Any}) Deletes an access control rule for the specified WorkMail organization. Deleting already deleted and non-existing rules does not produce an error. In those cases, the service sends back an HTTP 200 response with an empty HTTP body. # Arguments - `name`: The name of the access control rule. - `organization_id`: The identifier for the organization. """ function delete_access_control_rule( Name, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteAccessControlRule", Dict{String,Any}("Name" => Name, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_access_control_rule( Name, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteAccessControlRule", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Name" => Name, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_alias(alias, entity_id, organization_id) delete_alias(alias, entity_id, organization_id, params::Dict{String,<:Any}) Remove one or more specified aliases from a set of aliases for a given user. # Arguments - `alias`: The aliases to be removed from the user's set of aliases. Duplicate entries in the list are collapsed into single entries (the list is transformed into a set). - `entity_id`: The identifier for the member (user or group) from which to have the aliases removed. - `organization_id`: The identifier for the organization under which the user exists. """ function delete_alias( Alias, EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteAlias", Dict{String,Any}( "Alias" => Alias, "EntityId" => EntityId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_alias( Alias, EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteAlias", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Alias" => Alias, "EntityId" => EntityId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_availability_configuration(domain_name, organization_id) delete_availability_configuration(domain_name, organization_id, params::Dict{String,<:Any}) Deletes the AvailabilityConfiguration for the given WorkMail organization and domain. # Arguments - `domain_name`: The domain for which the AvailabilityConfiguration will be deleted. - `organization_id`: The WorkMail organization for which the AvailabilityConfiguration will be deleted. """ function delete_availability_configuration( DomainName, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteAvailabilityConfiguration", Dict{String,Any}("DomainName" => DomainName, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_availability_configuration( DomainName, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteAvailabilityConfiguration", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_email_monitoring_configuration(organization_id) delete_email_monitoring_configuration(organization_id, params::Dict{String,<:Any}) Deletes the email monitoring configuration for a specified organization. # Arguments - `organization_id`: The ID of the organization from which the email monitoring configuration is deleted. """ function delete_email_monitoring_configuration( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteEmailMonitoringConfiguration", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_email_monitoring_configuration( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteEmailMonitoringConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_group(group_id, organization_id) delete_group(group_id, organization_id, params::Dict{String,<:Any}) Deletes a group from WorkMail. # Arguments - `group_id`: The identifier of the group to be deleted. The identifier can be the GroupId, or Groupname. The following identity formats are available: Group ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Group name: group - `organization_id`: The organization that contains the group. """ function delete_group( GroupId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteGroup", Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_group( GroupId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteGroup", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_impersonation_role(impersonation_role_id, organization_id) delete_impersonation_role(impersonation_role_id, organization_id, params::Dict{String,<:Any}) Deletes an impersonation role for the given WorkMail organization. # Arguments - `impersonation_role_id`: The ID of the impersonation role to delete. - `organization_id`: The WorkMail organization from which to delete the impersonation role. """ function delete_impersonation_role( ImpersonationRoleId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteImpersonationRole", Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_impersonation_role( ImpersonationRoleId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteImpersonationRole", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_mailbox_permissions(entity_id, grantee_id, organization_id) delete_mailbox_permissions(entity_id, grantee_id, organization_id, params::Dict{String,<:Any}) Deletes permissions granted to a member (user or group). # Arguments - `entity_id`: The identifier of the entity that owns the mailbox. The identifier can be UserId or Group Id, Username or Groupname, or email. Entity ID: 12345678-1234-1234-1234-123456789012, r-0123456789a0123456789b0123456789, or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity name: entity - `grantee_id`: The identifier of the entity for which to delete granted permissions. The identifier can be UserId, ResourceID, or Group Id, Username or Groupname, or email. Grantee ID: 12345678-1234-1234-1234-123456789012,r-0123456789a0123456789b0123456789, or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Grantee name: grantee - `organization_id`: The identifier of the organization under which the member (user or group) exists. """ function delete_mailbox_permissions( EntityId, GranteeId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteMailboxPermissions", Dict{String,Any}( "EntityId" => EntityId, "GranteeId" => GranteeId, "OrganizationId" => OrganizationId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_mailbox_permissions( EntityId, GranteeId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteMailboxPermissions", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "GranteeId" => GranteeId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_mobile_device_access_override(device_id, organization_id, user_id) delete_mobile_device_access_override(device_id, organization_id, user_id, params::Dict{String,<:Any}) Deletes the mobile device access override for the given WorkMail organization, user, and device. Deleting already deleted and non-existing overrides does not produce an error. In those cases, the service sends back an HTTP 200 response with an empty HTTP body. # Arguments - `device_id`: The mobile device for which you delete the override. DeviceId is case insensitive. - `organization_id`: The WorkMail organization for which the access override will be deleted. - `user_id`: The WorkMail user for which you want to delete the override. Accepts the following types of user identities: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user """ function delete_mobile_device_access_override( DeviceId, OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteMobileDeviceAccessOverride", Dict{String,Any}( "DeviceId" => DeviceId, "OrganizationId" => OrganizationId, "UserId" => UserId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_mobile_device_access_override( DeviceId, OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteMobileDeviceAccessOverride", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DeviceId" => DeviceId, "OrganizationId" => OrganizationId, "UserId" => UserId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_mobile_device_access_rule(mobile_device_access_rule_id, organization_id) delete_mobile_device_access_rule(mobile_device_access_rule_id, organization_id, params::Dict{String,<:Any}) Deletes a mobile device access rule for the specified WorkMail organization. Deleting already deleted and non-existing rules does not produce an error. In those cases, the service sends back an HTTP 200 response with an empty HTTP body. # Arguments - `mobile_device_access_rule_id`: The identifier of the rule to be deleted. - `organization_id`: The WorkMail organization under which the rule will be deleted. """ function delete_mobile_device_access_rule( MobileDeviceAccessRuleId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteMobileDeviceAccessRule", Dict{String,Any}( "MobileDeviceAccessRuleId" => MobileDeviceAccessRuleId, "OrganizationId" => OrganizationId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_mobile_device_access_rule( MobileDeviceAccessRuleId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteMobileDeviceAccessRule", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "MobileDeviceAccessRuleId" => MobileDeviceAccessRuleId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_organization(delete_directory, organization_id) delete_organization(delete_directory, organization_id, params::Dict{String,<:Any}) Deletes an WorkMail organization and all underlying AWS resources managed by WorkMail as part of the organization. You can choose whether to delete the associated directory. For more information, see Removing an organization in the WorkMail Administrator Guide. # Arguments - `delete_directory`: If true, deletes the AWS Directory Service directory associated with the organization. - `organization_id`: The organization ID. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: The idempotency token associated with the request. - `"ForceDelete"`: Deletes a WorkMail organization even if the organization has enabled users. """ function delete_organization( DeleteDirectory, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteOrganization", Dict{String,Any}( "DeleteDirectory" => DeleteDirectory, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_organization( DeleteDirectory, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteOrganization", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DeleteDirectory" => DeleteDirectory, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_resource(organization_id, resource_id) delete_resource(organization_id, resource_id, params::Dict{String,<:Any}) Deletes the specified resource. # Arguments - `organization_id`: The identifier associated with the organization from which the resource is deleted. - `resource_id`: The identifier of the resource to be deleted. The identifier can accept ResourceId, or Resourcename. The following identity formats are available: Resource ID: r-0123456789a0123456789b0123456789 Resource name: resource """ function delete_resource( OrganizationId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteResource", Dict{String,Any}("OrganizationId" => OrganizationId, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_resource( OrganizationId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "OrganizationId" => OrganizationId, "ResourceId" => ResourceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_retention_policy(id, organization_id) delete_retention_policy(id, organization_id, params::Dict{String,<:Any}) Deletes the specified retention policy from the specified organization. # Arguments - `id`: The retention policy ID. - `organization_id`: The organization ID. """ function delete_retention_policy( Id, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteRetentionPolicy", Dict{String,Any}("Id" => Id, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_retention_policy( Id, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteRetentionPolicy", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Id" => Id, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_user(organization_id, user_id) delete_user(organization_id, user_id, params::Dict{String,<:Any}) Deletes a user from WorkMail and all subsequent systems. Before you can delete a user, the user state must be DISABLED. Use the DescribeUser action to confirm the user state. Deleting a user is permanent and cannot be undone. WorkMail archives user mailboxes for 30 days before they are permanently removed. # Arguments - `organization_id`: The organization that contains the user to be deleted. - `user_id`: The identifier of the user to be deleted. The identifier can be the UserId or Username. The following identity formats are available: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 User name: user """ function delete_user( OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeleteUser", Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_user( OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeleteUser", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ deregister_from_work_mail(entity_id, organization_id) deregister_from_work_mail(entity_id, organization_id, params::Dict{String,<:Any}) Mark a user, group, or resource as no longer used in WorkMail. This action disassociates the mailbox and schedules it for clean-up. WorkMail keeps mailboxes for 30 days before they are permanently removed. The functionality in the console is Disable. # Arguments - `entity_id`: The identifier for the member to be updated. The identifier can be UserId, ResourceId, or Group Id, Username, Resourcename, or Groupname, or email. Entity ID: 12345678-1234-1234-1234-123456789012, r-0123456789a0123456789b0123456789, or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity name: entity - `organization_id`: The identifier for the organization under which the WorkMail entity exists. """ function deregister_from_work_mail( EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeregisterFromWorkMail", Dict{String,Any}("EntityId" => EntityId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function deregister_from_work_mail( EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeregisterFromWorkMail", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ deregister_mail_domain(domain_name, organization_id) deregister_mail_domain(domain_name, organization_id, params::Dict{String,<:Any}) Removes a domain from WorkMail, stops email routing to WorkMail, and removes the authorization allowing WorkMail use. SES keeps the domain because other applications may use it. You must first remove any email address used by WorkMail entities before you remove the domain. # Arguments - `domain_name`: The domain to deregister in WorkMail and SES. - `organization_id`: The WorkMail organization for which the domain will be deregistered. """ function deregister_mail_domain( DomainName, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DeregisterMailDomain", Dict{String,Any}("DomainName" => DomainName, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function deregister_mail_domain( DomainName, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DeregisterMailDomain", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_email_monitoring_configuration(organization_id) describe_email_monitoring_configuration(organization_id, params::Dict{String,<:Any}) Describes the current email monitoring configuration for a specified organization. # Arguments - `organization_id`: The ID of the organization for which the email monitoring configuration is described. """ function describe_email_monitoring_configuration( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeEmailMonitoringConfiguration", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_email_monitoring_configuration( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeEmailMonitoringConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_entity(email, organization_id) describe_entity(email, organization_id, params::Dict{String,<:Any}) Returns basic details about an entity in WorkMail. # Arguments - `email`: The email under which the entity exists. - `organization_id`: The identifier for the organization under which the entity exists. """ function describe_entity( Email, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeEntity", Dict{String,Any}("Email" => Email, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_entity( Email, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeEntity", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Email" => Email, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_group(group_id, organization_id) describe_group(group_id, organization_id, params::Dict{String,<:Any}) Returns the data available for the group. # Arguments - `group_id`: The identifier for the group to be described. The identifier can accept GroupId, Groupname, or email. The following identity formats are available: Group ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Group name: group - `organization_id`: The identifier for the organization under which the group exists. """ function describe_group( GroupId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeGroup", Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_group( GroupId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeGroup", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_inbound_dmarc_settings(organization_id) describe_inbound_dmarc_settings(organization_id, params::Dict{String,<:Any}) Lists the settings in a DMARC policy for a specified organization. # Arguments - `organization_id`: Lists the ID of the given organization. """ function describe_inbound_dmarc_settings( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeInboundDmarcSettings", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_inbound_dmarc_settings( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeInboundDmarcSettings", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_mailbox_export_job(job_id, organization_id) describe_mailbox_export_job(job_id, organization_id, params::Dict{String,<:Any}) Describes the current status of a mailbox export job. # Arguments - `job_id`: The mailbox export job ID. - `organization_id`: The organization ID. """ function describe_mailbox_export_job( JobId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeMailboxExportJob", Dict{String,Any}("JobId" => JobId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_mailbox_export_job( JobId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeMailboxExportJob", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("JobId" => JobId, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_organization(organization_id) describe_organization(organization_id, params::Dict{String,<:Any}) Provides more information regarding a given organization based on its identifier. # Arguments - `organization_id`: The identifier for the organization to be described. """ function describe_organization( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeOrganization", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_organization( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeOrganization", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_resource(organization_id, resource_id) describe_resource(organization_id, resource_id, params::Dict{String,<:Any}) Returns the data available for the resource. # Arguments - `organization_id`: The identifier associated with the organization for which the resource is described. - `resource_id`: The identifier of the resource to be described. The identifier can accept ResourceId, Resourcename, or email. The following identity formats are available: Resource ID: r-0123456789a0123456789b0123456789 Email address: [email protected] Resource name: resource """ function describe_resource( OrganizationId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeResource", Dict{String,Any}("OrganizationId" => OrganizationId, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_resource( OrganizationId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "OrganizationId" => OrganizationId, "ResourceId" => ResourceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_user(organization_id, user_id) describe_user(organization_id, user_id, params::Dict{String,<:Any}) Provides information regarding the user. # Arguments - `organization_id`: The identifier for the organization under which the user exists. - `user_id`: The identifier for the user to be described. The identifier can be the UserId, Username, or email. The following identity formats are available: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user """ function describe_user( OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DescribeUser", Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_user( OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DescribeUser", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_delegate_from_resource(entity_id, organization_id, resource_id) disassociate_delegate_from_resource(entity_id, organization_id, resource_id, params::Dict{String,<:Any}) Removes a member from the resource's set of delegates. # Arguments - `entity_id`: The identifier for the member (user, group) to be removed from the resource's delegates. The entity ID can accept UserId or GroupID, Username or Groupname, or email. Entity: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity: entity - `organization_id`: The identifier for the organization under which the resource exists. - `resource_id`: The identifier of the resource from which delegates' set members are removed. The identifier can accept ResourceId, Resourcename, or email. The following identity formats are available: Resource ID: r-0123456789a0123456789b0123456789 Email address: [email protected] Resource name: resource """ function disassociate_delegate_from_resource( EntityId, OrganizationId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DisassociateDelegateFromResource", Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId, "ResourceId" => ResourceId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_delegate_from_resource( EntityId, OrganizationId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DisassociateDelegateFromResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId, "ResourceId" => ResourceId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_member_from_group(group_id, member_id, organization_id) disassociate_member_from_group(group_id, member_id, organization_id, params::Dict{String,<:Any}) Removes a member from a group. # Arguments - `group_id`: The identifier for the group from which members are removed. The identifier can accept GroupId, Groupname, or email. The following identity formats are available: Group ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Group name: group - `member_id`: The identifier for the member to be removed from the group. The member ID can accept UserID or GroupId, Username or Groupname, or email. Member ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Member name: member - `organization_id`: The identifier for the organization under which the group exists. """ function disassociate_member_from_group( GroupId, MemberId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "DisassociateMemberFromGroup", Dict{String,Any}( "GroupId" => GroupId, "MemberId" => MemberId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_member_from_group( GroupId, MemberId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "DisassociateMemberFromGroup", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "GroupId" => GroupId, "MemberId" => MemberId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_access_control_effect(action, ip_address, organization_id) get_access_control_effect(action, ip_address, organization_id, params::Dict{String,<:Any}) Gets the effects of an organization's access control rules as they apply to a specified IPv4 address, access protocol action, and user ID or impersonation role ID. You must provide either the user ID or impersonation role ID. Impersonation role ID can only be used with Action EWS. # Arguments - `action`: The access protocol action. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail. - `ip_address`: The IPv4 address. - `organization_id`: The identifier for the organization. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ImpersonationRoleId"`: The impersonation role ID. - `"UserId"`: The user ID. """ function get_access_control_effect( Action, IpAddress, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "GetAccessControlEffect", Dict{String,Any}( "Action" => Action, "IpAddress" => IpAddress, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_access_control_effect( Action, IpAddress, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetAccessControlEffect", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Action" => Action, "IpAddress" => IpAddress, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_default_retention_policy(organization_id) get_default_retention_policy(organization_id, params::Dict{String,<:Any}) Gets the default retention policy details for the specified organization. # Arguments - `organization_id`: The organization ID. """ function get_default_retention_policy( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "GetDefaultRetentionPolicy", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_default_retention_policy( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetDefaultRetentionPolicy", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_impersonation_role(impersonation_role_id, organization_id) get_impersonation_role(impersonation_role_id, organization_id, params::Dict{String,<:Any}) Gets the impersonation role details for the given WorkMail organization. # Arguments - `impersonation_role_id`: The impersonation role ID to retrieve. - `organization_id`: The WorkMail organization from which to retrieve the impersonation role. """ function get_impersonation_role( ImpersonationRoleId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "GetImpersonationRole", Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_impersonation_role( ImpersonationRoleId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetImpersonationRole", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_impersonation_role_effect(impersonation_role_id, organization_id, target_user) get_impersonation_role_effect(impersonation_role_id, organization_id, target_user, params::Dict{String,<:Any}) Tests whether the given impersonation role can impersonate a target user. # Arguments - `impersonation_role_id`: The impersonation role ID to test. - `organization_id`: The WorkMail organization where the impersonation role is defined. - `target_user`: The WorkMail organization user chosen to test the impersonation role. The following identity formats are available: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user """ function get_impersonation_role_effect( ImpersonationRoleId, OrganizationId, TargetUser; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetImpersonationRoleEffect", Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId, "TargetUser" => TargetUser, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_impersonation_role_effect( ImpersonationRoleId, OrganizationId, TargetUser, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetImpersonationRoleEffect", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "OrganizationId" => OrganizationId, "TargetUser" => TargetUser, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_mail_domain(domain_name, organization_id) get_mail_domain(domain_name, organization_id, params::Dict{String,<:Any}) Gets details for a mail domain, including domain records required to configure your domain with recommended security. # Arguments - `domain_name`: The domain from which you want to retrieve details. - `organization_id`: The WorkMail organization for which the domain is retrieved. """ function get_mail_domain( DomainName, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "GetMailDomain", Dict{String,Any}("DomainName" => DomainName, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_mail_domain( DomainName, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetMailDomain", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_mailbox_details(organization_id, user_id) get_mailbox_details(organization_id, user_id, params::Dict{String,<:Any}) Requests a user's mailbox details for a specified organization and user. # Arguments - `organization_id`: The identifier for the organization that contains the user whose mailbox details are being requested. - `user_id`: The identifier for the user whose mailbox details are being requested. The identifier can be the UserId, Username, or email. The following identity formats are available: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user """ function get_mailbox_details( OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "GetMailboxDetails", Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_mailbox_details( OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetMailboxDetails", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_mobile_device_access_effect(organization_id) get_mobile_device_access_effect(organization_id, params::Dict{String,<:Any}) Simulates the effect of the mobile device access rules for the given attributes of a sample access event. Use this method to test the effects of the current set of mobile device access rules for the WorkMail organization for a particular user's attributes. # Arguments - `organization_id`: The WorkMail organization to simulate the access effect for. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DeviceModel"`: Device model the simulated user will report. - `"DeviceOperatingSystem"`: Device operating system the simulated user will report. - `"DeviceType"`: Device type the simulated user will report. - `"DeviceUserAgent"`: Device user agent the simulated user will report. """ function get_mobile_device_access_effect( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "GetMobileDeviceAccessEffect", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_mobile_device_access_effect( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetMobileDeviceAccessEffect", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_mobile_device_access_override(device_id, organization_id, user_id) get_mobile_device_access_override(device_id, organization_id, user_id, params::Dict{String,<:Any}) Gets the mobile device access override for the given WorkMail organization, user, and device. # Arguments - `device_id`: The mobile device to which the override applies. DeviceId is case insensitive. - `organization_id`: The WorkMail organization to which you want to apply the override. - `user_id`: Identifies the WorkMail user for the override. Accepts the following types of user identities: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user """ function get_mobile_device_access_override( DeviceId, OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "GetMobileDeviceAccessOverride", Dict{String,Any}( "DeviceId" => DeviceId, "OrganizationId" => OrganizationId, "UserId" => UserId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_mobile_device_access_override( DeviceId, OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "GetMobileDeviceAccessOverride", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DeviceId" => DeviceId, "OrganizationId" => OrganizationId, "UserId" => UserId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_access_control_rules(organization_id) list_access_control_rules(organization_id, params::Dict{String,<:Any}) Lists the access control rules for the specified organization. # Arguments - `organization_id`: The identifier for the organization. """ function list_access_control_rules( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListAccessControlRules", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_access_control_rules( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListAccessControlRules", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_aliases(entity_id, organization_id) list_aliases(entity_id, organization_id, params::Dict{String,<:Any}) Creates a paginated call to list the aliases associated with a given entity. # Arguments - `entity_id`: The identifier for the entity for which to list the aliases. - `organization_id`: The identifier for the organization under which the entity exists. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_aliases( EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListAliases", Dict{String,Any}("EntityId" => EntityId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_aliases( EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListAliases", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_availability_configurations(organization_id) list_availability_configurations(organization_id, params::Dict{String,<:Any}) List all the AvailabilityConfiguration's for the given WorkMail organization. # Arguments - `organization_id`: The WorkMail organization for which the AvailabilityConfiguration's will be listed. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not require a token. """ function list_availability_configurations( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListAvailabilityConfigurations", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_availability_configurations( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListAvailabilityConfigurations", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_group_members(group_id, organization_id) list_group_members(group_id, organization_id, params::Dict{String,<:Any}) Returns an overview of the members of a group. Users and groups can be members of a group. # Arguments - `group_id`: The identifier for the group to which the members (users or groups) are associated. The identifier can accept GroupId, Groupname, or email. The following identity formats are available: Group ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Group name: group - `organization_id`: The identifier for the organization under which the group exists. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_group_members( GroupId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListGroupMembers", Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_group_members( GroupId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListGroupMembers", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_groups(organization_id) list_groups(organization_id, params::Dict{String,<:Any}) Returns summaries of the organization's groups. # Arguments - `organization_id`: The identifier for the organization under which the groups exist. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Filters"`: Limit the search results based on the filter criteria. Only one filter per request is supported. - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_groups(OrganizationId; aws_config::AbstractAWSConfig=global_aws_config()) return workmail( "ListGroups", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_groups( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListGroups", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_groups_for_entity(entity_id, organization_id) list_groups_for_entity(entity_id, organization_id, params::Dict{String,<:Any}) Returns all the groups to which an entity belongs. # Arguments - `entity_id`: The identifier for the entity. The entity ID can accept UserId or GroupID, Username or Groupname, or email. Entity ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity name: entity - `organization_id`: The identifier for the organization under which the entity exists. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Filters"`: Limit the search results based on the filter criteria. - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_groups_for_entity( EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListGroupsForEntity", Dict{String,Any}("EntityId" => EntityId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_groups_for_entity( EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListGroupsForEntity", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_impersonation_roles(organization_id) list_impersonation_roles(organization_id, params::Dict{String,<:Any}) Lists all the impersonation roles for the given WorkMail organization. # Arguments - `organization_id`: The WorkMail organization to which the listed impersonation roles belong. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results returned in a single call. - `"NextToken"`: The token used to retrieve the next page of results. The first call doesn't require a token. """ function list_impersonation_roles( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListImpersonationRoles", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_impersonation_roles( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListImpersonationRoles", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_mail_domains(organization_id) list_mail_domains(organization_id, params::Dict{String,<:Any}) Lists the mail domains in a given WorkMail organization. # Arguments - `organization_id`: The WorkMail organization for which to list domains. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not require a token. """ function list_mail_domains( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListMailDomains", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_mail_domains( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListMailDomains", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_mailbox_export_jobs(organization_id) list_mailbox_export_jobs(organization_id, params::Dict{String,<:Any}) Lists the mailbox export jobs started for the specified organization within the last seven days. # Arguments - `organization_id`: The organization ID. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. """ function list_mailbox_export_jobs( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListMailboxExportJobs", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_mailbox_export_jobs( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListMailboxExportJobs", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_mailbox_permissions(entity_id, organization_id) list_mailbox_permissions(entity_id, organization_id, params::Dict{String,<:Any}) Lists the mailbox permissions associated with a user, group, or resource mailbox. # Arguments - `entity_id`: The identifier of the user, or resource for which to list mailbox permissions. The entity ID can accept UserId or ResourceId, Username or Resourcename, or email. Entity ID: 12345678-1234-1234-1234-123456789012, or r-0123456789a0123456789b0123456789 Email address: [email protected] Entity name: entity - `organization_id`: The identifier of the organization under which the user, group, or resource exists. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_mailbox_permissions( EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListMailboxPermissions", Dict{String,Any}("EntityId" => EntityId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_mailbox_permissions( EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListMailboxPermissions", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_mobile_device_access_overrides(organization_id) list_mobile_device_access_overrides(organization_id, params::Dict{String,<:Any}) Lists all the mobile device access overrides for any given combination of WorkMail organization, user, or device. # Arguments - `organization_id`: The WorkMail organization under which to list mobile device access overrides. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DeviceId"`: The mobile device to which the access override applies. - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not require a token. - `"UserId"`: The WorkMail user under which you list the mobile device access overrides. Accepts the following types of user identities: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user """ function list_mobile_device_access_overrides( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListMobileDeviceAccessOverrides", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_mobile_device_access_overrides( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListMobileDeviceAccessOverrides", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_mobile_device_access_rules(organization_id) list_mobile_device_access_rules(organization_id, params::Dict{String,<:Any}) Lists the mobile device access rules for the specified WorkMail organization. # Arguments - `organization_id`: The WorkMail organization for which to list the rules. """ function list_mobile_device_access_rules( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListMobileDeviceAccessRules", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_mobile_device_access_rules( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListMobileDeviceAccessRules", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_organizations() list_organizations(params::Dict{String,<:Any}) Returns summaries of the customer's organizations. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_organizations(; aws_config::AbstractAWSConfig=global_aws_config()) return workmail( "ListOrganizations"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_organizations( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListOrganizations", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ list_resource_delegates(organization_id, resource_id) list_resource_delegates(organization_id, resource_id, params::Dict{String,<:Any}) Lists the delegates associated with a resource. Users and groups can be resource delegates and answer requests on behalf of the resource. # Arguments - `organization_id`: The identifier for the organization that contains the resource for which delegates are listed. - `resource_id`: The identifier for the resource whose delegates are listed. The identifier can accept ResourceId, Resourcename, or email. The following identity formats are available: Resource ID: r-0123456789a0123456789b0123456789 Email address: [email protected] Resource name: resource # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The number of maximum results in a page. - `"NextToken"`: The token used to paginate through the delegates associated with a resource. """ function list_resource_delegates( OrganizationId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListResourceDelegates", Dict{String,Any}("OrganizationId" => OrganizationId, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_resource_delegates( OrganizationId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListResourceDelegates", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "OrganizationId" => OrganizationId, "ResourceId" => ResourceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_resources(organization_id) list_resources(organization_id, params::Dict{String,<:Any}) Returns summaries of the organization's resources. # Arguments - `organization_id`: The identifier for the organization under which the resources exist. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Filters"`: Limit the resource search results based on the filter criteria. You can only use one filter per request. - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_resources(OrganizationId; aws_config::AbstractAWSConfig=global_aws_config()) return workmail( "ListResources", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_resources( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListResources", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_tags_for_resource(resource_arn) list_tags_for_resource(resource_arn, params::Dict{String,<:Any}) Lists the tags applied to an WorkMail organization resource. # Arguments - `resource_arn`: The resource ARN. """ function list_tags_for_resource( ResourceARN; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ListTagsForResource", Dict{String,Any}("ResourceARN" => ResourceARN); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_tags_for_resource( ResourceARN, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListTagsForResource", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceARN" => ResourceARN), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_users(organization_id) list_users(organization_id, params::Dict{String,<:Any}) Returns summaries of the organization's users. # Arguments - `organization_id`: The identifier for the organization under which the users exist. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Filters"`: Limit the user search results based on the filter criteria. You can only use one filter per request. - `"MaxResults"`: The maximum number of results to return in a single call. - `"NextToken"`: The token to use to retrieve the next page of results. The first call does not contain any tokens. """ function list_users(OrganizationId; aws_config::AbstractAWSConfig=global_aws_config()) return workmail( "ListUsers", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_users( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ListUsers", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_access_control_rule(description, effect, name, organization_id) put_access_control_rule(description, effect, name, organization_id, params::Dict{String,<:Any}) Adds a new access control rule for the specified organization. The rule allows or denies access to the organization for the specified IPv4 addresses, access protocol actions, user IDs and impersonation IDs. Adding a new rule with the same name as an existing rule replaces the older rule. # Arguments - `description`: The rule description. - `effect`: The rule effect. - `name`: The rule name. - `organization_id`: The identifier of the organization. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Actions"`: Access protocol actions to include in the rule. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail. - `"ImpersonationRoleIds"`: Impersonation role IDs to include in the rule. - `"IpRanges"`: IPv4 CIDR ranges to include in the rule. - `"NotActions"`: Access protocol actions to exclude from the rule. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail. - `"NotImpersonationRoleIds"`: Impersonation role IDs to exclude from the rule. - `"NotIpRanges"`: IPv4 CIDR ranges to exclude from the rule. - `"NotUserIds"`: User IDs to exclude from the rule. - `"UserIds"`: User IDs to include in the rule. """ function put_access_control_rule( Description, Effect, Name, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutAccessControlRule", Dict{String,Any}( "Description" => Description, "Effect" => Effect, "Name" => Name, "OrganizationId" => OrganizationId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_access_control_rule( Description, Effect, Name, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutAccessControlRule", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Description" => Description, "Effect" => Effect, "Name" => Name, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_email_monitoring_configuration(log_group_arn, organization_id, role_arn) put_email_monitoring_configuration(log_group_arn, organization_id, role_arn, params::Dict{String,<:Any}) Creates or updates the email monitoring configuration for a specified organization. # Arguments - `log_group_arn`: The Amazon Resource Name (ARN) of the CloudWatch Log group associated with the email monitoring configuration. - `organization_id`: The ID of the organization for which the email monitoring configuration is set. - `role_arn`: The Amazon Resource Name (ARN) of the IAM Role associated with the email monitoring configuration. """ function put_email_monitoring_configuration( LogGroupArn, OrganizationId, RoleArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "PutEmailMonitoringConfiguration", Dict{String,Any}( "LogGroupArn" => LogGroupArn, "OrganizationId" => OrganizationId, "RoleArn" => RoleArn, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_email_monitoring_configuration( LogGroupArn, OrganizationId, RoleArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutEmailMonitoringConfiguration", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "LogGroupArn" => LogGroupArn, "OrganizationId" => OrganizationId, "RoleArn" => RoleArn, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_inbound_dmarc_settings(enforced, organization_id) put_inbound_dmarc_settings(enforced, organization_id, params::Dict{String,<:Any}) Enables or disables a DMARC policy for a given organization. # Arguments - `enforced`: Enforces or suspends a policy after it's applied. - `organization_id`: The ID of the organization that you are applying the DMARC policy to. """ function put_inbound_dmarc_settings( Enforced, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "PutInboundDmarcSettings", Dict{String,Any}("Enforced" => Enforced, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_inbound_dmarc_settings( Enforced, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutInboundDmarcSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Enforced" => Enforced, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_mailbox_permissions(entity_id, grantee_id, organization_id, permission_values) put_mailbox_permissions(entity_id, grantee_id, organization_id, permission_values, params::Dict{String,<:Any}) Sets permissions for a user, group, or resource. This replaces any pre-existing permissions. # Arguments - `entity_id`: The identifier of the user or resource for which to update mailbox permissions. The identifier can be UserId, ResourceID, or Group Id, Username, Resourcename, or Groupname, or email. Entity ID: 12345678-1234-1234-1234-123456789012, r-0123456789a0123456789b0123456789, or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity name: entity - `grantee_id`: The identifier of the user, group, or resource to which to grant the permissions. The identifier can be UserId, ResourceID, or Group Id, Username, Resourcename, or Groupname, or email. Grantee ID: 12345678-1234-1234-1234-123456789012, r-0123456789a0123456789b0123456789, or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Grantee name: grantee - `organization_id`: The identifier of the organization under which the user, group, or resource exists. - `permission_values`: The permissions granted to the grantee. SEND_AS allows the grantee to send email as the owner of the mailbox (the grantee is not mentioned on these emails). SEND_ON_BEHALF allows the grantee to send email on behalf of the owner of the mailbox (the grantee is not mentioned as the physical sender of these emails). FULL_ACCESS allows the grantee full access to the mailbox, irrespective of other folder-level permissions set on the mailbox. """ function put_mailbox_permissions( EntityId, GranteeId, OrganizationId, PermissionValues; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutMailboxPermissions", Dict{String,Any}( "EntityId" => EntityId, "GranteeId" => GranteeId, "OrganizationId" => OrganizationId, "PermissionValues" => PermissionValues, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_mailbox_permissions( EntityId, GranteeId, OrganizationId, PermissionValues, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutMailboxPermissions", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EntityId" => EntityId, "GranteeId" => GranteeId, "OrganizationId" => OrganizationId, "PermissionValues" => PermissionValues, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_mobile_device_access_override(device_id, effect, organization_id, user_id) put_mobile_device_access_override(device_id, effect, organization_id, user_id, params::Dict{String,<:Any}) Creates or updates a mobile device access override for the given WorkMail organization, user, and device. # Arguments - `device_id`: The mobile device for which you create the override. DeviceId is case insensitive. - `effect`: The effect of the override, ALLOW or DENY. - `organization_id`: Identifies the WorkMail organization for which you create the override. - `user_id`: The WorkMail user for which you create the override. Accepts the following types of user identities: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Description"`: A description of the override. """ function put_mobile_device_access_override( DeviceId, Effect, OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutMobileDeviceAccessOverride", Dict{String,Any}( "DeviceId" => DeviceId, "Effect" => Effect, "OrganizationId" => OrganizationId, "UserId" => UserId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_mobile_device_access_override( DeviceId, Effect, OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutMobileDeviceAccessOverride", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DeviceId" => DeviceId, "Effect" => Effect, "OrganizationId" => OrganizationId, "UserId" => UserId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_retention_policy(folder_configurations, name, organization_id) put_retention_policy(folder_configurations, name, organization_id, params::Dict{String,<:Any}) Puts a retention policy to the specified organization. # Arguments - `folder_configurations`: The retention policy folder configurations. - `name`: The retention policy name. - `organization_id`: The organization ID. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Description"`: The retention policy description. - `"Id"`: The retention policy ID. """ function put_retention_policy( FolderConfigurations, Name, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutRetentionPolicy", Dict{String,Any}( "FolderConfigurations" => FolderConfigurations, "Name" => Name, "OrganizationId" => OrganizationId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_retention_policy( FolderConfigurations, Name, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "PutRetentionPolicy", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "FolderConfigurations" => FolderConfigurations, "Name" => Name, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ register_mail_domain(domain_name, organization_id) register_mail_domain(domain_name, organization_id, params::Dict{String,<:Any}) Registers a new domain in WorkMail and SES, and configures it for use by WorkMail. Emails received by SES for this domain are routed to the specified WorkMail organization, and WorkMail has permanent permission to use the specified domain for sending your users' emails. # Arguments - `domain_name`: The name of the mail domain to create in WorkMail and SES. - `organization_id`: The WorkMail organization under which you're creating the domain. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: Idempotency token used when retrying requests. """ function register_mail_domain( DomainName, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "RegisterMailDomain", Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function register_mail_domain( DomainName, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "RegisterMailDomain", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId, "ClientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ register_to_work_mail(email, entity_id, organization_id) register_to_work_mail(email, entity_id, organization_id, params::Dict{String,<:Any}) Registers an existing and disabled user, group, or resource for WorkMail use by associating a mailbox and calendaring capabilities. It performs no change if the user, group, or resource is enabled and fails if the user, group, or resource is deleted. This operation results in the accumulation of costs. For more information, see Pricing. The equivalent console functionality for this operation is Enable. Users can either be created by calling the CreateUser API operation or they can be synchronized from your directory. For more information, see DeregisterFromWorkMail. # Arguments - `email`: The email for the user, group, or resource to be updated. - `entity_id`: The identifier for the user, group, or resource to be updated. The identifier can accept UserId, ResourceId, or GroupId, or Username, Resourcename, or Groupname. The following identity formats are available: Entity ID: 12345678-1234-1234-1234-123456789012, r-0123456789a0123456789b0123456789, or S-1-1-12-1234567890-123456789-123456789-1234 Entity name: entity - `organization_id`: The identifier for the organization under which the user, group, or resource exists. """ function register_to_work_mail( Email, EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "RegisterToWorkMail", Dict{String,Any}( "Email" => Email, "EntityId" => EntityId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function register_to_work_mail( Email, EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "RegisterToWorkMail", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Email" => Email, "EntityId" => EntityId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ reset_password(organization_id, password, user_id) reset_password(organization_id, password, user_id, params::Dict{String,<:Any}) Allows the administrator to reset the password for a user. # Arguments - `organization_id`: The identifier of the organization that contains the user for which the password is reset. - `password`: The new password for the user. - `user_id`: The identifier of the user for whom the password is reset. """ function reset_password( OrganizationId, Password, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "ResetPassword", Dict{String,Any}( "OrganizationId" => OrganizationId, "Password" => Password, "UserId" => UserId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function reset_password( OrganizationId, Password, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "ResetPassword", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "OrganizationId" => OrganizationId, "Password" => Password, "UserId" => UserId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ start_mailbox_export_job(client_token, entity_id, kms_key_arn, organization_id, role_arn, s3_bucket_name, s3_prefix) start_mailbox_export_job(client_token, entity_id, kms_key_arn, organization_id, role_arn, s3_bucket_name, s3_prefix, params::Dict{String,<:Any}) Starts a mailbox export job to export MIME-format email messages and calendar items from the specified mailbox to the specified Amazon Simple Storage Service (Amazon S3) bucket. For more information, see Exporting mailbox content in the WorkMail Administrator Guide. # Arguments - `client_token`: The idempotency token for the client request. - `entity_id`: The identifier of the user or resource associated with the mailbox. The identifier can accept UserId or ResourceId, Username or Resourcename, or email. The following identity formats are available: Entity ID: 12345678-1234-1234-1234-123456789012, r-0123456789a0123456789b0123456789 , or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity name: entity - `kms_key_arn`: The Amazon Resource Name (ARN) of the symmetric AWS Key Management Service (AWS KMS) key that encrypts the exported mailbox content. - `organization_id`: The identifier associated with the organization. - `role_arn`: The ARN of the AWS Identity and Access Management (IAM) role that grants write permission to the S3 bucket. - `s3_bucket_name`: The name of the S3 bucket. - `s3_prefix`: The S3 bucket prefix. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Description"`: The mailbox export job description. """ function start_mailbox_export_job( ClientToken, EntityId, KmsKeyArn, OrganizationId, RoleArn, S3BucketName, S3Prefix; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "StartMailboxExportJob", Dict{String,Any}( "ClientToken" => ClientToken, "EntityId" => EntityId, "KmsKeyArn" => KmsKeyArn, "OrganizationId" => OrganizationId, "RoleArn" => RoleArn, "S3BucketName" => S3BucketName, "S3Prefix" => S3Prefix, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function start_mailbox_export_job( ClientToken, EntityId, KmsKeyArn, OrganizationId, RoleArn, S3BucketName, S3Prefix, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "StartMailboxExportJob", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ClientToken" => ClientToken, "EntityId" => EntityId, "KmsKeyArn" => KmsKeyArn, "OrganizationId" => OrganizationId, "RoleArn" => RoleArn, "S3BucketName" => S3BucketName, "S3Prefix" => S3Prefix, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ tag_resource(resource_arn, tags) tag_resource(resource_arn, tags, params::Dict{String,<:Any}) Applies the specified tags to the specified WorkMailorganization resource. # Arguments - `resource_arn`: The resource ARN. - `tags`: The tag key-value pairs. """ function tag_resource(ResourceARN, Tags; aws_config::AbstractAWSConfig=global_aws_config()) return workmail( "TagResource", Dict{String,Any}("ResourceARN" => ResourceARN, "Tags" => Tags); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function tag_resource( ResourceARN, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "TagResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ResourceARN" => ResourceARN, "Tags" => Tags), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ test_availability_configuration(organization_id) test_availability_configuration(organization_id, params::Dict{String,<:Any}) Performs a test on an availability provider to ensure that access is allowed. For EWS, it verifies the provided credentials can be used to successfully log in. For Lambda, it verifies that the Lambda function can be invoked and that the resource access policy was configured to deny anonymous access. An anonymous invocation is one done without providing either a SourceArn or SourceAccount header. The request must contain either one provider definition (EwsProvider or LambdaProvider) or the DomainName parameter. If the DomainName parameter is provided, the configuration stored under the DomainName will be tested. # Arguments - `organization_id`: The WorkMail organization where the availability provider will be tested. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DomainName"`: The domain to which the provider applies. If this field is provided, a stored availability provider associated to this domain name will be tested. - `"EwsProvider"`: - `"LambdaProvider"`: """ function test_availability_configuration( OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "TestAvailabilityConfiguration", Dict{String,Any}("OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function test_availability_configuration( OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "TestAvailabilityConfiguration", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("OrganizationId" => OrganizationId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ untag_resource(resource_arn, tag_keys) untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any}) Untags the specified tags from the specified WorkMail organization resource. # Arguments - `resource_arn`: The resource ARN. - `tag_keys`: The tag keys. """ function untag_resource( ResourceARN, TagKeys; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UntagResource", Dict{String,Any}("ResourceARN" => ResourceARN, "TagKeys" => TagKeys); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function untag_resource( ResourceARN, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UntagResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ResourceARN" => ResourceARN, "TagKeys" => TagKeys), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_availability_configuration(domain_name, organization_id) update_availability_configuration(domain_name, organization_id, params::Dict{String,<:Any}) Updates an existing AvailabilityConfiguration for the given WorkMail organization and domain. # Arguments - `domain_name`: The domain to which the provider applies the availability configuration. - `organization_id`: The WorkMail organization for which the AvailabilityConfiguration will be updated. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"EwsProvider"`: The EWS availability provider definition. The request must contain exactly one provider definition, either EwsProvider or LambdaProvider. The previously stored provider will be overridden by the one provided. - `"LambdaProvider"`: The Lambda availability provider definition. The request must contain exactly one provider definition, either EwsProvider or LambdaProvider. The previously stored provider will be overridden by the one provided. """ function update_availability_configuration( DomainName, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UpdateAvailabilityConfiguration", Dict{String,Any}("DomainName" => DomainName, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_availability_configuration( DomainName, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateAvailabilityConfiguration", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_default_mail_domain(domain_name, organization_id) update_default_mail_domain(domain_name, organization_id, params::Dict{String,<:Any}) Updates the default mail domain for an organization. The default mail domain is used by the WorkMail AWS Console to suggest an email address when enabling a mail user. You can only have one default domain. # Arguments - `domain_name`: The domain name that will become the default domain. - `organization_id`: The WorkMail organization for which to list domains. """ function update_default_mail_domain( DomainName, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UpdateDefaultMailDomain", Dict{String,Any}("DomainName" => DomainName, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_default_mail_domain( DomainName, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateDefaultMailDomain", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DomainName" => DomainName, "OrganizationId" => OrganizationId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_group(group_id, organization_id) update_group(group_id, organization_id, params::Dict{String,<:Any}) Updates attibutes in a group. # Arguments - `group_id`: The identifier for the group to be updated. The identifier can accept GroupId, Groupname, or email. The following identity formats are available: Group ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Group name: group - `organization_id`: The identifier for the organization under which the group exists. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"HiddenFromGlobalAddressList"`: If enabled, the group is hidden from the global address list. """ function update_group( GroupId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UpdateGroup", Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_group( GroupId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateGroup", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("GroupId" => GroupId, "OrganizationId" => OrganizationId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_impersonation_role(impersonation_role_id, name, organization_id, rules, type) update_impersonation_role(impersonation_role_id, name, organization_id, rules, type, params::Dict{String,<:Any}) Updates an impersonation role for the given WorkMail organization. # Arguments - `impersonation_role_id`: The ID of the impersonation role to update. - `name`: The updated impersonation role name. - `organization_id`: The WorkMail organization that contains the impersonation role to update. - `rules`: The updated list of rules. - `type`: The updated impersonation role type. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Description"`: The updated impersonation role description. """ function update_impersonation_role( ImpersonationRoleId, Name, OrganizationId, Rules, Type; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateImpersonationRole", Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "Name" => Name, "OrganizationId" => OrganizationId, "Rules" => Rules, "Type" => Type, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_impersonation_role( ImpersonationRoleId, Name, OrganizationId, Rules, Type, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateImpersonationRole", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ImpersonationRoleId" => ImpersonationRoleId, "Name" => Name, "OrganizationId" => OrganizationId, "Rules" => Rules, "Type" => Type, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_mailbox_quota(mailbox_quota, organization_id, user_id) update_mailbox_quota(mailbox_quota, organization_id, user_id, params::Dict{String,<:Any}) Updates a user's current mailbox quota for a specified organization and user. # Arguments - `mailbox_quota`: The updated mailbox quota, in MB, for the specified user. - `organization_id`: The identifier for the organization that contains the user for whom to update the mailbox quota. - `user_id`: The identifer for the user for whom to update the mailbox quota. The identifier can be the UserId, Username, or email. The following identity formats are available: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user """ function update_mailbox_quota( MailboxQuota, OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UpdateMailboxQuota", Dict{String,Any}( "MailboxQuota" => MailboxQuota, "OrganizationId" => OrganizationId, "UserId" => UserId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_mailbox_quota( MailboxQuota, OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateMailboxQuota", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "MailboxQuota" => MailboxQuota, "OrganizationId" => OrganizationId, "UserId" => UserId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_mobile_device_access_rule(effect, mobile_device_access_rule_id, name, organization_id) update_mobile_device_access_rule(effect, mobile_device_access_rule_id, name, organization_id, params::Dict{String,<:Any}) Updates a mobile device access rule for the specified WorkMail organization. # Arguments - `effect`: The effect of the rule when it matches. Allowed values are ALLOW or DENY. - `mobile_device_access_rule_id`: The identifier of the rule to be updated. - `name`: The updated rule name. - `organization_id`: The WorkMail organization under which the rule will be updated. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Description"`: The updated rule description. - `"DeviceModels"`: Device models that the updated rule will match. - `"DeviceOperatingSystems"`: Device operating systems that the updated rule will match. - `"DeviceTypes"`: Device types that the updated rule will match. - `"DeviceUserAgents"`: User agents that the updated rule will match. - `"NotDeviceModels"`: Device models that the updated rule will not match. All other device models will match. - `"NotDeviceOperatingSystems"`: Device operating systems that the updated rule will not match. All other device operating systems will match. - `"NotDeviceTypes"`: Device types that the updated rule will not match. All other device types will match. - `"NotDeviceUserAgents"`: User agents that the updated rule will not match. All other user agents will match. """ function update_mobile_device_access_rule( Effect, MobileDeviceAccessRuleId, Name, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateMobileDeviceAccessRule", Dict{String,Any}( "Effect" => Effect, "MobileDeviceAccessRuleId" => MobileDeviceAccessRuleId, "Name" => Name, "OrganizationId" => OrganizationId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_mobile_device_access_rule( Effect, MobileDeviceAccessRuleId, Name, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateMobileDeviceAccessRule", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Effect" => Effect, "MobileDeviceAccessRuleId" => MobileDeviceAccessRuleId, "Name" => Name, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_primary_email_address(email, entity_id, organization_id) update_primary_email_address(email, entity_id, organization_id, params::Dict{String,<:Any}) Updates the primary email for a user, group, or resource. The current email is moved into the list of aliases (or swapped between an existing alias and the current primary email), and the email provided in the input is promoted as the primary. # Arguments - `email`: The value of the email to be updated as primary. - `entity_id`: The user, group, or resource to update. The identifier can accept UseriD, ResourceId, or GroupId, Username, Resourcename, or Groupname, or email. The following identity formats are available: Entity ID: 12345678-1234-1234-1234-123456789012, r-0123456789a0123456789b0123456789, or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] Entity name: entity - `organization_id`: The organization that contains the user, group, or resource to update. """ function update_primary_email_address( Email, EntityId, OrganizationId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UpdatePrimaryEmailAddress", Dict{String,Any}( "Email" => Email, "EntityId" => EntityId, "OrganizationId" => OrganizationId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_primary_email_address( Email, EntityId, OrganizationId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdatePrimaryEmailAddress", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Email" => Email, "EntityId" => EntityId, "OrganizationId" => OrganizationId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_resource(organization_id, resource_id) update_resource(organization_id, resource_id, params::Dict{String,<:Any}) Updates data for the resource. To have the latest information, it must be preceded by a DescribeResource call. The dataset in the request should be the one expected when performing another DescribeResource call. # Arguments - `organization_id`: The identifier associated with the organization for which the resource is updated. - `resource_id`: The identifier of the resource to be updated. The identifier can accept ResourceId, Resourcename, or email. The following identity formats are available: Resource ID: r-0123456789a0123456789b0123456789 Email address: [email protected] Resource name: resource # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"BookingOptions"`: The resource's booking options to be updated. - `"Description"`: Updates the resource description. - `"HiddenFromGlobalAddressList"`: If enabled, the resource is hidden from the global address list. - `"Name"`: The name of the resource to be updated. - `"Type"`: Updates the resource type. """ function update_resource( OrganizationId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UpdateResource", Dict{String,Any}("OrganizationId" => OrganizationId, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_resource( OrganizationId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "OrganizationId" => OrganizationId, "ResourceId" => ResourceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_user(organization_id, user_id) update_user(organization_id, user_id, params::Dict{String,<:Any}) Updates data for the user. To have the latest information, it must be preceded by a DescribeUser call. The dataset in the request should be the one expected when performing another DescribeUser call. # Arguments - `organization_id`: The identifier for the organization under which the user exists. - `user_id`: The identifier for the user to be updated. The identifier can be the UserId, Username, or email. The following identity formats are available: User ID: 12345678-1234-1234-1234-123456789012 or S-1-1-12-1234567890-123456789-123456789-1234 Email address: [email protected] User name: user # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"City"`: Updates the user's city. - `"Company"`: Updates the user's company. - `"Country"`: Updates the user's country. - `"Department"`: Updates the user's department. - `"DisplayName"`: Updates the display name of the user. - `"FirstName"`: Updates the user's first name. - `"HiddenFromGlobalAddressList"`: If enabled, the user is hidden from the global address list. - `"Initials"`: Updates the user's initials. - `"JobTitle"`: Updates the user's job title. - `"LastName"`: Updates the user's last name. - `"Office"`: Updates the user's office. - `"Role"`: Updates the user role. You cannot pass SYSTEM_USER or RESOURCE. - `"Street"`: Updates the user's street address. - `"Telephone"`: Updates the user's contact details. - `"ZipCode"`: Updates the user's zipcode. """ function update_user( OrganizationId, UserId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmail( "UpdateUser", Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_user( OrganizationId, UserId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmail( "UpdateUser", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("OrganizationId" => OrganizationId, "UserId" => UserId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
2564
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: workmailmessageflow using AWS.Compat using AWS.UUIDs """ get_raw_message_content(message_id) get_raw_message_content(message_id, params::Dict{String,<:Any}) Retrieves the raw content of an in-transit email message, in MIME format. # Arguments - `message_id`: The identifier of the email message to retrieve. """ function get_raw_message_content( messageId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmailmessageflow( "GET", "/messages/$(messageId)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_raw_message_content( messageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmailmessageflow( "GET", "/messages/$(messageId)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_raw_message_content(content, message_id) put_raw_message_content(content, message_id, params::Dict{String,<:Any}) Updates the raw content of an in-transit email message, in MIME format. This example describes how to update in-transit email message. For more information and examples for using this API, see Updating message content with AWS Lambda. Updates to an in-transit message only appear when you call PutRawMessageContent from an AWS Lambda function configured with a synchronous Run Lambda rule. If you call PutRawMessageContent on a delivered or sent message, the message remains unchanged, even though GetRawMessageContent returns an updated message. # Arguments - `content`: Describes the raw message content of the updated email message. - `message_id`: The identifier of the email message being updated. """ function put_raw_message_content( content, messageId; aws_config::AbstractAWSConfig=global_aws_config() ) return workmailmessageflow( "POST", "/messages/$(messageId)", Dict{String,Any}("content" => content); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_raw_message_content( content, messageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workmailmessageflow( "POST", "/messages/$(messageId)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("content" => content), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
115964
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: workspaces using AWS.Compat using AWS.UUIDs """ accept_account_link_invitation(link_id) accept_account_link_invitation(link_id, params::Dict{String,<:Any}) Accepts the account link invitation. There's currently no unlinking capability after you accept the account linking invitation. # Arguments - `link_id`: The identifier of the account link. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: A string of up to 64 ASCII characters that Amazon EFS uses to ensure idempotent creation. """ function accept_account_link_invitation( LinkId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "AcceptAccountLinkInvitation", Dict{String,Any}("LinkId" => LinkId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function accept_account_link_invitation( LinkId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "AcceptAccountLinkInvitation", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("LinkId" => LinkId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_connection_alias(alias_id, resource_id) associate_connection_alias(alias_id, resource_id, params::Dict{String,<:Any}) Associates the specified connection alias with the specified directory to enable cross-Region redirection. For more information, see Cross-Region Redirection for Amazon WorkSpaces. Before performing this operation, call DescribeConnectionAliases to make sure that the current state of the connection alias is CREATED. # Arguments - `alias_id`: The identifier of the connection alias. - `resource_id`: The identifier of the directory to associate the connection alias with. """ function associate_connection_alias( AliasId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "AssociateConnectionAlias", Dict{String,Any}("AliasId" => AliasId, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_connection_alias( AliasId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "AssociateConnectionAlias", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("AliasId" => AliasId, "ResourceId" => ResourceId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_ip_groups(directory_id, group_ids) associate_ip_groups(directory_id, group_ids, params::Dict{String,<:Any}) Associates the specified IP access control group with the specified directory. # Arguments - `directory_id`: The identifier of the directory. - `group_ids`: The identifiers of one or more IP access control groups. """ function associate_ip_groups( DirectoryId, GroupIds; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "AssociateIpGroups", Dict{String,Any}("DirectoryId" => DirectoryId, "GroupIds" => GroupIds); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_ip_groups( DirectoryId, GroupIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "AssociateIpGroups", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DirectoryId" => DirectoryId, "GroupIds" => GroupIds), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_workspace_application(application_id, workspace_id) associate_workspace_application(application_id, workspace_id, params::Dict{String,<:Any}) Associates the specified application to the specified WorkSpace. # Arguments - `application_id`: The identifier of the application. - `workspace_id`: The identifier of the WorkSpace. """ function associate_workspace_application( ApplicationId, WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "AssociateWorkspaceApplication", Dict{String,Any}("ApplicationId" => ApplicationId, "WorkspaceId" => WorkspaceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_workspace_application( ApplicationId, WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "AssociateWorkspaceApplication", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ApplicationId" => ApplicationId, "WorkspaceId" => WorkspaceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ authorize_ip_rules(group_id, user_rules) authorize_ip_rules(group_id, user_rules, params::Dict{String,<:Any}) Adds one or more rules to the specified IP access control group. This action gives users permission to access their WorkSpaces from the CIDR address ranges specified in the rules. # Arguments - `group_id`: The identifier of the group. - `user_rules`: The rules to add to the group. """ function authorize_ip_rules( GroupId, UserRules; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "AuthorizeIpRules", Dict{String,Any}("GroupId" => GroupId, "UserRules" => UserRules); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function authorize_ip_rules( GroupId, UserRules, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "AuthorizeIpRules", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("GroupId" => GroupId, "UserRules" => UserRules), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ copy_workspace_image(name, source_image_id, source_region) copy_workspace_image(name, source_image_id, source_region, params::Dict{String,<:Any}) Copies the specified image from the specified Region to the current Region. For more information about copying images, see Copy a Custom WorkSpaces Image. In the China (Ningxia) Region, you can copy images only within the same Region. In Amazon Web Services GovCloud (US), to copy images to and from other Regions, contact Amazon Web Services Support. Before copying a shared image, be sure to verify that it has been shared from the correct Amazon Web Services account. To determine if an image has been shared and to see the ID of the Amazon Web Services account that owns an image, use the DescribeWorkSpaceImages and DescribeWorkspaceImagePermissions API operations. # Arguments - `name`: The name of the image. - `source_image_id`: The identifier of the source image. - `source_region`: The identifier of the source Region. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Description"`: A description of the image. - `"Tags"`: The tags for the image. """ function copy_workspace_image( Name, SourceImageId, SourceRegion; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "CopyWorkspaceImage", Dict{String,Any}( "Name" => Name, "SourceImageId" => SourceImageId, "SourceRegion" => SourceRegion ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function copy_workspace_image( Name, SourceImageId, SourceRegion, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CopyWorkspaceImage", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Name" => Name, "SourceImageId" => SourceImageId, "SourceRegion" => SourceRegion, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_account_link_invitation(target_account_id) create_account_link_invitation(target_account_id, params::Dict{String,<:Any}) Creates the account link invitation. # Arguments - `target_account_id`: The identifier of the target account. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: A string of up to 64 ASCII characters that Amazon EFS uses to ensure idempotent creation. """ function create_account_link_invitation( TargetAccountId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "CreateAccountLinkInvitation", Dict{String,Any}("TargetAccountId" => TargetAccountId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_account_link_invitation( TargetAccountId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateAccountLinkInvitation", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("TargetAccountId" => TargetAccountId), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_connect_client_add_in(name, resource_id, url) create_connect_client_add_in(name, resource_id, url, params::Dict{String,<:Any}) Creates a client-add-in for Amazon Connect within a directory. You can create only one Amazon Connect client add-in within a directory. This client add-in allows WorkSpaces users to seamlessly connect to Amazon Connect. # Arguments - `name`: The name of the client add-in. - `resource_id`: The directory identifier for which to configure the client add-in. - `url`: The endpoint URL of the Amazon Connect client add-in. """ function create_connect_client_add_in( Name, ResourceId, URL; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "CreateConnectClientAddIn", Dict{String,Any}("Name" => Name, "ResourceId" => ResourceId, "URL" => URL); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_connect_client_add_in( Name, ResourceId, URL, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateConnectClientAddIn", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Name" => Name, "ResourceId" => ResourceId, "URL" => URL), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_connection_alias(connection_string) create_connection_alias(connection_string, params::Dict{String,<:Any}) Creates the specified connection alias for use with cross-Region redirection. For more information, see Cross-Region Redirection for Amazon WorkSpaces. # Arguments - `connection_string`: A connection string in the form of a fully qualified domain name (FQDN), such as www.example.com. After you create a connection string, it is always associated to your Amazon Web Services account. You cannot recreate the same connection string with a different account, even if you delete all instances of it from the original account. The connection string is globally reserved for your account. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Tags"`: The tags to associate with the connection alias. """ function create_connection_alias( ConnectionString; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "CreateConnectionAlias", Dict{String,Any}("ConnectionString" => ConnectionString); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_connection_alias( ConnectionString, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateConnectionAlias", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ConnectionString" => ConnectionString), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_ip_group(group_name) create_ip_group(group_name, params::Dict{String,<:Any}) Creates an IP access control group. An IP access control group provides you with the ability to control the IP addresses from which users are allowed to access their WorkSpaces. To specify the CIDR address ranges, add rules to your IP access control group and then associate the group with your directory. You can add rules when you create the group or at any time using AuthorizeIpRules. There is a default IP access control group associated with your directory. If you don't associate an IP access control group with your directory, the default group is used. The default group includes a default rule that allows users to access their WorkSpaces from anywhere. You cannot modify the default IP access control group for your directory. # Arguments - `group_name`: The name of the group. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"GroupDesc"`: The description of the group. - `"Tags"`: The tags. Each WorkSpaces resource can have a maximum of 50 tags. - `"UserRules"`: The rules to add to the group. """ function create_ip_group(GroupName; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "CreateIpGroup", Dict{String,Any}("GroupName" => GroupName); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_ip_group( GroupName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateIpGroup", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("GroupName" => GroupName), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_standby_workspaces(primary_region, standby_workspaces) create_standby_workspaces(primary_region, standby_workspaces, params::Dict{String,<:Any}) Creates a standby WorkSpace in a secondary Region. # Arguments - `primary_region`: The Region of the primary WorkSpace. - `standby_workspaces`: Information about the standby WorkSpace to be created. """ function create_standby_workspaces( PrimaryRegion, StandbyWorkspaces; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "CreateStandbyWorkspaces", Dict{String,Any}( "PrimaryRegion" => PrimaryRegion, "StandbyWorkspaces" => StandbyWorkspaces ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_standby_workspaces( PrimaryRegion, StandbyWorkspaces, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateStandbyWorkspaces", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "PrimaryRegion" => PrimaryRegion, "StandbyWorkspaces" => StandbyWorkspaces, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_tags(resource_id, tags) create_tags(resource_id, tags, params::Dict{String,<:Any}) Creates the specified tags for the specified WorkSpaces resource. # Arguments - `resource_id`: The identifier of the WorkSpaces resource. The supported resource types are WorkSpaces, registered directories, images, custom bundles, IP access control groups, and connection aliases. - `tags`: The tags. Each WorkSpaces resource can have a maximum of 50 tags. """ function create_tags(ResourceId, Tags; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "CreateTags", Dict{String,Any}("ResourceId" => ResourceId, "Tags" => Tags); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_tags( ResourceId, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateTags", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ResourceId" => ResourceId, "Tags" => Tags), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_updated_workspace_image(description, name, source_image_id) create_updated_workspace_image(description, name, source_image_id, params::Dict{String,<:Any}) Creates a new updated WorkSpace image based on the specified source image. The new updated WorkSpace image has the latest drivers and other updates required by the Amazon WorkSpaces components. To determine which WorkSpace images need to be updated with the latest Amazon WorkSpaces requirements, use DescribeWorkspaceImages. Only Windows 10, Windows Server 2016, and Windows Server 2019 WorkSpace images can be programmatically updated at this time. Microsoft Windows updates and other application updates are not included in the update process. The source WorkSpace image is not deleted. You can delete the source image after you've verified your new updated image and created a new bundle. # Arguments - `description`: A description of whether updates for the WorkSpace image are available. - `name`: The name of the new updated WorkSpace image. - `source_image_id`: The identifier of the source WorkSpace image. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Tags"`: The tags that you want to add to the new updated WorkSpace image. To add tags at the same time when you're creating the updated image, you must create an IAM policy that grants your IAM user permissions to use workspaces:CreateTags. """ function create_updated_workspace_image( Description, Name, SourceImageId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "CreateUpdatedWorkspaceImage", Dict{String,Any}( "Description" => Description, "Name" => Name, "SourceImageId" => SourceImageId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_updated_workspace_image( Description, Name, SourceImageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateUpdatedWorkspaceImage", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Description" => Description, "Name" => Name, "SourceImageId" => SourceImageId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_workspace_bundle(bundle_description, bundle_name, compute_type, image_id, user_storage) create_workspace_bundle(bundle_description, bundle_name, compute_type, image_id, user_storage, params::Dict{String,<:Any}) Creates the specified WorkSpace bundle. For more information about creating WorkSpace bundles, see Create a Custom WorkSpaces Image and Bundle. # Arguments - `bundle_description`: The description of the bundle. - `bundle_name`: The name of the bundle. - `compute_type`: - `image_id`: The identifier of the image that is used to create the bundle. - `user_storage`: # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"RootStorage"`: - `"Tags"`: The tags associated with the bundle. To add tags at the same time when you're creating the bundle, you must create an IAM policy that grants your IAM user permissions to use workspaces:CreateTags. """ function create_workspace_bundle( BundleDescription, BundleName, ComputeType, ImageId, UserStorage; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateWorkspaceBundle", Dict{String,Any}( "BundleDescription" => BundleDescription, "BundleName" => BundleName, "ComputeType" => ComputeType, "ImageId" => ImageId, "UserStorage" => UserStorage, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_workspace_bundle( BundleDescription, BundleName, ComputeType, ImageId, UserStorage, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateWorkspaceBundle", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "BundleDescription" => BundleDescription, "BundleName" => BundleName, "ComputeType" => ComputeType, "ImageId" => ImageId, "UserStorage" => UserStorage, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_workspace_image(description, name, workspace_id) create_workspace_image(description, name, workspace_id, params::Dict{String,<:Any}) Creates a new WorkSpace image from an existing WorkSpace. # Arguments - `description`: The description of the new WorkSpace image. - `name`: The name of the new WorkSpace image. - `workspace_id`: The identifier of the source WorkSpace # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Tags"`: The tags that you want to add to the new WorkSpace image. To add tags when you're creating the image, you must create an IAM policy that grants your IAM user permission to use workspaces:CreateTags. """ function create_workspace_image( Description, Name, WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "CreateWorkspaceImage", Dict{String,Any}( "Description" => Description, "Name" => Name, "WorkspaceId" => WorkspaceId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_workspace_image( Description, Name, WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateWorkspaceImage", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Description" => Description, "Name" => Name, "WorkspaceId" => WorkspaceId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_workspaces(workspaces) create_workspaces(workspaces, params::Dict{String,<:Any}) Creates one or more WorkSpaces. This operation is asynchronous and returns before the WorkSpaces are created. The MANUAL running mode value is only supported by Amazon WorkSpaces Core. Contact your account team to be allow-listed to use this value. For more information, see Amazon WorkSpaces Core. You don't need to specify the PCOIP protocol for Linux bundles because WSP is the default protocol for those bundles. User-decoupled WorkSpaces are only supported by Amazon WorkSpaces Core. # Arguments - `workspaces`: The WorkSpaces to create. You can specify up to 25 WorkSpaces. """ function create_workspaces(Workspaces; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "CreateWorkspaces", Dict{String,Any}("Workspaces" => Workspaces); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_workspaces( Workspaces, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "CreateWorkspaces", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("Workspaces" => Workspaces), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_account_link_invitation(link_id) delete_account_link_invitation(link_id, params::Dict{String,<:Any}) Deletes the account link invitation. # Arguments - `link_id`: The identifier of the account link. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: A string of up to 64 ASCII characters that Amazon EFS uses to ensure idempotent creation. """ function delete_account_link_invitation( LinkId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteAccountLinkInvitation", Dict{String,Any}("LinkId" => LinkId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_account_link_invitation( LinkId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteAccountLinkInvitation", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("LinkId" => LinkId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_client_branding(platforms, resource_id) delete_client_branding(platforms, resource_id, params::Dict{String,<:Any}) Deletes customized client branding. Client branding allows you to customize your WorkSpace's client login portal. You can tailor your login portal company logo, the support email address, support link, link to reset password, and a custom message for users trying to sign in. After you delete your customized client branding, your login portal reverts to the default client branding. # Arguments - `platforms`: The device type for which you want to delete client branding. - `resource_id`: The directory identifier of the WorkSpace for which you want to delete client branding. """ function delete_client_branding( Platforms, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteClientBranding", Dict{String,Any}("Platforms" => Platforms, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_client_branding( Platforms, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DeleteClientBranding", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("Platforms" => Platforms, "ResourceId" => ResourceId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_connect_client_add_in(add_in_id, resource_id) delete_connect_client_add_in(add_in_id, resource_id, params::Dict{String,<:Any}) Deletes a client-add-in for Amazon Connect that is configured within a directory. # Arguments - `add_in_id`: The identifier of the client add-in to delete. - `resource_id`: The directory identifier for which the client add-in is configured. """ function delete_connect_client_add_in( AddInId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteConnectClientAddIn", Dict{String,Any}("AddInId" => AddInId, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_connect_client_add_in( AddInId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DeleteConnectClientAddIn", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("AddInId" => AddInId, "ResourceId" => ResourceId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_connection_alias(alias_id) delete_connection_alias(alias_id, params::Dict{String,<:Any}) Deletes the specified connection alias. For more information, see Cross-Region Redirection for Amazon WorkSpaces. If you will no longer be using a fully qualified domain name (FQDN) as the registration code for your WorkSpaces users, you must take certain precautions to prevent potential security issues. For more information, see Security Considerations if You Stop Using Cross-Region Redirection. To delete a connection alias that has been shared, the shared account must first disassociate the connection alias from any directories it has been associated with. Then you must unshare the connection alias from the account it has been shared with. You can delete a connection alias only after it is no longer shared with any accounts or associated with any directories. # Arguments - `alias_id`: The identifier of the connection alias to delete. """ function delete_connection_alias(AliasId; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DeleteConnectionAlias", Dict{String,Any}("AliasId" => AliasId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_connection_alias( AliasId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteConnectionAlias", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("AliasId" => AliasId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_ip_group(group_id) delete_ip_group(group_id, params::Dict{String,<:Any}) Deletes the specified IP access control group. You cannot delete an IP access control group that is associated with a directory. # Arguments - `group_id`: The identifier of the IP access control group. """ function delete_ip_group(GroupId; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DeleteIpGroup", Dict{String,Any}("GroupId" => GroupId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_ip_group( GroupId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteIpGroup", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("GroupId" => GroupId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_tags(resource_id, tag_keys) delete_tags(resource_id, tag_keys, params::Dict{String,<:Any}) Deletes the specified tags from the specified WorkSpaces resource. # Arguments - `resource_id`: The identifier of the WorkSpaces resource. The supported resource types are WorkSpaces, registered directories, images, custom bundles, IP access control groups, and connection aliases. - `tag_keys`: The tag keys. """ function delete_tags(ResourceId, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DeleteTags", Dict{String,Any}("ResourceId" => ResourceId, "TagKeys" => TagKeys); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_tags( ResourceId, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DeleteTags", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ResourceId" => ResourceId, "TagKeys" => TagKeys), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_workspace_bundle() delete_workspace_bundle(params::Dict{String,<:Any}) Deletes the specified WorkSpace bundle. For more information about deleting WorkSpace bundles, see Delete a Custom WorkSpaces Bundle or Image. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"BundleId"`: The identifier of the bundle. """ function delete_workspace_bundle(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DeleteWorkspaceBundle"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function delete_workspace_bundle( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteWorkspaceBundle", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_workspace_image(image_id) delete_workspace_image(image_id, params::Dict{String,<:Any}) Deletes the specified image from your account. To delete an image, you must first delete any bundles that are associated with the image and unshare the image if it is shared with other accounts. # Arguments - `image_id`: The identifier of the image. """ function delete_workspace_image(ImageId; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DeleteWorkspaceImage", Dict{String,Any}("ImageId" => ImageId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_workspace_image( ImageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeleteWorkspaceImage", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("ImageId" => ImageId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ deploy_workspace_applications(workspace_id) deploy_workspace_applications(workspace_id, params::Dict{String,<:Any}) Deploys associated applications to the specified WorkSpace # Arguments - `workspace_id`: The identifier of the WorkSpace. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Force"`: Indicates whether the force flag is applied for the specified WorkSpace. When the force flag is enabled, it allows previously failed deployments to be retried. """ function deploy_workspace_applications( WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeployWorkspaceApplications", Dict{String,Any}("WorkspaceId" => WorkspaceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function deploy_workspace_applications( WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DeployWorkspaceApplications", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("WorkspaceId" => WorkspaceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ deregister_workspace_directory(directory_id) deregister_workspace_directory(directory_id, params::Dict{String,<:Any}) Deregisters the specified directory. This operation is asynchronous and returns before the WorkSpace directory is deregistered. If any WorkSpaces are registered to this directory, you must remove them before you can deregister the directory. Simple AD and AD Connector are made available to you free of charge to use with WorkSpaces. If there are no WorkSpaces being used with your Simple AD or AD Connector directory for 30 consecutive days, this directory will be automatically deregistered for use with Amazon WorkSpaces, and you will be charged for this directory as per the Directory Service pricing terms. To delete empty directories, see Delete the Directory for Your WorkSpaces. If you delete your Simple AD or AD Connector directory, you can always create a new one when you want to start using WorkSpaces again. # Arguments - `directory_id`: The identifier of the directory. If any WorkSpaces are registered to this directory, you must remove them before you deregister the directory, or you will receive an OperationNotSupportedException error. """ function deregister_workspace_directory( DirectoryId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DeregisterWorkspaceDirectory", Dict{String,Any}("DirectoryId" => DirectoryId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function deregister_workspace_directory( DirectoryId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DeregisterWorkspaceDirectory", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("DirectoryId" => DirectoryId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_account() describe_account(params::Dict{String,<:Any}) Retrieves a list that describes the configuration of Bring Your Own License (BYOL) for the specified account. """ function describe_account(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeAccount"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function describe_account( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeAccount", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ describe_account_modifications() describe_account_modifications(params::Dict{String,<:Any}) Retrieves a list that describes modifications to the configuration of Bring Your Own License (BYOL) for the specified account. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_account_modifications(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeAccountModifications"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_account_modifications( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeAccountModifications", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_application_associations(application_id, associated_resource_types) describe_application_associations(application_id, associated_resource_types, params::Dict{String,<:Any}) Describes the associations between the application and the specified associated resources. # Arguments - `application_id`: The identifier of the specified application. - `associated_resource_types`: The resource type of the associated resources. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of associations to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_application_associations( ApplicationId, AssociatedResourceTypes; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeApplicationAssociations", Dict{String,Any}( "ApplicationId" => ApplicationId, "AssociatedResourceTypes" => AssociatedResourceTypes, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_application_associations( ApplicationId, AssociatedResourceTypes, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeApplicationAssociations", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ApplicationId" => ApplicationId, "AssociatedResourceTypes" => AssociatedResourceTypes, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_applications() describe_applications(params::Dict{String,<:Any}) Describes the specified applications by filtering based on their compute types, license availability, operating systems, and owners. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ApplicationIds"`: The identifiers of one or more applications. - `"ComputeTypeNames"`: The compute types supported by the applications. - `"LicenseType"`: The license availability for the applications. - `"MaxResults"`: The maximum number of applications to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. - `"OperatingSystemNames"`: The operating systems supported by the applications. - `"Owner"`: The owner of the applications. """ function describe_applications(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeApplications"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function describe_applications( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeApplications", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_bundle_associations(associated_resource_types, bundle_id) describe_bundle_associations(associated_resource_types, bundle_id, params::Dict{String,<:Any}) Describes the associations between the applications and the specified bundle. # Arguments - `associated_resource_types`: The resource types of the associated resource. - `bundle_id`: The identifier of the bundle. """ function describe_bundle_associations( AssociatedResourceTypes, BundleId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeBundleAssociations", Dict{String,Any}( "AssociatedResourceTypes" => AssociatedResourceTypes, "BundleId" => BundleId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_bundle_associations( AssociatedResourceTypes, BundleId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeBundleAssociations", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AssociatedResourceTypes" => AssociatedResourceTypes, "BundleId" => BundleId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_client_branding(resource_id) describe_client_branding(resource_id, params::Dict{String,<:Any}) Describes the specified client branding. Client branding allows you to customize the log in page of various device types for your users. You can add your company logo, the support email address, support link, link to reset password, and a custom message for users trying to sign in. Only device types that have branding information configured will be shown in the response. # Arguments - `resource_id`: The directory identifier of the WorkSpace for which you want to view client branding information. """ function describe_client_branding( ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeClientBranding", Dict{String,Any}("ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_client_branding( ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeClientBranding", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceId" => ResourceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_client_properties(resource_ids) describe_client_properties(resource_ids, params::Dict{String,<:Any}) Retrieves a list that describes one or more specified Amazon WorkSpaces clients. # Arguments - `resource_ids`: The resource identifier, in the form of directory IDs. """ function describe_client_properties( ResourceIds; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeClientProperties", Dict{String,Any}("ResourceIds" => ResourceIds); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_client_properties( ResourceIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeClientProperties", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceIds" => ResourceIds), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_connect_client_add_ins(resource_id) describe_connect_client_add_ins(resource_id, params::Dict{String,<:Any}) Retrieves a list of Amazon Connect client add-ins that have been created. # Arguments - `resource_id`: The directory identifier for which the client add-in is configured. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of items to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_connect_client_add_ins( ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeConnectClientAddIns", Dict{String,Any}("ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_connect_client_add_ins( ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeConnectClientAddIns", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceId" => ResourceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_connection_alias_permissions(alias_id) describe_connection_alias_permissions(alias_id, params::Dict{String,<:Any}) Describes the permissions that the owner of a connection alias has granted to another Amazon Web Services account for the specified connection alias. For more information, see Cross-Region Redirection for Amazon WorkSpaces. # Arguments - `alias_id`: The identifier of the connection alias. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of results to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_connection_alias_permissions( AliasId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeConnectionAliasPermissions", Dict{String,Any}("AliasId" => AliasId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_connection_alias_permissions( AliasId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeConnectionAliasPermissions", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("AliasId" => AliasId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_connection_aliases() describe_connection_aliases(params::Dict{String,<:Any}) Retrieves a list that describes the connection aliases used for cross-Region redirection. For more information, see Cross-Region Redirection for Amazon WorkSpaces. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"AliasIds"`: The identifiers of the connection aliases to describe. - `"Limit"`: The maximum number of connection aliases to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. - `"ResourceId"`: The identifier of the directory associated with the connection alias. """ function describe_connection_aliases(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeConnectionAliases"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function describe_connection_aliases( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeConnectionAliases", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_image_associations(associated_resource_types, image_id) describe_image_associations(associated_resource_types, image_id, params::Dict{String,<:Any}) Describes the associations between the applications and the specified image. # Arguments - `associated_resource_types`: The resource types of the associated resource. - `image_id`: The identifier of the image. """ function describe_image_associations( AssociatedResourceTypes, ImageId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeImageAssociations", Dict{String,Any}( "AssociatedResourceTypes" => AssociatedResourceTypes, "ImageId" => ImageId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_image_associations( AssociatedResourceTypes, ImageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeImageAssociations", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AssociatedResourceTypes" => AssociatedResourceTypes, "ImageId" => ImageId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_ip_groups() describe_ip_groups(params::Dict{String,<:Any}) Describes one or more of your IP access control groups. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"GroupIds"`: The identifiers of one or more IP access control groups. - `"MaxResults"`: The maximum number of items to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_ip_groups(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeIpGroups"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function describe_ip_groups( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeIpGroups", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ describe_tags(resource_id) describe_tags(resource_id, params::Dict{String,<:Any}) Describes the specified tags for the specified WorkSpaces resource. # Arguments - `resource_id`: The identifier of the WorkSpaces resource. The supported resource types are WorkSpaces, registered directories, images, custom bundles, IP access control groups, and connection aliases. """ function describe_tags(ResourceId; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeTags", Dict{String,Any}("ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_tags( ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeTags", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceId" => ResourceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_workspace_associations(associated_resource_types, workspace_id) describe_workspace_associations(associated_resource_types, workspace_id, params::Dict{String,<:Any}) Describes the associations betweens applications and the specified WorkSpace. # Arguments - `associated_resource_types`: The resource types of the associated resources. - `workspace_id`: The identifier of the WorkSpace. """ function describe_workspace_associations( AssociatedResourceTypes, WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaceAssociations", Dict{String,Any}( "AssociatedResourceTypes" => AssociatedResourceTypes, "WorkspaceId" => WorkspaceId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_workspace_associations( AssociatedResourceTypes, WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeWorkspaceAssociations", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AssociatedResourceTypes" => AssociatedResourceTypes, "WorkspaceId" => WorkspaceId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_workspace_bundles() describe_workspace_bundles(params::Dict{String,<:Any}) Retrieves a list that describes the available WorkSpace bundles. You can filter the results using either bundle ID or owner, but not both. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"BundleIds"`: The identifiers of the bundles. You cannot combine this parameter with any other filter. - `"NextToken"`: The token for the next set of results. (You received this token from a previous call.) - `"Owner"`: The owner of the bundles. You cannot combine this parameter with any other filter. To describe the bundles provided by Amazon Web Services, specify AMAZON. To describe the bundles that belong to your account, don't specify a value. """ function describe_workspace_bundles(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeWorkspaceBundles"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function describe_workspace_bundles( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaceBundles", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_workspace_directories() describe_workspace_directories(params::Dict{String,<:Any}) Describes the available directories that are registered with Amazon WorkSpaces. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DirectoryIds"`: The identifiers of the directories. If the value is null, all directories are retrieved. - `"Limit"`: The maximum number of directories to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_workspace_directories(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeWorkspaceDirectories"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_workspace_directories( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaceDirectories", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_workspace_image_permissions(image_id) describe_workspace_image_permissions(image_id, params::Dict{String,<:Any}) Describes the permissions that the owner of an image has granted to other Amazon Web Services accounts for an image. # Arguments - `image_id`: The identifier of the image. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of items to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_workspace_image_permissions( ImageId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaceImagePermissions", Dict{String,Any}("ImageId" => ImageId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_workspace_image_permissions( ImageId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaceImagePermissions", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("ImageId" => ImageId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_workspace_images() describe_workspace_images(params::Dict{String,<:Any}) Retrieves a list that describes one or more specified images, if the image identifiers are provided. Otherwise, all images in the account are described. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ImageIds"`: The identifier of the image. - `"ImageType"`: The type (owned or shared) of the image. - `"MaxResults"`: The maximum number of items to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function describe_workspace_images(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeWorkspaceImages"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function describe_workspace_images( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaceImages", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_workspace_snapshots(workspace_id) describe_workspace_snapshots(workspace_id, params::Dict{String,<:Any}) Describes the snapshots for the specified WorkSpace. # Arguments - `workspace_id`: The identifier of the WorkSpace. """ function describe_workspace_snapshots( WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaceSnapshots", Dict{String,Any}("WorkspaceId" => WorkspaceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_workspace_snapshots( WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DescribeWorkspaceSnapshots", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("WorkspaceId" => WorkspaceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ describe_workspaces() describe_workspaces(params::Dict{String,<:Any}) Describes the specified WorkSpaces. You can filter the results by using the bundle identifier, directory identifier, or owner, but you can specify only one filter at a time. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"BundleId"`: The identifier of the bundle. All WorkSpaces that are created from this bundle are retrieved. You cannot combine this parameter with any other filter. - `"DirectoryId"`: The identifier of the directory. In addition, you can optionally specify a specific directory user (see UserName). You cannot combine this parameter with any other filter. - `"Limit"`: The maximum number of items to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. - `"UserName"`: The name of the directory user. You must specify this parameter with DirectoryId. - `"WorkspaceIds"`: The identifiers of the WorkSpaces. You cannot combine this parameter with any other filter. Because the CreateWorkspaces operation is asynchronous, the identifier it returns is not immediately available. If you immediately call DescribeWorkspaces with this identifier, no information is returned. - `"WorkspaceName"`: The name of the user-decoupled WorkSpace. """ function describe_workspaces(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "DescribeWorkspaces"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function describe_workspaces( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspaces", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ describe_workspaces_connection_status() describe_workspaces_connection_status(params::Dict{String,<:Any}) Describes the connection status of the specified WorkSpaces. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. - `"WorkspaceIds"`: The identifiers of the WorkSpaces. You can specify up to 25 WorkSpaces. """ function describe_workspaces_connection_status(; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspacesConnectionStatus"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function describe_workspaces_connection_status( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DescribeWorkspacesConnectionStatus", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_connection_alias(alias_id) disassociate_connection_alias(alias_id, params::Dict{String,<:Any}) Disassociates a connection alias from a directory. Disassociating a connection alias disables cross-Region redirection between two directories in different Regions. For more information, see Cross-Region Redirection for Amazon WorkSpaces. Before performing this operation, call DescribeConnectionAliases to make sure that the current state of the connection alias is CREATED. # Arguments - `alias_id`: The identifier of the connection alias to disassociate. """ function disassociate_connection_alias( AliasId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DisassociateConnectionAlias", Dict{String,Any}("AliasId" => AliasId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_connection_alias( AliasId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DisassociateConnectionAlias", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("AliasId" => AliasId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_ip_groups(directory_id, group_ids) disassociate_ip_groups(directory_id, group_ids, params::Dict{String,<:Any}) Disassociates the specified IP access control group from the specified directory. # Arguments - `directory_id`: The identifier of the directory. - `group_ids`: The identifiers of one or more IP access control groups. """ function disassociate_ip_groups( DirectoryId, GroupIds; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DisassociateIpGroups", Dict{String,Any}("DirectoryId" => DirectoryId, "GroupIds" => GroupIds); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_ip_groups( DirectoryId, GroupIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DisassociateIpGroups", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("DirectoryId" => DirectoryId, "GroupIds" => GroupIds), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_workspace_application(application_id, workspace_id) disassociate_workspace_application(application_id, workspace_id, params::Dict{String,<:Any}) Disassociates the specified application from a WorkSpace. # Arguments - `application_id`: The identifier of the application. - `workspace_id`: The identifier of the WorkSpace. """ function disassociate_workspace_application( ApplicationId, WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "DisassociateWorkspaceApplication", Dict{String,Any}("ApplicationId" => ApplicationId, "WorkspaceId" => WorkspaceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_workspace_application( ApplicationId, WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "DisassociateWorkspaceApplication", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ApplicationId" => ApplicationId, "WorkspaceId" => WorkspaceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_account_link() get_account_link(params::Dict{String,<:Any}) Retrieves account link information. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"LinkId"`: The identifier of the account to link. - `"LinkedAccountId"`: The identifier of the account link """ function get_account_link(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "GetAccountLink"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function get_account_link( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "GetAccountLink", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ import_client_branding(resource_id) import_client_branding(resource_id, params::Dict{String,<:Any}) Imports client branding. Client branding allows you to customize your WorkSpace's client login portal. You can tailor your login portal company logo, the support email address, support link, link to reset password, and a custom message for users trying to sign in. After you import client branding, the default branding experience for the specified platform type is replaced with the imported experience You must specify at least one platform type when importing client branding. You can import up to 6 MB of data with each request. If your request exceeds this limit, you can import client branding for different platform types using separate requests. In each platform type, the SupportEmail and SupportLink parameters are mutually exclusive. You can specify only one parameter for each platform type, but not both. Imported data can take up to a minute to appear in the WorkSpaces client. # Arguments - `resource_id`: The directory identifier of the WorkSpace for which you want to import client branding. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DeviceTypeAndroid"`: The branding information to import for Android devices. - `"DeviceTypeIos"`: The branding information to import for iOS devices. - `"DeviceTypeLinux"`: The branding information to import for Linux devices. - `"DeviceTypeOsx"`: The branding information to import for macOS devices. - `"DeviceTypeWeb"`: The branding information to import for web access. - `"DeviceTypeWindows"`: The branding information to import for Windows devices. """ function import_client_branding( ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ImportClientBranding", Dict{String,Any}("ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function import_client_branding( ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ImportClientBranding", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceId" => ResourceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ import_workspace_image(ec2_image_id, image_description, image_name, ingestion_process) import_workspace_image(ec2_image_id, image_description, image_name, ingestion_process, params::Dict{String,<:Any}) Imports the specified Windows 10 or 11 Bring Your Own License (BYOL) image into Amazon WorkSpaces. The image must be an already licensed Amazon EC2 image that is in your Amazon Web Services account, and you must own the image. For more information about creating BYOL images, see Bring Your Own Windows Desktop Licenses. # Arguments - `ec2_image_id`: The identifier of the EC2 image. - `image_description`: The description of the WorkSpace image. - `image_name`: The name of the WorkSpace image. - `ingestion_process`: The ingestion process to be used when importing the image, depending on which protocol you want to use for your BYOL Workspace image, either PCoIP, WorkSpaces Streaming Protocol (WSP), or bring your own protocol (BYOP). To use WSP, specify a value that ends in _WSP. To use PCoIP, specify a value that does not end in _WSP. To use BYOP, specify a value that ends in _BYOP. For non-GPU-enabled bundles (bundles other than Graphics or GraphicsPro), specify BYOL_REGULAR, BYOL_REGULAR_WSP, or BYOL_REGULAR_BYOP, depending on the protocol. The BYOL_REGULAR_BYOP and BYOL_GRAPHICS_G4DN_BYOP values are only supported by Amazon WorkSpaces Core. Contact your account team to be allow-listed to use these values. For more information, see Amazon WorkSpaces Core. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Applications"`: If specified, the version of Microsoft Office to subscribe to. Valid only for Windows 10 and 11 BYOL images. For more information about subscribing to Office for BYOL images, see Bring Your Own Windows Desktop Licenses. Although this parameter is an array, only one item is allowed at this time. Windows 11 only supports Microsoft_Office_2019. - `"Tags"`: The tags. Each WorkSpaces resource can have a maximum of 50 tags. """ function import_workspace_image( Ec2ImageId, ImageDescription, ImageName, IngestionProcess; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ImportWorkspaceImage", Dict{String,Any}( "Ec2ImageId" => Ec2ImageId, "ImageDescription" => ImageDescription, "ImageName" => ImageName, "IngestionProcess" => IngestionProcess, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function import_workspace_image( Ec2ImageId, ImageDescription, ImageName, IngestionProcess, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ImportWorkspaceImage", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "Ec2ImageId" => Ec2ImageId, "ImageDescription" => ImageDescription, "ImageName" => ImageName, "IngestionProcess" => IngestionProcess, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_account_links() list_account_links(params::Dict{String,<:Any}) Lists all account links. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"LinkStatusFilter"`: Filters the account based on their link status. - `"MaxResults"`: The maximum number of accounts to return. - `"NextToken"`: The token to use to retrieve the next page of results. This value is null when there are no more results to return. """ function list_account_links(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "ListAccountLinks"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_account_links( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ListAccountLinks", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ list_available_management_cidr_ranges(management_cidr_range_constraint) list_available_management_cidr_ranges(management_cidr_range_constraint, params::Dict{String,<:Any}) Retrieves a list of IP address ranges, specified as IPv4 CIDR blocks, that you can use for the network management interface when you enable Bring Your Own License (BYOL). This operation can be run only by Amazon Web Services accounts that are enabled for BYOL. If your account isn't enabled for BYOL, you'll receive an AccessDeniedException error. The management network interface is connected to a secure Amazon WorkSpaces management network. It is used for interactive streaming of the WorkSpace desktop to Amazon WorkSpaces clients, and to allow Amazon WorkSpaces to manage the WorkSpace. # Arguments - `management_cidr_range_constraint`: The IP address range to search. Specify an IP address range that is compatible with your network and in CIDR notation (that is, specify the range as an IPv4 CIDR block). # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: The maximum number of items to return. - `"NextToken"`: If you received a NextToken from a previous call that was paginated, provide this token to receive the next set of results. """ function list_available_management_cidr_ranges( ManagementCidrRangeConstraint; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ListAvailableManagementCidrRanges", Dict{String,Any}("ManagementCidrRangeConstraint" => ManagementCidrRangeConstraint); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_available_management_cidr_ranges( ManagementCidrRangeConstraint, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ListAvailableManagementCidrRanges", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ManagementCidrRangeConstraint" => ManagementCidrRangeConstraint ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ migrate_workspace(bundle_id, source_workspace_id) migrate_workspace(bundle_id, source_workspace_id, params::Dict{String,<:Any}) Migrates a WorkSpace from one operating system or bundle type to another, while retaining the data on the user volume. The migration process recreates the WorkSpace by using a new root volume from the target bundle image and the user volume from the last available snapshot of the original WorkSpace. During migration, the original D:Users%USERNAME% user profile folder is renamed to D:Users%USERNAME%MMddyyTHHmmss%.NotMigrated. A new D:Users%USERNAME% folder is generated by the new OS. Certain files in the old user profile are moved to the new user profile. For available migration scenarios, details about what happens during migration, and best practices, see Migrate a WorkSpace. # Arguments - `bundle_id`: The identifier of the target bundle type to migrate the WorkSpace to. - `source_workspace_id`: The identifier of the WorkSpace to migrate from. """ function migrate_workspace( BundleId, SourceWorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "MigrateWorkspace", Dict{String,Any}("BundleId" => BundleId, "SourceWorkspaceId" => SourceWorkspaceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function migrate_workspace( BundleId, SourceWorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "MigrateWorkspace", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "BundleId" => BundleId, "SourceWorkspaceId" => SourceWorkspaceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_account() modify_account(params::Dict{String,<:Any}) Modifies the configuration of Bring Your Own License (BYOL) for the specified account. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DedicatedTenancyManagementCidrRange"`: The IP address range, specified as an IPv4 CIDR block, for the management network interface. Specify an IP address range that is compatible with your network and in CIDR notation (that is, specify the range as an IPv4 CIDR block). The CIDR block size must be /16 (for example, 203.0.113.25/16). It must also be specified as available by the ListAvailableManagementCidrRanges operation. - `"DedicatedTenancySupport"`: The status of BYOL. """ function modify_account(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "ModifyAccount"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function modify_account( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifyAccount", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ modify_certificate_based_auth_properties(resource_id) modify_certificate_based_auth_properties(resource_id, params::Dict{String,<:Any}) Modifies the properties of the certificate-based authentication you want to use with your WorkSpaces. # Arguments - `resource_id`: The resource identifiers, in the form of directory IDs. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"CertificateBasedAuthProperties"`: The properties of the certificate-based authentication. - `"PropertiesToDelete"`: The properties of the certificate-based authentication you want to delete. """ function modify_certificate_based_auth_properties( ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifyCertificateBasedAuthProperties", Dict{String,Any}("ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_certificate_based_auth_properties( ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifyCertificateBasedAuthProperties", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceId" => ResourceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_client_properties(client_properties, resource_id) modify_client_properties(client_properties, resource_id, params::Dict{String,<:Any}) Modifies the properties of the specified Amazon WorkSpaces clients. # Arguments - `client_properties`: Information about the Amazon WorkSpaces client. - `resource_id`: The resource identifiers, in the form of directory IDs. """ function modify_client_properties( ClientProperties, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifyClientProperties", Dict{String,Any}( "ClientProperties" => ClientProperties, "ResourceId" => ResourceId ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_client_properties( ClientProperties, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifyClientProperties", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ClientProperties" => ClientProperties, "ResourceId" => ResourceId ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_saml_properties(resource_id) modify_saml_properties(resource_id, params::Dict{String,<:Any}) Modifies multiple properties related to SAML 2.0 authentication, including the enablement status, user access URL, and relay state parameter name that are used for configuring federation with an SAML 2.0 identity provider. # Arguments - `resource_id`: The directory identifier for which you want to configure SAML properties. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"PropertiesToDelete"`: The SAML properties to delete as part of your request. Specify one of the following options: SAML_PROPERTIES_USER_ACCESS_URL to delete the user access URL. SAML_PROPERTIES_RELAY_STATE_PARAMETER_NAME to delete the relay state parameter name. - `"SamlProperties"`: The properties for configuring SAML 2.0 authentication. """ function modify_saml_properties( ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifySamlProperties", Dict{String,Any}("ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_saml_properties( ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifySamlProperties", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceId" => ResourceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_selfservice_permissions(resource_id, selfservice_permissions) modify_selfservice_permissions(resource_id, selfservice_permissions, params::Dict{String,<:Any}) Modifies the self-service WorkSpace management capabilities for your users. For more information, see Enable Self-Service WorkSpace Management Capabilities for Your Users. # Arguments - `resource_id`: The identifier of the directory. - `selfservice_permissions`: The permissions to enable or disable self-service capabilities. """ function modify_selfservice_permissions( ResourceId, SelfservicePermissions; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifySelfservicePermissions", Dict{String,Any}( "ResourceId" => ResourceId, "SelfservicePermissions" => SelfservicePermissions ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_selfservice_permissions( ResourceId, SelfservicePermissions, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifySelfservicePermissions", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ResourceId" => ResourceId, "SelfservicePermissions" => SelfservicePermissions, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_workspace_access_properties(resource_id, workspace_access_properties) modify_workspace_access_properties(resource_id, workspace_access_properties, params::Dict{String,<:Any}) Specifies which devices and operating systems users can use to access their WorkSpaces. For more information, see Control Device Access. # Arguments - `resource_id`: The identifier of the directory. - `workspace_access_properties`: The device types and operating systems to enable or disable for access. """ function modify_workspace_access_properties( ResourceId, WorkspaceAccessProperties; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifyWorkspaceAccessProperties", Dict{String,Any}( "ResourceId" => ResourceId, "WorkspaceAccessProperties" => WorkspaceAccessProperties, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_workspace_access_properties( ResourceId, WorkspaceAccessProperties, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifyWorkspaceAccessProperties", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ResourceId" => ResourceId, "WorkspaceAccessProperties" => WorkspaceAccessProperties, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_workspace_creation_properties(resource_id, workspace_creation_properties) modify_workspace_creation_properties(resource_id, workspace_creation_properties, params::Dict{String,<:Any}) Modify the default properties used to create WorkSpaces. # Arguments - `resource_id`: The identifier of the directory. - `workspace_creation_properties`: The default properties for creating WorkSpaces. """ function modify_workspace_creation_properties( ResourceId, WorkspaceCreationProperties; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifyWorkspaceCreationProperties", Dict{String,Any}( "ResourceId" => ResourceId, "WorkspaceCreationProperties" => WorkspaceCreationProperties, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_workspace_creation_properties( ResourceId, WorkspaceCreationProperties, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifyWorkspaceCreationProperties", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "ResourceId" => ResourceId, "WorkspaceCreationProperties" => WorkspaceCreationProperties, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_workspace_properties(workspace_id) modify_workspace_properties(workspace_id, params::Dict{String,<:Any}) Modifies the specified WorkSpace properties. For important information about how to modify the size of the root and user volumes, see Modify a WorkSpace. The MANUAL running mode value is only supported by Amazon WorkSpaces Core. Contact your account team to be allow-listed to use this value. For more information, see Amazon WorkSpaces Core. # Arguments - `workspace_id`: The identifier of the WorkSpace. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"DataReplication"`: Indicates the data replication status. - `"WorkspaceProperties"`: The properties of the WorkSpace. """ function modify_workspace_properties( WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifyWorkspaceProperties", Dict{String,Any}("WorkspaceId" => WorkspaceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_workspace_properties( WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifyWorkspaceProperties", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("WorkspaceId" => WorkspaceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ modify_workspace_state(workspace_id, workspace_state) modify_workspace_state(workspace_id, workspace_state, params::Dict{String,<:Any}) Sets the state of the specified WorkSpace. To maintain a WorkSpace without being interrupted, set the WorkSpace state to ADMIN_MAINTENANCE. WorkSpaces in this state do not respond to requests to reboot, stop, start, rebuild, or restore. An AutoStop WorkSpace in this state is not stopped. Users cannot log into a WorkSpace in the ADMIN_MAINTENANCE state. # Arguments - `workspace_id`: The identifier of the WorkSpace. - `workspace_state`: The WorkSpace state. """ function modify_workspace_state( WorkspaceId, WorkspaceState; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "ModifyWorkspaceState", Dict{String,Any}("WorkspaceId" => WorkspaceId, "WorkspaceState" => WorkspaceState); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function modify_workspace_state( WorkspaceId, WorkspaceState, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "ModifyWorkspaceState", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "WorkspaceId" => WorkspaceId, "WorkspaceState" => WorkspaceState ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ reboot_workspaces(reboot_workspace_requests) reboot_workspaces(reboot_workspace_requests, params::Dict{String,<:Any}) Reboots the specified WorkSpaces. You cannot reboot a WorkSpace unless its state is AVAILABLE, UNHEALTHY, or REBOOTING. Reboot a WorkSpace in the REBOOTING state only if your WorkSpace has been stuck in the REBOOTING state for over 20 minutes. This operation is asynchronous and returns before the WorkSpaces have rebooted. # Arguments - `reboot_workspace_requests`: The WorkSpaces to reboot. You can specify up to 25 WorkSpaces. """ function reboot_workspaces( RebootWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "RebootWorkspaces", Dict{String,Any}("RebootWorkspaceRequests" => RebootWorkspaceRequests); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function reboot_workspaces( RebootWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "RebootWorkspaces", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("RebootWorkspaceRequests" => RebootWorkspaceRequests), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ rebuild_workspaces(rebuild_workspace_requests) rebuild_workspaces(rebuild_workspace_requests, params::Dict{String,<:Any}) Rebuilds the specified WorkSpace. You cannot rebuild a WorkSpace unless its state is AVAILABLE, ERROR, UNHEALTHY, STOPPED, or REBOOTING. Rebuilding a WorkSpace is a potentially destructive action that can result in the loss of data. For more information, see Rebuild a WorkSpace. This operation is asynchronous and returns before the WorkSpaces have been completely rebuilt. # Arguments - `rebuild_workspace_requests`: The WorkSpace to rebuild. You can specify a single WorkSpace. """ function rebuild_workspaces( RebuildWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "RebuildWorkspaces", Dict{String,Any}("RebuildWorkspaceRequests" => RebuildWorkspaceRequests); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function rebuild_workspaces( RebuildWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "RebuildWorkspaces", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("RebuildWorkspaceRequests" => RebuildWorkspaceRequests), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ register_workspace_directory(directory_id, enable_work_docs) register_workspace_directory(directory_id, enable_work_docs, params::Dict{String,<:Any}) Registers the specified directory. This operation is asynchronous and returns before the WorkSpace directory is registered. If this is the first time you are registering a directory, you will need to create the workspaces_DefaultRole role before you can register a directory. For more information, see Creating the workspaces_DefaultRole Role. # Arguments - `directory_id`: The identifier of the directory. You cannot register a directory if it does not have a status of Active. If the directory does not have a status of Active, you will receive an InvalidResourceStateException error. If you have already registered the maximum number of directories that you can register with Amazon WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister directories that you are not using for WorkSpaces, and try again. - `enable_work_docs`: Indicates whether Amazon WorkDocs is enabled or disabled. If you have enabled this parameter and WorkDocs is not available in the Region, you will receive an OperationNotSupportedException error. Set EnableWorkDocs to disabled, and try again. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"EnableSelfService"`: Indicates whether self-service capabilities are enabled or disabled. - `"SubnetIds"`: The identifiers of the subnets for your virtual private cloud (VPC). Make sure that the subnets are in supported Availability Zones. The subnets must also be in separate Availability Zones. If these conditions are not met, you will receive an OperationNotSupportedException error. - `"Tags"`: The tags associated with the directory. - `"Tenancy"`: Indicates whether your WorkSpace directory is dedicated or shared. To use Bring Your Own License (BYOL) images, this value must be set to DEDICATED and your Amazon Web Services account must be enabled for BYOL. If your account has not been enabled for BYOL, you will receive an InvalidParameterValuesException error. For more information about BYOL images, see Bring Your Own Windows Desktop Images. """ function register_workspace_directory( DirectoryId, EnableWorkDocs; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "RegisterWorkspaceDirectory", Dict{String,Any}("DirectoryId" => DirectoryId, "EnableWorkDocs" => EnableWorkDocs); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function register_workspace_directory( DirectoryId, EnableWorkDocs, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "RegisterWorkspaceDirectory", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "DirectoryId" => DirectoryId, "EnableWorkDocs" => EnableWorkDocs ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ reject_account_link_invitation(link_id) reject_account_link_invitation(link_id, params::Dict{String,<:Any}) Rejects the account link invitation. # Arguments - `link_id`: The identifier of the account link # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"ClientToken"`: The client token of the account link invitation to reject. """ function reject_account_link_invitation( LinkId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "RejectAccountLinkInvitation", Dict{String,Any}("LinkId" => LinkId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function reject_account_link_invitation( LinkId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "RejectAccountLinkInvitation", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("LinkId" => LinkId), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ restore_workspace(workspace_id) restore_workspace(workspace_id, params::Dict{String,<:Any}) Restores the specified WorkSpace to its last known healthy state. You cannot restore a WorkSpace unless its state is AVAILABLE, ERROR, UNHEALTHY, or STOPPED. Restoring a WorkSpace is a potentially destructive action that can result in the loss of data. For more information, see Restore a WorkSpace. This operation is asynchronous and returns before the WorkSpace is completely restored. # Arguments - `workspace_id`: The identifier of the WorkSpace. """ function restore_workspace(WorkspaceId; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "RestoreWorkspace", Dict{String,Any}("WorkspaceId" => WorkspaceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function restore_workspace( WorkspaceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "RestoreWorkspace", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("WorkspaceId" => WorkspaceId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ revoke_ip_rules(group_id, user_rules) revoke_ip_rules(group_id, user_rules, params::Dict{String,<:Any}) Removes one or more rules from the specified IP access control group. # Arguments - `group_id`: The identifier of the group. - `user_rules`: The rules to remove from the group. """ function revoke_ip_rules( GroupId, UserRules; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "RevokeIpRules", Dict{String,Any}("GroupId" => GroupId, "UserRules" => UserRules); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function revoke_ip_rules( GroupId, UserRules, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "RevokeIpRules", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("GroupId" => GroupId, "UserRules" => UserRules), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ start_workspaces(start_workspace_requests) start_workspaces(start_workspace_requests, params::Dict{String,<:Any}) Starts the specified WorkSpaces. You cannot start a WorkSpace unless it has a running mode of AutoStop and a state of STOPPED. # Arguments - `start_workspace_requests`: The WorkSpaces to start. You can specify up to 25 WorkSpaces. """ function start_workspaces( StartWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "StartWorkspaces", Dict{String,Any}("StartWorkspaceRequests" => StartWorkspaceRequests); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function start_workspaces( StartWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "StartWorkspaces", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("StartWorkspaceRequests" => StartWorkspaceRequests), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ stop_workspaces(stop_workspace_requests) stop_workspaces(stop_workspace_requests, params::Dict{String,<:Any}) Stops the specified WorkSpaces. You cannot stop a WorkSpace unless it has a running mode of AutoStop and a state of AVAILABLE, IMPAIRED, UNHEALTHY, or ERROR. # Arguments - `stop_workspace_requests`: The WorkSpaces to stop. You can specify up to 25 WorkSpaces. """ function stop_workspaces( StopWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "StopWorkspaces", Dict{String,Any}("StopWorkspaceRequests" => StopWorkspaceRequests); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function stop_workspaces( StopWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "StopWorkspaces", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("StopWorkspaceRequests" => StopWorkspaceRequests), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ terminate_workspaces(terminate_workspace_requests) terminate_workspaces(terminate_workspace_requests, params::Dict{String,<:Any}) Terminates the specified WorkSpaces. Terminating a WorkSpace is a permanent action and cannot be undone. The user's data is destroyed. If you need to archive any user data, contact Amazon Web Services Support before terminating the WorkSpace. You can terminate a WorkSpace that is in any state except SUSPENDED. This operation is asynchronous and returns before the WorkSpaces have been completely terminated. After a WorkSpace is terminated, the TERMINATED state is returned only briefly before the WorkSpace directory metadata is cleaned up, so this state is rarely returned. To confirm that a WorkSpace is terminated, check for the WorkSpace ID by using DescribeWorkSpaces. If the WorkSpace ID isn't returned, then the WorkSpace has been successfully terminated. Simple AD and AD Connector are made available to you free of charge to use with WorkSpaces. If there are no WorkSpaces being used with your Simple AD or AD Connector directory for 30 consecutive days, this directory will be automatically deregistered for use with Amazon WorkSpaces, and you will be charged for this directory as per the Directory Service pricing terms. To delete empty directories, see Delete the Directory for Your WorkSpaces. If you delete your Simple AD or AD Connector directory, you can always create a new one when you want to start using WorkSpaces again. # Arguments - `terminate_workspace_requests`: The WorkSpaces to terminate. You can specify up to 25 WorkSpaces. """ function terminate_workspaces( TerminateWorkspaceRequests; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "TerminateWorkspaces", Dict{String,Any}("TerminateWorkspaceRequests" => TerminateWorkspaceRequests); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function terminate_workspaces( TerminateWorkspaceRequests, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "TerminateWorkspaces", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "TerminateWorkspaceRequests" => TerminateWorkspaceRequests ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_connect_client_add_in(add_in_id, resource_id) update_connect_client_add_in(add_in_id, resource_id, params::Dict{String,<:Any}) Updates a Amazon Connect client add-in. Use this action to update the name and endpoint URL of a Amazon Connect client add-in. # Arguments - `add_in_id`: The identifier of the client add-in to update. - `resource_id`: The directory identifier for which the client add-in is configured. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Name"`: The name of the client add-in. - `"URL"`: The endpoint URL of the Amazon Connect client add-in. """ function update_connect_client_add_in( AddInId, ResourceId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "UpdateConnectClientAddIn", Dict{String,Any}("AddInId" => AddInId, "ResourceId" => ResourceId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_connect_client_add_in( AddInId, ResourceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "UpdateConnectClientAddIn", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("AddInId" => AddInId, "ResourceId" => ResourceId), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_connection_alias_permission(alias_id, connection_alias_permission) update_connection_alias_permission(alias_id, connection_alias_permission, params::Dict{String,<:Any}) Shares or unshares a connection alias with one account by specifying whether that account has permission to associate the connection alias with a directory. If the association permission is granted, the connection alias is shared with that account. If the association permission is revoked, the connection alias is unshared with the account. For more information, see Cross-Region Redirection for Amazon WorkSpaces. Before performing this operation, call DescribeConnectionAliases to make sure that the current state of the connection alias is CREATED. To delete a connection alias that has been shared, the shared account must first disassociate the connection alias from any directories it has been associated with. Then you must unshare the connection alias from the account it has been shared with. You can delete a connection alias only after it is no longer shared with any accounts or associated with any directories. # Arguments - `alias_id`: The identifier of the connection alias that you want to update permissions for. - `connection_alias_permission`: Indicates whether to share or unshare the connection alias with the specified Amazon Web Services account. """ function update_connection_alias_permission( AliasId, ConnectionAliasPermission; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "UpdateConnectionAliasPermission", Dict{String,Any}( "AliasId" => AliasId, "ConnectionAliasPermission" => ConnectionAliasPermission ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_connection_alias_permission( AliasId, ConnectionAliasPermission, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "UpdateConnectionAliasPermission", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AliasId" => AliasId, "ConnectionAliasPermission" => ConnectionAliasPermission, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_rules_of_ip_group(group_id, user_rules) update_rules_of_ip_group(group_id, user_rules, params::Dict{String,<:Any}) Replaces the current rules of the specified IP access control group with the specified rules. # Arguments - `group_id`: The identifier of the group. - `user_rules`: One or more rules. """ function update_rules_of_ip_group( GroupId, UserRules; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "UpdateRulesOfIpGroup", Dict{String,Any}("GroupId" => GroupId, "UserRules" => UserRules); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_rules_of_ip_group( GroupId, UserRules, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "UpdateRulesOfIpGroup", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("GroupId" => GroupId, "UserRules" => UserRules), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_workspace_bundle() update_workspace_bundle(params::Dict{String,<:Any}) Updates a WorkSpace bundle with a new image. For more information about updating WorkSpace bundles, see Update a Custom WorkSpaces Bundle. Existing WorkSpaces aren't automatically updated when you update the bundle that they're based on. To update existing WorkSpaces that are based on a bundle that you've updated, you must either rebuild the WorkSpaces or delete and recreate them. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"BundleId"`: The identifier of the bundle. - `"ImageId"`: The identifier of the image. """ function update_workspace_bundle(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces( "UpdateWorkspaceBundle"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function update_workspace_bundle( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces( "UpdateWorkspaceBundle", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_workspace_image_permission(allow_copy_image, image_id, shared_account_id) update_workspace_image_permission(allow_copy_image, image_id, shared_account_id, params::Dict{String,<:Any}) Shares or unshares an image with one account in the same Amazon Web Services Region by specifying whether that account has permission to copy the image. If the copy image permission is granted, the image is shared with that account. If the copy image permission is revoked, the image is unshared with the account. After an image has been shared, the recipient account can copy the image to other Regions as needed. In the China (Ningxia) Region, you can copy images only within the same Region. In Amazon Web Services GovCloud (US), to copy images to and from other Regions, contact Amazon Web Services Support. For more information about sharing images, see Share or Unshare a Custom WorkSpaces Image. To delete an image that has been shared, you must unshare the image before you delete it. Sharing Bring Your Own License (BYOL) images across Amazon Web Services accounts isn't supported at this time in Amazon Web Services GovCloud (US). To share BYOL images across accounts in Amazon Web Services GovCloud (US), contact Amazon Web Services Support. # Arguments - `allow_copy_image`: The permission to copy the image. This permission can be revoked only after an image has been shared. - `image_id`: The identifier of the image. - `shared_account_id`: The identifier of the Amazon Web Services account to share or unshare the image with. Before sharing the image, confirm that you are sharing to the correct Amazon Web Services account ID. """ function update_workspace_image_permission( AllowCopyImage, ImageId, SharedAccountId; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "UpdateWorkspaceImagePermission", Dict{String,Any}( "AllowCopyImage" => AllowCopyImage, "ImageId" => ImageId, "SharedAccountId" => SharedAccountId, ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_workspace_image_permission( AllowCopyImage, ImageId, SharedAccountId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces( "UpdateWorkspaceImagePermission", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "AllowCopyImage" => AllowCopyImage, "ImageId" => ImageId, "SharedAccountId" => SharedAccountId, ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
20901
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: workspaces_thin_client using AWS.Compat using AWS.UUIDs """ create_environment(desktop_arn) create_environment(desktop_arn, params::Dict{String,<:Any}) Creates an environment for your thin client devices. # Arguments - `desktop_arn`: The Amazon Resource Name (ARN) of the desktop to stream from Amazon WorkSpaces, WorkSpaces Web, or AppStream 2.0. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: Specifies a unique, case-sensitive identifier that you provide to ensure the idempotency of the request. This lets you safely retry the request without accidentally performing the same operation a second time. Passing the same value to a later call to an operation requires that you also pass the same value for all other parameters. We recommend that you use a UUID type of value. If you don't provide this value, then Amazon Web Services generates a random one for you. If you retry the operation with the same ClientToken, but with different parameters, the retry fails with an IdempotentParameterMismatch error. - `"desiredSoftwareSetId"`: The ID of the software set to apply. - `"desktopEndpoint"`: The URL for the identity provider login (only for environments that use AppStream 2.0). - `"deviceCreationTags"`: A map of the key-value pairs of the tag or tags to assign to the newly created devices for this environment. - `"kmsKeyArn"`: The Amazon Resource Name (ARN) of the Key Management Service key to use to encrypt the environment. - `"maintenanceWindow"`: A specification for a time window to apply software updates. - `"name"`: The name for the environment. - `"softwareSetUpdateMode"`: An option to define which software updates to apply. - `"softwareSetUpdateSchedule"`: An option to define if software updates should be applied within a maintenance window. - `"tags"`: A map of the key-value pairs of the tag or tags to assign to the resource. """ function create_environment(desktopArn; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "POST", "/environments", Dict{String,Any}("desktopArn" => desktopArn, "clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_environment( desktopArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_thin_client( "POST", "/environments", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "desktopArn" => desktopArn, "clientToken" => string(uuid4()) ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_device(id) delete_device(id, params::Dict{String,<:Any}) Deletes a thin client device. # Arguments - `id`: The ID of the device to delete. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: Specifies a unique, case-sensitive identifier that you provide to ensure the idempotency of the request. This lets you safely retry the request without accidentally performing the same operation a second time. Passing the same value to a later call to an operation requires that you also pass the same value for all other parameters. We recommend that you use a UUID type of value. If you don't provide this value, then Amazon Web Services generates a random one for you. If you retry the operation with the same ClientToken, but with different parameters, the retry fails with an IdempotentParameterMismatch error. """ function delete_device(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "DELETE", "/devices/$(id)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_device( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "DELETE", "/devices/$(id)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_environment(id) delete_environment(id, params::Dict{String,<:Any}) Deletes an environment. # Arguments - `id`: The ID of the environment to delete. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: Specifies a unique, case-sensitive identifier that you provide to ensure the idempotency of the request. This lets you safely retry the request without accidentally performing the same operation a second time. Passing the same value to a later call to an operation requires that you also pass the same value for all other parameters. We recommend that you use a UUID type of value. If you don't provide this value, then Amazon Web Services generates a random one for you. If you retry the operation with the same ClientToken, but with different parameters, the retry fails with an IdempotentParameterMismatch error. """ function delete_environment(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "DELETE", "/environments/$(id)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_environment( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "DELETE", "/environments/$(id)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ deregister_device(id) deregister_device(id, params::Dict{String,<:Any}) Deregisters a thin client device. # Arguments - `id`: The ID of the device to deregister. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: Specifies a unique, case-sensitive identifier that you provide to ensure the idempotency of the request. This lets you safely retry the request without accidentally performing the same operation a second time. Passing the same value to a later call to an operation requires that you also pass the same value for all other parameters. We recommend that you use a UUID type of value. If you don't provide this value, then Amazon Web Services generates a random one for you. If you retry the operation with the same ClientToken, but with different parameters, the retry fails with an IdempotentParameterMismatch error. - `"targetDeviceStatus"`: The desired new status for the device. """ function deregister_device(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "POST", "/deregister-device/$(id)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function deregister_device( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "POST", "/deregister-device/$(id)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_device(id) get_device(id, params::Dict{String,<:Any}) Returns information for a thin client device. # Arguments - `id`: The ID of the device for which to return information. """ function get_device(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "GET", "/devices/$(id)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function get_device( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "GET", "/devices/$(id)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_environment(id) get_environment(id, params::Dict{String,<:Any}) Returns information for an environment. # Arguments - `id`: The ID of the environment for which to return information. """ function get_environment(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "GET", "/environments/$(id)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function get_environment( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "GET", "/environments/$(id)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_software_set(id) get_software_set(id, params::Dict{String,<:Any}) Returns information for a software set. # Arguments - `id`: The ID of the software set for which to return information. """ function get_software_set(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "GET", "/softwaresets/$(id)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function get_software_set( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "GET", "/softwaresets/$(id)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_devices() list_devices(params::Dict{String,<:Any}) Returns a list of thin client devices. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. - `"nextToken"`: If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. """ function list_devices(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "GET", "/devices"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_devices( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "GET", "/devices", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ list_environments() list_environments(params::Dict{String,<:Any}) Returns a list of environments. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. - `"nextToken"`: If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. """ function list_environments(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "GET", "/environments"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_environments( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "GET", "/environments", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_software_sets() list_software_sets(params::Dict{String,<:Any}) Returns a list of software sets. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. - `"nextToken"`: If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. """ function list_software_sets(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "GET", "/softwaresets"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_software_sets( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "GET", "/softwaresets", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_tags_for_resource(resource_arn) list_tags_for_resource(resource_arn, params::Dict{String,<:Any}) Returns a list of tags for a resource. # Arguments - `resource_arn`: The Amazon Resource Name (ARN) of the resource for which you want to retrieve tags. """ function list_tags_for_resource( resourceArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "GET", "/tags/$(resourceArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_tags_for_resource( resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_thin_client( "GET", "/tags/$(resourceArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ tag_resource(resource_arn, tags) tag_resource(resource_arn, tags, params::Dict{String,<:Any}) Assigns one or more tags (key-value pairs) to the specified resource. # Arguments - `resource_arn`: The Amazon Resource Name (ARN) of the resource that you want to tag. - `tags`: A map of the key-value pairs of the tag or tags to assign to the resource. """ function tag_resource(resourceArn, tags; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "POST", "/tags/$(resourceArn)", Dict{String,Any}("tags" => tags); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function tag_resource( resourceArn, tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_thin_client( "POST", "/tags/$(resourceArn)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tags" => tags), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ untag_resource(resource_arn, tag_keys) untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any}) Removes a tag or tags from a resource. # Arguments - `resource_arn`: The Amazon Resource Name (ARN) of the resource that you want to untag. - `tag_keys`: The keys of the key-value pairs for the tag or tags you want to remove from the specified resource. """ function untag_resource( resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "DELETE", "/tags/$(resourceArn)", Dict{String,Any}("tagKeys" => tagKeys); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function untag_resource( resourceArn, tagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_thin_client( "DELETE", "/tags/$(resourceArn)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_device(id) update_device(id, params::Dict{String,<:Any}) Updates a thin client device. # Arguments - `id`: The ID of the device to update. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"desiredSoftwareSetId"`: The ID of the software set to apply. - `"name"`: The name of the device to update. - `"softwareSetUpdateSchedule"`: An option to define if software updates should be applied within a maintenance window. """ function update_device(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "PATCH", "/devices/$(id)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function update_device( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "PATCH", "/devices/$(id)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_environment(id) update_environment(id, params::Dict{String,<:Any}) Updates an environment. # Arguments - `id`: The ID of the environment to update. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"desiredSoftwareSetId"`: The ID of the software set to apply. - `"desktopArn"`: The Amazon Resource Name (ARN) of the desktop to stream from Amazon WorkSpaces, WorkSpaces Web, or AppStream 2.0. - `"desktopEndpoint"`: The URL for the identity provider login (only for environments that use AppStream 2.0). - `"deviceCreationTags"`: A map of the key-value pairs of the tag or tags to assign to the newly created devices for this environment. - `"maintenanceWindow"`: A specification for a time window to apply software updates. - `"name"`: The name of the environment to update. - `"softwareSetUpdateMode"`: An option to define which software updates to apply. - `"softwareSetUpdateSchedule"`: An option to define if software updates should be applied within a maintenance window. """ function update_environment(id; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_thin_client( "PATCH", "/environments/$(id)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_environment( id, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "PATCH", "/environments/$(id)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_software_set(id, validation_status) update_software_set(id, validation_status, params::Dict{String,<:Any}) Updates a software set. # Arguments - `id`: The ID of the software set to update. - `validation_status`: An option to define if the software set has been validated. """ function update_software_set( id, validationStatus; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_thin_client( "PATCH", "/softwaresets/$(id)", Dict{String,Any}("validationStatus" => validationStatus); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_software_set( id, validationStatus, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_thin_client( "PATCH", "/softwaresets/$(id)", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("validationStatus" => validationStatus), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
78470
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: workspaces_web using AWS.Compat using AWS.UUIDs """ associate_browser_settings(browser_settings_arn, portal_arn) associate_browser_settings(browser_settings_arn, portal_arn, params::Dict{String,<:Any}) Associates a browser settings resource with a web portal. # Arguments - `browser_settings_arn`: The ARN of the browser settings. - `portal_arn`: The ARN of the web portal. """ function associate_browser_settings( browserSettingsArn, portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PUT", "/portals/$(portalArn)/browserSettings", Dict{String,Any}("browserSettingsArn" => browserSettingsArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_browser_settings( browserSettingsArn, portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)/browserSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("browserSettingsArn" => browserSettingsArn), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_ip_access_settings(ip_access_settings_arn, portal_arn) associate_ip_access_settings(ip_access_settings_arn, portal_arn, params::Dict{String,<:Any}) Associates an IP access settings resource with a web portal. # Arguments - `ip_access_settings_arn`: The ARN of the IP access settings. - `portal_arn`: The ARN of the web portal. """ function associate_ip_access_settings( ipAccessSettingsArn, portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PUT", "/portals/$(portalArn)/ipAccessSettings", Dict{String,Any}("ipAccessSettingsArn" => ipAccessSettingsArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_ip_access_settings( ipAccessSettingsArn, portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)/ipAccessSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ipAccessSettingsArn" => ipAccessSettingsArn), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_network_settings(network_settings_arn, portal_arn) associate_network_settings(network_settings_arn, portal_arn, params::Dict{String,<:Any}) Associates a network settings resource with a web portal. # Arguments - `network_settings_arn`: The ARN of the network settings. - `portal_arn`: The ARN of the web portal. """ function associate_network_settings( networkSettingsArn, portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PUT", "/portals/$(portalArn)/networkSettings", Dict{String,Any}("networkSettingsArn" => networkSettingsArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_network_settings( networkSettingsArn, portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)/networkSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("networkSettingsArn" => networkSettingsArn), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_trust_store(portal_arn, trust_store_arn) associate_trust_store(portal_arn, trust_store_arn, params::Dict{String,<:Any}) Associates a trust store with a web portal. # Arguments - `portal_arn`: The ARN of the web portal. - `trust_store_arn`: The ARN of the trust store. """ function associate_trust_store( portalArn, trustStoreArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PUT", "/portals/$(portalArn)/trustStores", Dict{String,Any}("trustStoreArn" => trustStoreArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_trust_store( portalArn, trustStoreArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)/trustStores", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("trustStoreArn" => trustStoreArn), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_user_access_logging_settings(portal_arn, user_access_logging_settings_arn) associate_user_access_logging_settings(portal_arn, user_access_logging_settings_arn, params::Dict{String,<:Any}) Associates a user access logging settings resource with a web portal. # Arguments - `portal_arn`: The ARN of the web portal. - `user_access_logging_settings_arn`: The ARN of the user access logging settings. """ function associate_user_access_logging_settings( portalArn, userAccessLoggingSettingsArn; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)/userAccessLoggingSettings", Dict{String,Any}("userAccessLoggingSettingsArn" => userAccessLoggingSettingsArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_user_access_logging_settings( portalArn, userAccessLoggingSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)/userAccessLoggingSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "userAccessLoggingSettingsArn" => userAccessLoggingSettingsArn ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_user_settings(portal_arn, user_settings_arn) associate_user_settings(portal_arn, user_settings_arn, params::Dict{String,<:Any}) Associates a user settings resource with a web portal. # Arguments - `portal_arn`: The ARN of the web portal. - `user_settings_arn`: The ARN of the user settings. """ function associate_user_settings( portalArn, userSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PUT", "/portals/$(portalArn)/userSettings", Dict{String,Any}("userSettingsArn" => userSettingsArn); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_user_settings( portalArn, userSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)/userSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("userSettingsArn" => userSettingsArn), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_browser_settings(browser_policy) create_browser_settings(browser_policy, params::Dict{String,<:Any}) Creates a browser settings resource that can be associated with a web portal. Once associated with a web portal, browser settings control how the browser will behave once a user starts a streaming session for the web portal. # Arguments - `browser_policy`: A JSON string containing Chrome Enterprise policies that will be applied to all streaming sessions. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"additionalEncryptionContext"`: Additional encryption context of the browser settings. - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"customerManagedKey"`: The custom managed key of the browser settings. - `"tags"`: The tags to add to the browser settings resource. A tag is a key-value pair. """ function create_browser_settings( browserPolicy; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "POST", "/browserSettings", Dict{String,Any}( "browserPolicy" => browserPolicy, "clientToken" => string(uuid4()) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_browser_settings( browserPolicy, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/browserSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "browserPolicy" => browserPolicy, "clientToken" => string(uuid4()) ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_identity_provider(identity_provider_details, identity_provider_name, identity_provider_type, portal_arn) create_identity_provider(identity_provider_details, identity_provider_name, identity_provider_type, portal_arn, params::Dict{String,<:Any}) Creates an identity provider resource that is then associated with a web portal. # Arguments - `identity_provider_details`: The identity provider details. The following list describes the provider detail keys for each identity provider type. For Google and Login with Amazon: client_id client_secret authorize_scopes For Facebook: client_id client_secret authorize_scopes api_version For Sign in with Apple: client_id team_id key_id private_key authorize_scopes For OIDC providers: client_id client_secret attributes_request_method oidc_issuer authorize_scopes authorize_url if not available from discovery URL specified by oidc_issuer key token_url if not available from discovery URL specified by oidc_issuer key attributes_url if not available from discovery URL specified by oidc_issuer key jwks_uri if not available from discovery URL specified by oidc_issuer key For SAML providers: MetadataFile OR MetadataURL IDPSignout (boolean) optional IDPInit (boolean) optional RequestSigningAlgorithm (string) optional - Only accepts rsa-sha256 EncryptedResponses (boolean) optional - `identity_provider_name`: The identity provider name. - `identity_provider_type`: The identity provider type. - `portal_arn`: The ARN of the web portal. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"tags"`: The tags to add to the identity provider resource. A tag is a key-value pair. """ function create_identity_provider( identityProviderDetails, identityProviderName, identityProviderType, portalArn; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/identityProviders", Dict{String,Any}( "identityProviderDetails" => identityProviderDetails, "identityProviderName" => identityProviderName, "identityProviderType" => identityProviderType, "portalArn" => portalArn, "clientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_identity_provider( identityProviderDetails, identityProviderName, identityProviderType, portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/identityProviders", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "identityProviderDetails" => identityProviderDetails, "identityProviderName" => identityProviderName, "identityProviderType" => identityProviderType, "portalArn" => portalArn, "clientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_ip_access_settings(ip_rules) create_ip_access_settings(ip_rules, params::Dict{String,<:Any}) Creates an IP access settings resource that can be associated with a web portal. # Arguments - `ip_rules`: The IP rules of the IP access settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"additionalEncryptionContext"`: Additional encryption context of the IP access settings. - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"customerManagedKey"`: The custom managed key of the IP access settings. - `"description"`: The description of the IP access settings. - `"displayName"`: The display name of the IP access settings. - `"tags"`: The tags to add to the IP access settings resource. A tag is a key-value pair. """ function create_ip_access_settings( ipRules; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "POST", "/ipAccessSettings", Dict{String,Any}("ipRules" => ipRules, "clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_ip_access_settings( ipRules, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "POST", "/ipAccessSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ipRules" => ipRules, "clientToken" => string(uuid4())), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_network_settings(security_group_ids, subnet_ids, vpc_id) create_network_settings(security_group_ids, subnet_ids, vpc_id, params::Dict{String,<:Any}) Creates a network settings resource that can be associated with a web portal. Once associated with a web portal, network settings define how streaming instances will connect with your specified VPC. # Arguments - `security_group_ids`: One or more security groups used to control access from streaming instances to your VPC. - `subnet_ids`: The subnets in which network interfaces are created to connect streaming instances to your VPC. At least two of these subnets must be in different availability zones. - `vpc_id`: The VPC that streaming instances will connect to. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"tags"`: The tags to add to the network settings resource. A tag is a key-value pair. """ function create_network_settings( securityGroupIds, subnetIds, vpcId; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "POST", "/networkSettings", Dict{String,Any}( "securityGroupIds" => securityGroupIds, "subnetIds" => subnetIds, "vpcId" => vpcId, "clientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_network_settings( securityGroupIds, subnetIds, vpcId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/networkSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "securityGroupIds" => securityGroupIds, "subnetIds" => subnetIds, "vpcId" => vpcId, "clientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_portal() create_portal(params::Dict{String,<:Any}) Creates a web portal. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"additionalEncryptionContext"`: The additional encryption context of the portal. - `"authenticationType"`: The type of authentication integration points used when signing into the web portal. Defaults to Standard. Standard web portals are authenticated directly through your identity provider. You need to call CreateIdentityProvider to integrate your identity provider with your web portal. User and group access to your web portal is controlled through your identity provider. IAM Identity Center web portals are authenticated through IAM Identity Center (successor to Single Sign-On). Identity sources (including external identity provider integration), plus user and group access to your web portal, can be configured in the IAM Identity Center. - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"customerManagedKey"`: The customer managed key of the web portal. - `"displayName"`: The name of the web portal. This is not visible to users who log into the web portal. - `"instanceType"`: The type and resources of the underlying instance. - `"maxConcurrentSessions"`: The maximum number of concurrent sessions for the portal. - `"tags"`: The tags to add to the web portal. A tag is a key-value pair. """ function create_portal(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "POST", "/portals", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_portal( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "POST", "/portals", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_trust_store(certificate_list) create_trust_store(certificate_list, params::Dict{String,<:Any}) Creates a trust store that can be associated with a web portal. A trust store contains certificate authority (CA) certificates. Once associated with a web portal, the browser in a streaming session will recognize certificates that have been issued using any of the CAs in the trust store. If your organization has internal websites that use certificates issued by private CAs, you should add the private CA certificate to the trust store. # Arguments - `certificate_list`: A list of CA certificates to be added to the trust store. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"tags"`: The tags to add to the trust store. A tag is a key-value pair. """ function create_trust_store( certificateList; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "POST", "/trustStores", Dict{String,Any}( "certificateList" => certificateList, "clientToken" => string(uuid4()) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_trust_store( certificateList, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/trustStores", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "certificateList" => certificateList, "clientToken" => string(uuid4()) ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_user_access_logging_settings(kinesis_stream_arn) create_user_access_logging_settings(kinesis_stream_arn, params::Dict{String,<:Any}) Creates a user access logging settings resource that can be associated with a web portal. # Arguments - `kinesis_stream_arn`: The ARN of the Kinesis stream. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"tags"`: The tags to add to the user settings resource. A tag is a key-value pair. """ function create_user_access_logging_settings( kinesisStreamArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "POST", "/userAccessLoggingSettings", Dict{String,Any}( "kinesisStreamArn" => kinesisStreamArn, "clientToken" => string(uuid4()) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_user_access_logging_settings( kinesisStreamArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/userAccessLoggingSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "kinesisStreamArn" => kinesisStreamArn, "clientToken" => string(uuid4()) ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_user_settings(copy_allowed, download_allowed, paste_allowed, print_allowed, upload_allowed) create_user_settings(copy_allowed, download_allowed, paste_allowed, print_allowed, upload_allowed, params::Dict{String,<:Any}) Creates a user settings resource that can be associated with a web portal. Once associated with a web portal, user settings control how users can transfer data between a streaming session and the their local devices. # Arguments - `copy_allowed`: Specifies whether the user can copy text from the streaming session to the local device. - `download_allowed`: Specifies whether the user can download files from the streaming session to the local device. - `paste_allowed`: Specifies whether the user can paste text from the local device to the streaming session. - `print_allowed`: Specifies whether the user can print to the local device. - `upload_allowed`: Specifies whether the user can upload files from the local device to the streaming session. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"additionalEncryptionContext"`: The additional encryption context of the user settings. - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"cookieSynchronizationConfiguration"`: The configuration that specifies which cookies should be synchronized from the end user's local browser to the remote browser. - `"customerManagedKey"`: The customer managed key used to encrypt sensitive information in the user settings. - `"deepLinkAllowed"`: Specifies whether the user can use deep links that open automatically when connecting to a session. - `"disconnectTimeoutInMinutes"`: The amount of time that a streaming session remains active after users disconnect. - `"idleDisconnectTimeoutInMinutes"`: The amount of time that users can be idle (inactive) before they are disconnected from their streaming session and the disconnect timeout interval begins. - `"tags"`: The tags to add to the user settings resource. A tag is a key-value pair. """ function create_user_settings( copyAllowed, downloadAllowed, pasteAllowed, printAllowed, uploadAllowed; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/userSettings", Dict{String,Any}( "copyAllowed" => copyAllowed, "downloadAllowed" => downloadAllowed, "pasteAllowed" => pasteAllowed, "printAllowed" => printAllowed, "uploadAllowed" => uploadAllowed, "clientToken" => string(uuid4()), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_user_settings( copyAllowed, downloadAllowed, pasteAllowed, printAllowed, uploadAllowed, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/userSettings", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "copyAllowed" => copyAllowed, "downloadAllowed" => downloadAllowed, "pasteAllowed" => pasteAllowed, "printAllowed" => printAllowed, "uploadAllowed" => uploadAllowed, "clientToken" => string(uuid4()), ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_browser_settings(browser_settings_arn) delete_browser_settings(browser_settings_arn, params::Dict{String,<:Any}) Deletes browser settings. # Arguments - `browser_settings_arn`: The ARN of the browser settings. """ function delete_browser_settings( browserSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/browserSettings/$(browserSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_browser_settings( browserSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/browserSettings/$(browserSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_identity_provider(identity_provider_arn) delete_identity_provider(identity_provider_arn, params::Dict{String,<:Any}) Deletes the identity provider. # Arguments - `identity_provider_arn`: The ARN of the identity provider. """ function delete_identity_provider( identityProviderArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/identityProviders/$(identityProviderArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_identity_provider( identityProviderArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/identityProviders/$(identityProviderArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_ip_access_settings(ip_access_settings_arn) delete_ip_access_settings(ip_access_settings_arn, params::Dict{String,<:Any}) Deletes IP access settings. # Arguments - `ip_access_settings_arn`: The ARN of the IP access settings. """ function delete_ip_access_settings( ipAccessSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/ipAccessSettings/$(ipAccessSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_ip_access_settings( ipAccessSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/ipAccessSettings/$(ipAccessSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_network_settings(network_settings_arn) delete_network_settings(network_settings_arn, params::Dict{String,<:Any}) Deletes network settings. # Arguments - `network_settings_arn`: The ARN of the network settings. """ function delete_network_settings( networkSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/networkSettings/$(networkSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_network_settings( networkSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/networkSettings/$(networkSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_portal(portal_arn) delete_portal(portal_arn, params::Dict{String,<:Any}) Deletes a web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function delete_portal(portalArn; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "DELETE", "/portals/$(portalArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_portal( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/portals/$(portalArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_trust_store(trust_store_arn) delete_trust_store(trust_store_arn, params::Dict{String,<:Any}) Deletes the trust store. # Arguments - `trust_store_arn`: The ARN of the trust store. """ function delete_trust_store( trustStoreArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/trustStores/$(trustStoreArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_trust_store( trustStoreArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/trustStores/$(trustStoreArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_user_access_logging_settings(user_access_logging_settings_arn) delete_user_access_logging_settings(user_access_logging_settings_arn, params::Dict{String,<:Any}) Deletes user access logging settings. # Arguments - `user_access_logging_settings_arn`: The ARN of the user access logging settings. """ function delete_user_access_logging_settings( userAccessLoggingSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/userAccessLoggingSettings/$(userAccessLoggingSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_user_access_logging_settings( userAccessLoggingSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/userAccessLoggingSettings/$(userAccessLoggingSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_user_settings(user_settings_arn) delete_user_settings(user_settings_arn, params::Dict{String,<:Any}) Deletes user settings. # Arguments - `user_settings_arn`: The ARN of the user settings. """ function delete_user_settings( userSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/userSettings/$(userSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_user_settings( userSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/userSettings/$(userSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_browser_settings(portal_arn) disassociate_browser_settings(portal_arn, params::Dict{String,<:Any}) Disassociates browser settings from a web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function disassociate_browser_settings( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/portals/$(portalArn)/browserSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_browser_settings( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/portals/$(portalArn)/browserSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_ip_access_settings(portal_arn) disassociate_ip_access_settings(portal_arn, params::Dict{String,<:Any}) Disassociates IP access settings from a web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function disassociate_ip_access_settings( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/portals/$(portalArn)/ipAccessSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_ip_access_settings( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/portals/$(portalArn)/ipAccessSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_network_settings(portal_arn) disassociate_network_settings(portal_arn, params::Dict{String,<:Any}) Disassociates network settings from a web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function disassociate_network_settings( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/portals/$(portalArn)/networkSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_network_settings( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/portals/$(portalArn)/networkSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_trust_store(portal_arn) disassociate_trust_store(portal_arn, params::Dict{String,<:Any}) Disassociates a trust store from a web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function disassociate_trust_store( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/portals/$(portalArn)/trustStores"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_trust_store( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/portals/$(portalArn)/trustStores", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_user_access_logging_settings(portal_arn) disassociate_user_access_logging_settings(portal_arn, params::Dict{String,<:Any}) Disassociates user access logging settings from a web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function disassociate_user_access_logging_settings( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/portals/$(portalArn)/userAccessLoggingSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_user_access_logging_settings( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/portals/$(portalArn)/userAccessLoggingSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_user_settings(portal_arn) disassociate_user_settings(portal_arn, params::Dict{String,<:Any}) Disassociates user settings from a web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function disassociate_user_settings( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/portals/$(portalArn)/userSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_user_settings( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/portals/$(portalArn)/userSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_browser_settings(browser_settings_arn) get_browser_settings(browser_settings_arn, params::Dict{String,<:Any}) Gets browser settings. # Arguments - `browser_settings_arn`: The ARN of the browser settings. """ function get_browser_settings( browserSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/browserSettings/$(browserSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_browser_settings( browserSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/browserSettings/$(browserSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_identity_provider(identity_provider_arn) get_identity_provider(identity_provider_arn, params::Dict{String,<:Any}) Gets the identity provider. # Arguments - `identity_provider_arn`: The ARN of the identity provider. """ function get_identity_provider( identityProviderArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/identityProviders/$(identityProviderArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_identity_provider( identityProviderArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/identityProviders/$(identityProviderArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_ip_access_settings(ip_access_settings_arn) get_ip_access_settings(ip_access_settings_arn, params::Dict{String,<:Any}) Gets the IP access settings. # Arguments - `ip_access_settings_arn`: The ARN of the IP access settings. """ function get_ip_access_settings( ipAccessSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/ipAccessSettings/$(ipAccessSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_ip_access_settings( ipAccessSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/ipAccessSettings/$(ipAccessSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_network_settings(network_settings_arn) get_network_settings(network_settings_arn, params::Dict{String,<:Any}) Gets the network settings. # Arguments - `network_settings_arn`: The ARN of the network settings. """ function get_network_settings( networkSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/networkSettings/$(networkSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_network_settings( networkSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/networkSettings/$(networkSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_portal(portal_arn) get_portal(portal_arn, params::Dict{String,<:Any}) Gets the web portal. # Arguments - `portal_arn`: The ARN of the web portal. """ function get_portal(portalArn; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/portals/$(portalArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_portal( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/portals/$(portalArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_portal_service_provider_metadata(portal_arn) get_portal_service_provider_metadata(portal_arn, params::Dict{String,<:Any}) Gets the service provider metadata. # Arguments - `portal_arn`: The ARN of the web portal. """ function get_portal_service_provider_metadata( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/portalIdp/$(portalArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_portal_service_provider_metadata( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/portalIdp/$(portalArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_trust_store(trust_store_arn) get_trust_store(trust_store_arn, params::Dict{String,<:Any}) Gets the trust store. # Arguments - `trust_store_arn`: The ARN of the trust store. """ function get_trust_store(trustStoreArn; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/trustStores/$(trustStoreArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_trust_store( trustStoreArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/trustStores/$(trustStoreArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_trust_store_certificate(thumbprint, trust_store_arn) get_trust_store_certificate(thumbprint, trust_store_arn, params::Dict{String,<:Any}) Gets the trust store certificate. # Arguments - `thumbprint`: The thumbprint of the trust store certificate. - `trust_store_arn`: The ARN of the trust store certificate. """ function get_trust_store_certificate( thumbprint, trustStoreArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/trustStores/$(trustStoreArn)/certificate", Dict{String,Any}("thumbprint" => thumbprint); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_trust_store_certificate( thumbprint, trustStoreArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/trustStores/$(trustStoreArn)/certificate", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("thumbprint" => thumbprint), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_user_access_logging_settings(user_access_logging_settings_arn) get_user_access_logging_settings(user_access_logging_settings_arn, params::Dict{String,<:Any}) Gets user access logging settings. # Arguments - `user_access_logging_settings_arn`: The ARN of the user access logging settings. """ function get_user_access_logging_settings( userAccessLoggingSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/userAccessLoggingSettings/$(userAccessLoggingSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_user_access_logging_settings( userAccessLoggingSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/userAccessLoggingSettings/$(userAccessLoggingSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_user_settings(user_settings_arn) get_user_settings(user_settings_arn, params::Dict{String,<:Any}) Gets user settings. # Arguments - `user_settings_arn`: The ARN of the user settings. """ function get_user_settings( userSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/userSettings/$(userSettingsArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_user_settings( userSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/userSettings/$(userSettingsArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_browser_settings() list_browser_settings(params::Dict{String,<:Any}) Retrieves a list of browser settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_browser_settings(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/browserSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_browser_settings( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/browserSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_identity_providers(portal_arn) list_identity_providers(portal_arn, params::Dict{String,<:Any}) Retrieves a list of identity providers for a specific web portal. # Arguments - `portal_arn`: The ARN of the web portal. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_identity_providers( portalArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/portals/$(portalArn)/identityProviders"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_identity_providers( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/portals/$(portalArn)/identityProviders", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_ip_access_settings() list_ip_access_settings(params::Dict{String,<:Any}) Retrieves a list of IP access settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_ip_access_settings(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/ipAccessSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_ip_access_settings( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/ipAccessSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_network_settings() list_network_settings(params::Dict{String,<:Any}) Retrieves a list of network settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_network_settings(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/networkSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_network_settings( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/networkSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_portals() list_portals(params::Dict{String,<:Any}) Retrieves a list or web portals. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_portals(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/portals"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_portals( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/portals", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ list_tags_for_resource(resource_arn) list_tags_for_resource(resource_arn, params::Dict{String,<:Any}) Retrieves a list of tags for a resource. # Arguments - `resource_arn`: The ARN of the resource. """ function list_tags_for_resource( resourceArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/tags/$(resourceArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_tags_for_resource( resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/tags/$(resourceArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_trust_store_certificates(trust_store_arn) list_trust_store_certificates(trust_store_arn, params::Dict{String,<:Any}) Retrieves a list of trust store certificates. # Arguments - `trust_store_arn`: The ARN of the trust store # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_trust_store_certificates( trustStoreArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/trustStores/$(trustStoreArn)/certificates"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_trust_store_certificates( trustStoreArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "GET", "/trustStores/$(trustStoreArn)/certificates", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_trust_stores() list_trust_stores(params::Dict{String,<:Any}) Retrieves a list of trust stores. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_trust_stores(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/trustStores"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_trust_stores( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/trustStores", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_user_access_logging_settings() list_user_access_logging_settings(params::Dict{String,<:Any}) Retrieves a list of user access logging settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_user_access_logging_settings(; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/userAccessLoggingSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_user_access_logging_settings( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/userAccessLoggingSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_user_settings() list_user_settings(params::Dict{String,<:Any}) Retrieves a list of user settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The maximum number of results to be included in the next page. - `"nextToken"`: The pagination token used to retrieve the next page of results for this operation. """ function list_user_settings(; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "GET", "/userSettings"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_user_settings( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "GET", "/userSettings", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ tag_resource(resource_arn, tags) tag_resource(resource_arn, tags, params::Dict{String,<:Any}) Adds or overwrites one or more tags for the specified resource. # Arguments - `resource_arn`: The ARN of the resource. - `tags`: The tags of the resource. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. """ function tag_resource(resourceArn, tags; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "POST", "/tags/$(resourceArn)", Dict{String,Any}("tags" => tags, "clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function tag_resource( resourceArn, tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "POST", "/tags/$(resourceArn)", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("tags" => tags, "clientToken" => string(uuid4())), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ untag_resource(resource_arn, tag_keys) untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any}) Removes one or more tags from the specified resource. # Arguments - `resource_arn`: The ARN of the resource. - `tag_keys`: The list of tag keys to remove from the resource. """ function untag_resource( resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "DELETE", "/tags/$(resourceArn)", Dict{String,Any}("tagKeys" => tagKeys); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function untag_resource( resourceArn, tagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "DELETE", "/tags/$(resourceArn)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_browser_settings(browser_settings_arn) update_browser_settings(browser_settings_arn, params::Dict{String,<:Any}) Updates browser settings. # Arguments - `browser_settings_arn`: The ARN of the browser settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"browserPolicy"`: A JSON string containing Chrome Enterprise policies that will be applied to all streaming sessions. - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. """ function update_browser_settings( browserSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PATCH", "/browserSettings/$(browserSettingsArn)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_browser_settings( browserSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PATCH", "/browserSettings/$(browserSettingsArn)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_identity_provider(identity_provider_arn) update_identity_provider(identity_provider_arn, params::Dict{String,<:Any}) Updates the identity provider. # Arguments - `identity_provider_arn`: The ARN of the identity provider. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"identityProviderDetails"`: The details of the identity provider. The following list describes the provider detail keys for each identity provider type. For Google and Login with Amazon: client_id client_secret authorize_scopes For Facebook: client_id client_secret authorize_scopes api_version For Sign in with Apple: client_id team_id key_id private_key authorize_scopes For OIDC providers: client_id client_secret attributes_request_method oidc_issuer authorize_scopes authorize_url if not available from discovery URL specified by oidc_issuer key token_url if not available from discovery URL specified by oidc_issuer key attributes_url if not available from discovery URL specified by oidc_issuer key jwks_uri if not available from discovery URL specified by oidc_issuer key For SAML providers: MetadataFile OR MetadataURL IDPSignout (boolean) optional IDPInit (boolean) optional RequestSigningAlgorithm (string) optional - Only accepts rsa-sha256 EncryptedResponses (boolean) optional - `"identityProviderName"`: The name of the identity provider. - `"identityProviderType"`: The type of the identity provider. """ function update_identity_provider( identityProviderArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PATCH", "/identityProviders/$(identityProviderArn)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_identity_provider( identityProviderArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PATCH", "/identityProviders/$(identityProviderArn)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_ip_access_settings(ip_access_settings_arn) update_ip_access_settings(ip_access_settings_arn, params::Dict{String,<:Any}) Updates IP access settings. # Arguments - `ip_access_settings_arn`: The ARN of the IP access settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"description"`: The description of the IP access settings. - `"displayName"`: The display name of the IP access settings. - `"ipRules"`: The updated IP rules of the IP access settings. """ function update_ip_access_settings( ipAccessSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PATCH", "/ipAccessSettings/$(ipAccessSettingsArn)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_ip_access_settings( ipAccessSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PATCH", "/ipAccessSettings/$(ipAccessSettingsArn)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_network_settings(network_settings_arn) update_network_settings(network_settings_arn, params::Dict{String,<:Any}) Updates network settings. # Arguments - `network_settings_arn`: The ARN of the network settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"securityGroupIds"`: One or more security groups used to control access from streaming instances to your VPC. - `"subnetIds"`: The subnets in which network interfaces are created to connect streaming instances to your VPC. At least two of these subnets must be in different availability zones. - `"vpcId"`: The VPC that streaming instances will connect to. """ function update_network_settings( networkSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PATCH", "/networkSettings/$(networkSettingsArn)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_network_settings( networkSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PATCH", "/networkSettings/$(networkSettingsArn)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_portal(portal_arn) update_portal(portal_arn, params::Dict{String,<:Any}) Updates a web portal. # Arguments - `portal_arn`: The ARN of the web portal. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"authenticationType"`: The type of authentication integration points used when signing into the web portal. Defaults to Standard. Standard web portals are authenticated directly through your identity provider. You need to call CreateIdentityProvider to integrate your identity provider with your web portal. User and group access to your web portal is controlled through your identity provider. IAM Identity Center web portals are authenticated through IAM Identity Center (successor to Single Sign-On). Identity sources (including external identity provider integration), plus user and group access to your web portal, can be configured in the IAM Identity Center. - `"displayName"`: The name of the web portal. This is not visible to users who log into the web portal. - `"instanceType"`: The type and resources of the underlying instance. - `"maxConcurrentSessions"`: The maximum number of concurrent sessions for the portal. """ function update_portal(portalArn; aws_config::AbstractAWSConfig=global_aws_config()) return workspaces_web( "PUT", "/portals/$(portalArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_portal( portalArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PUT", "/portals/$(portalArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_trust_store(trust_store_arn) update_trust_store(trust_store_arn, params::Dict{String,<:Any}) Updates the trust store. # Arguments - `trust_store_arn`: The ARN of the trust store. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"certificatesToAdd"`: A list of CA certificates to add to the trust store. - `"certificatesToDelete"`: A list of CA certificates to delete from a trust store. - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. """ function update_trust_store( trustStoreArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PATCH", "/trustStores/$(trustStoreArn)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_trust_store( trustStoreArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PATCH", "/trustStores/$(trustStoreArn)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_user_access_logging_settings(user_access_logging_settings_arn) update_user_access_logging_settings(user_access_logging_settings_arn, params::Dict{String,<:Any}) Updates the user access logging settings. # Arguments - `user_access_logging_settings_arn`: The ARN of the user access logging settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"kinesisStreamArn"`: The ARN of the Kinesis stream. """ function update_user_access_logging_settings( userAccessLoggingSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PATCH", "/userAccessLoggingSettings/$(userAccessLoggingSettingsArn)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_user_access_logging_settings( userAccessLoggingSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PATCH", "/userAccessLoggingSettings/$(userAccessLoggingSettingsArn)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_user_settings(user_settings_arn) update_user_settings(user_settings_arn, params::Dict{String,<:Any}) Updates the user settings. # Arguments - `user_settings_arn`: The ARN of the user settings. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"clientToken"`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. - `"cookieSynchronizationConfiguration"`: The configuration that specifies which cookies should be synchronized from the end user's local browser to the remote browser. If the allowlist and blocklist are empty, the configuration becomes null. - `"copyAllowed"`: Specifies whether the user can copy text from the streaming session to the local device. - `"deepLinkAllowed"`: Specifies whether the user can use deep links that open automatically when connecting to a session. - `"disconnectTimeoutInMinutes"`: The amount of time that a streaming session remains active after users disconnect. - `"downloadAllowed"`: Specifies whether the user can download files from the streaming session to the local device. - `"idleDisconnectTimeoutInMinutes"`: The amount of time that users can be idle (inactive) before they are disconnected from their streaming session and the disconnect timeout interval begins. - `"pasteAllowed"`: Specifies whether the user can paste text from the local device to the streaming session. - `"printAllowed"`: Specifies whether the user can print to the local device. - `"uploadAllowed"`: Specifies whether the user can upload files from the local device to the streaming session. """ function update_user_settings( userSettingsArn; aws_config::AbstractAWSConfig=global_aws_config() ) return workspaces_web( "PATCH", "/userSettings/$(userSettingsArn)", Dict{String,Any}("clientToken" => string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_user_settings( userSettingsArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return workspaces_web( "PATCH", "/userSettings/$(userSettingsArn)", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("clientToken" => string(uuid4())), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
43608
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: xray using AWS.Compat using AWS.UUIDs """ batch_get_traces(trace_ids) batch_get_traces(trace_ids, params::Dict{String,<:Any}) Retrieves a list of traces specified by ID. Each trace is a collection of segment documents that originates from a single request. Use GetTraceSummaries to get a list of trace IDs. # Arguments - `trace_ids`: Specify the trace IDs of requests for which to retrieve segments. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: Pagination token. """ function batch_get_traces(TraceIds; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/Traces", Dict{String,Any}("TraceIds" => TraceIds); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function batch_get_traces( TraceIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/Traces", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("TraceIds" => TraceIds), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_group(group_name) create_group(group_name, params::Dict{String,<:Any}) Creates a group resource with a name and a filter expression. # Arguments - `group_name`: The case-sensitive name of the new group. Default is a reserved name and names must be unique. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"FilterExpression"`: The filter expression defining criteria by which to group traces. - `"InsightsConfiguration"`: The structure containing configurations related to insights. The InsightsEnabled boolean can be set to true to enable insights for the new group or false to disable insights for the new group. The NotificationsEnabled boolean can be set to true to enable insights notifications for the new group. Notifications may only be enabled on a group with InsightsEnabled set to true. - `"Tags"`: A map that contains one or more tag keys and tag values to attach to an X-Ray group. For more information about ways to use tags, see Tagging Amazon Web Services resources in the Amazon Web Services General Reference. The following restrictions apply to tags: Maximum number of user-applied tags per resource: 50 Maximum tag key length: 128 Unicode characters Maximum tag value length: 256 Unicode characters Valid values for key and value: a-z, A-Z, 0-9, space, and the following characters: _ . : / = + - and @ Tag keys and values are case sensitive. Don't use aws: as a prefix for keys; it's reserved for Amazon Web Services use. """ function create_group(GroupName; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/CreateGroup", Dict{String,Any}("GroupName" => GroupName); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_group( GroupName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/CreateGroup", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("GroupName" => GroupName), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_sampling_rule(sampling_rule) create_sampling_rule(sampling_rule, params::Dict{String,<:Any}) Creates a rule to control sampling behavior for instrumented applications. Services retrieve rules with GetSamplingRules, and evaluate each rule in ascending order of priority for each request. If a rule matches, the service records a trace, borrowing it from the reservoir size. After 10 seconds, the service reports back to X-Ray with GetSamplingTargets to get updated versions of each in-use rule. The updated rule contains a trace quota that the service can use instead of borrowing from the reservoir. # Arguments - `sampling_rule`: The rule definition. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"Tags"`: A map that contains one or more tag keys and tag values to attach to an X-Ray sampling rule. For more information about ways to use tags, see Tagging Amazon Web Services resources in the Amazon Web Services General Reference. The following restrictions apply to tags: Maximum number of user-applied tags per resource: 50 Maximum tag key length: 128 Unicode characters Maximum tag value length: 256 Unicode characters Valid values for key and value: a-z, A-Z, 0-9, space, and the following characters: _ . : / = + - and @ Tag keys and values are case sensitive. Don't use aws: as a prefix for keys; it's reserved for Amazon Web Services use. """ function create_sampling_rule( SamplingRule; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/CreateSamplingRule", Dict{String,Any}("SamplingRule" => SamplingRule); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_sampling_rule( SamplingRule, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/CreateSamplingRule", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("SamplingRule" => SamplingRule), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_group() delete_group(params::Dict{String,<:Any}) Deletes a group resource. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"GroupARN"`: The ARN of the group that was generated on creation. - `"GroupName"`: The case-sensitive name of the group. """ function delete_group(; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/DeleteGroup"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function delete_group( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/DeleteGroup", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_resource_policy(policy_name) delete_resource_policy(policy_name, params::Dict{String,<:Any}) Deletes a resource policy from the target Amazon Web Services account. # Arguments - `policy_name`: The name of the resource policy to delete. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"PolicyRevisionId"`: Specifies a specific policy revision to delete. Provide a PolicyRevisionId to ensure an atomic delete operation. If the provided revision id does not match the latest policy revision id, an InvalidPolicyRevisionIdException exception is returned. """ function delete_resource_policy( PolicyName; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/DeleteResourcePolicy", Dict{String,Any}("PolicyName" => PolicyName); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_resource_policy( PolicyName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/DeleteResourcePolicy", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("PolicyName" => PolicyName), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_sampling_rule() delete_sampling_rule(params::Dict{String,<:Any}) Deletes a sampling rule. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"RuleARN"`: The ARN of the sampling rule. Specify a rule by either name or ARN, but not both. - `"RuleName"`: The name of the sampling rule. Specify a rule by either name or ARN, but not both. """ function delete_sampling_rule(; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/DeleteSamplingRule"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_sampling_rule( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/DeleteSamplingRule", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_encryption_config() get_encryption_config(params::Dict{String,<:Any}) Retrieves the current encryption configuration for X-Ray data. """ function get_encryption_config(; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/EncryptionConfig"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function get_encryption_config( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/EncryptionConfig", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_group() get_group(params::Dict{String,<:Any}) Retrieves group resource details. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"GroupARN"`: The ARN of the group that was generated on creation. - `"GroupName"`: The case-sensitive name of the group. """ function get_group(; aws_config::AbstractAWSConfig=global_aws_config()) return xray("POST", "/GetGroup"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) end function get_group( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/GetGroup", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ get_groups() get_groups(params::Dict{String,<:Any}) Retrieves all active group details. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: Pagination token. """ function get_groups(; aws_config::AbstractAWSConfig=global_aws_config()) return xray("POST", "/Groups"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) end function get_groups( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/Groups", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end """ get_insight(insight_id) get_insight(insight_id, params::Dict{String,<:Any}) Retrieves the summary information of an insight. This includes impact to clients and root cause services, the top anomalous services, the category, the state of the insight, and the start and end time of the insight. # Arguments - `insight_id`: The insight's unique identifier. Use the GetInsightSummaries action to retrieve an InsightId. """ function get_insight(InsightId; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/Insight", Dict{String,Any}("InsightId" => InsightId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_insight( InsightId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/Insight", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("InsightId" => InsightId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_insight_events(insight_id) get_insight_events(insight_id, params::Dict{String,<:Any}) X-Ray reevaluates insights periodically until they're resolved, and records each intermediate state as an event. You can review an insight's events in the Impact Timeline on the Inspect page in the X-Ray console. # Arguments - `insight_id`: The insight's unique identifier. Use the GetInsightSummaries action to retrieve an InsightId. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"MaxResults"`: Used to retrieve at most the specified value of events. - `"NextToken"`: Specify the pagination token returned by a previous request to retrieve the next page of events. """ function get_insight_events(InsightId; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/InsightEvents", Dict{String,Any}("InsightId" => InsightId); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_insight_events( InsightId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/InsightEvents", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("InsightId" => InsightId), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_insight_impact_graph(end_time, insight_id, start_time) get_insight_impact_graph(end_time, insight_id, start_time, params::Dict{String,<:Any}) Retrieves a service graph structure filtered by the specified insight. The service graph is limited to only structural information. For a complete service graph, use this API with the GetServiceGraph API. # Arguments - `end_time`: The estimated end time of the insight, in Unix time seconds. The EndTime is exclusive of the value provided. The time range between the start time and end time can't be more than six hours. - `insight_id`: The insight's unique identifier. Use the GetInsightSummaries action to retrieve an InsightId. - `start_time`: The estimated start time of the insight, in Unix time seconds. The StartTime is inclusive of the value provided and can't be more than 30 days old. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: Specify the pagination token returned by a previous request to retrieve the next page of results. """ function get_insight_impact_graph( EndTime, InsightId, StartTime; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/InsightImpactGraph", Dict{String,Any}( "EndTime" => EndTime, "InsightId" => InsightId, "StartTime" => StartTime ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_insight_impact_graph( EndTime, InsightId, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/InsightImpactGraph", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "EndTime" => EndTime, "InsightId" => InsightId, "StartTime" => StartTime ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_insight_summaries(end_time, start_time) get_insight_summaries(end_time, start_time, params::Dict{String,<:Any}) Retrieves the summaries of all insights in the specified group matching the provided filter values. # Arguments - `end_time`: The end of the time frame in which the insights ended. The end time can't be more than 30 days old. - `start_time`: The beginning of the time frame in which the insights started. The start time can't be more than 30 days old. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"GroupARN"`: The Amazon Resource Name (ARN) of the group. Required if the GroupName isn't provided. - `"GroupName"`: The name of the group. Required if the GroupARN isn't provided. - `"MaxResults"`: The maximum number of results to display. - `"NextToken"`: Pagination token. - `"States"`: The list of insight states. """ function get_insight_summaries( EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/InsightSummaries", Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_insight_summaries( EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/InsightSummaries", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_sampling_rules() get_sampling_rules(params::Dict{String,<:Any}) Retrieves all sampling rules. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: Pagination token. """ function get_sampling_rules(; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/GetSamplingRules"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function get_sampling_rules( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/GetSamplingRules", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_sampling_statistic_summaries() get_sampling_statistic_summaries(params::Dict{String,<:Any}) Retrieves information about recent sampling results for all sampling rules. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: Pagination token. """ function get_sampling_statistic_summaries(; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/SamplingStatisticSummaries"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_sampling_statistic_summaries( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/SamplingStatisticSummaries", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_sampling_targets(sampling_statistics_documents) get_sampling_targets(sampling_statistics_documents, params::Dict{String,<:Any}) Requests a sampling quota for rules that the service is using to sample requests. # Arguments - `sampling_statistics_documents`: Information about rules that the service is using to sample requests. """ function get_sampling_targets( SamplingStatisticsDocuments; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/SamplingTargets", Dict{String,Any}("SamplingStatisticsDocuments" => SamplingStatisticsDocuments); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_sampling_targets( SamplingStatisticsDocuments, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/SamplingTargets", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "SamplingStatisticsDocuments" => SamplingStatisticsDocuments ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_service_graph(end_time, start_time) get_service_graph(end_time, start_time, params::Dict{String,<:Any}) Retrieves a document that describes services that process incoming requests, and downstream services that they call as a result. Root services process incoming requests and make calls to downstream services. Root services are applications that use the Amazon Web Services X-Ray SDK. Downstream services can be other applications, Amazon Web Services resources, HTTP web APIs, or SQL databases. # Arguments - `end_time`: The end of the timeframe for which to generate a graph. - `start_time`: The start of the time frame for which to generate a graph. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"GroupARN"`: The Amazon Resource Name (ARN) of a group based on which you want to generate a graph. - `"GroupName"`: The name of a group based on which you want to generate a graph. - `"NextToken"`: Pagination token. """ function get_service_graph( EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/ServiceGraph", Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_service_graph( EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/ServiceGraph", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_time_series_service_statistics(end_time, start_time) get_time_series_service_statistics(end_time, start_time, params::Dict{String,<:Any}) Get an aggregation of service statistics defined by a specific time range. # Arguments - `end_time`: The end of the time frame for which to aggregate statistics. - `start_time`: The start of the time frame for which to aggregate statistics. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"EntitySelectorExpression"`: A filter expression defining entities that will be aggregated for statistics. Supports ID, service, and edge functions. If no selector expression is specified, edge statistics are returned. - `"ForecastStatistics"`: The forecasted high and low fault count values. Forecast enabled requests require the EntitySelectorExpression ID be provided. - `"GroupARN"`: The Amazon Resource Name (ARN) of the group for which to pull statistics from. - `"GroupName"`: The case-sensitive name of the group for which to pull statistics from. - `"NextToken"`: Pagination token. - `"Period"`: Aggregation period in seconds. """ function get_time_series_service_statistics( EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/TimeSeriesServiceStatistics", Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_time_series_service_statistics( EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/TimeSeriesServiceStatistics", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_trace_graph(trace_ids) get_trace_graph(trace_ids, params::Dict{String,<:Any}) Retrieves a service graph for one or more specific trace IDs. # Arguments - `trace_ids`: Trace IDs of requests for which to generate a service graph. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: Pagination token. """ function get_trace_graph(TraceIds; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/TraceGraph", Dict{String,Any}("TraceIds" => TraceIds); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_trace_graph( TraceIds, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/TraceGraph", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("TraceIds" => TraceIds), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_trace_summaries(end_time, start_time) get_trace_summaries(end_time, start_time, params::Dict{String,<:Any}) Retrieves IDs and annotations for traces available for a specified time frame using an optional filter. To get the full traces, pass the trace IDs to BatchGetTraces. A filter expression can target traced requests that hit specific service nodes or edges, have errors, or come from a known user. For example, the following filter expression targets traces that pass through api.example.com: service(\"api.example.com\") This filter expression finds traces that have an annotation named account with the value 12345: annotation.account = \"12345\" For a full list of indexed fields and keywords that you can use in filter expressions, see Using Filter Expressions in the Amazon Web Services X-Ray Developer Guide. # Arguments - `end_time`: The end of the time frame for which to retrieve traces. - `start_time`: The start of the time frame for which to retrieve traces. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"FilterExpression"`: Specify a filter expression to retrieve trace summaries for services or requests that meet certain requirements. - `"NextToken"`: Specify the pagination token returned by a previous request to retrieve the next page of results. - `"Sampling"`: Set to true to get summaries for only a subset of available traces. - `"SamplingStrategy"`: A parameter to indicate whether to enable sampling on trace summaries. Input parameters are Name and Value. - `"TimeRangeType"`: A parameter to indicate whether to query trace summaries by TraceId, Event (trace update time), or Service (segment end time). """ function get_trace_summaries( EndTime, StartTime; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/TraceSummaries", Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_trace_summaries( EndTime, StartTime, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/TraceSummaries", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("EndTime" => EndTime, "StartTime" => StartTime), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_resource_policies() list_resource_policies(params::Dict{String,<:Any}) Returns the list of resource policies in the target Amazon Web Services account. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: Not currently supported. """ function list_resource_policies(; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/ListResourcePolicies"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_resource_policies( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/ListResourcePolicies", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_tags_for_resource(resource_arn) list_tags_for_resource(resource_arn, params::Dict{String,<:Any}) Returns a list of tags that are applied to the specified Amazon Web Services X-Ray group or sampling rule. # Arguments - `resource_arn`: The Amazon Resource Number (ARN) of an X-Ray group or sampling rule. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"NextToken"`: A pagination token. If multiple pages of results are returned, use the NextToken value returned with the current page of results as the value of this parameter to get the next page of results. """ function list_tags_for_resource( ResourceARN; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/ListTagsForResource", Dict{String,Any}("ResourceARN" => ResourceARN); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_tags_for_resource( ResourceARN, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/ListTagsForResource", Dict{String,Any}( mergewith(_merge, Dict{String,Any}("ResourceARN" => ResourceARN), params) ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_encryption_config(type) put_encryption_config(type, params::Dict{String,<:Any}) Updates the encryption configuration for X-Ray data. # Arguments - `type`: The type of encryption. Set to KMS to use your own key for encryption. Set to NONE for default encryption. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"KeyId"`: An Amazon Web Services KMS key in one of the following formats: Alias - The name of the key. For example, alias/MyKey. Key ID - The KMS key ID of the key. For example, ae4aa6d49-a4d8-9df9-a475-4ff6d7898456. Amazon Web Services X-Ray does not support asymmetric KMS keys. ARN - The full Amazon Resource Name of the key ID or alias. For example, arn:aws:kms:us-east-2:123456789012:key/ae4aa6d49-a4d8-9df9-a475-4ff6d7898456. Use this format to specify a key in a different account. Omit this key if you set Type to NONE. """ function put_encryption_config(Type; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/PutEncryptionConfig", Dict{String,Any}("Type" => Type); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_encryption_config( Type, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/PutEncryptionConfig", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Type" => Type), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_resource_policy(policy_document, policy_name) put_resource_policy(policy_document, policy_name, params::Dict{String,<:Any}) Sets the resource policy to grant one or more Amazon Web Services services and accounts permissions to access X-Ray. Each resource policy will be associated with a specific Amazon Web Services account. Each Amazon Web Services account can have a maximum of 5 resource policies, and each policy name must be unique within that account. The maximum size of each resource policy is 5KB. # Arguments - `policy_document`: The resource policy document, which can be up to 5kb in size. - `policy_name`: The name of the resource policy. Must be unique within a specific Amazon Web Services account. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"BypassPolicyLockoutCheck"`: A flag to indicate whether to bypass the resource policy lockout safety check. Setting this value to true increases the risk that the policy becomes unmanageable. Do not set this value to true indiscriminately. Use this parameter only when you include a policy in the request and you intend to prevent the principal that is making the request from making a subsequent PutResourcePolicy request. The default value is false. - `"PolicyRevisionId"`: Specifies a specific policy revision, to ensure an atomic create operation. By default the resource policy is created if it does not exist, or updated with an incremented revision id. The revision id is unique to each policy in the account. If the policy revision id does not match the latest revision id, the operation will fail with an InvalidPolicyRevisionIdException exception. You can also provide a PolicyRevisionId of 0. In this case, the operation will fail with an InvalidPolicyRevisionIdException exception if a resource policy with the same name already exists. """ function put_resource_policy( PolicyDocument, PolicyName; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/PutResourcePolicy", Dict{String,Any}("PolicyDocument" => PolicyDocument, "PolicyName" => PolicyName); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_resource_policy( PolicyDocument, PolicyName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/PutResourcePolicy", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "PolicyDocument" => PolicyDocument, "PolicyName" => PolicyName ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_telemetry_records(telemetry_records) put_telemetry_records(telemetry_records, params::Dict{String,<:Any}) Used by the Amazon Web Services X-Ray daemon to upload telemetry. # Arguments - `telemetry_records`: # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"EC2InstanceId"`: - `"Hostname"`: - `"ResourceARN"`: """ function put_telemetry_records( TelemetryRecords; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/TelemetryRecords", Dict{String,Any}("TelemetryRecords" => TelemetryRecords); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_telemetry_records( TelemetryRecords, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/TelemetryRecords", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("TelemetryRecords" => TelemetryRecords), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ put_trace_segments(trace_segment_documents) put_trace_segments(trace_segment_documents, params::Dict{String,<:Any}) Uploads segment documents to Amazon Web Services X-Ray. The X-Ray SDK generates segment documents and sends them to the X-Ray daemon, which uploads them in batches. A segment document can be a completed segment, an in-progress segment, or an array of subsegments. Segments must include the following fields. For the full segment document schema, see Amazon Web Services X-Ray Segment Documents in the Amazon Web Services X-Ray Developer Guide. Required segment document fields name - The name of the service that handled the request. id - A 64-bit identifier for the segment, unique among segments in the same trace, in 16 hexadecimal digits. trace_id - A unique identifier that connects all segments and subsegments originating from a single client request. start_time - Time the segment or subsegment was created, in floating point seconds in epoch time, accurate to milliseconds. For example, 1480615200.010 or 1.480615200010E9. end_time - Time the segment or subsegment was closed. For example, 1480615200.090 or 1.480615200090E9. Specify either an end_time or in_progress. in_progress - Set to true instead of specifying an end_time to record that a segment has been started, but is not complete. Send an in-progress segment when your application receives a request that will take a long time to serve, to trace that the request was received. When the response is sent, send the complete segment to overwrite the in-progress segment. A trace_id consists of three numbers separated by hyphens. For example, 1-58406520-a006649127e371903a2de979. This includes: Trace ID Format The version number, for instance, 1. The time of the original request, in Unix epoch time, in 8 hexadecimal digits. For example, 10:00AM December 2nd, 2016 PST in epoch time is 1480615200 seconds, or 58406520 in hexadecimal. A 96-bit identifier for the trace, globally unique, in 24 hexadecimal digits. # Arguments - `trace_segment_documents`: A string containing a JSON document defining one or more segments or subsegments. """ function put_trace_segments( TraceSegmentDocuments; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/TraceSegments", Dict{String,Any}("TraceSegmentDocuments" => TraceSegmentDocuments); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function put_trace_segments( TraceSegmentDocuments, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/TraceSegments", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("TraceSegmentDocuments" => TraceSegmentDocuments), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ tag_resource(resource_arn, tags) tag_resource(resource_arn, tags, params::Dict{String,<:Any}) Applies tags to an existing Amazon Web Services X-Ray group or sampling rule. # Arguments - `resource_arn`: The Amazon Resource Number (ARN) of an X-Ray group or sampling rule. - `tags`: A map that contains one or more tag keys and tag values to attach to an X-Ray group or sampling rule. For more information about ways to use tags, see Tagging Amazon Web Services resources in the Amazon Web Services General Reference. The following restrictions apply to tags: Maximum number of user-applied tags per resource: 50 Maximum tag key length: 128 Unicode characters Maximum tag value length: 256 Unicode characters Valid values for key and value: a-z, A-Z, 0-9, space, and the following characters: _ . : / = + - and @ Tag keys and values are case sensitive. Don't use aws: as a prefix for keys; it's reserved for Amazon Web Services use. You cannot edit or delete system tags. """ function tag_resource(ResourceARN, Tags; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/TagResource", Dict{String,Any}("ResourceARN" => ResourceARN, "Tags" => Tags); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function tag_resource( ResourceARN, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/TagResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ResourceARN" => ResourceARN, "Tags" => Tags), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ untag_resource(resource_arn, tag_keys) untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any}) Removes tags from an Amazon Web Services X-Ray group or sampling rule. You cannot edit or delete system tags (those with an aws: prefix). # Arguments - `resource_arn`: The Amazon Resource Number (ARN) of an X-Ray group or sampling rule. - `tag_keys`: Keys for one or more tags that you want to remove from an X-Ray group or sampling rule. """ function untag_resource( ResourceARN, TagKeys; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/UntagResource", Dict{String,Any}("ResourceARN" => ResourceARN, "TagKeys" => TagKeys); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function untag_resource( ResourceARN, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/UntagResource", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("ResourceARN" => ResourceARN, "TagKeys" => TagKeys), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_group() update_group(params::Dict{String,<:Any}) Updates a group resource. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"FilterExpression"`: The updated filter expression defining criteria by which to group traces. - `"GroupARN"`: The ARN that was generated upon creation. - `"GroupName"`: The case-sensitive name of the group. - `"InsightsConfiguration"`: The structure containing configurations related to insights. The InsightsEnabled boolean can be set to true to enable insights for the group or false to disable insights for the group. The NotificationsEnabled boolean can be set to true to enable insights notifications for the group. Notifications can only be enabled on a group with InsightsEnabled set to true. """ function update_group(; aws_config::AbstractAWSConfig=global_aws_config()) return xray( "POST", "/UpdateGroup"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function update_group( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/UpdateGroup", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_sampling_rule(sampling_rule_update) update_sampling_rule(sampling_rule_update, params::Dict{String,<:Any}) Modifies a sampling rule's configuration. # Arguments - `sampling_rule_update`: The rule and fields to change. """ function update_sampling_rule( SamplingRuleUpdate; aws_config::AbstractAWSConfig=global_aws_config() ) return xray( "POST", "/UpdateSamplingRule", Dict{String,Any}("SamplingRuleUpdate" => SamplingRuleUpdate); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_sampling_rule( SamplingRuleUpdate, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return xray( "POST", "/UpdateSamplingRule", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("SamplingRuleUpdate" => SamplingRuleUpdate), params ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
8164
function _can_read_file(file_name::String) return isfile(file_name) && try isreadable(open(file_name, "r")) catch e false end end _begins_with_ec2(file_name::String) = uppercase(String(read(file_name, 3))) == "EC2" function _ends_with_ec2(file_name::String) return endswith(strip(uppercase(read(file_name, String))), "EC2") end """ Generate a valid role session name. Currently only ensures that the session name is 64-characters or less. """ function _role_session_name(prefix, name, suffix) b = IOBuffer() write(b, prefix, name) truncate(b, min(64 - length(suffix), b.size)) # Assumes ASCII write(b, suffix) return String(take!(b)) end """ Get the value for `key` in the `ini` file for a given `profile`. """ function _get_ini_value( ini::Inifile, profile::AbstractString, key::AbstractString; default_value=nothing ) value = get(ini, "profile $profile", key) value === :notfound && (value = get(ini, profile, key)) value === :notfound && (value = default_value) return value end function _aws_profile_config(ini::Inifile, profile::AbstractString) if profile != "default" || !haskey(sections(ini), "default") profile = "profile $profile" end return get(sections(ini), profile, Dict()) end function _aws_profile_config(ini::Inifile, profile::Nothing) return _aws_profile_config(ini, _aws_get_profile()) end function _aws_profile_config(config_file::AbstractString, profile) isfile(config_file) || return Dict() return _aws_profile_config(read(Inifile(), config_file), profile) end function _aws_profile_config(config_file::Nothing, profile) return _aws_profile_config(dot_aws_config_file(), profile) end """ Retrieve the `AWSCredentials` for a given role from Security Token Services (STS). """ function _aws_get_role(role::AbstractString, ini::Inifile) settings = @mock _aws_profile_config(ini, role) settings === nothing && return nothing source_profile = get(settings, "source_profile", nothing) source_profile === nothing && return nothing role_arn = get(settings, "role_arn", nothing) mfa_serial = get(settings, "mfa_serial", nothing) duration_seconds = get(settings, "duration_seconds", nothing) credentials = nothing for f in (sso_credentials, dot_aws_credentials, dot_aws_config) credentials = f(source_profile) credentials === nothing || break end credentials === nothing && return nothing config = AWSConfig(; creds=credentials, region=aws_get_region(; config=ini, profile=source_profile) ) params = LittleDict( "RoleArn" => role_arn, "RoleSessionName" => replace(role, r"[^\w+=,.@-]" => s"-") ) if mfa_serial !== nothing params["SerialNumber"] = mfa_serial token = @mock Base.getpass("Enter MFA code for $mfa_serial") params["TokenCode"] = read(token, String) Base.shred!(token) end if duration_seconds !== nothing params["DurationSeconds"] = duration_seconds end # RoleSessionName Documentation # https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html response = @mock AWSServices.sts( "AssumeRole", params; aws_config=config, feature_set=FeatureSet(; use_response_type=true), ) role = parse(response) role_creds = role["AssumeRoleResult"]["Credentials"] return AWSCredentials( role_creds["AccessKeyId"], role_creds["SecretAccessKey"], role_creds["SessionToken"]; expiry=DateTime(rstrip(role_creds["Expiration"], 'Z')), ) end """ Get `AWSCredentials` for the specified `profile` from the `inifile`. If targeting the `~/.aws/config` file, with a non-default `profile`, you must specify `config=true` otherwise the default credentials will be returned. """ function _aws_get_credential_details(profile::AbstractString, ini::Inifile) access_key = _get_ini_value(ini, profile, "aws_access_key_id") secret_key = _get_ini_value(ini, profile, "aws_secret_access_key") token = _get_ini_value(ini, profile, "aws_session_token"; default_value="") return (access_key, secret_key, token) end """ Get the default AWS profile """ function _aws_get_profile(; default="default") @something( get(ENV, "AWS_PROFILE", nothing), get(ENV, "AWS_DEFAULT_PROFILE", nothing), Some(default), ) end """ Check if credentials will expire within 5 minutes """ function _will_expire(aws_creds::AWSCredentials) return aws_creds.expiry - now(UTC) <= Minute(5) end """ Retrieve the EC2 meta data from the local AWS endpoint. Return the EC2 metadata request body, or `nothing` if not running on an EC2 instance. """ function _ec2_metadata(metadata_endpoint::String) try request = @mock HTTP.request( "GET", "http://169.254.169.254/latest/meta-data/$metadata_endpoint" ) return request === nothing ? nothing : String(request.body) catch e e isa HTTP.RequestError || e isa HTTP.StatusError && e.status == 404 || rethrow(e) end return nothing end """ Retrieve the SSO access token from cache. """ function _sso_cache_access_token(sso_start_url::Union{AbstractString,Nothing}) isnothing(sso_start_url) && return nothing cache_path = joinpath(homedir(), ".aws", "sso", "cache") cache_file = joinpath(cache_path, bytes2hex(sha1(sso_start_url)) * ".json") !isfile(cache_file) && return nothing _cache = JSON.parsefile(cache_file) token = get(_cache, "accessToken", nothing) return token end """ Retrieve sso-specific details for the given `profile`. """ function _aws_get_sso_credential_details(profile::AbstractString, ini::Inifile) sso_start_url = _get_ini_value(ini, profile, "sso_start_url") sso_account_id = _get_ini_value(ini, profile, "sso_account_id") sso_role_name = _get_ini_value(ini, profile, "sso_role_name"; default_value="default") sso_region = _get_ini_value(ini, profile, "sso_region"; default_value=DEFAULT_REGION) # sso cache access token access_token = @mock _sso_cache_access_token(sso_start_url) headers = Dict{String,Any}("x-amz-sso_bearer_token" => access_token) tmp_config = AWSConfig(; creds=nothing, region=sso_region) sso_creds = @mock AWSServices.sso( "GET", "/federation/credentials?account_id=$(sso_account_id)&role_name=$(sso_role_name)", Dict{String,Any}("headers" => headers), aws_config=tmp_config, ) access_key = sso_creds["roleCredentials"]["accessKeyId"] secret_key = sso_creds["roleCredentials"]["secretAccessKey"] token = sso_creds["roleCredentials"]["sessionToken"] expiry = DateTime( Dates.UTM(Dates.UNIXEPOCH + sso_creds["roleCredentials"]["expiration"]) ) return (access_key, secret_key, token, expiry) end """ _read_credential_process(io::IO) -> NamedTuple Parse the AWS CLI external process output out as defined in: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html """ function _read_credential_process(io::IO) # `JSON.parse` chokes on `Base.Process` I/O streams. json = JSON.parse(read(io, String)) version = json["Version"] if version != 1 error( "Credential process returned unhandled version $version:\n", sprint(JSON.print, json, 2), ) end access_key_id = json["AccessKeyId"] secret_access_key = json["SecretAccessKey"] # The presence of the "Expiration" key determines if the provided credentials are # long-term credentials or temporary credentials. Temporary credentials must include a # session token (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) if haskey(json, "Expiration") || haskey(json, "SessionToken") expiration = parse(DateTime, json["Expiration"], dateformat"yyyy-mm-dd\THH:MM:SS\Z") session_token = json["SessionToken"] else expiration = nothing session_token = nothing end return @compat (; access_key_id, secret_access_key, session_token, expiration) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
4979
""" DownloadsBackend <: AWS.AbstractBackend This backend uses the Downloads.jl stdlib to use libcurl as an HTTP client to connect to the AWS REST API. It has one field, - `downloader::Union{Nothing,Downloads.Downloader}` which is the `Downloads.Downloader` to use. If set to `nothing`, the default, then a global downloader object will be used. Downloads.jl tends to perform better under concurrent operation than HTTP.jl, particularly with `@async` / `asyncmap`. Note that threading (e.g. `@spawn` or `@threads`) with Downloads.jl is broken on Julia releases prior to 1.8 (https://github.com/JuliaLang/Downloads.jl/issues/182#issuecomment-1069269944). """ struct DownloadsBackend <: AWS.AbstractBackend downloader::Union{Nothing,Downloads.Downloader} end DownloadsBackend() = DownloadsBackend(nothing) const AWS_DOWNLOADER = Ref{Union{Nothing,Downloader}}(nothing) const AWS_DOWNLOAD_LOCK = ReentrantLock() # Here we mimic Download.jl's own setup for using a global downloader. # We do this to have our own downloader (separate from Downloads.jl's global downloader) # because we add a hook to avoid redirects in order to try to match the HTTPBackend's # implementation, and we don't want to mutate the global downloader from Downloads.jl. # https://github.com/JuliaLang/Downloads.jl/blob/84e948c02b8a0625552a764bf90f7d2ee97c949c/src/Downloads.jl#L293-L301 function get_downloader(downloader=nothing) lock(AWS_DOWNLOAD_LOCK) do yield() # let other downloads finish downloader isa Downloader && return nothing while true downloader = AWS_DOWNLOADER[] downloader isa Downloader && return nothing D = Downloader() D.easy_hook = (easy, info) -> Curl.setopt(easy, Curl.CURLOPT_FOLLOWLOCATION, false) AWS_DOWNLOADER[] = D end end return downloader end # https://github.com/JuliaWeb/HTTP.jl/blob/2a03ca76376162ffc3423ba7f15bd6d966edff9b/src/MessageRequest.jl#L84-L85 body_length(x::AbstractVector{UInt8}) = length(x) body_length(x::AbstractString) = sizeof(x) read_body(x::IOBuffer) = take!(x) function read_body(x::IO) close(x) return read(x) end function _http_request(backend::DownloadsBackend, request::Request, response_stream::IO) # HTTP.jl sets this header automatically. request.headers["Content-Length"] = string(body_length(request.content)) # We pass an `input` only when we have content we wish to send. input = !isempty(request.content) ? IOBuffer(request.content) : nothing downloader = @something(backend.downloader, get_downloader()) # set the hook so that we don't follow redirects. Only # need to do this on per-request downloaders, because we # set our global one with this hook already. if backend.downloader !== nothing && downloader.easy_hook === nothing downloader.easy_hook = (easy, info) -> Curl.setopt(easy, Curl.CURLOPT_FOLLOWLOCATION, false) end local buffer local response check = function (s, e) return (isa(e, HTTP.StatusError) && AWS._http_status(e) >= 500) || isa(e, Downloads.RequestError) end delays = AWSExponentialBackoff(; max_attempts=4) get_response = function () # Use a sacrificial I/O stream so that we only write the `response_stream` once # even with multiple attempts. buffer = Base.BufferStream() # Rewind the input on each attempt otherwise every subsequent attempt will send an # empty payload. input !== nothing && seekstart(input) r = @mock Downloads.request( request.url; input=input, # Compatibility with Downloads.jl versions below v1.5.2 # See: https://github.com/JuliaLang/Downloads.jl/issues/131 output=request.request_method != "HEAD" ? buffer : nothing, method=request.request_method, headers=request.headers, verbose=false, throw=true, downloader=downloader, ) response = _http_response(request, r; throw=true) # We'll rely on lexical scoping; `buffer` and `response` # are bindings in the outer scope, so we don't need to return here. return nothing end try retry(get_response; check=check, delays=delays)() finally close(buffer) # Transfer the contents of the `BufferStream` into `response_stream` variable. write(response_stream, buffer) end return AWS.Response(response, response_stream) end function _http_response(req::Request, res::Downloads.Response; throw::Bool=true) response = HTTP.Response(res.status, res.headers; body=IOBuffer(), request=nothing) if throw && HTTP.iserror(response) target = HTTP.resource(HTTP.URI(req.url)) e = HTTP.StatusError(res.status, req.request_method, target, response) Base.throw(e) end return response end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
9587
# Used to allow custom dispatches to `_http_request` """ AWS.AbstractBackend An abstract type representing a "backend" to use as an HTTP client to connect to the AWS REST API. """ abstract type AbstractBackend end """ AWS.HTTPBackend <: AWS.AbstractBackend This backend uses HTTP.jl as an HTTP client to connect to the AWS REST API, and has one field: - `http_options::AbstractDict{Symbol,<:Any}` which defaults to an empty dictionary. This field provides default options to use, which can be any of the keyword arguments to [`HTTP.request`](https://juliaweb.github.io/HTTP.jl/stable/public_interface/#HTTP.request). These options are overwritten by any per-request options. This is the default backend, and the only option until AWS.jl v1.57.0. Therefore, it has been used more often in practice, and may be more mature. Note, however, HTTP.jl currently (March 2022) has issues with concurrency (see [HTTP.jl#517](https://github.com/JuliaWeb/HTTP.jl/issues/517)). Therefore, it may be advisable to switch to the [`DownloadsBackend`](@ref) if you are using concurrency. """ struct HTTPBackend <: AbstractBackend http_options::AbstractDict{Symbol,<:Any} end function statuserror(status, resp) return HTTP.StatusError(status, resp.request.method, resp.request.target, resp) end function HTTPBackend(; kwargs...) return if isempty(kwargs) HTTPBackend(LittleDict{Symbol,Any}()) else HTTPBackend(LittleDict(kwargs)) end end # populated in `__init__` """ AWS.DEFAULT_BACKEND = Ref{AbstractBackend}() This specifies the default backend to use. This can be modified to change the default backend used by AWS.jl: ```julia using AWS AWS.DEFAULT_BACKEND[] = AWS.DownloadsBackend() ``` As an alternative, the `backend` can be specified on a per-request basis, by adding a pair `"backend" => AWS.DownloadsBackend()` to the `params` argument of AWS.jl functions. !!! warning Setting the `AWS.DEFAULT_BACKEND` is a global change that affects all packages in your Julia session using AWS.jl. Therefore, it is not recommended for library code to change the default backend, and instead set the backend on a per-request basis if needed (or ask the user to set a default backend). If you do wish to change the default backend inside package code which is precompiled, then it must be changed from within the `__init__` method. See the [Julia manual](https://docs.julialang.org/en/v1/manual/modules/#Module-initialization-and-precompilation) for more on module initialization. """ const DEFAULT_BACKEND = Ref{AbstractBackend}() Base.@kwdef mutable struct Request service::String api_version::String request_method::String headers::AbstractDict{String,String} = LittleDict{String,String}() content::Union{String,Vector{UInt8}} = "" resource::String = "" url::String = "" # Note: User provided `IO` should support seeking in order to support API error handling response_stream::Union{IO,Nothing} = nothing http_options::AbstractDict{Symbol,<:Any} = LittleDict{Symbol,String}() backend::AbstractBackend = DEFAULT_BACKEND[] # Deprecated fields use_response_type::Bool = false return_stream::Union{Bool,Nothing} = nothing return_raw::Union{Bool,Nothing} = nothing response_dict_type::Union{Type{<:AbstractDict},Nothing} = nothing end """ submit_request(aws::AbstractAWSConfig, request::Request; return_headers::Bool=false) Submit the request to AWS. # Arguments - `aws::AbstractAWSConfig`: AWSConfig containing credentials and other information for fulfilling the request, default value is the global configuration - `request::Request`: All the information about making a request to AWS # Keywords - `return_headers::Bool=false`: Set to `true` if you want the headers from the response returned back. Only used if `request.use_response_type = false`. # Returns - `AWS.Response`: A struct containing the response details """ function submit_request(aws::AbstractAWSConfig, request::Request; return_headers=nothing) aws_response = nothing TOO_MANY_REQUESTS = 429 EXPIRED_ERROR_CODES = ["ExpiredToken", "ExpiredTokenException", "RequestExpired"] REDIRECT_ERROR_CODES = [301, 302, 303, 304, 305, 307, 308] THROTTLING_ERROR_CODES = [ "Throttling", "ThrottlingException", "ThrottledException", "RequestThrottledException", "TooManyRequestsException", "ProvisionedThroughputExceededException", "TransactionInProgressException", "LimitExceededException", "RequestLimitExceeded", "BandwidthLimitExceeded", "RequestThrottled", "PriorRequestNotComplete", "SlowDown", "EC2ThrottledException", ] request.headers["User-Agent"] = user_agent[] request.headers["Host"] = HTTP.URI(request.url).host stream = @something request.response_stream IOBuffer() local aws_response local response get_response = function () credentials(aws) === nothing || sign!(aws, request) aws_response = @mock _http_request(request.backend, request, stream) response = aws_response.response if response.status in REDIRECT_ERROR_CODES if HTTP.header(response, "Location") != "" request.url = HTTP.header(response, "Location") else e = statuserror(response.status, response) throw(AWSException(e, stream)) end end end function upgrade_error(f) return () -> try return f() catch e if e isa HTTP.StatusError e = AWSException(e, stream) rethrow(e) end rethrow() end end check = function (s, e) # Pass on non-AWS exceptions. if !(e isa AWSException) return false end occursin("Signature expired", e.message) && return true # Handle ExpiredToken... # https://github.com/aws/aws-sdk-go/blob/v1.31.5/aws/request/retryer.go#L98 if e isa AWSException && e.code in EXPIRED_ERROR_CODES check_credentials(credentials(aws); force_refresh=true) return true end # Throttle handling # https://github.com/boto/botocore/blob/1.16.17/botocore/data/_retry.json # https://docs.aws.amazon.com/general/latest/gr/api-retries.html if _http_status(e.cause) == TOO_MANY_REQUESTS || e.code in THROTTLING_ERROR_CODES return true end # Handle BadDigest error and CRC32 check sum failure if _header(e.cause, "crc32body") == "x-amz-crc32" || e.code in ("BadDigest", "RequestTimeout", "RequestTimeoutException") return true end if occursin("Missing Authentication Token", e.message) && aws.credentials === nothing return throw( NoCredentials( "You're attempting to perform a request without credentials set." ), ) end return false end delays = AWSExponentialBackoff(; max_attempts=max_attempts(aws)) retry(upgrade_error(get_response); check=check, delays=delays)() if request.use_response_type return aws_response else return legacy_response(request, aws_response; return_headers=return_headers) end end function _http_request(http_backend::HTTPBackend, request::Request, response_stream::IO) http_options = merge(http_backend.http_options, request.http_options) local buffer local response get_response = function () # Use a sacrificial I/O stream so that we only write to the `response_stream` # once even with multiple attempted requests. Additionally this works around the # HTTP.jl issue (https://github.com/JuliaWeb/HTTP.jl/issues/543) where the # `response_stream` is closed automatically. Effectively, this works as if we're # not using streaming I/O at all, as we write all data at once, but only # returning data via I/O ensures we aren't relying on response's body being # populated. buffer = Base.BufferStream() response = @mock HTTP.request( request.request_method, HTTP.URI(request.url), HTTP.mkheaders(request.headers), request.content; redirect=false, retry=false, response_stream=buffer, http_options..., ) # We'll rely on lexical scoping; `buffer` and `response` # are bindings in the outer scope, so we don't need to return here. return nothing end check = function (s, e) return isa(e, HTTP.ConnectError) || isa(e, HTTP.RequestError) || (isa(e, HTTP.StatusError) && _http_status(e) >= 500) end delays = AWSExponentialBackoff(; max_attempts=4) try retry(get_response; check=check, delays=delays)() finally # We're unable to read from the `Base.BufferStream` until it has been closed. # HTTP.jl will close passed in `response_stream` keyword. This ensures that it # is always closed (e.g. HTTP.jl 0.9.15) close(buffer) # Transfer the contents of the `BufferStream` into `response_stream` variable. write(response_stream, buffer) end return @mock Response(response, response_stream) end _http_status(e::HTTP.StatusError) = e.status _header(e::HTTP.StatusError, k, d="") = HTTP.header(e.response, k, d)
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
3637
struct Response{S<:IO} response::HTTP.Response io::S # I/O type must support `seek` dict::Ref{AbstractDict} # Caches the parsed dict response end Response(response::HTTP.Response, io::IO) = Response(response, io, Ref{AbstractDict}()) function Base.getproperty(r::Response, f::Symbol) if f === :io || f === :response || f === :dict # Direct access to the fields stored in `Response` return getfield(r, f) elseif f === :body # As we're streaming the requests we'll fake the `HTTP.Response` body field return _rewind(read, r.io)::Vector{UInt8} else # Pretend like we're an `HTTP.Response` type for any other field access return getproperty(r.response, f) end end function mime_type(r::Response) # Parse response data according to mimetype... # Using "application/octet-stream" as the fallback MIME type as recommended by: # https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types mime = HTTP.header(r.response, "Content-Type", "application/octet-stream") # When the MIME type is not specified attempt to determine type from first bytes of the # stream. magic_bytes = if isempty(HTTP.header(r.response, "Content-Type", "")) _rewind(r.io) do io read(io, 5) end else UInt8[] end T = if occursin(r"/xml", mime) || magic_bytes == b"<?xml" MIME"application/xml" elseif occursin(r"/x-amz-json-1\.[01]$", mime) || endswith(mime, "json") MIME"application/json" elseif startswith(mime, "text/") MIME"text/plain" else MIME{Symbol(mime)} # Unhandled MIME type end return T end function Base.parse(f::Function, r::Response, mime::MIME=mime_type(r)()) result = _rewind(r.io) do io f(io, mime) end return result end Base.parse(r::Response, mime::MIME=mime_type(r)()) = parse(_read, r, mime) function _read(io::IO, ::MIME"application/xml") xml = parse_xml(read(io, String)) root = XMLDict.root(xml.x) # Drop XML declaration return xml_dict(root, LittleDict{Union{String,Symbol},Any}) end function _read(io::IO, ::MIME"application/json") # Note: Using JSON instead of JSON3 since it does not support OrderedDict/LittleDict return JSON.parse(io; dicttype=LittleDict{String,Any}) end _read(io::IO, ::MIME"text/plain") = read(io, String) _read(io::IO, ::MIME) = read(io) # Dict-like access function _dict(r::Response) if !isassigned(r.dict) dict = parse(r)::AbstractDict r.dict[] = dict end return r.dict[] end Base.getindex(r::Response, key::Union{AbstractString,Symbol}) = getindex(_dict(r), key) Base.haskey(r::Response, key::Union{AbstractString,Symbol}) = haskey(_dict(r), key) Base.keys(r::Response) = keys(_dict(r)) Base.values(r::Response) = values(_dict(r)) function Base.iterate(r::Response) iter = parse(r) x = iterate(iter) x === nothing && return nothing el, s = x return (el, (iter, s)) end function Base.iterate(r::Response, state) iter, s = state x = iterate(iter, s) x === nothing && return nothing el, s = x return (el, (iter, s)) end Base.String(r::Response) = _rewind(io -> read(io, String), r.io) function Base.show(io::IO, m::MIME"text/plain", r::Response) println(io, "$(Response): $(mime_type(r)()) interpreted as:") content = parse(r) show(io, m, content) return nothing end function _rewind(f::Function, io::IO) pos = position(io) seekstart(io) result = try f(io) finally seek(io, pos) end return result end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
5712
""" assume_role(principal::AbstractAWSConfig, role; kwargs...) -> AbstractAWSConfig Assumes the IAM `role` via temporary credentials via the `principal` entity. The `principal` entity must be included in the trust policy of the `role`. [Role chaining](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-role-chaining) must be manually specified by multiple `assume_role` calls (e.g. "role-a" has permissions to assume "role-b": `assume_role(assume_role(AWSConfig(), "role-a"), "role-b")`). # Arguments - `principal::AbstractAWSConfig`: The AWS configuration and credentials of the principal entity (user or role) performing the `sts:AssumeRole` action. - `role::AbstractString`: The AWS IAM role to assume. Either a full role ARN or just the role name. If only the role name is specified the role will be assumed to reside in the same account used in the `principal` argument. # Keywords - `duration::Integer` (optional): Role session duration in seconds. - `mfa_serial::AbstractString` (optional): The identification number of the MFA device that is associated with the user making the `AssumeRole` API call. Either a serial number for a hardware device ("GAHT12345678") or an ARN for a virtual device ("arn:aws:iam::123456789012:mfa/user"). When specified a MFA token must be provided via `token` or an interactive prompt. - `token::AbstractString` (optional): The value provided by the MFA device. Only can be specified when `mfa_serial` is set. - `session_name::AbstractString` (optional): The unique role session name associated with this API request. """ function assume_role(principal::AWSConfig, role; kwargs...) creds = assume_role_creds(principal, role; kwargs...) return AWSConfig(creds, principal.region, principal.output, principal.max_attempts) end """ assume_role(role; kwargs...) -> Function Create a function that assumes the IAM `role` via a deferred principal entity, i.e. a function equivalent to `principal -> assume_role(principal, role; kwargs...)`. Useful for [role chaining](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-role-chaining). # Examples Assume "role-a" which in turn assumes "role-b": ```julia AWSConfig() |> assume_role("role-a") |> assume_role("role-b") ``` """ assume_role(role; kwargs...) = principal -> assume_role(principal, role; kwargs...) """ assume_role_creds(principal, role; kwargs...) -> AWSCredentials Assumes the IAM `role` via temporary credentials via the `principal` entity and returns `AWSCredentials`. Typically, end-users should use [`assume_role`](@ref) instead. Details on the arguments and keywords for `assume_role_creds` can be found in the docstring for [`assume_role`](@ref). """ function assume_role_creds( principal::AbstractAWSConfig, role::AbstractString; duration::Union{Integer,Nothing}=nothing, mfa_serial::Union{AbstractString,Nothing}=nothing, token::Union{AbstractString,Nothing}=nothing, session_name::Union{AbstractString,Nothing}=nothing, ) if startswith(role, "arn:aws:iam") # Avoiding unnecessary parsing the role ARN or performing an expensive API call account_id = "" role_arn = role else account_id = aws_account_number(principal) role_arn = "arn:aws:iam::$account_id:role/$role" end params = Dict{String,Any}("RoleArn" => role_arn) if session_name !== nothing params["RoleSessionName"] = session_name else params["RoleSessionName"] = _role_session_name( "AWS.jl-", _whoami(), "-" * Dates.format(now(UTC), dateformat"yyyymmdd\THHMMSS\Z"), ) end if duration !== nothing params["DurationSeconds"] = duration end if mfa_serial !== nothing && token !== nothing params["SerialNumber"] = mfa_serial params["TokenCode"] = token elseif mfa_serial !== nothing && token === nothing params["SerialNumber"] = mfa_serial token = Base.getpass("Enter MFA code for $mfa_serial") params["TokenCode"] = Base.shred!(token) do t read(t, String) end elseif mfa_serial === nothing && token !== nothing msg = "Keyword `token` cannot be be specified when `mfa_serial` is not set" throw(ArgumentError(msg)) end response = AWSServices.sts( "AssumeRole", params; aws_config=principal, feature_set=AWS.FeatureSet(; use_response_type=true), ) body = parse(response) role_creds = body["AssumeRoleResult"]["Credentials"] role_user = body["AssumeRoleResult"]["AssumedRoleUser"] renew = function () # Avoid passing the `token` into the credential renew function as it will be expired return assume_role_creds(principal, role_arn; duration, mfa_serial, session_name) end return AWSCredentials( role_creds["AccessKeyId"], role_creds["SecretAccessKey"], role_creds["SessionToken"], role_user["Arn"], account_id; # May as well populate "account_number" field when we have it expiry=DateTime(rstrip(role_creds["Expiration"], 'Z')), renew, ) end """ _whoami() -> AbstractString The identity of the current user (i.e. effective user name). May differ from the logged in user if the current user has been assumed, perhaps by means of `su`. Note that the environmental variables `USER` or `USERNAME` are [not Bash built-in variables](https://tldp.org/LDP/abs/html/internalvariables.html#AMIROOT) and by default are not present in containers. """ _whoami() = readchomp(`id -un`) # The `whoami` utility is marked as obsolete
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
4097
function sign!(aws::AbstractAWSConfig, request::Request; time::DateTime=now(Dates.UTC)) if request.service in ("sdb", "importexport") sign_aws2!(aws, request, time) else sign_aws4!(aws, request, time) end end function sign_aws2!(aws::AbstractAWSConfig, request::Request, time::DateTime) # Create AWS Signature Version 2 Authentication query parameters. # http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html query = Dict{String,String}() for elem in split(request.content, '&'; keepempty=false) (n, v) = split(elem, "=") query[n] = HTTP.unescapeuri(v) end request.headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8" creds = check_credentials(credentials(aws)) query["AWSAccessKeyId"] = creds.access_key_id query["Expires"] = Dates.format( time + Dates.Minute(2), dateformat"yyyy-mm-dd\THH:MM:SS\Z" ) query["SignatureVersion"] = "2" query["SignatureMethod"] = "HmacSHA256" if !isempty(creds.token) query["SecurityToken"] = creds.token end query = [k => query[k] for k in sort!(collect(keys(query)))] uri = HTTP.URI(request.url) to_sign = "POST\n$(uri.host)\n$(uri.path)\n$(HTTP.escapeuri(query))" push!( query, "Signature" => strip(base64encode(digest(MD_SHA256, to_sign, creds.secret_key))), ) request.content = HTTP.escapeuri(query) return request end function sign_aws4!(aws::AbstractAWSConfig, request::Request, time::DateTime) # Create AWS Signature Version 4 Authentication Headers. # http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html date = Dates.format(time, dateformat"yyyymmdd") datetime = Dates.format(time, dateformat"yyyymmdd\THHMMSS\Z") # Authentication scope... authentication_scope = [date, region(aws), request.service, "aws4_request"] creds = check_credentials(credentials(aws)) signing_key = "AWS4$(creds.secret_key)" for scope in authentication_scope signing_key = digest(MD_SHA256, scope, signing_key) end # Authentication scope string... authentication_scope = join(authentication_scope, "/") # SHA256 hash of content... content_hash = bytes2hex(digest(MD_SHA256, request.content)) # HTTP headers... delete!(request.headers, "Authorization") merge!( request.headers, Dict( "x-amz-content-sha256" => content_hash, "x-amz-date" => datetime, "Content-MD5" => base64encode(digest(MD_MD5, request.content)), ), ) if !isempty(creds.token) request.headers["x-amz-security-token"] = creds.token end # Sort and lowercase() Headers to produce canonical form... canonical_headers = join( sort!(["$(lowercase(k)):$(strip(v))" for (k, v) in request.headers]), "\n" ) signed_headers = join(sort!([lowercase(k) for k in keys(request.headers)]), ";") # Sort Query String... uri = HTTP.URI(request.url) query = HTTP.URIs.queryparams(uri.query) query = [k => query[k] for k in sort!(collect(keys(query)))] # Create hash of canonical request... canonical_form = string( request.request_method, "\n", request.service == "s3" ? uri.path : HTTP.escapepath(uri.path), "\n", HTTP.escapeuri(query), "\n", canonical_headers, "\n\n", signed_headers, "\n", content_hash, ) canonical_hash = bytes2hex(digest(MD_SHA256, canonical_form)) # Create and sign "String to Sign"... string_to_sign = "AWS4-HMAC-SHA256\n$datetime\n$authentication_scope\n$canonical_hash" signature = bytes2hex(digest(MD_SHA256, string_to_sign, signing_key)) # Append Authorization header... request.headers["Authorization"] = join( [ "AWS4-HMAC-SHA256 Credential=$(creds.access_key_id)/$authentication_scope", "SignedHeaders=$signed_headers", "Signature=$signature", ], ", ", ) return request end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
4997
# This file contains functions used in the high level service definitions _merge(a::AbstractDict, b::AbstractDict) = merge(a, b) _merge(a::AbstractString, b::AbstractString) = b function _flatten_query(service::String, query::AbstractDict{String,<:Any}) return _flatten_query!(Pair{String,String}[], service, query) end function _flatten_query!( result::Vector{Pair{String,String}}, service::String, query::AbstractDict{String,<:Any}, prefix::String="", ) for (k, v) in query if v isa AbstractDict _flatten_query!(result, service, v, string(prefix, k, ".")) elseif v isa AbstractArray for (i, j) in enumerate(v) suffix = service in ("ec2", "sqs") ? "" : ".member" prefix_key = string(prefix, k, suffix, ".", i) if j isa AbstractDict _flatten_query!(result, service, j, string(prefix_key, ".")) else push!(result, Pair(prefix_key, string(j))) end end else push!(result, Pair(string(prefix, k), string(v))) end end return result end """ Escape special AWS S3 characters in the path of the uri properly. AWS S3 allows for various special characters in file names, these characters are not being properly escaped before we make the requests. We cannot call `HTTP.escapeuri(request.uri)` because this will escape `/` characters which are used in the filepathing for sub-directories. """ function _clean_s3_uri(uri::AbstractString) parsed_uri = URIs.URI(uri) cleaned_path = URIs.escapepath(parsed_uri.path) return string(URIs.URI(parsed_uri; path=cleaned_path)) end function _extract_common_kw_args(service, args) return ( service=service.signing_name, api_version=service.api_version, response_stream=_pop!(args, "response_stream", nothing), headers=LittleDict{String,String}(_pop!(args, "headers", [])), http_options=_pop!(args, "http_options", LittleDict{Symbol,String}()), backend=_pop!(args, "backend", DEFAULT_BACKEND[]), # Deprecated keywords return_stream=_pop!(args, "return_stream", nothing), return_raw=_pop!(args, "return_raw", nothing), response_dict_type=_pop!(args, "response_dict_type", nothing), ) end function _delete_legacy_response_kw_args!(args) used_kw_args = intersect( keys(args), ("return_headers", "return_stream", "return_raw", "response_dict_type") ) if !isempty(used_kw_args) Base.depwarn( "The parameter(s) \"$(join(used_kw_args, "\", \""))\" are no longer " * "supported when the feature `use_response_type` is enabled.", :_delete_legacy_response_kw_args!, ) end delete!(args, "return_headers") delete!(args, "return_stream") delete!(args, "return_raw") delete!(args, "response_dict_type") return args end # Use this until the three arg pop! is available for LittleDict # https://github.com/JuliaCollections/OrderedCollections.jl/pull/59 function _pop!(dict::AbstractDict{String,<:Any}, kw, default) if haskey(dict, kw) val = dict[kw] delete!(dict, kw) return val else return default end end function _generate_rest_resource(request_uri::String, args::AbstractDict{String,<:Any}) # There maybe a time where both $k and $k+ are in the request_uri, in which case this needs to be updated # From looking around, I have not seen an example yet, however that doesn't mean it doesn't exist for (k, v) in args if occursin("{$k}", request_uri) request_uri = replace(request_uri, "{$k}" => v) elseif occursin("{$k+}", request_uri) request_uri = replace(request_uri, "{$k+}" => HTTP.escapepath(v)) end end return request_uri end function _assignment_to_kw!(expr::Expr) if expr.head === :(=) expr.head = :kw else throw(ArgumentError("Expected assignment expression, instead found: `$expr`")) end return expr end function _assignment_to_kw!(x) return throw(ArgumentError("Expected assignment expression, instead found: `$x`")) end # https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html # Default values for AWS's `standard` retry mode. Note: these can be overridden elsewhere. Base.@kwdef struct AWSExponentialBackoff max_attempts::Int = AWS_MAX_RETRY_ATTEMPTS max_backoff::Float64 = 20.0 rng::AbstractRNG = Random.GLOBAL_RNG end # We make one more attempt than the number of delays Base.length(exp::AWSExponentialBackoff) = exp.max_attempts - 1 function Base.iterate(exp::AWSExponentialBackoff, i=1) i >= exp.max_attempts && return nothing # rand() has values in [0, 1), so we use 1.0 - rand() which has values in (0, 1] required. b = 1.0 - rand(exp.rng) r = 2.0 delay = min(b * r^i, exp.max_backoff) return delay, i + 1 end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
38258
@testset "service module" begin @service S3 @test :S3 in names(Main) end @testset "global config, kwargs" begin try region = "us-east-2" AWS.global_aws_config(; region=region) @test AWS.global_aws_config().region == region finally AWS.aws_config[] = AWSConfig() end end @testset "set global aws config" begin test_region = "test region" expected = AWSConfig(; region=test_region) try AWS.global_aws_config(expected) result = AWS.global_aws_config() @test result.region == test_region finally AWS.global_aws_config(AWSConfig()) end end @testset "set user agent" begin old_user_agent = AWS.user_agent[] new_user_agent = "new user agent" try @test AWS.user_agent[] == "AWS.jl/1.0.0" set_user_agent(new_user_agent) @test AWS.user_agent[] == new_user_agent finally set_user_agent(old_user_agent) end end @testset "sign" begin aws = AWS.AWSConfig(; region="us-east-1") access_key = "access-key" secret_key = "ssh... it is a secret" aws.credentials.access_key_id = access_key aws.credentials.secret_key = secret_key aws.credentials.token = "" time = DateTime(2020) date = Dates.format(time, dateformat"yyyymmdd") request = Request(; service="s3", api_version="api_version", request_method="GET", headers=LittleDict( "Host" => "s3.us-east-1.amazonaws.com", "User-Agent" => "AWS.jl/1.0.0" ), resource="/test-resource", url="https://s3.us-east-1.amazonaws.com/test-resource", ) @testset "sign v2" begin result = AWS.sign_aws2!(aws, request, time) content = result.content content_type = result.headers["Content-Type"] expected_access_key = "AWSAccessKeyId=$access_key" expected_expires = "Expires=2020-01-01T00%3A02%3A00Z" expected_signature_method = "SignatureMethod=HmacSHA256" expected_signature_version = "SignatureVersion=2" expected_signature = "Signature=O0MLzMKpEcfVZeHy0tyxVAuZF%2BvrvbgIGgqbWtJLTQ0%3D" expected_content = join( [ expected_access_key, expected_expires, expected_signature_method, expected_signature_version, expected_signature, ], '&', ) @test content == expected_content end @testset "sign v4" begin expected_x_amz_content_sha256 = bytes2hex(digest(MD_SHA256, request.content)) expected_content_md5 = base64encode(digest(MD_MD5, request.content)) expected_x_amz_date = Dates.format(time, dateformat"yyyymmdd\THHMMSS\Z") result = AWS.sign_aws4!(aws, request, time) headers = result.headers @test headers["x-amz-content-sha256"] == expected_x_amz_content_sha256 @test headers["Content-MD5"] == expected_content_md5 @test headers["x-amz-date"] == expected_x_amz_date authorization_header = split(headers["Authorization"], ' ') @test length(authorization_header) == 4 @test authorization_header[1] == "AWS4-HMAC-SHA256" @test authorization_header[2] == "Credential=$access_key/$date/us-east-1/$(request.service)/aws4_request," @test authorization_header[3] == "SignedHeaders=content-md5;content-type;host;user-agent;x-amz-content-sha256;x-amz-date," @test authorization_header[4] == "Signature=0f292eaf0b66cf353bafcb1b9b6d90ee27064236a60f17f6fc5bd7d40173a0be" end end @testset "submit_request" begin aws = AWS.AWSConfig() function _expected_xml(body::AbstractString, dict_type::Type) parsed = parse_xml(body) return xml_dict(XMLDict.root(parsed.x), dict_type) end @testset "301 redirect" begin request = Request(; service="s3", api_version="api_version", request_method="HEAD", url="https://s3.us-east-1.amazonaws.com/sample-bucket", use_response_type=true, ) apply(Patches._aws_http_request_patch(Patches._response(; status=301))) do @test_throws AWSException AWS.submit_request(aws, request) end end @testset "HEAD response" begin request = Request(; service="s3", api_version="api_version", request_method="HEAD", url="https://s3.us-east-1.amazonaws.com/sample-bucket", use_response_type=true, ) response = apply(Patches._aws_http_request_patch()) do AWS.submit_request(aws, request) end # Access to response headers @test response.response.headers == Patches.headers @test response.response.headers isa Vector # Access to streaming content @test response.io isa IO # Content as a string @test String(take!(response.io)) == Patches.body # Backwards compatibility with those expecting an `HTTP.Response` @test response.headers == Patches.headers @test response.headers isa Vector @test String(response.body) == Patches.body end @testset "GET response" begin request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", use_response_type=true, ) response = apply(Patches._aws_http_request_patch()) do AWS.submit_request(aws, request) end # Access to response headers @test response.response.headers == Patches.headers @test response.response.headers isa Vector # Access to streaming content @test response.io isa IO # Content as a string @test String(take!(response.io)) == Patches.body # Backwards compatibility with those expecting an `HTTP.Response` @test response.headers == Patches.headers @test response.headers isa Vector @test String(response.body) == Patches.body end @testset "Default throttling" begin request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", use_response_type=true, ) retries = Ref{Int}(0) exception = apply(Patches._throttling_patch(retries)) do try AWS.submit_request(aws, request) return nothing catch e if e isa AWSException return e else rethrow() end end end @test exception isa AWSException @test exception.code == "SlowDown" @test retries[] == AWS.max_attempts(aws) end @testset "Custom throttling" begin aws = AWS.AWSConfig(; max_attempts=1) @test AWS.max_attempts(aws) == 1 request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", use_response_type=true, ) retries = Ref{Int}(0) exception = apply(Patches._throttling_patch(retries)) do try AWS.submit_request(aws, request) return nothing catch e if e isa AWSException return e else rethrow() end end end @test exception isa AWSException @test exception.code == "SlowDown" @test retries[] == AWS.max_attempts(aws) end @testset "Not authorized" begin request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", use_response_type=true, ) message = "User is not authorized to perform: action on resource with an explicit deny" # Simulate the HTTP.request behaviour with a HTTP 400 response exception = apply(Patches.gen_http_options_400_patches(message)) do try AWS.submit_request(aws, request) return nothing catch e if e isa AWSException return e else rethrow() end end end @test exception isa AWSException # If handled incorrectly using a `response_stream` may result in the body data being # lost. Mainly, this is a problem when using a temporary I/O stream instead of # writing directly to the `response_stream`. @test exception.message == message @test exception.streamed_body !== nothing end @testset "Not authorized with BufferStream response_stream" begin buf = Base.BufferStream() request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", response_stream=buf, use_response_type=true, ) message = "User is not authorized to perform: action on resource with an explicit deny" # Simulate the HTTP.request behaviour with a HTTP 400 response exception = apply(Patches.gen_http_options_400_patches(message)) do try AWS.submit_request(aws, request) return nothing catch e if e isa AWSException return e else rethrow() end end end @test exception isa AWSException # If handled incorrectly using a `response_stream` may result in the body data being # lost. Mainly, this is a problem when using a temporary I/O stream instead of # writing directly to the `response_stream`. @test exception.message == message @test exception.streamed_body !== nothing end @testset "read MIME-type" begin request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", use_response_type=true, ) @testset "invalid content type" begin headers = Pair["Content-Type" => ""] body = "" expected_body_type = Vector{UInt8} expected_body = b"" r = Patches._response(; headers=headers, body=body) response = apply(Patches._aws_http_request_patch(r)) do AWS.submit_request(aws, request) end content = parse(response) @test content isa expected_body_type @test content == expected_body end @testset "text/xml" begin headers = Pair["Content-Type" => "text/xml"] expected_body_type = LittleDict{Union{String,Symbol},Any} expected_body = _expected_xml(Patches.body, expected_body_type) r = Patches._response(; headers=headers) response = apply(Patches._aws_http_request_patch(r)) do AWS.submit_request(aws, request) end content = parse(response) @test content isa expected_body_type @test content == expected_body end @testset "application/xml" begin headers = Pair["Content-Type" => "application/xml"] expected_body_type = LittleDict{Union{String,Symbol},Any} expected_body = _expected_xml(Patches.body, expected_body_type) r = Patches._response(; headers=headers) response = apply(Patches._aws_http_request_patch(r)) do AWS.submit_request(aws, request) end content = parse(response) @test content isa expected_body_type @test content == expected_body end @testset "application/json" begin headers = ["Content-Type" => "application/json"] body = JSON.json( Dict{String,Any}( "Marker" => nothing, "VaultList" => Any[Dict{String,Any}( "VaultName" => "test", "SizeInBytes" => 0, "NumberOfArchives" => 0, "CreationDate" => "2020-06-22T03:14:41.754Z", "VaultARN" => "arn:aws:glacier:us-east-1:000:vaults/test", "LastInventoryDate" => nothing, )], ), ) expected_body_type = LittleDict{String,Any} expected_body = JSON.parse(body; dicttype=expected_body_type) r = Patches._response(; body=body, headers=headers) response = apply(Patches._aws_http_request_patch(r)) do AWS.submit_request(aws, request) end content = parse(response) @test content isa expected_body_type @test content == expected_body end @testset "text/html" begin headers = ["Content-Type" => "text/html"] expected_body = Patches.body r = Patches._response(; headers=headers) response = apply(Patches._aws_http_request_patch(r)) do AWS.submit_request(aws, request) end content = parse(response) @test content isa String @test content == expected_body end # Note: `S3.create_multipart_upload` is an example of a response type that doesn't # specify a Content-Type. @testset "missing content type" begin headers = Pair[] body = """ <?xml version="1.0" encoding="UTF-8"?> <root><body>text</body></root> """ expected_body_type = AbstractDict expected_body = Dict{String,Any}("body" => "text") r = Patches._response(; headers=headers, body=body) response = apply(Patches._aws_http_request_patch(r)) do AWS.submit_request(aws, request) end content = parse(response) @test content isa expected_body_type @test content == expected_body content = parse(response, MIME"text/plain"()) @test content isa String @test content == body end end end struct TestBackend <: AWS.AbstractBackend param::Int end function AWS._http_request(backend::TestBackend, ::AWS.Request, ::IO) return backend.param end @testset "HTTPBackend" begin request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", backend=AWS.HTTPBackend(), ) io = IOBuffer() apply(Patches._http_options_patches) do # No default options @test isempty(AWS._http_request(request.backend, request, io)) # We can pass HTTP options via the backend custom_backend = AWS.HTTPBackend(Dict(:connection_limit => 5)) @test custom_backend isa AWS.AbstractBackend @test AWS._http_request(custom_backend, request, io) == Dict(:connection_limit => 5) # We can pass options per-request request.http_options = Dict(:pipeline_limit => 20) @test AWS._http_request(request.backend, request, io) == Dict(:pipeline_limit => 20) @test AWS._http_request(custom_backend, request, io) == Dict(:pipeline_limit => 20, :connection_limit => 5) # per-request options override backend options: custom_backend = AWS.HTTPBackend(Dict(:pipeline_limit => 5)) @test AWS._http_request(custom_backend, request, io) == Dict(:pipeline_limit => 20) end request.backend = TestBackend(2) @test AWS._http_request(request.backend, request, io) == 2 request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", backend=TestBackend(4), ) @test AWS._http_request(request.backend, request, io) == 4 # Let's test setting the default backend prev_backend = AWS.DEFAULT_BACKEND[] try AWS.DEFAULT_BACKEND[] = TestBackend(3) request = Request(; service="s3", api_version="api_version", request_method="GET", url="https://s3.us-east-1.amazonaws.com/sample-bucket", ) @test AWS._http_request(request.backend, request, io) == 3 finally AWS.DEFAULT_BACKEND[] = prev_backend end end @testset "_generate_rest_resource" begin request_uri = "/{Bucket}/{Key+}" args = Dict{String,Any}("Bucket" => "aws.jl-test", "Key" => "Test-Key") expected = "/$(args["Bucket"])/$(args["Key"])" result = AWS._generate_rest_resource(request_uri, args) @test result == expected end @testset "generate_service_url" begin region = "us-east-2" resource = "/aws.jl-test---timestamp" config = AWSConfig() config.region = region request = Request(; service="service", api_version="api_version", request_method="GET", resource=resource, ) @testset "regionless endpoints" for regionless_endpoint in ("iam", "route53") endpoint = "sdb" request.service = regionless_endpoint expected_result = "https://$regionless_endpoint.amazonaws.com$resource" result = AWS.generate_service_url(config, request.service, request.resource) @test result == expected_result end @testset "region service" begin endpoint = "sdb" request.service = endpoint expected_result = "https://$endpoint.$region.amazonaws.com$resource" result = AWS.generate_service_url(config, request.service, request.resource) @test result == expected_result end @testset "sdb -- us-east-1 region exception" begin endpoint = "sdb" request.service = endpoint expected_result = "https://$endpoint.amazonaws.com$resource" config.region = "us-east-1" result = AWS.generate_service_url(config, request.service, request.resource) @test result == expected_result end end @testset "_flatten_query" begin high_level_value = "high_level_value" entry_1 = LittleDict( "low_level_key_1" => "low_level_value_1", "low_level_key_2" => "low_level_value_2" ) entry_2 = LittleDict( "low_level_key_3" => "low_level_value_3", "low_level_key_4" => "low_level_value_4" ) args = LittleDict( "high_level_key" => high_level_value, "high_level_array" => [entry_1, entry_2] ) @testset "non-special case suffix" begin service = "sts" result = AWS._flatten_query(service, args) expected = Pair{String,String}[ "high_level_key" => "high_level_value", "high_level_array.member.1.low_level_key_1" => "low_level_value_1", "high_level_array.member.1.low_level_key_2" => "low_level_value_2", "high_level_array.member.2.low_level_key_3" => "low_level_value_3", "high_level_array.member.2.low_level_key_4" => "low_level_value_4", ] @test result == expected end @testset "sqs - special casing suffix" begin service = "sqs" result = AWS._flatten_query(service, args) expected = Pair{String,String}[ "high_level_key" => "high_level_value", "high_level_array.1.low_level_key_1" => "low_level_value_1", "high_level_array.1.low_level_key_2" => "low_level_value_2", "high_level_array.2.low_level_key_3" => "low_level_value_3", "high_level_array.2.low_level_key_4" => "low_level_value_4", ] @test result == expected end end @testset "_clean_s3_uri" begin uri = "/test-bucket/*)=('! +@,:.txt?list-objects=v2" expected_uri = "/test-bucket/%2A%29%3D%28%27%21%20%2B%40%2C%3A.txt?list-objects=v2" @test AWS._clean_s3_uri(uri) == expected_uri # make sure that other parts of the uri aren't changed by `_clean_s3_uri` for uri in ( "https://julialang.org", "http://julialang.org", "http://julialang.org:8080", "/onlypath", "/path?query= +99", "/anchor?query=yes#anchor1", ) @test AWS._clean_s3_uri(uri) == uri end end @testset "STS" begin @testset "high-level" begin @service STS response = STS.get_caller_identity() d = response["GetCallerIdentityResult"] @test Set(keys(d)) == Set(["Arn", "UserId", "Account"]) @test occursin(r"^arn:aws:(iam|sts):", d["Arn"]) @test all(isdigit, d["Account"]) end @testset "low-level" begin response = AWSServices.sts("GetCallerIdentity") d = response["GetCallerIdentityResult"] @test Set(keys(d)) == Set(["Arn", "UserId", "Account"]) @test occursin(r"^arn:aws:(iam|sts):", d["Arn"]) @test all(isdigit, d["Account"]) end end @testset "json" begin @testset "high-level secrets manager" begin @service Secrets_Manager secret_name = "aws-jl-test---" * _now_formatted() secret_string = "sshhh it is a secret!" function _get_secret_string(secret_name) response = Secrets_Manager.get_secret_value(secret_name) return response["SecretString"] end Secrets_Manager.create_secret( secret_name, LittleDict( "SecretString" => secret_string, "ClientRequestToken" => string(uuid4()) ), ) try @test _get_secret_string(secret_name) == secret_string finally Secrets_Manager.delete_secret( secret_name, LittleDict("ForceDeleteWithoutRecovery" => "true") ) end @test_throws AWSException _get_secret_string(secret_name) end @testset "low-level secrets manager" begin secret_name = "aws-jl-test---" * _now_formatted() secret_string = "sshhh it is a secret!" function _get_secret_string(secret_name) response = AWSServices.secrets_manager( "GetSecretValue", LittleDict("SecretId" => secret_name) ) return response["SecretString"] end resp = AWSServices.secrets_manager( "CreateSecret", LittleDict( "Name" => secret_name, "SecretString" => secret_string, "ClientRequestToken" => string(uuid4()), ), ) try @test _get_secret_string(secret_name) == secret_string finally AWSServices.secrets_manager( "DeleteSecret", LittleDict( "SecretId" => secret_name, "ForceDeleteWithoutRecovery" => "true" ), ) end @test_throws AWSException _get_secret_string(secret_name) end end @testset "query" begin @testset "high-level iam" begin @service IAM policy_arn = "" expected_policy_name = "aws-jl-test---" * _now_formatted() expected_policy_document = LittleDict( "Version" => "2012-10-17", "Statement" => [ LittleDict( "Effect" => "Allow", "Action" => ["s3:Get*", "s3:List*"], "Resource" => ["arn:aws:s3:::my-bucket/shared/*"], ), ], ) expected_policy_document = JSON.json(expected_policy_document) response = IAM.create_policy(expected_policy_document, expected_policy_name) policy_arn = response["CreatePolicyResult"]["Policy"]["Arn"] try response_policy_version = IAM.get_policy_version(policy_arn, "v1") response_document = response_policy_version["GetPolicyVersionResult"]["PolicyVersion"]["Document"] @test HTTP.unescapeuri(response_document) == expected_policy_document finally IAM.delete_policy(policy_arn) end @test_throws AWSException IAM.get_policy(policy_arn) end @testset "low-level iam" begin policy_arn = "" expected_policy_name = "aws-jl-test---" * _now_formatted() expected_policy_document = LittleDict( "Version" => "2012-10-17", "Statement" => [ LittleDict( "Effect" => "Allow", "Action" => ["s3:Get*", "s3:List*"], "Resource" => ["arn:aws:s3:::my-bucket/shared/*"], ), ], ) expected_policy_document = JSON.json(expected_policy_document) response = AWSServices.iam( "CreatePolicy", LittleDict( "PolicyName" => expected_policy_name, "PolicyDocument" => expected_policy_document, ), ) policy_arn = response["CreatePolicyResult"]["Policy"]["Arn"] try response_policy_version = AWSServices.iam( "GetPolicyVersion", LittleDict("PolicyArn" => policy_arn, "VersionId" => "v1"), ) response_document = response_policy_version["GetPolicyVersionResult"]["PolicyVersion"]["Document"] @test HTTP.unescapeuri(response_document) == expected_policy_document finally AWSServices.iam("DeletePolicy", LittleDict("PolicyArn" => policy_arn)) end @test_throws AWSException AWSServices.iam( "GetPolicy", LittleDict("PolicyArn" => policy_arn) ) end @testset "high-level sqs" begin @service SQS queue_name = "aws-jl-test---" * _now_formatted() expected_message = "Hello for AWS.jl" function _get_queue_url(queue_name) result = SQS.get_queue_url(queue_name) return result["QueueUrl"] end # Create Queue SQS.create_queue(queue_name) queue_url = _get_queue_url(queue_name) try # Get Queues @test !isempty(queue_url) # Change Message Visibility Batch Request expected_message_id = "aws-jl-test" SQS.send_message(expected_message, queue_url) response = SQS.receive_message(queue_url) receipt_handle = only(response["Messages"])["ReceiptHandle"] response = SQS.delete_message_batch( [ LittleDict( "Id" => expected_message_id, "ReceiptHandle" => receipt_handle ), ], queue_url, ) message_id = only(response["Successful"])["Id"] @test message_id == expected_message_id SQS.send_message(expected_message, queue_url) result = SQS.receive_message(queue_url) message = only(result["Messages"])["Body"] @test message == expected_message finally SQS.delete_queue(queue_url) end @test_throws AWSException _get_queue_url(queue_name) end @testset "low-level sqs" begin queue_name = "aws-jl-test---" * _now_formatted() expected_message = "Hello for AWS.jl" function _get_queue_url(queue_name) result = AWSServices.sqs("GetQueueUrl", LittleDict("QueueName" => queue_name)) return result["QueueUrl"] end # Create Queue AWSServices.sqs("CreateQueue", LittleDict("QueueName" => queue_name)) queue_url = _get_queue_url(queue_name) @test !isempty(queue_url) try # Change Message Visibility Batch Request expected_message_id = "aws-jl-test" AWSServices.sqs( "SendMessage", LittleDict("QueueUrl" => queue_url, "MessageBody" => expected_message), ) response = AWSServices.sqs( "ReceiveMessage", LittleDict("QueueUrl" => queue_url) ) receipt_handle = only(response["Messages"])["ReceiptHandle"] response = AWSServices.sqs( "DeleteMessageBatch", LittleDict( "QueueUrl" => queue_url, "Entries" => [ LittleDict( "Id" => expected_message_id, "ReceiptHandle" => receipt_handle, ), ], ), ) message_id = only(response["Successful"])["Id"] @test message_id == expected_message_id # Send message AWSServices.sqs( "SendMessage", LittleDict("QueueUrl" => queue_url, "MessageBody" => expected_message), ) # Receive Message result = AWSServices.sqs("ReceiveMessage", LittleDict("QueueUrl" => queue_url)) message = only(result["Messages"])["Body"] @test message == expected_message finally AWSServices.sqs("DeleteQueue", LittleDict("QueueUrl" => queue_url)) end @test_throws AWSException _get_queue_url(queue_name) end end @testset "rest-xml" begin @testset "high-level s3" begin @service S3 bucket_name = "aws-jl-test---" * _now_formatted() file_name = string(uuid4()) function _bucket_exists(bucket_name) try S3.head_bucket(bucket_name) return true catch e if e isa AWSException && e.cause.status == 404 return false else rethrow(e) end end end # HEAD operation @test _bucket_exists(bucket_name) == false # PUT operation S3.create_bucket(bucket_name) @test _bucket_exists(bucket_name) try # PUT with parameters operation body = "sample-file-body" S3.put_object(bucket_name, file_name, Dict("body" => body)) @test !isempty(S3.get_object(bucket_name, file_name)) # GET operation result = S3.list_objects(bucket_name) @test result["Contents"]["Key"] == file_name # GET with parameters operation max_keys = 1 result = S3.list_objects(bucket_name, Dict("max_keys" => max_keys)) @test length([result["Contents"]]) == max_keys # GET with an IO target mktemp() do f, io S3.get_object(bucket_name, file_name, Dict("response_stream" => io)) flush(io) @test read(f, String) == body end finally # DELETE with parameters operation S3.delete_object(bucket_name, file_name) @test_throws AWSException S3.get_object(bucket_name, file_name) # DELETE operation S3.delete_bucket(bucket_name) sleep(2) end @test _bucket_exists(bucket_name) == false end @testset "low-level s3" begin bucket_name = "aws-jl-test---" * _now_formatted() file_name = "*)=('! +@,:.txt" # Special characters which S3 allows function _bucket_exists(bucket_name) try AWSServices.s3("HEAD", "/$bucket_name") return true catch e if e isa AWSException && e.cause.status == 404 return false else rethrow(e) end end end # HEAD operation @test _bucket_exists(bucket_name) == false # PUT operation AWSServices.s3("PUT", "/$bucket_name") @test _bucket_exists(bucket_name) try # PUT with parameters operation body = Array{UInt8}("sample-file-body") AWSServices.s3("PUT", "/$bucket_name/$file_name", Dict("body" => body)) @test AWSServices.s3("GET", "/$bucket_name/$file_name") == body # GET operation result = AWSServices.s3("GET", "/$bucket_name") @test result["Contents"]["Key"] == file_name # GET with parameters operation max_keys = 1 result = AWSServices.s3("GET", "/$bucket_name", Dict("max_keys" => max_keys)) @test length([result["Contents"]]) == max_keys # POST with parameters operation body = """ <Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Object> <Key>$file_name</Key> </Object> </Delete> """ AWSServices.s3("POST", "/$bucket_name?delete", Dict("body" => body)) @test_throws AWSException AWSServices.s3("GET", "/$bucket_name/$file_name") finally # DELETE operation AWSServices.s3("DELETE", "/$bucket_name") sleep(2) end @test _bucket_exists(bucket_name) == false end @testset "additional S3 operations" begin @service S3 bucket_name = "aws-jl-test---" * _now_formatted() # Testing a file name with various special & Unicode characters file_name = "$(uuid4())/📁!!/@ +*" function _bucket_exists(bucket_name) try S3.head_bucket(bucket_name) return true catch e if e isa AWSException && e.cause.status == 404 return false else rethrow(e) end end end # HEAD operation @test _bucket_exists(bucket_name) == false # PUT operation S3.create_bucket(bucket_name) @test _bucket_exists(bucket_name) try # PUT with parameters operation body = "sample-file-body" S3.put_object(bucket_name, file_name, Dict("body" => body)) @test !isempty(S3.get_object(bucket_name, file_name)) # GET operation result = S3.list_objects(bucket_name) @test result["Contents"]["Key"] == file_name finally # DELETE the file, check that it's gone, and then DELETE the bucket S3.delete_object(bucket_name, file_name) @test_throws AWSException S3.get_object(bucket_name, file_name) S3.delete_bucket(bucket_name) sleep(2) end @test _bucket_exists(bucket_name) == false end end @testset "rest-json" begin @testset "high-level glacier" begin @service Glacier timestamp = _now_formatted() vault_names = ["aws-jl-test-01---$timestamp", "aws-jl-test-02---$timestamp"] # PUT for vault in vault_names Glacier.create_vault("-", vault) end try # POST tags = Dict("Tags" => LittleDict("Tag-01" => "Tag-01", "Tag-02" => "Tag-02")) for vault in vault_names Glacier.add_tags_to_vault("-", vault, tags) end for vault in vault_names result_tags = Glacier.list_tags_for_vault("-", vault) @test result_tags == tags end # GET # If this is an Integer AWS Coral cannot convert it to a String # "class com.amazon.coral.value.json.numbers.TruncatingBigNumber can not be converted to an String" limit = "1" args = LittleDict("limit" => limit) result = Glacier.list_vaults("-", args) @test length(result["VaultList"]) == parse(Int, limit) finally # DELETE for vault in vault_names Glacier.delete_vault("-", vault) end end result = Glacier.list_vaults("-") res_vault_names = [v["VaultName"] for v in result["VaultList"]] for vault in vault_names @test !(vault in res_vault_names) end end @testset "low-level glacier" begin timestamp = _now_formatted() vault_names = ["aws-jl-test-01---$timestamp", "aws-jl-test-02---$timestamp"] # PUT for vault in vault_names AWSServices.glacier("PUT", "/-/vaults/$vault") end try # POST tags = Dict("Tags" => LittleDict("Tag-01" => "Tag-01", "Tag-02" => "Tag-02")) for vault in vault_names AWSServices.glacier("POST", "/-/vaults/$vault/tags?operation=add", tags) end for vault in vault_names result_tags = AWSServices.glacier("GET", "/-/vaults/$vault/tags") @test result_tags == tags end # GET # If this is an Integer AWS Coral cannot convert it to a String # "class com.amazon.coral.value.json.numbers.TruncatingBigNumber can not be converted to an String" limit = "1" params = LittleDict("limit" => limit) result = AWSServices.glacier("GET", "/-/vaults/", params) @test length(result["VaultList"]) == parse(Int, limit) finally # DELETE for vault in vault_names AWSServices.glacier("DELETE", "/-/vaults/$vault") end end result = AWSServices.glacier("GET", "/-/vaults") res_vault_names = [v["VaultName"] for v in result["VaultList"]] for vault in vault_names @test !(vault in res_vault_names) end end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
1462
@testset "AWSConfig" begin @testset "default profile assumes role" begin access_key_id = "assumed_access_key_id" config_dir = joinpath(@__DIR__, "configs", "default-role") # Avoid calling out to STS with invalid credentials patch = Patches._assume_role_patch("AssumeRole"; access_key=access_key_id) config = withenv( [k => nothing for k in filter(startswith("AWS_"), keys(ENV))]..., "AWS_CONFIG_FILE" => joinpath(config_dir, "config"), "AWS_SHARED_CREDENTIALS_FILE" => joinpath(config_dir, "credentials"), ) do apply(patch) do AWSConfig(; profile="default") end end @test config.credentials.access_key_id == access_key_id end @testset "default profile section names" begin allowed_default_sections = ["default", "profile default"] mktemp() do config_path, _ withenv([k => nothing for k in filter(startswith("AWS_"), keys(ENV))]...) do for default_section_str in allowed_default_sections config = """ [$default_section_str] region = xx-yy-1 """ write(config_path, config) region = aws_get_region(; profile="default", config=config_path) @test region == "xx-yy-1" end end end end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
52146
macro test_ecode(error_codes, expr) quote try $expr @test false catch e if e isa AWSException @test e.code in [$error_codes;] else rethrow(e) end end end end const EXPIRATION_FMT = dateformat"yyyy-mm-dd\THH:MM:SS\Z" http_header(h::Vector, k, d="") = get(Dict(h), k, d) http_header(args...) = HTTP.header(args...) @testset "Load Credentials" begin user = aws_user_arn(aws) @test occursin(r"^arn:aws:(iam|sts)::[0-9]+:[^:]+$", user) aws.region = "us-east-1" @test_ecode("InvalidAction", AWSServices.iam("GetFoo")) @test_ecode( ["AccessDenied", "NoSuchEntity"], AWSServices.iam("GetUser", Dict("UserName" => "notauser")) ) @test_ecode("ValidationError", AWSServices.iam("GetUser", Dict("UserName" => "@#!%%!"))) # Please note: If testing in a managed Corporate AWS environment, this can set off alarms... @test_ecode( ["AccessDenied", "EntityAlreadyExists"], AWSServices.iam("CreateUser", Dict("UserName" => "root")) ) end @testset "_role_session_name" begin @test AWS._role_session_name("prefix-", "name", "-suffix") == "prefix-name-suffix" @test AWS._role_session_name("a"^22, "b"^22, "c"^22) == "a"^22 * "b"^20 * "c"^22 end @testset "aws_get_profile_settings" begin @testset "no profile" begin @test aws_get_profile_settings("foo", Inifile()) === nothing end end @testset "_aws_get_role" begin profile = "foobar" ini = Inifile() @testset "settings early exit" begin apply(Patches.get_profile_settings_empty_patch) do @test AWS._aws_get_role(profile, ini) === nothing end end @testset "source_profile early exit" begin apply(Patches.get_profile_settings_empty_patch) do @test AWS._aws_get_role(profile, ini) === nothing end end @testset "default profile" begin access_key_id = "assumed_access_key_id" config_dir = joinpath(@__DIR__, "configs", "default-role") patch = Patches._assume_role_patch("AssumeRole"; access_key=access_key_id) cred = withenv( "AWS_CONFIG_FILE" => joinpath(config_dir, "config"), "AWS_SHARED_CREDENTIALS_FILE" => joinpath(config_dir, "credentials"), "AWS_ACCESS_KEY_ID" => nothing, "AWS_SECRET_ACCESS_KEY" => nothing, ) do ini = read(Inifile(), ENV["AWS_CONFIG_FILE"]) apply(patch) do AWS._aws_get_role("default", ini) end end @test cred.access_key_id == access_key_id end @testset "profile with role and MFA" begin access_key_id = "assumed_access_key_id" config_dir = joinpath(@__DIR__, "configs", "role-with-mfa") mfa_token = "123456" sent_token = Ref("") server_time = DateTime(0) patches = [ Patches._assume_role_patch( "AssumeRole"; access_key=access_key_id, expiry=duration -> server_time + duration, token_code_ref=sent_token, ), Patches._getpass_patch(; secret=mfa_token), ] cred = withenv( "AWS_CONFIG_FILE" => joinpath(config_dir, "config"), "AWS_SHARED_CREDENTIALS_FILE" => joinpath(config_dir, "credentials"), "AWS_ACCESS_KEY_ID" => nothing, "AWS_SECRET_ACCESS_KEY" => nothing, ) do ini = read(Inifile(), ENV["AWS_CONFIG_FILE"]) apply(patches) do AWS._aws_get_role("role_and_mfa", ini) end end @test cred.access_key_id == access_key_id @test cred.expiry == server_time + Second(1234) @test sent_token[] == mfa_token end end @testset "AWSCredentials" begin @testset "Defaults" begin creds = AWSCredentials("access_key_id", "secret_key") @test creds.token == "" @test creds.user_arn == "" @test creds.account_number == "" @test creds.expiry == typemax(DateTime) @test creds.renew === nothing end @testset "Renewal" begin # Credentials shouldn't throw an error if no renew function is supplied creds = AWSCredentials("access_key_id", "secret_key"; renew=nothing) newcreds = check_credentials(creds; force_refresh=true) # Creds should remain unchanged if no renew function exists @test creds === newcreds @test creds.access_key_id == "access_key_id" @test creds.secret_key == "secret_key" @test creds.renew === nothing # Creds should error if the renew function returns nothing creds = AWSCredentials("access_key_id", "secret_key"; renew=() -> nothing) @test_throws NoCredentials check_credentials(creds; force_refresh=true) # Creds should remain unchanged @test creds.access_key_id == "access_key_id" @test creds.secret_key == "secret_key" # Creds should take on value of a returned AWSCredentials except renew function function gen_credentials() i = 0 return () -> (i += 1; AWSCredentials("NEW_ID_$i", "NEW_KEY_$i")) end creds = AWSCredentials( "access_key_id", "secret_key"; renew=gen_credentials(), expiry=now(UTC) ) @test creds.renew !== nothing renewed = creds.renew() @test creds.access_key_id == "access_key_id" @test creds.secret_key == "secret_key" @test creds.expiry <= now(UTC) @test AWS._will_expire(creds) @test renewed.access_key_id === "NEW_ID_1" @test renewed.secret_key == "NEW_KEY_1" @test renewed.renew === nothing @test renewed.expiry == typemax(DateTime) @test !AWS._will_expire(renewed) renew = creds.renew # Check renewal on time out newcreds = check_credentials(creds; force_refresh=false) @test creds === newcreds @test creds.access_key_id == "NEW_ID_2" @test creds.secret_key == "NEW_KEY_2" @test creds.renew !== nothing @test creds.renew === renew @test creds.expiry == typemax(DateTime) @test !AWS._will_expire(creds) # Check renewal doesn't happen if not forced or timed out newcreds = check_credentials(creds; force_refresh=false) @test creds === newcreds @test creds.access_key_id == "NEW_ID_2" @test creds.secret_key == "NEW_KEY_2" @test creds.renew !== nothing @test creds.renew === renew @test creds.expiry == typemax(DateTime) # Check forced renewal works newcreds = check_credentials(creds; force_refresh=true) @test creds === newcreds @test creds.access_key_id == "NEW_ID_3" @test creds.secret_key == "NEW_KEY_3" @test creds.renew !== nothing @test creds.renew === renew @test creds.expiry == typemax(DateTime) end mktempdir() do dir config_file = joinpath(dir, "config") creds_file = joinpath(dir, "creds") write( config_file, """ [profile test] output = json region = us-east-1 [profile test:dev] source_profile = test role_arn = arn:aws:iam::123456789000:role/Dev [profile test:sub-dev] source_profile = test:dev role_arn = arn:aws:iam::123456789000:role/SubDev [profile test2] aws_access_key_id = WRONG_ACCESS_ID aws_secret_access_key = WRONG_ACCESS_KEY output = json region = us-east-1 [profile test3] source_profile = test:dev role_arn = arn:aws:iam::123456789000:role/test3 [profile test4] aws_access_key_id = RIGHT_ACCESS_ID4 aws_secret_access_key = RIGHT_ACCESS_KEY4 source_profile = test:dev role_arn = arn:aws:iam::123456789000:role/test3 """, ) write( creds_file, """ [test] aws_access_key_id = TEST_ACCESS_ID aws_secret_access_key = TEST_ACCESS_KEY [test2] aws_access_key_id = RIGHT_ACCESS_ID2 aws_secret_access_key = RIGHT_ACCESS_KEY2 [test3] aws_access_key_id = RIGHT_ACCESS_ID3 aws_secret_access_key = RIGHT_ACCESS_KEY3 """, ) withenv( "AWS_SHARED_CREDENTIALS_FILE" => creds_file, "AWS_CONFIG_FILE" => config_file, "AWS_DEFAULT_PROFILE" => "test", "AWS_PROFILE" => nothing, "AWS_ACCESS_KEY_ID" => nothing, ) do @testset "Loading" begin # Check credentials load config = AWSConfig() creds = config.credentials @test creds isa AWSCredentials @test creds.access_key_id == "TEST_ACCESS_ID" @test creds.secret_key == "TEST_ACCESS_KEY" @test creds.renew !== nothing # Check credential file takes precedence over config withenv("AWS_DEFAULT_PROFILE" => "test2") do config = AWSConfig() creds = config.credentials @test creds.access_key_id == "RIGHT_ACCESS_ID2" @test creds.secret_key == "RIGHT_ACCESS_KEY2" end # Check credentials take precedence over role withenv("AWS_DEFAULT_PROFILE" => "test3") do config = AWSConfig() creds = config.credentials @test creds.access_key_id == "RIGHT_ACCESS_ID3" @test creds.secret_key == "RIGHT_ACCESS_KEY3" end withenv("AWS_DEFAULT_PROFILE" => "test4") do config = AWSConfig() creds = config.credentials @test creds.access_key_id == "RIGHT_ACCESS_ID4" @test creds.secret_key == "RIGHT_ACCESS_KEY4" end end @testset "Refresh" begin withenv("AWS_DEFAULT_PROFILE" => "test") do # Check credentials refresh on timeout config = AWSConfig() creds = config.credentials creds.access_key_id = "EXPIRED_ACCESS_ID" creds.secret_key = "EXPIRED_ACCESS_KEY" creds.expiry = now(UTC) @test creds.renew !== nothing renew = creds.renew @test renew() isa AWSCredentials creds = check_credentials(config.credentials) @test creds.access_key_id == "TEST_ACCESS_ID" @test creds.secret_key == "TEST_ACCESS_KEY" @test creds.expiry > now(UTC) # Check renew function remains unchanged @test creds.renew !== nothing @test creds.renew === renew # Check force_refresh creds.access_key_id = "WRONG_ACCESS_KEY" creds = check_credentials(creds; force_refresh=true) @test creds.access_key_id == "TEST_ACCESS_ID" end end @testset "Profile" begin # Check profile kwarg withenv("AWS_DEFAULT_PROFILE" => "test") do creds = AWSCredentials(; profile="test2") @test creds.access_key_id == "RIGHT_ACCESS_ID2" @test creds.secret_key == "RIGHT_ACCESS_KEY2" config = AWSConfig(; profile="test2") creds = config.credentials @test creds.access_key_id == "RIGHT_ACCESS_ID2" @test creds.secret_key == "RIGHT_ACCESS_KEY2" # Check profile persists on renewal creds.access_key_id = "WRONG_ACCESS_ID2" creds.secret_key = "WRONG_ACCESS_KEY2" creds = check_credentials(creds; force_refresh=true) @test creds.access_key_id == "RIGHT_ACCESS_ID2" @test creds.secret_key == "RIGHT_ACCESS_KEY2" end end @testset "Assume Role" begin # Check we try to assume a role withenv("AWS_DEFAULT_PROFILE" => "test:dev") do @test_ecode("InvalidClientTokenId", AWSConfig()) end # Check we try to assume a role withenv("AWS_DEFAULT_PROFILE" => "test:sub-dev") do oldout = stdout r, w = redirect_stdout() @test_ecode("InvalidClientTokenId", AWSConfig()) redirect_stdout(oldout) close(w) output = String(read(r)) occursin("Assuming \"test:dev\"", output) occursin("Assuming \"test\"", output) close(r) end end end end # Verify that the search order for credentials mirrors the behavior of the AWS CLI # (version 2.11.13). Whenever support is added for new credential types new tests should # be added to this test set. To determine the credential preference order used by AWS # CLI it is recommended you use a set of valid credentials and a set of invalid # credentials to determine the precedence. # # Documentation on credential precedence: # - https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-authentication.html#cli-chap-authentication-precedence # - https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/creds-assign.html # - https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html @testset "Credential Precedence" begin mktempdir() do dir config_file = joinpath(dir, "config") creds_file = joinpath(dir, "creds") basic_creds_content = """ [profile1] aws_access_key_id = AKI1 aws_secret_access_key = SAK1 [profile2] aws_access_key_id = AKI2 aws_secret_access_key = SAK2 """ ec2_json = Dict( "AccessKeyId" => "AKI_EC2", "SecretAccessKey" => "SAK_EC2", "Token" => "TOK_EC2", "Expiration" => Dates.format(now(UTC), EXPIRATION_FMT), ) function ec2_metadata(url::AbstractString) name = "local-credentials" metadata_uri = "http://169.254.169.254/latest/meta-data" if url == "$metadata_uri/iam/info" return HTTP.Response(200, JSON.json("InstanceProfileArn" => "ARN0")) elseif url == "$metadata_uri/iam/security-credentials/" return HTTP.Response(200, name) elseif url == "$metadata_uri/iam/security-credentials/$name" return HTTP.Response(200, JSON.json(ec2_json)) else return HTTP.Response(404) end end ecs_json = Dict( "AccessKeyId" => "AKI_ECS", "SecretAccessKey" => "SAK_ECS", "Token" => "TOK_ECS", "Expiration" => Dates.format(now(UTC), EXPIRATION_FMT), ) function ecs_metadata(url::AbstractString) if startswith(url, "http://169.254.170.2/") return HTTP.Response(200, JSON.json(ecs_json)) else return HTTP.Response(404) end end function ecs_metadata_localhost(url::AbstractString) if startswith(url, "http://localhost:8080") return HTTP.Response(200, JSON.json(ecs_json)) else return HTTP.Response(404) end end function http_request_patcher(funcs) @patch function HTTP.request(method, url, args...; kwargs...) local r for f in funcs r = f(string(url)) r.status != 404 && break end return r end end withenv( [k => nothing for k in filter(startswith("AWS_"), keys(ENV))]..., "AWS_SHARED_CREDENTIALS_FILE" => creds_file, "AWS_CONFIG_FILE" => config_file, ) do @testset "explicit profile preferred" begin isfile(config_file) && rm(config_file) write(creds_file, basic_creds_content) withenv("AWS_PROFILE" => "profile1") do creds = AWSCredentials(; profile="profile2") @test creds.access_key_id == "AKI2" end withenv( "AWS_ACCESS_KEY_ID" => "AKI0", "AWS_SECRET_ACCESS_KEY" => "SAK0", # format trick: using this comment to force use of multiple lines ) do creds = AWSCredentials(; profile="profile2") @test creds.access_key_id == "AKI2" end end @testset "AWS_ACCESS_KEY_ID preferred over AWS_PROFILE" begin isfile(config_file) && rm(config_file) write(creds_file, basic_creds_content) withenv( "AWS_PROFILE" => "profile1", "AWS_ACCESS_KEY_ID" => "AKI0", "AWS_SECRET_ACCESS_KEY" => "SAK0", ) do creds = AWSCredentials() @test creds.access_key_id == "AKI0" end end # The AWS CLI used to use `AWS_DEFAULT_PROFILE` to set the AWS profile via the # command line but this was deprecated in favor of `AWS_PROFILE`. We'll probably # keeps support for this as long as AWS CLI continues to support it. # https://github.com/aws/aws-cli/issues/2597 @testset "AWS_PROFILE preferred over AWS_DEFAULT_PROFILE" begin isfile(config_file) && rm(config_file) write(creds_file, basic_creds_content) withenv( "AWS_DEFAULT_PROFILE" => "profile1", "AWS_PROFILE" => "profile2", # format trick: using this comment to force use of multiple lines ) do creds = AWSCredentials() @test creds.access_key_id == "AKI2" end end @testset "Web identity preferred over SSO" begin write( config_file, """ [default] sso_start_url = https://my-sso-portal.awsapps.com/start sso_role_name = role1 """, ) isfile(creds_file) && rm(creds_file) web_identity_file = joinpath(dir, "web_identity") write(web_identity_file, "webid") patches = [ Patches._assume_role_patch( "AssumeRoleWithWebIdentity"; access_key="AKI_WEB", secret_key="SAK_WEB", session_token="TOK_WEB", ), Patches.sso_service_patches("AKI_SSO", "SAK_SSO"), Patches._imds_region_patch(nothing), ] withenv( "AWS_WEB_IDENTITY_TOKEN_FILE" => web_identity_file, "AWS_ROLE_ARN" => "webid", ) do apply(patches) do creds = AWSCredentials() @test creds.access_key_id == "AKI_WEB" end end end # TODO: Additional, precedence tests should be added for IAM Identity Center # once support has been introduced. @testset "IAM Identity Center preferred over legacy SSO" begin write( config_file, """ [sso-session my-sso] sso_region = us-east-1 sso_start_url = https://my-sso-portal.awsapps.com/start [default] sso_session = my-sso sso_start_url = https://my-legacy-sso-portal.awsapps.com/start sso_role_name = role1 """, ) isfile(creds_file) && rm(creds_file) apply(Patches.sso_service_patches("AKI_SSO", "SAK_SSO")) do @test_throws ErrorException AWSCredentials() end end @testset "SSO preferred over credentials file" begin write( config_file, """ [profile profile1] sso_start_url = https://my-sso-portal.awsapps.com/start sso_role_name = role1 """, ) write(creds_file, basic_creds_content) apply(Patches.sso_service_patches("AKI_SSO", "SAK_SSO")) do creds = AWSCredentials(; profile="profile1") @test creds.access_key_id == "AKI_SSO" end end @testset "Credential file over credential_process" begin json = Dict( "Version" => 1, "AccessKeyId" => "AKI0", "SecretAccessKey" => "SAK0", # format trick: using this comment to force use of multiple lines ) write( config_file, """ [profile profile1] credential_process = echo '$(JSON.json(json))' """, ) write(creds_file, basic_creds_content) creds = AWSCredentials(; profile="profile1") @test creds.access_key_id == "AKI1" end @testset "credential_process over config credentials" begin json = Dict( "Version" => 1, "AccessKeyId" => "AKI0", "SecretAccessKey" => "SAK0", # format trick: using this comment to force use of multiple lines ) write( config_file, """ [profile profile1] aws_access_key_id = AKI1 aws_secret_access_key = SAK1 credential_process = echo '$(JSON.json(json))' """, ) isfile(creds_file) && rm(creds_file) creds = AWSCredentials(; profile="profile1") @test creds.access_key_id == "AKI0" end @testset "default config credentials over ECS container credentials ENV variables" begin write( config_file, """ [default] aws_access_key_id = AKI1 aws_secret_access_key = SAK1 """, ) isfile(creds_file) && rm(creds_file) withenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" => "/get-creds") do apply(http_request_patcher([ecs_metadata])) do @test isnothing(AWS._aws_get_profile(; default=nothing)) creds = AWSCredentials() @test creds.access_key_id == "AKI1" end end withenv( "AWS_CONTAINER_CREDENTIALS_FULL_URI" => "http://localhost:8080" ) do apply(http_request_patcher([ecs_metadata_localhost])) do @test isnothing(AWS._aws_get_profile(; default=nothing)) creds = AWSCredentials() @test creds.access_key_id == "AKI1" end end end @testset "default config credentials over EC2 instance credentials" begin write( config_file, """ [default] aws_access_key_id = AKI1 aws_secret_access_key = SAK1 """, ) isfile(creds_file) && rm(creds_file) apply(http_request_patcher([ec2_metadata])) do @test isnothing(AWS._aws_get_profile(; default=nothing)) creds = AWSCredentials() @test creds.access_key_id == "AKI1" end end @testset "ECS container credentials ENV variables over EC2 instance credentials" begin isfile(config_file) && rm(config_file) isfile(creds_file) && rm(creds_file) withenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" => "/get-creds") do apply(http_request_patcher([ec2_metadata, ecs_metadata])) do creds = AWSCredentials() @test creds.access_key_id == "AKI_ECS" end end withenv( "AWS_CONTAINER_CREDENTIALS_FULL_URI" => "http://localhost:8080" ) do p = http_request_patcher([ec2_metadata, ecs_metadata_localhost]) apply(p) do creds = AWSCredentials() @test creds.access_key_id == "AKI_ECS" end end end # Note: It appears that the ECS container credentials are only used when # a `AWS_CONTAINER_*` environmental variable is set. However, this test # ensures that if we do add implicit support that the documented precedence # order is not violated. @testset "EC2 instance credentials over ECS container credentials" begin isfile(config_file) && rm(config_file) isfile(creds_file) && rm(creds_file) apply(http_request_patcher([ec2_metadata, ecs_metadata])) do creds = AWSCredentials() @test creds.access_key_id == "AKI_EC2" end end end end end end @testset "Retrieving AWS Credentials" begin test_values = Dict{String,Any}( "Default-Profile" => "default", "Test-Profile" => "test", "Test-Config-Profile" => "test", "AccessKeyId" => "Default-Key", "SecretAccessKey" => "Default-Secret", "Test-AccessKeyId" => "Test-Key", "Test-SecretAccessKey" => "Test-Secret", "Token" => "Test-Token", "InstanceProfileArn" => "Test-Arn", "RoleArn" => "Test-Arn", "Expiration" => now(UTC), "Security-Credentials" => "Test-Security-Credentials", "Test-SSO-Profile" => "sso-test", "Test-SSO-start-url" => "https://test-sso.com/start", "Test-SSO-Role" => "SSORoleName", ) @testset "~/.aws/config - Default Profile" begin mktemp() do config_file, config_io write( config_io, """ [$(test_values["Default-Profile"])] aws_access_key_id=$(test_values["AccessKeyId"]) aws_secret_access_key=$(test_values["SecretAccessKey"]) """, ) close(config_io) withenv("AWS_CONFIG_FILE" => config_file) do default_profile = dot_aws_config(test_values["Default-Profile"]) @test default_profile.access_key_id == test_values["AccessKeyId"] @test default_profile.secret_key == test_values["SecretAccessKey"] end end end @testset "~/.aws/config - Specified Profile" begin mktemp() do config_file, config_io write( config_io, """ [profile $(test_values["Test-Config-Profile"])] aws_access_key_id=$(test_values["Test-AccessKeyId"]) aws_secret_access_key=$(test_values["Test-SecretAccessKey"]) """, ) close(config_io) withenv("AWS_CONFIG_FILE" => config_file) do specified_result = dot_aws_config(test_values["Test-Profile"]) @test specified_result.access_key_id == test_values["Test-AccessKeyId"] @test specified_result.secret_key == test_values["Test-SecretAccessKey"] end end end @testset "~/.aws/config - Specified SSO Profile" begin mktemp() do config_file, config_io write( config_io, """ [profile $(test_values["Test-SSO-Profile"])] sso_start_url=$(test_values["Test-SSO-start-url"]) sso_role_name=$(test_values["Test-SSO-Role"]) """, ) close(config_io) withenv("AWS_CONFIG_FILE" => config_file) do apply( Patches.sso_service_patches( test_values["AccessKeyId"], test_values["SecretAccessKey"] ), ) do specified_result = sso_credentials(test_values["Test-SSO-Profile"]) @test specified_result.access_key_id == test_values["AccessKeyId"] @test specified_result.secret_key == test_values["SecretAccessKey"] end end end end @testset "~/.aws/config - Credential Process" begin mktempdir() do dir config_file = joinpath(dir, "config") credential_process_file = joinpath(dir, "cred_process") open(credential_process_file, "w") do io println(io, "#!/bin/sh") println(io, "cat <<EOF") json = Dict( "Version" => 1, "AccessKeyId" => test_values["Test-AccessKeyId"], "SecretAccessKey" => test_values["Test-SecretAccessKey"], ) JSON.print(io, json) println(io, "\nEOF") end chmod(credential_process_file, 0o700) withenv("AWS_CONFIG_FILE" => config_file) do open(config_file, "w") do io write( io, """ [profile $(test_values["Test-Config-Profile"])] credential_process = $(abspath(credential_process_file)) """, ) end result = dot_aws_config(test_values["Test-Config-Profile"]) @test result.access_key_id == test_values["Test-AccessKeyId"] @test result.secret_key == test_values["Test-SecretAccessKey"] @test isempty(result.token) @test result.expiry == typemax(DateTime) end end end @testset "~/.aws/creds - Default Profile" begin mktemp() do creds_file, creds_io write( creds_io, """ [$(test_values["Default-Profile"])] aws_access_key_id=$(test_values["AccessKeyId"]) aws_secret_access_key=$(test_values["SecretAccessKey"]) """, ) close(creds_io) withenv("AWS_SHARED_CREDENTIALS_FILE" => creds_file) do specified_result = dot_aws_credentials(test_values["Default-Profile"]) @test specified_result.access_key_id == test_values["AccessKeyId"] @test specified_result.secret_key == test_values["SecretAccessKey"] end end end @testset "~/.aws/creds - Specified Profile" begin mktemp() do creds_file, creds_io write( creds_io, """ [$(test_values["Test-Profile"])] aws_access_key_id=$(test_values["Test-AccessKeyId"]) aws_secret_access_key=$(test_values["Test-SecretAccessKey"]) """, ) close(creds_io) withenv("AWS_SHARED_CREDENTIALS_FILE" => creds_file) do specified_result = dot_aws_credentials(test_values["Test-Profile"]) @test specified_result.access_key_id == test_values["Test-AccessKeyId"] @test specified_result.secret_key == test_values["Test-SecretAccessKey"] end end end @testset "Environment Variables" begin withenv( "AWS_ACCESS_KEY_ID" => test_values["AccessKeyId"], "AWS_SECRET_ACCESS_KEY" => test_values["SecretAccessKey"], ) do aws_creds = env_var_credentials() @test aws_creds.access_key_id == test_values["AccessKeyId"] @test aws_creds.secret_key == test_values["SecretAccessKey"] end end @testset "Instance - EC2" begin role_name = "foobar" role_arn = "arn:aws:sts::1234:assumed-role/$role_name" access_key = "access-key-$(randstring(6))" secret_key = "secret-key-$(randstring(6))" session_token = "session-token-$(randstring(6))" session_name = "$role_name-session" assume_role_patch = Patches._assume_role_patch( "AssumeRole"; access_key=access_key, secret_key=secret_key, session_token=session_token, role_arn=role_arn, ) ec2_metadata_patch = @patch function HTTP.request(method, url, args...; kwargs...) url = string(url) security_credentials = test_values["Security-Credentials"] metadata_uri = "http://169.254.169.254/latest/meta-data" if url == "$metadata_uri/iam/info" json = JSON.json("InstanceProfileArn" => test_values["InstanceProfileArn"]) return HTTP.Response(200, json) elseif url == "$metadata_uri/iam/security-credentials/" return HTTP.Response(200, security_credentials) elseif url == "$metadata_uri/iam/security-credentials/$security_credentials" return HTTP.Response(200, JSON.json(test_values)) else return HTTP.Response(404) end end apply([assume_role_patch, ec2_metadata_patch]) do result = ec2_instance_credentials("default") @test result.access_key_id == test_values["AccessKeyId"] @test result.secret_key == test_values["SecretAccessKey"] @test result.token == test_values["Token"] @test result.user_arn == test_values["InstanceProfileArn"] @test result.expiry == test_values["Expiration"] @test result.renew !== nothing result = mktemp() do config_file, config_io write( config_io, """ [profile $role_name] credential_source = Ec2InstanceMetadata role_arn = $role_arn """, ) close(config_io) withenv( "AWS_CONFIG_FILE" => config_file, "AWS_ROLE_SESSION_NAME" => session_name, ) do ec2_instance_credentials(role_name) end end @test result.access_key_id == access_key @test result.secret_key == secret_key @test result.token == session_token @test result.user_arn == "$(role_arn)/$(session_name)" @test result.renew !== nothing end end @testset "Instance - ECS" begin expiration = floor(now(UTC), Second) rel_uri_json = Dict( "AccessKeyId" => "AKI_REL_ECS", "SecretAccessKey" => "SAK_REL_ECS", "Token" => "TOK_REL_ECS", "Expiration" => Dates.format(expiration, dateformat"yyyy-mm-dd\THH:MM:SS\Z"), "RoleArn" => "ROLE_REL_ECS", ) rel_uri_patch = @patch function HTTP.request(::String, url, headers=[]; kwargs...) url = string(url) @test url == "http://169.254.170.2/get-credentials" @test isempty(headers) if url == "http://169.254.170.2/get-credentials" return HTTP.Response(200, JSON.json(rel_uri_json)) else return HTTP.Response(404) end end withenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" => "/get-credentials") do apply(rel_uri_patch) do result = ecs_instance_credentials() @test result.access_key_id == rel_uri_json["AccessKeyId"] @test result.secret_key == rel_uri_json["SecretAccessKey"] @test result.token == rel_uri_json["Token"] @test result.user_arn == rel_uri_json["RoleArn"] @test result.expiry == expiration @test result.renew == ecs_instance_credentials end end # When the environmental variable isn't set then the ECS credential provider is # unavailable. withenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" => nothing) do @test ecs_instance_credentials() === nothing end # Specifying the environmental variable results in us attempting to connect to the # ECS credential provider. withenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" => "/invalid") do # Internally throws a `ConnectError` exception @test ecs_instance_credentials() === nothing end full_uri_json = Dict( "AccessKeyId" => "AKI_FULL_ECS", "SecretAccessKey" => "SAK_FULL_ECS", "Token" => "TOK_FULL_ECS", "Expiration" => Dates.format(expiration, dateformat"yyyy-mm-dd\THH:MM:SS\Z"), "RoleArn" => "ROLE_FULL_ECS", ) full_uri_patch = @patch function HTTP.request(::String, url, headers=[]; kwargs...) url = string(url) authorization = http_header(headers, "Authorization") @test url == "http://localhost/get-credentials" @test authorization == "Basic abcd" if url == "http://localhost/get-credentials" && authorization == "Basic abcd" return HTTP.Response(200, JSON.json(full_uri_json)) else return HTTP.Response(403) end end withenv( "AWS_CONTAINER_CREDENTIALS_FULL_URI" => "http://localhost/get-credentials", "AWS_CONTAINER_AUTHORIZATION_TOKEN" => "Basic abcd", ) do apply(full_uri_patch) do result = ecs_instance_credentials() @test result.access_key_id == full_uri_json["AccessKeyId"] @test result.secret_key == full_uri_json["SecretAccessKey"] @test result.token == full_uri_json["Token"] @test result.user_arn == full_uri_json["RoleArn"] @test result.expiry == expiration @test result.renew == ecs_instance_credentials end end # `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` should be preferred over # `AWS_CONTAINER_CREDENTIALS_FULL_URI`. withenv( "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" => "/get-credentials", "AWS_CONTAINER_CREDENTIALS_FULL_URI" => "http://localhost/get-credentials", ) do apply(rel_uri_patch) do result = ecs_instance_credentials() @test result.access_key_id == rel_uri_json["AccessKeyId"] end end end @testset "Web Identity File" begin @test credentials_from_webtoken() == nothing mktempdir() do dir web_identity_file = joinpath(dir, "web_identity") write(web_identity_file, "foobar") session_name = "foobar-session" access_key = "access-key-$(randstring(6))" secret_key = "secret-key-$(randstring(6))" session_token = "session-token-$(randstring(6))" role_arn = "arn:aws:sts::1234:assumed-role/foobar" patch = Patches._assume_role_patch( "AssumeRoleWithWebIdentity"; access_key=access_key, secret_key=secret_key, session_token=session_token, role_arn=role_arn, expiry=duration -> now(UTC), # expire immediately to check renewal ) withenv( "AWS_ROLE_ARN" => "foobar", "AWS_WEB_IDENTITY_TOKEN_FILE" => web_identity_file, "AWS_ROLE_SESSION_NAME" => session_name, ) do apply(patch) do result = credentials_from_webtoken() @test result.access_key_id == access_key @test result.secret_key == secret_key @test result.token == session_token @test result.user_arn == "$(role_arn)/$(session_name)" @test result.renew == credentials_from_webtoken expiry = result.expiry sleep(0.1) result = check_credentials(result) @test result.access_key_id == access_key @test result.secret_key == secret_key @test result.token == session_token @test result.user_arn == "$(role_arn)/$(session_name)" @test result.renew == credentials_from_webtoken @test expiry != result.expiry end end session_name = "AWS.jl-role-foobar-20210101T000000Z" patches = [ patch @patch Dates.now(::Type{UTC}) = DateTime(2021) ] withenv( "AWS_ROLE_ARN" => "foobar", "AWS_WEB_IDENTITY_TOKEN_FILE" => web_identity_file, "AWS_ROLE_SESSION_NAME" => nothing, ) do apply(patches) do result = credentials_from_webtoken() @test result.user_arn == "$(role_arn)/$(session_name)" end end end end @testset "Credential Process" begin gen_process(json) = Cmd(["echo", JSON.json(json)]) long_term_resp = Dict( "Version" => 1, "AccessKeyId" => "access-key", "SecretAccessKey" => "secret-key", # format trick: using this comment to force use of multiple lines ) creds = external_process_credentials(gen_process(long_term_resp)) @test creds.access_key_id == long_term_resp["AccessKeyId"] @test creds.secret_key == long_term_resp["SecretAccessKey"] @test isempty(creds.token) @test creds.expiry == typemax(DateTime) expiration = floor(now(UTC), Second) temporary_resp = Dict( "Version" => 1, "AccessKeyId" => "access-key", "SecretAccessKey" => "secret-key", "SessionToken" => "session-token", "Expiration" => Dates.format(expiration, EXPIRATION_FMT), ) creds = external_process_credentials(gen_process(temporary_resp)) @test creds.access_key_id == temporary_resp["AccessKeyId"] @test creds.secret_key == temporary_resp["SecretAccessKey"] @test creds.token == temporary_resp["SessionToken"] @test creds.expiry == expiration unhandled_version_resp = Dict("Version" => 2) json = sprint(JSON.print, unhandled_version_resp, 2) ex = ErrorException("Credential process returned unhandled version 2:\n$json") @test_throws ex external_process_credentials(gen_process(unhandled_version_resp)) missing_token_resp = Dict( "Version" => 1, "AccessKeyId" => "access-key", "SecretAccessKey" => "secret-key", "Expiration" => Dates.format(expiration, EXPIRATION_FMT), ) ex = KeyError("SessionToken") @test_throws ex external_process_credentials(gen_process(missing_token_resp)) missing_expiration_resp = Dict( "Version" => 1, "AccessKeyId" => "access-key", "SecretAccessKey" => "secret-key", "SessionToken" => "session-token", ) ex = KeyError("Expiration") @test_throws ex external_process_credentials(gen_process(missing_expiration_resp)) end @testset "Credentials Not Found" begin patches = [ @patch function HTTP.request(method::String, url, args...; kwargs...) throw(HTTP.Exceptions.ConnectError(string(url), "host is unreachable")) end Patches._cred_file_patch Patches._config_file_patch ] withenv( "AWS_ACCESS_KEY_ID" => nothing, "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" => nothing, ) do apply(patches) do @test_throws NoCredentials AWSConfig() end end end @testset "Helper functions" begin @testset "Check Credentials - EnvVars" begin withenv( "AWS_ACCESS_KEY_ID" => test_values["AccessKeyId"], "AWS_SECRET_ACCESS_KEY" => test_values["SecretAccessKey"], ) do testAWSCredentials = AWSCredentials( test_values["AccessKeyId"], test_values["SecretAccessKey"]; expiry=Dates.now(UTC) - Minute(10), renew=env_var_credentials, ) result = check_credentials(testAWSCredentials; force_refresh=true) @test result.access_key_id == testAWSCredentials.access_key_id @test result.secret_key == testAWSCredentials.secret_key @test result.expiry == typemax(DateTime) @test result.renew == testAWSCredentials.renew end end end end @testset "aws_get_region" begin mktempdir() do dir config_str = """ [default] region = us-west-2 [profile test] region = ap-northeast-1 """ config_file = joinpath(dir, "config") write(config_file, config_str) ini = read(Inifile(), IOBuffer(config_str)) @testset "environmental variable" begin withenv("AWS_DEFAULT_REGION" => "us-gov-east-1") do @test aws_get_region(; config=ini, profile="default") == "us-gov-east-1" @test aws_get_region() == "us-gov-east-1" end end @testset "default profile" begin withenv("AWS_DEFAULT_REGION" => nothing) do @test aws_get_region(; config=ini, profile="default") == "us-west-2" @test aws_get_region(; config=config_file, profile="default") == "us-west-2" end withenv( "AWS_DEFAULT_REGION" => nothing, "AWS_CONFIG_FILE" => config_file, "AWS_PROFILE" => nothing, "AWS_DEFAULT_PROFILE" => nothing, ) do @test aws_get_region() == "us-west-2" end end @testset "specified profile" begin withenv("AWS_DEFAULT_REGION" => nothing) do @test aws_get_region(; config=ini, profile="test") == "ap-northeast-1" @test aws_get_region(; config=config_file, profile="test") == "ap-northeast-1" end withenv( "AWS_DEFAULT_REGION" => nothing, "AWS_CONFIG_FILE" => config_file, "AWS_PROFILE" => "test", ) do @test aws_get_region() == "ap-northeast-1" end end @testset "unknown profile" begin withenv("AWS_DEFAULT_REGION" => nothing) do apply(Patches._imds_region_patch(nothing)) do @test aws_get_region(; config=ini, profile="unknown") == AWS.DEFAULT_REGION @test aws_get_region(; config=config_file, profile="unknown") == AWS.DEFAULT_REGION end end withenv( "AWS_DEFAULT_REGION" => nothing, "AWS_CONFIG_FILE" => config_file, "AWS_PROFILE" => "unknown", ) do apply(Patches._imds_region_patch(nothing)) do @test aws_get_region() == AWS.DEFAULT_REGION end end end @testset "default keyword" begin default = nothing withenv("AWS_DEFAULT_REGION" => nothing) do apply(Patches._imds_region_patch(nothing)) do @test aws_get_region(; config=ini, profile="unknown", default) === default @test aws_get_region(; config=config_file, profile="unknown", default ) === default end end withenv( "AWS_DEFAULT_REGION" => nothing, "AWS_CONFIG_FILE" => config_file, "AWS_PROFILE" => "unknown", ) do apply(Patches._imds_region_patch(nothing)) do @test aws_get_region(; default=default) === default end end end @testset "no such config file" begin withenv("AWS_DEFAULT_REGION" => nothing, "AWS_CONFIG_FILE" => tempname()) do apply(Patches._imds_region_patch(nothing)) do @test aws_get_region() == AWS.DEFAULT_REGION end end end @testset "instance profile" begin withenv("AWS_DEFAULT_REGION" => nothing, "AWS_CONFIG_FILE" => tempname()) do apply(Patches._imds_region_patch("ap-atlantis-1")) do @test aws_get_region() == "ap-atlantis-1" end end end end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
5121
@testset "AWSException" begin function _test_exception(ex::AWSException, expected::AbstractDict, msg::String) @test ex.code == expected["code"] @test ex.message == ex.info[msg] == expected["message"] @test ex.cause.response.body == expected["body"] @test ex.cause.status == expected["status_code"] @test ex.cause.response.headers == expected["headers"] @test ex.streamed_body == expected["streamed_body"] end cases = [ ("Error", "message"), ("Error", "Message"), ("Errors", "message"), ("Errors", "Message"), ] @testset "XMLRequest $err -- $msg" for (err, msg) in cases expected = Dict( "code" => "NoSuchKey", "message" => "The resource you requested does not exist", "resource" => "/mybucket/myfoto.jpg", "requestId" => "4442587FB7D0A2F9", "headers" => ["Content-Type" => "application/xml"], "status_code" => 400, ) expected["body"] = IOBuffer() expected["streamed_body"] = """ <?xml version="1.0" encoding="UTF-8"?> <$err> <Code>$(expected["code"])</Code> <$msg>$(expected["message"])</$msg> <Resource>$(expected["resource"])</Resource> <RequestId>$(expected["requestId"])</RequestId> </$err> """ # This does not actually send a request, just creates the object to test with req = HTTP.Request("GET", "https://aws.com", expected["headers"], expected["body"]) resp = HTTP.Response( expected["status_code"], expected["headers"]; body=expected["body"], request=req ) status_error = AWS.statuserror(expected["status_code"], resp) ex = AWSException(status_error, expected["streamed_body"]) _test_exception(ex, expected, msg) @test ex.info["Resource"] == expected["resource"] @test ex.info["RequestId"] == expected["requestId"] end @testset "XMLRequest - Invalid XML" begin expected = Dict( "body" => IOBuffer(), "streamed_body" => """<?xml version="1.0" encoding="UTF-8"?>InvalidXML""", "headers" => ["Content-Type" => "application/xml"], "status_code" => 404, ) req = HTTP.Request("GET", "https://aws.com", expected["headers"], expected["body"]) resp = HTTP.Response( expected["status_code"], expected["headers"]; body=expected["body"], request=req ) status_error = AWS.statuserror(expected["status_code"], resp) ex = @test_logs (:error,) AWSException(status_error, expected["streamed_body"]) @test ex.code == "404" @test ex.streamed_body == expected["streamed_body"] end @testset "JSON Request -- $msg" for msg in ["message", "Message"] expected = Dict( "code" => "InvalidSignatureException", "message" => "Signature expired: ...", "headers" => ["Content-Type" => "application/x-amz-json-1.1"], "status_code" => 400, ) expected["body"] = IOBuffer() expected["streamed_body"] = """ { "__type": "$(expected["code"])", "$msg": "$(expected["message"])" } """ # This does not actually send a request, just creates the object to test with req = HTTP.Request("GET", "https://aws.com", expected["headers"], expected["body"]) resp = HTTP.Response( expected["status_code"], expected["headers"]; body=expected["body"], request=req ) status_error = AWS.statuserror(expected["status_code"], resp) ex = AWSException(status_error, expected["streamed_body"]) _test_exception(ex, expected, "$msg") @test ex.info["__type"] == expected["code"] end @testset "JSON requests can have invalid bodies" begin expected = Dict( "code" => "400", "message" => "AWSException", "headers" => ["Content-Type" => "application/json"], "status_code" => 400, ) expected["body"] = IOBuffer() expected["streamed_body"] = "\"foo\"" # This does not actually send a request, just creates the object to test with req = HTTP.Request("GET", "https://aws.com", expected["headers"], expected["body"]) resp = HTTP.Response( expected["status_code"], expected["headers"]; body=expected["body"], request=req ) status_error = AWS.statuserror(expected["status_code"], resp) ex = AWSException(status_error, expected["streamed_body"]) @test ex.code == expected["code"] @test ex.info == "foo" # nothing better we can do than just forward the invalid body @test ex.message == expected["message"] @test ex.cause.response.body == expected["body"] @test ex.cause.status == expected["status_code"] @test ex.cause.response.headers == expected["headers"] @test ex.streamed_body == expected["streamed_body"] end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
25039
function _clean_high_level_definition(definition::String) # Required Julia 1.5 or higher with how triple quoted strings are dealt with. definition = replace(definition, " " => "") definition = replace(definition, "\n" => "") return definition end @testset "_get_service_files" begin apply(Patches._github_tree_patch) do service_files = _get_service_files("foobar", GitHub.OAuth2("foobar")) @test length(service_files) == 1 @test service_files[1] == ServiceFile("foobar", "test-2020-01-01.normal.json", "test-sha", nothing) end end @testset "_filter_latest_service_version" begin migration_hub_v1 = Dict("path" => "AWSMigrationHub-2017-05-31.normal.json") migration_hub_v2 = Dict("path" => "AWSMigrationHub-2020-01-01.normal.json") access_analyzer_v1 = Dict("path" => "accessanalyzer-2019-11-01.normal.json") access_analyzer_v2 = Dict("path" => "accessanalyzer-2020-01-01.normal.json") @testset "empty" begin @test isempty(_filter_latest_service_version([])) end @testset "single service - single version" begin result = _filter_latest_service_version([migration_hub_v1]) @test result == [migration_hub_v1] end @testset "single service - multiple versions" begin result = _filter_latest_service_version([migration_hub_v1, migration_hub_v2]) @test result == [migration_hub_v2] end @testset "multiple service - single version" begin result = _filter_latest_service_version([migration_hub_v1, access_analyzer_v1]) @test result == [access_analyzer_v1, migration_hub_v1] end @testset "multiple services - multiple versions" begin result = _filter_latest_service_version([ migration_hub_v1, migration_hub_v2, access_analyzer_v1, access_analyzer_v2 ]) @test result == [access_analyzer_v2, migration_hub_v2] end end @testset "_get_service_and_version" begin @testset "empty string" begin filename = "" @test_throws InvalidFileName _get_service_and_version(filename) end @testset "invalid filename" begin filename = "This is an invalid file name." @test_throws InvalidFileName _get_service_and_version(filename) end @testset "valid filename" begin filename = "AWSMigrationHub-2017-05-31.normal.json" service, version = _get_service_and_version(filename) @test service == "AWSMigrationHub" @test version == "2017-05-31" end end @testset "_generate_low_level_definitions" begin services = JSON.parsefile(joinpath(@__DIR__, "resources/services.json")) @testset "rest-xml" begin expected = "const s3 = AWS.RestXMLService(\"s3\", \"s3\", \"2006-03-01\")" response = _generate_low_level_definition(services["s3"]) @test response == expected end @testset "rest-json" begin expected = "const glacier = AWS.RestJSONService(\"glacier\", \"glacier\", \"2012-06-01\", LittleDict(\"x-amz-glacier-version\" => \"2012-06-01\"))" response = _generate_low_level_definition(services["glacier"]) @test response == expected end @testset "ec2 / query" begin expected = "const ec2 = AWS.QueryService(\"ec2\", \"ec2\", \"2016-11-15\")" response = _generate_low_level_definition(services["ec2"]) @test response == expected end @testset "json" begin expected = "const budgets = AWS.JSONService(\"budgets\", \"budgets\", \"2016-10-20\", \"1.1\", \"AWSBudgetServiceGateway\")" response = _generate_low_level_definition(services["budgets"]) @test response == expected end @testset "signingName matches endpointPrefix" begin expected = "const serviceid = AWS.RestXMLService(\"signingName\", \"signingName\", \"2021-04-09\")" response = _generate_low_level_definition(services["signingNameMatch"]) @test response == expected end @testset "signingName does not match endpointPrefix" begin expected = "const serviceid = AWS.RestXMLService(\"signingName\", \"endpointPrefix\", \"2021-04-09\")" response = _generate_low_level_definition(services["signingNameNonMatch"]) @test response == expected end @testset "invalid protocol" begin @test_throws ProtocolNotDefined _generate_low_level_definition(services["invalid"]) end end @testset "_generate_low_level_definition" begin service = Dict( "serviceId" => "sample_service", "protocol" => "invalid-protocol", "endpointPrefix" => "endpoint", "apiVersion" => "api_version", "jsonVersion" => "json_version", "targetPrefix" => "target", ) @testset "Invalid Protocol" begin @test_throws ProtocolNotDefined _generate_low_level_definition(service) end @testset "rest-xml" begin service["protocol"] = "rest-xml" expected_result = "const sample_service = AWS.RestXMLService(\"endpoint\", \"endpoint\", \"api_version\")" result = _generate_low_level_definition(service) @test result == expected_result end @testset "rest-json" begin service["protocol"] = "rest-json" expected_result = "const sample_service = AWS.RestJSONService(\"endpoint\", \"endpoint\", \"api_version\")" result = _generate_low_level_definition(service) @test result == expected_result end @testset "json" begin service["protocol"] = "json" expected_result = "const sample_service = AWS.JSONService(\"endpoint\", \"endpoint\", \"api_version\", \"json_version\", \"target\")" result = _generate_low_level_definition(service) @test result == expected_result end @testset "query" begin service["protocol"] = "query" expected_result = "const sample_service = AWS.QueryService(\"endpoint\", \"endpoint\", \"api_version\")" result = _generate_low_level_definition(service) @test result == expected_result end @testset "ec2" begin service["protocol"] = "ec2" expected_result = "const sample_service = AWS.QueryService(\"endpoint\", \"endpoint\", \"api_version\")" result = _generate_low_level_definition(service) @test result == expected_result end end @testset "_clean_documentation" begin documentation = "<p>To remove one or more tags, use the <a>RemoveTagsFromCertificate</a> action. \$ \\ To view all of the tags that have been applied to the certificate, use the <a>ListTagsForCertificate</a> action." expected_result = "To remove one or more tags, use the RemoveTagsFromCertificate action. To view all of the tags that have been applied to the certificate, use the ListTagsForCertificate action." result = _clean_documentation(documentation) @test result == expected_result end @testset "_clean_uri" begin @testset "no parameters" begin uri = "/v1/configurations/" expected = "/v1/configurations/" @test _clean_uri(uri) == expected end @testset "single parameter" begin uri = "/v1/configurations/{parameter-one}" expected = "/v1/configurations/\$(parameter_one)" @test _clean_uri(uri) == expected end @testset "multiple parameters" begin uri = "/v1/configurations/{parameter_one}/{parameter_two}" expected = "/v1/configurations/\$(parameter_one)/\$(parameter_two)" @test _clean_uri(uri) == expected end @testset "hyphen not in parameter" begin uri = "/v1/configuration-parameters/{parameter-one}" expected = "/v1/configuration-parameters/\$(parameter_one)" @test _clean_uri(uri) == expected end @testset "remove plus signs" begin uri = "/v1/configuration-parameters/{parameter-one+}" expected = "/v1/configuration-parameters/\$(parameter_one)" @test _clean_uri(uri) == expected end end @testset "_format_name" begin @testset "single captial" begin function_name = "Testfunctionname" expected = "testfunctionname" @test _format_name(function_name) == expected end @testset "all capitals" begin function_name = "TESTFUNCTIONNAME" expected = "testfunctionname" @test _format_name(function_name) == expected end @testset "subsequent capitals" begin function_name = "TestFUNCTIONName" expected = "test_functionname" @test _format_name(function_name) == expected end @testset "normal" begin function_name = "TestFunctionName" expected = "test_function_name" @test _format_name(function_name) == expected end end @testset "_get_function_parameters" begin shapes = JSON.parsefile(joinpath(@__DIR__, "resources/shapes.json")) @testset "required params" begin input = "RequiredParams" required_params, optional_params = _get_function_parameters(input, shapes) @test required_params == Dict( "RequiredParam" => LittleDict("location" => "", "documentation" => "Required param"), ) @test isempty(optional_params) end @testset "optional params" begin input = "OptionalParams" required_params, optional_params = _get_function_parameters(input, shapes) @test isempty(required_params) @test optional_params == Dict( "OptionalParam1" => Dict("documentation" => "Optional param 1", "idempotent" => false), "OptionalParam2" => Dict("documentation" => "Optional param 2", "idempotent" => false), ) end @testset "required and optional params" begin input = "RequiredAndOptionalParams" required_params, optional_params = _get_function_parameters(input, shapes) @test required_params == Dict( "RequiredParam1" => LittleDict("location" => "", "documentation" => "Required param 1"), "RequiredParam2" => LittleDict("location" => "", "documentation" => "Required param 2"), ) @test optional_params == Dict( "OptionalParam" => Dict("documentation" => "Optional param", "idempotent" => false), ) end @testset "no params" begin input = "NoParams" required_params, optional_params = _get_function_parameters(input, shapes) @test isempty(required_params) @test isempty(optional_params) end end @testset "_generate_high_level_definitions" begin service_name = "sample_service" protocol = "rest-xml" operations = JSON.parsefile(joinpath(@__DIR__, "resources/operations.json")) shapes = JSON.parsefile(joinpath(@__DIR__, "resources/shapes.json")) expected_result = """ \"\"\" sample_operation(required_param1, required_param2) sample_operation(required_param1, required_param2, params::Dict{String,<:Any}) The documentation for this operation. # Arguments - `required_param1`: Required param 1 - `required_param2`: Required param 2 # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"OptionalParam"`: Optional param \"\"\" sample_operation(RequiredParam1, RequiredParam2; aws_config::AbstractAWSConfig=global_aws_config()) = sample_service("POST", "/", Dict{String, Any}("RequiredParam1"=>RequiredParam1, "RequiredParam2"=>RequiredParam2); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) sample_operation(RequiredParam1, RequiredParam2, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = sample_service("POST", "/", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RequiredParam1"=>RequiredParam1, "RequiredParam2"=>RequiredParam2), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) """ result = _generate_high_level_definitions(service_name, protocol, operations, shapes) @test size(result)[1] == 1 expected_result = _clean_high_level_definition(expected_result) result = _clean_high_level_definition(result[1]) @test result == expected_result end @testset "_generate_high_level_definition" begin service_name = "service_name" name = "FunctionName" method = "GET" request_uri = "request_uri" documentation = "Documentation for $name." @testset "locationless and non-idempotent" begin required_params = Dict( "RequiredParam" => Dict("location" => "", "documentation" => "This parameter is required."), ) optional_params = Dict( "OptionalParam" => Dict( "idempotent" => false, "documentation" => "This parameter is optional." ), ) @testset "rest protocol" begin protocol = "rest-xml" expected_result = """ \"\"\" function_name(required_param) function_name(required_param, params::Dict{String,<:Any}) Documentation for FunctionName. # Arguments - `required_param`: This parameter is required. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"OptionalParam"`: This parameter is optional. \"\"\" function_name(RequiredParam; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("GET", "request_uri", Dict{String, Any}("RequiredParam"=>RequiredParam); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) function_name(RequiredParam, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("GET", "request_uri", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RequiredParam"=>RequiredParam), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) """ result = _generate_high_level_definition( service_name, protocol, name, method, request_uri, required_params, optional_params, documentation, ) expected_result = _clean_high_level_definition(expected_result) result = _clean_high_level_definition(result) @test result == expected_result end @testset "json, query, ec2 protocol" begin protocol = "ec2" expected_result = """ \"\"\" function_name(required_param) function_name(required_param, params::Dict{String,<:Any}) Documentation for FunctionName. # Arguments - `required_param`: This parameter is required. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"OptionalParam"`: This parameter is optional. \"\"\" function_name(RequiredParam; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("FunctionName", Dict{String, Any}("RequiredParam"=>RequiredParam); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) function_name(RequiredParam, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("FunctionName", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RequiredParam"=>RequiredParam), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) """ result = _generate_high_level_definition( service_name, protocol, name, method, request_uri, required_params, optional_params, documentation, ) expected_result = _clean_high_level_definition(expected_result) result = _clean_high_level_definition(result) @test result == expected_result end end @testset "header location and idempotent" begin required_params = Dict( "RequiredParam" => Dict( "location" => "header", "documentation" => "This parameter is required." ), ) optional_params = Dict( "OptionalParam" => Dict( "idempotent" => true, "documentation" => "This parameter is optional." ), ) @testset "rest protocol" begin protocol = "rest-xml" expected_result = """ \"\"\" function_name(required_param) function_name(required_param, params::Dict{String,<:Any}) Documentation for FunctionName. # Arguments - `required_param`: This parameter is required. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"OptionalParam"`: This parameter i s optional. \"\"\" function_name(RequiredParam; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("GET", "request_uri", Dict{String, Any}("OptionalParam"=>string(uuid4()), "headers"=>Dict{String, Any}("RequiredParam"=>RequiredParam)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) function_name(RequiredParam, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("GET", "request_uri", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("OptionalParam"=>string(uuid4()), "headers"=>Dict{String, Any}("RequiredParam"=>RequiredParam)), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) """ result = _generate_high_level_definition( service_name, protocol, name, method, request_uri, required_params, optional_params, documentation, ) expected_result = _clean_high_level_definition(expected_result) result = _clean_high_level_definition(result) @test result == expected_result end @testset "json, query, ec2 protocol" begin protocol = "ec2" expected_result = """ \"\"\" function_name(required_param) function_name(required_param, params::Dict{String,<:Any}) Documentation for FunctionName. # Arguments - `required_param`: This parameter is required. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"OptionalParam"`: This parameter i s optional. \"\"\" function_name(RequiredParam; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("FunctionName", Dict{String, Any}("RequiredParam"=>RequiredParam, "OptionalParam"=>string(uuid4())); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) function_name(RequiredParam, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = service_name("FunctionName", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RequiredParam"=>RequiredParam, "OptionalParam"=>string(uuid4())), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET) """ result = _generate_high_level_definition( service_name, protocol, name, method, request_uri, required_params, optional_params, documentation, ) expected_result = _clean_high_level_definition(expected_result) result = _clean_high_level_definition(result) @test result == expected_result end end end @testset "string wrapping functionality" begin @testset "_validindex" begin str = "jμΛIα" # μ, Λ, α have 2 codeunits. @test _validindex(str, 1) == 1 # j @test _validindex(str, 2) == 2 # μ @test _validindex(str, 3) == 2 # μ still @test _validindex(str, 4) == 4 # Λ @test_throws BoundsError _validindex(str, 0) @test_throws BoundsError _validindex(str, 10) end @testset "_splitline" begin str = "This is a short sentence." @testset "limit < 1" begin @test_throws DomainError _splitline(str, 0) @test_throws DomainError _splitline(str, -1) end @testset "limit == 1" begin result = _splitline(str, 1) @test result isa Tuple{String,String} line1, line2 = result @test line1 == string(first(str)) == "T" @test line2 == str[2:end] == "his is a short sentence." end @testset "limit >= ncodeunits" begin for limit in (ncodeunits(str), ncodeunits(str) + 1) result = _splitline(str, limit) @test result isa Tuple{String,String} line1, line2 = result @test line1 == str @test line2 == "" end end @testset "split on whitespace when possible" begin abc = "Aa Bb Cc" @test _splitline(abc, 1) == ("A", "a Bb Cc") # No preceding whitespace to split on @test _splitline(abc, 2) == ("Aa", " Bb Cc") @test _splitline(abc, 3) == ("Aa ", "Bb Cc") @test _splitline(abc, 4) == ("Aa ", "Bb Cc") # 4 == `B`, split on preceding whitespace @test _splitline(abc, 5) == ("Aa ", "Bb Cc") # 5 == 'b', split on preceding whitespace @test _splitline(abc, 6) == ("Aa Bb ", "Cc") @test _splitline(abc, ncodeunits(abc) - 1) == ("Aa Bb ", "Cc") end @testset "does not try to split mid-character" begin str = "jμΛIα" # 'μ' starts at str[2], 'Λ' starts at str[4] @test _splitline(str, 2) == ("jμ", "ΛIα") @test _splitline(str, 3) == ("jμ", "ΛIα") # should not try to split mid-'μ' @test _splitline(str, 4) == ("jμΛ", "Iα") end @testset "does not split on punctuation" begin str = "\"arn:aws:health:us-west-1::event/EBS/AWS\"" result = _splitline(str, ncodeunits(str) - 1) # don't split escaped closing quote `\"` into `\` and `"` @test result == ("\"arn:aws:health:us-west-1::event/EBS/AWS", "\"") end end @testset "_wraplines" begin str = "This sentence contains exactly `η = 50` codeunits" @testset "limit < 1" begin @test_throws DomainError _wraplines(str, 0) @test_throws DomainError _wraplines(str, -1) end @testset "limit == 1" begin wrapped = _wraplines(str, 1) @test wrapped isa String @test startswith(wrapped, "T\nh\ni\ns\n\ns\ne") end @testset "limit >= ncodeunits" begin for limit in (50, 99) wrapped = _wraplines(str, limit) @test wrapped isa String @test wrapped == str end end @testset "1 < limit < ncodeunits" begin @test _wraplines(str, 20) == """ This sentence contains exactly `η = 50` codeunits""" @test _wraplines(str, 25) == """ This sentence contains exactly `η = 50` codeunits""" @test _wraplines(str, 30) == """ This sentence contains exactly `η = 50` codeunits""" end @testset "trailing whitespace is stripped" begin str = "16charactersthen fourspaces " @test _wraplines(str, 16) == "16charactersthen\n fourspaces" @test _wraplines(str, 17) == "16charactersthen\n fourspaces" @test _wraplines(str, 18) == "16charactersthen\n fourspaces" end @testset "has default `limit=92` argument" begin str = string( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, ", "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", ) @test _wraplines(str) == _wraplines(str, 92) end @testset "optional `delim` keyword" begin str = string( "- Lorem ipsum dolor sit amet, consectetur adipiscing elit, ", "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", ) @test _wraplines(str, 50; delim="\n ") == """ - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" end end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
12304
struct Route method::String path::String handler end function register!(router::HTTP.Router, route::Route) return HTTP.register!(router, route.method, route.path, route.handler) end function Router(routes) router = HTTP.Router() for route in routes register!(router, route) end return router end function token_route(token) handler = function (req::HTTP.Request) ttl_secs = HTTP.header(req, "X-aws-ec2-metadata-token-ttl-seconds", nothing) if !isnothing(ttl_secs) HTTP.Response(200, token) else HTTP.Response(400) # Behavior when required header is missing end end return Route("PUT", "/latest/api/token", handler) end function secure_route(route::Route, token) wrapper = function (req::HTTP.Request) if HTTP.header(req, "X-aws-ec2-metadata-token", nothing) == token route.handler(req) else HTTP.Response(401) # Behavior when IMDSv2 is required end end return Route(route.method, route.path, wrapper) end function response_route(method, path, response::HTTP.Response) handler = function (req::HTTP.Request) return HTTP.Response( response.version, response.status, response.headers, response.body, req ) end return Route(method, path, handler) end # Use Mocking to re-route requests to 169.254.169.254 without having to actually start an # HTTP.jl server. Should result in faster running tests. function _imds_patch(router::HTTP.Router=HTTP.Router(); listening=true, enabled=true) patch = @patch function HTTP.request( method, url, headers=[], body=HTTP.nobody; status_exception=true, kwargs... ) uri = HTTP.URI(url) if uri.host != "169.254.169.254" error("Internal error: Unexpected HTTP call to non-IMDS service: $url") end request = HTTP.Request(method, uri.path, headers, body) response = if listening && enabled router(request) elseif listening && !enabled HTTP.Response(403) else connect_timeout = HTTP.ConnectionPool.ConnectTimeout(uri.host, uri.port) throw(HTTP.Exceptions.ConnectError(string(uri), connect_timeout)) end if status_exception && response.status >= 300 ex = HTTP.Exceptions.StatusError( response.status, request.method, request.target, response ) throw(ex) end return response end end @testset "IMDS" begin @testset "is_connection_exception / is_ttl_expired_exception" begin url = "http://169.254.169.254/latest/api/token" connect_timeout = HTTP.ConnectionPool.ConnectTimeout("169.254.169.254", 80) e = HTTP.Exceptions.ConnectError(url, connect_timeout) @test IMDS.is_connection_exception(e) @test !IMDS.is_ttl_expired_exception(e) request = HTTP.Request("PUT", "/latest/api/token", [], HTTP.nobody) io_error = Base.IOError("read: connection timed out (ETIMEDOUT)", -110) e = HTTP.Exceptions.RequestError(request, io_error) @test !IMDS.is_connection_exception(e) @test IMDS.is_ttl_expired_exception(e) e = ErrorException("non-connection error") @test !IMDS.is_connection_exception(e) @test !IMDS.is_ttl_expired_exception(e) end @testset "refresh_token!" begin # Running outside of an EC2 instance apply(_imds_patch(; listening=false)) do session = IMDS.Session() @test isempty(session.token) @test session.duration == IMDS.DEFAULT_DURATION @test IMDS.token_expired(session) @test_throws IMDSUnavailable IMDS.refresh_token!(session) end # Running on an EC2 instance where IMDS is disabled apply(_imds_patch(; enabled=false)) do session = IMDS.Session() @test_throws IMDSUnavailable IMDS.refresh_token!(session) end # IMDS is non-functional router = Router([response_route("PUT", "/latest/api/token", HTTP.Response(500))]) apply(_imds_patch(router)) do session = IMDS.Session() @test_throws HTTP.Exceptions.StatusError IMDS.refresh_token!(session) end # IMDSv1 is available router = Router([response_route("PUT", "/latest/api/token", HTTP.Response(404))]) apply(_imds_patch(router)) do session = IMDS.Session() @test IMDS.refresh_token!(session) === session @test isempty(session.token) @test session.duration == 0 @test session.expiration == typemax(Int64) end # IMDSv2 is available token = "foo" router = Router([token_route(token)]) apply(_imds_patch(router)) do session = IMDS.Session(; duration=60) t = floor(Int64, time()) @test IMDS.refresh_token!(session) === session @test session.token == token @test session.duration == 60 @test 0 <= session.expiration - (t + session.duration) <= 5 end end @testset "request" begin instance_id = "123" path = "/latest/meta-data/instance-id" # Running outside of an EC2 instance apply(_imds_patch(; listening=false)) do session = IMDS.Session() @test_throws IMDSUnavailable IMDS.request(session, "GET", path) end # Running on an EC2 instance where IMDS is disabled apply(_imds_patch(; enabled=false)) do session = IMDS.Session() @test_throws IMDSUnavailable IMDS.request(session, "GET", path) end # Requested metadata is missing router = Router([response_route("GET", path, HTTP.Response(500))]) apply(_imds_patch(router)) do session = IMDS.Session() @test_throws HTTP.Exceptions.StatusError IMDS.request(session, "GET", path) end # Requested metadata available via IMDSv1 router = Router([response_route("GET", path, HTTP.Response(instance_id))]) apply(_imds_patch(router)) do session = IMDS.Session() r = IMDS.request(session, "GET", path) @test r isa HTTP.Response @test r.status == 200 @test String(r.body) == instance_id @test isempty(session.token) end # Requested metadata available via IMDSv2 token = "token" router = Router([ token_route(token), secure_route(response_route("GET", path, HTTP.Response(instance_id)), token), ]) apply(_imds_patch(router)) do session = IMDS.Session() r = IMDS.request(session, "GET", path) @test r isa HTTP.Response @test r.status == 200 @test String(r.body) == instance_id @test session.token == token end # Invalid token used with IMDSv2 router = Router([ token_route("good"), secure_route(response_route("GET", path, HTTP.Response(instance_id)), "bad"), ]) apply(_imds_patch(router)) do session = IMDS.Session() r = IMDS.request(session, "GET", path; status_exception=false) @test r isa HTTP.Response @test r.status == 401 end # Unlikely scenario where the instance metadata services has switched over from # IMDSv2 being optional to required while a long running Julia service on that # instance has session which is set to use IMDSv1 indefinitely. # TODO: We may want to have the code automatically attempt a token refresh when this # occurs but I doubt this scenario will occur in scenario will occur in reality as # instances cannot be configured to use IMDSv1 only. token = "token" router = Router([ token_route(token), secure_route(response_route("GET", path, HTTP.Response(instance_id)), token), ]) apply(_imds_patch(router)) do # Emulate a pre-existing session where IMDSv2 was not available. session = IMDS.Session("", 60, typemax(Int64)) # Request attempts to use IMDSv1 but now only IMDSv2 is enabled r = IMDS.request(session, "GET", path; status_exception=false) @test r isa HTTP.Response @test r.status == 401 end # When running in a container running on an EC2 instance and the hop limit is 1 the # IMDSv2 token retrieval will fail so we should fall back to using IMDSv1. # https://github.com/JuliaCloud/AWS.jl/issues/654 # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html#imds-considerations connection_timeout = function (req::HTTP.Request) io_error = Base.IOError("read: connection timed out (ETIMEDOUT)", -110) throw(HTTP.Exceptions.RequestError(request, io_error)) end router = Router([ Route("PUT", "/latest/api/token", connection_timeout), response_route("GET", path, HTTP.Response(instance_id)), ]) apply(_imds_patch(router)) do session = IMDS.Session() msg_regex = r"IMDSv2 token request rejected due to reaching hop limit" r = @test_logs (:warn, msg_regex) begin IMDS.request(session, "GET", path; status_exception=false) end @test r isa HTTP.Response @test r.status == 200 @test String(r.body) == instance_id @test isempty(session.token) end end @testset "get" begin instance_id = "123" path = "/latest/meta-data/instance-id" # Running outside of an EC2 instancee apply(_imds_patch(; listening=false)) do session = IMDS.Session() @test IMDS.get(session, path) === nothing end # Requested metadata available via IMDSv1 router = Router([response_route("GET", path, HTTP.Response(instance_id))]) apply(_imds_patch(router)) do session = IMDS.Session() @test IMDS.get(session, path) == instance_id end # When using GitHub Action CI a non-IMDS service uses the same local-link address # and returns HTTP 404. # https://github.com/JuliaCloud/AWS.jl/issues/652 iam_path = "/latest/meta-data/iam/info" router = Router([ response_route("PUT", "/**", HTTP.Response(404)), response_route("GET", "/**", HTTP.Response(404)), ]) apply(_imds_patch(router)) do session = IMDS.Session() response = IMDS.request(session, "GET", iam_path; status_exception=false) @test response.status == 404 @test IMDS.get(session, iam_path) === nothing end end @testset "region" begin region = "ap-atlantis-1" # Made up region path = "/latest/meta-data/placement/region" # Running outside of an EC2 instance apply(_imds_patch(; listening=false)) do session = IMDS.Session() @test IMDS.region(session) === nothing end # Running on a webserver which doesn't understand our requests and returns HTTP 404. # This exact scenario occurs in GHA CI and can be reproduced locally with the # `aws-vault exec --ec2-server` which provides a very limited implementation of # IMDSv1. router = Router([ response_route("PUT", "/**", HTTP.Response(404)), response_route("GET", "/**", HTTP.Response(404)), ]) apply(_imds_patch(router)) do session = IMDS.Session() response = IMDS.request(session, "GET", path; status_exception=false) @test response.status == 404 @test IMDS.region(session) === nothing end # Requested metadata available via IMDSv1 router = Router([response_route("GET", path, HTTP.Response(region))]) apply(_imds_patch(router)) do session = IMDS.Session() @test IMDS.region(session) == region end end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
8032
@service S3 BUCKET_NAME = "aws-jl-test-issues---" * _now_formatted() try S3.create_bucket(BUCKET_NAME) @testset "issue 223" begin # https://github.com/JuliaCloud/AWS.jl/issues/223 body = "Hello World!" file_name = "contains spaces" try S3.put_object(BUCKET_NAME, file_name, Dict("body" => body)) resp = S3.get_object(BUCKET_NAME, file_name) @test String(resp) == body finally S3.delete_object(BUCKET_NAME, file_name) end end @testset "issue 227" begin @testset "s3 public bucket" begin # https://github.com/JuliaCloud/AWS.jl/issues/227 config = AWSConfig(; creds=nothing) resp = S3.get_object("julialang2", "bin/versions.json"; aws_config=config) @test !isempty(resp) end @testset "s3 private bucket" begin bucket_name = "aws-jl-test-issues---" * _now_formatted() file_name = "hello_world" try S3.create_bucket(bucket_name) S3.put_object(bucket_name, file_name) @test_throws AWSException S3.get_object( bucket_name, file_name; aws_config=AWSConfig(; creds=nothing) ) finally S3.delete_object(bucket_name, file_name) S3.delete_bucket(bucket_name) end end @testset "lambda" begin @service Lambda @test_throws NoCredentials Lambda.list_functions(; aws_config=AWSConfig(; creds=nothing) ) end end @testset "issue 324" begin body = "Hello World!" file_name = "streaming.bin" try S3.put_object(BUCKET_NAME, file_name, Dict("body" => body)) resp = S3.get_object(BUCKET_NAME, file_name) @test String(resp) == body # ERROR: MethodError: no method matching iterate(::Base.BufferStream) # => BUG: header `response_stream` is pushed into the query... io = Base.BufferStream() S3.get_object( BUCKET_NAME, file_name, Dict("response_stream" => io, "return_stream" => true), ) if bytesavailable(io) > 0 @test String(readavailable(io)) == body else @test "no body data was available" == body end finally S3.delete_object(BUCKET_NAME, file_name) end end @testset "issue 466" begin file_name = "hang.txt" try S3.put_object(BUCKET_NAME, file_name) # The tests below validate the current behavior of how streams are handled. # Note: Avoid using `eof` for these tests can hang when using an unclosed `Base.BufferStream` stream = S3.get_object(BUCKET_NAME, file_name, Dict("return_stream" => true)) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test !isopen(stream) else @test isopen(stream) end stream = Base.BufferStream() S3.get_object(BUCKET_NAME, file_name, Dict("response_stream" => stream)) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test !isopen(stream) else # See: https://github.com/JuliaCloud/AWS.jl/issues/471 @test_broken isopen(stream) end stream = Base.BufferStream() S3.get_object( BUCKET_NAME, file_name, Dict("response_stream" => stream, "return_stream" => true), ) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test !isopen(stream) else @test isopen(stream) end finally S3.delete_object(BUCKET_NAME, file_name) end end @testset "issue 474" begin body = "foo\0bar" expected = Vector{UInt8}(body) file_name = "null.txt" try S3.put_object(BUCKET_NAME, file_name, Dict("body" => body)) raw = S3.get_object(BUCKET_NAME, file_name, Dict("return_raw" => true)) @test raw == expected stream = S3.get_object(BUCKET_NAME, file_name, Dict("return_stream" => true)) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test stream isa Base.BufferStream @test !isopen(stream) if !isopen(stream) @test read(stream) == expected end else @test stream isa IOBuffer @test isopen(stream) seekstart(stream) @test read(stream) == expected end finally S3.delete_object(BUCKET_NAME, file_name) end end # https://github.com/JuliaCloud/AWS.jl/issues/515 @testset "issue 515" begin function _incomplete_patch(; data, num_attempts_to_fail=4) attempt_num = 0 n = length(data) function _downloads_response(content_length) headers = ["content-length" => string(content_length)] return Downloads.Response("http", "", 200, "HTTP/1.1 200 OK", headers) end patch = if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @patch function HTTP.request(args...; response_stream, kwargs...) attempt_num += 1 if attempt_num <= num_attempts_to_fail write(response_stream, data[1:(n - 1)]) # an incomplete stream that shouldn't be retained throw(HTTP.RequestError(HTTP.Request(), EOFError())) else write(response_stream, data) return HTTP.Response(200, "{\"Location\": \"us-east-1\"}") end end elseif AWS.DEFAULT_BACKEND[] isa AWS.DownloadsBackend @patch function Downloads.request(args...; output, kwargs...) attempt_num += 1 if attempt_num <= num_attempts_to_fail write(output, data[1:(n - 1)]) # an incomplete stream that shouldn't be retained message = "transfer closed with 1 bytes remaining to read" e = Downloads.RequestError("", 18, message, _downloads_response(n)) throw(e) else write(output, data) return _downloads_response(n) end end end return patch end n = 100 data = rand(UInt8, n) bucket = "julialang2" # use public bucket as dummy key = "bin/versions.json" config = AWSConfig(; creds=nothing) @testset "Fail 2 attempts then succeed" begin apply(_incomplete_patch(; data=data, num_attempts_to_fail=2)) do retrieved = S3.get_object(bucket, key; aws_config=config) @test length(retrieved) == n @test retrieved == data end end @testset "Fail all 4 attempts then throw" begin err_t = if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend HTTP.RequestError else Downloads.RequestError end io = IOBuffer() apply(_incomplete_patch(; data=data, num_attempts_to_fail=4)) do params = Dict("response_stream" => io) @test_throws err_t S3.get_object(bucket, key, params; aws_config=config) seekstart(io) retrieved = read(io) @test length(retrieved) == n - 1 @test retrieved == data[1:(n - 1)] end end end finally S3.delete_bucket(BUCKET_NAME) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
4976
@service S3 struct MinioConfig <: AbstractAWSConfig endpoint::String region::String creds end struct SimpleCredentials access_key_id::String secret_key::String token::String end AWS.region(c::MinioConfig) = c.region AWS.credentials(c::MinioConfig) = c.creds AWS.check_credentials(c::SimpleCredentials) = c function AWS.generate_service_url(aws::MinioConfig, service::String, resource::String) service == "s3" || throw(ArgumentError("Can only handle s3 requests to Minio")) return string(aws.endpoint, resource) end AWS.global_aws_config( MinioConfig( "http://127.0.0.1:9000", ENV["MINIO_REGION_NAME"], SimpleCredentials(ENV["MINIO_ACCESS_KEY"], ENV["MINIO_SECRET_KEY"], ""), ), ) datadir = joinpath(dirname(pathof(AWS)), "..", "data") # Create bucket and place objects in it S3.create_bucket("anewbucket") try S3.put_object("anewbucket", "myobject", Dict("body" => "Hi from Minio")) S3.put_object("anewbucket", "empty") S3.put_object("anewbucket", "foo/bar", Dict("body" => "a nested object")) S3.put_object("anewbucket", "foo/baz", Dict("body" => "a secondnested object")) # Test retrieving an object @test String(S3.get_object("anewbucket", "myobject")) == "Hi from Minio" # Test retrieving an object into a stream target mktemp() do f, io S3.get_object("anewbucket", "myobject", Dict("response_stream" => io)) flush(io) @test read(f, String) == "Hi from Minio" end # Test listing objs = S3.list_objects_v2("anewbucket") @test length(objs["Contents"]) == 4 # Test api version 2 of list-objects objs_truncated = S3.list_objects_v2("anewbucket", Dict("max-keys" => 2)) @test length(objs_truncated["Contents"]) == 2 @test objs_truncated["IsTruncated"] == "true" @test haskey(objs_truncated, "NextContinuationToken") # Test listing with prefixes objs_prefix = S3.list_objects_v2("anewbucket", Dict("prefix" => "", "delimiter" => "/")) @test length(objs_prefix["Contents"]) == 2 @test sort(getindex.(objs_prefix["Contents"], "Key")) == ["empty", "myobject"] @test objs_prefix["CommonPrefixes"]["Prefix"] == "foo/" # Duplicated testset from "test/issues.jl". Useful for testing outside the CI. Ideally, # the tests should be revised such that local testing works without having to duplicate # testsets. @testset "issue 466" begin file_name = "hang.txt" try S3.put_object("anewbucket", file_name) # Note: Using `eof` for these tests can hang when using an unclosed `Base.BufferStream` stream = S3.get_object("anewbucket", file_name, Dict("return_stream" => true)) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test !isopen(stream) else @test isopen(stream) end stream = Base.BufferStream() S3.get_object("anewbucket", file_name, Dict("response_stream" => stream)) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test !isopen(stream) else @test_broken isopen(stream) end stream = Base.BufferStream() S3.get_object( "anewbucket", file_name, Dict("response_stream" => stream, "return_stream" => true), ) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test !isopen(stream) else @test isopen(stream) end finally S3.delete_object("anewbucket", file_name) end end @testset "issue 474" begin body = "foo\0bar" expected = Vector{UInt8}(body) file_name = "null.txt" bucket_name = "anewbucket" try S3.put_object(bucket_name, file_name, Dict("body" => body)) raw = S3.get_object(bucket_name, file_name, Dict("return_raw" => true)) @test raw isa Vector{UInt8} @test raw == expected stream = S3.get_object(bucket_name, file_name, Dict("return_stream" => true)) if AWS.DEFAULT_BACKEND[] isa AWS.HTTPBackend @test stream isa Base.BufferStream @test !isopen(stream) if !isopen(stream) @test read(stream) == expected end else @test stream isa IOBuffer @test isopen(stream) seekstart(stream) @test read(stream) == expected end finally S3.delete_object(bucket_name, file_name) end end finally # Delete all objects and the bucket objs = S3.list_objects_v2("anewbucket") for obj in objs["Contents"] S3.delete_object("anewbucket", obj["Key"]) end S3.delete_bucket("anewbucket") end @test isempty(filter(!isequal(".minio.sys"), readdir(datadir)))
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
7331
module Patches using AWS using Dates using Downloads: Downloads using HTTP using JSON using GitHub using Mocking using OrderedCollections: LittleDict version = v"1.1.0" status = 200 headers = Pair[ "x-amz-id-2" => "x-amz-id-2", "x-amz-request-id" => "x-amz-request-id", "Date" => "Tue, 16 Jun 2020 21:29:18 GMT", "x-amz-bucket-region" => "us-east-1", "Content-Type" => "application/xml", "Transfer-Encoding" => "chunked", "Server" => "AmazonS3", ] body = """ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"> <Name>sample-bucket</Name> <Prefix></Prefix> <Marker></Marker> <MaxKeys>1000</MaxKeys> <IsTruncated>false</IsTruncated> <Contents> <Key>test.txt</Key> <LastModified>2020-06-16T21:37:34.000Z</LastModified> <ETag>&quot;d41d8cd98f00b204e9800998ecf8427e&quot;</ETag> <Size>0</Size> <Owner> <ID>id</ID> <DisplayName>matt.brzezinski</DisplayName> </Owner> <StorageClass>STANDARD</StorageClass> </Contents> </ListBucketResult> """ function _response(; version::VersionNumber=version, status::Int64=status, headers::Array=headers, body::String=body, ) response = HTTP.Messages.Response() response.version = version response.status = status response.headers = headers response.body = b"[Message Body was streamed]" b = IOBuffer(body) return AWS.Response(response, b) end function _aws_http_request_patch(response::AWS.Response=_response()) p = @patch AWS._http_request(::AWS.AbstractBackend, request::Request, ::IO) = response return p end function _throttling_patch(retries::Ref{Int}) status = 503 body = """ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <Error> <Code>SlowDown</Code> <Message>Please reduce your request rate</Message> <Resource>/mybucket/myfoto.jpg</Resource> <RequestId>4442587FB7D0A2F9</RequestId> </Error> """ p = @patch function AWS._http_request(::AWS.AbstractBackend, request::Request, ::IO) retries[] += 1 resp = _response(; status=status, body=body).response err = HTTP.StatusError(status, request.request_method, request.resource, resp) throw(AWS.AWSException(err, body)) end return p end _cred_file_patch = @patch function dot_aws_credentials_file() return "" end _config_file_patch = @patch function dot_aws_config_file() return "" end _assume_role_patch = function ( op; access_key="access_key", secret_key="secret_key", session_token="token", role_arn="arn:aws:sts:::assumed-role/role-name", expiry=duration -> now(UTC) + duration, token_code_ref=nothing, ) @patch function AWSServices.sts(op, params; aws_config, feature_set) duration = Second(parse(Int, get(params, "DurationSeconds", "3600"))) expiration = expiry(duration) if token_code_ref !== nothing token_code_ref[] = params["TokenCode"] end xml = """ <$(op)Response xmlns="https://sts.amazonaws.com/doc/2011-06-15/"> <$(op)Result> <AssumedRoleUser> <Arn>$(role_arn)/$(params["RoleSessionName"])</Arn> </AssumedRoleUser> <Credentials> <AccessKeyId>$access_key</AccessKeyId> <SecretAccessKey>$secret_key</SecretAccessKey> <SessionToken>$session_token</SessionToken> <Expiration>$expiration</Expiration> </Credentials> </$(op)Result> </$(op)Response> """ r = _response(; body=xml) return feature_set.use_response_type ? r : parse(r)::AbstractDict end end _getpass_patch = function (; secret="the_secret") @patch function Base.getpass(prompt) return Base.SecretBuffer(secret) end end _github_tree_patch = @patch function tree(repo, tree_obj; kwargs...) if tree_obj == "master" tree = [Dict("path" => "apis", "sha" => "apis-sha")] return Tree("test-sha", HTTP.URI(), tree, false) else tree = [Dict("path" => "test-2020-01-01.normal.json", "sha" => "test-sha")] return Tree("test-sha", HTTP.URI(), tree, false) end end # This patch causes `HTTP.request` to return all of its keyword arguments # except `require_ssl_verification` and `response_stream`. This is used to # test which other options are being passed to `HTTP.Request` inside of # `_http_request`. _http_options_patches = [ @patch function HTTP.request(args...; kwargs...) options = Dict(kwargs) delete!(options, :redirect) delete!(options, :retry) delete!(options, :response_stream) return options end @patch AWS.Response(options, args...) = options ] get_profile_settings_empty_patch = @patch function aws_get_profile_settings(profile, ini) return nothing end get_profile_settings_patch = @patch function aws_get_profile_settings(profile, ini) return Dict("foo" => "bar") end # Simulate the HTTP.request behaviour with a HTTP 400 response function gen_http_options_400_patches(message) body = "{\"__type\":\"AccessDeniedException\",\"Message\":\"$message\"}" headers = [ "Content-Type" => "application/x-amz-json-1.1", "Content-Length" => string(sizeof(body)), ] return [ @patch function HTTP.request( args...; status_exception=true, response_stream=nothing, kwargs... ) request = HTTP.Request("GET", "/") if response_stream !== nothing write(response_stream, body) close(response_stream) # Simulating current HTTP.jl 0.9.14 behaviour body = IOBuffer() end response = HTTP.Response(400, headers; body=body, request=request) exception = AWS.statuserror(400, response) return !status_exception ? response : throw(exception) end @patch function Downloads.request(args...; output=nothing, kwargs...) if output !== nothing write(output, body) end return Downloads.Response( "https", "https://region.amazonaws.com/", 400, "HTTP/1.1 400 Bad Request", headers, ) end ] end _sso_access_token_patch = @patch function AWS._sso_cache_access_token(sso_start_url) return "123token456" end function sso_service_patches(access_key_id, secret_access_key) p = @patch function AWSServices.sso(args...; kwargs...) return Dict( "roleCredentials" => Dict( "accessKeyId" => access_key_id, "secretAccessKey" => secret_access_key, "sessionToken" => "", "expiration" => floor(Int, Dates.datetime2unix(Dates.now(UTC) + Dates.Hour(1))) * 1000, # ms ), ) end return [p, _sso_access_token_patch] end function _imds_region_patch(region) return @patch IMDS.region() = region end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
5365
function get_assumed_role(aws_config::AbstractAWSConfig=global_aws_config()) r = AWSServices.sts( "GetCallerIdentity"; aws_config, feature_set=AWS.FeatureSet(; use_response_type=true), ) result = parse(r) arn = result["GetCallerIdentityResult"]["Arn"] m = match(r":assumed-role/(?<role>[^/]+)", arn) if m !== nothing return m["role"] else error("Caller Identity ARN is not an assumed role: $arn") end end get_assumed_role(creds::AWSCredentials) = get_assumed_role(AWSConfig(; creds)) function mfa_user_credentials(config::AbstractAWSConfig) r = AWSServices.secrets_manager( "GetSecretValue", Dict("SecretId" => "AWS.jl-mfa-user-credentials"); aws_config=config, feature_set=AWS.FeatureSet(; use_response_type=true), ) json = JSON.parse(parse(r)["SecretString"]) mfa_user_creds = AWSCredentials(json["access_key_id"], json["secret_access_key"]) mfa_user_cfg = AWSConfig(; creds=mfa_user_creds) r = AWSServices.secrets_manager( "GetSecretValue", Dict("SecretId" => "AWS.jl-mfa-user-virtual-mfa-devices"); aws_config=config, feature_set=AWS.FeatureSet(; use_response_type=true), ) json = JSON.parse(parse(r)["SecretString"]) mfa_devices = [(; mfa_serial=d["mfa_serial"], seed=d["seed"]) for d in json] return mfa_user_cfg, mfa_devices end @testset "_whoami" begin user = AWS._whoami() @test user isa AbstractString @test !isempty(user) end @testset "assume_role / assume_role_creds" begin # In order to mitigate the effects of using `assume_role` in order to test itself we'll # use the lowest-level call with as many defaults as possible. base_config = aws creds = assume_role_creds(base_config, testset_role("AssumeRoleTestset")) config = AWSConfig(; creds) @test get_assumed_role(config) == testset_role("AssumeRoleTestset") role_a = testset_role("RoleA") role_b = testset_role("RoleB") @testset "basic" begin creds = assume_role_creds(config, role_a) @test creds isa AWSCredentials @test creds.token != "" # Temporary credentials @test creds.renew !== nothing cfg = assume_role(config, role_a) @test cfg isa AWSConfig @test cfg.credentials isa AWSCredentials @test cfg.region == config.region @test cfg.output == config.output @test cfg.max_attempts == config.max_attempts end @testset "role name/ARN" begin account_id = aws_account_number(config) creds = assume_role_creds(config, role_a) @test contains(creds.user_arn, r":assumed-role/" * (role_a * '/')) @test creds.account_number == account_id creds = assume_role_creds(config, "arn:aws:iam::$account_id:role/$role_a") @test contains(creds.user_arn, r":assumed-role/" * (role_a * '/')) @test creds.account_number == "" end @testset "duration" begin # Have seen up to 3 seconds of drift on CI jobs drift = Second(5) creds = assume_role_creds(config, role_a; duration=nothing) t = floor(now(UTC), Second) @test t <= creds.expiry <= t + Second(3600) + drift duration = 900 # Minimum allowed duration creds = assume_role_creds(config, role_a; duration) t = floor(now(UTC), Second) @test t <= creds.expiry <= t + Second(duration) + drift end @testset "session_name" begin session_prefix = "AWS.jl-" creds = assume_role_creds(config, role_a; session_name=nothing) regex = r":assumed-role/" * (role_a * '/' * session_prefix) * r".*-\d{8}T\d{6}Z$" @test contains(creds.user_arn, regex) @test get_assumed_role(creds) == role_a session_name = "assume-role-session-name-testset-" * randstring(5) creds = assume_role_creds(config, role_a; session_name) regex = r":assumed-role/" * (role_a * '/' * session_name) * r"$" @test contains(creds.user_arn, regex) @test get_assumed_role(creds) == role_a end @testset "mfa_serial / token" begin mfa_user_cfg, mfa_devices = mfa_user_credentials(config) # User policy should deny "sts:AssumeRole" when MFA is not present. @test_throws AWSException assume_role_creds(mfa_user_cfg, role_a) creds = mfa_device_pool(mfa_devices) do mfa_serial, token assume_role_creds(mfa_user_cfg, role_a; mfa_serial, token) end @test get_assumed_role(creds) == role_a end @testset "renew" begin creds = assume_role_creds(config, role_a; duration=nothing) @test creds.renew isa Function @test get_assumed_role(creds) == role_a new_creds = creds.renew() @test new_creds isa AWSCredentials @test get_assumed_role(new_creds) == role_a @test new_creds.access_key_id != creds.access_key_id @test new_creds.secret_key != creds.secret_key @test new_creds.expiry >= creds.expiry end @testset "role chaining" begin cfg = assume_role(assume_role(config, role_a), role_b) @test get_assumed_role(cfg) == role_b #! format: off cfg = config |> assume_role(role_a) |> assume_role(role_b) #! format: on @test get_assumed_role(cfg) == role_b end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
1824
using AWS using AWS: AWSCredentials, AWSServices, assume_role_creds using AWS.AWSExceptions: AWSException, IMDSUnavailable, InvalidFileName, NoCredentials, ProtocolNotDefined using AWS.AWSMetadata: ServiceFile, _clean_documentation, _filter_latest_service_version, _generate_low_level_definition, _generate_high_level_definition, _generate_high_level_definitions, _get_service_files, _get_service_and_version, _get_function_parameters, _clean_uri, _format_name, _splitline, _wraplines, _validindex using Base64 using Compat: mergewith using Dates using Downloads using GitHub using HTTP using IniFile: Inifile using JSON using OrderedCollections: LittleDict, OrderedDict using MbedTLS: digest, MD_SHA256, MD_MD5 using Mocking using Pkg using Random using Suppressor using Test using UUIDs using XMLDict using StableRNGs Mocking.activate() include("patch.jl") include("resources/totp.jl") const TEST_MINIO = begin all(k -> haskey(ENV, k), ("MINIO_ACCESS_KEY", "MINIO_SECRET_KEY", "MINIO_REGION_NAME")) end aws = AWSConfig() function _now_formatted() return lowercase(Dates.format(now(Dates.UTC), dateformat"yyyymmdd\THHMMSSsss\Z")) end testset_role(role_name) = "AWS.jl-$role_name" @testset "AWS.jl" begin include("AWSExceptions.jl") include("AWSMetadataUtilities.jl") include("test_pkg.jl") include("utilities.jl") include("AWSConfig.jl") backends = [AWS.HTTPBackend, AWS.DownloadsBackend] @testset "Backend: $(nameof(backend))" for backend in backends AWS.DEFAULT_BACKEND[] = backend() include("AWS.jl") include("IMDS.jl") include("AWSCredentials.jl") include("role.jl") include("issues.jl") if TEST_MINIO include("minio.jl") end end end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
374
path = joinpath(@__DIR__, "resources", "TestPkg") if VERSION >= v"1.5" Pkg.develop(; path=path) else Pkg.develop(PackageSpec(; path=path)) end # Check to see if we get any warnings when using AWS.jl inside of another package. out = @capture_out begin err = @capture_err begin @eval using TestPkg end @test isempty(err) end @test isempty(out)
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
2915
@testset "_merge - AbstractDict" begin @testset "Simple" begin expected = Dict("a" => 1, "b" => 2) a = Dict("a" => 1) b = Dict("b" => 2) @test AWS._merge(a, b) == expected end @testset "Complex Different Nested Dict Keys" begin expected = Dict("common" => Dict("b" => 2)) a = Dict("common" => Dict("a" => 1)) b = Dict("common" => Dict("b" => 2)) @test AWS._merge(a, b) == expected end @testset "Complex Same Nested Dict Keys" begin expected = Dict("common" => Dict("a" => 2)) a1 = Dict("common" => Dict("a" => 1)) a2 = Dict("common" => Dict("a" => 2)) @test AWS._merge(a1, a2) == expected end end @testset "mergewith(_merge) - AbstractDict" begin @testset "Simple" begin expected = Dict("a" => 1, "b" => 2) a = Dict("a" => 1) b = Dict("b" => 2) @test mergewith(AWS._merge, a, b) == expected end @testset "Complex Differed Nested Dict Keys" begin expected = Dict("common" => Dict("a" => 1, "b" => 2)) a = Dict("common" => Dict("a" => 1)) b = Dict("common" => Dict("b" => 2)) @test mergewith(AWS._merge, a, b) == expected end @testset "Complex Same Nested Dict Keys" begin expected = Dict("common" => Dict("a" => 2)) a1 = Dict("common" => Dict("a" => 1)) a2 = Dict("common" => Dict("a" => 2)) @test mergewith(AWS._merge, a1, a2) == expected end end @testset "_merge - AbstractString" begin expected = "b" @test AWS._merge("a", "b") == expected end @testset "_assignment_to_kw!" begin @testset "non-expression" begin ex = :(true) @test_throws ArgumentError AWS._assignment_to_kw!(ex) end @testset "non-assignment" begin ex = :(a => true) @test_throws ArgumentError AWS._assignment_to_kw!(ex) end @testset "assignment" begin ex = :(a = true) @test AWS._assignment_to_kw!(ex) == Expr(:kw, :a, true) @test ex == Expr(:kw, :a, true) end end # Count the elements in an iterator without using `length` function count_len(itr) c = 0 for _ in itr c += 1 end return c end @testset "AWSExponentialBackoff" begin for (n, max_backoff) in [(3, 5.0), (10, 20.0)] itr = AWS.AWSExponentialBackoff(; max_attempts=n, max_backoff=max_backoff, rng=StableRNG(1) ) @test count_len(itr) == n - 1 @test length(collect(itr)) == n - 1 @test all(>(0), itr) @test all(<=(max_backoff), itr) end end @testset "_clean_s3_uri" begin @test AWS._clean_s3_uri("/ !'()*+,:=@") == "/%20%21%27%28%29%2A%2B%2C%3A%3D%40" @test AWS._clean_s3_uri("/bucket/!'()*+,:=@ /file") == "/bucket/%21%27%28%29%2A%2B%2C%3A%3D%40%20/file" @test AWS._clean_s3_uri("/📁/📁") == "/%F0%9F%93%81/%F0%9F%93%81" end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
7626
#!/usr/bin/env julia --project # Using AWS.jl to bootstrap AWS.jl test resources. using AWS using AWS: AWSException using JSON @service CloudFormation use_response_type = true @service IAM use_response_type = true # TODO: Support PascalCase, https://github.com/JuliaCloud/AWS.jl/issues/642 @service Secrets_Manager use_response_type = true global_aws_config(; region="us-east-1") include("totp.jl") function create_or_update_stack(args...; kwargs...) response = nothing result_key = nothing try response = CloudFormation.update_stack(args...; kwargs...) result_key = "UpdateStackResult" catch e if ( e isa AWSException && e.code == "ValidationError" && e.message == "No updates are to be performed." ) nothing elseif ( e isa AWSException && e.code == "ValidationError" && contains(e.message, r"^Stack .* does not exist$") ) response = CloudFormation.create_stack(args...; kwargs...) result_key = "CreateStackResult" else rethrow() end end return response, result_key end function create_or_update_secret(secret_id, params) secret_exists = try Secrets_Manager.get_secret_value(secret_id) true catch e if e isa AWSException && e.code == "ResourceNotFoundException" false else rethrow() end end r = if !secret_exists Secrets_Manager.create_secret(secret_id, params) else Secrets_Manager.update_secret(secret_id, params) end return r end # TODO: Add timeout function wait_for_user_to_exist(user_name) while true try IAM.get_user(Dict("UserName" => user_name)) break catch e if e isa AWSException && e.code == "NoSuchEntity" sleep(5) continue else rethrow() end end end return nothing end # Create multiple MFA devices for the `MFAUser`. Utilizing virtual MFA devices for our AWS.jl # integration tests proved challenging for the following reasons: # # 1. A TOTP code can only be used once. # 2. MFA devices can only be associated with users. See `iam:EnableMFADevice`: https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html # 3. Up to 8 MFA devices can be associated win a single user: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html#replace-virt-mfa # 4. AWS CloudFormation supports creating MFA devices and even assocaiting the device with a # user but doesn't provide access to the seed. See `AWS::IAM::VirtualMFADevice`: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#aws-resource-iam-role-return-values # 5. There is a lag between when you associating an MFA device with a user and when you can first use it (~10 seconds) # # When running integration tests in parallel having TOTP codes be consumed or having a # limited amount of MFA devices per user can cause unwanted throttling when running tests. # To mitigate this issue the following algorithm is employed: # # As part of our resource setup we'll create and associate 8 virtual MFA devices with our # AWS user. When running a test that requires the MFA user iterate through a randomized list # of the MFA devices and attempt the API call with the associated TOTP. If the TOTP has been # consumed we'll try the next MFA device in the list until all MFA devices have been # attempted. If all TOTPs have been consumed we'll wait until th next time window and try # again with a new randomized list of MFA devices. # # The primary advantage of this approach is that it allows up to 8 API calls to occur # concurrently during the same time window. Concurrent integration tests will only be # throttled if all TOTP tokens have been consumed. function create_or_update_mfa_devices(; user_name, secret_id, num_devices=8) # Assumes user exists # TODO: Should be `list_mfa_devices` instead of `list_mfadevices` r = IAM.list_mfadevices(Dict("UserName" => user_name)) existing_mfa_devices = get(parse(r)["ListMFADevicesResult"]["MFADevices"], "member", []) # When only a single MFA device is associated with the `user_name` then an # `AbstractDict` will be returned instead of an `AbstractVector`. if existing_mfa_devices isa AbstractDict existing_mfa_devices = [existing_mfa_devices] end if !isempty(existing_mfa_devices) @info "Deleting MFA devices for $user_name" for mfa_device in existing_mfa_devices mfa_serial = mfa_device["SerialNumber"] IAM.deactivate_mfadevice(mfa_serial, user_name) IAM.delete_virtual_mfadevice(mfa_serial) end end # Under certain conditions (such as manually deleting a stack) the user may no longer # exist but the MFA devices we want to create mfa_device_names = ["$user_name-$i" for i in 1:8] account_id = aws_account_number(AWSConfig()) for mfa_device_name in mfa_device_names mfa_serial = "arn:aws:iam::$account_id:mfa/$mfa_device_name" try IAM.delete_virtual_mfadevice(mfa_serial) @warn "Deleting orphaned MFA device: $mfa_serial" catch e if e isa AWSException && e.code == "NoSuchEntity" nothing else rethrow() end end end @info "Creating $num_devices MFA devices for $user_name" mfa_devices = NamedTuple{(:mfa_serial, :seed),Tuple{String,String}}[] for mfa_device_name in mfa_device_names r = IAM.create_virtual_mfadevice(mfa_device_name) mfa_device = parse(r)["CreateVirtualMFADeviceResult"]["VirtualMFADevice"] mfa_serial = mfa_device["SerialNumber"] seed = String(transcode(Base64Decoder(), mfa_device["Base32StringSeed"])) # When a human sets up an virtual MFA device they prompted to enter "two consecutive # authentication codes". Usually one would enter the currency OTP code and wait for # next code to be generated. Entering the current and future OTP codes could result in # issues. # https://aws.amazon.com/blogs/security/how-to-enable-mfa-protection-on-your-aws-api-calls/ # TODO: Argument ordering here is horrible IAM.enable_mfadevice(totp(seed; offset=-1), totp(seed), mfa_serial, user_name) push!(mfa_devices, (; mfa_serial, seed)) end @info "Storing MFA device details" return create_or_update_secret( secret_id, Dict("SecretString" => JSON.json(mfa_devices)) ) end if @__FILE__() == abspath(PROGRAM_FILE) stack_name = "AWS-jl-test" prefix = "AWS.jl" stack_params = Dict("GitHubRepo" => prefix) template_body = read("aws_jl_test.yaml", String) @info "Creating/updating stack: $stack_name" parameters = [ Dict("ParameterKey" => k, "ParameterValue" => v) for (k, v) in stack_params ] create_or_update_stack( stack_name, Dict( "Capabilities" => ["CAPABILITY_NAMED_IAM"], "TemplateBody" => template_body, "Parameters" => parameters, ), ) # When the stack is first created we need to wait for the user to be created mfa_user = "$prefix-mfa-user" @info "Waiting for $mfa_user" wait_for_user_to_exist(mfa_user) create_or_update_mfa_devices(; user_name=mfa_user, secret_id="$prefix-mfa-user-virtual-mfa-devices" ) end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
3673
using CodecBase: Base32Decoder, Base64Decoder, transcode using Dates: UTC, now using SHA: hmac_sha1 # As defined in https://datatracker.ietf.org/doc/html/rfc4226#section-5 # Using fixed number of digits (6) function hotp(k, c) digits = 6 hs = hmac_sha1(k, c) dbc1 = dynamic_truncation(hs) otp = Int32(dbc1 % 10^digits) return lpad(otp, digits, '0') end function dynamic_truncation(hmac_result::Vector{UInt8}) offset = hmac_result[20] & 0x0f # lower 4-bits return ( UInt32(hmac_result[offset + 1] & 0x7f) << 24 | UInt32(hmac_result[offset + 2] & 0xff) << 16 | UInt32(hmac_result[offset + 3] & 0xff) << 8 | UInt32(hmac_result[offset + 4] & 0xff) ) # big-endian end # As defined in https://datatracker.ietf.org/doc/html/rfc6238#section-4 function totp(k::Vector{UInt8}; duration=30, offset=0) t = time_step_window(; duration) c = reinterpret(UInt8, [hton(t + offset)]) # Convert to big-endian return hotp(k, c) end totp(k::AbstractString; kwargs...) = totp(transcode(Base32Decoder(), k); kwargs...) function consumed_totp(k; duration=30, offset=0) last_window = 0 function () t = time() window = time_step_window(; duration, t) if window <= last_window sleep(duration - (t % duration) + 1) window += 1 end last_window = window return totp(k; duration, offset) end end """ time_step_window(; duration=30, t=time(), t0=0) -> Int # Keywords - `duration::Integer`: Time step in seconds. - `t::Number=time()`: Number of seconds since midnight UTC of January 1, 1970 (UNIX epoch). - `t0::Number=0`: UNIX time to start counting time steps (default 0 is the UNIX epoch). """ time_step_window(; duration=30, t=time(), t0=0) = div(floor(Int64, t - t0), duration) # Utilize all MFA devices associated with a user in order to reduce throttling due to TOTP # tokens being consumed. function mfa_device_pool(f, mfa_devices; duration=30, max_windows=3, debug=false) num_windows = 0 while num_windows < max_windows num_windows += 1 # Attempt to authenticate with each MFA device associated with the user until one # succeeds. If an invalid MFA OTP error is found then the OTP has been already # consumed. for d in shuffle(mfa_devices) token = totp(d.seed; duration) debug && println("$(now(UTC))Z - $(d.mfa_serial) - $token") try return f(d.mfa_serial, token) catch e # Examples of MFA token failures to retry: # "MultiFactorAuthentication failed with invalid MFA one time pass code." # "MultiFactorAuthentication failed, unable to validate MFA code. Please verify your MFA serial number is valid and associated with this user." if ( e isa AWSException && contains(e.message, "MultiFactorAuthentication failed") ) debug && println("MFA token has been consumed") continue else rethrow() end end end # Wait until the next time step window as the MFA device's OTP codes have been # consumed for this window. debug && println("All MFA tokens have been consumed. Waiting for next window...") sleep(duration - (time() % duration) + 1) end error( "Unable to find a working TOTP token after $(length(mfa_devices) * max_windows) " * "attempts over $(duration * (max_windows - 1)) seconds.", ) return nothing end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
code
44
module TestPkg using AWS @service S3 end
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
docs
9082
## AWS.jl [![CI](https://github.com/JuliaCloud/AWS.jl/workflows/CI/badge.svg)](https://github.com/JuliaCloud/AWS.jl/actions?query=workflow%3ACI) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) [![Docs: stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliacloud.github.io/AWS.jl/stable) [![Docs: dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://juliacloud.github.io/AWS.jl/dev) ## Overview A Julia interface for [Amazon Web Services](https://aws.amazon.com). This package replaces [AWSCore.jl](https://github.com/JuliaCloud/AWSCore.jl) and [AWSSDK.jl](https://github.com/JuliaCloud/AWSSDK.jl) which previously provided low-level and high-level APIs respectively. It includes automated code generation to ensure all new AWS services are available, as well as keeping existing services up to date. semver note: AWS.jl uses [semver](https://semver.org/) to imbue it's version numbers with semantic meaning. In particular, breaking changes to the programmatic interface provided by AWS.jl (e.g. the `@service` macro, the [backends](https://juliacloud.github.io/AWS.jl/stable/backends.html) mechanism, etc) will only occur when the major version number changes. However, breaking changes to the upstream AWS-provided API are **not** reflected in the AWS.jl version number. For example, if AWS removes functionality, changes a keyword argument, etc, then the corresponding changes will be made here (via an automated update mechanism) **without** a corresponding breaking release to AWS.jl. These changes will always be made as a *feature release*, i.e. a minor-version bump to AWS.jl. Therefore it is recommended to use the [tilde specifier](https://pkgdocs.julialang.org/v1/compatibility/#Tilde-specifiers) in your compat bounds with AWS.jl if your code is sensitive to such changes. To see an overview of the architecture see the [design document](https://github.com/JuliaCloud/AWS.jl/wiki/v1-Design-Document). ## Installation ```julia julia> Pkg.add("AWS") ``` ## Usage `AWS.jl` can be used with low-level and high-level API requests. Please note when passing parameters for a request they must be a subtype of `AbstractDict{String, <:Any}`. ### Low-Level To use the low-level API, you must know how to perform the request you are making. If you do not know how to perform a request you can reference the [AWS Documentation](https://docs.aws.amazon.com/). Alternatively you can look at `/src/services/{Service}.jl` to find a list of available requests, as well as their required and optional parameters. For example, to list the objects in an S3 bucket you must pass in the request method (`"GET"`) and the endpoint (`"/${bucket}"`): ```julia using AWS.AWSServices: s3 s3("GET", "/your-bucket") ``` ### High-Level To use the high-level API, you only need to know the name of the request you wish to make. For example again, to list the objects in an S3 bucket: ```julia using AWS: @service @service S3 S3.list_objects("your-bucket") # note: no '/' in front of bucket name ``` Working with public buckets that require "--no-sign-request", e.g. [copernicus data](https://registry.opendata.aws/copernicus-dem/), you'll need to set AWS credentials to `nothing`: ```julia using AWS: @service @service S3 aws_config = AWSConfig(; creds=nothing, region="eu-central-1") a = S3.list_objects("copernicus-dem-30m/"; aws_config) ``` The high-level function calls are wrapped around the low-level function calls, meaning you can still pass along any low-level `kwargs` such as `aws_config` when making these requests. **Note:** When calling the `@service` macro you **CANNOT** match the predefined constant for the low level API. The low level API constants are named in all lowercase, and spaces are replaced with underscores. ```julia using AWS.AWSServices: secrets_manager using AWS: @service # This matches the constant and will error! @service secrets_manager > ERROR: cannot assign a value to variable AWSServices.secrets_manager from module Main # This does NOT match the filename structure and will error! @service secretsmanager > ERROR: could not open file /.julia/dev/AWS.jl/src/services/secretsmanager.jl # All of the examples below are valid! @service Secrets_Manager @service SECRETS_MANAGER @service sECRETS_MANAGER ``` ## Limitations Currently there are a few limitations with the high-level APIs. For example, with S3's DeleteMultipleObjects call. To remove multiple objects you must pass in an XML string (see below) in the body of the request. Low-Level API Example: ```julia using AWS.AWSServices: s3 body = """ <Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Object> <Key>test.txt</Key> </Object> </Delete> """ bucket_name = "example-bucket" s3("POST", "/$bucket_name?delete", Dict("body" => body)) # Delete multiple objects ``` There is no-programatic way to see this from the [aws-sdk-js](https://github.com/aws/aws-sdk-js/blob/master/apis/s3-2006-03-01.normal.json), so the high-level function will not work. High-Level API Example: ```julia using AWS: @service @service S3 body = """ <Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Object> <Key>test.txt</Key> </Object> </Delete> """ bucket_name = "example-bucket" S3.DeleteObjects(bucket_name, body) # Delete multiple objects > ERROR: AWS.AWSExceptions.AWSException("MissingRequestBodyError", "Request Body is empty") ``` There are most likely other similar functions which require more intricate details in how the requests are performed, both in the S3 definitions and in other services. ## Modifying Functionality There are sometimes situations, in which default behavior of AWS.jl might be overridden, for example when this package is used to access S3-compatible object storage of a different cloud service provider, which might have different ways of joining the endpoint url, encoding the region in the signature etc. In many cases this can be achieved by creating a user-defined subtype of `AbstractAWSConfig` where some of the default methods are overwritten. For example, if you want to use the S3 high-level interface to access public data from GCS without authorisation, you could define: ````julia struct AnonymousGCS <:AbstractAWSConfig end struct NoCredentials end AWS.region(aws::AnonymousGCS) = "" # No region AWS.credentials(aws::AnonymousGCS) = NoCredentials() # No credentials AWS.check_credentials(c::NoCredentials) = c # Skip credentials check AWS.sign!(aws::AnonymousGCS, ::AWS.Request) = nothing # Don't sign request function AWS.generate_service_url(aws::AnonymousGCS, service::String, resource::String) service == "s3" || throw(ArgumentError("Can only handle s3 requests to GCS")) return string("https://storage.googleapis.com.", resource) end AWS.global_aws_config(AnonymousGCS()) ```` which skips some of the signature and credentials checking and modifies the generation of the endpoint url. A more extended example would be to use this package to access a custom minio server, we can define: ````julia struct MinioConfig <: AbstractAWSConfig endpoint::String region::String creds end AWS.region(c::MinioConfig) = c.region AWS.credentials(c::MinioConfig) = c.creds ```` and we define our own credentials type: ````julia struct SimpleCredentials access_key_id::String secret_key::String token::String end AWS.check_credentials(c::SimpleCredentials) = c ```` as well as a custom url generator: ````julia function AWS.generate_service_url(aws::MinioConfig, service::String, resource::String) service == "s3" || throw(ArgumentError("Can only handle s3 requests to Minio")) return string(aws.endpoint, resource) end AWS.global_aws_config(MinioConfig("http://127.0.0.1:9000", "aregion", SimpleCredentials("minio", "minio123", ""))) ```` Now we are ready to use AWS.jl to do S3-compatible requests to a minio server. ## Alternative Solutions There are a few alternatives to this package, the two below are being deprecated in favour of this package: * [AWSCore.jl](https://github.com/JuliaCloud/AWSCore.jl) - Low-level AWS interface * [AWSSDK.jl](https://github.com/JuliaCloud/AWSSDK.jl) - High-level AWS interface As well as some hand-written packages for specific AWS services: * [AWSS3.jl](https://github.com/JuliaCloud/AWSS3.jl) - Julia 1.0+ * [AWSSQS.jl](https://github.com/JuliaCloud/AWSSQS.jl) - Julia 1.0+ * [AWSSNS.jl](https://github.com/samoconnor/AWSSNS.jl) - Julia 0.7 * [AWSIAM.jl](https://github.com/samoconnor/AWSIAM.jl) - Julia 0.6 * [AWSEC2.jl](https://github.com/samoconnor/AWSEC2.jl) - Julia 0.6 * [AWSLambda.jl](https://github.com/samoconnor/AWSLambda.jl) - Julia 0.6 * [AWSSES.jl](https://github.com/samoconnor/AWSSES.jl) - Julia 0.6 * [AWSSDB.jl](https://github.com/samoconnor/AWSSDB.jl) - Julia 0.6
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
docs
204
# AWS ```@meta CurrentModule = AWS ``` ### Index ```@index Modules = [AWS] ``` ### Documentation ```@autodocs Modules = [AWS] Order = [:module, :macro, :type, :function, :constant] Private = false ```
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
docs
694
# Backends AWS.jl supports two "backends" which serve as HTTP clients to reach the AWS REST API. The backend can be specified in two ways: by setting the global [`AWS.DEFAULT_BACKEND`](@ref), or by setting the backend on a per-request basis by setting the `"backend"` key in `params` dictionaries: ```julia using AWS @service S3 use_response_type = true result = S3.get_object(bucket, key, Dict("backend" => AWS.DownloadsBackend())) ``` Note: `use_response_type=true` is not needed here for the backend selection to work; it is just a recommended option in general. See [`@service`](@ref) for more. ```@docs AWS.AbstractBackend AWS.DEFAULT_BACKEND AWS.HTTPBackend AWS.DownloadsBackend ```
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
docs
194
# IMDS ```@meta CurrentModule = AWS ``` Provides a Julia interface for accessing AWS instance metadata. ### Documentation ```@docs AWS.IMDS AWS.IMDS.Session AWS.IMDS.get AWS.IMDS.region ```
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
1.92.0
319ade7f8fc88243369e119859a7d3a3e7e7f267
docs
2364
## AWS.jl [![CI](https://github.com/JuliaCloud/AWS.jl/workflows/CI/badge.svg)](https://github.com/JuliaCloud/AWS.jl/actions?query=workflow%3ACI) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) [AWS.jl](https://github.com/JuliaCloud/AWS.jl) is a Julia interface for [Amazon Web Services](https://aws.amazon.com). This package replaces [AWSCore.jl](https://github.com/JuliaCloud/AWSCore.jl) and [AWSSDK.jl](https://github.com/JuliaCloud/AWSSDK.jl) which previously provided low-level and high-level APIs respectively. It includes automated code generation to ensure all new AWS services are available, as well as keeping existing services up to date. To see an overview of the architecture see the [design document](https://github.com/JuliaCloud/AWS.jl/wiki/v1-Design-Document). ## Installation You will need some form of AWS credentials to use this package. The most simple way is to set up [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html). ```julia julia> Pkg.add("AWS") ``` ## Usage `AWS.jl` can be used with low-level and high-level API requests. Please note when passing parameters for a request they must be a subtype of `AbstractDict{String, <:Any}`. ### Low-Level To use the low-level API, you must know how to perform the request you are making. If you do not know how to perform a request you can reference the [AWS Documentation](https://docs.aws.amazon.com/). Alternatively you can look at `/src/services/{Service}.jl` to find a list of available requests, as well as their required and optional parameters. For example, to list the objects in an S3 bucket you must pass in the request method (`"GET"`) and the endpoint (`"/${bucket}"`): ```julia using AWS.AWSServices: s3 s3("GET", "/your-bucket") ``` ### High-Level To use the high-level API, you only need to know the name of the request you wish to make. For example again, to list the objects in an S3 bucket: ```julia using AWS: @service @service S3 S3.list_objects("/your-bucket") ``` #### Documentation for High-Level APIs ```@contents Pages = readdir("services"; join=true) ```
AWS
https://github.com/JuliaCloud/AWS.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
753
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. include(joinpath("..", "src", "GlassCat", "constants.jl")) include(joinpath(GLASSCAT_DIR, "GlassTypes.jl")) include(joinpath(GLASSCAT_DIR, "sources.jl")) include(joinpath(GLASSCAT_DIR, "generate.jl")) mkpath(AGF_DIR) mkpath(JL_DIR) # Build/verify a source directory using information from sources.txt sources = split.(readlines(SOURCES_PATH)) verify_sources!(sources, AGF_DIR) verified_source_names = first.(sources) # Use verified sources to generate required .jl files @info "Using sources: $(join(verified_source_names, ", ", " and "))" generate_jls(verified_source_names, AGFGLASSCAT_PATH, JL_DIR, AGF_DIR)
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
364
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. using OpticSim # this will only work after the main build steps are completed @info "Running representative workload" # add stuff here # Examples.hexapolarspotdiagramexample() @info "Finished running representative workload"
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
1306
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. import Pkg, Libdl, PackageCompiler function compile(sysimage_path = "JuliaSysimage.$(Libdl.dlext)") env_to_precompile = joinpath(@__DIR__, "..") precompile_execution_file = joinpath(@__DIR__, "precompile.jl") project_filename = joinpath(env_to_precompile, "Project.toml") project = Pkg.API.read_project(project_filename) used_packages = Symbol.(collect(keys(project.deps))) # don't need these ever after building this so no need to have them in the sysimage filter!(x -> x ∉ [:Libdl, :PackageCompiler, :Pkg], used_packages) if Libdl.dlext == "dll" @warn "Ignoring packages which use gl dlls on Windows as these cause build errors" # see https://github.com/JuliaLang/PackageCompiler.jl/issues/365 # recently the build leaves a corrupt dll if we include these rather than the error in the issue above used_packages = filter(x -> x ∉ [:Makie, :ImageView], used_packages) end @info "Building a custom sysimage for OpticSim.jl." PackageCompiler.create_sysimage(used_packages, sysimage_path = sysimage_path, project = env_to_precompile, precompile_execution_file = precompile_execution_file) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
4266
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. using Documenter using OpticSim import Makie # override certain functions to allow production of interactive figures OpticSim.Vis.set_current_mode(:docs) makedocs( sitename = "OpticSim.jl", format = Documenter.HTML( # prettyurls = get(ENV, "CI", nothing) == "true", assets = [asset("assets/logo.svg", class = :ico, islocal = true)], ), modules = [OpticSim], pages = [ "Home" => "index.md", "Examples" => "examples.md", "Geometry" => [ "Basic Types" => "basic_types.md", "Primitives" => "primitives.md", "CSG" => "csg.md", "Repeating Structures" => "repeat.md" ], "Optical" => [ "Systems" => "systems.md", "Emitters" => "emitters.md", "Interfaces" => "interfaces.md", "Lenses" => "lenses.md" ], "Visualization" => "vis.md", "Glass Functions" => "glasscat.md", "Optimization" => "optimization.md", "Cloud Execution" => "cloud.md", "Notebook utilities" => "notebooksutils.md", "Reference" => "ref.md", "Roadmap" => "roadmap.md" ], expandfirst = ["glasscat.md", "systems.md", "vis.md"] ) deploydocs( repo = "github.com/microsoft/OpticSim.jl.git", devbranch = "main", push_preview = true, ) # function children(m::Module) # ns = names(m, imported = false, all = true) # ms = [] # for n in ns # try # x = Core.eval(m, n) # if x isa Module # if(x != OpticSim.GlassCat) # println("x $x") # push!(ms, x) # end # end # catch # end # end # return ms # end #WARNING: I think this code creates a type for each glass name, which overwrites the definition in the src files where each glass name corresponds to an integer indexing into a glass table. Obviously nothing works after this. Needs major surgery to generate glass documentation at the same time as the documentation for everything else. # # write a code file for the catalog with docstrings # io = open(joinpath(@__DIR__, "../src/AGFGlassCatDocs.jl"), "w") # catalogs = children(OpticSim.GlassCat) # cat_pages = [] # for catname in catalogs # println(catalogs) # eval_string = ["module $(nameof(catname))"] # escape_catalog_name = replace(string(nameof(catname)), "_" => "\\_") # push!(cat_pages, escape_catalog_name => "$(nameof(catname)).md") # iomd = open(joinpath(@__DIR__, "src/$(nameof(catname)).md"), "w") # write(iomd, "# $escape_catalog_name\n\n") # write(iomd, "```@raw html\n") # write(iomd, "<style>article p {display:flex;justify-content:space-between;}</style>\n") # write(iomd, "```\n") # write(iomd, "```@docs\n") # catalog_module = eval(catname) # glass_names = names(catalog_module, all = true, imported = false) # for glass_name in glass_names # glass_name_str = string(glass_name) # if !occursin("#", glass_name_str) && glass_name_str != "eval" && glass_name_str != "include" && glass_name != nameof(catname) && !in(glass_name,(:MODEL, :MIL, :AGF, :OTHER, :AIR)) # glass = Core.eval(catalog_module, glass_name) # temp = typeof(glass) # println("type of glass $temp") # let io = IOBuffer() # OpticSim.GlassCat.docstring(io, glass) # infostr = String(take!(io)) # push!(eval_string, "\"\"\"\n$infostr\n\"\"\"") # end # push!(eval_string, "function $glass_name_str()\nend") # write(iomd, "$catname.$glass_name_str\n") # end # end # write(iomd, "```\n") # push!(eval_string, "end") # module # eval_string = join(eval_string, "\n") # write(io, eval_string * "\n") # close(iomd) # end # close(io) # # include source with docstrings # OpticSim.GlassCat.include(joinpath(@__DIR__, "../src/AGFGlassCatDocs.jl")) # clean up # rm(joinpath(@__DIR__, "../src/AGFGlassCatDocs.jl")) # for p in cat_pages # rm(joinpath(@__DIR__, "src/" * p[2])) # end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
88338
### A Pluto.jl notebook ### # v0.18.0 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═╡ 3f2e9c20-974c-11eb-3e97-757b3e0255f4 begin init_notebook = true using OpticSim, OpticSim.Geometry, OpticSim.Emitters import OpticSim.NotebooksUtils as NB NB.InitNotebook() end # ╔═╡ d6c83680-879e-11eb-31d4-7dbda7e93e48 begin init_notebook import PlutoUI using Makie defs = OpticSim.NotebooksUtils.Defs("ran") NB.DefsClearHTML(defs) # this function is needed to allow the visualization scene to be displayed inside a pluto notebook function Makie.display(obj) #@info "RG: $obj" return obj end #text of this cell to appear in the notebook NB.DefsAddHTML(defs, NB.HTMLFromObj(md"Basic Initialization (code)")) PlutoUI.Show(MIME"text/html"(), NB.DefsHTML(defs)) end # ╔═╡ 576fb1c0-8ba3-11eb-1c10-fdb51172e2c9 md"# Basic CSG (more to come soon)" # ╔═╡ aa47f750-8c1f-11eb-21d7-d3a969fb1f6d begin csg1_top_surface_caption = "Top Surface" csg1_bottom_surface_caption = "Bottom Surface" csg1_cylinder_surface_caption = "Cylinder" csg1_result_surface_caption = "Intersection Result" csg1_surfaces = [ csg1_top_surface_caption, csg1_bottom_surface_caption, csg1_cylinder_surface_caption, csg1_result_surface_caption, ] NB.DefsClearHTML(defs) csg1_selected_surfaces_info = NB.GetVarInfo(@bind csg1_selected_surfaces PlutoUI.MultiSelect(csg1_surfaces, default=csg1_surfaces)) cyl_rot_x_info = NB.GetVarInfo(@bind cyl_rot_x NB.UISlider(0:30, 0)) cyl_rot_y_info = NB.GetVarInfo(@bind cyl_rot_y NB.UISlider(0:30, 0)) cyl_rot_z_info = NB.GetVarInfo(@bind cyl_rot_z NB.UISlider(0:30, 0)) NB.DefsAddHTML(defs, "<div>" * csg1_selected_surfaces_info.html *"</div>" * "Rotation: (x, y, z):" * cyl_rot_x_info.html * cyl_rot_y_info.html * cyl_rot_z_info.html ) PlutoUI.Show(MIME"text/html"(), NB.DefsHTML(defs)) end # ╔═╡ 5cc45e60-8c1f-11eb-3e4a-17c26a3214f6 begin function beziersurface() points = map( x -> collect(x), [ (0.0, 0.0, 0.0) (0.0, 0.33, 0.0) (0.0, 0.66, 0.0) (0.0, 1.0, 0.0) (0.33, 0.0, 0.0) (0.33, 0.33, 1.0) (0.33, 0.66, 1.0) (0.33, 1.0, 0.0) (0.66, 0.0, 0.0) (0.66, 0.33, 1.0) (0.66, 0.66, 1.0) (0.66, 1.0, 0.0) (1.0, 0.0, 0.0) (1.0, 0.33, 0.0) (1.0, 0.66, 0.0) (1.0, 1.0, 0.0) ], ) return BezierSurface{OpticSim.Euclidean,Float64,3,3}(points) end # canonic bezier surface csg1_surf1 = AcceleratedParametricSurface(beziersurface(), 25); # two transformed copies of the canonic bezier surface csg1_surf2 = leaf(csg1_surf1, OpticSim.translation(-0.5, -0.5, 0.0)) csg1_surf3 = leaf(csg1_surf1, Transform(0.0, Float64(π), 0.0, 0.5, -0.5, 0.0)) # transformed cilinder csg1_surf4_1 = leaf(Cylinder(0.3, 1.0), OpticSim.translation(0.0, 0.0, 0.0)) csg1_surf4 = leaf(csg1_surf4_1, OpticSim.rotation(deg2rad(cyl_rot_x), deg2rad(cyl_rot_y), deg2rad(cyl_rot_z))) # intersection result csg1_surf5 = (csg1_surf2 ∩ csg1_surf4 ∩ csg1_surf3)() md"## Define Surfaces and Perform CSG Optrations (code)" end # ╔═╡ 5f77cfd0-8854-11eb-377c-ef975f9abf63 md"## Initialization Stuff - Can be ignored" # ╔═╡ 68e9b210-87ad-11eb-0f3a-5bb2dbf7d86c begin NB.DefsClearHTML(defs) default_resolution_info = NB.GetVarInfo( @bind default_resolution PlutoUI.Select(["Small", "Medium", "Large"], default="Medium") ) makie_backend_info = NB.GetVarInfo( @bind makie_backend PlutoUI.Select(["Static", "Web"], default="Static") ) show_toc_info = NB.GetVarInfo( @bind show_toc PlutoUI.CheckBox(default=true) ) fb3_items = [ "Options", "@ Drawings Size $(default_resolution_info.html)", "Document Options", "@ $(show_toc_info.html) Show Table Of Content", "@ Makie Backend $(makie_backend_info.html) <i><b>(Leave as Static for now)</b></i>", ] NB.DefsAddHTML(defs, NB.HTMLFloatingBox( fb3_items, name="plutoui-docmenu", header="Document Menu", width="25%", top="45%", ) ) # wide document layout NB.DefsAddHTML(defs, NB.HTMLNewDocLayout()) # add TOC NB.DefsAddHTML(defs, NB.HTMLFromObj( PlutoUI.TableOfContents(title = "Document Table of Content", depth = 4) )* NB.HTMLFixTOC() ) #text of this cell to appear in the notebook NB.DefsAddHTML(defs, NB.HTMLFromObj(md"Define Floating Menu, TOC and New Layout (code)")) PlutoUI.Show(MIME"text/html"(), NB.DefsHTML(defs)) end # ╔═╡ 3a5d3ba0-87ae-11eb-1717-93be0b802cab begin drawing = 1 OpticSim.NotebooksUtils.SetBackend(defs, makie_backend) md"Set Makie backend" end # ╔═╡ 8ba2f700-8c1f-11eb-209f-b76b9713b576 begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL Vis.draw(OpticSim.SVector(0.0, 0.0, 0.0), markersize=0) if (csg1_top_surface_caption in csg1_selected_surfaces) Vis.draw!( csg1_surf2; wireframe=true, linewidth=1, color=:orange, shaded=false, normals=false, numdivisions=50 ) end if (csg1_bottom_surface_caption in csg1_selected_surfaces) Vis.draw!( csg1_surf3; wireframe=true, linewidth=1, color=:blue, shaded=false, normals=false, numdivisions=50 ) end if (csg1_cylinder_surface_caption in csg1_selected_surfaces) Vis.draw!( csg1_surf4; wireframe=true, linewidth=1, color=:red, shaded=false, normals=false, numdivisions=50 ) end if (csg1_result_surface_caption in csg1_selected_surfaces) Vis.draw!( csg1_surf5; wireframe=true, linewidth=1, color=:green, shaded=true, normals=false, numdivisions=50 ) end Vis.current_main_scene end # ╔═╡ 96e423a0-885a-11eb-02a3-8704e8dbdab6 begin function Vis.scene(resolution = (1000, 1000)) # @info "RG: Vis.Scene Replacement" scene, layout = Makie.layoutscene(resolution = resolution) Vis.set_current_main_scene(scene) lscene = layout[1, 1] = Makie.LScene(scene, scenekw = (camera = Makie.cam3d_cad!, axis_type = Makie.axis3d!, raw = false)) Vis.set_current_3d_scene(lscene) return scene, lscene end function resolution() if (default_resolution == "Small") return (300, 300) elseif (default_resolution == "Medium") return (500, 500) else return (1000, 1000) end end end # ╔═╡ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] Makie = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" OpticSim = "24114763-4efb-45e7-af0e-cde916beb153" PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8" [compat] Makie = "~0.15.3" OpticSim = "~0.5.3" PlutoUI = "~0.7.35" """ # ╔═╡ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.7.2" manifest_format = "2.0" [[deps.ASL_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "6252039f98492252f9e47c312c8ffda0e3b9e78d" uuid = "ae81ac8f-d209-56e5-92de-9978fef736f9" version = "0.1.3+0" [[deps.ATK_jll]] deps = ["Artifacts", "Glib_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "58c36d8a1beeb12d63921bcfaa674baf30a1140e" uuid = "7b86fcea-f67b-53e1-809c-8f1719c154e8" version = "2.36.1+0" [[deps.AbstractFFTs]] deps = ["ChainRulesCore", "LinearAlgebra"] git-tree-sha1 = "6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4" uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c" version = "1.1.0" [[deps.AbstractPlutoDingetjes]] deps = ["Pkg"] git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481" uuid = "6e696c72-6542-2067-7265-42206c756150" version = "1.1.4" [[deps.AbstractTrees]] git-tree-sha1 = "03e0550477d86222521d254b741d470ba17ea0b5" uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" version = "0.3.4" [[deps.Adapt]] deps = ["LinearAlgebra"] git-tree-sha1 = "af92965fb30777147966f58acb05da51c5616b5f" uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" version = "3.3.3" [[deps.Animations]] deps = ["Colors"] git-tree-sha1 = "e81c509d2c8e49592413bfb0bb3b08150056c79d" uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340" version = "0.4.1" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" [[deps.ArnoldiMethod]] deps = ["LinearAlgebra", "Random", "StaticArrays"] git-tree-sha1 = "62e51b39331de8911e4a7ff6f5aaf38a5f4cc0ae" uuid = "ec485272-7323-5ecc-a04f-4719b315124d" version = "0.2.0" [[deps.ArrayInterface]] deps = ["Compat", "IfElse", "LinearAlgebra", "Requires", "SparseArrays", "Static"] git-tree-sha1 = "745233d77146ad221629590b6d82fe7f1ddb478f" uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9" version = "4.0.3" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Automa]] deps = ["Printf", "ScanByte", "TranscodingStreams"] git-tree-sha1 = "d50976f217489ce799e366d9561d56a98a30d7fe" uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b" version = "0.8.2" [[deps.AxisAlgorithms]] deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"] git-tree-sha1 = "66771c8d21c8ff5e3a93379480a2307ac36863f7" uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950" version = "1.0.1" [[deps.AxisArrays]] deps = ["Dates", "IntervalSets", "IterTools", "RangeArrays"] git-tree-sha1 = "d127d5e4d86c7680b20c35d40b503c74b9a39b5e" uuid = "39de3d68-74b9-583c-8d2d-e117c070f3a9" version = "0.4.4" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.BenchmarkTools]] deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"] git-tree-sha1 = "4c10eee4af024676200bc7752e536f858c6b8f93" uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" version = "1.3.1" [[deps.BinaryProvider]] deps = ["Libdl", "Logging", "SHA"] git-tree-sha1 = "ecdec412a9abc8db54c0efc5548c64dfce072058" uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" version = "0.5.10" [[deps.Bzip2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2" uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0" version = "1.0.8+0" [[deps.CEnum]] git-tree-sha1 = "215a9aa4a1f23fbd05b92769fdd62559488d70e9" uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" version = "0.4.1" [[deps.CRlibm]] deps = ["CRlibm_jll"] git-tree-sha1 = "32abd86e3c2025db5172aa182b982debed519834" uuid = "96374032-68de-5a5b-8d9e-752f78720389" version = "1.0.1" [[deps.CRlibm_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "e329286945d0cfc04456972ea732551869af1cfc" uuid = "4e9b3aee-d8a1-5a3d-ad8b-7d824db253f0" version = "1.0.1+0" [[deps.CSV]] deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings"] git-tree-sha1 = "49f14b6c56a2da47608fe30aed711b5882264d7a" uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" version = "0.9.11" [[deps.Cairo]] deps = ["Cairo_jll", "Colors", "Glib_jll", "Graphics", "Libdl", "Pango_jll"] git-tree-sha1 = "d0b3f8b4ad16cb0a2988c6788646a5e6a17b6b1b" uuid = "159f3aea-2a34-519c-b102-8c37f9878175" version = "1.0.5" [[deps.Cairo_jll]] deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"] git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2" uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a" version = "1.16.1+1" [[deps.Calculus]] deps = ["LinearAlgebra"] git-tree-sha1 = "f641eb0a4f00c343bbc32346e1217b86f3ce9dad" uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9" version = "0.5.1" [[deps.CatIndices]] deps = ["CustomUnitRanges", "OffsetArrays"] git-tree-sha1 = "a0f80a09780eed9b1d106a1bf62041c2efc995bc" uuid = "aafaddc9-749c-510e-ac4f-586e18779b91" version = "0.2.2" [[deps.ChainRules]] deps = ["ChainRulesCore", "Compat", "IrrationalConstants", "LinearAlgebra", "Random", "RealDot", "SparseArrays", "Statistics"] git-tree-sha1 = "098b5eeb1170f569a45f363066b0e405868fc210" uuid = "082447d4-558c-5d27-93f4-14fc19e9eca2" version = "1.27.0" [[deps.ChainRulesCore]] deps = ["Compat", "LinearAlgebra", "SparseArrays"] git-tree-sha1 = "c9a6160317d1abe9c44b3beb367fd448117679ca" uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" version = "1.13.0" [[deps.ChangesOfVariables]] deps = ["ChainRulesCore", "LinearAlgebra", "Test"] git-tree-sha1 = "bf98fa45a0a4cee295de98d4c1462be26345b9a1" uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0" version = "0.1.2" [[deps.Clustering]] deps = ["Distances", "LinearAlgebra", "NearestNeighbors", "Printf", "SparseArrays", "Statistics", "StatsBase"] git-tree-sha1 = "75479b7df4167267d75294d14b58244695beb2ac" uuid = "aaaa29a8-35af-508c-8bc3-b662a17a0fe5" version = "0.14.2" [[deps.CodeTracking]] deps = ["InteractiveUtils", "UUIDs"] git-tree-sha1 = "759a12cefe1cd1bb49e477bc3702287521797483" uuid = "da1fd8a2-8d9e-5ec2-8556-3022fb5608a2" version = "1.0.7" [[deps.CodecBzip2]] deps = ["Bzip2_jll", "Libdl", "TranscodingStreams"] git-tree-sha1 = "2e62a725210ce3c3c2e1a3080190e7ca491f18d7" uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd" version = "0.7.2" [[deps.CodecZlib]] deps = ["TranscodingStreams", "Zlib_jll"] git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da" uuid = "944b1d66-785c-5afd-91f1-9de20f533193" version = "0.7.0" [[deps.ColorBrewer]] deps = ["Colors", "JSON", "Test"] git-tree-sha1 = "61c5334f33d91e570e1d0c3eb5465835242582c4" uuid = "a2cac450-b92f-5266-8821-25eda20663c8" version = "0.4.0" [[deps.ColorSchemes]] deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random"] git-tree-sha1 = "12fc73e5e0af68ad3137b886e3f7c1eacfca2640" uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" version = "3.17.1" [[deps.ColorTypes]] deps = ["FixedPointNumbers", "Random"] git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597" uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" version = "0.11.0" [[deps.ColorVectorSpace]] deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"] git-tree-sha1 = "3f1f500312161f1ae067abe07d13b40f78f32e07" uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" version = "0.9.8" [[deps.Colors]] deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40" uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" version = "0.12.8" [[deps.CommonSubexpressions]] deps = ["MacroTools", "Test"] git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7" uuid = "bbf7d656-a473-5ed7-a52c-81e309532950" version = "0.3.0" [[deps.Compat]] deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] git-tree-sha1 = "44c37b4636bc54afac5c574d2d02b625349d6582" uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" version = "3.41.0" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" [[deps.ComputationalResources]] git-tree-sha1 = "52cb3ec90e8a8bea0e62e275ba577ad0f74821f7" uuid = "ed09eef8-17a6-5b46-8889-db040fac31e3" version = "0.3.2" [[deps.Conda]] deps = ["Downloads", "JSON", "VersionParsing"] git-tree-sha1 = "6e47d11ea2776bc5627421d59cdcc1296c058071" uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d" version = "1.7.0" [[deps.Configurations]] deps = ["ExproniconLite", "OrderedCollections", "TOML"] git-tree-sha1 = "ab9b7c51e8acdd20c769bccde050b5615921c533" uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d" version = "0.17.3" [[deps.ConstructionBase]] deps = ["LinearAlgebra"] git-tree-sha1 = "f74e9d5388b8620b4cee35d4c5a618dd4dc547f4" uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9" version = "1.3.0" [[deps.Contour]] deps = ["StaticArrays"] git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7" uuid = "d38c429a-6771-53c6-b99e-75d170b6e991" version = "0.5.7" [[deps.CoordinateTransformations]] deps = ["LinearAlgebra", "StaticArrays"] git-tree-sha1 = "681ea870b918e7cff7111da58791d7f718067a19" uuid = "150eb455-5306-5404-9cee-2592286d6298" version = "0.6.2" [[deps.Crayons]] git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15" uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" version = "4.1.1" [[deps.CustomUnitRanges]] git-tree-sha1 = "1a3f97f907e6dd8983b744d2642651bb162a3f7a" uuid = "dc8bdbbb-1ca9-579f-8c36-e416f6a65cce" version = "1.0.2" [[deps.DataAPI]] git-tree-sha1 = "cc70b17275652eb47bc9e5f81635981f13cea5c8" uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" version = "1.9.0" [[deps.DataFrames]] deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] git-tree-sha1 = "ae02104e835f219b8930c7664b8012c93475c340" uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" version = "1.3.2" [[deps.DataStructures]] deps = ["Compat", "InteractiveUtils", "OrderedCollections"] git-tree-sha1 = "3daef5523dd2e769dad2365274f760ff5f282c7d" uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" version = "0.18.11" [[deps.DataValueInterfaces]] git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" version = "1.0.0" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.Dbus_jll]] deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "97f1325c10bd02b1cc1882e9c2bf6407ba630ace" uuid = "ee1fde0b-3d02-5ea6-8484-8dfef6360eab" version = "1.12.16+3" [[deps.DelimitedFiles]] deps = ["Mmap"] uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" [[deps.DensityInterface]] deps = ["InverseFunctions", "Test"] git-tree-sha1 = "80c3e8639e3353e5d2912fb3a1916b8455e2494b" uuid = "b429d917-457f-4dbc-8f4c-0cc954292b1d" version = "0.4.0" [[deps.DiffResults]] deps = ["StaticArrays"] git-tree-sha1 = "c18e98cba888c6c25d1c3b048e4b3380ca956805" uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5" version = "1.0.3" [[deps.DiffRules]] deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"] git-tree-sha1 = "dd933c4ef7b4c270aacd4eb88fa64c147492acf0" uuid = "b552c78f-8df3-52c6-915a-8e097449b14b" version = "1.10.0" [[deps.Distances]] deps = ["LinearAlgebra", "SparseArrays", "Statistics", "StatsAPI"] git-tree-sha1 = "3258d0659f812acde79e8a74b11f17ac06d0ca04" uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" version = "0.10.7" [[deps.Distributed]] deps = ["Random", "Serialization", "Sockets"] uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" [[deps.Distributions]] deps = ["ChainRulesCore", "DensityInterface", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "Test"] git-tree-sha1 = "9d3c0c762d4666db9187f363a76b47f7346e673b" uuid = "31c24e10-a181-5473-b8eb-7969acd0382f" version = "0.25.49" [[deps.DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "b19534d1895d702889b219c382a6e18010797f0b" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.8.6" [[deps.Downloads]] deps = ["ArgTools", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" [[deps.DualNumbers]] deps = ["Calculus", "NaNMath", "SpecialFunctions"] git-tree-sha1 = "84f04fe68a3176a583b864e492578b9466d87f1e" uuid = "fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74" version = "0.6.6" [[deps.EarCut_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d" uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5" version = "2.2.3+0" [[deps.EllipsisNotation]] deps = ["ArrayInterface"] git-tree-sha1 = "d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa" uuid = "da5c29d0-fa7d-589e-88eb-ea29b0a81949" version = "1.3.0" [[deps.ErrorfreeArithmetic]] git-tree-sha1 = "d6863c556f1142a061532e79f611aa46be201686" uuid = "90fa49ef-747e-5e6f-a989-263ba693cf1a" version = "0.5.2" [[deps.Expat_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "ae13fcbc7ab8f16b0856729b050ef0c446aa3492" uuid = "2e619515-83b5-522b-bb60-26c02a35a201" version = "2.4.4+0" [[deps.ExprTools]] git-tree-sha1 = "56559bbef6ca5ea0c0818fa5c90320398a6fbf8d" uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04" version = "0.1.8" [[deps.ExproniconLite]] git-tree-sha1 = "8b08cc88844e4d01db5a2405a08e9178e19e479e" uuid = "55351af7-c7e9-48d6-89ff-24e801d99491" version = "0.6.13" [[deps.FFMPEG]] deps = ["FFMPEG_jll"] git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8" uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a" version = "0.4.1" [[deps.FFMPEG_jll]] deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"] git-tree-sha1 = "d8a578692e3077ac998b50c0217dfd67f21d1e5f" uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5" version = "4.4.0+0" [[deps.FFTViews]] deps = ["CustomUnitRanges", "FFTW"] git-tree-sha1 = "cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2" uuid = "4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd" version = "0.3.2" [[deps.FFTW]] deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"] git-tree-sha1 = "463cb335fa22c4ebacfd1faba5fde14edb80d96c" uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" version = "1.4.5" [[deps.FFTW_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea" uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a" version = "3.3.10+0" [[deps.FastRounding]] deps = ["ErrorfreeArithmetic", "Test"] git-tree-sha1 = "224175e213fd4fe112db3eea05d66b308dc2bf6b" uuid = "fa42c844-2597-5d31-933b-ebd51ab2693f" version = "0.2.0" [[deps.FileIO]] deps = ["Pkg", "Requires", "UUIDs"] git-tree-sha1 = "80ced645013a5dbdc52cf70329399c35ce007fae" uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" version = "1.13.0" [[deps.FilePathsBase]] deps = ["Compat", "Dates", "Mmap", "Printf", "Test", "UUIDs"] git-tree-sha1 = "04d13bfa8ef11720c24e4d840c0033d145537df7" uuid = "48062228-2e41-5def-b9a4-89aafe57970f" version = "0.9.17" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.FillArrays]] deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"] git-tree-sha1 = "deed294cde3de20ae0b2e0355a6c4e1c6a5ceffc" uuid = "1a297f60-69ca-5386-bcde-b61e274b549b" version = "0.12.8" [[deps.FiniteDiff]] deps = ["ArrayInterface", "LinearAlgebra", "Requires", "SparseArrays", "StaticArrays"] git-tree-sha1 = "ec299fdc8f49ae450807b0cb1d161c6b76fd2b60" uuid = "6a86dc24-6348-571c-b903-95158fe2bd41" version = "2.10.1" [[deps.FixedPointNumbers]] deps = ["Statistics"] git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc" uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" version = "0.8.4" [[deps.Fontconfig_jll]] deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03" uuid = "a3f928ae-7b40-5064-980b-68af3947d34b" version = "2.13.93+0" [[deps.Format]] git-tree-sha1 = "03bcdf8ab1a5b9e6455ccb45c30910d282aa09f4" uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8" version = "1.3.2" [[deps.Formatting]] deps = ["Printf"] git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8" uuid = "59287772-0a20-5a39-b81b-1366585eb4c0" version = "0.4.2" [[deps.ForwardDiff]] deps = ["CommonSubexpressions", "DiffResults", "DiffRules", "LinearAlgebra", "LogExpFunctions", "NaNMath", "Preferences", "Printf", "Random", "SpecialFunctions", "StaticArrays"] git-tree-sha1 = "1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2" uuid = "f6369f11-7733-5829-9624-2563aa707210" version = "0.10.25" [[deps.FreeType]] deps = ["CEnum", "FreeType2_jll"] git-tree-sha1 = "cabd77ab6a6fdff49bfd24af2ebe76e6e018a2b4" uuid = "b38be410-82b0-50bf-ab77-7b57e271db43" version = "4.0.0" [[deps.FreeType2_jll]] deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "87eb71354d8ec1a96d4a7636bd57a7347dde3ef9" uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7" version = "2.10.4+0" [[deps.FreeTypeAbstraction]] deps = ["ColorVectorSpace", "Colors", "FreeType", "GeometryBasics", "StaticArrays"] git-tree-sha1 = "770050893e7bc8a34915b4b9298604a3236de834" uuid = "663a7486-cb36-511b-a19d-713bb74d65c9" version = "0.9.5" [[deps.FriBidi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91" uuid = "559328eb-81f9-559d-9380-de523a88c83c" version = "1.0.10+0" [[deps.FunctionWrappers]] git-tree-sha1 = "241552bc2209f0fa068b6415b1942cc0aa486bcc" uuid = "069b7b12-0de2-55c6-9aab-29f3d0a68a2e" version = "1.1.2" [[deps.Future]] deps = ["Random"] uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" [[deps.FuzzyCompletions]] deps = ["REPL"] git-tree-sha1 = "2cc2791b324e8ed387a91d7226d17be754e9de61" uuid = "fb4132e2-a121-4a70-b8a1-d5b831dcdcc2" version = "0.4.3" [[deps.GLFW]] deps = ["GLFW_jll"] git-tree-sha1 = "35dbc482f0967d8dceaa7ce007d16f9064072166" uuid = "f7f18e0c-5ee9-5ccd-a5bf-e8befd85ed98" version = "3.4.1" [[deps.GLFW_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"] git-tree-sha1 = "51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01" uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89" version = "3.3.6+0" [[deps.GLMakie]] deps = ["ColorTypes", "Colors", "FileIO", "FixedPointNumbers", "FreeTypeAbstraction", "GLFW", "GeometryBasics", "LinearAlgebra", "Makie", "Markdown", "MeshIO", "ModernGL", "Observables", "Printf", "Serialization", "ShaderAbstractions", "StaticArrays"] git-tree-sha1 = "25dd999ef6ad2904206f96211386535bcb86cc58" uuid = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a" version = "0.4.7" [[deps.GLPK]] deps = ["BinaryProvider", "GLPK_jll", "Libdl", "MathOptInterface", "SparseArrays"] git-tree-sha1 = "86573ecb852e303b209212046af44871f1c0e49c" uuid = "60bf3e95-4087-53dc-ae20-288a0d20c6a6" version = "0.13.0" [[deps.GLPK_jll]] deps = ["GMP_jll", "Libdl", "Pkg"] git-tree-sha1 = "ccc855de74292e478d4278e3a6fdd8212f75e81e" uuid = "e8aa6df9-e6ca-548a-97ff-1f85fc5b8b98" version = "4.64.0+0" [[deps.GMP_jll]] deps = ["Artifacts", "Libdl"] uuid = "781609d7-10c4-51f6-84f2-b8444358ff6d" [[deps.GR]] deps = ["Base64", "DelimitedFiles", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Pkg", "Printf", "Random", "RelocatableFolders", "Serialization", "Sockets", "Test", "UUIDs"] git-tree-sha1 = "9f836fb62492f4b0f0d3b06f55983f2704ed0883" uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71" version = "0.64.0" [[deps.GR_jll]] deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Pkg", "Qt5Base_jll", "Zlib_jll", "libpng_jll"] git-tree-sha1 = "a6c850d77ad5118ad3be4bd188919ce97fffac47" uuid = "d2c73de3-f751-5644-a686-071e5b155ba9" version = "0.64.0+0" [[deps.GTK3_jll]] deps = ["ATK_jll", "Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Libepoxy_jll", "Pango_jll", "Pkg", "Wayland_jll", "Xorg_libX11_jll", "Xorg_libXcomposite_jll", "Xorg_libXcursor_jll", "Xorg_libXdamage_jll", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll", "Xorg_libXrender_jll", "at_spi2_atk_jll", "gdk_pixbuf_jll", "iso_codes_jll", "xkbcommon_jll"] git-tree-sha1 = "b080a592525632d287aee4637a62682576b7f5e4" uuid = "77ec8976-b24b-556a-a1bf-49a033a670a6" version = "3.24.31+0" [[deps.GeometryBasics]] deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"] git-tree-sha1 = "58bcdf5ebc057b085e58d95c138725628dd7453c" uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326" version = "0.4.1" [[deps.Gettext_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"] git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046" uuid = "78b55507-aeef-58d4-861c-77aaff3498b1" version = "0.21.0+0" [[deps.Ghostscript_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "78e2c69783c9753a91cdae88a8d432be85a2ab5e" uuid = "61579ee1-b43e-5ca0-a5da-69d92c66a64b" version = "9.55.0+0" [[deps.Glib_jll]] deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "a32d672ac2c967f3deb8a81d828afc739c838a06" uuid = "7746bdde-850d-59dc-9ae8-88ece973131d" version = "2.68.3+2" [[deps.Graphics]] deps = ["Colors", "LinearAlgebra", "NaNMath"] git-tree-sha1 = "1c5a84319923bea76fa145d49e93aa4394c73fc2" uuid = "a2bd30eb-e257-5431-a919-1863eab51364" version = "1.1.1" [[deps.Graphite2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011" uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472" version = "1.3.14+0" [[deps.Graphs]] deps = ["ArnoldiMethod", "Compat", "DataStructures", "Distributed", "Inflate", "LinearAlgebra", "Random", "SharedArrays", "SimpleTraits", "SparseArrays", "Statistics"] git-tree-sha1 = "57c021de207e234108a6f1454003120a1bf350c4" uuid = "86223c79-3864-5bf0-83f7-82e725a168b6" version = "1.6.0" [[deps.GridLayoutBase]] deps = ["GeometryBasics", "InteractiveUtils", "Observables"] git-tree-sha1 = "70938436e2720e6cb8a7f2ca9f1bbdbf40d7f5d0" uuid = "3955a311-db13-416c-9275-1d80ed98e5e9" version = "0.6.4" [[deps.Grisu]] git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2" uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe" version = "1.0.2" [[deps.Gtk]] deps = ["Cairo", "Cairo_jll", "Dates", "GTK3_jll", "Glib_jll", "Graphics", "JLLWrappers", "Libdl", "Librsvg_jll", "Pkg", "Reexport", "Serialization", "Test", "Xorg_xkeyboard_config_jll", "adwaita_icon_theme_jll", "gdk_pixbuf_jll", "hicolor_icon_theme_jll"] git-tree-sha1 = "09afd81dd7d80ae0dc6f489fd21560725e45497e" uuid = "4c0ca9eb-093a-5379-98c5-f87ac0bbbf44" version = "1.2.0" [[deps.GtkReactive]] deps = ["Cairo", "Colors", "Dates", "FixedPointNumbers", "Graphics", "Gtk", "IntervalSets", "Reactive", "Reexport", "RoundingIntegers"] git-tree-sha1 = "ccb07a5fa45e43ac83b6795c9e218d6a802c93d8" uuid = "27996c0f-39cd-5cc1-a27a-05f136f946b6" version = "1.0.6" [[deps.HTTP]] deps = ["Base64", "Dates", "IniFile", "Logging", "MbedTLS", "NetworkOptions", "Sockets", "URIs"] git-tree-sha1 = "0fa77022fe4b511826b39c894c90daf5fce3334a" uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" version = "0.9.17" [[deps.HarfBuzz_jll]] deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"] git-tree-sha1 = "129acf094d168394e80ee1dc4bc06ec835e510a3" uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566" version = "2.8.1+1" [[deps.HypergeometricFunctions]] deps = ["DualNumbers", "LinearAlgebra", "SpecialFunctions", "Test"] git-tree-sha1 = "65e4589030ef3c44d3b90bdc5aac462b4bb05567" uuid = "34004b35-14d8-5ef3-9330-4cdb6864b03a" version = "0.3.8" [[deps.Hyperscript]] deps = ["Test"] git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9" uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91" version = "0.0.4" [[deps.HypertextLiteral]] git-tree-sha1 = "2b078b5a615c6c0396c77810d92ee8c6f470d238" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.3" [[deps.IOCapture]] deps = ["Logging", "Random"] git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a" uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89" version = "0.2.2" [[deps.IRTools]] deps = ["InteractiveUtils", "MacroTools", "Test"] git-tree-sha1 = "7f43342f8d5fd30ead0ba1b49ab1a3af3b787d24" uuid = "7869d1d1-7146-5819-86e3-90919afe41df" version = "0.4.5" [[deps.IfElse]] git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1" uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173" version = "0.1.1" [[deps.ImageAxes]] deps = ["AxisArrays", "ImageBase", "ImageCore", "Reexport", "SimpleTraits"] git-tree-sha1 = "c54b581a83008dc7f292e205f4c409ab5caa0f04" uuid = "2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac" version = "0.6.10" [[deps.ImageBase]] deps = ["ImageCore", "Reexport"] git-tree-sha1 = "b51bb8cae22c66d0f6357e3bcb6363145ef20835" uuid = "c817782e-172a-44cc-b673-b171935fbb9e" version = "0.1.5" [[deps.ImageContrastAdjustment]] deps = ["ImageCore", "ImageTransformations", "Parameters"] git-tree-sha1 = "0d75cafa80cf22026cea21a8e6cf965295003edc" uuid = "f332f351-ec65-5f6a-b3d1-319c6670881a" version = "0.3.10" [[deps.ImageCore]] deps = ["AbstractFFTs", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Graphics", "MappedArrays", "MosaicViews", "OffsetArrays", "PaddedViews", "Reexport"] git-tree-sha1 = "9a5c62f231e5bba35695a20988fc7cd6de7eeb5a" uuid = "a09fc81d-aa75-5fe9-8630-4744c3626534" version = "0.9.3" [[deps.ImageDistances]] deps = ["Distances", "ImageCore", "ImageMorphology", "LinearAlgebra", "Statistics"] git-tree-sha1 = "7a20463713d239a19cbad3f6991e404aca876bda" uuid = "51556ac3-7006-55f5-8cb3-34580c88182d" version = "0.2.15" [[deps.ImageFiltering]] deps = ["CatIndices", "ComputationalResources", "DataStructures", "FFTViews", "FFTW", "ImageBase", "ImageCore", "LinearAlgebra", "OffsetArrays", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "TiledIteration"] git-tree-sha1 = "15bd05c1c0d5dbb32a9a3d7e0ad2d50dd6167189" uuid = "6a3955dd-da59-5b1f-98d4-e7296123deb5" version = "0.7.1" [[deps.ImageIO]] deps = ["FileIO", "Netpbm", "OpenEXR", "PNGFiles", "TiffImages", "UUIDs"] git-tree-sha1 = "a2951c93684551467265e0e32b577914f69532be" uuid = "82e4d734-157c-48bb-816b-45c225c6df19" version = "0.5.9" [[deps.ImageMagick]] deps = ["FileIO", "ImageCore", "ImageMagick_jll", "InteractiveUtils", "Libdl", "Pkg", "Random"] git-tree-sha1 = "5bc1cb62e0c5f1005868358db0692c994c3a13c6" uuid = "6218d12a-5da1-5696-b52f-db25d2ecc6d1" version = "1.2.1" [[deps.ImageMagick_jll]] deps = ["Artifacts", "Ghostscript_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pkg", "Zlib_jll", "libpng_jll"] git-tree-sha1 = "f025b79883f361fa1bd80ad132773161d231fd9f" uuid = "c73af94c-d91f-53ed-93a7-00f77d67a9d7" version = "6.9.12+2" [[deps.ImageMetadata]] deps = ["AxisArrays", "ImageAxes", "ImageBase", "ImageCore"] git-tree-sha1 = "36cbaebed194b292590cba2593da27b34763804a" uuid = "bc367c6b-8a6b-528e-b4bd-a4b897500b49" version = "0.9.8" [[deps.ImageMorphology]] deps = ["ImageCore", "LinearAlgebra", "Requires", "TiledIteration"] git-tree-sha1 = "7668b123ecfd39a6ae3fc31c532b588999bdc166" uuid = "787d08f9-d448-5407-9aad-5290dd7ab264" version = "0.3.1" [[deps.ImageQualityIndexes]] deps = ["ImageContrastAdjustment", "ImageCore", "ImageDistances", "ImageFiltering", "OffsetArrays", "Statistics"] git-tree-sha1 = "1d2d73b14198d10f7f12bf7f8481fd4b3ff5cd61" uuid = "2996bd0c-7a13-11e9-2da2-2f5ce47296a9" version = "0.3.0" [[deps.ImageSegmentation]] deps = ["Clustering", "DataStructures", "Distances", "Graphs", "ImageCore", "ImageFiltering", "ImageMorphology", "LinearAlgebra", "MetaGraphs", "RegionTrees", "SimpleWeightedGraphs", "StaticArrays", "Statistics"] git-tree-sha1 = "36832067ea220818d105d718527d6ed02385bf22" uuid = "80713f31-8817-5129-9cf8-209ff8fb23e1" version = "1.7.0" [[deps.ImageShow]] deps = ["Base64", "FileIO", "ImageBase", "ImageCore", "OffsetArrays", "StackViews"] git-tree-sha1 = "d0ac64c9bee0aed6fdbb2bc0e5dfa9a3a78e3acc" uuid = "4e3cecfd-b093-5904-9786-8bbb286a6a31" version = "0.3.3" [[deps.ImageTransformations]] deps = ["AxisAlgorithms", "ColorVectorSpace", "CoordinateTransformations", "ImageBase", "ImageCore", "Interpolations", "OffsetArrays", "Rotations", "StaticArrays"] git-tree-sha1 = "42fe8de1fe1f80dab37a39d391b6301f7aeaa7b8" uuid = "02fcd773-0e25-5acc-982a-7f6622650795" version = "0.9.4" [[deps.ImageView]] deps = ["AxisArrays", "Cairo", "Graphics", "Gtk", "GtkReactive", "ImageBase", "ImageCore", "ImageMetadata", "RoundingIntegers", "StatsBase"] git-tree-sha1 = "279acc77190075c4abc62d8a0d68337d25d3e55c" uuid = "86fae568-95e7-573e-a6b2-d8a6b900c9ef" version = "0.10.15" [[deps.Images]] deps = ["Base64", "FileIO", "Graphics", "ImageAxes", "ImageBase", "ImageContrastAdjustment", "ImageCore", "ImageDistances", "ImageFiltering", "ImageIO", "ImageMagick", "ImageMetadata", "ImageMorphology", "ImageQualityIndexes", "ImageSegmentation", "ImageShow", "ImageTransformations", "IndirectArrays", "IntegralArrays", "Random", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "TiledIteration"] git-tree-sha1 = "11d268adba1869067620659e7cdf07f5e54b6c76" uuid = "916415d5-f1e6-5110-898d-aaa5f9f070e0" version = "0.25.1" [[deps.Imath_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "87f7662e03a649cffa2e05bf19c303e168732d3e" uuid = "905a6f67-0a94-5f89-b386-d35d92009cd1" version = "3.1.2+0" [[deps.IndirectArrays]] git-tree-sha1 = "012e604e1c7458645cb8b436f8fba789a51b257f" uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959" version = "1.0.0" [[deps.Inflate]] git-tree-sha1 = "f5fc07d4e706b84f72d54eedcc1c13d92fb0871c" uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9" version = "0.1.2" [[deps.IniFile]] git-tree-sha1 = "f550e6e32074c939295eb5ea6de31849ac2c9625" uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" version = "0.5.1" [[deps.InlineStrings]] deps = ["Parsers"] git-tree-sha1 = "61feba885fac3a407465726d0c330b3055df897f" uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" version = "1.1.2" [[deps.IntegralArrays]] deps = ["ColorTypes", "FixedPointNumbers", "IntervalSets"] git-tree-sha1 = "cf737764159c66b95cdbf5c10484929b247fecfe" uuid = "1d092043-8f09-5a30-832f-7509e371ab51" version = "0.1.3" [[deps.IntelOpenMP_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "d979e54b71da82f3a65b62553da4fc3d18c9004c" uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0" version = "2018.0.3+2" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.Interpolations]] deps = ["AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"] git-tree-sha1 = "b15fc0a95c564ca2e0a7ae12c1f095ca848ceb31" uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59" version = "0.13.5" [[deps.IntervalArithmetic]] deps = ["CRlibm", "FastRounding", "LinearAlgebra", "Markdown", "Random", "RecipesBase", "RoundingEmulator", "SetRounding", "StaticArrays"] git-tree-sha1 = "bbf2793a70c0a7aaa09aa298b277fe1b90e06d78" uuid = "d1acc4aa-44c8-5952-acd4-ba5d80a2a253" version = "0.20.3" [[deps.IntervalSets]] deps = ["Dates", "EllipsisNotation", "Statistics"] git-tree-sha1 = "3cc368af3f110a767ac786560045dceddfc16758" uuid = "8197267c-284f-5f27-9208-e0e47529a953" version = "0.5.3" [[deps.Intervals]] deps = ["Dates", "Printf", "RecipesBase", "Serialization", "TimeZones"] git-tree-sha1 = "323a38ed1952d30586d0fe03412cde9399d3618b" uuid = "d8418881-c3e1-53bb-8760-2df7ec849ed5" version = "1.5.0" [[deps.InverseFunctions]] deps = ["Test"] git-tree-sha1 = "a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65" uuid = "3587e190-3f89-42d0-90ee-14403ec27112" version = "0.1.2" [[deps.InvertedIndices]] git-tree-sha1 = "bee5f1ef5bf65df56bdd2e40447590b272a5471f" uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" version = "1.1.0" [[deps.Ipopt]] deps = ["BinaryProvider", "Ipopt_jll", "Libdl", "LinearAlgebra", "MathOptInterface", "MathProgBase"] git-tree-sha1 = "380786b4929b8d18d76e909c6b2eca355b7c3bd6" uuid = "b6b21f68-93f8-5de0-b562-5493be1d77c9" version = "0.7.0" [[deps.Ipopt_jll]] deps = ["ASL_jll", "Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "MUMPS_seq_jll", "OpenBLAS32_jll", "Pkg"] git-tree-sha1 = "82124f27743f2802c23fcb05febc517d0b15d86e" uuid = "9cc047cb-c261-5740-88fc-0cf96f7bdcc7" version = "3.13.4+2" [[deps.IrrationalConstants]] git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151" uuid = "92d709cd-6900-40b7-9082-c6be49f344b6" version = "0.1.1" [[deps.Isoband]] deps = ["isoband_jll"] git-tree-sha1 = "f9b6d97355599074dc867318950adaa6f9946137" uuid = "f1662d9f-8043-43de-a69a-05efc1cc6ff4" version = "0.1.1" [[deps.IterTools]] git-tree-sha1 = "fa6287a4469f5e048d763df38279ee729fbd44e5" uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e" version = "1.4.0" [[deps.IteratorInterfaceExtensions]] git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" uuid = "82899510-4779-5014-852e-03e436cf321d" version = "1.0.0" [[deps.JLD2]] deps = ["FileIO", "MacroTools", "Mmap", "OrderedCollections", "Pkg", "Printf", "Reexport", "TranscodingStreams", "UUIDs"] git-tree-sha1 = "28b114b3279cdbac9a61c57b3e6548a572142b34" uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819" version = "0.4.21" [[deps.JLLWrappers]] deps = ["Preferences"] git-tree-sha1 = "abc9885a7ca2052a736a600f7fa66209f96506e1" uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" version = "1.4.1" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "3c837543ddb02250ef42f4738347454f95079d4e" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.3" [[deps.JSON3]] deps = ["Dates", "Mmap", "Parsers", "StructTypes", "UUIDs"] git-tree-sha1 = "7d58534ffb62cd947950b3aa9b993e63307a6125" uuid = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" version = "1.9.2" [[deps.JSONSchema]] deps = ["HTTP", "JSON", "URIs"] git-tree-sha1 = "2f49f7f86762a0fbbeef84912265a1ae61c4ef80" uuid = "7d188eb4-7ad8-530c-ae41-71a32a6d4692" version = "0.3.4" [[deps.JSServe]] deps = ["Base64", "CodecZlib", "Colors", "HTTP", "Hyperscript", "JSON3", "LinearAlgebra", "Markdown", "MsgPack", "Observables", "RelocatableFolders", "SHA", "Sockets", "Tables", "Test", "UUIDs", "WebSockets", "WidgetsBase"] git-tree-sha1 = "e8c3434c3e880e15760821a9eac00deb35ab6ea9" uuid = "824d6782-a2ef-11e9-3a09-e5662e0c26f9" version = "1.2.5" [[deps.JpegTurbo_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b53380851c6e6664204efb2e62cd24fa5c47e4ba" uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8" version = "2.1.2+0" [[deps.JuMP]] deps = ["Calculus", "DataStructures", "ForwardDiff", "JSON", "LinearAlgebra", "MathOptInterface", "MutableArithmetics", "NaNMath", "Random", "SparseArrays", "Statistics"] git-tree-sha1 = "57c17a221a55f81890aabf00f478886859e25eaf" uuid = "4076af6c-e467-56ae-b986-b466b2749572" version = "0.21.5" [[deps.JuliaInterpreter]] deps = ["CodeTracking", "InteractiveUtils", "Random", "UUIDs"] git-tree-sha1 = "8a50f8b3e6b261561df26f5718a6b59a3c947221" uuid = "aa1ae85d-cabe-5617-a682-6adf51b2e16a" version = "0.9.6" [[deps.Juno]] deps = ["Base64", "Logging", "Media", "Profile"] git-tree-sha1 = "07cb43290a840908a771552911a6274bc6c072c7" uuid = "e5e0dc1b-0480-54bc-9374-aad01c23163d" version = "0.8.4" [[deps.KernelDensity]] deps = ["Distributions", "DocStringExtensions", "FFTW", "Interpolations", "StatsBase"] git-tree-sha1 = "591e8dc09ad18386189610acafb970032c519707" uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b" version = "0.6.3" [[deps.LAME_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c" uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d" version = "3.100.1+0" [[deps.LZO_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6" uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac" version = "2.10.1+0" [[deps.LaTeXStrings]] git-tree-sha1 = "f2355693d6778a178ade15952b7ac47a4ff97996" uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" version = "1.3.0" [[deps.Latexify]] deps = ["Formatting", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "Printf", "Requires"] git-tree-sha1 = "a6552bfeab40de157a297d84e03ade4b8177677f" uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" version = "0.15.12" [[deps.LazyArtifacts]] deps = ["Artifacts", "Pkg"] uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3" [[deps.LazySets]] deps = ["Distributed", "ExprTools", "GLPK", "InteractiveUtils", "IntervalArithmetic", "JuMP", "LinearAlgebra", "Random", "RecipesBase", "Reexport", "Requires", "SharedArrays", "SparseArrays"] git-tree-sha1 = "e92e22dcd8abf31f9418213936aa41399740dd94" uuid = "b4f0291d-fe17-52bc-9479-3d1a343d9043" version = "1.55.0" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" [[deps.LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.Libepoxy_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "18b65a0eff6b58546bec18065e73f8a04e83758d" uuid = "42c93a91-0102-5b3f-8f9d-e41de60ac950" version = "1.5.8+1" [[deps.Libffi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "0b4a5d71f3e5200a7dff793393e09dfc2d874290" uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490" version = "3.2.2+1" [[deps.Libgcrypt_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"] git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae" uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4" version = "1.8.7+0" [[deps.Libglvnd_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll", "Xorg_libXext_jll"] git-tree-sha1 = "7739f837d6447403596a75d19ed01fd08d6f56bf" uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29" version = "1.3.0+3" [[deps.Libgpg_error_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9" uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8" version = "1.42.0+0" [[deps.Libiconv_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778" uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" version = "1.16.1+1" [[deps.Libmount_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73" uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9" version = "2.35.0+0" [[deps.Librsvg_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pango_jll", "Pkg", "gdk_pixbuf_jll"] git-tree-sha1 = "25d5e6b4eb3558613ace1c67d6a871420bfca527" uuid = "925c91fb-5dd6-59dd-8e8c-345e74382d89" version = "2.52.4+0" [[deps.Libtiff_jll]] deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Pkg", "Zlib_jll", "Zstd_jll"] git-tree-sha1 = "340e257aada13f95f98ee352d316c3bed37c8ab9" uuid = "89763e89-9b03-5906-acba-b20f662cd828" version = "4.3.0+0" [[deps.Libuuid_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066" uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700" version = "2.36.0+0" [[deps.LineSearches]] deps = ["LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "Printf"] git-tree-sha1 = "f27132e551e959b3667d8c93eae90973225032dd" uuid = "d3d80556-e9d4-5f37-9878-2ab0fcc64255" version = "7.1.1" [[deps.LinearAlgebra]] deps = ["Libdl", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.LogExpFunctions]] deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"] git-tree-sha1 = "e5718a00af0ab9756305a0392832c8952c7426c1" uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" version = "0.3.6" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.LoweredCodeUtils]] deps = ["JuliaInterpreter"] git-tree-sha1 = "6b0440822974cab904c8b14d79743565140567f6" uuid = "6f1432cf-f94c-5a45-995e-cdbf5db27b0b" version = "2.2.1" [[deps.Luxor]] deps = ["Base64", "Cairo", "Colors", "Dates", "FFMPEG", "FileIO", "Juno", "Random", "Requires", "Rsvg"] git-tree-sha1 = "aa804f92cf77298c86b26ef2487cc624b3dd4004" uuid = "ae8d54c2-7ccd-5906-9d76-62fc9837b5bc" version = "2.19.0" [[deps.METIS_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "1d31872bb9c5e7ec1f618e8c4a56c8b0d9bddc7e" uuid = "d00139f3-1899-568f-a2f0-47f597d42d70" version = "5.1.1+0" [[deps.MKL_jll]] deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"] git-tree-sha1 = "5455aef09b40e5020e1520f551fa3135040d4ed0" uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7" version = "2021.1.1+2" [[deps.MUMPS_seq_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "METIS_jll", "OpenBLAS32_jll", "Pkg"] git-tree-sha1 = "1a11a84b2af5feb5a62a820574804056cdc59c39" uuid = "d7ed1dd3-d0ae-5e8e-bfb4-87a502085b8d" version = "5.2.1+4" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.9" [[deps.Makie]] deps = ["Animations", "Base64", "ColorBrewer", "ColorSchemes", "ColorTypes", "Colors", "Contour", "Distributions", "DocStringExtensions", "FFMPEG", "FileIO", "FixedPointNumbers", "Formatting", "FreeType", "FreeTypeAbstraction", "GeometryBasics", "GridLayoutBase", "ImageIO", "IntervalSets", "Isoband", "KernelDensity", "LaTeXStrings", "LinearAlgebra", "MakieCore", "Markdown", "Match", "MathTeXEngine", "Observables", "Packing", "PlotUtils", "PolygonOps", "Printf", "Random", "RelocatableFolders", "Serialization", "Showoff", "SignedDistanceFields", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsFuns", "StructArrays", "UnicodeFun"] git-tree-sha1 = "56b0b7772676c499430dc8eb15cfab120c05a150" uuid = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" version = "0.15.3" [[deps.MakieCore]] deps = ["Observables"] git-tree-sha1 = "7bcc8323fb37523a6a51ade2234eee27a11114c8" uuid = "20f20a25-4f0e-4fdf-b5d1-57303727442b" version = "0.1.3" [[deps.MappedArrays]] git-tree-sha1 = "e8b359ef06ec72e8c030463fe02efe5527ee5142" uuid = "dbb5928d-eab1-5f90-85c2-b9b0edb7c900" version = "0.4.1" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.Match]] git-tree-sha1 = "1d9bc5c1a6e7ee24effb93f175c9342f9154d97f" uuid = "7eb4fadd-790c-5f42-8a69-bfa0b872bfbf" version = "1.2.0" [[deps.MathOptInterface]] deps = ["BenchmarkTools", "CodecBzip2", "CodecZlib", "JSON", "JSONSchema", "LinearAlgebra", "MutableArithmetics", "OrderedCollections", "SparseArrays", "Test", "Unicode"] git-tree-sha1 = "575644e3c05b258250bb599e57cf73bbf1062901" uuid = "b8f27783-ece8-5eb3-8dc8-9495eed66fee" version = "0.9.22" [[deps.MathProgBase]] deps = ["LinearAlgebra", "SparseArrays"] git-tree-sha1 = "9abbe463a1e9fc507f12a69e7f29346c2cdc472c" uuid = "fdba3010-5040-5b88-9595-932c9decdf73" version = "0.7.8" [[deps.MathTeXEngine]] deps = ["AbstractTrees", "Automa", "DataStructures", "FreeTypeAbstraction", "GeometryBasics", "LaTeXStrings", "REPL", "RelocatableFolders", "Test"] git-tree-sha1 = "70e733037bbf02d691e78f95171a1fa08cdc6332" uuid = "0a4f8689-d25c-4efe-a92b-7142dfc1aa53" version = "0.2.1" [[deps.MbedTLS]] deps = ["Dates", "MbedTLS_jll", "Random", "Sockets"] git-tree-sha1 = "1c38e51c3d08ef2278062ebceade0e46cefc96fe" uuid = "739be429-bea8-5141-9913-cc70e7f3736d" version = "1.0.3" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" [[deps.Measures]] git-tree-sha1 = "e498ddeee6f9fdb4551ce855a46f54dbd900245f" uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e" version = "0.3.1" [[deps.Media]] deps = ["MacroTools", "Test"] git-tree-sha1 = "75a54abd10709c01f1b86b84ec225d26e840ed58" uuid = "e89f7d12-3494-54d1-8411-f7d8b9ae1f27" version = "0.5.0" [[deps.MeshIO]] deps = ["ColorTypes", "FileIO", "GeometryBasics", "Printf"] git-tree-sha1 = "8be09d84a2d597c7c0c34d7d604c039c9763e48c" uuid = "7269a6da-0436-5bbc-96c2-40638cbb6118" version = "0.4.10" [[deps.MetaGraphs]] deps = ["Graphs", "JLD2", "Random"] git-tree-sha1 = "2af69ff3c024d13bde52b34a2a7d6887d4e7b438" uuid = "626554b9-1ddb-594c-aa3c-2596fe9399a5" version = "0.7.1" [[deps.Missings]] deps = ["DataAPI"] git-tree-sha1 = "bf210ce90b6c9eed32d25dbcae1ebc565df2687f" uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" version = "1.0.2" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.Mocking]] deps = ["Compat", "ExprTools"] git-tree-sha1 = "29714d0a7a8083bba8427a4fbfb00a540c681ce7" uuid = "78c3b35d-d492-501b-9361-3d52fe80e533" version = "0.7.3" [[deps.ModernGL]] deps = ["Libdl"] git-tree-sha1 = "344f8896e55541e30d5ccffcbf747c98ad57ca47" uuid = "66fc600b-dfda-50eb-8b99-91cfa97b1301" version = "1.1.4" [[deps.MosaicViews]] deps = ["MappedArrays", "OffsetArrays", "PaddedViews", "StackViews"] git-tree-sha1 = "b34e3bc3ca7c94914418637cb10cc4d1d80d877d" uuid = "e94cdb99-869f-56ef-bcf0-1ae2bcbe0389" version = "0.3.3" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" [[deps.MsgPack]] deps = ["Serialization"] git-tree-sha1 = "a8cbf066b54d793b9a48c5daa5d586cf2b5bd43d" uuid = "99f44e22-a591-53d1-9472-aa23ef4bd671" version = "1.1.0" [[deps.MutableArithmetics]] deps = ["LinearAlgebra", "SparseArrays", "Test"] git-tree-sha1 = "8d9496b2339095901106961f44718920732616bb" uuid = "d8a4904e-b15c-11e9-3269-09a3773c0cb0" version = "0.2.22" [[deps.NLSolversBase]] deps = ["DiffResults", "Distributed", "FiniteDiff", "ForwardDiff"] git-tree-sha1 = "50310f934e55e5ca3912fb941dec199b49ca9b68" uuid = "d41bc354-129a-5804-8e4c-c37616107c6c" version = "7.8.2" [[deps.NLopt]] deps = ["MathOptInterface", "MathProgBase", "NLopt_jll"] git-tree-sha1 = "d80cb3327d1aeef0f59eacf225e000f86e4eee0a" uuid = "76087f3c-5699-56af-9a33-bf431cd00edd" version = "0.6.3" [[deps.NLopt_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9b1f15a08f9d00cdb2761dcfa6f453f5d0d6f973" uuid = "079eb43e-fd8e-5478-9966-2cf3e3edb778" version = "2.7.1+0" [[deps.NaNMath]] git-tree-sha1 = "b086b7ea07f8e38cf122f5016af580881ac914fe" uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" version = "0.3.7" [[deps.NearestNeighbors]] deps = ["Distances", "StaticArrays"] git-tree-sha1 = "16baacfdc8758bc374882566c9187e785e85c2f0" uuid = "b8a86587-4115-5ab1-83bc-aa920d37bbce" version = "0.4.9" [[deps.Netpbm]] deps = ["FileIO", "ImageCore"] git-tree-sha1 = "18efc06f6ec36a8b801b23f076e3c6ac7c3bf153" uuid = "f09324ee-3d7c-5217-9330-fc30815ba969" version = "1.0.2" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" [[deps.Observables]] git-tree-sha1 = "fe29afdef3d0c4a8286128d4e45cc50621b1e43d" uuid = "510215fc-4207-5dde-b226-833fc4488ee2" version = "0.4.0" [[deps.OffsetArrays]] deps = ["Adapt"] git-tree-sha1 = "043017e0bdeff61cfbb7afeb558ab29536bbb5ed" uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881" version = "1.10.8" [[deps.Ogg_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "887579a3eb005446d514ab7aeac5d1d027658b8f" uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051" version = "1.3.5+1" [[deps.OpenBLAS32_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9c6c2ed4b7acd2137b878eb96c68e63b76199d0f" uuid = "656ef2d0-ae68-5445-9ca0-591084a874a2" version = "0.3.17+0" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" [[deps.OpenEXR]] deps = ["Colors", "FileIO", "OpenEXR_jll"] git-tree-sha1 = "327f53360fdb54df7ecd01e96ef1983536d1e633" uuid = "52e1d378-f018-4a11-a4be-720524705ac7" version = "0.3.2" [[deps.OpenEXR_jll]] deps = ["Artifacts", "Imath_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "923319661e9a22712f24596ce81c54fc0366f304" uuid = "18a262bb-aa17-5467-a713-aee519bc75cb" version = "3.1.1+0" [[deps.OpenLibm_jll]] deps = ["Artifacts", "Libdl"] uuid = "05823500-19ac-5b8b-9628-191a04bc5112" [[deps.OpenSSL_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "648107615c15d4e09f7eca16307bc821c1f718d8" uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" version = "1.1.13+0" [[deps.OpenSpecFun_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1" uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" version = "0.5.5+0" [[deps.OpticSim]] deps = ["CSV", "ColorSchemes", "ColorTypes", "Colors", "Conda", "DataFrames", "DelimitedFiles", "Distributions", "FileIO", "Format", "ForwardDiff", "GLMakie", "GeometryBasics", "HTTP", "ImageView", "Images", "InteractiveUtils", "Ipopt", "JSServe", "JuMP", "LazySets", "Libdl", "LinearAlgebra", "Luxor", "Makie", "MeshIO", "NLopt", "Optim", "PackageCompiler", "Pkg", "Plots", "Pluto", "PlutoUI", "Polynomials", "PyCall", "Random", "ReverseDiff", "Revise", "SHA", "StaticArrays", "Statistics", "StringEncodings", "Unitful", "WGLMakie", "ZipFile", "Zygote"] git-tree-sha1 = "92c4d80370ce21772bb041b333366bbf91495fbe" uuid = "24114763-4efb-45e7-af0e-cde916beb153" version = "0.5.3" [[deps.Optim]] deps = ["Compat", "FillArrays", "ForwardDiff", "LineSearches", "LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "PositiveFactorizations", "Printf", "SparseArrays", "StatsBase"] git-tree-sha1 = "045d10789f5daff18deb454d5923c6996017c2f3" uuid = "429524aa-4258-5aef-a3af-852621145aeb" version = "1.6.1" [[deps.Opus_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720" uuid = "91d4177d-7536-5919-b921-800302f37372" version = "1.3.2+0" [[deps.OrderedCollections]] git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c" uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" version = "1.4.1" [[deps.PCRE_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b2a7af664e098055a7529ad1a900ded962bca488" uuid = "2f80f16e-611a-54ab-bc61-aa92de5b98fc" version = "8.44.0+0" [[deps.PDMats]] deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"] git-tree-sha1 = "7e2166042d1698b6072352c74cfd1fca2a968253" uuid = "90014a1f-27ba-587c-ab20-58faa44d9150" version = "0.11.6" [[deps.PNGFiles]] deps = ["Base64", "CEnum", "ImageCore", "IndirectArrays", "OffsetArrays", "libpng_jll"] git-tree-sha1 = "eb4dbb8139f6125471aa3da98fb70f02dc58e49c" uuid = "f57f5aa1-a3ce-4bc8-8ab9-96f992907883" version = "0.3.14" [[deps.PackageCompiler]] deps = ["Artifacts", "LazyArtifacts", "Libdl", "Pkg", "Printf", "RelocatableFolders", "UUIDs"] git-tree-sha1 = "4ad92047603f8e955503f92767577b32508c39af" uuid = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d" version = "2.0.5" [[deps.Packing]] deps = ["GeometryBasics"] git-tree-sha1 = "1155f6f937fa2b94104162f01fa400e192e4272f" uuid = "19eb6ba3-879d-56ad-ad62-d5c202156566" version = "0.4.2" [[deps.PaddedViews]] deps = ["OffsetArrays"] git-tree-sha1 = "03a7a85b76381a3d04c7a1656039197e70eda03d" uuid = "5432bcbf-9aad-5242-b902-cca2824c8663" version = "0.5.11" [[deps.Pango_jll]] deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "3a121dfbba67c94a5bec9dde613c3d0cbcf3a12b" uuid = "36c8627f-9965-5494-a995-c6b170f724f3" version = "1.50.3+0" [[deps.Parameters]] deps = ["OrderedCollections", "UnPack"] git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe" uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a" version = "0.12.3" [[deps.Parsers]] deps = ["Dates"] git-tree-sha1 = "13468f237353112a01b2d6b32f3d0f80219944aa" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.2.2" [[deps.Pixman_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b4f5d02549a10e20780a24fce72bea96b6329e29" uuid = "30392449-352a-5448-841d-b1acce4e97dc" version = "0.40.1+0" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" [[deps.PkgVersion]] deps = ["Pkg"] git-tree-sha1 = "a7a7e1a88853564e551e4eba8650f8c38df79b37" uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688" version = "0.1.1" [[deps.PlotThemes]] deps = ["PlotUtils", "Requires", "Statistics"] git-tree-sha1 = "a3a964ce9dc7898193536002a6dd892b1b5a6f1d" uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a" version = "2.0.1" [[deps.PlotUtils]] deps = ["ColorSchemes", "Colors", "Dates", "Printf", "Random", "Reexport", "Statistics"] git-tree-sha1 = "6f1b25e8ea06279b5689263cc538f51331d7ca17" uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043" version = "1.1.3" [[deps.Plots]] deps = ["Base64", "Contour", "Dates", "Downloads", "FFMPEG", "FixedPointNumbers", "GR", "GeometryBasics", "JSON", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "PlotThemes", "PlotUtils", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "UUIDs", "UnicodeFun", "Unzip"] git-tree-sha1 = "5c907bdee5966a9adb8a106807b7c387e51e4d6c" uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" version = "1.25.11" [[deps.Pluto]] deps = ["Base64", "Configurations", "Dates", "Distributed", "FileWatching", "FuzzyCompletions", "HTTP", "InteractiveUtils", "Logging", "Markdown", "MsgPack", "Pkg", "REPL", "Sockets", "Tables", "UUIDs"] git-tree-sha1 = "7f99cb352c944ad28e3212ea9d887868c80e3d03" uuid = "c3e4b0f8-55cb-11ea-2926-15256bba5781" version = "0.17.7" [[deps.PlutoUI]] deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"] git-tree-sha1 = "85bf3e4bd279e405f91489ce518dedb1e32119cb" uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8" version = "0.7.35" [[deps.PolygonOps]] git-tree-sha1 = "77b3d3605fc1cd0b42d95eba87dfcd2bf67d5ff6" uuid = "647866c9-e3ac-4575-94e7-e3d426903924" version = "0.1.2" [[deps.Polynomials]] deps = ["Intervals", "LinearAlgebra", "MutableArithmetics", "RecipesBase"] git-tree-sha1 = "7499556d31417baeabaa55d266a449ffe4ec5a3e" uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45" version = "2.0.17" [[deps.PooledArrays]] deps = ["DataAPI", "Future"] git-tree-sha1 = "db3a23166af8aebf4db5ef87ac5b00d36eb771e2" uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" version = "1.4.0" [[deps.PositiveFactorizations]] deps = ["LinearAlgebra"] git-tree-sha1 = "17275485f373e6673f7e7f97051f703ed5b15b20" uuid = "85a6dd25-e78a-55b7-8502-1745935b8125" version = "0.2.4" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "de893592a221142f3db370f48290e3a2ef39998f" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.2.4" [[deps.PrettyTables]] deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"] git-tree-sha1 = "dfb54c4e414caa595a1f2ed759b160f5a3ddcba5" uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" version = "1.3.1" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.Profile]] deps = ["Printf"] uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79" [[deps.ProgressMeter]] deps = ["Distributed", "Printf"] git-tree-sha1 = "afadeba63d90ff223a6a48d2009434ecee2ec9e8" uuid = "92933f4c-e287-5a05-a399-4b506db050ca" version = "1.7.1" [[deps.PyCall]] deps = ["Conda", "Dates", "Libdl", "LinearAlgebra", "MacroTools", "Serialization", "VersionParsing"] git-tree-sha1 = "71fd4022ecd0c6d20180e23ff1b3e05a143959c2" uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0" version = "1.93.0" [[deps.Qt5Base_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "xkbcommon_jll"] git-tree-sha1 = "ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8" uuid = "ea2cea3b-5b76-57ae-a6ef-0a8af62496e1" version = "5.15.3+0" [[deps.QuadGK]] deps = ["DataStructures", "LinearAlgebra"] git-tree-sha1 = "78aadffb3efd2155af139781b8a8df1ef279ea39" uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc" version = "2.4.2" [[deps.Quaternions]] deps = ["DualNumbers", "LinearAlgebra", "Random"] git-tree-sha1 = "09eea2ccdfd03257d0a4977729613cee37935a8e" uuid = "94ee1d12-ae83-5a48-8b1c-48b8ff168ae0" version = "0.5.0" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA", "Serialization"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.RangeArrays]] git-tree-sha1 = "b9039e93773ddcfc828f12aadf7115b4b4d225f5" uuid = "b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d" version = "0.3.2" [[deps.Ratios]] deps = ["Requires"] git-tree-sha1 = "01d341f502250e81f6fec0afe662aa861392a3aa" uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439" version = "0.4.2" [[deps.Reactive]] deps = ["DataStructures", "Distributed", "Test"] git-tree-sha1 = "5862d915387ebb954016f50a88e34f79a9e5fcd2" uuid = "a223df75-4e93-5b7c-acf9-bdd599c0f4de" version = "0.8.3" [[deps.RealDot]] deps = ["LinearAlgebra"] git-tree-sha1 = "9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9" uuid = "c1ae055f-0cd5-4b69-90a6-9a35b1a98df9" version = "0.1.0" [[deps.RecipesBase]] git-tree-sha1 = "6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d" uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" version = "1.2.1" [[deps.RecipesPipeline]] deps = ["Dates", "NaNMath", "PlotUtils", "RecipesBase"] git-tree-sha1 = "995a812c6f7edea7527bb570f0ac39d0fb15663c" uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c" version = "0.5.1" [[deps.Reexport]] git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.2.2" [[deps.RegionTrees]] deps = ["IterTools", "LinearAlgebra", "StaticArrays"] git-tree-sha1 = "4618ed0da7a251c7f92e869ae1a19c74a7d2a7f9" uuid = "dee08c22-ab7f-5625-9660-a9af2021b33f" version = "0.3.2" [[deps.RelocatableFolders]] deps = ["SHA", "Scratch"] git-tree-sha1 = "cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca" uuid = "05181044-ff0b-4ac5-8273-598c1e38db00" version = "0.1.3" [[deps.Requires]] deps = ["UUIDs"] git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.3.0" [[deps.ReverseDiff]] deps = ["ChainRulesCore", "DiffResults", "DiffRules", "ForwardDiff", "FunctionWrappers", "LinearAlgebra", "LogExpFunctions", "MacroTools", "NaNMath", "Random", "SpecialFunctions", "StaticArrays", "Statistics"] git-tree-sha1 = "8d85c98fc33d4d37d88c8f9ccee4f1f3f98e56f4" uuid = "37e2e3b7-166d-5795-8a7a-e32c996b4267" version = "1.12.0" [[deps.Revise]] deps = ["CodeTracking", "Distributed", "FileWatching", "JuliaInterpreter", "LibGit2", "LoweredCodeUtils", "OrderedCollections", "Pkg", "REPL", "Requires", "UUIDs", "Unicode"] git-tree-sha1 = "606ddc4d3d098447a09c9337864c73d017476424" uuid = "295af30f-e4ad-537b-8983-00126c2a3abe" version = "3.3.2" [[deps.Rmath]] deps = ["Random", "Rmath_jll"] git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f" uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa" version = "0.7.0" [[deps.Rmath_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7" uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f" version = "0.3.0+0" [[deps.Rotations]] deps = ["LinearAlgebra", "Quaternions", "Random", "StaticArrays", "Statistics"] git-tree-sha1 = "a167638e2cbd8ac41f9cd57282cab9b042fa26e6" uuid = "6038ab10-8711-5258-84ad-4b1120ba62dc" version = "1.3.0" [[deps.RoundingEmulator]] git-tree-sha1 = "40b9edad2e5287e05bd413a38f61a8ff55b9557b" uuid = "5eaf0fd0-dfba-4ccb-bf02-d820a40db705" version = "0.2.1" [[deps.RoundingIntegers]] git-tree-sha1 = "99acd97f396ea71a5be06ba6de5c9defe188a778" uuid = "d5f540fe-1c90-5db3-b776-2e2f362d9394" version = "1.1.0" [[deps.Rsvg]] deps = ["Cairo", "Glib_jll", "Librsvg_jll"] git-tree-sha1 = "3d3dc66eb46568fb3a5259034bfc752a0eb0c686" uuid = "c4c386cf-5103-5370-be45-f3a111cca3b8" version = "1.0.0" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" [[deps.SIMD]] git-tree-sha1 = "39e3df417a0dd0c4e1f89891a281f82f5373ea3b" uuid = "fdea26ae-647d-5447-a871-4b548cad5224" version = "3.4.0" [[deps.ScanByte]] deps = ["Libdl", "SIMD"] git-tree-sha1 = "9cc2955f2a254b18be655a4ee70bc4031b2b189e" uuid = "7b38b023-a4d7-4c5e-8d43-3f3097f304eb" version = "0.3.0" [[deps.Scratch]] deps = ["Dates"] git-tree-sha1 = "0b4b7f1393cff97c33891da2a0bf69c6ed241fda" uuid = "6c6a2e73-6563-6170-7368-637461726353" version = "1.1.0" [[deps.SentinelArrays]] deps = ["Dates", "Random"] git-tree-sha1 = "6a2f7d70512d205ca8c7ee31bfa9f142fe74310c" uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" version = "1.3.12" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.SetRounding]] git-tree-sha1 = "d7a25e439d07a17b7cdf97eecee504c50fedf5f6" uuid = "3cc68bcd-71a2-5612-b932-767ffbe40ab0" version = "0.2.1" [[deps.ShaderAbstractions]] deps = ["ColorTypes", "FixedPointNumbers", "GeometryBasics", "LinearAlgebra", "Observables", "StaticArrays", "StructArrays", "Tables"] git-tree-sha1 = "0d97c895406b552bed78f3a1fe9925248e908ae2" uuid = "65257c39-d410-5151-9873-9b3e5be5013e" version = "0.2.8" [[deps.SharedArrays]] deps = ["Distributed", "Mmap", "Random", "Serialization"] uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [[deps.Showoff]] deps = ["Dates", "Grisu"] git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de" uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f" version = "1.0.3" [[deps.SignedDistanceFields]] deps = ["Random", "Statistics", "Test"] git-tree-sha1 = "d263a08ec505853a5ff1c1ebde2070419e3f28e9" uuid = "73760f76-fbc4-59ce-8f25-708e95d2df96" version = "0.4.0" [[deps.SimpleTraits]] deps = ["InteractiveUtils", "MacroTools"] git-tree-sha1 = "5d7e3f4e11935503d3ecaf7186eac40602e7d231" uuid = "699a6c99-e7fa-54fc-8d76-47d257e15c1d" version = "0.9.4" [[deps.SimpleWeightedGraphs]] deps = ["Graphs", "LinearAlgebra", "Markdown", "SparseArrays", "Test"] git-tree-sha1 = "a6f404cc44d3d3b28c793ec0eb59af709d827e4e" uuid = "47aef6b3-ad0c-573a-a1e2-d07658019622" version = "1.2.1" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SortingAlgorithms]] deps = ["DataStructures"] git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508" uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" version = "1.0.1" [[deps.SparseArrays]] deps = ["LinearAlgebra", "Random"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [[deps.SpecialFunctions]] deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"] git-tree-sha1 = "85e5b185ed647b8ee89aa25a7788a2b43aa8a74f" uuid = "276daf66-3868-5448-9aa4-cd146d93841b" version = "2.1.3" [[deps.StackViews]] deps = ["OffsetArrays"] git-tree-sha1 = "46e589465204cd0c08b4bd97385e4fa79a0c770c" uuid = "cae243ae-269e-4f55-b966-ac2d0dc13c15" version = "0.1.1" [[deps.Static]] deps = ["IfElse"] git-tree-sha1 = "00b725fffc9a7e9aac8850e4ed75b4c1acbe8cd2" uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3" version = "0.5.5" [[deps.StaticArrays]] deps = ["LinearAlgebra", "Random", "Statistics"] git-tree-sha1 = "6354dfaf95d398a1a70e0b28238321d5d17b2530" uuid = "90137ffa-7385-5640-81b9-e52037218182" version = "1.4.0" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [[deps.StatsAPI]] deps = ["LinearAlgebra"] git-tree-sha1 = "c3d8ba7f3fa0625b062b82853a7d5229cb728b6b" uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" version = "1.2.1" [[deps.StatsBase]] deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] git-tree-sha1 = "8977b17906b0a1cc74ab2e3a05faa16cf08a8291" uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" version = "0.33.16" [[deps.StatsFuns]] deps = ["ChainRulesCore", "HypergeometricFunctions", "InverseFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"] git-tree-sha1 = "25405d7016a47cf2bd6cd91e66f4de437fd54a07" uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c" version = "0.9.16" [[deps.StringEncodings]] deps = ["Libiconv_jll"] git-tree-sha1 = "50ccd5ddb00d19392577902f0079267a72c5ab04" uuid = "69024149-9ee7-55f6-a4c4-859efe599b68" version = "0.3.5" [[deps.StructArrays]] deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"] git-tree-sha1 = "57617b34fa34f91d536eb265df67c2d4519b8b98" uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a" version = "0.6.5" [[deps.StructTypes]] deps = ["Dates", "UUIDs"] git-tree-sha1 = "d24a825a95a6d98c385001212dc9020d609f2d4f" uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" version = "1.8.1" [[deps.SuiteSparse]] deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"] uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" [[deps.TableTraits]] deps = ["IteratorInterfaceExtensions"] git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" version = "1.0.1" [[deps.Tables]] deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"] git-tree-sha1 = "bb1064c9a84c52e277f1096cf41434b675cd368b" uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" version = "1.6.1" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" [[deps.TensorCore]] deps = ["LinearAlgebra"] git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" version = "0.1.1" [[deps.Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[deps.TiffImages]] deps = ["ColorTypes", "DataStructures", "DocStringExtensions", "FileIO", "FixedPointNumbers", "IndirectArrays", "Inflate", "OffsetArrays", "PkgVersion", "ProgressMeter", "UUIDs"] git-tree-sha1 = "991d34bbff0d9125d93ba15887d6594e8e84b305" uuid = "731e570b-9d59-4bfa-96dc-6df516fadf69" version = "0.5.3" [[deps.TiledIteration]] deps = ["OffsetArrays"] git-tree-sha1 = "5683455224ba92ef59db72d10690690f4a8dc297" uuid = "06e1c1a7-607b-532d-9fad-de7d9aa2abac" version = "0.3.1" [[deps.TimeZones]] deps = ["Dates", "Downloads", "InlineStrings", "LazyArtifacts", "Mocking", "Printf", "RecipesBase", "Serialization", "Unicode"] git-tree-sha1 = "0f1017f68dc25f1a0cb99f4988f78fe4f2e7955f" uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53" version = "1.7.1" [[deps.TranscodingStreams]] deps = ["Random", "Test"] git-tree-sha1 = "216b95ea110b5972db65aa90f88d8d89dcb8851c" uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" version = "0.9.6" [[deps.URIs]] git-tree-sha1 = "97bbe755a53fe859669cd907f2d96aee8d2c1355" uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" version = "1.3.0" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.UnPack]] git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b" uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed" version = "1.0.2" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.UnicodeFun]] deps = ["REPL"] git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf" uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1" version = "0.4.1" [[deps.Unitful]] deps = ["ConstructionBase", "Dates", "LinearAlgebra", "Random"] git-tree-sha1 = "b649200e887a487468b71821e2644382699f1b0f" uuid = "1986cc42-f94f-5a68-af5c-568840ba703d" version = "1.11.0" [[deps.Unzip]] git-tree-sha1 = "34db80951901073501137bdbc3d5a8e7bbd06670" uuid = "41fe7b60-77ed-43a1-b4f0-825fd5a5650d" version = "0.1.2" [[deps.VersionParsing]] git-tree-sha1 = "58d6e80b4ee071f5efd07fda82cb9fbe17200868" uuid = "81def892-9a0e-5fdd-b105-ffc91e053289" version = "1.3.0" [[deps.WGLMakie]] deps = ["Colors", "FileIO", "FreeTypeAbstraction", "GeometryBasics", "Hyperscript", "ImageMagick", "JSServe", "LinearAlgebra", "Makie", "Observables", "ShaderAbstractions", "StaticArrays"] git-tree-sha1 = "716e15ba27090a96c2f3afc16a464c9a280089cd" uuid = "276b4fcb-3e11-5398-bf8b-a0c2d153d008" version = "0.4.7" [[deps.Wayland_jll]] deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg", "XML2_jll"] git-tree-sha1 = "3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23" uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89" version = "1.19.0+0" [[deps.Wayland_protocols_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4528479aa01ee1b3b4cd0e6faef0e04cf16466da" uuid = "2381bf8a-dfd0-557d-9999-79630e7b1b91" version = "1.25.0+0" [[deps.WeakRefStrings]] deps = ["DataAPI", "InlineStrings", "Parsers"] git-tree-sha1 = "c69f9da3ff2f4f02e811c3323c22e5dfcb584cfa" uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5" version = "1.4.1" [[deps.WebSockets]] deps = ["Base64", "Dates", "HTTP", "Logging", "Sockets"] git-tree-sha1 = "f91a602e25fe6b89afc93cf02a4ae18ee9384ce3" uuid = "104b5d7c-a370-577a-8038-80a2059c5097" version = "1.5.9" [[deps.WidgetsBase]] deps = ["Observables"] git-tree-sha1 = "c1ef6e02bc457c3b23aafc765b94c3dcd25f174d" uuid = "eead4739-05f7-45a1-878c-cee36b57321c" version = "0.1.3" [[deps.WoodburyMatrices]] deps = ["LinearAlgebra", "SparseArrays"] git-tree-sha1 = "de67fa59e33ad156a590055375a30b23c40299d3" uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6" version = "0.5.5" [[deps.XML2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a" uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a" version = "2.9.12+0" [[deps.XSLT_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"] git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a" uuid = "aed1982a-8fda-507f-9586-7b0439959a61" version = "1.1.34+0" [[deps.Xorg_libX11_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"] git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527" uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc" version = "1.6.9+4" [[deps.Xorg_libXau_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e" uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec" version = "1.0.9+4" [[deps.Xorg_libXcomposite_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll"] git-tree-sha1 = "7c688ca9c957837539bbe1c53629bb871025e423" uuid = "3c9796d7-64a0-5134-86ad-79f8eb684845" version = "0.4.5+4" [[deps.Xorg_libXcursor_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"] git-tree-sha1 = "12e0eb3bc634fa2080c1c37fccf56f7c22989afd" uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724" version = "1.2.0+4" [[deps.Xorg_libXdamage_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll"] git-tree-sha1 = "fe4ffb2024ba3eddc862c6e1d70e2b070cd1c2bf" uuid = "0aeada51-83db-5f97-b67e-184615cfc6f6" version = "1.1.5+4" [[deps.Xorg_libXdmcp_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4" uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05" version = "1.1.3+4" [[deps.Xorg_libXext_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3" uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3" version = "1.3.4+4" [[deps.Xorg_libXfixes_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "0e0dc7431e7a0587559f9294aeec269471c991a4" uuid = "d091e8ba-531a-589c-9de9-94069b037ed8" version = "5.0.3+4" [[deps.Xorg_libXi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll"] git-tree-sha1 = "89b52bc2160aadc84d707093930ef0bffa641246" uuid = "a51aa0fd-4e3c-5386-b890-e753decda492" version = "1.7.10+4" [[deps.Xorg_libXinerama_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll"] git-tree-sha1 = "26be8b1c342929259317d8b9f7b53bf2bb73b123" uuid = "d1454406-59df-5ea1-beac-c340f2130bc3" version = "1.1.4+4" [[deps.Xorg_libXrandr_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll"] git-tree-sha1 = "34cea83cb726fb58f325887bf0612c6b3fb17631" uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484" version = "1.5.2+4" [[deps.Xorg_libXrender_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96" uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa" version = "0.9.10+4" [[deps.Xorg_libXtst_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll"] git-tree-sha1 = "0c0a60851f44add2a64069ddf213e941c30ed93c" uuid = "b6f176f1-7aea-5357-ad67-1d3e565ea1c6" version = "1.2.3+4" [[deps.Xorg_libpthread_stubs_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb" uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74" version = "0.1.0+3" [[deps.Xorg_libxcb_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"] git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6" uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b" version = "1.13.0+3" [[deps.Xorg_libxkbfile_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "926af861744212db0eb001d9e40b5d16292080b2" uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a" version = "1.1.0+4" [[deps.Xorg_xcb_util_image_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "0fab0a40349ba1cba2c1da699243396ff8e94b97" uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b" version = "0.4.0+1" [[deps.Xorg_xcb_util_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll"] git-tree-sha1 = "e7fd7b2881fa2eaa72717420894d3938177862d1" uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5" version = "0.4.0+1" [[deps.Xorg_xcb_util_keysyms_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "d1151e2c45a544f32441a567d1690e701ec89b00" uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7" version = "0.4.0+1" [[deps.Xorg_xcb_util_renderutil_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "dfd7a8f38d4613b6a575253b3174dd991ca6183e" uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e" version = "0.3.9+1" [[deps.Xorg_xcb_util_wm_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "e78d10aab01a4a154142c5006ed44fd9e8e31b67" uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361" version = "0.4.1+1" [[deps.Xorg_xkbcomp_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxkbfile_jll"] git-tree-sha1 = "4bcbf660f6c2e714f87e960a171b119d06ee163b" uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4" version = "1.4.2+4" [[deps.Xorg_xkeyboard_config_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xkbcomp_jll"] git-tree-sha1 = "5c8424f8a67c3f2209646d4425f3d415fee5931d" uuid = "33bec58e-1273-512f-9401-5d533626f822" version = "2.27.0+4" [[deps.Xorg_xtrans_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845" uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10" version = "1.4.0+3" [[deps.ZipFile]] deps = ["Libdl", "Printf", "Zlib_jll"] git-tree-sha1 = "3593e69e469d2111389a9bd06bac1f3d730ac6de" uuid = "a5390f91-8eb1-5f08-bee0-b1d1ffed6cea" version = "0.9.4" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" [[deps.Zstd_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "e45044cd873ded54b6a5bac0eb5c971392cf1927" uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" version = "1.5.2+0" [[deps.Zygote]] deps = ["AbstractFFTs", "ChainRules", "ChainRulesCore", "DiffRules", "Distributed", "FillArrays", "ForwardDiff", "IRTools", "InteractiveUtils", "LinearAlgebra", "MacroTools", "NaNMath", "Random", "Requires", "SparseArrays", "SpecialFunctions", "Statistics", "ZygoteRules"] git-tree-sha1 = "93285d2877f1f1b09b2a2b029f90e9db10127022" uuid = "e88e6eb3-aa80-5325-afca-941959d7151f" version = "0.6.35" [[deps.ZygoteRules]] deps = ["MacroTools"] git-tree-sha1 = "8c1a8e4dfacb1fd631745552c8db35d0deb09ea0" uuid = "700de1a5-db45-46bc-99cf-38207098b444" version = "0.2.2" [[deps.adwaita_icon_theme_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "hicolor_icon_theme_jll"] git-tree-sha1 = "37c9a36ccb876e02876c8a654f1b2e8c1b443a78" uuid = "b437f822-2cd6-5e08-a15c-8bac984d38ee" version = "3.33.92+5" [[deps.at_spi2_atk_jll]] deps = ["ATK_jll", "Artifacts", "JLLWrappers", "Libdl", "Pkg", "XML2_jll", "Xorg_libX11_jll", "at_spi2_core_jll"] git-tree-sha1 = "f16ae690aca4761f33d2cb338ee9899e541f5eae" uuid = "de012916-1e3f-58c2-8f29-df3ef51d412d" version = "2.34.1+4" [[deps.at_spi2_core_jll]] deps = ["Artifacts", "Dbus_jll", "Glib_jll", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXtst_jll"] git-tree-sha1 = "d2d540cd145f2b2933614649c029d222fe125188" uuid = "0fc3237b-ac94-5853-b45c-d43d59a06200" version = "2.34.0+4" [[deps.gdk_pixbuf_jll]] deps = ["Artifacts", "Glib_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pkg", "Xorg_libX11_jll", "libpng_jll"] git-tree-sha1 = "c23323cd30d60941f8c68419a70905d9bdd92808" uuid = "da03df04-f53b-5353-a52f-6a8b0620ced0" version = "2.42.6+1" [[deps.hicolor_icon_theme_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b458a6f6fc2b1a8ca74ed63852e4eaf43fb9f5ea" uuid = "059c91fe-1bad-52ad-bddd-f7b78713c282" version = "0.17.0+3" [[deps.iso_codes_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "5ee24c3ae30e006117ec2da5ea50f2ce457c019a" uuid = "bf975903-5238-5d20-8243-bc370bc1e7e5" version = "4.3.0+4" [[deps.isoband_jll]] deps = ["Libdl", "Pkg"] git-tree-sha1 = "a1ac99674715995a536bbce674b068ec1b7d893d" uuid = "9a68df92-36a6-505f-a73e-abb412b6bfb4" version = "0.2.2+0" [[deps.libass_jll]] deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "5982a94fcba20f02f42ace44b9894ee2b140fe47" uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0" version = "0.15.1+0" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl", "OpenBLAS_jll"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" [[deps.libfdk_aac_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55" uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280" version = "2.0.2+0" [[deps.libpng_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c" uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f" version = "1.6.38+0" [[deps.libvorbis_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"] git-tree-sha1 = "b910cb81ef3fe6e78bf6acee440bda86fd6ae00c" uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a" version = "1.3.7+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" [[deps.x264_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2" uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a" version = "2021.5.5+0" [[deps.x265_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9" uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76" version = "3.5.0+0" [[deps.xkbcommon_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll", "Wayland_protocols_jll", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"] git-tree-sha1 = "ece2350174195bb31de1a63bea3a41ae1aa593b6" uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd" version = "0.9.1+5" """ # ╔═╡ Cell order: # ╟─576fb1c0-8ba3-11eb-1c10-fdb51172e2c9 # ╟─5cc45e60-8c1f-11eb-3e4a-17c26a3214f6 # ╟─aa47f750-8c1f-11eb-21d7-d3a969fb1f6d # ╠═8ba2f700-8c1f-11eb-209f-b76b9713b576 # ╟─5f77cfd0-8854-11eb-377c-ef975f9abf63 # ╠═3f2e9c20-974c-11eb-3e97-757b3e0255f4 # ╠═d6c83680-879e-11eb-31d4-7dbda7e93e48 # ╟─68e9b210-87ad-11eb-0f3a-5bb2dbf7d86c # ╟─3a5d3ba0-87ae-11eb-1717-93be0b802cab # ╟─96e423a0-885a-11eb-02a3-8704e8dbdab6 # ╟─00000000-0000-0000-0000-000000000001 # ╟─00000000-0000-0000-0000-000000000002
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
94864
### A Pluto.jl notebook ### # v0.18.0 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═╡ 67c8fac0-974e-11eb-2898-d14b79387954 begin init_notebook = true using OpticSim, OpticSim.Geometry, OpticSim.Emitters import OpticSim.NotebooksUtils as NB NB.InitNotebook() end # ╔═╡ a891a210-87bc-11eb-311d-4d020986fe19 begin using DataFrames # defining the optical system sys = AxisymmetricOpticalSystem( DataFrame(SurfaceType = ["Object", "Standard", "Standard", "Standard", "Stop", "Standard", "Standard", "Image"], Radius = [Inf, 26.777, 66.604, -35.571, 35.571, 35.571, -26.777, Inf], Thickness = [Inf, 4.0, 2.0, 4.0, 2.0, 4.0, 44.748, missing], Material = [OpticSim.GlassCat.Air, OpticSim.Examples.Examples_N_SK16, OpticSim.GlassCat.Air, OpticSim.Examples.Examples_N_SF2, OpticSim.GlassCat.Air, OpticSim.Examples.Examples_N_SK16, OpticSim.GlassCat.Air, missing], SemiDiameter = [Inf, 8.580, 7.513, 7.054, 6.033, 7.003, 7.506, 15.0])) @show sys end # ╔═╡ d6c83680-879e-11eb-31d4-7dbda7e93e48 begin init_notebook import PlutoUI using Makie defs = OpticSim.NotebooksUtils.Defs("ran") NB.DefsClearHTML(defs) # this function is needed to allow the visualization scene to be displayed inside a pluto notebook function Makie.display(obj) # @info "RG: $obj" return obj end #text of this cell to appear in the notebook NB.DefsAddHTML(defs, NB.HTMLFromObj(md"Basic Initialization (code)")) PlutoUI.Show(MIME"text/html"(), NB.DefsHTML(defs)) end # ╔═╡ 6ce01760-879e-11eb-2b13-4d3d07c4b4ce md"# Introductions To Emitters" # ╔═╡ 87954830-8854-11eb-2baf-d3b79b804e07 md"## Basic Emitters" # ╔═╡ 9608ed90-8854-11eb-080d-4d1f60d596f5 md""" Emitters are defined by Pixels and Spatial Layouts. An emitter has a spectrum, and an optical power distribution over the hemisphere. These are intrinsic physical properties of the emitter. The **basic emitter** is constructed as a combination of 4 basic elements and a 3D transform. The basic elements include: - Spectrum - Angular Power Distribution - Rays Origins Distribution - Rays Directions Distribution The OpticSim package comes with various implementations of each of these basic elements: - Spectrum - the **generate** interface returns a tuple (power, wavelength) * **Uniform** - A flat spectrum bounded (default: from 450nm to 680nm). the range is sampled uniformly. * **DeltaFunction** - Constant wave length. * **Measured** - measured spectrum to compute emitter power and wavelength (created by reading CSV files – more details will follow). - Angular Power Distribution - the interface **apply** returns an OpticalRay with modified power * **Lambertian** * **Cosine** * **Gaussian** - Rays Origins Distribution - the interface **length** returns the number of samples, and **generate** returns the n'th sample. * **Point** - a single point * **RectUniform** - a uniformly sampled rectangle with user defined number of samples * **RectGrid** - a rectangle sampled in a grid fashion * **Hexapolar** - a circle (or an ellipse) sampled in an hexapolar fasion (rings) - Rays Directions Distribution - the interface **length** returns the number of samples, and **generate** returns the n'th sample. * **Constant** * **RectGrid** * **UniformCone** * **HexapolarCone** """ # ╔═╡ d970a5b0-8858-11eb-1425-cdfb68e222ba md"### Examples of basic emitters" # ╔═╡ f21787a0-8858-11eb-19b1-914e835922eb md"#### Point Origin Samples" # ╔═╡ 5efca830-885b-11eb-3f76-3d9ac33369d8 md"#### Rectangle and Ellipse Origins samples" # ╔═╡ 4d265a60-885c-11eb-2b6d-7b244ccfd172 md"#### Angular Power Distribution" # ╔═╡ 4553fb50-88d7-11eb-3fc3-6ddfeb3f1910 md"In the following drawings, the length of the sampled rays is relative to its power." # ╔═╡ fd3287f0-885f-11eb-279d-990c4222ba83 md"## Composite Emitters" # ╔═╡ 03fc33b0-8860-11eb-2a20-0f8c2b1f79a3 md""" **Composite Emitters** are emitters that can hold a list of basic emitters or composite ones. Composite emitters allow you to combine multiple basic emitters, such as an R, G and B emitters in to a Pixel emitter, which then can be combined in to a "Display" composite emitters. The Transform data structure allow the user to define the geometric arrangment of the composited elements. """ # ╔═╡ 94bffc60-8860-11eb-37ca-b3203b46693a md"### Display example" # ╔═╡ b39c3952-8860-11eb-13a4-0b5004282a09 begin # construct the emitter's basic components local S = Spectrum.Uniform() local P = AngularPower.Lambertian() local O = Origins.RectGrid(1.0, 1.0, 3, 3) local D = Directions.HexapolarCone(deg2rad(5.0), 3) # construct the source. in this example a "pixel" source will contain only one source as we are simulating a "b/w" display. # for RGB displays we can combine 3 sources to simulate "a pixel". local Tr = Transform(Geometry.Vec3(0.5, 0.5, 0.0)) local source1 = Sources.Source(Tr, S, O, D, P) # create a list of pixels - each one is a composite source local pixels = Vector{Sources.CompositeSource{Float64}}(undef, 0) for y in 1:10 # image_height for x in 1:10 # image_width # pixel position relative to the display's origin local pixel_position = Geometry.Vec3((x-1) * 1.1, (y-1) * 1.5, 0.0) local Tr = Transform(pixel_position) # constructing the "pixel" pixel = Sources.CompositeSource(Tr, [source1]) push!(pixels, pixel) end end local Tr = Transform(Geometry.Vec3(0.0, 0.0, 0.0)) my_display = Sources.CompositeSource(Tr, pixels) md"###### CONSTRUCTION CODE: Display is composed $(length(pixels)) pixels, esch one generating $(length(pixels[1])) rays, resulting in $(length(my_display)) total." end # ╔═╡ 04d97450-8860-11eb-2bda-036792395ee4 md"----" # ╔═╡ 0b6553c2-8860-11eb-0c5e-89632a8dd612 md"## Cooke Triplet Example" # ╔═╡ 5f77cfd0-8854-11eb-377c-ef975f9abf63 md"## Initialization Stuff - Can be ignored" # ╔═╡ 68e9b210-87ad-11eb-0f3a-5bb2dbf7d86c begin NB.DefsClearHTML(defs) default_resolution_info = NB.GetVarInfo( @bind default_resolution PlutoUI.Select(["Small", "Medium", "Large"], default="Medium") ) makie_backend_info = NB.GetVarInfo( @bind makie_backend PlutoUI.Select(["Static", "Web"], default="Static") ) show_toc_info = NB.GetVarInfo( @bind show_toc PlutoUI.CheckBox(default=true) ) fb3_items = [ "Options", "@ Drawings Size $(default_resolution_info.html)", "Document Options", "@ $(show_toc_info.html) Show Table Of Content", "@ Makie Backend $(makie_backend_info.html) <i><b>(Leave as Static for now)</b></i>", ] NB.DefsAddHTML(defs, NB.HTMLFloatingBox( fb3_items, name="plutoui-docmenu", header="Document Menu", width="25%", top="45%", ) ) # wide document layout NB.DefsAddHTML(defs, NB.HTMLNewDocLayout()) # add TOC NB.DefsAddHTML(defs, NB.HTMLFromObj( PlutoUI.TableOfContents(title = "Document Table of Content", depth = 4) )* NB.HTMLFixTOC() ) #text of this cell to appear in the notebook NB.DefsAddHTML(defs, NB.HTMLFromObj(md"Define Floating Menu, TOC and New Layout (code)")) PlutoUI.Show(MIME"text/html"(), NB.DefsHTML(defs)) end # ╔═╡ 3a5d3ba0-87ae-11eb-1717-93be0b802cab begin drawing = 1 OpticSim.NotebooksUtils.SetBackend(defs, makie_backend) md"Set Makie backend" end # ╔═╡ 96e423a0-885a-11eb-02a3-8704e8dbdab6 begin function Vis.scene(resolution = (1000, 1000)) # @info "RG: Vis.Scene Replacement" scene, layout = Makie.layoutscene(resolution = resolution) Vis.set_current_main_scene(scene) lscene = layout[1, 1] = Makie.LScene(scene, scenekw = (camera = Makie.cam3d_cad!, axis_type = Makie.axis3d!, raw = false)) Vis.set_current_3d_scene(lscene) return scene, lscene end function resolution() if (default_resolution == "Small") return (300, 300) elseif (default_resolution == "Medium") return (500, 500) else return (1000, 1000) end end end # ╔═╡ e92e18de-8847-11eb-2fdf-b90425c7327b begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source(origins=Origins.Point(), directions=Directions.RectGrid(π/4, π/4, 15, 15)) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ 544d5870-8848-11eb-385e-afcce49d099d begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source(origins=Origins.Point(), directions=Directions.UniformCone(π/6, 1000)) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ 78875510-8848-11eb-18d6-eba32897a99e begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source(origins=Origins.Point(), directions=Directions.HexapolarCone(π/6, 10)) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ 69f94f40-885b-11eb-08b0-e9faf7969dda begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source(origins=Origins.RectGrid(1.0, 1.0, 10, 10), directions=Directions.Constant()) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ ac0ee1b0-885b-11eb-0395-a19b37c5a472 begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source(origins=Origins.RectGrid(1.0, 1.0, 3, 3), directions=Directions.HexapolarCone(π/6, 10)) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ e14e85c0-8846-11eb-1f4a-2768e655321c begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source(origins=Origins.Hexapolar(2, 8.0, 8.0), directions=Directions.RectGrid(π/8, π/8, 5, 5)) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ 69d61a60-885c-11eb-3f97-75e98121ec8c begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source( origins=Origins.Hexapolar(1, 8.0, 8.0), directions=Directions.RectGrid(π/6, π/6, 15, 15), # try to comment and un-comment the following lines to see the diffrence power=AngularPower.Cosine(10.0) ) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ 0ae26f80-885d-11eb-2c2a-ad23b34daac1 begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s = Sources.Source( origins=Origins.RectGrid(1.0, 1.0, 3, 3), directions=Directions.HexapolarCone(π/6, 10), # try to comment and un-comment the following lines to see the diffrence power=AngularPower.Gaussian(2.0, 2.0) ) Vis.draw(s, resolution=resolution(), debug=true) end # ╔═╡ 941bb0a0-8861-11eb-09fd-87e2022e068e begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL Vis.draw(my_display; resolution=resolution(), color=:red, debug=false) local rays = AbstractArray{OpticalRay{Float64, 3}}(collect(my_display)) Vis.draw!(rays; color=:red, debug=false) end # ╔═╡ def239f0-87bc-11eb-2edb-2f859ac41bee begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s1 = Sources.Source(sourcenum = 1, origins=Origins.Hexapolar(5, 8.0, 8.0), directions=Directions.Constant()) # create a second source and rotate it by -5 degs local s2 = Sources.Source(sourcenum = 2, origins=Origins.Hexapolar(5, 8.0, 8.0), directions=Directions.Constant(), transform=Transform(zeros(Geometry.Vec3), rotationY(deg2rad(-8)) * unitZ3())) # create the "ray generator" local combined_sources = Sources.CompositeSource(Transform(Geometry.Vec3(0.0, 0.0, 10.0), unitZ3() * -1), [s1, s2]) # and draw the system + the generated rays Vis.drawtracerays(sys, raygenerator = combined_sources, resolution=resolution(), test = true, trackallrays = true, colorbysourcenum = true, drawgen = false) end # ╔═╡ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" Makie = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" OpticSim = "24114763-4efb-45e7-af0e-cde916beb153" PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8" [compat] DataFrames = "~1.3.2" Makie = "~0.15.3" OpticSim = "~0.5.3" PlutoUI = "~0.7.35" """ # ╔═╡ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.7.2" manifest_format = "2.0" [[deps.ASL_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "6252039f98492252f9e47c312c8ffda0e3b9e78d" uuid = "ae81ac8f-d209-56e5-92de-9978fef736f9" version = "0.1.3+0" [[deps.ATK_jll]] deps = ["Artifacts", "Glib_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "58c36d8a1beeb12d63921bcfaa674baf30a1140e" uuid = "7b86fcea-f67b-53e1-809c-8f1719c154e8" version = "2.36.1+0" [[deps.AbstractFFTs]] deps = ["ChainRulesCore", "LinearAlgebra"] git-tree-sha1 = "6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4" uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c" version = "1.1.0" [[deps.AbstractPlutoDingetjes]] deps = ["Pkg"] git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481" uuid = "6e696c72-6542-2067-7265-42206c756150" version = "1.1.4" [[deps.AbstractTrees]] git-tree-sha1 = "03e0550477d86222521d254b741d470ba17ea0b5" uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" version = "0.3.4" [[deps.Adapt]] deps = ["LinearAlgebra"] git-tree-sha1 = "af92965fb30777147966f58acb05da51c5616b5f" uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" version = "3.3.3" [[deps.Animations]] deps = ["Colors"] git-tree-sha1 = "e81c509d2c8e49592413bfb0bb3b08150056c79d" uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340" version = "0.4.1" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" [[deps.ArnoldiMethod]] deps = ["LinearAlgebra", "Random", "StaticArrays"] git-tree-sha1 = "62e51b39331de8911e4a7ff6f5aaf38a5f4cc0ae" uuid = "ec485272-7323-5ecc-a04f-4719b315124d" version = "0.2.0" [[deps.ArrayInterface]] deps = ["Compat", "IfElse", "LinearAlgebra", "Requires", "SparseArrays", "Static"] git-tree-sha1 = "745233d77146ad221629590b6d82fe7f1ddb478f" uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9" version = "4.0.3" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Automa]] deps = ["Printf", "ScanByte", "TranscodingStreams"] git-tree-sha1 = "d50976f217489ce799e366d9561d56a98a30d7fe" uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b" version = "0.8.2" [[deps.AxisAlgorithms]] deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"] git-tree-sha1 = "66771c8d21c8ff5e3a93379480a2307ac36863f7" uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950" version = "1.0.1" [[deps.AxisArrays]] deps = ["Dates", "IntervalSets", "IterTools", "RangeArrays"] git-tree-sha1 = "d127d5e4d86c7680b20c35d40b503c74b9a39b5e" uuid = "39de3d68-74b9-583c-8d2d-e117c070f3a9" version = "0.4.4" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.BenchmarkTools]] deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"] git-tree-sha1 = "4c10eee4af024676200bc7752e536f858c6b8f93" uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" version = "1.3.1" [[deps.BinaryProvider]] deps = ["Libdl", "Logging", "SHA"] git-tree-sha1 = "ecdec412a9abc8db54c0efc5548c64dfce072058" uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232" version = "0.5.10" [[deps.Bzip2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2" uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0" version = "1.0.8+0" [[deps.CEnum]] git-tree-sha1 = "215a9aa4a1f23fbd05b92769fdd62559488d70e9" uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" version = "0.4.1" [[deps.CRlibm]] deps = ["CRlibm_jll"] git-tree-sha1 = "32abd86e3c2025db5172aa182b982debed519834" uuid = "96374032-68de-5a5b-8d9e-752f78720389" version = "1.0.1" [[deps.CRlibm_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "e329286945d0cfc04456972ea732551869af1cfc" uuid = "4e9b3aee-d8a1-5a3d-ad8b-7d824db253f0" version = "1.0.1+0" [[deps.CSV]] deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings"] git-tree-sha1 = "49f14b6c56a2da47608fe30aed711b5882264d7a" uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" version = "0.9.11" [[deps.Cairo]] deps = ["Cairo_jll", "Colors", "Glib_jll", "Graphics", "Libdl", "Pango_jll"] git-tree-sha1 = "d0b3f8b4ad16cb0a2988c6788646a5e6a17b6b1b" uuid = "159f3aea-2a34-519c-b102-8c37f9878175" version = "1.0.5" [[deps.Cairo_jll]] deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"] git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2" uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a" version = "1.16.1+1" [[deps.Calculus]] deps = ["LinearAlgebra"] git-tree-sha1 = "f641eb0a4f00c343bbc32346e1217b86f3ce9dad" uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9" version = "0.5.1" [[deps.CatIndices]] deps = ["CustomUnitRanges", "OffsetArrays"] git-tree-sha1 = "a0f80a09780eed9b1d106a1bf62041c2efc995bc" uuid = "aafaddc9-749c-510e-ac4f-586e18779b91" version = "0.2.2" [[deps.ChainRules]] deps = ["ChainRulesCore", "Compat", "IrrationalConstants", "LinearAlgebra", "Random", "RealDot", "SparseArrays", "Statistics"] git-tree-sha1 = "098b5eeb1170f569a45f363066b0e405868fc210" uuid = "082447d4-558c-5d27-93f4-14fc19e9eca2" version = "1.27.0" [[deps.ChainRulesCore]] deps = ["Compat", "LinearAlgebra", "SparseArrays"] git-tree-sha1 = "c9a6160317d1abe9c44b3beb367fd448117679ca" uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" version = "1.13.0" [[deps.ChangesOfVariables]] deps = ["ChainRulesCore", "LinearAlgebra", "Test"] git-tree-sha1 = "bf98fa45a0a4cee295de98d4c1462be26345b9a1" uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0" version = "0.1.2" [[deps.Clustering]] deps = ["Distances", "LinearAlgebra", "NearestNeighbors", "Printf", "SparseArrays", "Statistics", "StatsBase"] git-tree-sha1 = "75479b7df4167267d75294d14b58244695beb2ac" uuid = "aaaa29a8-35af-508c-8bc3-b662a17a0fe5" version = "0.14.2" [[deps.CodeTracking]] deps = ["InteractiveUtils", "UUIDs"] git-tree-sha1 = "759a12cefe1cd1bb49e477bc3702287521797483" uuid = "da1fd8a2-8d9e-5ec2-8556-3022fb5608a2" version = "1.0.7" [[deps.CodecBzip2]] deps = ["Bzip2_jll", "Libdl", "TranscodingStreams"] git-tree-sha1 = "2e62a725210ce3c3c2e1a3080190e7ca491f18d7" uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd" version = "0.7.2" [[deps.CodecZlib]] deps = ["TranscodingStreams", "Zlib_jll"] git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da" uuid = "944b1d66-785c-5afd-91f1-9de20f533193" version = "0.7.0" [[deps.ColorBrewer]] deps = ["Colors", "JSON", "Test"] git-tree-sha1 = "61c5334f33d91e570e1d0c3eb5465835242582c4" uuid = "a2cac450-b92f-5266-8821-25eda20663c8" version = "0.4.0" [[deps.ColorSchemes]] deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random"] git-tree-sha1 = "12fc73e5e0af68ad3137b886e3f7c1eacfca2640" uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" version = "3.17.1" [[deps.ColorTypes]] deps = ["FixedPointNumbers", "Random"] git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597" uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" version = "0.11.0" [[deps.ColorVectorSpace]] deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"] git-tree-sha1 = "3f1f500312161f1ae067abe07d13b40f78f32e07" uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" version = "0.9.8" [[deps.Colors]] deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40" uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" version = "0.12.8" [[deps.CommonSubexpressions]] deps = ["MacroTools", "Test"] git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7" uuid = "bbf7d656-a473-5ed7-a52c-81e309532950" version = "0.3.0" [[deps.Compat]] deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] git-tree-sha1 = "44c37b4636bc54afac5c574d2d02b625349d6582" uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" version = "3.41.0" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" [[deps.ComputationalResources]] git-tree-sha1 = "52cb3ec90e8a8bea0e62e275ba577ad0f74821f7" uuid = "ed09eef8-17a6-5b46-8889-db040fac31e3" version = "0.3.2" [[deps.Conda]] deps = ["Downloads", "JSON", "VersionParsing"] git-tree-sha1 = "6e47d11ea2776bc5627421d59cdcc1296c058071" uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d" version = "1.7.0" [[deps.Configurations]] deps = ["ExproniconLite", "OrderedCollections", "TOML"] git-tree-sha1 = "ab9b7c51e8acdd20c769bccde050b5615921c533" uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d" version = "0.17.3" [[deps.ConstructionBase]] deps = ["LinearAlgebra"] git-tree-sha1 = "f74e9d5388b8620b4cee35d4c5a618dd4dc547f4" uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9" version = "1.3.0" [[deps.Contour]] deps = ["StaticArrays"] git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7" uuid = "d38c429a-6771-53c6-b99e-75d170b6e991" version = "0.5.7" [[deps.CoordinateTransformations]] deps = ["LinearAlgebra", "StaticArrays"] git-tree-sha1 = "681ea870b918e7cff7111da58791d7f718067a19" uuid = "150eb455-5306-5404-9cee-2592286d6298" version = "0.6.2" [[deps.Crayons]] git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15" uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" version = "4.1.1" [[deps.CustomUnitRanges]] git-tree-sha1 = "1a3f97f907e6dd8983b744d2642651bb162a3f7a" uuid = "dc8bdbbb-1ca9-579f-8c36-e416f6a65cce" version = "1.0.2" [[deps.DataAPI]] git-tree-sha1 = "cc70b17275652eb47bc9e5f81635981f13cea5c8" uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" version = "1.9.0" [[deps.DataFrames]] deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] git-tree-sha1 = "ae02104e835f219b8930c7664b8012c93475c340" uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" version = "1.3.2" [[deps.DataStructures]] deps = ["Compat", "InteractiveUtils", "OrderedCollections"] git-tree-sha1 = "3daef5523dd2e769dad2365274f760ff5f282c7d" uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" version = "0.18.11" [[deps.DataValueInterfaces]] git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" version = "1.0.0" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.Dbus_jll]] deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "97f1325c10bd02b1cc1882e9c2bf6407ba630ace" uuid = "ee1fde0b-3d02-5ea6-8484-8dfef6360eab" version = "1.12.16+3" [[deps.DelimitedFiles]] deps = ["Mmap"] uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" [[deps.DensityInterface]] deps = ["InverseFunctions", "Test"] git-tree-sha1 = "80c3e8639e3353e5d2912fb3a1916b8455e2494b" uuid = "b429d917-457f-4dbc-8f4c-0cc954292b1d" version = "0.4.0" [[deps.DiffResults]] deps = ["StaticArrays"] git-tree-sha1 = "c18e98cba888c6c25d1c3b048e4b3380ca956805" uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5" version = "1.0.3" [[deps.DiffRules]] deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"] git-tree-sha1 = "dd933c4ef7b4c270aacd4eb88fa64c147492acf0" uuid = "b552c78f-8df3-52c6-915a-8e097449b14b" version = "1.10.0" [[deps.Distances]] deps = ["LinearAlgebra", "SparseArrays", "Statistics", "StatsAPI"] git-tree-sha1 = "3258d0659f812acde79e8a74b11f17ac06d0ca04" uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" version = "0.10.7" [[deps.Distributed]] deps = ["Random", "Serialization", "Sockets"] uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" [[deps.Distributions]] deps = ["ChainRulesCore", "DensityInterface", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "Test"] git-tree-sha1 = "9d3c0c762d4666db9187f363a76b47f7346e673b" uuid = "31c24e10-a181-5473-b8eb-7969acd0382f" version = "0.25.49" [[deps.DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "b19534d1895d702889b219c382a6e18010797f0b" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.8.6" [[deps.Downloads]] deps = ["ArgTools", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" [[deps.DualNumbers]] deps = ["Calculus", "NaNMath", "SpecialFunctions"] git-tree-sha1 = "84f04fe68a3176a583b864e492578b9466d87f1e" uuid = "fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74" version = "0.6.6" [[deps.EarCut_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d" uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5" version = "2.2.3+0" [[deps.EllipsisNotation]] deps = ["ArrayInterface"] git-tree-sha1 = "d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa" uuid = "da5c29d0-fa7d-589e-88eb-ea29b0a81949" version = "1.3.0" [[deps.ErrorfreeArithmetic]] git-tree-sha1 = "d6863c556f1142a061532e79f611aa46be201686" uuid = "90fa49ef-747e-5e6f-a989-263ba693cf1a" version = "0.5.2" [[deps.Expat_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "ae13fcbc7ab8f16b0856729b050ef0c446aa3492" uuid = "2e619515-83b5-522b-bb60-26c02a35a201" version = "2.4.4+0" [[deps.ExprTools]] git-tree-sha1 = "56559bbef6ca5ea0c0818fa5c90320398a6fbf8d" uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04" version = "0.1.8" [[deps.ExproniconLite]] git-tree-sha1 = "8b08cc88844e4d01db5a2405a08e9178e19e479e" uuid = "55351af7-c7e9-48d6-89ff-24e801d99491" version = "0.6.13" [[deps.FFMPEG]] deps = ["FFMPEG_jll"] git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8" uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a" version = "0.4.1" [[deps.FFMPEG_jll]] deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"] git-tree-sha1 = "d8a578692e3077ac998b50c0217dfd67f21d1e5f" uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5" version = "4.4.0+0" [[deps.FFTViews]] deps = ["CustomUnitRanges", "FFTW"] git-tree-sha1 = "cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2" uuid = "4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd" version = "0.3.2" [[deps.FFTW]] deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"] git-tree-sha1 = "463cb335fa22c4ebacfd1faba5fde14edb80d96c" uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" version = "1.4.5" [[deps.FFTW_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea" uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a" version = "3.3.10+0" [[deps.FastRounding]] deps = ["ErrorfreeArithmetic", "Test"] git-tree-sha1 = "224175e213fd4fe112db3eea05d66b308dc2bf6b" uuid = "fa42c844-2597-5d31-933b-ebd51ab2693f" version = "0.2.0" [[deps.FileIO]] deps = ["Pkg", "Requires", "UUIDs"] git-tree-sha1 = "80ced645013a5dbdc52cf70329399c35ce007fae" uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" version = "1.13.0" [[deps.FilePathsBase]] deps = ["Compat", "Dates", "Mmap", "Printf", "Test", "UUIDs"] git-tree-sha1 = "04d13bfa8ef11720c24e4d840c0033d145537df7" uuid = "48062228-2e41-5def-b9a4-89aafe57970f" version = "0.9.17" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.FillArrays]] deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"] git-tree-sha1 = "deed294cde3de20ae0b2e0355a6c4e1c6a5ceffc" uuid = "1a297f60-69ca-5386-bcde-b61e274b549b" version = "0.12.8" [[deps.FiniteDiff]] deps = ["ArrayInterface", "LinearAlgebra", "Requires", "SparseArrays", "StaticArrays"] git-tree-sha1 = "ec299fdc8f49ae450807b0cb1d161c6b76fd2b60" uuid = "6a86dc24-6348-571c-b903-95158fe2bd41" version = "2.10.1" [[deps.FixedPointNumbers]] deps = ["Statistics"] git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc" uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" version = "0.8.4" [[deps.Fontconfig_jll]] deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03" uuid = "a3f928ae-7b40-5064-980b-68af3947d34b" version = "2.13.93+0" [[deps.Format]] git-tree-sha1 = "03bcdf8ab1a5b9e6455ccb45c30910d282aa09f4" uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8" version = "1.3.2" [[deps.Formatting]] deps = ["Printf"] git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8" uuid = "59287772-0a20-5a39-b81b-1366585eb4c0" version = "0.4.2" [[deps.ForwardDiff]] deps = ["CommonSubexpressions", "DiffResults", "DiffRules", "LinearAlgebra", "LogExpFunctions", "NaNMath", "Preferences", "Printf", "Random", "SpecialFunctions", "StaticArrays"] git-tree-sha1 = "1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2" uuid = "f6369f11-7733-5829-9624-2563aa707210" version = "0.10.25" [[deps.FreeType]] deps = ["CEnum", "FreeType2_jll"] git-tree-sha1 = "cabd77ab6a6fdff49bfd24af2ebe76e6e018a2b4" uuid = "b38be410-82b0-50bf-ab77-7b57e271db43" version = "4.0.0" [[deps.FreeType2_jll]] deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "87eb71354d8ec1a96d4a7636bd57a7347dde3ef9" uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7" version = "2.10.4+0" [[deps.FreeTypeAbstraction]] deps = ["ColorVectorSpace", "Colors", "FreeType", "GeometryBasics", "StaticArrays"] git-tree-sha1 = "770050893e7bc8a34915b4b9298604a3236de834" uuid = "663a7486-cb36-511b-a19d-713bb74d65c9" version = "0.9.5" [[deps.FriBidi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91" uuid = "559328eb-81f9-559d-9380-de523a88c83c" version = "1.0.10+0" [[deps.FunctionWrappers]] git-tree-sha1 = "241552bc2209f0fa068b6415b1942cc0aa486bcc" uuid = "069b7b12-0de2-55c6-9aab-29f3d0a68a2e" version = "1.1.2" [[deps.Future]] deps = ["Random"] uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" [[deps.FuzzyCompletions]] deps = ["REPL"] git-tree-sha1 = "2cc2791b324e8ed387a91d7226d17be754e9de61" uuid = "fb4132e2-a121-4a70-b8a1-d5b831dcdcc2" version = "0.4.3" [[deps.GLFW]] deps = ["GLFW_jll"] git-tree-sha1 = "35dbc482f0967d8dceaa7ce007d16f9064072166" uuid = "f7f18e0c-5ee9-5ccd-a5bf-e8befd85ed98" version = "3.4.1" [[deps.GLFW_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"] git-tree-sha1 = "51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01" uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89" version = "3.3.6+0" [[deps.GLMakie]] deps = ["ColorTypes", "Colors", "FileIO", "FixedPointNumbers", "FreeTypeAbstraction", "GLFW", "GeometryBasics", "LinearAlgebra", "Makie", "Markdown", "MeshIO", "ModernGL", "Observables", "Printf", "Serialization", "ShaderAbstractions", "StaticArrays"] git-tree-sha1 = "25dd999ef6ad2904206f96211386535bcb86cc58" uuid = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a" version = "0.4.7" [[deps.GLPK]] deps = ["BinaryProvider", "GLPK_jll", "Libdl", "MathOptInterface", "SparseArrays"] git-tree-sha1 = "86573ecb852e303b209212046af44871f1c0e49c" uuid = "60bf3e95-4087-53dc-ae20-288a0d20c6a6" version = "0.13.0" [[deps.GLPK_jll]] deps = ["GMP_jll", "Libdl", "Pkg"] git-tree-sha1 = "ccc855de74292e478d4278e3a6fdd8212f75e81e" uuid = "e8aa6df9-e6ca-548a-97ff-1f85fc5b8b98" version = "4.64.0+0" [[deps.GMP_jll]] deps = ["Artifacts", "Libdl"] uuid = "781609d7-10c4-51f6-84f2-b8444358ff6d" [[deps.GR]] deps = ["Base64", "DelimitedFiles", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Pkg", "Printf", "Random", "RelocatableFolders", "Serialization", "Sockets", "Test", "UUIDs"] git-tree-sha1 = "9f836fb62492f4b0f0d3b06f55983f2704ed0883" uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71" version = "0.64.0" [[deps.GR_jll]] deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Pkg", "Qt5Base_jll", "Zlib_jll", "libpng_jll"] git-tree-sha1 = "a6c850d77ad5118ad3be4bd188919ce97fffac47" uuid = "d2c73de3-f751-5644-a686-071e5b155ba9" version = "0.64.0+0" [[deps.GTK3_jll]] deps = ["ATK_jll", "Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Libepoxy_jll", "Pango_jll", "Pkg", "Wayland_jll", "Xorg_libX11_jll", "Xorg_libXcomposite_jll", "Xorg_libXcursor_jll", "Xorg_libXdamage_jll", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll", "Xorg_libXrender_jll", "at_spi2_atk_jll", "gdk_pixbuf_jll", "iso_codes_jll", "xkbcommon_jll"] git-tree-sha1 = "b080a592525632d287aee4637a62682576b7f5e4" uuid = "77ec8976-b24b-556a-a1bf-49a033a670a6" version = "3.24.31+0" [[deps.GeometryBasics]] deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"] git-tree-sha1 = "58bcdf5ebc057b085e58d95c138725628dd7453c" uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326" version = "0.4.1" [[deps.Gettext_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"] git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046" uuid = "78b55507-aeef-58d4-861c-77aaff3498b1" version = "0.21.0+0" [[deps.Ghostscript_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "78e2c69783c9753a91cdae88a8d432be85a2ab5e" uuid = "61579ee1-b43e-5ca0-a5da-69d92c66a64b" version = "9.55.0+0" [[deps.Glib_jll]] deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "a32d672ac2c967f3deb8a81d828afc739c838a06" uuid = "7746bdde-850d-59dc-9ae8-88ece973131d" version = "2.68.3+2" [[deps.Graphics]] deps = ["Colors", "LinearAlgebra", "NaNMath"] git-tree-sha1 = "1c5a84319923bea76fa145d49e93aa4394c73fc2" uuid = "a2bd30eb-e257-5431-a919-1863eab51364" version = "1.1.1" [[deps.Graphite2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011" uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472" version = "1.3.14+0" [[deps.Graphs]] deps = ["ArnoldiMethod", "Compat", "DataStructures", "Distributed", "Inflate", "LinearAlgebra", "Random", "SharedArrays", "SimpleTraits", "SparseArrays", "Statistics"] git-tree-sha1 = "57c021de207e234108a6f1454003120a1bf350c4" uuid = "86223c79-3864-5bf0-83f7-82e725a168b6" version = "1.6.0" [[deps.GridLayoutBase]] deps = ["GeometryBasics", "InteractiveUtils", "Observables"] git-tree-sha1 = "70938436e2720e6cb8a7f2ca9f1bbdbf40d7f5d0" uuid = "3955a311-db13-416c-9275-1d80ed98e5e9" version = "0.6.4" [[deps.Grisu]] git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2" uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe" version = "1.0.2" [[deps.Gtk]] deps = ["Cairo", "Cairo_jll", "Dates", "GTK3_jll", "Glib_jll", "Graphics", "JLLWrappers", "Libdl", "Librsvg_jll", "Pkg", "Reexport", "Serialization", "Test", "Xorg_xkeyboard_config_jll", "adwaita_icon_theme_jll", "gdk_pixbuf_jll", "hicolor_icon_theme_jll"] git-tree-sha1 = "09afd81dd7d80ae0dc6f489fd21560725e45497e" uuid = "4c0ca9eb-093a-5379-98c5-f87ac0bbbf44" version = "1.2.0" [[deps.GtkReactive]] deps = ["Cairo", "Colors", "Dates", "FixedPointNumbers", "Graphics", "Gtk", "IntervalSets", "Reactive", "Reexport", "RoundingIntegers"] git-tree-sha1 = "ccb07a5fa45e43ac83b6795c9e218d6a802c93d8" uuid = "27996c0f-39cd-5cc1-a27a-05f136f946b6" version = "1.0.6" [[deps.HTTP]] deps = ["Base64", "Dates", "IniFile", "Logging", "MbedTLS", "NetworkOptions", "Sockets", "URIs"] git-tree-sha1 = "0fa77022fe4b511826b39c894c90daf5fce3334a" uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" version = "0.9.17" [[deps.HarfBuzz_jll]] deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"] git-tree-sha1 = "129acf094d168394e80ee1dc4bc06ec835e510a3" uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566" version = "2.8.1+1" [[deps.HypergeometricFunctions]] deps = ["DualNumbers", "LinearAlgebra", "SpecialFunctions", "Test"] git-tree-sha1 = "65e4589030ef3c44d3b90bdc5aac462b4bb05567" uuid = "34004b35-14d8-5ef3-9330-4cdb6864b03a" version = "0.3.8" [[deps.Hyperscript]] deps = ["Test"] git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9" uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91" version = "0.0.4" [[deps.HypertextLiteral]] git-tree-sha1 = "2b078b5a615c6c0396c77810d92ee8c6f470d238" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.3" [[deps.IOCapture]] deps = ["Logging", "Random"] git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a" uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89" version = "0.2.2" [[deps.IRTools]] deps = ["InteractiveUtils", "MacroTools", "Test"] git-tree-sha1 = "7f43342f8d5fd30ead0ba1b49ab1a3af3b787d24" uuid = "7869d1d1-7146-5819-86e3-90919afe41df" version = "0.4.5" [[deps.IfElse]] git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1" uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173" version = "0.1.1" [[deps.ImageAxes]] deps = ["AxisArrays", "ImageBase", "ImageCore", "Reexport", "SimpleTraits"] git-tree-sha1 = "c54b581a83008dc7f292e205f4c409ab5caa0f04" uuid = "2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac" version = "0.6.10" [[deps.ImageBase]] deps = ["ImageCore", "Reexport"] git-tree-sha1 = "b51bb8cae22c66d0f6357e3bcb6363145ef20835" uuid = "c817782e-172a-44cc-b673-b171935fbb9e" version = "0.1.5" [[deps.ImageContrastAdjustment]] deps = ["ImageCore", "ImageTransformations", "Parameters"] git-tree-sha1 = "0d75cafa80cf22026cea21a8e6cf965295003edc" uuid = "f332f351-ec65-5f6a-b3d1-319c6670881a" version = "0.3.10" [[deps.ImageCore]] deps = ["AbstractFFTs", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Graphics", "MappedArrays", "MosaicViews", "OffsetArrays", "PaddedViews", "Reexport"] git-tree-sha1 = "9a5c62f231e5bba35695a20988fc7cd6de7eeb5a" uuid = "a09fc81d-aa75-5fe9-8630-4744c3626534" version = "0.9.3" [[deps.ImageDistances]] deps = ["Distances", "ImageCore", "ImageMorphology", "LinearAlgebra", "Statistics"] git-tree-sha1 = "7a20463713d239a19cbad3f6991e404aca876bda" uuid = "51556ac3-7006-55f5-8cb3-34580c88182d" version = "0.2.15" [[deps.ImageFiltering]] deps = ["CatIndices", "ComputationalResources", "DataStructures", "FFTViews", "FFTW", "ImageBase", "ImageCore", "LinearAlgebra", "OffsetArrays", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "TiledIteration"] git-tree-sha1 = "15bd05c1c0d5dbb32a9a3d7e0ad2d50dd6167189" uuid = "6a3955dd-da59-5b1f-98d4-e7296123deb5" version = "0.7.1" [[deps.ImageIO]] deps = ["FileIO", "Netpbm", "OpenEXR", "PNGFiles", "TiffImages", "UUIDs"] git-tree-sha1 = "a2951c93684551467265e0e32b577914f69532be" uuid = "82e4d734-157c-48bb-816b-45c225c6df19" version = "0.5.9" [[deps.ImageMagick]] deps = ["FileIO", "ImageCore", "ImageMagick_jll", "InteractiveUtils", "Libdl", "Pkg", "Random"] git-tree-sha1 = "5bc1cb62e0c5f1005868358db0692c994c3a13c6" uuid = "6218d12a-5da1-5696-b52f-db25d2ecc6d1" version = "1.2.1" [[deps.ImageMagick_jll]] deps = ["Artifacts", "Ghostscript_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pkg", "Zlib_jll", "libpng_jll"] git-tree-sha1 = "f025b79883f361fa1bd80ad132773161d231fd9f" uuid = "c73af94c-d91f-53ed-93a7-00f77d67a9d7" version = "6.9.12+2" [[deps.ImageMetadata]] deps = ["AxisArrays", "ImageAxes", "ImageBase", "ImageCore"] git-tree-sha1 = "36cbaebed194b292590cba2593da27b34763804a" uuid = "bc367c6b-8a6b-528e-b4bd-a4b897500b49" version = "0.9.8" [[deps.ImageMorphology]] deps = ["ImageCore", "LinearAlgebra", "Requires", "TiledIteration"] git-tree-sha1 = "7668b123ecfd39a6ae3fc31c532b588999bdc166" uuid = "787d08f9-d448-5407-9aad-5290dd7ab264" version = "0.3.1" [[deps.ImageQualityIndexes]] deps = ["ImageContrastAdjustment", "ImageCore", "ImageDistances", "ImageFiltering", "OffsetArrays", "Statistics"] git-tree-sha1 = "1d2d73b14198d10f7f12bf7f8481fd4b3ff5cd61" uuid = "2996bd0c-7a13-11e9-2da2-2f5ce47296a9" version = "0.3.0" [[deps.ImageSegmentation]] deps = ["Clustering", "DataStructures", "Distances", "Graphs", "ImageCore", "ImageFiltering", "ImageMorphology", "LinearAlgebra", "MetaGraphs", "RegionTrees", "SimpleWeightedGraphs", "StaticArrays", "Statistics"] git-tree-sha1 = "36832067ea220818d105d718527d6ed02385bf22" uuid = "80713f31-8817-5129-9cf8-209ff8fb23e1" version = "1.7.0" [[deps.ImageShow]] deps = ["Base64", "FileIO", "ImageBase", "ImageCore", "OffsetArrays", "StackViews"] git-tree-sha1 = "d0ac64c9bee0aed6fdbb2bc0e5dfa9a3a78e3acc" uuid = "4e3cecfd-b093-5904-9786-8bbb286a6a31" version = "0.3.3" [[deps.ImageTransformations]] deps = ["AxisAlgorithms", "ColorVectorSpace", "CoordinateTransformations", "ImageBase", "ImageCore", "Interpolations", "OffsetArrays", "Rotations", "StaticArrays"] git-tree-sha1 = "42fe8de1fe1f80dab37a39d391b6301f7aeaa7b8" uuid = "02fcd773-0e25-5acc-982a-7f6622650795" version = "0.9.4" [[deps.ImageView]] deps = ["AxisArrays", "Cairo", "Graphics", "Gtk", "GtkReactive", "ImageBase", "ImageCore", "ImageMetadata", "RoundingIntegers", "StatsBase"] git-tree-sha1 = "279acc77190075c4abc62d8a0d68337d25d3e55c" uuid = "86fae568-95e7-573e-a6b2-d8a6b900c9ef" version = "0.10.15" [[deps.Images]] deps = ["Base64", "FileIO", "Graphics", "ImageAxes", "ImageBase", "ImageContrastAdjustment", "ImageCore", "ImageDistances", "ImageFiltering", "ImageIO", "ImageMagick", "ImageMetadata", "ImageMorphology", "ImageQualityIndexes", "ImageSegmentation", "ImageShow", "ImageTransformations", "IndirectArrays", "IntegralArrays", "Random", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "TiledIteration"] git-tree-sha1 = "11d268adba1869067620659e7cdf07f5e54b6c76" uuid = "916415d5-f1e6-5110-898d-aaa5f9f070e0" version = "0.25.1" [[deps.Imath_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "87f7662e03a649cffa2e05bf19c303e168732d3e" uuid = "905a6f67-0a94-5f89-b386-d35d92009cd1" version = "3.1.2+0" [[deps.IndirectArrays]] git-tree-sha1 = "012e604e1c7458645cb8b436f8fba789a51b257f" uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959" version = "1.0.0" [[deps.Inflate]] git-tree-sha1 = "f5fc07d4e706b84f72d54eedcc1c13d92fb0871c" uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9" version = "0.1.2" [[deps.IniFile]] git-tree-sha1 = "f550e6e32074c939295eb5ea6de31849ac2c9625" uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f" version = "0.5.1" [[deps.InlineStrings]] deps = ["Parsers"] git-tree-sha1 = "61feba885fac3a407465726d0c330b3055df897f" uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" version = "1.1.2" [[deps.IntegralArrays]] deps = ["ColorTypes", "FixedPointNumbers", "IntervalSets"] git-tree-sha1 = "cf737764159c66b95cdbf5c10484929b247fecfe" uuid = "1d092043-8f09-5a30-832f-7509e371ab51" version = "0.1.3" [[deps.IntelOpenMP_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "d979e54b71da82f3a65b62553da4fc3d18c9004c" uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0" version = "2018.0.3+2" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.Interpolations]] deps = ["AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"] git-tree-sha1 = "b15fc0a95c564ca2e0a7ae12c1f095ca848ceb31" uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59" version = "0.13.5" [[deps.IntervalArithmetic]] deps = ["CRlibm", "FastRounding", "LinearAlgebra", "Markdown", "Random", "RecipesBase", "RoundingEmulator", "SetRounding", "StaticArrays"] git-tree-sha1 = "bbf2793a70c0a7aaa09aa298b277fe1b90e06d78" uuid = "d1acc4aa-44c8-5952-acd4-ba5d80a2a253" version = "0.20.3" [[deps.IntervalSets]] deps = ["Dates", "EllipsisNotation", "Statistics"] git-tree-sha1 = "3cc368af3f110a767ac786560045dceddfc16758" uuid = "8197267c-284f-5f27-9208-e0e47529a953" version = "0.5.3" [[deps.Intervals]] deps = ["Dates", "Printf", "RecipesBase", "Serialization", "TimeZones"] git-tree-sha1 = "323a38ed1952d30586d0fe03412cde9399d3618b" uuid = "d8418881-c3e1-53bb-8760-2df7ec849ed5" version = "1.5.0" [[deps.InverseFunctions]] deps = ["Test"] git-tree-sha1 = "a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65" uuid = "3587e190-3f89-42d0-90ee-14403ec27112" version = "0.1.2" [[deps.InvertedIndices]] git-tree-sha1 = "bee5f1ef5bf65df56bdd2e40447590b272a5471f" uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" version = "1.1.0" [[deps.Ipopt]] deps = ["BinaryProvider", "Ipopt_jll", "Libdl", "LinearAlgebra", "MathOptInterface", "MathProgBase"] git-tree-sha1 = "380786b4929b8d18d76e909c6b2eca355b7c3bd6" uuid = "b6b21f68-93f8-5de0-b562-5493be1d77c9" version = "0.7.0" [[deps.Ipopt_jll]] deps = ["ASL_jll", "Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "MUMPS_seq_jll", "OpenBLAS32_jll", "Pkg"] git-tree-sha1 = "82124f27743f2802c23fcb05febc517d0b15d86e" uuid = "9cc047cb-c261-5740-88fc-0cf96f7bdcc7" version = "3.13.4+2" [[deps.IrrationalConstants]] git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151" uuid = "92d709cd-6900-40b7-9082-c6be49f344b6" version = "0.1.1" [[deps.Isoband]] deps = ["isoband_jll"] git-tree-sha1 = "f9b6d97355599074dc867318950adaa6f9946137" uuid = "f1662d9f-8043-43de-a69a-05efc1cc6ff4" version = "0.1.1" [[deps.IterTools]] git-tree-sha1 = "fa6287a4469f5e048d763df38279ee729fbd44e5" uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e" version = "1.4.0" [[deps.IteratorInterfaceExtensions]] git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" uuid = "82899510-4779-5014-852e-03e436cf321d" version = "1.0.0" [[deps.JLD2]] deps = ["FileIO", "MacroTools", "Mmap", "OrderedCollections", "Pkg", "Printf", "Reexport", "TranscodingStreams", "UUIDs"] git-tree-sha1 = "28b114b3279cdbac9a61c57b3e6548a572142b34" uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819" version = "0.4.21" [[deps.JLLWrappers]] deps = ["Preferences"] git-tree-sha1 = "abc9885a7ca2052a736a600f7fa66209f96506e1" uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" version = "1.4.1" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "3c837543ddb02250ef42f4738347454f95079d4e" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.3" [[deps.JSON3]] deps = ["Dates", "Mmap", "Parsers", "StructTypes", "UUIDs"] git-tree-sha1 = "7d58534ffb62cd947950b3aa9b993e63307a6125" uuid = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" version = "1.9.2" [[deps.JSONSchema]] deps = ["HTTP", "JSON", "URIs"] git-tree-sha1 = "2f49f7f86762a0fbbeef84912265a1ae61c4ef80" uuid = "7d188eb4-7ad8-530c-ae41-71a32a6d4692" version = "0.3.4" [[deps.JSServe]] deps = ["Base64", "CodecZlib", "Colors", "HTTP", "Hyperscript", "JSON3", "LinearAlgebra", "Markdown", "MsgPack", "Observables", "RelocatableFolders", "SHA", "Sockets", "Tables", "Test", "UUIDs", "WebSockets", "WidgetsBase"] git-tree-sha1 = "e8c3434c3e880e15760821a9eac00deb35ab6ea9" uuid = "824d6782-a2ef-11e9-3a09-e5662e0c26f9" version = "1.2.5" [[deps.JpegTurbo_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b53380851c6e6664204efb2e62cd24fa5c47e4ba" uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8" version = "2.1.2+0" [[deps.JuMP]] deps = ["Calculus", "DataStructures", "ForwardDiff", "JSON", "LinearAlgebra", "MathOptInterface", "MutableArithmetics", "NaNMath", "Random", "SparseArrays", "Statistics"] git-tree-sha1 = "57c17a221a55f81890aabf00f478886859e25eaf" uuid = "4076af6c-e467-56ae-b986-b466b2749572" version = "0.21.5" [[deps.JuliaInterpreter]] deps = ["CodeTracking", "InteractiveUtils", "Random", "UUIDs"] git-tree-sha1 = "8a50f8b3e6b261561df26f5718a6b59a3c947221" uuid = "aa1ae85d-cabe-5617-a682-6adf51b2e16a" version = "0.9.6" [[deps.Juno]] deps = ["Base64", "Logging", "Media", "Profile"] git-tree-sha1 = "07cb43290a840908a771552911a6274bc6c072c7" uuid = "e5e0dc1b-0480-54bc-9374-aad01c23163d" version = "0.8.4" [[deps.KernelDensity]] deps = ["Distributions", "DocStringExtensions", "FFTW", "Interpolations", "StatsBase"] git-tree-sha1 = "591e8dc09ad18386189610acafb970032c519707" uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b" version = "0.6.3" [[deps.LAME_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c" uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d" version = "3.100.1+0" [[deps.LZO_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6" uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac" version = "2.10.1+0" [[deps.LaTeXStrings]] git-tree-sha1 = "f2355693d6778a178ade15952b7ac47a4ff97996" uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" version = "1.3.0" [[deps.Latexify]] deps = ["Formatting", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "Printf", "Requires"] git-tree-sha1 = "a6552bfeab40de157a297d84e03ade4b8177677f" uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" version = "0.15.12" [[deps.LazyArtifacts]] deps = ["Artifacts", "Pkg"] uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3" [[deps.LazySets]] deps = ["Distributed", "ExprTools", "GLPK", "InteractiveUtils", "IntervalArithmetic", "JuMP", "LinearAlgebra", "Random", "RecipesBase", "Reexport", "Requires", "SharedArrays", "SparseArrays"] git-tree-sha1 = "e92e22dcd8abf31f9418213936aa41399740dd94" uuid = "b4f0291d-fe17-52bc-9479-3d1a343d9043" version = "1.55.0" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" [[deps.LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.Libepoxy_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "18b65a0eff6b58546bec18065e73f8a04e83758d" uuid = "42c93a91-0102-5b3f-8f9d-e41de60ac950" version = "1.5.8+1" [[deps.Libffi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "0b4a5d71f3e5200a7dff793393e09dfc2d874290" uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490" version = "3.2.2+1" [[deps.Libgcrypt_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"] git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae" uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4" version = "1.8.7+0" [[deps.Libglvnd_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll", "Xorg_libXext_jll"] git-tree-sha1 = "7739f837d6447403596a75d19ed01fd08d6f56bf" uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29" version = "1.3.0+3" [[deps.Libgpg_error_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9" uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8" version = "1.42.0+0" [[deps.Libiconv_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778" uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" version = "1.16.1+1" [[deps.Libmount_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73" uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9" version = "2.35.0+0" [[deps.Librsvg_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pango_jll", "Pkg", "gdk_pixbuf_jll"] git-tree-sha1 = "25d5e6b4eb3558613ace1c67d6a871420bfca527" uuid = "925c91fb-5dd6-59dd-8e8c-345e74382d89" version = "2.52.4+0" [[deps.Libtiff_jll]] deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Pkg", "Zlib_jll", "Zstd_jll"] git-tree-sha1 = "340e257aada13f95f98ee352d316c3bed37c8ab9" uuid = "89763e89-9b03-5906-acba-b20f662cd828" version = "4.3.0+0" [[deps.Libuuid_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066" uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700" version = "2.36.0+0" [[deps.LineSearches]] deps = ["LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "Printf"] git-tree-sha1 = "f27132e551e959b3667d8c93eae90973225032dd" uuid = "d3d80556-e9d4-5f37-9878-2ab0fcc64255" version = "7.1.1" [[deps.LinearAlgebra]] deps = ["Libdl", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.LogExpFunctions]] deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"] git-tree-sha1 = "e5718a00af0ab9756305a0392832c8952c7426c1" uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" version = "0.3.6" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.LoweredCodeUtils]] deps = ["JuliaInterpreter"] git-tree-sha1 = "6b0440822974cab904c8b14d79743565140567f6" uuid = "6f1432cf-f94c-5a45-995e-cdbf5db27b0b" version = "2.2.1" [[deps.Luxor]] deps = ["Base64", "Cairo", "Colors", "Dates", "FFMPEG", "FileIO", "Juno", "Random", "Requires", "Rsvg"] git-tree-sha1 = "aa804f92cf77298c86b26ef2487cc624b3dd4004" uuid = "ae8d54c2-7ccd-5906-9d76-62fc9837b5bc" version = "2.19.0" [[deps.METIS_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "1d31872bb9c5e7ec1f618e8c4a56c8b0d9bddc7e" uuid = "d00139f3-1899-568f-a2f0-47f597d42d70" version = "5.1.1+0" [[deps.MKL_jll]] deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"] git-tree-sha1 = "5455aef09b40e5020e1520f551fa3135040d4ed0" uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7" version = "2021.1.1+2" [[deps.MUMPS_seq_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "METIS_jll", "OpenBLAS32_jll", "Pkg"] git-tree-sha1 = "1a11a84b2af5feb5a62a820574804056cdc59c39" uuid = "d7ed1dd3-d0ae-5e8e-bfb4-87a502085b8d" version = "5.2.1+4" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.9" [[deps.Makie]] deps = ["Animations", "Base64", "ColorBrewer", "ColorSchemes", "ColorTypes", "Colors", "Contour", "Distributions", "DocStringExtensions", "FFMPEG", "FileIO", "FixedPointNumbers", "Formatting", "FreeType", "FreeTypeAbstraction", "GeometryBasics", "GridLayoutBase", "ImageIO", "IntervalSets", "Isoband", "KernelDensity", "LaTeXStrings", "LinearAlgebra", "MakieCore", "Markdown", "Match", "MathTeXEngine", "Observables", "Packing", "PlotUtils", "PolygonOps", "Printf", "Random", "RelocatableFolders", "Serialization", "Showoff", "SignedDistanceFields", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsFuns", "StructArrays", "UnicodeFun"] git-tree-sha1 = "56b0b7772676c499430dc8eb15cfab120c05a150" uuid = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" version = "0.15.3" [[deps.MakieCore]] deps = ["Observables"] git-tree-sha1 = "7bcc8323fb37523a6a51ade2234eee27a11114c8" uuid = "20f20a25-4f0e-4fdf-b5d1-57303727442b" version = "0.1.3" [[deps.MappedArrays]] git-tree-sha1 = "e8b359ef06ec72e8c030463fe02efe5527ee5142" uuid = "dbb5928d-eab1-5f90-85c2-b9b0edb7c900" version = "0.4.1" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.Match]] git-tree-sha1 = "1d9bc5c1a6e7ee24effb93f175c9342f9154d97f" uuid = "7eb4fadd-790c-5f42-8a69-bfa0b872bfbf" version = "1.2.0" [[deps.MathOptInterface]] deps = ["BenchmarkTools", "CodecBzip2", "CodecZlib", "JSON", "JSONSchema", "LinearAlgebra", "MutableArithmetics", "OrderedCollections", "SparseArrays", "Test", "Unicode"] git-tree-sha1 = "575644e3c05b258250bb599e57cf73bbf1062901" uuid = "b8f27783-ece8-5eb3-8dc8-9495eed66fee" version = "0.9.22" [[deps.MathProgBase]] deps = ["LinearAlgebra", "SparseArrays"] git-tree-sha1 = "9abbe463a1e9fc507f12a69e7f29346c2cdc472c" uuid = "fdba3010-5040-5b88-9595-932c9decdf73" version = "0.7.8" [[deps.MathTeXEngine]] deps = ["AbstractTrees", "Automa", "DataStructures", "FreeTypeAbstraction", "GeometryBasics", "LaTeXStrings", "REPL", "RelocatableFolders", "Test"] git-tree-sha1 = "70e733037bbf02d691e78f95171a1fa08cdc6332" uuid = "0a4f8689-d25c-4efe-a92b-7142dfc1aa53" version = "0.2.1" [[deps.MbedTLS]] deps = ["Dates", "MbedTLS_jll", "Random", "Sockets"] git-tree-sha1 = "1c38e51c3d08ef2278062ebceade0e46cefc96fe" uuid = "739be429-bea8-5141-9913-cc70e7f3736d" version = "1.0.3" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" [[deps.Measures]] git-tree-sha1 = "e498ddeee6f9fdb4551ce855a46f54dbd900245f" uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e" version = "0.3.1" [[deps.Media]] deps = ["MacroTools", "Test"] git-tree-sha1 = "75a54abd10709c01f1b86b84ec225d26e840ed58" uuid = "e89f7d12-3494-54d1-8411-f7d8b9ae1f27" version = "0.5.0" [[deps.MeshIO]] deps = ["ColorTypes", "FileIO", "GeometryBasics", "Printf"] git-tree-sha1 = "8be09d84a2d597c7c0c34d7d604c039c9763e48c" uuid = "7269a6da-0436-5bbc-96c2-40638cbb6118" version = "0.4.10" [[deps.MetaGraphs]] deps = ["Graphs", "JLD2", "Random"] git-tree-sha1 = "2af69ff3c024d13bde52b34a2a7d6887d4e7b438" uuid = "626554b9-1ddb-594c-aa3c-2596fe9399a5" version = "0.7.1" [[deps.Missings]] deps = ["DataAPI"] git-tree-sha1 = "bf210ce90b6c9eed32d25dbcae1ebc565df2687f" uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" version = "1.0.2" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.Mocking]] deps = ["Compat", "ExprTools"] git-tree-sha1 = "29714d0a7a8083bba8427a4fbfb00a540c681ce7" uuid = "78c3b35d-d492-501b-9361-3d52fe80e533" version = "0.7.3" [[deps.ModernGL]] deps = ["Libdl"] git-tree-sha1 = "344f8896e55541e30d5ccffcbf747c98ad57ca47" uuid = "66fc600b-dfda-50eb-8b99-91cfa97b1301" version = "1.1.4" [[deps.MosaicViews]] deps = ["MappedArrays", "OffsetArrays", "PaddedViews", "StackViews"] git-tree-sha1 = "b34e3bc3ca7c94914418637cb10cc4d1d80d877d" uuid = "e94cdb99-869f-56ef-bcf0-1ae2bcbe0389" version = "0.3.3" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" [[deps.MsgPack]] deps = ["Serialization"] git-tree-sha1 = "a8cbf066b54d793b9a48c5daa5d586cf2b5bd43d" uuid = "99f44e22-a591-53d1-9472-aa23ef4bd671" version = "1.1.0" [[deps.MutableArithmetics]] deps = ["LinearAlgebra", "SparseArrays", "Test"] git-tree-sha1 = "8d9496b2339095901106961f44718920732616bb" uuid = "d8a4904e-b15c-11e9-3269-09a3773c0cb0" version = "0.2.22" [[deps.NLSolversBase]] deps = ["DiffResults", "Distributed", "FiniteDiff", "ForwardDiff"] git-tree-sha1 = "50310f934e55e5ca3912fb941dec199b49ca9b68" uuid = "d41bc354-129a-5804-8e4c-c37616107c6c" version = "7.8.2" [[deps.NLopt]] deps = ["MathOptInterface", "MathProgBase", "NLopt_jll"] git-tree-sha1 = "d80cb3327d1aeef0f59eacf225e000f86e4eee0a" uuid = "76087f3c-5699-56af-9a33-bf431cd00edd" version = "0.6.3" [[deps.NLopt_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9b1f15a08f9d00cdb2761dcfa6f453f5d0d6f973" uuid = "079eb43e-fd8e-5478-9966-2cf3e3edb778" version = "2.7.1+0" [[deps.NaNMath]] git-tree-sha1 = "b086b7ea07f8e38cf122f5016af580881ac914fe" uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" version = "0.3.7" [[deps.NearestNeighbors]] deps = ["Distances", "StaticArrays"] git-tree-sha1 = "16baacfdc8758bc374882566c9187e785e85c2f0" uuid = "b8a86587-4115-5ab1-83bc-aa920d37bbce" version = "0.4.9" [[deps.Netpbm]] deps = ["FileIO", "ImageCore"] git-tree-sha1 = "18efc06f6ec36a8b801b23f076e3c6ac7c3bf153" uuid = "f09324ee-3d7c-5217-9330-fc30815ba969" version = "1.0.2" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" [[deps.Observables]] git-tree-sha1 = "fe29afdef3d0c4a8286128d4e45cc50621b1e43d" uuid = "510215fc-4207-5dde-b226-833fc4488ee2" version = "0.4.0" [[deps.OffsetArrays]] deps = ["Adapt"] git-tree-sha1 = "043017e0bdeff61cfbb7afeb558ab29536bbb5ed" uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881" version = "1.10.8" [[deps.Ogg_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "887579a3eb005446d514ab7aeac5d1d027658b8f" uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051" version = "1.3.5+1" [[deps.OpenBLAS32_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9c6c2ed4b7acd2137b878eb96c68e63b76199d0f" uuid = "656ef2d0-ae68-5445-9ca0-591084a874a2" version = "0.3.17+0" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" [[deps.OpenEXR]] deps = ["Colors", "FileIO", "OpenEXR_jll"] git-tree-sha1 = "327f53360fdb54df7ecd01e96ef1983536d1e633" uuid = "52e1d378-f018-4a11-a4be-720524705ac7" version = "0.3.2" [[deps.OpenEXR_jll]] deps = ["Artifacts", "Imath_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "923319661e9a22712f24596ce81c54fc0366f304" uuid = "18a262bb-aa17-5467-a713-aee519bc75cb" version = "3.1.1+0" [[deps.OpenLibm_jll]] deps = ["Artifacts", "Libdl"] uuid = "05823500-19ac-5b8b-9628-191a04bc5112" [[deps.OpenSSL_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "648107615c15d4e09f7eca16307bc821c1f718d8" uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" version = "1.1.13+0" [[deps.OpenSpecFun_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1" uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" version = "0.5.5+0" [[deps.OpticSim]] deps = ["CSV", "ColorSchemes", "ColorTypes", "Colors", "Conda", "DataFrames", "DelimitedFiles", "Distributions", "FileIO", "Format", "ForwardDiff", "GLMakie", "GeometryBasics", "HTTP", "ImageView", "Images", "InteractiveUtils", "Ipopt", "JSServe", "JuMP", "LazySets", "Libdl", "LinearAlgebra", "Luxor", "Makie", "MeshIO", "NLopt", "Optim", "PackageCompiler", "Pkg", "Plots", "Pluto", "PlutoUI", "Polynomials", "PyCall", "Random", "ReverseDiff", "Revise", "SHA", "StaticArrays", "Statistics", "StringEncodings", "Unitful", "WGLMakie", "ZipFile", "Zygote"] git-tree-sha1 = "92c4d80370ce21772bb041b333366bbf91495fbe" uuid = "24114763-4efb-45e7-af0e-cde916beb153" version = "0.5.3" [[deps.Optim]] deps = ["Compat", "FillArrays", "ForwardDiff", "LineSearches", "LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "PositiveFactorizations", "Printf", "SparseArrays", "StatsBase"] git-tree-sha1 = "045d10789f5daff18deb454d5923c6996017c2f3" uuid = "429524aa-4258-5aef-a3af-852621145aeb" version = "1.6.1" [[deps.Opus_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720" uuid = "91d4177d-7536-5919-b921-800302f37372" version = "1.3.2+0" [[deps.OrderedCollections]] git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c" uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" version = "1.4.1" [[deps.PCRE_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b2a7af664e098055a7529ad1a900ded962bca488" uuid = "2f80f16e-611a-54ab-bc61-aa92de5b98fc" version = "8.44.0+0" [[deps.PDMats]] deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"] git-tree-sha1 = "7e2166042d1698b6072352c74cfd1fca2a968253" uuid = "90014a1f-27ba-587c-ab20-58faa44d9150" version = "0.11.6" [[deps.PNGFiles]] deps = ["Base64", "CEnum", "ImageCore", "IndirectArrays", "OffsetArrays", "libpng_jll"] git-tree-sha1 = "eb4dbb8139f6125471aa3da98fb70f02dc58e49c" uuid = "f57f5aa1-a3ce-4bc8-8ab9-96f992907883" version = "0.3.14" [[deps.PackageCompiler]] deps = ["Artifacts", "LazyArtifacts", "Libdl", "Pkg", "Printf", "RelocatableFolders", "UUIDs"] git-tree-sha1 = "4ad92047603f8e955503f92767577b32508c39af" uuid = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d" version = "2.0.5" [[deps.Packing]] deps = ["GeometryBasics"] git-tree-sha1 = "1155f6f937fa2b94104162f01fa400e192e4272f" uuid = "19eb6ba3-879d-56ad-ad62-d5c202156566" version = "0.4.2" [[deps.PaddedViews]] deps = ["OffsetArrays"] git-tree-sha1 = "03a7a85b76381a3d04c7a1656039197e70eda03d" uuid = "5432bcbf-9aad-5242-b902-cca2824c8663" version = "0.5.11" [[deps.Pango_jll]] deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "3a121dfbba67c94a5bec9dde613c3d0cbcf3a12b" uuid = "36c8627f-9965-5494-a995-c6b170f724f3" version = "1.50.3+0" [[deps.Parameters]] deps = ["OrderedCollections", "UnPack"] git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe" uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a" version = "0.12.3" [[deps.Parsers]] deps = ["Dates"] git-tree-sha1 = "13468f237353112a01b2d6b32f3d0f80219944aa" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.2.2" [[deps.Pixman_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b4f5d02549a10e20780a24fce72bea96b6329e29" uuid = "30392449-352a-5448-841d-b1acce4e97dc" version = "0.40.1+0" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" [[deps.PkgVersion]] deps = ["Pkg"] git-tree-sha1 = "a7a7e1a88853564e551e4eba8650f8c38df79b37" uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688" version = "0.1.1" [[deps.PlotThemes]] deps = ["PlotUtils", "Requires", "Statistics"] git-tree-sha1 = "a3a964ce9dc7898193536002a6dd892b1b5a6f1d" uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a" version = "2.0.1" [[deps.PlotUtils]] deps = ["ColorSchemes", "Colors", "Dates", "Printf", "Random", "Reexport", "Statistics"] git-tree-sha1 = "6f1b25e8ea06279b5689263cc538f51331d7ca17" uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043" version = "1.1.3" [[deps.Plots]] deps = ["Base64", "Contour", "Dates", "Downloads", "FFMPEG", "FixedPointNumbers", "GR", "GeometryBasics", "JSON", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "PlotThemes", "PlotUtils", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "UUIDs", "UnicodeFun", "Unzip"] git-tree-sha1 = "5c907bdee5966a9adb8a106807b7c387e51e4d6c" uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" version = "1.25.11" [[deps.Pluto]] deps = ["Base64", "Configurations", "Dates", "Distributed", "FileWatching", "FuzzyCompletions", "HTTP", "InteractiveUtils", "Logging", "Markdown", "MsgPack", "Pkg", "REPL", "Sockets", "Tables", "UUIDs"] git-tree-sha1 = "7f99cb352c944ad28e3212ea9d887868c80e3d03" uuid = "c3e4b0f8-55cb-11ea-2926-15256bba5781" version = "0.17.7" [[deps.PlutoUI]] deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"] git-tree-sha1 = "85bf3e4bd279e405f91489ce518dedb1e32119cb" uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8" version = "0.7.35" [[deps.PolygonOps]] git-tree-sha1 = "77b3d3605fc1cd0b42d95eba87dfcd2bf67d5ff6" uuid = "647866c9-e3ac-4575-94e7-e3d426903924" version = "0.1.2" [[deps.Polynomials]] deps = ["Intervals", "LinearAlgebra", "MutableArithmetics", "RecipesBase"] git-tree-sha1 = "7499556d31417baeabaa55d266a449ffe4ec5a3e" uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45" version = "2.0.17" [[deps.PooledArrays]] deps = ["DataAPI", "Future"] git-tree-sha1 = "db3a23166af8aebf4db5ef87ac5b00d36eb771e2" uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" version = "1.4.0" [[deps.PositiveFactorizations]] deps = ["LinearAlgebra"] git-tree-sha1 = "17275485f373e6673f7e7f97051f703ed5b15b20" uuid = "85a6dd25-e78a-55b7-8502-1745935b8125" version = "0.2.4" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "de893592a221142f3db370f48290e3a2ef39998f" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.2.4" [[deps.PrettyTables]] deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"] git-tree-sha1 = "dfb54c4e414caa595a1f2ed759b160f5a3ddcba5" uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" version = "1.3.1" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.Profile]] deps = ["Printf"] uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79" [[deps.ProgressMeter]] deps = ["Distributed", "Printf"] git-tree-sha1 = "afadeba63d90ff223a6a48d2009434ecee2ec9e8" uuid = "92933f4c-e287-5a05-a399-4b506db050ca" version = "1.7.1" [[deps.PyCall]] deps = ["Conda", "Dates", "Libdl", "LinearAlgebra", "MacroTools", "Serialization", "VersionParsing"] git-tree-sha1 = "71fd4022ecd0c6d20180e23ff1b3e05a143959c2" uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0" version = "1.93.0" [[deps.Qt5Base_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "xkbcommon_jll"] git-tree-sha1 = "ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8" uuid = "ea2cea3b-5b76-57ae-a6ef-0a8af62496e1" version = "5.15.3+0" [[deps.QuadGK]] deps = ["DataStructures", "LinearAlgebra"] git-tree-sha1 = "78aadffb3efd2155af139781b8a8df1ef279ea39" uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc" version = "2.4.2" [[deps.Quaternions]] deps = ["DualNumbers", "LinearAlgebra", "Random"] git-tree-sha1 = "09eea2ccdfd03257d0a4977729613cee37935a8e" uuid = "94ee1d12-ae83-5a48-8b1c-48b8ff168ae0" version = "0.5.0" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA", "Serialization"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.RangeArrays]] git-tree-sha1 = "b9039e93773ddcfc828f12aadf7115b4b4d225f5" uuid = "b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d" version = "0.3.2" [[deps.Ratios]] deps = ["Requires"] git-tree-sha1 = "01d341f502250e81f6fec0afe662aa861392a3aa" uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439" version = "0.4.2" [[deps.Reactive]] deps = ["DataStructures", "Distributed", "Test"] git-tree-sha1 = "5862d915387ebb954016f50a88e34f79a9e5fcd2" uuid = "a223df75-4e93-5b7c-acf9-bdd599c0f4de" version = "0.8.3" [[deps.RealDot]] deps = ["LinearAlgebra"] git-tree-sha1 = "9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9" uuid = "c1ae055f-0cd5-4b69-90a6-9a35b1a98df9" version = "0.1.0" [[deps.RecipesBase]] git-tree-sha1 = "6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d" uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" version = "1.2.1" [[deps.RecipesPipeline]] deps = ["Dates", "NaNMath", "PlotUtils", "RecipesBase"] git-tree-sha1 = "995a812c6f7edea7527bb570f0ac39d0fb15663c" uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c" version = "0.5.1" [[deps.Reexport]] git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.2.2" [[deps.RegionTrees]] deps = ["IterTools", "LinearAlgebra", "StaticArrays"] git-tree-sha1 = "4618ed0da7a251c7f92e869ae1a19c74a7d2a7f9" uuid = "dee08c22-ab7f-5625-9660-a9af2021b33f" version = "0.3.2" [[deps.RelocatableFolders]] deps = ["SHA", "Scratch"] git-tree-sha1 = "cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca" uuid = "05181044-ff0b-4ac5-8273-598c1e38db00" version = "0.1.3" [[deps.Requires]] deps = ["UUIDs"] git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.3.0" [[deps.ReverseDiff]] deps = ["ChainRulesCore", "DiffResults", "DiffRules", "ForwardDiff", "FunctionWrappers", "LinearAlgebra", "LogExpFunctions", "MacroTools", "NaNMath", "Random", "SpecialFunctions", "StaticArrays", "Statistics"] git-tree-sha1 = "8d85c98fc33d4d37d88c8f9ccee4f1f3f98e56f4" uuid = "37e2e3b7-166d-5795-8a7a-e32c996b4267" version = "1.12.0" [[deps.Revise]] deps = ["CodeTracking", "Distributed", "FileWatching", "JuliaInterpreter", "LibGit2", "LoweredCodeUtils", "OrderedCollections", "Pkg", "REPL", "Requires", "UUIDs", "Unicode"] git-tree-sha1 = "606ddc4d3d098447a09c9337864c73d017476424" uuid = "295af30f-e4ad-537b-8983-00126c2a3abe" version = "3.3.2" [[deps.Rmath]] deps = ["Random", "Rmath_jll"] git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f" uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa" version = "0.7.0" [[deps.Rmath_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7" uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f" version = "0.3.0+0" [[deps.Rotations]] deps = ["LinearAlgebra", "Quaternions", "Random", "StaticArrays", "Statistics"] git-tree-sha1 = "a167638e2cbd8ac41f9cd57282cab9b042fa26e6" uuid = "6038ab10-8711-5258-84ad-4b1120ba62dc" version = "1.3.0" [[deps.RoundingEmulator]] git-tree-sha1 = "40b9edad2e5287e05bd413a38f61a8ff55b9557b" uuid = "5eaf0fd0-dfba-4ccb-bf02-d820a40db705" version = "0.2.1" [[deps.RoundingIntegers]] git-tree-sha1 = "99acd97f396ea71a5be06ba6de5c9defe188a778" uuid = "d5f540fe-1c90-5db3-b776-2e2f362d9394" version = "1.1.0" [[deps.Rsvg]] deps = ["Cairo", "Glib_jll", "Librsvg_jll"] git-tree-sha1 = "3d3dc66eb46568fb3a5259034bfc752a0eb0c686" uuid = "c4c386cf-5103-5370-be45-f3a111cca3b8" version = "1.0.0" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" [[deps.SIMD]] git-tree-sha1 = "39e3df417a0dd0c4e1f89891a281f82f5373ea3b" uuid = "fdea26ae-647d-5447-a871-4b548cad5224" version = "3.4.0" [[deps.ScanByte]] deps = ["Libdl", "SIMD"] git-tree-sha1 = "9cc2955f2a254b18be655a4ee70bc4031b2b189e" uuid = "7b38b023-a4d7-4c5e-8d43-3f3097f304eb" version = "0.3.0" [[deps.Scratch]] deps = ["Dates"] git-tree-sha1 = "0b4b7f1393cff97c33891da2a0bf69c6ed241fda" uuid = "6c6a2e73-6563-6170-7368-637461726353" version = "1.1.0" [[deps.SentinelArrays]] deps = ["Dates", "Random"] git-tree-sha1 = "6a2f7d70512d205ca8c7ee31bfa9f142fe74310c" uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" version = "1.3.12" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.SetRounding]] git-tree-sha1 = "d7a25e439d07a17b7cdf97eecee504c50fedf5f6" uuid = "3cc68bcd-71a2-5612-b932-767ffbe40ab0" version = "0.2.1" [[deps.ShaderAbstractions]] deps = ["ColorTypes", "FixedPointNumbers", "GeometryBasics", "LinearAlgebra", "Observables", "StaticArrays", "StructArrays", "Tables"] git-tree-sha1 = "0d97c895406b552bed78f3a1fe9925248e908ae2" uuid = "65257c39-d410-5151-9873-9b3e5be5013e" version = "0.2.8" [[deps.SharedArrays]] deps = ["Distributed", "Mmap", "Random", "Serialization"] uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [[deps.Showoff]] deps = ["Dates", "Grisu"] git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de" uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f" version = "1.0.3" [[deps.SignedDistanceFields]] deps = ["Random", "Statistics", "Test"] git-tree-sha1 = "d263a08ec505853a5ff1c1ebde2070419e3f28e9" uuid = "73760f76-fbc4-59ce-8f25-708e95d2df96" version = "0.4.0" [[deps.SimpleTraits]] deps = ["InteractiveUtils", "MacroTools"] git-tree-sha1 = "5d7e3f4e11935503d3ecaf7186eac40602e7d231" uuid = "699a6c99-e7fa-54fc-8d76-47d257e15c1d" version = "0.9.4" [[deps.SimpleWeightedGraphs]] deps = ["Graphs", "LinearAlgebra", "Markdown", "SparseArrays", "Test"] git-tree-sha1 = "a6f404cc44d3d3b28c793ec0eb59af709d827e4e" uuid = "47aef6b3-ad0c-573a-a1e2-d07658019622" version = "1.2.1" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SortingAlgorithms]] deps = ["DataStructures"] git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508" uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" version = "1.0.1" [[deps.SparseArrays]] deps = ["LinearAlgebra", "Random"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [[deps.SpecialFunctions]] deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"] git-tree-sha1 = "85e5b185ed647b8ee89aa25a7788a2b43aa8a74f" uuid = "276daf66-3868-5448-9aa4-cd146d93841b" version = "2.1.3" [[deps.StackViews]] deps = ["OffsetArrays"] git-tree-sha1 = "46e589465204cd0c08b4bd97385e4fa79a0c770c" uuid = "cae243ae-269e-4f55-b966-ac2d0dc13c15" version = "0.1.1" [[deps.Static]] deps = ["IfElse"] git-tree-sha1 = "00b725fffc9a7e9aac8850e4ed75b4c1acbe8cd2" uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3" version = "0.5.5" [[deps.StaticArrays]] deps = ["LinearAlgebra", "Random", "Statistics"] git-tree-sha1 = "6354dfaf95d398a1a70e0b28238321d5d17b2530" uuid = "90137ffa-7385-5640-81b9-e52037218182" version = "1.4.0" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [[deps.StatsAPI]] deps = ["LinearAlgebra"] git-tree-sha1 = "c3d8ba7f3fa0625b062b82853a7d5229cb728b6b" uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" version = "1.2.1" [[deps.StatsBase]] deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] git-tree-sha1 = "8977b17906b0a1cc74ab2e3a05faa16cf08a8291" uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" version = "0.33.16" [[deps.StatsFuns]] deps = ["ChainRulesCore", "HypergeometricFunctions", "InverseFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"] git-tree-sha1 = "25405d7016a47cf2bd6cd91e66f4de437fd54a07" uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c" version = "0.9.16" [[deps.StringEncodings]] deps = ["Libiconv_jll"] git-tree-sha1 = "50ccd5ddb00d19392577902f0079267a72c5ab04" uuid = "69024149-9ee7-55f6-a4c4-859efe599b68" version = "0.3.5" [[deps.StructArrays]] deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"] git-tree-sha1 = "57617b34fa34f91d536eb265df67c2d4519b8b98" uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a" version = "0.6.5" [[deps.StructTypes]] deps = ["Dates", "UUIDs"] git-tree-sha1 = "d24a825a95a6d98c385001212dc9020d609f2d4f" uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" version = "1.8.1" [[deps.SuiteSparse]] deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"] uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" [[deps.TableTraits]] deps = ["IteratorInterfaceExtensions"] git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" version = "1.0.1" [[deps.Tables]] deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"] git-tree-sha1 = "bb1064c9a84c52e277f1096cf41434b675cd368b" uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" version = "1.6.1" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" [[deps.TensorCore]] deps = ["LinearAlgebra"] git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" version = "0.1.1" [[deps.Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[deps.TiffImages]] deps = ["ColorTypes", "DataStructures", "DocStringExtensions", "FileIO", "FixedPointNumbers", "IndirectArrays", "Inflate", "OffsetArrays", "PkgVersion", "ProgressMeter", "UUIDs"] git-tree-sha1 = "991d34bbff0d9125d93ba15887d6594e8e84b305" uuid = "731e570b-9d59-4bfa-96dc-6df516fadf69" version = "0.5.3" [[deps.TiledIteration]] deps = ["OffsetArrays"] git-tree-sha1 = "5683455224ba92ef59db72d10690690f4a8dc297" uuid = "06e1c1a7-607b-532d-9fad-de7d9aa2abac" version = "0.3.1" [[deps.TimeZones]] deps = ["Dates", "Downloads", "InlineStrings", "LazyArtifacts", "Mocking", "Printf", "RecipesBase", "Serialization", "Unicode"] git-tree-sha1 = "0f1017f68dc25f1a0cb99f4988f78fe4f2e7955f" uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53" version = "1.7.1" [[deps.TranscodingStreams]] deps = ["Random", "Test"] git-tree-sha1 = "216b95ea110b5972db65aa90f88d8d89dcb8851c" uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" version = "0.9.6" [[deps.URIs]] git-tree-sha1 = "97bbe755a53fe859669cd907f2d96aee8d2c1355" uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" version = "1.3.0" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.UnPack]] git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b" uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed" version = "1.0.2" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.UnicodeFun]] deps = ["REPL"] git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf" uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1" version = "0.4.1" [[deps.Unitful]] deps = ["ConstructionBase", "Dates", "LinearAlgebra", "Random"] git-tree-sha1 = "b649200e887a487468b71821e2644382699f1b0f" uuid = "1986cc42-f94f-5a68-af5c-568840ba703d" version = "1.11.0" [[deps.Unzip]] git-tree-sha1 = "34db80951901073501137bdbc3d5a8e7bbd06670" uuid = "41fe7b60-77ed-43a1-b4f0-825fd5a5650d" version = "0.1.2" [[deps.VersionParsing]] git-tree-sha1 = "58d6e80b4ee071f5efd07fda82cb9fbe17200868" uuid = "81def892-9a0e-5fdd-b105-ffc91e053289" version = "1.3.0" [[deps.WGLMakie]] deps = ["Colors", "FileIO", "FreeTypeAbstraction", "GeometryBasics", "Hyperscript", "ImageMagick", "JSServe", "LinearAlgebra", "Makie", "Observables", "ShaderAbstractions", "StaticArrays"] git-tree-sha1 = "716e15ba27090a96c2f3afc16a464c9a280089cd" uuid = "276b4fcb-3e11-5398-bf8b-a0c2d153d008" version = "0.4.7" [[deps.Wayland_jll]] deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg", "XML2_jll"] git-tree-sha1 = "3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23" uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89" version = "1.19.0+0" [[deps.Wayland_protocols_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4528479aa01ee1b3b4cd0e6faef0e04cf16466da" uuid = "2381bf8a-dfd0-557d-9999-79630e7b1b91" version = "1.25.0+0" [[deps.WeakRefStrings]] deps = ["DataAPI", "InlineStrings", "Parsers"] git-tree-sha1 = "c69f9da3ff2f4f02e811c3323c22e5dfcb584cfa" uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5" version = "1.4.1" [[deps.WebSockets]] deps = ["Base64", "Dates", "HTTP", "Logging", "Sockets"] git-tree-sha1 = "f91a602e25fe6b89afc93cf02a4ae18ee9384ce3" uuid = "104b5d7c-a370-577a-8038-80a2059c5097" version = "1.5.9" [[deps.WidgetsBase]] deps = ["Observables"] git-tree-sha1 = "c1ef6e02bc457c3b23aafc765b94c3dcd25f174d" uuid = "eead4739-05f7-45a1-878c-cee36b57321c" version = "0.1.3" [[deps.WoodburyMatrices]] deps = ["LinearAlgebra", "SparseArrays"] git-tree-sha1 = "de67fa59e33ad156a590055375a30b23c40299d3" uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6" version = "0.5.5" [[deps.XML2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a" uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a" version = "2.9.12+0" [[deps.XSLT_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"] git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a" uuid = "aed1982a-8fda-507f-9586-7b0439959a61" version = "1.1.34+0" [[deps.Xorg_libX11_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"] git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527" uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc" version = "1.6.9+4" [[deps.Xorg_libXau_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e" uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec" version = "1.0.9+4" [[deps.Xorg_libXcomposite_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll"] git-tree-sha1 = "7c688ca9c957837539bbe1c53629bb871025e423" uuid = "3c9796d7-64a0-5134-86ad-79f8eb684845" version = "0.4.5+4" [[deps.Xorg_libXcursor_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"] git-tree-sha1 = "12e0eb3bc634fa2080c1c37fccf56f7c22989afd" uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724" version = "1.2.0+4" [[deps.Xorg_libXdamage_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll"] git-tree-sha1 = "fe4ffb2024ba3eddc862c6e1d70e2b070cd1c2bf" uuid = "0aeada51-83db-5f97-b67e-184615cfc6f6" version = "1.1.5+4" [[deps.Xorg_libXdmcp_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4" uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05" version = "1.1.3+4" [[deps.Xorg_libXext_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3" uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3" version = "1.3.4+4" [[deps.Xorg_libXfixes_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "0e0dc7431e7a0587559f9294aeec269471c991a4" uuid = "d091e8ba-531a-589c-9de9-94069b037ed8" version = "5.0.3+4" [[deps.Xorg_libXi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll"] git-tree-sha1 = "89b52bc2160aadc84d707093930ef0bffa641246" uuid = "a51aa0fd-4e3c-5386-b890-e753decda492" version = "1.7.10+4" [[deps.Xorg_libXinerama_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll"] git-tree-sha1 = "26be8b1c342929259317d8b9f7b53bf2bb73b123" uuid = "d1454406-59df-5ea1-beac-c340f2130bc3" version = "1.1.4+4" [[deps.Xorg_libXrandr_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll"] git-tree-sha1 = "34cea83cb726fb58f325887bf0612c6b3fb17631" uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484" version = "1.5.2+4" [[deps.Xorg_libXrender_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96" uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa" version = "0.9.10+4" [[deps.Xorg_libXtst_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll"] git-tree-sha1 = "0c0a60851f44add2a64069ddf213e941c30ed93c" uuid = "b6f176f1-7aea-5357-ad67-1d3e565ea1c6" version = "1.2.3+4" [[deps.Xorg_libpthread_stubs_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb" uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74" version = "0.1.0+3" [[deps.Xorg_libxcb_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"] git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6" uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b" version = "1.13.0+3" [[deps.Xorg_libxkbfile_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "926af861744212db0eb001d9e40b5d16292080b2" uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a" version = "1.1.0+4" [[deps.Xorg_xcb_util_image_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "0fab0a40349ba1cba2c1da699243396ff8e94b97" uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b" version = "0.4.0+1" [[deps.Xorg_xcb_util_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll"] git-tree-sha1 = "e7fd7b2881fa2eaa72717420894d3938177862d1" uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5" version = "0.4.0+1" [[deps.Xorg_xcb_util_keysyms_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "d1151e2c45a544f32441a567d1690e701ec89b00" uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7" version = "0.4.0+1" [[deps.Xorg_xcb_util_renderutil_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "dfd7a8f38d4613b6a575253b3174dd991ca6183e" uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e" version = "0.3.9+1" [[deps.Xorg_xcb_util_wm_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"] git-tree-sha1 = "e78d10aab01a4a154142c5006ed44fd9e8e31b67" uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361" version = "0.4.1+1" [[deps.Xorg_xkbcomp_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxkbfile_jll"] git-tree-sha1 = "4bcbf660f6c2e714f87e960a171b119d06ee163b" uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4" version = "1.4.2+4" [[deps.Xorg_xkeyboard_config_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xkbcomp_jll"] git-tree-sha1 = "5c8424f8a67c3f2209646d4425f3d415fee5931d" uuid = "33bec58e-1273-512f-9401-5d533626f822" version = "2.27.0+4" [[deps.Xorg_xtrans_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845" uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10" version = "1.4.0+3" [[deps.ZipFile]] deps = ["Libdl", "Printf", "Zlib_jll"] git-tree-sha1 = "3593e69e469d2111389a9bd06bac1f3d730ac6de" uuid = "a5390f91-8eb1-5f08-bee0-b1d1ffed6cea" version = "0.9.4" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" [[deps.Zstd_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "e45044cd873ded54b6a5bac0eb5c971392cf1927" uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" version = "1.5.2+0" [[deps.Zygote]] deps = ["AbstractFFTs", "ChainRules", "ChainRulesCore", "DiffRules", "Distributed", "FillArrays", "ForwardDiff", "IRTools", "InteractiveUtils", "LinearAlgebra", "MacroTools", "NaNMath", "Random", "Requires", "SparseArrays", "SpecialFunctions", "Statistics", "ZygoteRules"] git-tree-sha1 = "93285d2877f1f1b09b2a2b029f90e9db10127022" uuid = "e88e6eb3-aa80-5325-afca-941959d7151f" version = "0.6.35" [[deps.ZygoteRules]] deps = ["MacroTools"] git-tree-sha1 = "8c1a8e4dfacb1fd631745552c8db35d0deb09ea0" uuid = "700de1a5-db45-46bc-99cf-38207098b444" version = "0.2.2" [[deps.adwaita_icon_theme_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "hicolor_icon_theme_jll"] git-tree-sha1 = "37c9a36ccb876e02876c8a654f1b2e8c1b443a78" uuid = "b437f822-2cd6-5e08-a15c-8bac984d38ee" version = "3.33.92+5" [[deps.at_spi2_atk_jll]] deps = ["ATK_jll", "Artifacts", "JLLWrappers", "Libdl", "Pkg", "XML2_jll", "Xorg_libX11_jll", "at_spi2_core_jll"] git-tree-sha1 = "f16ae690aca4761f33d2cb338ee9899e541f5eae" uuid = "de012916-1e3f-58c2-8f29-df3ef51d412d" version = "2.34.1+4" [[deps.at_spi2_core_jll]] deps = ["Artifacts", "Dbus_jll", "Glib_jll", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXtst_jll"] git-tree-sha1 = "d2d540cd145f2b2933614649c029d222fe125188" uuid = "0fc3237b-ac94-5853-b45c-d43d59a06200" version = "2.34.0+4" [[deps.gdk_pixbuf_jll]] deps = ["Artifacts", "Glib_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pkg", "Xorg_libX11_jll", "libpng_jll"] git-tree-sha1 = "c23323cd30d60941f8c68419a70905d9bdd92808" uuid = "da03df04-f53b-5353-a52f-6a8b0620ced0" version = "2.42.6+1" [[deps.hicolor_icon_theme_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b458a6f6fc2b1a8ca74ed63852e4eaf43fb9f5ea" uuid = "059c91fe-1bad-52ad-bddd-f7b78713c282" version = "0.17.0+3" [[deps.iso_codes_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "5ee24c3ae30e006117ec2da5ea50f2ce457c019a" uuid = "bf975903-5238-5d20-8243-bc370bc1e7e5" version = "4.3.0+4" [[deps.isoband_jll]] deps = ["Libdl", "Pkg"] git-tree-sha1 = "a1ac99674715995a536bbce674b068ec1b7d893d" uuid = "9a68df92-36a6-505f-a73e-abb412b6bfb4" version = "0.2.2+0" [[deps.libass_jll]] deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "5982a94fcba20f02f42ace44b9894ee2b140fe47" uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0" version = "0.15.1+0" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl", "OpenBLAS_jll"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" [[deps.libfdk_aac_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55" uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280" version = "2.0.2+0" [[deps.libpng_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c" uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f" version = "1.6.38+0" [[deps.libvorbis_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"] git-tree-sha1 = "b910cb81ef3fe6e78bf6acee440bda86fd6ae00c" uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a" version = "1.3.7+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" [[deps.x264_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2" uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a" version = "2021.5.5+0" [[deps.x265_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9" uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76" version = "3.5.0+0" [[deps.xkbcommon_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll", "Wayland_protocols_jll", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"] git-tree-sha1 = "ece2350174195bb31de1a63bea3a41ae1aa593b6" uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd" version = "0.9.1+5" """ # ╔═╡ Cell order: # ╟─6ce01760-879e-11eb-2b13-4d3d07c4b4ce # ╟─87954830-8854-11eb-2baf-d3b79b804e07 # ╟─9608ed90-8854-11eb-080d-4d1f60d596f5 # ╟─d970a5b0-8858-11eb-1425-cdfb68e222ba # ╟─f21787a0-8858-11eb-19b1-914e835922eb # ╠═e92e18de-8847-11eb-2fdf-b90425c7327b # ╠═544d5870-8848-11eb-385e-afcce49d099d # ╠═78875510-8848-11eb-18d6-eba32897a99e # ╠═5efca830-885b-11eb-3f76-3d9ac33369d8 # ╠═69f94f40-885b-11eb-08b0-e9faf7969dda # ╠═ac0ee1b0-885b-11eb-0395-a19b37c5a472 # ╠═e14e85c0-8846-11eb-1f4a-2768e655321c # ╟─4d265a60-885c-11eb-2b6d-7b244ccfd172 # ╟─4553fb50-88d7-11eb-3fc3-6ddfeb3f1910 # ╠═69d61a60-885c-11eb-3f97-75e98121ec8c # ╠═0ae26f80-885d-11eb-2c2a-ad23b34daac1 # ╟─fd3287f0-885f-11eb-279d-990c4222ba83 # ╟─03fc33b0-8860-11eb-2a20-0f8c2b1f79a3 # ╟─94bffc60-8860-11eb-37ca-b3203b46693a # ╠═b39c3952-8860-11eb-13a4-0b5004282a09 # ╠═941bb0a0-8861-11eb-09fd-87e2022e068e # ╟─04d97450-8860-11eb-2bda-036792395ee4 # ╟─0b6553c2-8860-11eb-0c5e-89632a8dd612 # ╟─a891a210-87bc-11eb-311d-4d020986fe19 # ╠═def239f0-87bc-11eb-2edb-2f859ac41bee # ╟─5f77cfd0-8854-11eb-377c-ef975f9abf63 # ╟─67c8fac0-974e-11eb-2898-d14b79387954 # ╟─d6c83680-879e-11eb-31d4-7dbda7e93e48 # ╟─68e9b210-87ad-11eb-0f3a-5bb2dbf7d86c # ╟─3a5d3ba0-87ae-11eb-1717-93be0b802cab # ╟─96e423a0-885a-11eb-02a3-8704e8dbdab6 # ╟─00000000-0000-0000-0000-000000000001 # ╟─00000000-0000-0000-0000-000000000002
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
10006
### A Pluto.jl notebook ### # v0.12.21 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing el end end # ╔═╡ 520e8300-9751-11eb-392f-65d015cad73d begin init_notebook = true using OpticSim, OpticSim.Geometry, OpticSim.Emitters import OpticSim.NotebooksUtils as NB NB.InitNotebook() end # ╔═╡ a891a210-87bc-11eb-311d-4d020986fe19 begin using DataFrames # defining the optical system sys_cooke = AxisymmetricOpticalSystem( DataFrame(SurfaceType= ["Object", "Standard", "Standard", "Standard", "Stop", "Standard", "Standard", "Image"], Radius = [Inf, 26.777, 66.604, -35.571, 35.571, 35.571, -26.777, Inf], Thickness = [Inf, 4.0, 2.0, 4.0, 2.0, 4.0, 44.748, missing], Material = [OpticSim.GlassCat.Air, OpticSim.Examples.Examples_N_SK16, OpticSim.GlassCat.Air, OpticSim.Examples.Examples_N_SF2, OpticSim.GlassCat.Air, OpticSim.Examples.Examples_N_SK16, OpticSim.GlassCat.Air, missing], SemiDiameter = [Inf, 8.580, 7.513, 7.054, 6.033, 7.003, 7.506, 15.0])) @show sys_cooke end # ╔═╡ d6c83680-879e-11eb-31d4-7dbda7e93e48 begin init_notebook import PlutoUI using Makie defs = OpticSim.NotebooksUtils.Defs("ran") NB.DefsClearHTML(defs) # this function is needed to allow the visualization scene to be displayed inside a pluto notebook function Makie.display(obj) # @info "RG: $obj" return obj end #text of this cell to appear in the notebook NB.DefsAddHTML(defs, NB.HTMLFromObj(md"Basic Initialization (code)")) PlutoUI.Show(MIME"text/html"(), NB.DefsHTML(defs)) end # ╔═╡ 6ce01760-879e-11eb-2b13-4d3d07c4b4ce md"# Various Examples" # ╔═╡ 0d8de290-8ba1-11eb-0ae9-79fed06aae32 md"## Zoom Lenses" # ╔═╡ e88e92c0-8ba3-11eb-11ba-d7e44bf5373e md"## Focusing" # ╔═╡ 576fb1c0-8ba3-11eb-1c10-fdb51172e2c9 md"## Lens Construction" # ╔═╡ 0b6553c2-8860-11eb-0c5e-89632a8dd612 md"## Cooke Triplet Example" # ╔═╡ 5f77cfd0-8854-11eb-377c-ef975f9abf63 md"## Initialization Stuff - Can be ignored" # ╔═╡ 68e9b210-87ad-11eb-0f3a-5bb2dbf7d86c begin NB.DefsClearHTML(defs) default_resolution_info = NB.GetVarInfo( @bind default_resolution PlutoUI.Select(["Small", "Medium", "Large"], default="Medium") ) makie_backend_info = NB.GetVarInfo( @bind makie_backend PlutoUI.Select(["Static", "Web"], default="Static") ) show_toc_info = NB.GetVarInfo( @bind show_toc PlutoUI.CheckBox(default=true) ) fb3_items = [ "Options", "@ Drawings Size $(default_resolution_info.html)", "Document Options", "@ $(show_toc_info.html) Show Table Of Content", "@ Makie Backend $(makie_backend_info.html) <i><b>(Leave as Static for now)</b></i>", ] NB.DefsAddHTML(defs, NB.HTMLFloatingBox( fb3_items, name="plutoui-docmenu", header="Document Menu", width="25%", top="45%", ) ) # wide document layout NB.DefsAddHTML(defs, NB.HTMLNewDocLayout()) # add TOC NB.DefsAddHTML(defs, NB.HTMLFromObj( PlutoUI.TableOfContents(title = "Document Table of Content", depth = 4) )* NB.HTMLFixTOC() ) #text of this cell to appear in the notebook NB.DefsAddHTML(defs, NB.HTMLFromObj(md"Define Floating Menu, TOC and New Layout (code)")) PlutoUI.Show(MIME"text/html"(), NB.DefsHTML(defs)) end # ╔═╡ 3a5d3ba0-87ae-11eb-1717-93be0b802cab begin drawing = 1 OpticSim.NotebooksUtils.SetBackend(defs, makie_backend) md"Set Makie backend" end # ╔═╡ 5db83180-8ba1-11eb-0364-ad9cfed99509 begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL # glass entrance lens on telescope topsurf = Plane(OpticSim.SVector(0.0, 0.0, 1.0), OpticSim.SVector(0.0, 0.0, 0.0), interface = FresnelInterface{Float64}(OpticSim.Examples.Examples_N_BK7, OpticSim.GlassCat.Air), vishalfsizeu = 12.00075, vishalfsizev = 12.00075) botsurf = AcceleratedParametricSurface(ZernikeSurface(12.00075, radius = -1.14659768e+4, aspherics = [(4, 3.68090959e-7), (6, 2.73643352e-11), (8, 3.20036892e-14)]), 17, interface = FresnelInterface{Float64}(OpticSim.Examples.Examples_N_BK7, OpticSim.GlassCat.Air)) coverlens = Cylinder(12.00075, 1.4) ∩ topsurf ∩ leaf(botsurf, Transform(OpticSim.rotmatd(0, 180, 0), OpticSim.SVector(0.0, 0.0, -0.65))) # big mirror with a hole in it bigmirror = ConicLens(OpticSim.Examples.Examples_N_BK7, -72.65, -95.2773500000134, 0.077235, Inf, 0.0, 0.2, 12.18263, frontsurfacereflectance = 1.0) bigmirror = bigmirror - leaf(Cylinder(4.0, 0.3, interface = opaqueinterface()), OpticSim.translation(0.0, 0.0, -72.75)) # small mirror supported on a spider smallmirror = SphericalLens(OpticSim.Examples.Examples_N_BK7, -40.65, Inf, -49.6845, 1.13365, 4.3223859, backsurfacereflectance = 1.0) obscuration1 = OpticSim.Circle(4.5, OpticSim.SVector(0.0, 0.0, 1.0), OpticSim.SVector(0.0, 0.0, -40.649), interface = opaqueinterface()) obscurations2 = Spider(3, 0.5, 12.0, OpticSim.SVector(0.0, 0.0, -40.65)) # put it together with the detector la = LensAssembly(coverlens(), bigmirror(), smallmirror(), obscuration1, obscurations2...) det = OpticSim.Circle(3.0, OpticSim.SVector(0.0, 0.0, 1.0), OpticSim.SVector(0.0, 0.0, -92.4542988), interface = opaqueinterface()) tele = CSGOpticalSystem(la, det) Vis.drawtracerays(tele, raygenerator = UniformOpticalSource(CollimatedSource(GridRectOriginPoints(5, 5, 10.0, 10.0, position = OpticSim.SVector(0.0, 0.0, 20.0))), 0.55), trackallrays = true, colorbynhits = true, test = true) end # ╔═╡ f08a07c0-8ba3-11eb-382a-23dc079b623a begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local rect = Rectangle(5.0, 5.0, OpticSim.SVector(0.0, 0.0, 1.0), OpticSim.SVector(0.0, 0.0, 0.0)) local int = HologramInterface(OpticSim.SVector(0.0, -3.0, -20.0), ConvergingBeam, OpticSim.SVector(0.0, 0.0, -1.0), CollimatedBeam, 0.55, 9.0, OpticSim.GlassCat.Air, OpticSim.Examples.Examples_N_BK7, OpticSim.GlassCat.Air, OpticSim.GlassCat.Air, OpticSim.GlassCat.Air, 0.05, false) local obj = HologramSurface(rect, int) local sys = CSGOpticalSystem(LensAssembly(obj), Rectangle(10.0, 10.0, OpticSim.SVector(0.0, 0.0, 1.0), OpticSim.SVector(0.0, 0.0, -25.0), interface = opaqueinterface())) Vis.drawtracerays(sys; raygenerator = UniformOpticalSource(CollimatedSource(GridRectOriginPoints(5, 5, 3.0, 3.0, position = OpticSim.SVector(0.0, 0.0, 10.0), direction = OpticSim.SVector(0.0, 0.0, -1.0))), 0.55), trackallrays = true, rayfilter = nothing, test = true) end # ╔═╡ 5e2debd0-8ba3-11eb-0c4e-09d110230e2d begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL topsurface = leaf(AcceleratedParametricSurface(QTypeSurface(9.0, radius = -25.0, conic = 0.3, αcoeffs = [(1, 0, 0.3), (1, 1, 1.0)], βcoeffs = [(1, 0, -0.1), (2, 0, 0.4), (3, 0, -0.6)], normradius = 9.5), interface = FresnelInterface{Float64}(OpticSim.Examples.Examples_N_BK7, OpticSim.GlassCat.Air)), OpticSim.translation(0.0, 0.0, 5.0)) botsurface = leaf(Plane(0.0, 0.0, -1.0, 0.0, 0.0, -5.0, vishalfsizeu = 9.5, vishalfsizev = 9.5, interface = FresnelInterface{Float64}(OpticSim.Examples.Examples_N_BK7, OpticSim.GlassCat.Air))) barrel = leaf(Cylinder(9.0, 20.0, interface = FresnelInterface{Float64}(OpticSim.Examples.Examples_N_BK7, OpticSim.GlassCat.Air, reflectance = zero(Float64), transmission = zero(Float64)))) lens = (barrel ∩ topsurface ∩ botsurface)(Transform(0.0, Float64(π), 0.0, 0.0, 0.0, -5.0)) sys = CSGOpticalSystem(LensAssembly(lens), Rectangle(15.0, 15.0, [0.0, 0.0, 1.0], [0.0, 0.0, -67.8], interface = opaqueinterface())) Vis.drawtracerays(sys, test = true, trackallrays = true) end # ╔═╡ def239f0-87bc-11eb-2edb-2f859ac41bee begin drawing # notebook only - create dependency on drawing backend - comment if running in REPL local s1 = Sources.Source(sourcenum = 1, origins=Origins.Hexapolar(5, 8.0, 8.0), directions=Directions.Constant()) # create a second source and rotate it by -5 degs local s2 = Sources.Source(sourcenum = 2, origins=Origins.Hexapolar(5, 8.0, 8.0), directions=Directions.Constant(), transform=Transform(zero(Geometry.Vec3), rotationY(deg2rad(-8)) * unitZ3())) # create the "ray generator" local combined_sources = Sources.CompositeSource(Transform(Geometry.Vec3(0.0, 0.0, 10.0), unitZ3() * -1), [s1 s2]) # and draw the system + the generated rays Vis.drawtracerays(sys_cooke, raygenerator = combined_sources, test = true, trackallrays = true, colorbysourcenum = true, drawgen = false) end # ╔═╡ 96e423a0-885a-11eb-02a3-8704e8dbdab6 begin function Vis.scene(resolution = (1000, 1000)) # @info "RG: Vis.Scene Replacement" scene, layout = Makie.layoutscene(resolution = resolution) Vis.set_current_main_scene(scene) lscene = layout[1, 1] = Makie.LScene(scene, scenekw = (camera = Makie.cam3d_cad!, axis_type = Makie.axis3d!, raw = false)) Vis.set_current_3d_scene(lscene) return scene, lscene end function resolution() if (default_resolution == "Small") return (300, 300) elseif (default_resolution == "Medium") return (500, 500) else return (1000, 1000) end end end # ╔═╡ Cell order: # ╟─6ce01760-879e-11eb-2b13-4d3d07c4b4ce # ╟─0d8de290-8ba1-11eb-0ae9-79fed06aae32 # ╠═5db83180-8ba1-11eb-0364-ad9cfed99509 # ╟─e88e92c0-8ba3-11eb-11ba-d7e44bf5373e # ╠═f08a07c0-8ba3-11eb-382a-23dc079b623a # ╟─576fb1c0-8ba3-11eb-1c10-fdb51172e2c9 # ╠═5e2debd0-8ba3-11eb-0c4e-09d110230e2d # ╟─0b6553c2-8860-11eb-0c5e-89632a8dd612 # ╟─a891a210-87bc-11eb-311d-4d020986fe19 # ╠═def239f0-87bc-11eb-2edb-2f859ac41bee # ╟─5f77cfd0-8854-11eb-377c-ef975f9abf63 # ╟─520e8300-9751-11eb-392f-65d015cad73d # ╟─d6c83680-879e-11eb-31d4-7dbda7e93e48 # ╟─68e9b210-87ad-11eb-0f3a-5bb2dbf7d86c # ╟─3a5d3ba0-87ae-11eb-1717-93be0b802cab # ╟─96e423a0-885a-11eb-02a3-8704e8dbdab6
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
4811
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. module OpticSim import Unitful using LinearAlgebra: eigen, svd, I, qr, dot, cross, norm, det, normalize, inv import LinearAlgebra using StaticArrays using DataFrames: DataFrame using Images using Base: @. using ForwardDiff using StringEncodings # this dependency is intentional! Revise allows OpticSim to reload AGFGlassCat.jl (the glass database) after calling # `add_agf` (src/GlassCat/sources.jl) with `rebuild = true` using Revise # included here to allow a call to the activate! during the initialization import GLMakie import Makie include("constants.jl") include("utilities.jl") include("GlassCat/GlassCat.jl") import .GlassCat: plot_indices, index, polyfit_indices, absairindex, absorption, info, glassid, glassname, glassforid, isair, findglass, modelglass, glassfromMIL, GlassID include("Data/Data.jl") include("Geometry/Geometry.jl") include("Optical/Optical.jl") include("RepeatingStructures/Repeat.jl") include("Vis/Vis.jl") include("Examples/Examples.jl") include("Optimization/Optimization.jl") include("Cloud/Cloud.jl") # define the NotebooksUtils module include("NotebooksUtils/NotebooksUtils.jl") #initialize these caches here so they will get the correct number of threads from the load time environment, rather than the precompile environment. The latter happens if the initialization happens in the const definition. If the precompile and load environments have different numbers of threads this will cause an error. function __init__() # this call is to try and keep the original behevior of Makie's default backend after adding the WGLMakie backend to the package try GLMakie.activate!() catch e @warn "Unable to activate! the GLMakie backend\n$e" end for _ in 1:Threads.nthreads() push!(threadedtrianglepool,Dict{DataType,TrianglePool}((Float64 => TrianglePool{Float64}()))) push!(threadedintervalpool,Dict{DataType,IntervalPool}((Float64 => IntervalPool{Float64}()))) end end ################################################ # This can be used to track NaN, particularly in ForwardDiff gradients, causing problems # e.g. Diagnostics.testoptimization(lens = Examples.doubleconvex(NaNCheck{Float64}), samples = 1) # struct NaNCheck{T<:Real} <: Real # val::T # function NaNCheck{T}(a::S) where {T<:Real, S<:Real} # @assert !(T <: NaNCheck) # new{T}(T(a)) # end # end # export NaNCheck # Base.isnan(a::NaNCheck{T}) where{T} = isnan(a.val) # Base.isinf(a::NaNCheck{T}) where{T} = isinf(a.val) # Base.typemin(::Type{NaNCheck{T}}) where{T} = NaNCheck{T}(typemin(T)) # Base.typemax(::Type{NaNCheck{T}}) where{T} = NaNCheck{T}(typemax(T)) # Base.eps(::Type{NaNCheck{T}}) where {T} = NaNCheck{T}(eps(T)) # Base.decompose(a::NaNCheck{T}) where {T} = Base.decompose(a.val) # Base.round(a::NaNCheck{T}, m::RoundingMode) where {T} = NaNCheck{T}(round(a.val, m)) # struct NaNException <: Exception end # # (::Type{Float64})(a::NaNCheck{S}) where {S<:Real} = NaNCheck{Float64}(Float64(a.val)) # (::Type{T})(a::NaNCheck{S}) where {T<:Integer,S<:Real} = T(a.val) # (::Type{NaNCheck{T}})(a::NaNCheck{S}) where {T<:Real,S<:Real} = NaNCheck{T}(T(a.val)) # Base.promote_rule(::Type{NaNCheck{T}}, ::Type{T}) where {T<:Number} = NaNCheck{T} # Base.promote_rule(::Type{T}, ::Type{NaNCheck{T}}) where {T<:Number} = NaNCheck{T} # Base.promote_rule(::Type{S}, ::Type{NaNCheck{T}}) where {T<:Number, S<:Number} = NaNCheck{promote_type(T,S)} # Base.promote_rule(::Type{NaNCheck{T}}, ::Type{S}) where {T<:Number, S<:Number} = NaNCheck{promote_type(T,S)} # Base.promote_rule(::Type{NaNCheck{S}}, ::Type{NaNCheck{T}}) where {T<:Number, S<:Number} = NaNCheck{promote_type(T,S)} # for op = (:sin, :cos, :tan, :log, :exp, :sqrt, :abs, :-, :atan, :acos, :asin, :log1p, :floor, :ceil, :float) # eval(quote # function Base.$op(a::NaNCheck{T}) where{T} # temp = NaNCheck{T}(Base.$op(a.val)) # if isnan(temp) # throw(NaNException()) # end # return temp # end # end) # end # for op = (:+, :-, :/, :*, :^, :atan) # eval(quote # function Base.$op(a::NaNCheck{T}, b::NaNCheck{T}) where{T} # temp = NaNCheck{T}(Base.$op(a.val, b.val)) # if isnan(temp) # throw(NaNException()) # end # return temp # end # end) # end # for op = (:<, :>, :<=, :>=, :(==), :isequal) # eval(quote # function Base.$op(a::NaNCheck{T}, b::NaNCheck{T}) where{T} # temp = Base.$op(a.val, b.val) # return temp # end # end) # end ################################################ end # module
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
1983
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. # small offset along ray direction to prevent ray from reintersecting the surface it just intersected. Optical pathlength is measured in mm so this is much smaller than a wavelength of light. const RAY_OFFSET = 1e-6 # if the power of a ray drops below this value return nothing and do not continue the ray tracing recursion const POWER_THRESHOLD = 1e-6 # if the ray is traced recursively more than this many times then the trace will be terminated and the ray ignored (mostly happens with TIR) const TRACE_RECURSION_LIMIT = 256 # triangulated surfaces are imprecise mostly due to floating point precision, particularly if using trig functions # expanding every triangle by a fraction resolves missed intersections const TRIANGULATION_EXPANSION = 2 * eps(Float64) # we also need to extend the bounds of the surface to ensure we don't miss anythgin at the edges of the surface const TRIANGULATION_EXTENSION = 0.02 # for accelerated surface the triangulated surface can often be very imprecise, this will mean rays which start close # to the surface might miss intersection because the ray origin lies above the triangulated surface but below the true surface # (where for this example the ray direction is straight upwards), offsetting the ray fixes this, and as we check the alpha # of the intersection point afterwards there are no problems const ACCEL_SURF_RAY_OFFSET = 0.1 # settings for visualization const MIN_VIS_TRI_SIZE = 1e-3 const MESH_PRECISION = 1e-3 const VIS_RECURSION_LIMIT = 64 # number of M/N to precompute for various variables involved in the QType calculations const QTYPE_PRECOMP = 16 # maximum number of orders for a thin grating interface const GRATING_MAX_ORDERS = 10 # LensAssemblyN methods will be generated at compile time (faster on first run) for N up to this number const PREGENERATED_LENS_ASSEMBLY_SIZE = 10
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
3460
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ plane_from_points(points::SMatrix{D, N, P}}) -> centroid, normal, local_to_world transform Points to be fitted are assumed to be stored by column in the `points` matrix. Estimate the best fitting plane for a set of points in 3D. `D` is the dimension of the plane. `N` is the number of points to fit. `P` is the number type used to represent points. """ function plane_from_points(points::SMatrix{D, N, P}) where {D,N,P<:Real} center = Statistics.mean(points,dims=2) #compute average of columns of point matrix. u, _, _ = svd(points .- center) #always want a rotation matrix. if det(u) < 0 u = SMatrix{D,D}(u[:,1:(end-1)]...,-u[:,end]...) #change sign of last singular vector to turn into rotation matrix end normal = u[:,3] # The two largest singular vectors lie in the plane that is the best fit to the points, i.e., that accounts for the largest fraction of variance in the set of points. The smallest singular vector is perpendicular to this plane. # make sure the normal is pointing consistently to positive Z direction of local coordinate frame if dot(normal, unitZ3()) < P(0.0) normal = normal * P(-1.0) end return SVector(center), SVector(normal), u # convert from SMatrix to SVector, return u matrix to use as local coordinate frame for the plane. end function plane_from_points(points::AbstractMatrix{P}) where{P<:Real} dims = size(points) temp = MMatrix{dims[1],dims[2],P}(points) return plane_from_points(SMatrix(temp)) end """only returns real roots""" function quadraticroots(a::T, b::T, c::T) where {T<:Real} temp = b^2 - 4 * a * c if temp < zero(T) return nothing # no real roots so no ray cylinder intersection end radical = sqrt(temp) if b >= zero(T) radicalterm = -b - radical x1 = radicalterm / (2a) x2 = (2c) / radicalterm else radicalterm = -b + radical x1 = (2c) / radicalterm x2 = radicalterm / (2a) end return SVector{2,T}(x1, x2) end replprint(a) = show(IOContext(stdout), "text/plain", a) @inline samepoint(pt1, pt2) = isapprox(pt1, pt2, atol = 1e-10) password() = String(collect(rand(('1':'9'..., 'A':'Z'..., 'a':'z'...)) for i in 1:14)) # 1 if val>= 0 and -1 otherwise. Unlike Math.Sign which returns 0 if val==0 @inline sign(val::T) where {T<:Real} = val >= zero(T) ? 1 : -1 @inline function NaNsafeatan(x::T, y::T)::T where {T<:Real} if y == zero(T) if x == zero(T) return zero(T) elseif x > zero(T) return T(π / 2) else return -T(π / 2) end else return atan(x, y) end end @inline function NaNsafeasin(x::T)::T where {T<:Real} if x == zero(T) return zero(T) elseif x == one(T) return T(π / 2) elseif x == -one(T) return -T(π / 2) else return asin(x) end end @inline function NaNsafeacos(x::T)::T where {T<:Real} if x == zero(T) return T(π / 2) elseif x == one(T) return zero(T) elseif x == -one(T) return T(π) else return acos(x) end end # some place holders for package level function names. # these names need to exist before any internal module can override them. function origin end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
8650
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. module Cloud using PyCall using Conda using Pkg using Random """ cache_run_config(subscription_id::String, resource_group::String, workspace_name::String, compute_name::String[, path::String]) Writes the AML config information to a file at `path`. If `path` isn't set then the config will be used globally for that OpticSim install. """ function cache_run_config(subscription_id::String, resource_group::String, workspace_name::String, compute_name::String, path::String = joinpath(@__DIR__, "amlconf")) open(path, "w") do io write(io, subscription_id * "\n") write(io, resource_group * "\n") write(io, workspace_name * "\n") write(io, compute_name) end nothing end """ get_cached_run_config([path::String]) Reads the AML config information from a file at `path`. If not specified then the global config will be read. """ function get_cached_run_config(path::String = joinpath(@__DIR__, "amlconf")) open(path, "r") do io subscription_id = readline(io) resource_group = readline(io) workspace_name = readline(io) compute_name = readline(io) return subscription_id, resource_group, workspace_name, compute_name end end """ submit_run_to_AML(run_name::String, path_to_script::String, script_args::Vector{String} = nothing, sampled_args:Dict{String,Vector{String}} = nothing, config_path::String; hyperdrive_concurrent_runs::Int = 10) submit_run_to_AML(run_name::String, path_to_script::String, subscription_id::String, resource_group::String, workspace_name::String, compute_name::String, script_args::Vector{String} = nothing, sampled_args::Dict{String, Vector{String}} = nothing; hyperdrive_concurrent_runs::Int = 10) Submit a run to AML, `path_to_script` is relative to your local package root (i.e. location of `Project.toml`). `script_args` are a series of arguments to your script as strings. `sampled_args` is a dictionary where keys are argument names and values are lists of values (as strings) that that argument will take. `config_path` is a path to a config file as written by [`cache_run_config`](@ref), if not specified the global config is used. Alternatively this information can be provided directly using the second method above. `hyperdrive_concurrent_runs` is the maximum number of concurrent runs that will execute on AML (limited by your compute cluster size). """ function submit_run_to_AML(run_name::String, path_to_script::String, script_args::Union{Nothing,Vector{String}} = nothing, sampled_args::Union{Nothing,Dict{String,Vector{String}}} = nothing; config_path::String = joinpath(@__DIR__, "amlconf"), hyperdrive_concurrent_runs::Int = 10) subscription_id, resource_group, workspace_name, compute_name = get_cached_run_config(config_path) submit_run_to_AML(run_name, path_to_script, subscription_id, resource_group, workspace_name, compute_name, script_args, sampled_args, hyperdrive_concurrent_runs=hyperdrive_concurrent_runs) end function submit_run_to_AML(run_name::String, path_to_script::String, subscription_id::String, resource_group::String, workspace_name::String, compute_name::String, script_args::Union{Nothing,Vector{String}} = nothing, sampled_args::Union{Nothing,Dict{String,Vector{String}}} = nothing; hyperdrive_concurrent_runs::Int = 10) dockerfile = open(joinpath(@__DIR__, "dockerfile")) do file read(file, String) end # add deps to dockerfile project_dict = Pkg.TOML.parsefile(Base.active_project()) packages = collect(keys(project_dict["deps"])) sort!(packages) pkg_install_cmd = "RUN julia -e \"using Pkg; " for package_name in packages if "compat" in keys(project_dict) && package_name in keys(project_dict["compat"]) pkg_install_cmd = pkg_install_cmd * "Pkg.add(name=\\\"" * package_name * "\\\", version=\\\"" * project_dict["compat"][package_name] * "\\\");" else pkg_install_cmd = pkg_install_cmd * "Pkg.add(\\\"" * package_name * "\\\");" end end if "OpticSim" in packages # build OpticSim if it is there pkg_install_cmd = pkg_install_cmd * "Pkg.build(\\\"OpticSim\\\");" end pkg_install_cmd = pkg_install_cmd * "\"" dockerfile = dockerfile * pkg_install_cmd # TODO maybe compile sysimage in docker - would be horribly slow but should speed up import a lot? source_directory = joinpath(dirname(Base.active_project())) if isfile(joinpath(source_directory, "Manifest.toml")) && !isfile(joinpath(source_directory, ".amlignore")) println("No .amlignore file found, creating one") open(joinpath(source_directory, ".amlignore"), "w") do io write(io, "Manifest.toml\n") end end # set up env for python stuff try pyimport("azureml.core") catch # FIXME maybe won't work, might need to restart Julia after this? Conda.add("python=3.7") Conda.add("pip=20.1.1") Conda.pip_interop(true) Conda.pip("install", "azureml-sdk") Pkg.build("PyCall") end # copy entry_script from here to source_directory entry_script_path = "entry_script_" * randstring() * ".py" cp(joinpath(@__DIR__, "entry_script.py"), joinpath(source_directory, entry_script_path)) py""" import os import webbrowser from azureml.core import Environment, Experiment, Run, Workspace, ScriptRunConfig import azureml.train.hyperdrive as hyperdrive from azureml.train.hyperdrive.parameter_expressions import choice def get_hyperparam_dict(param_dict): hyper_param_dict = {} num_params = 1 for key, value in param_dict.items(): hyper_param_dict[key] = choice(value) num_params = num_params * len(value) return hyper_param_dict, num_params def submit_run(subscription_id, resource_group, workspace_name, compute_name, source_directory, julia_script, script_args, sampled_args, run_name, dockerfile, entry_script_path, hyperdrive_concurrent_runs): workspace = Workspace(subscription_id, resource_group, workspace_name) compute_target = workspace.compute_targets[compute_name] env = Environment("opticsim") env.docker.base_image = None env.docker.base_dockerfile = dockerfile args = [julia_script.replace(os.sep, "/")] if script_args is not None: args.extend(script_args) src = ScriptRunConfig(source_directory=source_directory, script=entry_script_path, arguments=args, compute_target=compute_target, environment=env) src.run_config.docker.use_docker = True exp_name = os.getlogin() + "-opticsim" experiment = Experiment(workspace, exp_name) if sampled_args is not None: sampling_params, num_params = get_hyperparam_dict(sampled_args) param_sampling = hyperdrive.GridParameterSampling(sampling_params) hyperdrive_run_config = hyperdrive.HyperDriveConfig(run_config=src, hyperparameter_sampling=param_sampling, max_concurrent_runs=hyperdrive_concurrent_runs, primary_metric_name="", primary_metric_goal=hyperdrive.PrimaryMetricGoal.MINIMIZE, max_total_runs=num_params) run_object = experiment.submit(hyperdrive_run_config, tags={"run_name": run_name}) else: run_object = experiment.submit(src, tags={"run_name": run_name}) webbrowser.open_new(run_object.get_portal_url()) """ py"submit_run"(subscription_id, resource_group, workspace_name, compute_name, source_directory, path_to_script, script_args, sampled_args, run_name, dockerfile, entry_script_path, hyperdrive_concurrent_runs) # remove the entry script rm(joinpath(source_directory, entry_script_path)) end export submit_run_to_AML, cache_run_config, get_cached_run_config end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
236
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. module Data import Unitful using Unitful.DefaultSymbols:mm,° include("HumanEye.jl") end #module
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
2982
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. # This file contains average properties of the human eye and optical human eye models # luminance (cd/m2) Multiple Value Item # 10−6 µcd/m2 1 µcd/m2 Absolute threshold of vision[1] # 10−5 # 10−4 400 µcd/m2 Darkest sky[2] # 10−3 mcd/m2 1 mcd/m2 Night sky[3] # 1.4 mcd/m2 Typical photographic scene lit by full moon[4] # 5 mcd/m2 Approximate scotopic/mesopic threshold[5] # 10−2 40 mcd/m2 Phosphorescent markings on a watch dial after 1 h in the dark[6][7] # 10−1 # 100 cd/m2 2 cd/m2 Floodlit buildings, monuments, and fountains[8] # 5 cd/m2 Approximate mesopic/photopic threshold[5] # 101 25 cd/m2 Typical photographic scene at sunrise or sunset[4] # 30 cd/m2 Green electroluminescent source[2] # 102 250 cd/m2 Peak luminance of a typical LCD monitor[10][11] # 700 cd/m2 Typical photographic scene on overcast day[4][8][11] # 103 kcd/m2 2 kcd/m2 Average cloudy sky[2] # 5 kcd/m2 Typical photographic scene in full sunlight[4][8] """ # Pupil diameter as a function of scene luminance https://jov.arvojournals.org/article.aspx?articleid=2279420 https://en.wikipedia.org/wiki/Orders_of_magnitude_(luminance) Pupil diameter is approximately 2.8mm at 100cd/m^2. A typical overcast day is 700cd/m^2 """ """computes pupil diameter as a function of scene luminance `L`, in cd/m², and the angular area, `a`, over which this luminance is presented to the eye.""" 𝐃sd(L,a) = 7.75 - 5.75 * ((L * a / 846)^.41) / ((L * a / 846)^.41 + 2) # the first letter of this function name is \bfD not D. export 𝐃sd eyeradius() = 12mm export eyeradius """Posterior focal length, i.e., optical distance from entrance pupil to the retina. Focal length will change depending on accomodation. This value is for focus at ∞. When the eye is focused at 25cm focal length will be ≈ 22mm. Because the index of refraction of the vitreous humor is approximately 1.33 the physical distance from the entrance pupil to the retina will be 24mm/1.33 = 18mm.""" eyefocallength() = 24mm export eyefocallength vc_epupil() = 3mm #distance from vertex of cornea to entrance pupil """ distance from vertex of cornea to center of rotation""" cornea_to_eyecenter() = 13.5mm export cornea_to_eyecenter entrancepupil_to_retina() = 22.9mm """distance from entrance pupil to center of rotation.""" entrancepupil_to_eyecenter() = entrancepupil_to_retina() - eyeradius() export entrancepupil_to_eyecenter """average angle, in degrees, the eye will rotate before users will turn their head""" comfortable_eye_rotation_angle() = 20° """Average one sided translation of the entrance pupil associated with comfortable eye rotation. If you are using this to define an eyebox multiply this value by 2""" comfortable_entrance_pupil_translation() = sin(comfortable_eye_rotation_angle())*entrancepupil_to_eyecenter() export comfortable_entrance_pupil_translation
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
3907
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """Contains example usage of the features in the OpticSim.jl package.""" module Examples using ..OpticSim using ..OpticSim.Vis using ..OpticSim.Geometry using ..OpticSim.Emitters using ..OpticSim.GlassCat using ..OpticSim.Repeat using StaticArrays using DataFrames: DataFrame using Images using Unitful using Plots using LinearAlgebra import Luxor #Hardcode these glass types so this code will work even if it is not possible to download the glasses at build time. const Examples_N_BK7 = GlassCat.Glass("$(@__MODULE__).Examples_N_BK7", 2, 1.03961212, 0.00600069867, 0.231792344, 0.0200179144, 1.01046945, 103.560653, 0.0, 0.0, NaN, NaN, 0.3, 2.5, 1.86e-6, 1.31e-8, -1.37e-11, 4.34e-7, 6.27e-10, 0.17, 20.0, -0.0009, 2.3, 1.0, 7.1, 1.0, 1, 1.0, [(0.3, 0.05, 25.0), (0.31, 0.25, 25.0), (0.32, 0.52, 25.0), (0.334, 0.78, 25.0), (0.35, 0.92, 25.0), (0.365, 0.971, 25.0), (0.37, 0.977, 25.0), (0.38, 0.983, 25.0), (0.39, 0.989, 25.0), (0.4, 0.992, 25.0), (0.405, 0.993, 25.0), (0.42, 0.993, 25.0), (0.436, 0.992, 25.0), (0.46, 0.993, 25.0), (0.5, 0.994, 25.0), (0.546, 0.996, 25.0), (0.58, 0.995, 25.0), (0.62, 0.994, 25.0), (0.66, 0.994, 25.0), (0.7, 0.996, 25.0), (1.06, 0.997, 25.0), (1.53, 0.98, 25.0), (1.97, 0.84, 25.0), (2.325, 0.56, 25.0), (2.5, 0.36, 25.0)], 1.5168, 2.3, 0.0, 0, 64.17, 0, 2.51, 0.0) const Examples_N_SK16 =GlassCat.Glass("$(@__MODULE__).Examples_N_SK16", 2, 1.34317774, 0.00704687339, 0.241144399, 0.0229005, 0.994317969, 92.7508526, 0.0, 0.0, NaN, NaN, 0.31, 2.5, -2.37e-8, 1.32e-8, -1.29e-11, 4.09e-7, 5.17e-10, 0.17, 20.0, -0.0011, 3.2, 1.4, 6.3, 4.0, 1, 53.3, [(0.31, 0.02, 25.0), (0.32, 0.11, 25.0), (0.334, 0.4, 25.0), (0.35, 0.7, 25.0), (0.365, 0.86, 25.0), (0.37, 0.89, 25.0), (0.38, 0.93, 25.0), (0.39, 0.956, 25.0), (0.4, 0.97, 25.0), (0.405, 0.974, 25.0), (0.42, 0.979, 25.0), (0.436, 0.981, 25.0), (0.46, 0.984, 25.0), (0.5, 0.991, 25.0), (0.546, 0.994, 25.0), (0.58, 0.994, 25.0), (0.62, 0.993, 25.0), (0.66, 0.994, 25.0), (0.7, 0.996, 25.0), (1.06, 0.995, 25.0), (1.53, 0.973, 25.0), (1.97, 0.88, 25.0), (2.325, 0.54, 25.0), (2.5, 0.26, 25.0)], 1.62041, 3.3, 4.0, 0, 60.32, 0, 3.58, 0.0) const Examples_N_SF2 = GlassCat.Glass("$(@__MODULE__).Examples_N_SF2", 2, 1.47343127, 0.0109019098, 0.163681849, 0.0585683687, 1.36920899, 127.404933, 0.0, 0.0, NaN, NaN, 0.365, 2.5, 3.1e-6, 1.75e-8, 6.62e-11, 7.51e-7, 8.99e-10, 0.277, 20.0, 0.0081, 1.0, 1.4, 6.68, 1.0, 1, 1.0, [(0.365, 0.007, 25.0), (0.37, 0.06, 25.0), (0.38, 0.4, 25.0), (0.39, 0.68, 25.0), (0.4, 0.83, 25.0), (0.405, 0.865, 25.0), (0.42, 0.926, 25.0), (0.436, 0.949, 25.0), (0.46, 0.961, 25.0), (0.5, 0.975, 25.0), (0.546, 0.986, 25.0), (0.58, 0.987, 25.0), (0.62, 0.984, 25.0), (0.66, 0.984, 25.0), (0.7, 0.987, 25.0), (1.06, 0.997, 25.0), (1.53, 0.984, 25.0), (1.97, 0.93, 25.0), (2.325, 0.76, 25.0), (2.5, 0.67, 25.0)], 1.64769, 1.2, 0.0, 0, 33.82, 0, 2.718, 0.0) const Examples_N_SF14 = GlassCat.Glass("$(@__MODULE__).Examples_N_SF14", 2, 1.69022361, 0.0130512113, 0.288870052, 0.061369188, 1.7045187, 149.517689, 0.0, 0.0, NaN, NaN, 0.365, 2.5, -5.56e-6, 7.09e-9, -1.09e-11, 9.85e-7, 1.39e-9, 0.287, 20.0, 0.013, 1.0, 2.2, 9.41, 1.0, 1, 1.0, [(0.365, 0.004, 25.0), (0.37, 0.04, 25.0), (0.38, 0.33, 25.0), (0.39, 0.61, 25.0), (0.4, 0.75, 25.0), (0.405, 0.79, 25.0), (0.42, 0.87, 25.0), (0.436, 0.91, 25.0), (0.46, 0.938, 25.0), (0.5, 0.964, 25.0), (0.546, 0.983, 25.0), (0.58, 0.987, 25.0), (0.62, 0.987, 25.0), (0.66, 0.987, 25.0), (0.7, 0.985, 25.0), (1.06, 0.998, 25.0), (1.53, 0.98, 25.0), (1.97, 0.88, 25.0), (2.325, 0.64, 25.0), (2.5, 0.57, 25.0)], 1.76182, 1.0, 0.0, 0, 26.53, 0, 3.118, 0.0) include("docs_examples.jl") include("other_examples.jl") include("repeating_structure_examples.jl") include("eyemodels.jl") end #module Examples export Examples
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
12692
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. # Group examples that are used in the docs (examples.md) export draw_cooketriplet, draw_schmidtcassegraintelescope, draw_lensconstruction, draw_zoomlenses, draw_HOEfocus, draw_HOEcollimate, draw_multiHOE, draw_stackedbeamsplitters function draw_cooketriplet(filename::Union{Nothing,AbstractString} = nothing) g1, g2 = Examples_N_SK16, Examples_N_SF2 sys = AxisymmetricOpticalSystem{Float64}(DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Standard", "Stop", "Standard", "Standard", "Image"], Radius = [Inf, 26.777, 66.604, -35.571, 35.571, 35.571, -26.777, Inf ], Thickness = [Inf, 4.0, 2.0, 4.0, 2.0, 4.0, 44.748, missing], Material = [Air, g1, Air, g2, Air, g1, Air, missing], SemiDiameter = [Inf, 8.580, 7.513, 7.054, 6.033, 7.003, 7.506, 15.0 ], )) origins = Origins.Hexapolar(8, 15.0, 15.0) directions = Directions.Constant(0.0, 0.0, -1.0) s1 = Sources.Source(; origins, directions, sourcenum=1) transform = Transform(rotmatd(10, 0, 0), unitZ3()) s2 = Sources.Source(; transform, origins, directions, sourcenum=2) raygenerator = Sources.CompositeSource(Transform(), [s1, s2]) trackallrays = test = colorbysourcenum = true; resolution = (1000, 700) Vis.drawtracerays(sys; raygenerator, trackallrays, test, colorbysourcenum, resolution) Vis.make2dy(); Vis.save(filename) return sys end function draw_zoomlenses(filenames::Vector{<:Union{Nothing,AbstractString}} = repeat([nothing], 3)) stops = [2.89, 3.99, 4.90] zooms = [9.48, 4.48, 2.00] dists = [4.46970613, 21.21, 43.81] transform = translation(0.0, 0.0, 10.0) origins = Origins.Hexapolar(8, 10.0, 10.0) directions = Directions.Constant(0.0, 0.0, -1.0) raygenerator = Sources.Source(; transform, origins, directions) aspherics = [ ["4" => 1.0386E-04, "6" => 1.4209E-07, "8" => -8.8495E-09, "10" => 1.2477E-10, "12" => -1.0367E-12, "14" => 3.6556E-15], ["4" => 4.2721E-05, "6" => 1.2484E-07, "8" => 9.7079E-09, "10" => -1.8444E-10, "12" => 1.8644E-12, "14" => -7.7975E-15], ["4" => 1.1339E-04, "6" => 4.8165E-07, "8" => 1.8778E-08, "10" => -5.7571E-10, "12" => 8.9994E-12, "14" => -4.6768E-14], ] syss = [ AxisymmetricOpticalSystem{Float64}(DataFrame( SurfaceType = ["Object", "Stop", "Standard", "Standard", "Standard", "Aspheric", "Standard", "Standard", "Aspheric", "Aspheric", "Standard", "Standard", "Standard", "Standard", "Standard", "Standard", "Image"], Radius = [Inf64, Inf64, -1.6202203499676E+01, -4.8875855327468E+01, 1.5666614444619E+01, -4.2955326460481E+01, 1.0869565217391E+02, 2.3623907394283E+01, -1.6059097478722E+01, -4.2553191489362E+02, -3.5435861091425E+01, -1.4146272457208E+01, -2.5125628140704E+02, -2.2502250225023E+01, -1.0583130489999E+01, -4.4444444444444E+01, Inf64], Parameters = [missing, missing, missing, missing, missing, aspherics[1], missing, missing, aspherics[2], aspherics[3], missing, missing, missing, missing, missing, missing, missing], Thickness = [Inf64, 0.0, 5.18, 0.10, 4.40, 0.16, 1.0, 4.96, zoom, 4.04, 1.35, 1.0, 2.80, 3.0, 1.22, dist, missing], Material = [Air, Air, OHARA.S_LAH66, Air, NIKON.LLF6, Air, OHARA.S_TIH6, OHARA.S_FSL5, Air, OHARA.S_FSL5, Air, OHARA.S_LAL8, OHARA.S_FSL5, Air, OHARA.S_LAH66, Air, missing], SemiDiameter = [Inf64, stop, 3.85433218451, 3.85433218451, 4.36304692871, 4.36304692871, 4.72505505439, 4.72505505439, 4.72505505439, 4.45240784026, 4.45240784026, 4.50974054117, 4.50974054117, 4.50974054117, 4.76271114409, 4.76271114409, 15.0])) for (stop, zoom, dist) in zip(stops, zooms, dists)] for (sys, filename) in zip(syss, filenames) Vis.drawtracerays(sys; raygenerator, trackallrays=true, test=true, numdivisions=50, resolution=(1200, 600)) Vis.make2dy(); Vis.save(filename) end return syss end function draw_schmidtcassegraintelescope(filename::Union{Nothing,AbstractString} = nothing) # glass entrance lens on telescope topsurf = Plane( SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, 0.0), interface = FresnelInterface{Float64}(Examples_N_BK7, Air), vishalfsizeu = 12.00075, vishalfsizev = 12.00075) botsurf = AcceleratedParametricSurface(ZernikeSurface( 12.00075, radius = -1.14659768e+4, aspherics = [(4, 3.68090959e-7), (6, 2.73643352e-11), (8, 3.20036892e-14)]), 17, interface = FresnelInterface{Float64}(Examples_N_BK7, Air)) coverlens = Cylinder(12.00075, 1.4) ∩ topsurf ∩ leaf(botsurf, Transform(rotmatd(0, 180, 0), Vec3(0.0, 0.0, -0.65))) # big mirror with a hole in it frontsurfacereflectance = 1.0 bigmirror = ( ConicLens(Examples_N_BK7, -72.65, -95.2773500000134, 0.077235, Inf, 0.0, 0.2, 12.18263; frontsurfacereflectance) - leaf(Cylinder(4.0, 0.3, interface = opaqueinterface()), translation(0.0, 0.0, -72.75)) ) # small mirror supported on a spider backsurfacereflectance = 1.0 smallmirror = SphericalLens(Examples_N_BK7, -40.65, Inf, -49.6845, 1.13365, 4.3223859; backsurfacereflectance) obscuration1 = Circle(4.5, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, -40.649), interface = opaqueinterface()) obscurations2 = Spider(3, 0.5, 12.0, SVector(0.0, 0.0, -40.65)) # put it together with the detector la = LensAssembly(coverlens(), bigmirror(), smallmirror(), obscuration1, obscurations2...) det = Circle(3.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, -92.4542988), interface = opaqueinterface()) sys = CSGOpticalSystem(la, det) # define ray generator transform = translation(0.0, 0.0, 10.0) origins = Origins.Hexapolar(8, 20.0, 20.0) directions = Directions.Constant(0.0, 0.0, -1.0) raygenerator = Sources.Source(; transform, origins, directions) # draw and output Vis.drawtracerays(sys; raygenerator, trackallrays = true, colorbynhits = true, test = true, numdivisions = 100, drawgen = false) Vis.save(filename) return nothing end function draw_lensconstruction(filename::Union{Nothing,AbstractString} = nothing) topsurface = leaf( AcceleratedParametricSurface( QTypeSurface( 9.0, radius = -25.0, conic = 0.3, αcoeffs = [(1, 0, 0.3), (1, 1, 1.0)], βcoeffs = [(1, 0, -0.1), (2, 0, 0.4), (3, 0, -0.6)], normradius = 9.5), interface = FresnelInterface{Float64}(Examples_N_BK7, Air)), translation(0.0, 0.0, 5.0)) botsurface = Plane( SVector(0.0, 0.0, -1.0), SVector(0.0, 0.0, -5.0), vishalfsizeu = 9.5, vishalfsizev = 9.5, interface = FresnelInterface{Float64}(Examples_N_BK7, Air)) barrel = Cylinder( 9.0, 20.0, interface = FresnelInterface{Float64}(Examples_N_BK7, Air, reflectance=0.0, transmission=0.0) ) lens = (barrel ∩ topsurface ∩ botsurface)(Transform(0.0, Float64(π), 0.0, 0.0, 0.0, -5.0)) detector = Rectangle(15.0, 15.0, [0.0, 0.0, 1.0], [0.0, 0.0, -67.8], interface = opaqueinterface()) sys = CSGOpticalSystem(LensAssembly(lens), detector) Vis.drawtracerays(sys, test = true, trackallrays = true, colorbynhits = true) Vis.save(filename) return nothing end function draw_HOEfocus(filename::Union{Nothing,AbstractString} = nothing) rect = Rectangle(5.0, 5.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, 0.0)) int = HologramInterface( SVector(0.0, -3.0, -20.0), ConvergingBeam, SVector(0.0, 0.0, -1.0), CollimatedBeam, 0.55, 9.0, Air, Examples_N_BK7, Air, Air, Air, 0.05, false) obj = HologramSurface(rect, int) sys = CSGOpticalSystem( LensAssembly(obj), Rectangle(10.0, 10.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, -25.0), interface = opaqueinterface())) raygenerator = Sources.Source(; transform = translation(0.0, 0.0, 10.0), spectrum = Spectrum.DeltaFunction(0.55), origins = Origins.RectGrid(3.0, 3.0, 5, 5), directions = Directions.Constant(0.0, 0.0, -1.0)) Vis.drawtracerays(sys; raygenerator, trackallrays = true, rayfilter = nothing, test = true) Vis.save(filename) return nothing end function draw_HOEcollimate(filename::Union{Nothing,AbstractString} = nothing) rect = Rectangle(5.0, 5.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, 0.0)) int = HologramInterface( SVector(0.1, -0.05, -1.0), CollimatedBeam, SVector(0.0, 0.0, 10), DivergingBeam, 0.55, 9.0, Air, Examples_N_BK7, Air, Air, Air, 0.05, false) obj = HologramSurface(rect, int) sys = CSGOpticalSystem( LensAssembly(obj), Rectangle(10.0, 10.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, -25.0), interface = opaqueinterface())) raygenerator = Sources.Source( transform = Transform(rotmatd(180, 0, 0), Vec3(0.0, 0.0, 10.0)), spectrum = Spectrum.DeltaFunction(0.55), origins = Origins.Point(), directions = Directions.RectGrid(π/4, π/4, 8, 8)) Vis.drawtracerays(sys; raygenerator, trackallrays = true, rayfilter = nothing, test = true) Vis.save(filename) return nothing end function draw_multiHOE(filename::Union{Nothing,AbstractString} = nothing) rect = Rectangle(5.0, 5.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, 0.0)) int1 = HologramInterface( SVector(-5.0, 0.0, -20.0), ConvergingBeam, SVector(0.0, -1.0, -1.0), CollimatedBeam, 0.55, 100.0, Air, Examples_N_BK7, Air, Air, Air, 0.05, false) int2 = HologramInterface( SVector(5.0, 0.0, -20.0), ConvergingBeam, SVector(0.0, 1.0, -1.0), CollimatedBeam, 0.55, 100.0, Air, Examples_N_BK7, Air, Air, Air, 0.05, false) mint = MultiHologramInterface(int1, int2) obj = MultiHologramSurface(rect, mint) sys = CSGOpticalSystem( LensAssembly(obj), Rectangle(10.0, 10.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, -20.0), interface = opaqueinterface())) spectrum = Spectrum.DeltaFunction(0.55) origins = Origins.RectUniform(3.0, 3.0, 500) directions = Directions.Constant(0.0, 0.0, -1.0) s1 = Sources.Source(; spectrum, origins, directions, sourcenum = 1, transform = Transform(rotmatd(-45, 0, 0), Vec3(0.0, 3.0, 3.0))) s2 = Sources.Source(; spectrum, origins, directions, sourcenum = 2, transform = Transform(rotmatd(45, 0, 0), Vec3(0.0, -3.0, 3.0))) s3 = Sources.Source(; spectrum, origins, directions, sourcenum = 3, transform = translation(0.0, 0.0, 3.0)) raygenerator = Sources.CompositeSource(Transform(), [s1, s2, s3]) Vis.drawtracerays(sys; raygenerator, trackallrays = true, colorbysourcenum = true, rayfilter = nothing, drawgen = true) Vis.save(filename) return nothing end function draw_stackedbeamsplitters(filenames::Vector{<:Union{Nothing,AbstractString}} = repeat([nothing], 3)) # ReflectOrTransmit: nondeterministic # Transmit: deterministic, all beamsplitters transmissive # Reflect: deterministic, all beamsplitters reflective interfacemodes = [ReflectOrTransmit, Transmit, Reflect] for (interfacemode, filename) in zip(interfacemodes, filenames) interface = FresnelInterface{Float64}(Examples_N_BK7, Air; reflectance=0.5, transmission=0.5, interfacemode) bs_1 = OpticSim.transform( Cuboid(10.0, 20.0, 2.0, interface=interface), translation(0.0, 0.0, -30.0-2*sqrt(2))*rotationX(π/4)) l1 = OpticSim.transform( SphericalLens(Examples_N_BK7, -70.0, 30.0, Inf, 5.0, 10.0), translation(0.0, -1.34, 0.0)) bs_2 = OpticSim.transform( Cuboid(10.0, 20.0, 2.0, interface=interface), translation(0.0, 40.0, -30.0+2*sqrt(2))*rotationX(π/4)) l2 = OpticSim.transform( SphericalLens(Examples_N_BK7, -70.0, 30.0, Inf, 5.0, 10.0), translation(0.0, 40.0, 0.0)) la = LensAssembly(bs_1(), l1(), bs_2(), l2()) detector = Rectangle(20.0, 40.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 20.0, -130.0); interface = opaqueinterface()) sys = CSGOpticalSystem(la, detector) Vis.drawtracerays(sys; trackallrays=true, rayfilter=nothing, colorbynhits=true) Vis.save(filename) end return nothing end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
5243
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. #Model eyes of varying degrees of verisimilitude """ ModelEye(assembly::LensAssembly{T}, nsamples::Int = 17; pupil_radius::T = 3.0, detpixels::Int = 1000, transform::Transform{T} = identitytransform(T)) Geometrically accurate model of the human eye focused at infinity with variable `pupil_radius`. The eye is added to the provided `assembly` to create a [`CSGOpticalSystem`](@ref) with the retina of the eye as the detector. The eye can be positioned in the scene using the `transform` argument and the resolution of the detector specified with `detpixels`. By default the eye is directed along the positive z-axis with the vertex of the cornea at the origin. `nsamples` determines the resolution at which accelerated surfaces within the eye are triangulated. """ function ModelEye(assembly::LensAssembly{T}; nsamples::Int = 17, pupil_radius::T = 3.0, detpixels::Int = 1000, transform::Transform{T} = identitytransform(T), detdatatype::Type{D} = Float32) where {T<:Real,D<:Real} cornea_front = AcceleratedParametricSurface(ZernikeSurface(6.9, radius = -7.8, conic = -0.5), nsamples, interface = FresnelInterface{T}(OpticSim.GlassCat.EYE.CORNEA, OpticSim.GlassCat.Air)) cornea_rear = Plane(SVector{3,T}(0, 0, -1), SVector{3,T}(0, 0, -3.2)) cornea = (cornea_front ∩ cornea_rear)(transform) anterior_chamber_front = AcceleratedParametricSurface(ZernikeSurface(6.0, radius = -6.7, conic = -0.3), nsamples, interface = FresnelInterface{T}(OpticSim.GlassCat.EYE.AQUEOUS, OpticSim.GlassCat.EYE.CORNEA)) anterior_chamber_rear = Plane(SVector{3,T}(0, 0, -1), SVector(0.0, 0.0, -3.2), vishalfsizeu = 6.0, vishalfsizev = 6.0, interface = FresnelInterface{T}(OpticSim.GlassCat.EYE.AQUEOUS, OpticSim.GlassCat.EYE.VITREOUS)) anterior_chamber = leaf(anterior_chamber_front ∩ anterior_chamber_rear, translation(0.0, 0.0, -0.52))(transform) pupil = Annulus(pupil_radius, 5.9, rotate(transform, SVector{3,T}(0, 0, 1)), transform * SVector{3,T}(0.0, 0.0, -3.62)) lens_front = AcceleratedParametricSurface(ZernikeSurface(5.1, radius = -10.0), nsamples, interface = FresnelInterface{T}(OpticSim.GlassCat.EYE.LENS, OpticSim.GlassCat.EYE.VITREOUS)) lens_rear = AcceleratedParametricSurface(ZernikeSurface(5.1, radius = 6.0, conic = -3.25), nsamples, interface = FresnelInterface{T}(OpticSim.GlassCat.EYE.LENS, OpticSim.GlassCat.EYE.VITREOUS)) lens_barrel = Cylinder(5.0, 5.0, interface = FresnelInterface{T}(OpticSim.GlassCat.EYE.LENS, OpticSim.GlassCat.EYE.VITREOUS)) lens_csg = (lens_front - leaf(lens_rear, translation(0.0, 0.0, -3.7))) ∩ leaf(lens_barrel, translation(0.0, 0.0, -2.0)) lens = leaf(lens_csg, translation(0.0, 0.0, -3.72))(transform) vitreous_chamber_csg = ( leaf( Sphere(11.0, interface = FresnelInterface{T}(EYE.VITREOUS, Air, reflectance = 0.0, transmission = 0.0)), translation(0.0, 0.0, -13.138998863513297) ) ∩ Plane(0.0, 0.0, 1.0, 0.0, 0.0, -3.72, interface = FresnelInterface{T}(EYE.VITREOUS, EYE.AQUEOUS)) ∩ Plane(0.0, 0.0, -1.0, 0.0, 0.0, -24 + (11 - sqrt(11^2 - 10^2)), interface = NullInterface(T)) ) vitreous_chamber = vitreous_chamber_csg(transform) new_assembly = OpticSim.LensAssembly(assembly, cornea, anterior_chamber, pupil, vitreous_chamber, lens) retina = SphericalCap( 11.0, asin(10 / 11), rotate(transform, SVector{3,T}(0, 0, 1)), transform * SVector{3,T}(0.0, 0.0, -24.0), interface = FresnelInterface{T}(EYE.VITREOUS, EYE.VITREOUS, reflectance = zero(T), transmission = zero(T)) ) return CSGOpticalSystem(new_assembly, retina, detpixels, detpixels, D) end export ModelEye #! format: off """ ArizonaEye(::Type{T} = Float64; accommodation::T = 0.0) The popular Arizona eye model taken from [this definition](https://photonengr.com/wp-content/uploads/kbasefiles/ArizonaEyeModel.pdf). The `accommodation` of the eye can be varied in this model. Returns a `DataFrame` specifying the prescription of the eye model. """ function ArizonaEye(::Type{T} = Float64; accommodation::T = 0.0) where {T<:Real} # from https://photonengr.com/wp-content/uploads/kbasefiles/ArizonaEyeModel.pdf also in our documentation/papers directory return DataFrame( Name = ["Air", "Cornea", "Aqueous", "Lens", "Vitreous", "Retina"], Surface = ["Object", "Standard", "Standard", "Standard", "Standard", "Image"], Radius = [Inf64, 7.8, 6.5, 12.0 - 0.4*accommodation, -5.22 + 0.2*accommodation, -13.4], Conic = [missing, -.25, -.25, -7.52 + 1.29*accommodation, -1.35 - 0.43*accommodation, missing], Material = [OpticSim.GlassCat.Air, OpticSim.GlassCat.modelglass(1.377, 57.1, 0.0), OpticSim.GlassCat.modelglass(1.337, 61.3, 0.0), OpticSim.GlassCat.modelglass(1.42 + 0.0026 * accommodation - 0.00022 * accommodation^2, 51.9, 0.0), OpticSim.GlassCat.modelglass(1.336, 61.1, 0.0), missing], SemiDiameter = [Inf64, 5.3, 5.3, 5.3, 5.3, 5.3], Thickness = [Inf64, 0.55, 2.97 - 0.04*accommodation, 3.77 + 0.04accommodation, 16.713, missing], ) end export ArizonaEye
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
14311
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. export cooketriplet, doubleconvexlensonly """ hemisphere() Create a geometric hemisphere """ function hemisphere()::CSGTree sph = Sphere(10.0) pln = Plane(0.0, 0.0, -1.0, 0.0, 0.0, 0.0) # CSV operations create a csggenerator which instantiates the csg tree after applying a rigid body transformation. # This allows you to make as many instances of the object as you want with different transformations. We just want # the CSGTree object rather than a generator. return (sph ∩ pln)() end """ opticalhemisphere() Create an optical hemisphere that has optical material properties so it will reflect and refract light. In the previous example the hemisphere object had optical properties of Air, which is the default optical interface, so it won't refract or reflect light. """ function opticalhemisphere()::CSGOpticalSystem sph = Sphere(10.0, interface = FresnelInterface{Float64}(Examples_N_BK7, Air)) pln = Plane(0.0, 0.0, -1.0, 0.0, 0.0, 0.0, interface = FresnelInterface{Float64}(Examples_N_BK7, Air)) assy = LensAssembly{Float64}((sph ∩ pln)()) return CSGOpticalSystem(assy, Rectangle(1.0, 1.0, SVector{3,Float64}(0.0, 0.0, 1.0), SVector{3,Float64}(0.0, 0.0, -11.0))) end function cooketriplet(::Type{T} = Float64, detpix::Int = 1000) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Standard", "Stop", "Standard", "Standard", "Image"], Radius = [Inf, 26.777, 66.604, -35.571, 35.571, 35.571, -26.777, Inf], # OptimizeRadius = [false, true, true, true, true, true, true, false], Thickness = [Inf, 4.0, 2.0, 4.0, 2.0, 4.0, 44.748, missing], # OptimizeThickness = [false, true, true, true, true, true, true, false], Material = [Air, Examples_N_SK16, Air, Examples_N_SF2, Air, Examples_N_SK16, Air, missing], SemiDiameter = [Inf, 8.580, 7.513, 7.054, 6.033, 7.003, 7.506, 15.0] ), detpix, detpix ) end function cooketripletfirstelement(::Type{T} = Float64) where {T<:Real} AxisymmetricOpticalSystem( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf, -35.571, 35.571, Inf], Thickness = [Inf, 4.0, 44.748, missing], Material = [Air, Examples_N_SK16, Air, missing], SemiDiameter = [Inf, 7.054, 6.033, 15.0] ) ) end function convexplano(::Type{T} = Float64) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf, 60.0, Inf, Inf], Thickness = [Inf, 10.0, 57.8, missing], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [Inf, 9.0, 9.0, 15.0] ) ) end function doubleconvex(frontradius::T, rearradius::T) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [convert(T, Inf64), frontradius, rearradius, convert(T, Inf64)], # OptimizeRadius = [false, true, true, false], Thickness = [convert(T, Inf64), convert(T, 10.0), convert(T, 57.8), missing], # OptimizeThickness = [false, false, false, false], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [convert(T, Inf64), convert(T, 9.0), convert(T, 9.0), convert(T, 15.0)] ) ) end function doubleconvexconic(::Type{T} = Float64) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf64, 60, -60, Inf64], # OptimizeRadius = [false, true, true, false], Thickness = [Inf64, 10.0, 57.8, missing], # OptimizeThickness = [false, false, false, false], Conic = [missing, 0.01, 0.01, missing], # OptimizeConic = [false, true, true, false], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [Inf64, 9.0, 9.0, 15.0] ) ) end function doubleconvexlensonly(frontradius::T,rearradius::T) where{T<:Real} AxisymmetricLens{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [convert(T, Inf64), frontradius, rearradius, convert(T, Inf64)], # OptimizeRadius = [false, true, true, false], Thickness = [convert(T, Inf64), convert(T, 10.0), convert(T, 57.8), missing], # OptimizeThickness = [false, false, false, false], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [convert(T, Inf64), convert(T, 9.0), convert(T, 9.0), convert(T, 15.0)] ) ) end function doubleconvex( ::Type{T} = Float64; temperature::Unitful.Temperature = GlassCat.TEMP_REF_UNITFUL, pressure::T = convert(T, PRESSURE_REF) ) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf64, 60, -60, Inf64], # OptimizeRadius = [false, true, true, false], Thickness = [Inf64, 10.0, 57.8, missing], # OptimizeThickness = [false, true, true, false], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [Inf64, 9.0, 9.0, 15.0] ); temperature, pressure ) end function doubleconcave(::Type{T} = Float64) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf64, -41.0, 41.0, Inf64], Thickness = [Inf64, 10.0, 57.8, missing], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [Inf64, 9.0, 9.0, 15.0] ) ) end function planoconcaverefl(::Type{T} = Float64) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf64, Inf64, -41.0, Inf64], Thickness = [Inf64, 10.0, -57.8, missing], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [Inf64, 9.0, 9.0, 25.0], Reflectance = [missing, missing, 1.0, missing] ) ) end function concaveplano(::Type{T} = Float64) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf64, -41.0, Inf64, Inf64], Thickness = [Inf64, 10.0, 57.8, missing], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [Inf64, 9.0, 9.0, 15.0] ) ) end function planoplano(::Type{T} = Float64) where {T<:Real} AxisymmetricOpticalSystem{T}( DataFrame( SurfaceType = ["Object", "Standard", "Standard", "Image"], Radius = [Inf64, Inf64, Inf64, Inf64], Thickness = [Inf64, 10.0, 57.8, missing], Material = [Air, Examples_N_BK7, Air, missing], SemiDiameter = [Inf64, 9.0, 9.0, 15.0] ) ) end """This example no longer works correctly. The visualization code needs to be updated to support RayListSource""" function prism_refraction() # build the triangular prism int = FresnelInterface{Float64}(Examples_N_SF14, Air) s = 2.0 prism = ( Plane( SVector(0.0, -1.0, 0.0), SVector(0.0, -s, 0.0), interface = int, vishalfsizeu = 2 * s, vishalfsizev = 2 * s ) ∩ Plane( SVector(0.0, sind(30), cosd(30)), SVector(0.0, s * sind(30), s * cosd(30)), interface = int, vishalfsizeu = 2 * s, vishalfsizev = 2 * s ) ∩ Plane( SVector(0.0, sind(30), -cosd(30)), SVector(0.0, s * sind(30), -s * cosd(30)), interface = int, vishalfsizeu = 2 * s, vishalfsizev = 2 * s ) ) sys = CSGOpticalSystem(LensAssembly(prism()), Rectangle(15.0, 15.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, -20.0), interface = opaqueinterface())) # create some 'white' light rays = Vector{OpticalRay{Float64,3}}(undef, 0) for i in 0:7 λ = ((i / 7) * 200 + 450) / 1000 r = OpticalRay(SVector(0.0, -3.0, 10.0), SVector(0.0, 0.5, -1.0), 1.0, λ) push!(rays, r) end raygen = Emitters.Sources.RayListSource(rays) # draw the result Vis.drawtracerays(sys, raygenerator = raygen, test = true, trackallrays = true) end function fresnel(convex = true; kwargs...) lens = FresnelLens(Examples_N_BK7, 0.0, convex ? 15.0 : -15.0, 1.0, 8.0, 0.8, conic = 0.1) sys = CSGOpticalSystem(LensAssembly(lens()), Rectangle(15.0, 15.0, SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, -25.0), interface = opaqueinterface())) Vis.drawtracerays(sys; test = true, trackallrays = true, numdivisions = 30, kwargs...) end """This example no longer works correctly. The visualization code needs to be updated to support RayListSource""" function eyetrackHOE(nrays = 5000, det = false, showhead = true, zeroorder = false; kwargs...) # TODO update for new specs from Chris hoehalfwidth = 50.0 #25.0 hoehalfheight = 50.0 #22.5 hoecenter = SVector(-8.0 - 25.0, 0.0, -10.0 - 25.0) rect = Rectangle(hoehalfheight, hoehalfwidth, SVector(0.0, 1.0, 0.0), hoecenter) er = 15.0 cornea_rad = 7.85 corneavertex = SVector(0.0, er, 0.0) sourceloc = SVector(-33.0, er, 0.0) camloc = SVector(20.0, 3.0, -11.0) camdir = corneavertex - camloc camdir_norm = normalize(camdir) interfaces = [] # offset = SVector(-5.0, 10.0, -10.0) # for θ in 0:(π / 6):(2π) # ledloc = SVector(20 * cos(θ) + offset[1], 0 + offset[2], 15 * sin(θ) + offset[3]) # int = HologramInterface(ledloc, ConvergingBeam, sourceloc, DivergingBeam, 0.78, 100.0, Air, Examples_N_BK7, Air, Air, Air, 0.05, zeroorder) # push!(interfaces, int) # end dirs = [SVector(0.7713, 0.6350, -0.0437), SVector(0.5667, 0.8111, -0.1445), SVector(0.3400, 0.9349, -0.1017), SVector(0.1492, 0.9878, 0.0445), SVector(0.0249, 0.9686, 0.2474), SVector(-0.0184, 0.8855, 0.4643), SVector(0.0254, 0.7537, 0.6567), SVector(0.1548, 0.5964, 0.7876), SVector(0.3570, 0.4462, 0.8207), SVector(0.5959, 0.3470, 0.7242), SVector(0.7976, 0.3449, 0.4948), SVector(0.8680, 0.4555, 0.1978)] for d in dirs int = HologramInterface(normalize(d), CollimatedBeam, sourceloc, DivergingBeam, 0.78, 100.0, Air, Examples_N_BK7, Air, Air, Air, 0.05, zeroorder) # int = HologramInterface(corneavertex - 10 * d, ConvergingBeam, sourceloc, DivergingBeam, 0.78, 100.0, Air, Examples_N_BK7, Air, Air, Air, 0.05, zeroorder) push!(interfaces, int) end mint = MultiHologramInterface(interfaces...) obj = MultiHologramSurface(rect, mint) cornea = leaf(Sphere(cornea_rad, interface = FresnelInterface{Float64}(EYE.CORNEA, Air, reflectance = 1.0, transmission = 0.0)), translation(0.0, er + cornea_rad, 0.0))() # cam settings fnum = 2.0 fov = 80 sensorrad = 1.0 barrellength = sensorrad / tand(fov / 2) aprad = barrellength / fnum / 2 camrad = max(sensorrad, aprad) camap = Annulus(aprad, camrad, camdir_norm, camloc) distfromcamtoeye = norm(camdir) focallength = 1 / (1 / distfromcamtoeye + 1 / barrellength) camlens = ParaxialLensEllipse(focallength, aprad, aprad, -camdir_norm, camloc) barrelloc = camloc - barrellength / 2 * camdir_norm barreltop = Plane(camdir_norm, camloc) barrelbot = Plane(-camdir_norm, camloc - 3 * barrellength * camdir_norm) barrelrot = OpticSim.Geometry.rotmatbetween(SVector(0.0, 0.0, 1.0), camdir_norm) cambarrel = ( barrelbot ∩ barreltop ∩ leaf(Cylinder(camrad, barrellength, interface = opaqueinterface(Float64)), Transform(barrelrot, barrelloc)) )() camdet = Circle(sensorrad, camdir_norm, camloc - barrellength * camdir_norm, interface = opaqueinterface(Float64)) # sourceleft = hoecenter[1] + hoehalfwidth - sourceloc[1] # sourceright = hoecenter[1] - hoehalfwidth - sourceloc[1] # sourceleftθ = atan(sourceleft, sourceloc[2]) # sourcerightθ = atan(sourceright, sourceloc[2]) # midθ = (sourceleftθ + sourcerightθ) / 2 # sourcedir = normalize(SVector(er * tan(midθ), -er, 0.0)) # sourceextentθ = abs(midθ - sourcerightθ) # source = CosineOpticalSource(RandomSource(OriginPoint{Float64}(1, position = sourceloc, direction = sourcedir), nrays, sourceextentθ), 1.0, 0.78) rays = Vector{OpticalRay{Float64,3}}(undef, nrays) @simd for i in 1:nrays p = point(rect, rand() * 2 - 1, rand() * 2 - 1) rays[i] = OpticalRay(sourceloc, p - sourceloc, 1.0, 0.78) end source = Emitters.Sources.RayListSource(rays) sys = CSGOpticalSystem(LensAssembly(obj, cornea, camlens, cambarrel, camap), camdet, 800, 800) if det Vis.show(OpticSim.traceMT(sys, source)) else Vis.drawtracerays(sys; raygenerator = source, trackallrays = true, kwargs...) # for θ in 0:(π / 6):(2π) # ledloc = SVector(20 * cos(θ) + offset[1], 0 + offset[2], 15 * sin(θ) + offset[3]) # Vis.draw!(leaf(Sphere(1.0), translation(ledloc...)), color = :red) # end for d in dirs # Vis.draw!(leaf(Sphere(1.0), translation((corneavertex - 10 * d)...)), color = :red) Vis.draw!((corneavertex - 50 * d, corneavertex), color = :red) end if showhead Vis.draw!(joinpath(@__DIR__, "../../OBJ/glasses.obj"), scale = 100.0, transform = Transform(OpticSim.rotmatd(90, 0, 0), [27.0, 45.0, -8.0]), color = :black) Vis.draw!(joinpath(@__DIR__, "../../OBJ/femalehead.obj"), scale = 13.0, transform = Transform(OpticSim.rotmatd(0, 0, 180), [27.0, 105.0, -148.0]), color = :white) end Vis.display() end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
2342
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. export drawrectlattice, drawhexneighbors, drawhexregion, drawhexrect, drawhexrectcolors export hex3cluster, hex3RGB, hexRGBW, hex12RGB export drawhex3RGB, drawhex12RGB drawrectlattice() = Vis.drawcells(Repeat.RectangularBasis(),50.0,SMatrix{2,4,Int64}(0,0,0,1,1,0,1,1)) """draw the 2 ring neighbors of the hex cell at coordinates (0,0)""" drawhexneighbors() = Vis.drawcells(Repeat.HexBasis1(),50,Repeat.neighbors(Repeat.HexBasis1,(0,0),2)) """draw hex cell at coordinates (0,0) and the 1 and 2 ring neighbors""" drawhexregion() = Vis.drawcells(Repeat.HexBasis1(),50,Repeat.region(Repeat.HexBasis1,(0,0),2)) """draw hex cells that fit within a rectangular box centered at coordinates (0,0). Use fill color yellow.""" function drawhexrect() cells = Repeat.hexcellsinbox(2,2) Vis.drawcells(Repeat.HexBasis1(),50,cells,color = repeat(["yellow"],length(cells))) end """draw hex cells that fit within a rectangular box centered at coordinates (0,0). Use random fill colors selected for maximum distinguishability.""" function drawhexrectcolors() cells = Repeat.hexcellsinbox(4,4) Vis.drawcells(Repeat.HexBasis1(),30,cells) end """ Create a LatticeCluser with three elements at (0,0),(-1,0),(-1,1) coordinates in the HexBasis1 lattice""" function hex3cluster() clusterelts = SVector((0,0),(-1,0),(-1,1)) eltlattice = HexBasis1() clusterbasis = LatticeBasis(( -1,2),(2,-1)) return LatticeCluster(clusterbasis,eltlattice,clusterelts) end """ Create a ClusterWithProperties with four types of elements, R,G,B,W """ function hexRGBW() clusterelements = SVector((0,0),(-1,0),(-1,1),(0,-1)) colors = [colorant"red",colorant"green",colorant"blue",colorant"white"] names = ["R","G","B","W"] eltlattice = HexBasis1() clusterbasis = LatticeBasis((0,2),(2,-2)) lattice = LatticeCluster(clusterbasis,eltlattice,clusterelements) properties = DataFrame(Color = colors, Name = names) return ClusterWithProperties(lattice,properties) end """ draw 3 repeats of hex3RGB cluster """ drawhex3RGB() = Vis.draw(hex3RGB(),[0 1 0; 0 0 1]) """ draw 3 repeats of hex12RGB cluster """ drawhex12RGB() = Vis.draw(Repeat.Multilens.hex12RGB(),[0 1 0 1; 0 0 1 1])
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
14594
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ AcceleratedParametricSurface{T,N,S} <: ParametricSurface{T,N} Wrapper class for [`ParametricSurface`](@ref)s where analytical intersection isn't feasible (e.g. [`ZernikeSurface`](@ref), [`ChebyshevSurface`](@ref)). The surface is instead triangulated and an iterative (newton raphson) process carried out to determine precise ray intersection points. `S` is the type of the ParametricSurface being wrapped. ```julia AcceleratedParametricSurface(surf::ParametricSurface{T,N}, numsamples::Int = 17; interface::NullOrFresnel{T} = nullinterface(T)) ``` """ struct AcceleratedParametricSurface{T,N,S<:ParametricSurface{T,N}} <: ParametricSurface{T,N} surface::S triangles::Vector{Triangle{T}} sidelengths::Vector{T} triangles_bbox::BoundingBox{T} interface::NullOrFresnel{T} function AcceleratedParametricSurface(surf::S, numsamples::Int = 17; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real,N,S<:ParametricSurface{T,N}} a = AcceleratedParametricSurface(surf, triangulate(surf, numsamples, true, true), interface = interface) emptytrianglepool!(T) return a end function AcceleratedParametricSurface(surf::S, triangles::Vector{Triangle{T}}; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real,N,S<:ParametricSurface{T,N}} sidelengths = Vector{T}(undef, length(triangles)) @inbounds @simd for i in 1:length(triangles) t = triangles[i] sidelengths[i] = max(norm(t.BA), norm(t.CA)) end return new{T,N,S}(surf, copy(triangles), sidelengths, BoundingBox(triangles), interface) end end export AcceleratedParametricSurface uvrange(::Type{AcceleratedParametricSurface{T,N,S}}) where {T<:Real,N,S<:ParametricSurface{T,N}} = uvrange(S) uvrange(surf::AcceleratedParametricSurface{T,N,S}) where {T<:Real,N,S<:ParametricSurface{T,N}} = uvrange(surf.surface) point(surf::AcceleratedParametricSurface{T,N,S}, u::T, v::T) where {T<:Real,N,S<:ParametricSurface{T,N}} = point(surf.surface, u, v) partials(surf::AcceleratedParametricSurface{T,N,S}, u::T, v::T) where {T<:Real,N,S<:ParametricSurface{T,N}} = partials(surf.surface, u, v) normal(surf::AcceleratedParametricSurface{T,N,S}, u::T, v::T) where {T<:Real,N,S<:ParametricSurface{T,N}} = normal(surf.surface, u, v) inside(surf::AcceleratedParametricSurface{T,N,S}, x::T, y::T, z::T) where {T<:Real,N,S<:ParametricSurface{T,N}} = inside(surf.surface, x, y, z) onsurface(surf::AcceleratedParametricSurface{T,N,S}, x::T, y::T, z::T) where {T<:Real,N,S<:ParametricSurface{T,N}} = onsurface(surf.surface, x, y, z) """ interface(surf::Surface{T}) -> OpticalInterface{T} Return the [`OpticalInterface`](@ref) associated with `surf`. """ interface(a::AcceleratedParametricSurface{T}) where {T<:Real} = a.interface uv(surf::AcceleratedParametricSurface{T,3}, x::T, y::T, z::T) where {T<:Real} = uv(surf.surface, x, y, z) function BoundingBox(surf::AcceleratedParametricSurface{T,3}) where {T<:Real} # the stored bbox is a tight one around the triangulated surface only, in reality the half-space created is an infinite prism capped by the triangulated surface # this bounding box is not accurate to the actual surface, but it is accurate to the triangulated surface # if a ray hits the accurate bounding box but not the triangulated bounding box then it would miss the triangulated surface # anyway (erroneously) and not return an intersection - so we don't lose anything by making this approximation here tbox = surf.triangles_bbox return BoundingBox(tbox.xmin, tbox.xmax, tbox.ymin, tbox.ymax, typemin(T), tbox.zmax) end # function makemesh(surface::AcceleratedParametricSurface{S,N,T}, ::Int) where {S<:Real,N,T<:ParametricSurface{S,N}} # # If we've already triangulated the surface then use this directly as it will be the most # # accurate representation of the surface being intersected with # return TriangleMesh(surface.triangles) # end # "computes all the intersections of the ray with the surface. Each intersection is represented as an Interval that encloses the interior of the object. If the ray is entering the surface, dot(ray,normal) < 0, then the interval is (intersection,infinity) where α is the parametric value of the line surface intersection. If the ray is leaving the surface, dot(ray,normal) > 0, then the interval is (rayorigin, α). If there are two intersections with the surface then returns an Interval(intersection,intersection). If there are multiple segments enclosing the object then will return a list that will contain some combination of the above types of Interval." # fallback method for any accelerated surface which doesn't have an overridden method """ surfaceintersection(surf::Surface{T}, r::AbstractRay{T}) where {T} Calculates the intersection of `r` with a surface of any type, `surf`. Note that some surfaces cannot be intersected analytically so must be wrapped in an [`AcceleratedParametricSurface`](@ref) in order to be intersected. Returns an [`EmptyInterval`](@ref) if there is no [`Intersection`](@ref), an [`Interval`](@ref) if there is one or two intersections and a [`DisjointUnion`](@ref) if there are more than two intersections. """ function surfaceintersection(surf::AcceleratedParametricSurface{T,N}, r::AbstractRay{T,N}) where {T,N} if doesintersect(surf.triangles_bbox, r) i = triangulatedintersection(surf, r) if i isa EmptyInterval{T} if inside(surf, origin(r)) return rayorigininterval(Infinity(T)) else return EmptyInterval(T) end else return i end else if inside(surf, origin(r)) return rayorigininterval(Infinity(T)) else return EmptyInterval(T) end end end """ triangulatedintersection(surf::AcceleratedParametricSurface{T,N,S}, r::AbstractRay{T,N}) Intersection of a ray, `r`, with a triangulated surface, `surf`, no concept of inside so never returns a [`RayOrigin`](@ref) [`Interval`](@ref). """ function triangulatedintersection(surf::AcceleratedParametricSurface{T,N,S}, r::AbstractRay{T,N}) where {T<:Real,N,S} result = newinintervalpool!(T) offset_ray = Ray(origin(r) - ACCEL_SURF_RAY_OFFSET * direction(r), direction(r)) for (i, tri) in enumerate(surf.triangles) # test if the ray is within the maximum side length from one of the points, if not then skip it w = vertex(tri, 1) - origin(r) dist = norm(w - dot(w, direction(r)) * direction(r)) if dist > surf.sidelengths[i] continue end # find the triangle intersection - it's quite possible that for rays starting near the surface we will we miss # an intersection because of imprecise triangulation, so introduce an offset intv = surfaceintersection(tri, offset_ray) if !(intv isa EmptyInterval{T}) ints = halfspaceintersection(intv) if α(ints) <= ACCEL_SURF_RAY_OFFSET # skip any intersection behind the true start point (with some wiggle room) continue end let dup = false # check if a point with the same alpha had already been included, if so ignore this one # doing this check now avoids executing newton many times unnecessarily for eintv in result eints = halfspaceintersection(eintv) if samepoint(α(eints), α(ints) + ACCEL_SURF_RAY_OFFSET) dup = true break end end if !dup # evaluate the precise point of the intersection with the surface intuv = newton(surf.surface, r, uv(ints)) # check that the evaluated uv point lies on the (correct side of the) ray if intuv !== nothing u, v = intuv surfpt = point(surf, u, v) t = α(r, surfpt) # this is the 'true' α again (i.e. not offset) if t > zero(T) # check again that this point hasn't already been included (α might be slightly different, i.e. more accurate, now) for eintv in result eints = halfspaceintersection(eintv) if samepoint(α(eints), t) dup = true break end end if !dup && samepoint(point(r, t), surfpt) # intersection is good so calc the normal and add to list surfnormal = normal(surf, u, v) intsct = Intersection(t, surfpt, surfnormal, u, v, interface(surf)) if dot(direction(r), surfnormal) < zero(T) intvl = positivehalfspace(intsct) else intvl = rayorigininterval(intsct) end push!(result, intvl) end end end end end end end nr = length(result) if nr === 0 return EmptyInterval(T) elseif nr === 1 return result[1] end # sort!(result, lt = (a, b) -> α(halfspaceintersection(a)) < α(halfspaceintersection(b))) #this will sort the intervals by α # alloc free sort of result @inbounds for i in 2:nr value = result[i] j = i - 1 while j > 0 && α(halfspaceintersection(result[j])) > α(halfspaceintersection(value)) result[j + 1] = result[j] j = j - 1 end result[j + 1] = value end let start = 1 temp = newinintervalpool!(T) if lower(result[1]) isa RayOrigin{T} # Starting "inside" the surface, i.e., n̂⋅d̂, > 0. # Can't truly define inside for Bezier patches because they don't define a half-space. start = 2 push!(temp, result[1]) end @inbounds for i in start:2:(nr - 1) intvlintsct = intervalintersection(result[i], result[i + 1]) if !(intvlintsct isa EmptyInterval{T}) push!(temp, intvlintsct) else # this can happen in some edge cases, seems like the best thing to do is juse ignore it... @warn "Funny behavior in triangulated intersection" maxlog = 1 # throw(ErrorException("Triangulated intersection error - this should never happen.")) end end if mod(nr - (start - 1), 2) === 1 #one unpaired interval push!(temp, last(result)) end return DisjointUnion(temp) end end """ jacobian(surf::ParametricSurface{T,N}, u::T, v::T, P1::SVector{M,T}, P2::SVector{M,T}) Computes Jacobian of `f(t,u,v) = ( dot(P1,[surf(u,v),1],P2,[surf(u,v),1]) )`. `P1`, `P2` are orthogonal planes that pass through the ray. `J = [ ∂f1/∂u ∂f1/∂v ; ∂f2/∂u ∂f2/∂v]` """ function jacobian(surf::ParametricSurface{T,N}, u::T, v::T, P1::SVector{M,T}, P2::SVector{M,T}) where {T<:Real,N,M} (du, dv) = partials(surf, u, v) return SMatrix{2,2,T}(dot(view(P1, 1:(M - 1)), du), dot(view(P2, 1:(M - 1)), du), dot(view(P1, 1:(M - 1)), dv), dot(view(P2, 1:(M - 1)), dv)) end """ newton(surf::ParametricSurface{T,N}, r::AbstractRay{T,N}, startingpoint::SVector{2,T}) Newton iteration to find the precise intersection of a parametric surface with a ray given a starting point (in uv space) on the surface. """ function newton(surf::ParametricSurface{T,N}, r::AbstractRay{T,N}, startingpoint::SVector{2,T}) where {T,N} tolerance = 1e-12 maxiterations = 6 urange, vrange = uvrange(surf) dx, dy, dz = direction(r) if abs(dx) > abs(dy) && abs(dx) > abs(dz) N1 = SVector{3,T}(dy, -dx, zero(T)) else N1 = SVector{3,T}(zero(T), dz, -dy) end N2 = cross(N1, direction(r)) P1 = SVector{4,T}(N1[1], N1[2], N1[3], -dot(N1, origin(r))) P2 = SVector{4,T}(N2[1], N2[2], N2[3], -dot(N2, origin(r))) @inline function f(uv::SVector{2,T})::SVector{2,T} psurf = point(surf, uv[1], uv[2]) res1 = zero(T) res2 = zero(T) @inbounds for i in 1:3 res1 += P1[i] * psurf[i] res2 += P2[i] * psurf[i] end res1 += P1[4] res2 += P2[4] # return [dot(P1, vcat(psurf, 1)), dot(P2, vcat(psurf, 1))] return SVector{2,T}(res1, res2) end xilast = startingpoint xi = zeros(SVector{2,T}) error = typemax(T) i = 0 finalpass = false while i < maxiterations if any(isnan.(xilast)) # if something is NaN then just return the starting point and hope that the surface point matches xilast = startingpoint error = zero(T) break end j = jacobian(surf, xilast[1], xilast[2], P1, P2) # xi has values u,v if det(j) == zero(T) # if the jacobian is singular then break at the current iteration and return whatever we have error = zero(T) break end lstf = f(xilast) xi = xilast - (j \ lstf) error = sum(abs.(xi - xilast)) if !finalpass && error < tolerance i = maxiterations - 3 # iterate a few more times after the xi and xi-1 are the same value, at least to 64 bit precision. Seems to give more accurate solutions. Perhaps because of higher precision for intermediate results? finalpass = true end i += 1 xilast = xi end if error > tolerance return nothing else if xi[1] < urange[1] || xi[1] > urange[2] || xi[2] < vrange[1] || xi[2] > vrange[2] return nothing else return xilast end end end # Only show the underlying Bezier surface control points, not the approximating triangle mesh which is generally huge Base.show(io::IO, a::AcceleratedParametricSurface{S,N,T}) where {S<:Real,N,T<:ParametricSurface{S,N}} = println(io, "Accelerated$(string(a.surface))")
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
7620
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. # These constants determine the order in which the g coefficients are stored in the nullspace matrix, and the corresponding moving line matrix. Do not change these. Every other function depends on this. # later will change code so changing these constants will automagically work. const lineindex = 3 const spatialindex = 1 const orderindex = 2 "spatial dimension of curve represented as an array of coefficients `x[i] = ∑Bj(θ)*x[i,j]` where `Bj(θ)` is the curve basis" curvedimension(x::Array) = size(x, spatialindex) "highest polynomial power of the curve represented as an array of coefficients `x[i] = ∑Bj(θ)*x[i,j]` where `Bj(θ)` is the curve basis" curveorder(x::Array) = size(x, orderindex) - 1 numcoefficients(x::Array) = size(x, orderindex) "spatial dimension of the moving line represented as an array of coefficients `g[i] = ∑Bl(θ)*gl[i,j]` where `Bl(θ)` is the polynomial basis" linedimension(x::Array) = size(x, 1) - 1 "number of lines in moving line array" numberoflines(x::Array) = size(x, lineindex) movingline(x::Array, linenum::Integer) = x[:, :, linenum] "returns a matrix expressing the relationship `[x(θ) 1]⋅g(θ) = 0`. The vectors in the right nullspace of this matrix contain the coefficients of the moving lines `gᵢ(θ)`." function orthogonalitymatrix(curve::Array{T,2}, movinglineorder) where {T} x = curve qx = curveorder(x) qg = movinglineorder d = curvedimension(x) C = zeros(T, qx + qg + 1, (d + 1) * (qg + 1)) for i in 1:d, j in 1:(qx + 1), l in 1:(qg + 1) C[(j - 1) + (l - 1) + 1, (i - 1) * (qg + 1) + l] = x[i, j] end # now set the final term which does not include any components of the curve x(theta) for row in 1:(qg + 1) col = d * (qg + 1) + row C[row, col] = one(T) end return C end "returns 3D array indexed like this: `x[line curve order,spatial dimension, line number]``" function extractmovinglines(Vt, nullspacesize, movinglineorder, dimension) rows, _ = size(Vt) # temp = Vt[(rows-nullspacesize + 1):end,:] # println("rows $rows null $nullspacesize") # show(IOContext(stdout), "text/plain", temp) lines = permutedims(Vt[(rows - nullspacesize + 1):end, :]) # use this instead of transpose because transpose is recursive so it tries to transpose the elements of the array and crashes for Expr element types. # show(IOContext(stdout), "text/plain", lines) linecoeffs = movinglineorder + 1 return permutedims(reshape(lines, linecoeffs, (dimension + 1), :), (2, 1, 3)) end "`movinglines[:,i]` is the ith moving line. For `li = movinglines[:,i] (dimension+1,lineorder) = size(li)`. `rline[:,1] = pt1` and `rline[:,2] = pt2`. The line equation is `pt1 + alpha*pt2`." function matricesforeigen(ray::AbstractRay{T,N}, movinglines::Array{T,3}) where {T,N} pt1 = origin(ray) pt2 = direction(ray) dimension = size(pt1, 1) numcoeffs = numcoefficients(movinglines) numlines = numberoflines(movinglines) A = Array{T,2}(undef, numcoeffs, numlines) B = Array{T,2}(undef, numcoeffs, numlines) for i in 1:numlines li = movinglines[:, :, i] for l in 1:numcoeffs asum = zero(T) bsum = zero(T) for j in 1:dimension asum += pt1[j] * li[j, l] bsum += pt2[j] * li[j, l] end asum += li[dimension + 1, l] # add in the final term of the sum that is not dotted with rline bsum = -bsum # reverse sign to get matrices in A-alpha*B form A[l, i] = asum B[l, i] = bsum end end return (A, B) end function matrixsizes(dimension, movinglineorder, curveorder) cols, rows = ((dimension + 1) * (movinglineorder + 1), curveorder + movinglineorder + 1) # cols is the number of coefficients for the moving line. The line has d+1 terms for the line(plane/hyperplane) equation and movinglineorder+1 coefficients for the curve describing the moving line. nullspacesize = cols - rows return cols, rows, nullspacesize end "Evaluates a curve defined in the power basis. Curves and moving lines accessed like this: `[xi,ci]` where `xi` is the dimension index, and `ci` is the coefficient index." function evaluatecurve(x::Array{T,2}, theta::Real) where {T<:Real} # dim,coefficients = size(x) dim = curvedimension(x) numcoeffs = numcoefficients(x) result = Array{T,1}(undef, dim) for dimension in 1:dim power = one(T) sum = zero(T) for coefficient in 1:numcoeffs sum += x[dimension, coefficient] * power power *= theta end result[dimension] = sum end return result end function validintersection(rline::AbstractRay{T,N}, linealpha, curve::Array{T,2}, curvetheta) where {T<:Real,N} if linealpha < 0 return false end linepoint = point(rline, linealpha) curvepoint = evaluatecurve(curve, curvetheta) return isapprox(linepoint, curvepoint, rtol = 1e-10) end function eigenresults(rline::AbstractRay{T,N}, curve::Array{T,2}) where {T<:Real,N} # force rline and curve to use same number type to avoid expensive runtime conversion. dim = curvedimension(curve) orderofcurve = curveorder(curve) movinglineorder = max(orderofcurve, Int64(ceil(orderofcurve * 2 / dim - 1))) # Hve two constraints for movingline order. Must be big enough to result in a nullspace >= orderofcurve for the first step of computing the moving lines. Also need need at least as many eigenvalues as possible intersections of the line with the curve. Eigenmatrix is square of size qgxqg so need this matrix to be at least of size qx by qx. Take the greater of the the two constraint values. cmat = orthogonalitymatrix(curve, movinglineorder) fact = svd(cmat, full = true) nullspace = fact.Vt _, _, nullspacesize = matrixsizes(dim, movinglineorder, orderofcurve) movinglines = extractmovinglines(nullspace, nullspacesize, movinglineorder, dim) A, B = matricesforeigen(rline, movinglines) eig = eigen(A[:, 1:4]', B[:, 1:4]') # transpose so [A-lambdaB]'*Pl = 0 return eig end "returns an array of intersection points. Each element in the array is (`[x,y,...],alpha,theta)` where `[x,y,...]` is the n-dimensional intersection point, alpha is the line parameter value at the intersection point, and theta is the curve parameter value at the intersection point" function intersections(rline::AbstractRay{T,N}, curve::Array{T,2})::Array{Tuple{Array{T,1},T,T}} where {T<:Real,N} eigenstuff = eigenresults(rline, curve) result = Array{Tuple{Array{T,1},T,T}}(undef, 0) for index in CartesianIndices(eigenstuff.values) eigenvector = view(eigenstuff.vectors, :, index) eigenvalue = eigenstuff.values[index] # only take the real part of the solution. Due to roundoff might have real roots with very small complex part. theta = real(eigenvector[2] / eigenvector[1]) # this is only correct for curves defined in power basis. Once new Curve types are defined this function will be determined by the curve basis of the curve. Something like curveParameter(::CurveBasis,eigenvector) println(theta) if validintersection(rline, eigenvalue, curve, theta) push!(result, (point(rline, eigenvalue), eigenvalue, theta)) # return point on curve and alpha and theta parametric values corresponding to this point. end end return result end export intersections
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
12650
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ BoundingBox{T<:Real} Axis-aligned three-dimensional bounding box. ```julia BoundingBox(xmin::T, xmax::T, ymin::T, ymax::T, zmin::T, zmax::T) BoundingBox(s::Surface{T}) BoundingBox(s::ParametricSurface{T,3}, transform::Transform{T} = identitytransform(T)) BoundingBox(c::CSGTree{T}) BoundingBox(tri::Triangle{T}) BoundingBox(triangles::AbstractVector{Triangle{T}}) BoundingBox(points::AbstractArray{SVector{3,T}}) BoundingBox(la::LensAssembly{T}) ``` """ struct BoundingBox{T<:Real} xmin::T ymin::T zmin::T xmax::T ymax::T zmax::T function BoundingBox(xmin::T, xmax::T, ymin::T, ymax::T, zmin::T, zmax::T) where {T<:Real} # if anything is NaN then we want to fall back to the infinite bounding box # if the input bounds are infinite then we also want to fall back to the infinite bounding box - this is necessary because the signs of the Infinity can sometimes get messed up # isinf(-Inf) == true so this works for any infinity xmin = isnan(xmin) || isinf(xmin) ? typemin(T) : xmin ymin = isnan(ymin) || isinf(ymin) ? typemin(T) : ymin zmin = isnan(zmin) || isinf(zmin) ? typemin(T) : zmin xmax = isnan(xmax) || isinf(xmax) ? typemax(T) : xmax ymax = isnan(ymax) || isinf(ymax) ? typemax(T) : ymax zmax = isnan(zmax) || isinf(zmax) ? typemax(T) : zmax if xmin <= xmax && ymin <= ymax && zmin <= zmax return new{T}(xmin, ymin, zmin, xmax, ymax, zmax) else throw(ErrorException("Invalid bounding box")) end end end export BoundingBox function BoundingBox(s::ParametricSurface{T,3}, transform::Transform{T} = identitytransform(T)) where {T<:Real} # get the bounding box of a transformed bounding box bbox = BoundingBox(s) if transform == identitytransform(T) return bbox else p1 = transform * SVector(bbox.xmin, bbox.ymin, bbox.zmin) p2 = transform * SVector(bbox.xmin, bbox.ymax, bbox.zmin) p3 = transform * SVector(bbox.xmin, bbox.ymax, bbox.zmax) p4 = transform * SVector(bbox.xmin, bbox.ymin, bbox.zmax) p5 = transform * SVector(bbox.xmax, bbox.ymin, bbox.zmin) p6 = transform * SVector(bbox.xmax, bbox.ymax, bbox.zmin) p7 = transform * SVector(bbox.xmax, bbox.ymax, bbox.zmax) p8 = transform * SVector(bbox.xmax, bbox.ymin, bbox.zmax) return BoundingBox(SVector(p1, p2, p3, p4, p5, p6, p7, p8)) end end function BoundingBox(tri::Triangle{T}) where {T<:Real} big = fill(typemin(T), SVector{3,T}) small = fill(typemax(T), SVector{3,T}) for vert in vertices(tri) small = min.(small, vert) big = max.(big, vert) end return BoundingBox(small[1], big[1], small[2], big[2], small[3], big[3]) end function BoundingBox(triangles::AbstractVector{Triangle{T}}) where {T<:Real} big = fill(typemin(T), SVector{3,T}) small = fill(typemax(T), SVector{3,T}) for tri in triangles for vert in vertices(tri) small = min.(small, vert) big = max.(big, vert) end end return BoundingBox(small[1], big[1], small[2], big[2], small[3], big[3]) end function BoundingBox(points::AbstractArray{SVector{3,T}}) where {T<:Real} xmax = maximum((x) -> x[1], points) ymax = maximum((x) -> x[2], points) zmax = maximum((x) -> x[3], points) xmin = minimum((x) -> x[1], points) ymin = minimum((x) -> x[2], points) zmin = minimum((x) -> x[3], points) return BoundingBox(xmin, xmax, ymin, ymax, zmin, zmax) end function area(a::BoundingBox{T}) where {T<:Real} dx = a.xmax - a.xmin dy = a.ymax - a.ymin dz = a.zmax - a.zmin return 2 * (dx * dy + dy * dz + dz * dx) end union(::Nothing, b::BoundingBox{T}) where {T<:Real} = b union(a::BoundingBox{T}, ::Nothing) where {T<:Real} = a function union(a::BoundingBox{T}, b::BoundingBox{T}) where {T<:Real} return BoundingBox(min(a.xmin, b.xmin), max(a.xmax, b.xmax), min(a.ymin, b.ymin), max(a.ymax, b.ymax), min(a.zmin, b.zmin), max(a.zmax, b.zmax)) end function intersection(a::BoundingBox{T}, b::BoundingBox{T}) where {T<:Real} if a.xmax < b.xmin || a.ymax < b.ymin || a.zmax < b.zmin || b.xmax < a.xmin || b.ymax < a.ymin || b.zmax < b.zmin @info a, b return nothing else return BoundingBox(max(a.xmin, b.xmin), min(a.xmax, b.xmax), max(a.ymin, b.ymin), min(a.ymax, b.ymax), max(a.zmin, b.zmin), min(a.zmax, b.zmax)) end end """ doesintersect(bbox::BoundingBox{T}, r::AbstractRay{T,3}) -> Bool Tests whether `r` intersects an axis-aligned [`BoundingBox`](@ref), `bbox`. """ function doesintersect(a::BoundingBox{T}, r::AbstractRay{T,3}) where {T<:Real} if inside(a, origin(r)) || onsurface(a, origin(r)) return true end d = direction(r) o = origin(r) # Infs and zeros get us into all kinds of problems with AutoDiff here.. # work arounds are possible in all cases, the code just gets messy :( # really we are doing this: # dfx = one(T) / d[1] # dfy = one(T) / d[2] # dfz = one(T) / d[3] # t1 = (a.xmin - o[1]) * dfx # t2 = (a.xmax - o[1]) * dfx # t3 = (a.ymin - o[2]) * dfy # t4 = (a.ymax - o[2]) * dfy # t5 = (a.zmin - o[3]) * dfz # t6 = (a.zmax - o[3]) * dfz # tmin = max(max(min(t1, t2), min(t3, t4)), min(t5, t6)) # tmax = min(min(max(t1, t2), max(t3, t4)), max(t5, t6)) tmin = typemin(T) tmax = typemax(T) if d[1] != zero(T) # don't really understand why the gradient fails here is xmin or xmax is Inf, but this fixes it tx1 = isinf(a.xmin) ? sign(d[1]) * a.xmin : (a.xmin - o[1]) / d[1] tx2 = isinf(a.xmax) ? sign(d[1]) * a.xmax : (a.xmax - o[1]) / d[1] else # avoiding divide by zero (when d[1] == 0) to preserve gradients tx1 = sign(a.xmin - o[1]) * typemax(T) tx2 = sign(a.xmax - o[1]) * typemax(T) end # avoid min/max on Infs to preserve gradients if tx1 > tx2 if tmin < tx2 tmin = tx2 end if tmax > tx1 tmax = tx1 end else if tmin < tx1 tmin = tx1 end if tmax > tx2 tmax = tx2 end end # below uses the same NaN avoidance techniques... if d[2] != zero(T) ty1 = isinf(a.ymin) ? sign(d[2]) * a.ymin : (a.ymin - o[2]) / d[2] ty2 = isinf(a.ymax) ? sign(d[2]) * a.ymax : (a.ymax - o[2]) / d[2] else ty1 = sign(a.ymin - o[2]) * typemax(T) ty2 = sign(a.ymax - o[2]) * typemax(T) end if ty1 > ty2 if tmin < ty2 tmin = ty2 end if tmax > ty1 tmax = ty1 end else if tmin < ty1 tmin = ty1 end if tmax > ty2 tmax = ty2 end end if d[3] != zero(T) tz1 = isinf(a.zmin) ? sign(d[3]) * a.zmin : (a.zmin - o[3]) / d[3] tz2 = isinf(a.zmax) ? sign(d[3]) * a.zmax : (a.zmax - o[3]) / d[3] else tz1 = sign(a.zmin - o[3]) * typemax(T) tz2 = sign(a.zmax - o[3]) * typemax(T) end if tz1 > tz2 if tmin < tz2 tmin = tz2 end if tmax > tz1 tmax = tz1 end else if tmin < tz1 tmin = tz1 end if tmax > tz2 tmax = tz2 end end return tmax >= tmin && tmax > zero(T) end export doesintersect function inside(a::BoundingBox{T}, p::SVector{3,T}) where {T<:Real} return a.xmin < p[1] < a.xmax && a.ymin < p[2] < a.ymax && a.zmin < p[3] < a.zmax end function onsurface(a::BoundingBox{T}, p::SVector{3,T}) where {T<:Real} return ((p[1] === a.xmin || p[1] === a.xmax) && a.ymin < p[2] < a.ymax && a.zmin < p[3] < a.zmax) || (a.xmin < p[1] < a.xmax && (p[2] === a.ymin || p[2] === a.ymax) && a.zmin < p[3] < a.zmax) || (a.xmin < p[1] < a.xmax && a.ymin < p[2] < a.ymax && (p[3] === a.zmin || p[3] === a.zmax)) end """ surfaceintersection(bbox::BoundingBox{T}, r::AbstractRay{T,3}) -> Union{EmptyInterval{T},Interval{T}} Calculates the intersection of `r` with an axis-aligned [`BoundingBox`](@ref), `bbox`. Returns an [`EmptyInterval`](@ref) if there is no intersection or an [`Interval`](@ref) if there is one or two intersections. Note that the uv of the returned intersection is always **0**. """ function surfaceintersection(a::BoundingBox{T}, r::AbstractRay{T,3}) where {T<:Real} d = direction(r) o = origin(r) # Infs and zeros get us into all kinds of problems with AutoDiff here.. # work arounds are possible in all cases, the code just gets messy :( # really we are doing this: # dfx = one(T) / d[1] # dfy = one(T) / d[2] # dfz = one(T) / d[3] # t1 = (a.xmin - o[1]) * dfx # t2 = (a.xmax - o[1]) * dfx # t3 = (a.ymin - o[2]) * dfy # t4 = (a.ymax - o[2]) * dfy # t5 = (a.zmin - o[3]) * dfz # t6 = (a.zmax - o[3]) * dfz # tmin = max(max(min(t1, t2), min(t3, t4)), min(t5, t6)) # tmax = min(min(max(t1, t2), max(t3, t4)), max(t5, t6)) tmin = typemin(T) tmax = typemax(T) upper_normal = nothing lower_normal = nothing if d[1] != zero(T) # don't really understand why the gradient fails here is xmin or xmax is Inf, but this fixes it tx1 = isinf(a.xmin) ? sign(d[1]) * a.xmin : (a.xmin - o[1]) / d[1] tx2 = isinf(a.xmax) ? sign(d[1]) * a.xmax : (a.xmax - o[1]) / d[1] else # avoiding divide by zero (when d[1] == 0) to preserve gradients tx1 = sign(a.xmin - o[1]) * typemax(T) tx2 = sign(a.xmax - o[1]) * typemax(T) end # avoid min/max on Infs to preserve gradients if tx1 > tx2 if tmin < tx2 lower_normal = SVector{3,T}(1, 0, 0) tmin = tx2 end if tmax > tx1 upper_normal = SVector{3,T}(-1, 0, 0) tmax = tx1 end else if tmin < tx1 lower_normal = SVector{3,T}(-1, 0, 0) tmin = tx1 end if tmax > tx2 upper_normal = SVector{3,T}(1, 0, 0) tmax = tx2 end end # below uses the same NaN avoidance techniques... if d[2] != zero(T) ty1 = isinf(a.ymin) ? sign(d[2]) * a.ymin : (a.ymin - o[2]) / d[2] ty2 = isinf(a.ymax) ? sign(d[2]) * a.ymax : (a.ymax - o[2]) / d[2] else ty1 = sign(a.ymin - o[2]) * typemax(T) ty2 = sign(a.ymax - o[2]) * typemax(T) end if ty1 > ty2 if tmin < ty2 lower_normal = SVector{3,T}(0, 1, 0) tmin = ty2 end if tmax > ty1 upper_normal = SVector{3,T}(0, -1, 0) tmax = ty1 end else if tmin < ty1 lower_normal = SVector{3,T}(0, -1, 0) tmin = ty1 end if tmax > ty2 upper_normal = SVector{3,T}(0, 1, 0) tmax = ty2 end end if d[3] != zero(T) tz1 = isinf(a.zmin) ? sign(d[3]) * a.zmin : (a.zmin - o[3]) / d[3] tz2 = isinf(a.zmax) ? sign(d[3]) * a.zmax : (a.zmax - o[3]) / d[3] else tz1 = sign(a.zmin - o[3]) * typemax(T) tz2 = sign(a.zmax - o[3]) * typemax(T) end if tz1 > tz2 if tmin < tz2 lower_normal = SVector{3,T}(0, 0, 1) tmin = tz2 end if tmax > tz1 upper_normal = SVector{3,T}(0, 0, -1) tmax = tz1 end else if tmin < tz1 lower_normal = SVector{3,T}(0, 0, -1) tmin = tz1 end if tmax > tz2 upper_normal = SVector{3,T}(0, 0, 1) tmax = tz2 end end if !(tmax >= tmin && tmax > zero(T)) return EmptyInterval(T) else if tmin <= zero(T) if tmax == typemax(T) return rayorigininterval(Infinity(T)) else return rayorigininterval(Intersection(tmax, point(r, tmax), upper_normal, zero(T), zero(T), NullInterface(T))) end else lower = Intersection(tmin, point(r, tmin), lower_normal, zero(T), zero(T), NullInterface(T)) if tmax == typemax(T) return positivehalfspace(lower) else return Interval(lower, Intersection(tmax, point(r, tmax), upper_normal, zero(T), zero(T), NullInterface(T))) end end end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
4388
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. #= Notes for CSG bounding boxes The intersection nodes could compute bounding boxes as the CSGTree is being constructed because the bbox can only be equal or smaller than either of the children. Subtrees of union nodes should be processed as a whole so they can be properly subdivided or the bounding boxes are likely to be very inefficient. Need to cluster nodes geometrically to subdivide well but the order in which the unions are called by the user's code is unlikely to have the best geometric distribution. This makes the recursion a bit more complicated than conventional BVH because of the interleaved union and intersection operations. =# """if fewer than this many primitives in a bounding box then do no subdivide further""" const minprims = 4 abstract type BVHNode{T<:Real,S<:Primitive{T}} end struct SplitBVH{T<:Real,S<:Primitive{T}} <: BVHNode{T,S} left::BVHNode{T,S} right::BVHNode{T,S} axis::Int64 end struct LeafBVH{T<:Real,S<:Primitive{T}} <: BVHNode{T,S} primitives::Vector{S} end struct BVHData{T<:Real,S<:Primitive{T}} primitive::S centroid::SVector{3,T} boundingbox::BoundingBox{T} end centroid(a::BVHData) = a.centroid boundingbox(a::BVHData) = a.boundingbox primitive(a::BVHData) = a.primitive struct PrimitiveData{T<:Real,S<:Primitive{T}} data::Vector{BVHData{T,S}} boundingbox::BoundingBox{T} function PrimitiveData(primitives::Vector{S}) where {T<:Real,S<:Primitive{T}} combined = Vector{BVHData{T,S}}(undef, length(primitives)) totalbox = nothing for i in eachindex(primitives) box = BoundingBox(primitives[i]) combined[i] = BVHData{T,S}(primitives[i], centroid(primitives[i]), box) totalbox = union(totalbox, box) end return new{T,S}(combined, totalbox) end end function computebvh(a::PrimitiveData) subdivide(a.boundingbox, a) end function subdivide(parentbounds::BoundingBox{T}, primitives::AbstractVector{S}) where {T<:Real,S<:Primitive{T}} if length(primitives <= minprims) return LeafBVH(primitives) else # test subdivision in 3 axes. #partition primitives # compute costs using parentbounds # return SplitBVH(subdivide(reduce(union,leftprims),leftprims),subdivide(reduce(union,rightprims,rightprims)) end end cost(enclosingbox::BoundingBox{T}, childboxes::AbstractVector{BoundingBox{T}}) where {T<:Real} = sum(area.(childboxes)) / area(enclosingbox) cost(boxes::Vector{BVHData{T,S}}) where {T,S} = sum(area.(boundingbox.(boxes))) function partition!(a::Vector{S}, valfunc::Function, value::T) where {S,T<:Real} lower = 0 upper = lastindex(a) + 1 while true while upper - 1 >= 1 && valfunc(a[upper - 1]) > value upper = upper - 1 end while lower + 1 <= lastindex(a) && valfunc(a[lower + 1]) <= value lower = lower + 1 end if upper - lower == 1 if lower == 0 return (nothing, a) else if upper == lastindex(a) + 1 return (a, nothing) else return (view(a, 1:lower), view(a, upper:lastindex(a))) end end end temp = a[upper - 1] a[upper - 1] = a[lower + 1] a[lower + 1] = temp upper = upper - 1 lower = lower + 1 end end """compute compacted version of bounding volume hierarchy that can be traversed more quickly than the original tree structure, without recursion""" function linearizebvh(bvhtree::BVHNode{T,S}) where {T<:Real,S<:Primitive{T}} end """traverses BVH and computes surface intersection""" function surfaceintersection(a::BVHNode{T,S}, r::Ray{T,N}) where {T<:Real,S<:Primitive{T},N} end # function testpartition() # split = .5 # for i in 1:10000000 # a = rand(5) # lower,upper = partition!(a,(x)->x,split) # if lower !== nothing # for i in lower # @assert i < split # end # end # if upper !== nothing # for i in upper # @assert i > split # end # end # end # end export PrimitiveData
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
8124
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. # declaring the Geometry module. in the future we might add or move existing code to it. currently it contains the basic types: Vec3, Vec4 and Transform module Geometry include("Transform.jl") end # module Geometry export Geometry using .Geometry include("Ray.jl") include("Surface.jl") # not ideal having this like this, but we need the types for Intersection include("../Optical/OpticalInterface.jl") include("CSG/Intersection.jl") include("CSG/Interval.jl") include("Primitives/NonCSG/Triangle.jl") include("BoundingBox.jl") include("Primitives/Plane.jl") include("Primitives/Cylinder.jl") include("Primitives/Sphere.jl") include("Primitives/SphericalCap.jl") include("Primitives/NonCSG/PlanarShape.jl") include("Primitives/NonCSG/Rectangle.jl") include("Primitives/NonCSG/Hexagon.jl") include("Primitives/NonCSG/ConvexPolygon.jl") include("Primitives/NonCSG/Ellipse.jl") include("Primitives/NonCSG/Stop.jl") # include("BoundingVolumeHierarchy.jl") include("AccelSurface.jl") include("Primitives/Curves/Knots.jl") include("Primitives/Curves/Spline.jl") include("Primitives/Curves/BSpline.jl") include("Primitives/Curves/Bezier.jl") include("Primitives/Curves/PowerBasis.jl") include("CSG/CSG.jl") include("Primitives/AsphericSurface.jl") include("Primitives/Zernike.jl") include("Primitives/Qtype.jl") include("Primitives/Chebyshev.jl") include("Primitives/GridSag.jl") include("AnalyticIntersection.jl") include("SphericalPolygon.jl") ########################################################################################################### export BoundedCylinder, Cuboid, HexagonalPrism, RectangularPrism, TriangularPrism, Spider """ BoundedCylinder(radius::T, height::T; interface::NullOrFresnel{T} = nullinterface(T)) -> CSGGenerator{T} Create a cylinder with planar caps on both ends centred at `(0, 0, 0)` with axis `(0, 0, 1)`. """ function BoundedCylinder(radius::T, height::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} barrel = Cylinder(radius, height, interface = interface) top = Plane(SVector{3,T}(0.0, 0.0, 1.0), SVector{3,T}(0.0, 0.0, height / 2), vishalfsizeu = radius, vishalfsizev = radius) bottom = Plane(SVector{3,T}(0.0, 0.0, -1.0), SVector{3,T}(0.0, 0.0, -height / 2), vishalfsizeu = radius, vishalfsizev = radius) return barrel ∩ top ∩ bottom end """ Cuboid(halfsizex::T, halfsizey::T, halfsizez::T; interface::NullOrFresnel{T} = nullinterface(T)) -> CSGGenerator{T} Create a cuboid centred at `(0, 0, 0)`. """ function Cuboid(halfsizex::T, halfsizey::T, halfsizez::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} xmin = Plane(SVector{3,T}(-1.0, 0.0, 0.0), SVector{3,T}(-halfsizex, 0.0, 0.0); vishalfsizeu = halfsizez, vishalfsizev = halfsizey, interface) xmax = Plane(SVector{3,T}(1.0, 0.0, 0.0), SVector{3,T}(halfsizex, 0.0, 0.0); vishalfsizeu = halfsizez, vishalfsizev = halfsizey, interface) ymin = Plane(SVector{3,T}(0.0, -1.0, 0.0), SVector{3,T}(0.0, -halfsizey, 0.0); vishalfsizeu = halfsizez, vishalfsizev = halfsizex, interface) ymax = Plane(SVector{3,T}(0.0, 1.0, 0.0), SVector{3,T}(0.0, halfsizey, 0.0); vishalfsizeu = halfsizez, vishalfsizev = halfsizex, interface) zmin = Plane(SVector{3,T}(0.0, 0.0, -1.0), SVector{3,T}(0.0, 0.0, -halfsizez); vishalfsizeu = halfsizex, vishalfsizev = halfsizey, interface) zmax = Plane(SVector{3,T}(0.0, 0.0, 1.0), SVector{3,T}(0.0, 0.0, halfsizez); vishalfsizeu = halfsizex, vishalfsizev = halfsizey, interface) return xmin ∩ xmax ∩ ymin ∩ ymax ∩ zmin ∩ zmax end """ HexagonalPrism(side_length::T, visheight::T = 2.0; interface::NullOrFresnel{T} = nullinterface(T)) -> CSGGenerator{T} Create an infinitely tall hexagonal prism with axis `(0, 0, 1)`, the longer hexagon diameter is along the x axis. For visualization `visheight` is used, **note that this does not fully represent the surface**. """ function HexagonalPrism(side_length::T, visheight::T = 2.0; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} h = side_length * sqrt(3.0) / 2.0 hcos = h * sqrt(3.0) / 2.0 hsin = h / 2.0 vishalfsizeu = visheight / 2.0 vishalfsizev = side_length * 1.0001 / 2.0 s1 = Plane(SVector{3,T}(0.0, 1.0, 0.0), SVector{3,T}(0.0, h, 0.0); vishalfsizeu, vishalfsizev, interface) s2 = Plane(SVector{3,T}(0.0, -1.0, 0.0), SVector{3,T}(0.0, -h, 0.0); vishalfsizeu, vishalfsizev, interface) s3 = Plane(SVector{3,T}(hcos, hsin, 0.0), SVector{3,T}(hcos, hsin, 0.0); vishalfsizeu, vishalfsizev, interface) s4 = Plane(SVector{3,T}(-hcos, -hsin, 0.0), SVector{3,T}(-hcos, -hsin, 0.0); vishalfsizeu, vishalfsizev, interface) s5 = Plane(SVector{3,T}(hcos, -hsin, 0.0), SVector{3,T}(hcos, -hsin, 0.0); vishalfsizeu, vishalfsizev, interface) s6 = Plane(SVector{3,T}(-hcos, hsin, 0.0), SVector{3,T}(-hcos, hsin, 0.0); vishalfsizeu, vishalfsizev, interface) return s1 ∩ s2 ∩ s3 ∩ s4 ∩ s5 ∩ s6 end """ RectangularPrism(halfsizex::T, halfsizey::T, visheight::T=2.0; interface::NullOrFresnel{T} = nullinterface(T)) -> CSGGenerator{T} Create an infinitely tall rectangular prism with axis `(0, 0, 1)`. For visualization `visheight` is used, **note that this does not fully represent the surface**. """ function RectangularPrism(halfsizex::T, halfsizey::T, visheight::T = 2.0; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} vishalfsizeu = visheight / 2.0 s1 = Plane(SVector{3,T}(0.0, 1.0, 0.0), SVector{3,T}(0.0, halfsizey, 0.0); vishalfsizeu, vishalfsizev=halfsizex, interface) s2 = Plane(SVector{3,T}(0.0, -1.0, 0.0), SVector{3,T}(0.0, -halfsizey, 0.0); vishalfsizeu, vishalfsizev=halfsizex, interface) s3 = Plane(SVector{3,T}(1.0, 0.0, 0.0), SVector{3,T}(halfsizex, 0.0, 0.0); vishalfsizeu, vishalfsizev=halfsizey, interface) s4 = Plane(SVector{3,T}(-1.0, 0.0, 0.0), SVector{3,T}(-halfsizex, 0.0, 0.0); vishalfsizeu, vishalfsizev=halfsizey, interface) return s1 ∩ s2 ∩ s3 ∩ s4 end """ TriangularPrism(side_length::T, visheight::T = 2.0; interface::NullOrFresnel{T} = nullinterface(T)) -> CSGGenerator{T} Create an infinitely tall triangular prism with axis `(0, 0, 1)`. For visualization `visheight` is used, **note that this does not fully represent the surface**. """ function TriangularPrism(side_length::T, visheight::T = 2.0; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} vishalfsizeu = visheight / 2 vishalfsizev = side_length / 2 p1 = Plane( SVector{3,T}(-1.0, 0.0, 0.0), SVector{3,T}(-side_length / 4, 0.0, 0.0); interface, vishalfsizeu, vishalfsizev ) p2 = Plane( SVector{3,T}(sind(30), cosd(30), 0.0), SVector{3,T}(side_length / 4 * sind(30), side_length / 4 * cosd(30), 0.0); interface, vishalfsizeu, vishalfsizev ) p3 = Plane( SVector{3,T}(sind(30), -cosd(30), 0.0), SVector{3,T}(side_length / 4 * sind(30), -side_length / 4 * cosd(30), 0.0); interface, vishalfsizeu, vishalfsizev ) return p1 ∩ p2 ∩ p3 end """ Spider(narms::Int, armwidth::T, radius::T, origin::SVector{3,T} = SVector{3,T}(0.0, 0.0, 0.0), normal::SVector{3,T} = SVector{3,T}(0.0, 0.0, 1.0)) -> Vector{Rectangle{T}} Creates a 'spider' obscuration with `narms` rectangular arms evenly spaced around a circle defined by `origin` and `normal`. Each arm is a rectangle `armwidth`×`radius`. e.g. for 3 and 4 arms we get: ``` | _|_ / \\ | ``` """ function Spider(narms::Int, armwidth::T, radius::T, origin::SVector{3,T} = SVector{3,T}(0.0, 0.0, 0.0), normal::SVector{3,T} = SVector{3,T}(0.0, 0.0, 1.0)) where {T<:Real} dθ = 2π / narms rects = Vector{Rectangle{T}}(undef, 0) for i in 0:(narms - 1) θ = i * dθ r = Rectangle(armwidth / 2, radius / 2, normal, origin + SVector(radius / 2 * cos(θ), radius / 2 * sin(θ), 0.0), rotationvec = SVector(cos(θ), sin(θ), 0.0), interface = opaqueinterface(T)) push!(rects, r) end return rects end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
3314
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. abstract type AbstractRay{T<:Real,N} end export AbstractRay """ Ray{T,N} <: AbstractRay{T,N} Purely geometric ray, defined as `origin + alpha * direction`. ```julia Ray(origin::SVector{N,T}, direction::SVector{N,T}) ``` Has the following accessor methods: ```julia direction(ray::Ray{T,N}) -> SVector{N,T} origin(ray::Ray{T,N}) -> SVector{N,T} ``` """ struct Ray{T,N} <: AbstractRay{T,N} origin::SVector{N,T} direction::SVector{N,T} function Ray(origin::SVector{N,T}, direction::SVector{N,T}) where {T<:Real,N} return new{T,N}(origin, normalize(direction)) end function Ray(origin::AbstractArray{T,1}, direction::AbstractArray{T,1}) where {T<:Real} @assert length(origin) == length(direction) N = length(origin) return new{T,N}(SVector{N,T}(origin), normalize(SVector{N,T}(direction))) end end export Ray direction(ray::Ray{T,N}) where {T<:Real,N} = ray.direction origin(ray::Ray{T,N}) where {T<:Real,N} = ray.origin export origin, direction function Base.print(io::IO, a::Ray{T,N}) where {T,N} println(io, "$(rpad("Origin:", 20)) $(origin(a))") println(io, "$(rpad("Direction:", 20)) $(direction(a))") end """ point(ray::AbstractRay{T,N}, alpha::T) -> SVector{T, N} Returns a point on the ray at origin + alpha * direction. Alpha must be >= 0. """ function point(ray::AbstractRay{T,N}, alpha::T) where {N,T<:Real} @assert alpha >= zero(T) "Alpha must be nonnegative. alpha value: $alpha" return origin(ray) + alpha * direction(ray) end """ closestpointonray(r::Ray{T,N}, point::SVector{N,T}) -> SVector{T,N Returns the point on the ray closest to point. """ function closestpointonray(r::AbstractRay{T,N}, point::SVector{N,T}) where {T,N} #find t that gives the smallest distance between the ray and the point #ray = p0 + tr̂, distance = ||line - point|| o = origin(r) r̂ = direction(r) t = dot(point .- o, r̂) if t >= 0.0 return o .+ t .* r̂ else return o end end export closestpointonray """ distance(r::Ray{T,N}, point::SVector{N,T}) -> Union{Nothing,T} Returns distance to the position on the ray closest to point. If t < 0 returns nothing. """ function distance(r::AbstractRay{T,N}, point::SVector{N,T}) where {T,N} #find t that gives the smallest distance between the ray and the point #ray = p0 + tr̂, distance = ||line - point|| # this has redundant code with closestpointonray but it is faster to do this way than to call closestpointonray and then comput norm(result .- point) o = origin(r) r̂ = direction(r) t = dot(point .- o, r̂) if t >= 0.0 temp = o .+ t .* r̂ return norm(temp .- point) else return nothing end end """ α(ray::AbstractRay{T,N}, point::SVector{N,T}) -> T Computes the alpha corresponding to the closest position on the ray to point """ α(ray::AbstractRay{T,N}, point::SVector{N,T}) where {T<:Real,N} = dot(direction(ray), (point .- origin(ray))) """ Apply a Transform to a Ray object """ function Base.:*(a::Transform{T}, r::Ray{T,3})::Ray{T,3} where {T} return Ray(a * origin(r), Geometry.rotate(a, direction(r))) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
5368
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """SphericalPolygon uses StaticArrays to represent vertices. Expect performance degradation for polygons with large numbers of vertices. Performance appears to be good up to perhaps 100 vertices, perhaps as much as 1000 vertices. By 10,000 vertices performance is terrible.""" struct SphericalPolygon{N,T<:Real} ptvectors::SMatrix{3,N,T} spherecenter::SVector{3,T} radius::T function SphericalPolygon(points::SMatrix{3,N,T},spherecenter::SVector{3,T},radius::T) where{T<:Real,N} normpoints = MMatrix{3,N,T}(undef) for i in 1:N normpoints[:,i] = normalize(points[:,i] - spherecenter) end return new{N,T}(SMatrix{3,N,T}(normpoints),SVector{3,T}(spherecenter),radius) end end export SphericalPolygon """returns the spherical angle formed by the cone with centervector at its center with neighbor1,neighbor2 the edges""" function sphericalangle(neighbor1::SVector{3,T}, centervector::SVector{3,T}, neighbor2::SVector{3,T}) where{T<:Real} vec1 = normalize(neighbor1 - (dot(neighbor1,centervector)*centervector)) #subtract off the component of the neighbor vectors from the center vector. This leaves only the component orthogonal to center vector vec2 = normalize(neighbor2 - (dot(neighbor2,centervector)*centervector)) return acos(dot(vec1,vec2)) end struct SphericalTriangle{T<:Real} ptvectors::SMatrix{3,3,T} spherecenter::SVector{3,T} radius::T """Constructor which uses SMatrix to store vectors. For compatibility with LazySets this is more efficient""" function SphericalTriangle(vectors::SMatrix{3,3,T},spherecenter::SVector{3,T},radius::T) where{T} temp = MMatrix{3,3,T}(undef) for col in 1:3 temp[:,col] = normalize(vectors[:,col]-spherecenter) end new{T}(temp,spherecenter,radius) end end export SphericalTriangle vector(a::SphericalTriangle,i::Int) = a.ptvectors[:,i] function area(tri::SphericalTriangle{T}) where{T<:Real} vec1,vec2,vec3 = vector(tri,1),vector(tri,2),vector(tri,3) sum = T(0) sum += sphericalangle(vec1,vec3,vec2) sum += sphericalangle(vec2,vec1,vec3) sum += sphericalangle(vec3,vec2,vec1) return (sum-π) * tri.radius^2 end """Conceptually breaks the convex spherical polygon into spherical triangles and computes the sum of the angles of all the triangles. The sum of all the angles around the centroid is 2π. Have to subtract π for each of the N triangles. Rather than compute the angles of triangles formed by taking edges from the centroid to each vertex, can instead just compute the internal angle of neighboring edges. Total polygon area is 2π -Nπ + ∑(interior angles).""" function area(poly::SphericalPolygon{N,T}) where{T<:Real,N} return area(poly.ptvectors,poly.radius) end function area(ptvecs::SMatrix{3,N,T},radius::T) where{N,T<:Real} accum = T(0) for i in 2:N-1 v1 = SVector{3,T}(ptvecs[1,i-1],ptvecs[2,i-1],ptvecs[3,i-1]) v2 = SVector{3,T}(ptvecs[1,i],ptvecs[2,i],ptvecs[3,i]) v3 = SVector{3,T}(ptvecs[1,i+1],ptvecs[2,i+1],ptvecs[3,i+1]) accum += sphericalangle(v1,v2,v3) end # finish up first and last interior angles which have different indexing because of wraparound v1 = SVector{3,T}(ptvecs[1,N-1],ptvecs[2,N-1],ptvecs[3,N-1]) v2 = SVector{3,T}(ptvecs[1,N],ptvecs[2,N],ptvecs[3,N]) v3 = SVector{3,T}(ptvecs[1,1],ptvecs[2,1],ptvecs[3,1]) accum += sphericalangle(v1,v2,v3) v1 = SVector{3,T}(ptvecs[1,2],ptvecs[2,2],ptvecs[3,2]) v2 = SVector{3,T}(ptvecs[1,1],ptvecs[2,1],ptvecs[3,1]) v3 = SVector{3,T}(ptvecs[1,N],ptvecs[2,N],ptvecs[3,N]) accum += sphericalangle(v1,v2,v3) accum = (2π -N*π + accum)*radius^2 return accum end function circlepoly(nsides; offset = [0.0,0.0,1.0]) step = 2π/nsides result = MMatrix{3,nsides,Float64}(undef) for i in 0:nsides-1 y,x = sincos(step*i) result[:,i+1] = [x,y,0.0] .+ offset end return SMatrix{3,nsides,Float64}(result) end export circlepoly """creates a circular polygon that subtends a half angle of θ""" function sphericalcircle(θ, nsides = 10) temp = MMatrix{3,nsides,Float64}(undef) for i in 0:1:(nsides-1) ϕ = i*2π/nsides temp[1,i+1] = sin(θ)*cos(ϕ) temp[2,i+1] = cos(θ) temp[3,i+1] = sin(θ)*sin(ϕ) end return SphericalPolygon(SMatrix{3,nsides,Float64}(temp),SVector(0.0,0.0,0.0),1.0) end export sphericalcircle oneeigthsphere() = SphericalTriangle(SMatrix{3,3,Float64}( 0.0,1.0,0.0, 1.0,0.0,0.0, 0.0,0.0,1.0), SVector(0.0,0.0,0.0), 1.0) export oneeigthsphere onesixteenthphere() = SphericalTriangle(SMatrix{3,3,Float64}( 0.0,1.0,0.0, 1.0,1.0,0.0, 0.0,0.0,1.0), SVector(0.0,0.0,0.0), 1.0) export onesixteenthphere threesidedpoly() = SphericalPolygon(SMatrix{3,3,Float64}( 0.0,1.0,0.0, 1.0,0.0,0.0, 0.0,0.0,1.0), SVector(0.0,0.0,0.0), 1.0) export threesidedpoly foursidedpoly() = SphericalPolygon(SMatrix{3,4,Float64}( 0.0,1.0,0.0, 1.0,1.0,-.9, 1.0,0.0,0.0, 0.0,0.0,1.0), SVector(0.0,0.0,0.0), 1.0) export foursidedpoly
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
12402
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Primitive{T<:Real} `T` is the number type used to represent the primitive, e.g., `Float64`. Primitives are the basic elements which can be stored in bounding volume hierarchies and include surfaces and CSG objects **Must** implement the following: ```julia boundingbox(a::Primitive{T})::BoundingBox{T} centroid(a::Primitive{T})::SVector{3,T} ``` """ abstract type Primitive{T<:Real} end """ Surface{T<:Real} `T` is the number type used to represent the surface, e.g., `Float64`. Basic `Surface`s are _not_ valid CSG objects, they function only in a stand-alone capacity. **Must** implement the following: ```julia surfaceintersection(surface::Surface{T}, ray::AbstractRay{T,3}) -> Union{EmptyInterval{T},Interval{T}} normal(surface::Surface{T}) -> SVector{3,T} interface(surface::Surface{T}) -> OpticalInterface{T} makemesh(surface::Surface{T}) -> TriangleMesh{T} ``` In a conventional ray tracer the surface intersection function would only return the first surface the ray intersects. Because our ray tracer does CSG operations the surface intersection function intersects the ray with all leaf surfaces which are part of the CSG tree. Each leaf surface returns one or more 1D intervals along the ray. These intervals contain the part of the ray which is inside the surface. The intervals computed at the leaves are propagated upward through the CSG tree and the CSG operations of union, intersection, and difference are applied to generate new intervals which are themselves propagated upward. The result is a union of 1D intervals, which may be disjoint, a single interval, or empty. The union of intervals represents the parts of the ray which are inside the CSG object. Inside is well defined for halfspaces such as cylinders and spheres which divide space into two parts, but not for Bezier or NURBS patches which generally do not enclose a volume. For surfaces which are not halfspaces the notion of inside is defined locally by computing the angle between the incoming ray and the normal of the surface at the point of intersection. All surfaces must be defined so that the normal points to the outside of the surface. A negative dot product between the incoming ray and the normal indicates the ray is coming from the outside of the surface and heading toward the inside. A positive dot product indicates the ray is coming from the inside of the surface and heading toward the outside. Intervals are defined along the ray which is being intersected with the surface, so they are one dimensional. For example, assume we have a ray with origin o on the outside of a plane and an intersection with the plane at point int = o + td where t is a scalar and d is the unit direction of the ray. The inside interval will be (Intersection(t),Infinity). This interval begins at the intersection point on the plane and continues to positive infinity. The Intersection struct stores both the parametric value t and the 3D point of intersection to make various operations more efficient. But the interval operations only depend on the parametric value t. If the origin o is on the inside of the plane then the inside interval will be (RayOrigin,Intersection(t)). Only the part of the ray from the ray origin to the intersection point is inside the plane. It is the programmer's responsibility to return Interval results from surfaceintersection that maintain these properties. The following must be impemented only if the surface is being used as a detector ```julia uv(surface::Surface{T}, p::SVector{3,T}) -> SVector{2,T} uvtopix(surface::Surface{T}, uv::SVector{2,T}, imsize::Tuple{Int,Int}) -> Tuple{Int,Int} onsurface(surface::Surface{T}, p::SVector{3,T}) -> Bool ``` """ abstract type Surface{T<:Real} <: Primitive{T} end export Surface, surfaceintersection, normal, interface """ ParametricSurface{T,N} <: Surface{T} `T` is the number type used to represent the surface, e.g., `Float64`. `N` is the dimension of the space the surface is embedded in. `ParametricSurface`s are valid CSG objects, in some cases (where analytic intersection isn't possible) they must be wrapped in an [`AcceleratedParametricSurface`](@ref) for use. **Must** implement the following: ```julia uv(surface::ParametricSurface{T,N}, p::SVector{N,T}) -> SVector{2,T} uvrange(surface::ParametricSurface{T,N}) -> Tuple{Tuple{T,T},Tuple{T,T}} point(surface::ParametricSurface{T,N}, u::T, v::T) -> SVector{N,T} partials(surface::ParametricSurface{T,N}, u::T, v::T) -> Tuple{SVector{N,T}, SVector{N,T}} normal(surface::ParametricSurface{T,N}, u::T, v::T) -> SVector{N,T} inside(surface::ParametricSurface{T,N}, p: :SVector{N,T}) -> Bool onsurface(surface::ParametricSurface{T,N}, p::SVector{N,T}) -> Bool surfaceintersection(surface::ParametricSurface{T,N}, AbstractRay::Ray{T,N}) -> Union{EmptyInterval{T},Interval{T},DisjointUnion{T}} interface(surface::ParametricSurface{T,N}) -> OpticalInterface{T} ``` """ abstract type ParametricSurface{S<:Real,N} <: Surface{S} end export ParametricSurface, point, partials, uvrange, inside, onsurface, uv # all subclasses must implement one of these at least... """ point(surf::ParametricSurface{T}, u::T, v::T) -> SVector{3,T} point(surf::ParametricSurface{T}, uv::SVector{2,T}) -> SVector{3,T} Returns the 3D point on `surf` at the given uv coordinate. """ point(s::ParametricSurface{T}, u::T, v::T) where {T<:Real} = point(s, SVector{2,T}(u, v)) point(s::ParametricSurface{T}, uv::SVector{2,T}) where {T<:Real} = point(s, uv[1], uv[2]) """ normal(surf::ParametricSurface{T}, u::T, v::T) -> SVector{3,T} normal(surf::ParametricSurface{T}, uv::SVector{2,T}) -> SVector{3,T} Returns the normal to `surf` at the given uv coordinate. """ normal(s::ParametricSurface{T}, u::T, v::T) where {T<:Real} = normal(s, SVector{2,T}(u, v)) normal(s::ParametricSurface{T}, uv::SVector{2,T}) where {T<:Real} = normal(s, uv[1], uv[2]) """ partials(surf::ParametricSurface{T}, u::T, v::T) -> (SVector{3,T}, SVector{3,T}) partials(surf::ParametricSurface{T}, uv::SVector{2,T}) -> (SVector{3,T}, SVector{3,T}) Returns a tuple of the 3D partial derivatives of `surf` with respect to u and v at the given uv coordinate. """ partials(s::ParametricSurface{T}, u::T, v::T) where {T<:Real} = partials(s, SVector{2,T}(u, v)) partials(s::ParametricSurface{T}, uv::SVector{2,T}) where {T<:Real} = partials(s, uv[1], uv[2]) """ uv(surf::ParametricSurface{T}, p::SVector{3,T}) -> SVector{2,T} uv(surf::ParametricSurface{T}, x::T, y::T, z::T) -> SVector{2,T} Returns the uv coordinate on `surf` of a point, `p`, in 3D space. If `onsurface(surf, p)` is false then the behavior is undefined, it may return an inorrect uv, an invalid uv, NaN or crash. """ uv(s::ParametricSurface{T,3}, x::T, y::T, z::T) where {T<:Real} = uv(s, SVector{3,T}(x, y, z)) uv(s::ParametricSurface{T,3}, p::SVector{3,T}) where {T<:Real} = uv(s, p[1], p[2], p[3]) """ inside(surf::ParametricSurface{T}, p::SVector{3,T}) -> Bool inside(surf::ParametricSurface{T}, x::T, y::T, z::T) -> Bool Tests whether a 3D point in world space is _inside_ `surf`. """ inside(s::ParametricSurface{T,3}, x::T, y::T, z::T) where {T<:Real} = inside(s, SVector{3,T}(x, y, z)) inside(s::ParametricSurface{T,3}, p::SVector{3,T}) where {T<:Real} = inside(s, p[1], p[2], p[3]) """ onsurface(surf::ParametricSurface{T}, p::SVector{3,T}) -> Bool onsurface(surf::ParametricSurface{T}, x::T, y::T, z::T) -> Bool Tests whether a 3D point in world space is _on_ `surf`. """ onsurface(s::ParametricSurface{T,3}, x::T, y::T, z::T) where {T<:Real} = onsurface(s, SVector{3,T}(x, y, z)) onsurface(s::ParametricSurface{T,3}, p::SVector{3,T}) where {T<:Real} = onsurface(s, p[1], p[2], p[3]) """ uvrange(s::ParametricSurface) uvrange(::Type{S}) where {S<:ParametricSurface} Returns a tuple of the form: `((umin, umax), (vmin, vmax))` specifying the limits of the parameterisation for this surface type. Also implemented for some `Surface`s which are not `ParametricSurface`s (e.g. `Rectangle`). """ uvrange(::S) where {S<:ParametricSurface} = uvrange(S) """ samplesurface(surf::ParametricSurface{T,N}, samplefunction::Function, numsamples::Int = 30) Sample a parametric surface on an even `numsamples`×`numsamples` grid in UV space with provided function """ function samplesurface(surf::ParametricSurface{T,N}, samplefunction::Function, numsamples::Int = 30) where {T<:Real,N} urange, vrange = uvrange(surf) rt = typeof(samplefunction(surf, urange[1], vrange[1])) samples = Vector{rt}(undef, (numsamples + 1)^2) ustep = (urange[2] - urange[1]) / numsamples vstep = (vrange[2] - vrange[1]) / numsamples for ui in 0:numsamples for vi in 0:numsamples u = urange[1] + ui * ustep v = vrange[1] + vi * vstep samples[ui * (numsamples + 1) + vi + 1] = samplefunction(surf, u, v) end end return samples end export samplesurface """ triangulate(surf::ParametricSurface{S,N}, quads_per_row::Int, extensionu::Bool = false, extensionv::Bool = false, radialu::Bool = false, radialv::Bool = false) Create an array of triangles representing the parametric surface where vertices are sampled on an even grid in UV space. The surface can be extended by 1% in u and v separately, and specifying either u or v as being radial - i.e. detemining the radius on the surface e.g. rho for zernike - will result in that dimension being sampled using sqwrt so that area of triangles is uniform. The extension will also only apply to the maximum in this case. """ function triangulate(surf::ParametricSurface{T,N}, subdivisons::Int, extensionu::Bool = false, extensionv::Bool = false, radialu::Bool = false, radialv::Bool = false) where {T,N} triangles = newintrianglepool!(T) (umin, umax), (vmin, vmax) = uvrange(surf) if extensionu if !radialu umin -= TRIANGULATION_EXTENSION end umax += TRIANGULATION_EXTENSION end if extensionv if !radialv vmin -= TRIANGULATION_EXTENSION end vmax += TRIANGULATION_EXTENSION end # if we are using this for intersection then we need to expand the triangles very slightly to # avoid misses due to floating point precision expansion = extensionu || extensionv ? TRIANGULATION_EXPANSION : zero(T) for ui in 0:(subdivisons - 1) for vj in 0:(subdivisons - 1) # this can be inefficient as we evaluate each point twice # in practice we usually use extension in which case no point is the same anyway u1 = T(ui / subdivisons) u2 = T((ui + 1) / subdivisons) v1 = T(vj / subdivisons) v2 = T((vj + 1) / subdivisons) if radialu u1 = sqrt(max(u1, zero(T))) u2 = sqrt(max(u2, zero(T))) end if radialv v1 = sqrt(max(v1, zero(T))) v2 = sqrt(max(v2, zero(T))) end u1 = (umax - umin) * u1 + umin - expansion u2 = (umax - umin) * u2 + umin + expansion v1 = (vmax - vmin) * v1 + vmin - expansion v2 = (vmax - vmin) * v2 + vmin + expansion p1 = point(surf, u1, v1) p2 = point(surf, u2, v1) p3 = point(surf, u2, v2) p4 = point(surf, u1, v2) if validtri(p1, p2, p3) push!(triangles, Triangle(p1, p2, p3, SVector{2,T}(u1, v1), SVector{2,T}(u2, v1), SVector{2,T}(u2, v2))) end if validtri(p1, p3, p4) push!(triangles, Triangle(p1, p3, p4, SVector{2,T}(u1, v1), SVector{2,T}(u2, v2), SVector{2,T}(u1, v2))) end end end return triangles end export triangulate """ makemesh(object, subdivisions::Int = 30) -> TriangleMesh Creates a [`TriangleMesh`](@ref) from an object, either a [`ParametricSurface`](@ref), [`CSGTree`](@ref) or certain surfaces (e.g. `Circle`, `Rectangle`). This is used for visualization purposes only. """ function makemesh(surface::ParametricSurface{S,N}, subdivisions::Int = 30)::TriangleMesh{S} where {S,N} m = TriangleMesh(triangulate(surface, subdivisions, false)) emptytrianglepool!(S) return m end export makemesh
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
19728
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. # ----------------------------------------------------------------------------------------------- # GEOMETRY # ----------------------------------------------------------------------------------------------- using ...OpticSim using StaticArrays using LinearAlgebra #region Vec3 """ `Vec3{T}` provides an immutable vector of fixed length 3 and type `T`. `Vec3` defines a series of convenience constructors, so you can just type e.g. `Vec3(1, 2, 3)` or `Vec3([1.0, 2.0, 3.0])`. It also supports comprehensions, and the `zeros()`, `ones()`, `fill()`, `rand()` and `randn()` functions, such as `Vec3(rand(3))`. """ Vec3{T} = SVector{3,T} export Vec3 # empty constructor - initialized with zeros Vec3(::Type{T} = Float64) where {T<:Real} = zeros(Vec3{T}) """ returns the unit vector `[1, 0, 0]` """ unitX3(::Type{T} = Float64) where {T<:Real} = Vec3{T}(one(T), zero(T), zero(T)) """ returns the unit vector `[0, 1, 0]` """ unitY3(::Type{T} = Float64) where {T<:Real} = Vec3{T}(zero(T), one(T), zero(T)) """ returns the unit vector `[0, 0, 1]` """ unitZ3(::Type{T} = Float64) where {T<:Real} = Vec3{T}(zero(T), zero(T), one(T)) export unitX3, unitY3, unitZ3 #endregion Vec3 #region Vec4 """ `Vec4{T}` provides an immutable vector of fixed length 4 and type `T`. `Vec4` defines a series of convenience constructors, so you can just type e.g. `Vec3(1, 2, 3, 4)` or `Vec3([1.0, 2.0, 3.0, 4.0])`. It also supports comprehensions, and the `zeros()`, `ones()`, `fill()`, `rand()` and `randn()` functions, such as `Vec4(rand(4))`. """ Vec4{T} = SVector{4,T} # empty constructor - initialized with zeros Vec4(::Type{T} = Float64) where {T<:Real} = zeros(Vec4{T}) export Vec4 """ Vec4(v::SVector{3, T}) where {T<:Real} -> Vec4{T} Accept `SVector` and create a `Vec4` type [v[1], v[2], v[3], 1] """ function Vec4(v::SVector{3, T}) where {T<:Real} return Vec4{T}(v[1], v[2], v[3], one(T)) end """ Vec4(m::SMatrix{3,N,T} where{N,T<:Real} -> SMatrix{3,N,T}) Input is matrix of 3d points, each column is one point. Returns matrix of 3d points with 1 appended in the last row. """ function Vec4(m::SMatrix{3,N,T}) where {N,T<:Real} return vcat(m,ones(SMatrix{1,N,T}))::SMatrix{4,N,T} end """ returns the unit vector `[1, 0, 0, 0]` """ unitX4(::Type{T} = Float64) where {T<:Real} = Vec4{T}(one(T), zero(T), zero(T), zero(T)) """ returns the unit vector `[0, 1, 0, 0]` """ unitY4(::Type{T} = Float64) where {T<:Real} = Vec4{T}(zero(T), one(T), zero(T), zero(T)) """ returns the unit vector `[0, 0, 1, 0]` """ unitZ4(::Type{T} = Float64) where {T<:Real} = Vec4{T}(zero(T), zero(T), one(T), zero(T)) """ returns the unit vector `[0, 0, 0, 1]` """ unitW4(::Type{T} = Float64) where {T<:Real} = Vec4{T}(zero(T), zero(T), zero(T), one(T)) export unitX4, unitY4, unitZ4, unitW4 #endregion Vec4 #region Transform # utility function that given a vector, return 2 orthogonal vectors to that one function get_orthogonal_vectors(direction::Vec3{T}) where {T<:Real} axis1 = normalize(direction) dp = dot(unitX3(T), axis1) # check the special case where the input vector is parallel to the X axis if ( dp >= one(T) - eps(T)) # axis1 = unitX(T); axis2 = unitY3(T); axis3 = unitZ3(T); return (axis2, axis3) elseif ( dp <= -one(T) + eps(T)) # axis1 = -unitX(T); axis2 = -unitY3(T); axis3 = -unitZ3(T); return (axis2, axis3) end axis3 = normalize(cross(axis1, unitX3(T))) axis2 = normalize(cross(axis3, axis1)) return (axis2, axis3) end export get_orthogonal_vectors #--------------------------------------- # 3D Transform / Local Frame #--------------------------------------- """ Transform{S<:Real} Transform encapsulating rotation, translation and scale in 3D space. Translation happens **after** rotation. ```julia Transform{S}(θ::T, ϕ::T, ψ::T, x::T, y::T, z::T) Transform(rotation::SMatrix{3,3,S}, translation::SVector{3,S}) Transform(rotation::AbstractArray{S,2}, translation::AbstractArray{S,1}) ``` `θ`, `ϕ` and `ψ` in first constructor are in **radians**. """ struct Transform{T} matrix::SMatrix{4,4,T,16} """ This is a private internal function. In general don't want to allow users to populate Transform matrices with arbitrary elements. Not to be called by code outside of the Transform module. Don't use Transform{Float64}(...) for example. Instead use Transform(..)""" function Transform{T}(a11::T,a21::T,a31::T,a41::T,a12::T,a22::T,a32::T,a42::T,a13::T,a23::T,a33::T,a43::T,a14::T,a24::T,a34::T,a44::T) where{T<:Real} return new{T}(SMatrix{4,4,T,16}(a11,a21,a31,a41,a12,a22,a32,a42,a13,a23,a33,a43,a14,a24,a34,a44)) end Transform{T}(mat::SMatrix{4,4,T,16}) where{T<:Real} = new{T}(mat) end export Transform #functions to make Transform compatible with base matrix API matrix(a::Transform) = a.matrix # Base.length(a::Transform) = length(matrix(a)) Base.getindex(a::Transform, indices::Vararg{Int,N}) where{N} = getindex(matrix(a),indices...) # Base.iterate(a::Transform) = iterate(matrix(a)) # Base.iterate(a::Transform{Float64}, b::Tuple{StaticArrays.SOneTo{16}, Int64}) = iterate(matrix(a),b) Base.collect(a::Transform) = collect(matrix(a)) Base.:*(transa::Transform{T},transb::Transform{T}) where{T<:Real} = Transform{T}(matrix(transa)*matrix(transb)) function Base.:*(transform::Transform{T}, v::SVector{3,S}) where {T<:Real,S<:Number} t = matrix(transform) res = t * Vec4(v) if (t[4,4] == one(T)) return SVector{3,S}(res[1], res[2], res[3]) else return SVector{3,S}(res[1]/res[4], res[2]/res[4], res[3]/res[4]) end end #Transform is not necessarily constrained to be a rigid body transformation so use general invers. Base.inv(a::Transform{T}) where{T<:Real}= Transform{T}(inv(matrix(a))) """ The t and m matrices are allowed to be of different element type. This allows transforming a Unitful matrix for example: ``` id = identitytransform() m = fill(1mm,3,4) id*m #returns a matrix filled with Unitful quantities. If both matrices had to be the same type this would not work ``` """ function Base.:*(transform::Transform{T}, m::SMatrix{3,N,S}) where{N,T<:Real,S<:Number} res = MMatrix{3,N,T}(undef) t = matrix(transform) for outcol in 1:N for row in 1:3 sum = T(0) for incol in 1:3 sum += t[row,incol]*m[incol,outcol] end #implicit 1 w coordinate value sum += t[row,4] res[row,outcol] = sum end if t[4,4] != 1 res[:,outcol] /= t[4,4] end end return SMatrix{3,N,S}(res) end """ The t and m matrices are allowed to be of different element type. This allows transforming a Unitful matrix for example: WARNING: this doesn't work. The translation component of the transform matrix has to be in Unitful units but the rotation part has to be in unitless units for this to work. Only works if one assumes that the translation part of the transform implicitly has the same units as the Unitful vectors being transformed. Brittle and likely to cause obscure bugs. ``` id = identitytransform() m = fill(1mm,3,4) id*m #returns a matrix filled with Unitful quantities. If both matrices had to be the same type this would not work ``` """ Base.:*(transform::Transform{T},m::SMatrix{4,N,S}) where{N,T<:Real,S<:Number} = matrix(transform)*m Base.transpose(a::Transform{T}) where{T<:Real} = Transform{T}(a.matrix') # END of functions for compatibility with base matrix API # for compatability ith the "old" RigidBodyTransform """ identitytransform([S::Type]) -> Transform{S} Returns the [`Transform`](@ref) of type `S` (default `Float64`) representing the identity transform. """ identitytransform(::Type{T} = Float64) where {T<:Real} = Transform{T}( one(T), zero(T), zero(T), zero(T), zero(T), one(T), zero(T), zero(T), zero(T), zero(T), one(T), zero(T), zero(T), zero(T), zero(T), one(T) ) export identitytransform """ Transform([S::Type]) -> Transform{S} Returns the [`Transform`](@ref) of type `S` (default `Float64`) representing the identity transform. """ function Transform(::Type{T} = Float64) where {T<:Real} return identitytransform(T) end """ Transform(colx::Vec3{T}, coly::Vec3{T},colz::Vec3{T}, colw::Vec3{T}, ::Type{T} = Float64) where {T<:Real} Costruct a transform from the input columns. """ function Transform(colx::Vec3{T}, coly::Vec3{T}, colz::Vec3{T}, colw::Vec3{T} = zero(Vec3{T})) where {T<:Real} return Transform{T}(vcat(hcat(colx,coly,colz,colw),SMatrix{1,4,T}(zero(T),zero(T),zero(T),one(T)) )) end """ Transform(colx::Vec3{T}, coly::Vec3{T},colz::Vec3{T}, colw::Vec3{T}, ::Type{T} = Float64) where {T<:Real} Costruct a transform from the input columns. """ function Transform(colx::Vec4{T}, coly::Vec4{T}, colz::Vec4{T}, colw::Vec4{T}) where {T<:Real} return Transform{T}(hcat(colx,coly,colz,colw)) end """ Transform(origin, forward) -> Transform{S} Returns the [`Transform`](@ref) of type `S` (default `Float64`) representing the local frame with origin and forward direction. the other 2 axes are computed automaticlly. """ function Transform(origin::Vec3{T}, forward::Vec3{T} = unitZ3()) where {T<:Real} forward = normalize(forward) right, up = get_orthogonal_vectors(forward) return Transform(right, up, forward, origin) end function Transform(θ::T, ϕ::T, ψ::T, x::T, y::T, z::T) where {T<:Number} return Transform(rotmat(T, θ, ϕ, ψ), Vec3{T}(x, y, z)) end """ Transform(rotation::SMatrix{3,3,T}, translation::SVector{3,T}) where {T<:Real} -> Transform{S} Returns the [`Transform`](@ref) of type `S` (default `Float64`) created by a rotation matrix and translation vector. """ function Transform(rotation::SMatrix{3,3,T}, translation::SVector{3,T}) where {T<:Real} return Transform{T}( rotation[1,1], rotation[2,1], rotation[3,1], zero(T), rotation[1,2], rotation[2,2], rotation[3,2], zero(T), rotation[1,3], rotation[2,3], rotation[3,3], zero(T), translation[1], translation[2], translation[3], one(T)) end """ Transform(rotation::AbstractArray{T,2}, translation::AbstractArray{T,1}) where {T<:Real} -> Transform{S} Returns the [`Transform`](@ref) of type `S` (default `Float64`) created by a rotation matrix (3x3) and translation vector of length 3. """ function Transform(rotation::AbstractArray{T,2}, translation::AbstractArray{T,1}) where {T<:Real} @assert size(rotation)[1] == size(rotation)[2] == length(translation) == 3 return Transform{T}( rotation[1,1], rotation[2,1], rotation[3,1], zero(T), rotation[1,2], rotation[2,2], rotation[3,2], zero(T), rotation[1,3], rotation[2,3], rotation[3,3], zero(T), translation[1], translation[2], translation[3], one(T)) end # define some utility functions """ right(t::Transform{<:Real}) -> Vec3 Assuming t is a 3D rigid transform representing a local left-handed coordinate system, this function will return the first column, representing the "X" axis. """ right(t::Transform{<:Real}) = normalize(Vec3(t[1,1], t[2,1], t[3,1])) """ up(t::Transform{<:Real}) -> Vec3 Assuming t is a 3D rigid transform representing a local left-handed coordinate system, this function will return the second column, representing the "Y" axis. """ up(t::Transform{<:Real}) = normalize(Vec3(t[1,2], t[2,2], t[3,2])) """ forward(t::Transform{<:Real}) -> Vec3 Assuming t is a 3D rigid transform representing a local left-handed coordinate system, this function will return the third column, representing the "Z" axis. """ forward(t::Transform{<:Real}) = normalize(Vec3(t[1,3], t[2,3], t[3,3])) """ origin(t::Transform{<:Real}) -> Vec3 Assuming t is a 3D rigid transform representing a local left-handed coordinate system, this function will return the fourth column, containing the translation part of the transform in 3D. """ OpticSim.origin(t::Transform{<:Real}) = Vec3(t[1,4], t[2,4], t[3,4]) export right, up, forward, origin """ rotationX(angle::T) where {T<:Real} -> Transform Builds a rotation matrix for a rotation around the x-axis. Parameters: The counter-clockwise `angle` in radians. """ function rotationX(angle::T) where {T<:Real} c = cos(angle); s = sin(angle); row1 = unitX4() row2 = Vec4(zero(T), c, s, zero(T)) row3 = Vec4(zero(T), -s, c, zero(T)) row4 = unitW4() # transposing because the constructors treat these vectors as columns instead of rows return transpose(Transform(row1, row2, row3, row4)) end export rotationX """ rotationY(angle::T) where {T<:Real} -> Transform Builds a rotation matrix for a rotation around the y-axis. Parameters: The counter-clockwise `angle` in radians. """ function rotationY(angle::T) where {T<:Real} c = cos(angle); s = sin(angle); row1 = Vec4(c, zero(T), -s, zero(T)) row2 = unitY4() row3 = Vec4(s, zero(T), c, zero(T)) row4 = unitW4() # transposing because the constructors treat these vectors as columns instead of rows return transpose(Transform(row1, row2, row3, row4)) end export rotationY """ rotationZ(angle::T) where {T<:Real} -> Transform Builds a rotation matrix for a rotation around the z-axis. Parameters: The counter-clockwise `angle` in radians. """ function rotationZ(angle::T) where {T<:Real} c = cos(angle); s = sin(angle); row1 = Vec4(c, s, zero(T), zero(T)) row2 = Vec4(-s, c, zero(T), zero(T)) row3 = unitZ4() row4 = unitW4() # transposing because the constructors treat these vectors as columns instead of rows return transpose(Transform(row1, row2, row3, row4)) end export rotationZ """ rotation(t::Transform{T}) where {T<:Real} -> SMatrix{3,3,T} returns the rotation part of the transform `t` - a 3x3 matrix. """ function rotation(t::Transform{T}) where {T<:Real} rot = SMatrix{3, 3, T}( t[1, 1], t[2, 1], t[3, 1], t[1, 2], t[2, 2], t[3, 2], t[1, 3], t[2, 3], t[3, 3]) return Transform(rot, zero(Vec3{T})) end """ rotate(a::Transform{T}, vector::Union{Vec3{T}, SVector{3,T}}) where {T<:Real} -> Vec3{T} apply the rotation part of the transform `a` to the vector `vector` - this operation is usually used to rotate direction vectors. """ rotate(a::Transform{T}, vector::Union{Vec3{T}, SVector{3,T}}) where {T<:Real} = rotation(a) * vector """ rotation([S::Type], θ::T, ϕ::T, ψ::T) -> Transform{S} Returns the [`Transform`](@ref) of type `S` (default `Float64`) representing the rotation by `θ`, `ϕ` and `ψ` around the *x*, *y* and *z* axes respectively **in radians**. """ rotation(θ::T, ϕ::T, ψ::T) where {T<:Number} = rotation(Float64, θ, ϕ, ψ) rotation(::Type{S}, θ::T, ϕ::T, ψ::T) where {T<:Number,S<:Real} = Transform(rotmat(S, θ, ϕ, ψ), zeros(SVector{3,S})) """ rotationd([S::Type], θ::T, ϕ::T, ψ::T) -> Transform{S} Returns the [`Transform`](@ref) of type `S` (default `Float64`) representing the rotation by `θ`, `ϕ` and `ψ` around the *x*, *y* and *z* axes respectively **in degrees**. """ rotationd(θ::T, ϕ::T, ψ::T) where {T<:Number} = rotationd(Float64, θ, ϕ, ψ) rotationd(::Type{S}, θ::T, ϕ::T, ψ::T) where {T<:Number,S<:Real} = Transform(rotmatd(S, θ, ϕ, ψ), zeros(SVector{3,S})) export translation, rotation, rotationd """ translation(x::T, y::T, z::T) where {T<:Real} Creates a translation transform """ translation(::Type{S}, x::T, y::T, z::T) where {T<:Number,S<:Real} = convert(Transform{S},translation(x, y, z)) function translation(x::T, y::T, z::T) where {T<:Real} col1 = unitX4(T) col2 = unitY4(T) col3 = unitZ4(T) col4 = Vec4(x, y, z, one(T)) return Transform(col1, col2, col3, col4) end """ translation(x::T, y::T, z::T) where {T<:Real} Creates a translation transform """ function translation(t::Vec3{T}) where {T<:Real} return translation(t[1], t[2], t[3]) end export translation """ scale(x::T, y::T, z::T) where {T<:Real} Creates a scaling transform """ function scale(x::T, y::T, z::T) where {T<:Real} col1 = unitX4(T) * x col2 = unitY4(T) * y col3 = unitZ4(T) * z col4 = unitW4(T) return Transform(col1, col2, col3, col4) end """ scale(s::T) where {T<:Real} Creates a uniform scaling transform """ function scale(s::T) where {T<:Real} return scale(s, s, s) end """ scale(t::Vec3{T}) where {T<:Real} Creates a scaling transform """ function scale(t::Vec3{T}) where {T<:Real} return scale(t[1], [2], [3]) end export scale """ local2world(t::Transform{T}) where {T<:Real} return the transform matrix that takes a point in the local coordinate system to the global one """ function local2world(t::Transform{T}) where {T<:Real} return t end export local2world """ world2local(t::Transform{T}) where {T<:Real} return the transform matrix that takes a point in the global coordinate system to the local one """ function world2local(t::Transform{T}) where {T<:Real} return inv(t) end export world2local """ decomposeRTS(tr::Transform{T}) where {T<:Real} return a touple containing the rotation matrix, the translation vector and the scale vecto represnting the transform. """ function decomposeRTS(tr::Transform{T}) where {T<:Real} t = Vec3(tr[1,4], tr[2,4], tr[3,4]) sx = norm(Vec3(tr[1,1], tr[2,1], tr[3,1])) sy = norm(Vec3(tr[1,2], tr[2,2], tr[3,2])) sz = norm(Vec3(tr[1,3], tr[2,3], tr[3,3])) s = Vec3(sx, sy, sz) rot = SMatrix{4, 4, T}(tr[1,1]/sx, tr[2, 1]/sx, tr[3,1]/sx, 0, tr[1,2]/sy, tr[2, 2]/sy, tr[3,2]/sy, 0, tr[1,3]/sz, tr[2, 3]/sz, tr[3,3]/sz, 0, 0, 0, 0, 1) return rot, t, s end export decomposeRTS """ rotmatbetween([S::Type], a::SVector{3,T}, b::SVector{3,T}) -> SMatrix{3,3,S} Returns the rotation matrix of type `S` (default `Float64`) representing the rotation between vetors `a` and `b`, i.e. rotation(a,b) * a = b. """ rotmatbetween(a::SVector{3,T}, b::SVector{3,T}) where {T<:Real} = rotmatbetween(Float64, a, b) function rotmatbetween(::Type{S}, a::SVector{3,T}, b::SVector{3,T}) where {T<:Real,S<:Real} # TODO: Brian, is there a hidden assumption that a and b are normalized? v = cross(a, b) c = dot(a, b) V = SMatrix{3,3,S,9}(0, v[3], -v[2], -v[3], 0, v[1], v[2], -v[1], 0) R = I + V + V^2 * one(T) / (one(T) + c) return SMatrix{3,3,S,9}(R) end """ rotmatd([S::Type], θ::T, ϕ::T, ψ::T) -> SMatrix{3,3,S} Returns the rotation matrix of type `S` (default `Float64`) representing the rotation by `θ`, `ϕ` and `ψ` around the *x*, *y* and *z* axes respectively **in degrees**. """ rotmatd(θ::T, ϕ::T, ψ::T) where {T<:Number} = rotmat(Float64, deg2rad(θ), deg2rad(ϕ), deg2rad(ψ)) rotmatd(::Type{S}, θ::T, ϕ::T, ψ::T) where {T<:Number,S<:Real} = rotmat(S, deg2rad(θ), deg2rad(ϕ), deg2rad(ψ)) export rotmatd """ rotmat([S::Type], θ::T, ϕ::T, ψ::T) -> SMatrix{3,3,S} Returns the rotation matrix of type `S` (default `Float64`) representing the rotation by `θ`, `ϕ` and `ψ` around the *x*, *y* and *z* axes respectively **in radians**. """ rotmat(θ::T, ϕ::T, ψ::T) where {T<:Number} = rotmat(Float64, θ, ϕ, ψ) function rotmat(::Type{S}, θ::T, ϕ::T, ψ::T) where {T<:Number,S<:Real} sinψ = sin(ψ) sinϕ = sin(ϕ) sinθ = sin(θ) cosψ = cos(ψ) cosϕ = cos(ϕ) cosθ = cos(θ) return SMatrix{3,3,S,9}(cosψ * cosϕ, sinψ * cosϕ, -sinϕ, cosψ * sinϕ * sinθ - sinψ * cosθ, sinψ * sinϕ * sinθ + cosψ * cosθ, cosϕ * sinθ, cosψ * sinϕ * cosθ + sinψ * sinθ, sinψ * sinϕ * cosθ - cosψ * sinθ, cosϕ * cosθ) end export rotmat #endregion Transform
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
24689
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. export CSGTree, CSGGenerator, leaf """Abstract type representing any evaluated CSG structure.""" abstract type CSGTree{T} <: Primitive{T} end """ ComplementNode{T,C<:CSGTree{T}} <: CSGTree{T} An evaluated complement node within the CSG tree, must be the second child of a [`IntersectionNode`](@ref) forming a subtraction. """ struct ComplementNode{T,C<:CSGTree{T}} <: CSGTree{T} child::C function ComplementNode(child::C) where {T<:Real,C<:CSGTree{T}} return new{T,C}(child) end end Base.show(io::IO, a::ComplementNode{T}) where {T} = print(io, "Complement($(a.child))") BoundingBox(a::ComplementNode{T}) where {T<:Real} = BoundingBox(a.child) """ UnionNode{T,L<:CSGTree{T},R<:CSGTree{T}} <: CSGTree{T} An evaluated union node within the CSG tree. """ struct UnionNode{T,L<:CSGTree{T},R<:CSGTree{T}} <: CSGTree{T} leftchild::L rightchild::R bbox::BoundingBox{T} function UnionNode(a::L, b::R) where {T<:Real,L<:CSGTree{T},R<:CSGTree{T}} # union should never contain a complement so should be fine return new{T,L,R}(a, b, union(BoundingBox(a), BoundingBox(b))) end end Base.show(io::IO, a::UnionNode{T}) where {T} = print(io, "Union($(a.leftchild), $(a.rightchild))") """ IntersectionNode{T,L<:CSGTree{T},R<:CSGTree{T}} <: CSGTree{T} An evaluated intersection node within the CSG tree. """ struct IntersectionNode{T,L<:CSGTree{T},R<:CSGTree{T}} <: CSGTree{T} leftchild::L rightchild::R bbox::BoundingBox{T} function IntersectionNode(a::L, b::R) where {T<:Real,L<:CSGTree{T},R<:CSGTree{T}} # normal intersection is fine for most nodes return new{T,L,R}(a, b, intersection(BoundingBox(a), BoundingBox(b))) end function IntersectionNode(a::L, b::R) where {T<:Real,L<:CSGTree{T},R<:ComplementNode{T}} # this is a subtraction so just take the original unclipped bounding box for simplicity return new{T,L,R}(a, b, BoundingBox(a)) end end Base.show(io::IO, a::IntersectionNode{T}) where {T} = print(io, "Intersection($(a.leftchild), $(a.rightchild))") """ LeafNode{T,S<:ParametricSurface{T}} <: CSGTree{T} An evaluated leaf node in the CSG tree, `geometry` attribute which contains a [`ParametricSurface`](@ref) of type `S`. The leaf node also has a transform associated which is the composition of all nodes above it in the tree. As such, transforming points from the geometry using this transform puts them in world space, and transforming rays by the inverse transform puts them in object space. """ struct LeafNode{T,S<:ParametricSurface{T,3}} <: CSGTree{T} geometry::S transform::Transform{T} invtransform::Transform{T} bbox::BoundingBox{T} function LeafNode(a::S, transform::Transform{T}) where {T<:Real,S<:ParametricSurface{T,3}} # store the transformed bounding box so nodes higher in the tree have correct global space bounding boxes return new{T,S}(a, transform, inv(transform), BoundingBox(a, transform)) end end function Base.show(io::IO, a::LeafNode{T}) where {T} if a.transform == identitytransform(T) print(io, "Leaf($(a.geometry))") else print(io, "Leaf($(a.geometry), $(a.transform))") end end BoundingBox(a::CSGTree{T}) where {T<:Real} = a.bbox """ CSGGenerator{T<:Real} This is the type you should use when making CSG objects. This type allows for the construction of [`CSGTree`](@ref) objects with different transforms. When the generator is evaluated, all transforms are propagated down to the [`LeafNode`](@ref)s and stored there. # Example ```julia a = Cylinder(1.0,1.0) b = Plane([0.0,0.0,1.0], [0.0,0.0,0.0]) generator = a ∩ b # now make a csg object that can be ray traced csgobj = generator(Transform(1.0,1.0,2.0)) ``` """ struct CSGGenerator{T<:Real} f::Function end function (a::CSGGenerator{T})(transform::Transform{T})::CSGTree{T} where {T<:Real} a.f(transform) end function (a::CSGGenerator{T})()::CSGTree{T} where {T<:Real} a.f(identitytransform(T)) end """ leaf(surf::ParametricSurface{T}, transform::Transform{T} = identitytransform(T)) -> CSGGenerator{T} Create a leaf node from a parametric surface with a given transform. """ function leaf(surf::ParametricSurface{T}, transform::Transform{T} = identitytransform(T)) where {T<:Real} return CSGGenerator{T}((parenttransform) -> LeafNode(surf, parenttransform * transform)) end """ transform(surf::CSGGenerator{T}, transform::Transform{T} = identitytransform(T)) -> CSGGenerator{T} Returns a new CSGGenerator with another transform applied. This is useful if you want multiple copies of a premade CSG structure with different transforms, for example in an MLA. """ function transform(n::CSGGenerator{T}, transform::Transform{T} = identitytransform(T)) where {T<:Real} return CSGGenerator{T}((parenttransform) -> n(parenttransform * transform)) end # CSG objects are trees, not graphs, since it makes no sense to reuse intermediate results. Hence no need to keep track # of common subexpressions. # Static arrays are much faster than mutable arrays so want node transforms to be static. Unfortunately the # transformations cascade from the root to the leaves but the nodes have to be created from the leaves to the roots. # Wrap the csg operations in function that delays evaluation until the transform has been computed. """ ∩(a::Union{CSGGenerator{T},ParametricSurface{T}}, b::Union{CSGGenerator{T},ParametricSurface{T}}) where {T<:Real} Create a binary node in the CSG tree representing an intersection between `a` and `b`. ![Intersect Image](https://upload.wikimedia.org/wikipedia/commons/0/0b/Boolean_intersect.PNG) """ Base.:∩ function Base.:∩(a::CSGGenerator{T}, b::CSGGenerator{T}) where {T<:Real} return CSGGenerator{T}((parenttransform) -> IntersectionNode(a(parenttransform), b(parenttransform))) end Base.:∩(a::ParametricSurface, b::ParametricSurface) = leaf(a) ∩ leaf(b) Base.:∩(a::ParametricSurface, b::CSGGenerator) = leaf(a) ∩ b Base.:∩(a::CSGGenerator, b::ParametricSurface) = a ∩ leaf(b) @deprecate csgintersection(a, b) a ∩ b @deprecate csgintersection(a, b, tr) transform(a ∩ b, tr) """ ∪(a::Union{CSGGenerator{T},ParametricSurface{T}}, b::Union{CSGGenerator{T},ParametricSurface{T}}) where {T<:Real} Create a binary node in the CSG tree representing a union between `a` and `b`. ![Union Image](https://upload.wikimedia.org/wikipedia/commons/4/4a/Boolean_union.PNG) """ Base.:∪ function Base.:∪(a::CSGGenerator{T}, b::CSGGenerator{T}) where {T<:Real} return CSGGenerator{T}((parenttransform) -> UnionNode(a(parenttransform), b(parenttransform))) end Base.:∪(a::ParametricSurface, b::ParametricSurface) = leaf(a) ∪ leaf(b) Base.:∪(a::ParametricSurface, b::CSGGenerator) = leaf(a) ∪ b Base.:∪(a::CSGGenerator, b::ParametricSurface) = a ∪ leaf(b) @deprecate csgunion(a, b) a ∪ b @deprecate csgunion(a, b, tr) transform(a ∪ b, tr) """ -(a::Union{CSGGenerator{T},ParametricSurface{T}}, b::Union{CSGGenerator{T},ParametricSurface{T}}) where {T<:Real} Create a binary node in the CSG tree representing the difference of `a` and `b`, essentially `a - b`. ![Difference Image](https://upload.wikimedia.org/wikipedia/commons/8/86/Boolean_difference.PNG) """ Base.:- function Base.:-(a::CSGGenerator{T}, b::CSGGenerator{T}) where {T<:Real} return CSGGenerator{T}((parenttransform) -> IntersectionNode(a(parenttransform), ComplementNode(b(parenttransform)))) end Base.:-(a::ParametricSurface, b::ParametricSurface) = leaf(a) - leaf(b) Base.:-(a::ParametricSurface, b::CSGGenerator) = leaf(a) - b Base.:-(a::CSGGenerator, b::ParametricSurface) = a - leaf(b) @deprecate csgdifference(a, b) a - b @deprecate csgdifference(a, b, tr) transform(a - b, tr) """ evalcsg( a::Union{UnionNode{T},IntersectionNode{T},ComplementNode{T},LeafNode{T}}, ray::AbstractRay{T,N}, normalreverse::Bool = false )::Union{EmptyInterval{T},DisjointUnion{T},Interval{T}} [TODO] """ function evalcsg end function evalcsg(a::UnionNode{T}, ray::AbstractRay{T,N}, normalreverse::Bool = false) where {T<:Real,N} if !doesintersect(a.bbox, ray) return EmptyInterval(T) end l = evalcsg(a.leftchild, ray, normalreverse) if l isa Interval{T} if lower(l) isa RayOrigin{T} && upper(l) isa Infinity{T} return l end end r = evalcsg(a.rightchild, ray, normalreverse) if l isa EmptyInterval{T} return r end if r isa Interval{T} if lower(r) isa RayOrigin{T} && upper(r) isa Infinity{T} return r end end if r isa EmptyInterval{T} return l end return intervalunion(l, r) end function evalcsg(a::IntersectionNode{T}, ray::AbstractRay{T,N}, normalreverse::Bool = false) where {T<:Real,N} if !doesintersect(a.bbox, ray) return EmptyInterval(T) end l = evalcsg(a.leftchild, ray, normalreverse) if l isa EmptyInterval{T} return EmptyInterval(T) else r = evalcsg(a.rightchild, ray, normalreverse) if r isa EmptyInterval{T} return EmptyInterval(T) else return intervalintersection(l, r) end end end function evalcsg(a::ComplementNode{T}, ray::AbstractRay{T,N}, normalreverse::Bool = false) where {T<:Real,N} return intervalcomplement(evalcsg(a.child, ray, !normalreverse)) end function evalcsg(a::LeafNode{T}, ray::AbstractRay{T,N}, normalreverse::Bool = false) where {T<:Real,N} # the bounding box is in global coordinates so use the un-transformed ray if !doesintersect(a.bbox, ray) return EmptyInterval(T) end intscts = surfaceintersection(a.geometry, a.invtransform * ray) if !(intscts isa EmptyInterval{T}) if normalreverse intscts = reversenormal(intscts) end if intscts isa Interval{T} return a.transform * intscts elseif intscts isa DisjointUnion{T} for i in eachindex(intervals(intscts)) intervals(intscts)[i] = a.transform * intervals(intscts)[i] end return intscts else throw(ErrorException("EvalCSG error - returned type not an interval or disjoint union")) end else return EmptyInterval(T) end end """ surfaceintersection(obj::CSGTree{T}, r::AbstractRay{T,N}) Calculates the intersection of `r` with CSG object, `obj`. Returns an [`EmptyInterval`](@ref) if there is no intersection, an [`Interval`](@ref) if there is one or two interesections and a [`DisjointUnion`](@ref) if there are more than two intersections. The ray is intersected with the [`LeafNode`](@ref)s that make up the CSG object and the resulting `Interval`s and `DisjointUnion`s are composed with the same boolean operations to give a final result. The ray is transformed by the inverse of the transform associated with the leaf node to put it in _object space_ for that node before the intersection is carried out, typically this _object space_ is centered at the origin, but may differ for each primitive. Some intersections are culled without actually evaluating them by first checking if the ray intersects the [`BoundingBox`](@ref) of each node in the [`CSGTree`](@ref), this can substantially improve performance in some cases. """ surfaceintersection(element::CSGTree{T}, r::AbstractRay{T,N}) where {T<:Real,N} = evalcsg(element, r) point(::EmptyInterval) = nothing normal(::EmptyInterval) = nothing point(a::DisjointUnion) = point(closestintersection(a)) normal(a::DisjointUnion) = normal(closestintersection(a)) point(a::Interval) = point(closestintersection(a)) normal(a::Interval) = point(closestintersection(a)) """ onsurface(obj::CSGTree{T}, point::SVector{3,T}) -> Bool onsurface(obj::CSGTree{T}, x::T, y::T, z::T) -> Bool Tests whether a 3D point in world space is _on_ the surface (i.e. shell) of `obj`. """ onsurface(a::CSGTree{T}, x::T, y::T, z::T) where {T<:Real} = onsurface(a, SVector{3,T}(x, y, z)) onsurface(a::ComplementNode{T}, point::SVector{3,T}) where {T<:Real} = onsurface(a.child, point) function onsurface(a::IntersectionNode{T}, point::SVector{3,T}) where {T<:Real} return ( (onsurface(a.leftchild, point) && inside(a.rightchild, point)) || (onsurface(a.rightchild, point) && inside(a.leftchild, point)) ) end function onsurface(a::UnionNode{T}, point::SVector{3,T}) where {T<:Real} return( (onsurface(a.leftchild, point) && !inside(a.rightchild, point)) || (onsurface(a.rightchild, point) && !inside(a.leftchild, point)) ) end onsurface(a::LeafNode{T}, point::SVector{3,T}) where {T<:Real} = onsurface(a.geometry, a.invtransform * point) """ inside(obj::CSGTree{T}, point::SVector{3,T}) -> Bool inside(obj::CSGTree{T}, x::T, y::T, z::T) -> Bool Tests whether a 3D point in world space is _inside_ `obj`. """ inside(a::CSGTree{T}, x::T, y::T, z::T) where {T<:Real} = inside(a, SVector{3,T}(x, y, z)) inside(a::ComplementNode{T}, point::SVector{3,T}) where {T<:Real} = !inside(a.child, point) function inside(a::IntersectionNode{T}, point::SVector{3,T}) where {T<:Real} return inside(a.bbox, point) && (inside(a.leftchild, point) && inside(a.rightchild, point)) end function inside(a::UnionNode{T}, point::SVector{3,T}) where {T<:Real} return inside(a.bbox, point) && (inside(a.leftchild, point) || inside(a.rightchild, point)) end function inside(a::LeafNode{T}, point::SVector{3,T}) where {T<:Real} return inside(a.bbox, point) && inside(a.geometry, a.invtransform * point) end ######################################################################################################################## struct TrianglePool{T<:Real} allocated::Vector{Vector{Triangle{T}}} unallocated::Vector{Vector{Triangle{T}}} TrianglePool{T}() where {T<:Real} = new{T}(Vector{Vector{Triangle{T}}}(), Vector{Vector{Triangle{T}}}()) end function allocate!(a::TrianglePool{T}) where {T<:Real} if length(a.unallocated) === 0 push!(a.unallocated, Vector{Triangle{T}}()) #this will extend the array with a new Vector of Triangles. end temp = pop!(a.unallocated) Base.empty!(temp) #resets count in array but doesn't reclaim space push!(a.allocated, temp) return temp end function empty!(a::TrianglePool{T}) where {T<:Real} for i in 1:length(a.allocated) push!(a.unallocated, pop!(a.allocated)) end end # Allocate a zero length array which will be filled with Threads.nthreads() entries by the __init__ method for OpticSim # module. Have to do this in the __init__ method because this captures the load time environment. const values are # evaluated at precompile time and the number of threads in these two environments can be different. const threadedtrianglepool = Vector{Dict{DataType,TrianglePool}}() function newintrianglepool!(::Type{T} = Float64, tid::Int = Threads.threadid()) where {T<:Real} if T ∉ keys(threadedtrianglepool[tid]) # if the type of the interval pool has changed then we need to refill it with the correct type threadedtrianglepool[tid][T] = TrianglePool{T}() end return allocate!(threadedtrianglepool[tid][T]) end function emptytrianglepool!(::Type{T} = Float64, tid::Int = Threads.threadid()) where {T} if T ∈ keys(threadedtrianglepool[tid]) OpticSim.empty!(threadedtrianglepool[tid][T]) end end ######################################################################################################################## # currrently we assume that no triangles span 2 sides of a shape, i.e. any triangle only crosses one shape boundary and # so splitting is trivial function uniontri!( csg::CSGTree{T}, tri::Triangle{T}, triangles::Vector{Triangle{T}}, thisforcoplanar::Bool = false ) where {T<:Real} v1 = vertex(tri, 1) v2 = vertex(tri, 2) v3 = vertex(tri, 3) in1 = inside(csg, v1) in2 = inside(csg, v2) in3 = inside(csg, v3) # second condition for if the vertex is in the plane of the other object, in which case we want to keep one copy of # the two coplanar surfaces if !thisforcoplanar # if we are NOT using this surface for coplanar faces then we want to count the verts on the surface as # being inside too in case we have coplanar faces in1 |= onsurface(csg, v1) in2 |= onsurface(csg, v2) in3 |= onsurface(csg, v3) end if !(in1 || in2 || in3) || (thisforcoplanar && onsurface(csg, v1) && onsurface(csg, v2) && onsurface(csg, v3)) # whole triangle is valid push!(triangles, tri) elseif !in1 && !in2 && in3 splittri2out!(csg, v1, v2, v3, triangles) elseif !in2 && !in3 && in1 splittri2out!(csg, v2, v3, v1, triangles) elseif !in1 && !in3 && in2 splittri2out!(csg, v3, v1, v2, triangles) elseif !in1 && in2 && in3 splittri1out!(csg, v1, v2, v3, triangles) elseif !in2 && in1 && in3 splittri1out!(csg, v2, v3, v1, triangles) elseif !in3 && in1 && in2 splittri1out!(csg, v3, v1, v2, triangles) end end function intersecttri!( csg::CSGTree{T}, tri::Triangle{T}, triangles::Vector{Triangle{T}}, thisforcoplanar::Bool = false ) where {T<:Real} v1 = vertex(tri, 1) v2 = vertex(tri, 2) v3 = vertex(tri, 3) in1 = inside(csg, v1) in2 = inside(csg, v2) in3 = inside(csg, v3) if thisforcoplanar # if we are allowing dupes then we want to count the verts on the surface as being inside too # in case we have coplanar faces in1 |= onsurface(csg, v1) in2 |= onsurface(csg, v2) in3 |= onsurface(csg, v3) end if (in1 && in2 && in3) # whole triangle is valid push!(triangles, tri) elseif in1 && in2 && !in3 splittri2out!(csg, v1, v2, v3, triangles) elseif in2 && in3 && !in1 splittri2out!(csg, v2, v3, v1, triangles) elseif in1 && in3 && !in2 splittri2out!(csg, v3, v1, v2, triangles) elseif in1 && !in2 && !in3 splittri1out!(csg, v1, v2, v3, triangles) elseif in2 && !in1 && !in3 splittri1out!(csg, v2, v3, v1, triangles) elseif in3 && !in1 && !in2 splittri1out!(csg, v3, v1, v2, triangles) end end function splittri1out!( csg::CSGTree{T}, outv::SVector{3,T}, inv1::SVector{3,T}, inv2::SVector{3,T}, triangles::Vector{Triangle{T}}, recurse::Int = 0 ) where {T<:Real} if !validtri(outv, inv1, inv2) || recurse > VIS_RECURSION_LIMIT # if this triangle is invalid then just stop return end n1 = norm(outv - inv1) n2 = norm(outv - inv2) n3 = norm(inv1 - inv2) if min(n1, n2, n3) < MIN_VIS_TRI_SIZE # triangle is too small to bother splitting so just add it as is push!(triangles, Triangle(outv, inv1, inv2)) return end n1 *= 1.0 + MESH_PRECISION n2 *= 1.0 + MESH_PRECISION int1 = closestintersection(evalcsg(csg, Ray(outv, inv1 - outv)), false) int2 = closestintersection(evalcsg(csg, Ray(outv, inv2 - outv)), false) if (!(int1 === nothing || int2 === nothing) && validtri(outv, point(int1), point(int2)) && α(int1) <= n1 && α(int2) <= n2 ) mid = (inv1 + inv2) / 2 test = closestintersection(evalcsg(csg, Ray(outv, mid - outv)), false) if test !== nothing if !isapprox(point(test), mid, atol = MESH_PRECISION) splittri1out!(csg, outv, point(int1), point(test), triangles, recurse + 1) splittri1out!(csg, outv, point(test), point(int2), triangles, recurse + 1) else push!(triangles, Triangle(outv, point(int1), point(int2))) end else push!(triangles, Triangle(outv, point(int1), point(int2))) end end end function splittri2out!( csg::CSGTree{T}, outv1::SVector{3,T}, outv2::SVector{3,T}, inv::SVector{3,T}, triangles::Vector{Triangle{T}}, flip::Bool = false, recurse::Int = 0 ) where {T<:Real} if !validtri(outv1, outv2, inv) || recurse > VIS_RECURSION_LIMIT # if this triangle is invalid then just stop return end n1 = norm(outv1 - inv) n2 = norm(outv2 - inv) n3 = norm(outv1 - outv2) if min(n1, n2, n3) < MIN_VIS_TRI_SIZE # triangle is too small to bother splitting so just add it as is push!(triangles, Triangle(outv1, outv2, inv)) return end n1 *= 1.0 + MESH_PRECISION n2 *= 1.0 + MESH_PRECISION int1 = closestintersection(evalcsg(csg, Ray(outv1, inv - outv1)), false) int2 = closestintersection(evalcsg(csg, Ray(outv2, inv - outv2)), false) if int2 !== nothing && α(int2) <= n2 # int2 is valid if int1 !== nothing && α(int1) <= n1 if isapprox(point(int1), point(int2), atol = MESH_PRECISION) # we just need one triangle in this case as inv lies on the boundary of the shape if validtri(outv1, outv2, point(int2)) if flip push!(triangles, Triangle(outv1, point(int2), outv2)) else push!(triangles, Triangle(outv1, outv2, point(int2))) end end else if flip splittri1out!(csg, outv1, point(int1), point(int2), triangles) else splittri1out!(csg, outv1, point(int2), point(int1), triangles) end splittri2out!(csg, outv2, outv1, point(int2), triangles, !flip, recurse + 1) end else if validtri(outv1, outv2, point(int2)) if flip push!(triangles, Triangle(outv1, point(int2), outv2)) else push!(triangles, Triangle(outv1, outv2, point(int2))) end end end elseif int1 !== nothing && α(int1) <= n1 if validtri(outv1, outv2, point(int1)) if flip push!(triangles, Triangle(outv1, point(int1), outv2)) else push!(triangles, Triangle(outv1, outv2, point(int1))) end end end end # visualization functions from CSG objects, most actualy work happens in the above functions function makemeshi(a::UnionNode{T}, subdivisions::Int = 30)::Vector{Triangle{T}} where {T<:Real} # do the two children in parallel th1 = Threads.@spawn makemesh(a.leftchild, subdivisions) th2 = Threads.@spawn makemesh(a.rightchild, subdivisions) ltris = (fetch(th1)::TriangleMesh{T}).triangles rtris = (fetch(th2)::TriangleMesh{T}).triangles triangles = newintrianglepool!(T) @inbounds for tri in ltris uniontri!(a.rightchild, tri, triangles, true) end @inbounds for tri in rtris uniontri!(a.leftchild, tri, triangles) end return triangles end function makemeshi(a::IntersectionNode{T}, subdivisions::Int = 30)::Vector{Triangle{T}} where {T<:Real} # do the two children in parallel th1 = Threads.@spawn makemesh(a.leftchild, subdivisions) th2 = Threads.@spawn makemesh(a.rightchild, subdivisions) ltris = (fetch(th1)::TriangleMesh{T}).triangles rtris = (fetch(th2)::TriangleMesh{T}).triangles triangles = newintrianglepool!(T) @inbounds for tri in ltris intersecttri!(a.rightchild, tri, triangles, true) end @inbounds for tri in rtris intersecttri!(a.leftchild, tri, triangles) end return triangles end function makemeshi(a::ComplementNode{T}, subdivisions::Int = 30)::Vector{Triangle{T}} where {T<:Real} child_triangles = makemeshi(a.child, subdivisions) # flip the normals triangles = newintrianglepool!(T) @inbounds for i in 1:length(child_triangles) tri = child_triangles[i] push!(triangles, Triangle(vertex(tri, 3), vertex(tri, 2), vertex(tri, 1))) end return triangles end function makemeshi(a::LeafNode{T}, subdivisions::Int = 30)::Vector{Triangle{T}} where {T<:Real} child_triangles = triangulate(a.geometry, subdivisions) triangles = newintrianglepool!(T) @inbounds for i in 1:length(child_triangles) push!(triangles, a.transform * child_triangles[i]) end return triangles end function makemesh(c::CSGTree{T}, subdivisions::Int = 30)::TriangleMesh{T} where {T<:Real} m = TriangleMesh(copy(makemeshi(c, subdivisions))) # need to copy with multithreading emptytrianglepool!(T) emptyintervalpool!(T) return m end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
7031
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Each [`Interval`](@ref) consists of two `IntervalPoint`s, one of [`RayOrigin`](@ref), [`Intersection`](@ref) or [`Infinity`](@ref). """ abstract type IntervalPoint{T<:Real} end Base.eltype(::IntervalPoint{T}) where {T<:Real} = T abstract type FinitePoint{T} <: IntervalPoint{T} end Base.eltype(::FinitePoint{T}) where {T<:Real} = T """ Intersection{T,N} <: IntervalPoint{T} Represents the point at which an [`Ray`](@ref) hits a [`Surface`](@ref). This consists of the distance along the ray, the intersection point in world space, the normal in world space, the UV on the surface and the [`OpticalInterface`](@ref) hit. Has the following accessor methods: ```julia point(a::Intersection{T,N}) -> SVector{N,T} normal(a::Intersection{T,N}) -> SVector{N,T} uv(a::Intersection{T,N}) -> SVector{2,T} u(a::Intersection{T,N}) -> T v(a::Intersection{T,N}) -> T α(a::Intersection{T,N}) -> T interface(a::Intersection{T,N}) -> OpticalInterface{T} flippednormal(a::Intersection{T,N}) -> Bool ``` """ struct Intersection{T,N} <: FinitePoint{T} α::T # value of ray parameter at the point of intersection point::SVector{N,T} normal::SVector{N,T} u::T v::T interface::AllOpticalInterfaces{T} # returns a union of all OpticalInterface subtypes - can't have an abstract type here as it results in allocations flippednormal::Bool function Intersection(α::T, point::SVector{N,T}, normal::SVector{N,T}, u::T, v::T, interface::AllOpticalInterfaces{T}; flippednormal = false) where {T<:Real,N} new{T,N}(α, point, normalize(normal), u, v, interface, flippednormal) end function Intersection(α::T, point::AbstractVector{T}, normal::AbstractVector{T}, u::T, v::T, interface::AllOpticalInterfaces{T}; flippednormal = false) where {T<:Real} @assert length(point) == length(normal) N = length(point) new{T,N}(α, SVector{N,T}(point), SVector{N,T}(normal), u, v, interface, flippednormal) end end export Intersection point(a::Intersection{T,N}) where {T<:Real,N} = a.point normal(a::Intersection{T,N}) where {T<:Real,N} = a.normal uv(a::Intersection{T,N}) where {T<:Real,N} = SVector{2,T}(a.u, a.v) u(a::Intersection{T,N}) where {T<:Real,N} = a.u v(a::Intersection{T,N}) where {T<:Real,N} = a.v α(a::Intersection{T,N}) where {T<:Real,N} = a.α interface(a::Intersection{T,N}) where {T<:Real,N} = a.interface flippednormal(a::Intersection{T,N}) where {T<:Real,N} = a.flippednormal function Base.print(io::IO, a::Intersection{T,N}) where {T<:Real,N} println(io, Intersection{T,N}) println(io, "α \t$(α(a))") println(io, "Point \t$(point(a))") println(io, "Normal \t$(normal(a))") println(io, "normal is flipped? \t$(flippednormal(a))") println(io, "u \t$(u(a))") println(io, "v \t$(v(a))") println(io, "interface \t$(interface(a))") end """ reversenormal(a::Intersection{T,N}) Used by the CSG complement operator (i.e. [`-`](@ref)) to reverse the inside outside sense of the object. """ function reversenormal(a::Intersection{T,N}) where {T<:Real,N} return Intersection(α(a), point(a), -normal(a), u(a), v(a), interface(a), flippednormal = !flippednormal(a)) end """ Infinity{T} <: IntervalPoint{T} Point representing ∞ within an [`Interval`](@ref). ```julia Infinity(T = Float64) Infinity{T}() ``` """ struct Infinity{T} <: IntervalPoint{T} Infinity(::Type{T} = Float64) where {T<:Real} = new{T}() Infinity{T}() where {T<:Real} = new{T}() end """ RayOrigin{T} <: IntervalPoint{T} Point representing 0 within an [`Interval`](@ref), i.e. the start of the ray. ```julia RayOrigin(T = Float64) RayOrigin{T}() ``` """ struct RayOrigin{T} <: FinitePoint{T} RayOrigin(::Type{T} = Float64) where {T<:Real} = new{T}() RayOrigin{T}() where {T<:Real} = new{T}() end export Infinity, RayOrigin Base.:(==)(::RayOrigin{P}, ::RayOrigin{P}) where {P<:Real} = true Base.:(==)(::Infinity{P}, ::Infinity{P}) where {P<:Real} = true Base.:(==)(a::Intersection{P,N}, b::Intersection{P,N}) where {P<:Real,N} = α(a) == α(b) Base.:(==)(::IntervalPoint{P}, ::IntervalPoint{P}) where {P<:Real} = false Base.:(<=)(::RayOrigin{P}, ::RayOrigin{P}) where {P<:Real} = true Base.:(<=)(::Infinity{P}, ::Infinity{P}) where {P<:Real} = true Base.:(<=)(a::IntervalPoint{P}, b::Infinity{P}) where {P<:Real} = true Base.:(<=)(a::Intersection{P,N}, b::Intersection{P,N}) where {P<:Real,N} = α(a) <= α(b) Base.:(<=)(a::RayOrigin{P}, b::Infinity{P}) where {P<:Real} = true Base.:(<=)(a::RayOrigin{P}, b::IntervalPoint{P}) where {P<:Real} = true Base.:(<=)(::IntervalPoint{P}, ::IntervalPoint{P}) where {P<:Real} = false Base.:(>=)(::RayOrigin{P}, ::RayOrigin{P}) where {P<:Real} = true Base.:(>=)(::Infinity{P}, ::Infinity{P}) where {P<:Real} = true Base.:(>=)(a::IntervalPoint{P}, b::Infinity{P}) where {P<:Real} = false Base.:(>=)(a::Intersection{P,N}, b::Intersection{P,N}) where {P<:Real,N} = α(a) >= α(b) Base.:(>=)(a::RayOrigin{P}, b::Infinity{P}) where {P<:Real} = false Base.:(>=)(a::RayOrigin{P}, b::IntervalPoint{P}) where {P<:Real} = false Base.:(>=)(::IntervalPoint{P}, ::IntervalPoint{P}) where {P<:Real} = false Base.:(<)(::Infinity{P}, ::Infinity{P}) where {P<:Real} = false Base.:(<)(::IntervalPoint{P}, ::Infinity{P}) where {P<:Real} = true Base.:(<)(a::Intersection{P,N}, b::Intersection{P,N}) where {P<:Real,N} = α(a) < α(b) Base.:(>)(::Infinity{P}, ::Infinity{P}) where {P<:Real} = false Base.:(>)(::IntervalPoint{P}, ::Infinity{P}) where {P<:Real} = false Base.:(>)(a::Intersection{P,N}, b::Intersection{P,N}) where {P<:Real,N} = α(a) > α(b) Base.isless(a::IntervalPoint{P}, b::IntervalPoint{P}) where {P<:Real} = α(a) < α(b) Base.eltype(::Intersection{T,N}) where {T<:Real,N} = T """ isinfinity(a) -> Bool Returns true if `a` is [`Infinity`](@ref). In performance critical contexts use `a isa Infinity{T}`. """ isinfinity(::Infinity) = true isinfinity(::Any) = false α(::Infinity{T}) where {T<:AbstractFloat} = typemax(T) Base.eltype(::Infinity{T}) where {T<:Real} = T """ israyorigin(a) -> Bool Returns true if `a` is [`RayOrigin`](@ref). In performance critical contexts use `a isa RayOrigin{T}`. """ israyorigin(::Any) = false israyorigin(::RayOrigin) = true α(::RayOrigin{T}) where {T<:Real} = zero(T) Base.eltype(::RayOrigin{T}) where {T<:Real} = T """ Apply a Transform to an Intersection object """ function Base.:*(a::Transform{T}, intsct::Intersection{T,3})::Intersection{T,3} where {T<:Real} u, v = uv(intsct) i = interface(intsct) if VERSION < v"1.6.0-DEV" # TODO REMOVE return @unionsplit OpticalInterface T i Intersection(α(intsct), a * point(intsct), Geometry.rotate(a, normal(intsct)), u, v, i, flippednormal = flippednormal(intsct)) else return Intersection(α(intsct), a * point(intsct), Geometry.rotate(a, normal(intsct)), u, v, interface(intsct), flippednormal = flippednormal(intsct)) end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
20761
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. abstract type AbstractRayInterval{T<:Real} end """ EmptyInterval{T} <: AbstractRayInterval{T} An interval with no [`Intersection`](@ref)s which is also not infinite. ``` EmptyInterval(T = Float64) EmptyInterval{T}() ``` """ struct EmptyInterval{T} <: AbstractRayInterval{T} EmptyInterval(::Type{T} = Float64) where {T<:Real} = new{T}() EmptyInterval{T}() where {T<:Real} = new{T}() end export EmptyInterval """ Interval{T} <: AbstractRayInterval{T} Datatype representing an interval between two [`IntervalPoint`](@ref)s on a ray. The lower element can either be [`RayOrigin`](@ref) or an [`Intersection`](@ref). The upper element can either be an [`Intersection`](@ref) or [`Infinity`](@ref). ```julia positivehalfspace(int::Intersection) -> Interval with lower = int, upper = Infinity rayorigininterval(int::Intersection) -> Interval with lower = RayOrigin, upper = int Interval(low, high) ``` Has the following accessor methods: ```julia lower(a::Interval{T}) -> Union{RayOrigin{T},Intersection{T,3}} upper(a::Interval{T}) -> Union{Intersection{T,3},Infinity{T}} ``` """ struct Interval{R} <: AbstractRayInterval{R} lower::Union{RayOrigin{R},Intersection{R,3}} #making this a Union of two concrete types allows the compiler to statically enough space to hold the larger of the two. The entire Interval struct can then be stack allocated. upper::Union{Intersection{R,3},Infinity{R}} #same as above function Interval(low::S, high::T) where {R<:Real,S<:Union{RayOrigin{R},Intersection{R,3}},T<:Union{Intersection{R,3},Infinity{R}}} @assert low <= high return new{R}(low, high) end end export Interval function Base.show(io::IO, a::Interval{R}) where {R<:Real} println(io, Interval{R}) println(io, "\tLower \n\t\t$(lower(a))") println(io, "\tUpper \n\t\t$(upper(a))") end Base.eltype(::Interval{R}) where {R} = R lower(a::Interval) = a.lower upper(a::Interval) = a.upper ######################################################################################################################## """ To prevent allocations we have a manually managed pool of arrays of [`Interval`](@ref)s which are used to store values during execution. The memory is kept allocated and reused across runs of functions like [`trace`](@ref). `threadedintervalpool` is a global threadsafe pool which is accessed through the functions: ```julia newinintervalpool!(::Type{T} = Float64, tid::Int = Threads.threadid()) -> Vector{Interval{T}} indexednewinintervalpool!(::Type{T} = Float64, tid::Int = Threads.threadid()) -> Tuple{Int,Vector{Interval{T}}} emptyintervalpool!(::Type{T} = Float64, tid::Int = Threads.threadid()) getfromintervalpool([::Type{T} = Float64], id::Int, tid::Int = Threads.threadid()) -> Vector{Interval{T}} ``` """ struct IntervalPool{T<:Real} allocated::Vector{Vector{Interval{T}}} unallocated::Vector{Vector{Interval{T}}} IntervalPool{T}() where {T<:Real} = new{T}(Vector{Vector{Interval{T}}}(), Vector{Vector{Interval{T}}}()) end function allocate!(a::IntervalPool{T}) where {T<:Real} if length(a.unallocated) === 0 push!(a.unallocated, Vector{Interval{T}}()) #this will extend the array with a new Vector of intervals. end temp = pop!(a.unallocated) Base.empty!(temp) #resets count in array but doesn't reclaim space push!(a.allocated, temp) return temp end function empty!(a::IntervalPool{T}) where {T<:Real} while length(a.allocated) > 0 temp = pop!(a.allocated) Base.empty!(temp) #not strictly necessary since allocate will reset this array to empty before pushing it back on allocated stack. But this ensures the interval pool is in a consistent emptied state upon completion of this function. push!(a.unallocated, temp) end end # Allocate a zero length array which will be filled with Threads.nthreads() entries by the __init__ method for OpticSim module. Have to do this in the __init__ method because this captures the load time environment. const values are evaluated at precompile time and the number of threads in these two environments can be different. const threadedintervalpool = Vector{Dict{DataType,IntervalPool}}() #const threadedintervalpool = [Dict{DataType,IntervalPool}([Float64 => IntervalPool{Float64}()]) for _ in 1:Threads.nthreads()] function newinintervalpool!(::Type{T} = Float64, tid::Int = Threads.threadid())::Vector{Interval{T}} where {T<:Real} if T ∉ keys(threadedintervalpool[tid]) # if the type of the interval pool has changed then we need to refill it with the correct type threadedintervalpool[tid][T] = IntervalPool{T}() end return allocate!(threadedintervalpool[tid][T]) end function indexednewinintervalpool!(::Type{T} = Float64, tid::Int = Threads.threadid())::Tuple{Int,Vector{Interval{T}}} where {T<:Real} a = newinintervalpool!(T, tid) index = length(threadedintervalpool[tid][T].allocated) return index, a end function emptyintervalpool!(::Type{T} = Float64, tid::Int = Threads.threadid()) where {T} if T ∈ keys(threadedintervalpool[tid]) OpticSim.empty!(threadedintervalpool[tid][T]) end end getfromintervalpool(id::Int, tid::Int = Threads.threadid())::Vector{Interval{Float64}} = getfromintervalpool(Float64, id, tid) function getfromintervalpool(::Type{T}, id::Int, tid::Int = Threads.threadid())::Vector{Interval{T}} where {T<:Real} return threadedintervalpool[tid][T].allocated[id] end ######################################################################################################################## macro inplaceinsertionsort(array, f) esc(quote for i in 2:length($array) value = $array[i] j = i - 1 while j > 0 && $f($array[j]) > $f(value) $array[j + 1] = $array[j] j = j - 1 end $array[j + 1] = value end end) end """ Datatype representing an ordered series of disjoint intervals on a ray. An arbitrary array of `Interval`s can be input to the constructor and they will automatically be processed into a valid `DisjointUnion` (or a single [`Interval`](@ref) if appropriate). ```julia DisjointUnion(intervals::AbstractVector{Interval{R}}) ``` """ struct DisjointUnion{T<:Real} intervalarrayindex::Int function DisjointUnion(a::Interval{R}, b::Interval{R})::Union{DisjointUnion{R},Interval{R}} where {R<:Real} temp = newinintervalpool!(R) push!(temp, a) push!(temp, b) return DisjointUnion(temp) end function DisjointUnion(intervals::AbstractVector{Interval{R}})::Union{DisjointUnion{R},Interval{R}} where {R<:Real} if length(intervals) === 1 return intervals[1] end @inplaceinsertionsort(intervals, upper) index, result = indexednewinintervalpool!(R) while length(intervals) > 0 current = pop!(intervals) while length(intervals) > 0 temp = intervalintersection(current, last(intervals)) if !(temp isa EmptyInterval{R}) current = intervalunion(current, last(intervals)) pop!(intervals) else break end end push!(result, current) end if length(result) === 1 return result[1] else @inplaceinsertionsort(result, lower) return new{R}(index) end end end intervals(a::DisjointUnion{R}) where {R<:Real} = getfromintervalpool(R, a.intervalarrayindex) function Base.show(io::IO, a::DisjointUnion{R}) where {R<:Real} println(io, DisjointUnion{R}) for i in intervals(a) show(io, i) end end export DisjointUnion Base.getindex(a::DisjointUnion, index::Int) = intervals(a)[index] Base.firstindex(a::DisjointUnion) = firstindex(intervals(a)) Base.lastindex(a::DisjointUnion) = lastindex(intervals(a)) Base.length(a::DisjointUnion) = length(intervals(a)) Base.:(==)(a::DisjointUnion, b::DisjointUnion) = intervals(a) == intervals(b) # this works so long as the elements in the intervals array are structs and not arrays. ######################################################################################################################## """ isemptyinterval(a) -> Bool Returns true if `a` is an [`EmptyInterval`](@ref). In performance critical contexts use `a isa EmptyInterval{T}`. """ isemptyinterval(::EmptyInterval) = true isemptyinterval(::Interval) = false isemptyinterval(::DisjointUnion) = false """ ispositivehalfspace(a) -> Bool Returns true if `upper(a)` is [`Infinity`](@ref). In performance critical contexts check directly i.e. `upper(a) isa Infinity{T}`. """ ispositivehalfspace(a::Interval{T}) where {T<:Real} = upper(a) isa Infinity{T} """ israyorigininterval(a) -> Bool Returns true if `lower(a)` is [`RayOrigin`](@ref). In performance critical contexts check directly i.e. `lower(a) isa RayOrigin{T}`. """ israyorigininterval(a::Interval{T}) where {T<:Real} = lower(a) isa RayOrigin{T} isinfiniteinterval(a::Interval{T}) where {T<:Real} = israyorigininterval(a) && ispositivehalfspace(a) positivehalfspace(a::RayOrigin{T}) where {T<:Real} = Interval(a, Infinity(T)) positivehalfspace(a::Intersection{T,N}) where {T<:Real,N} = Interval(a, Infinity(T)) rayorigininterval(a::Intersection{T,N}) where {T<:Real,N} = Interval(RayOrigin(T), a) # special kind of interval that has ray origin as lower bound. α(a::RayOrigin) will always return 0 so CSG operations should work. rayorigininterval(a::Infinity{T}) where {T<:Real} = Interval(RayOrigin(T), a) """ halfspaceintersection(a::Interval{T}) -> Intersection{T,3} Returns the [`Intersection`](@ref) from a half space [`Interval`](@ref), throws an error if not a half space. """ function halfspaceintersection(a::Interval{T})::Intersection{T,3} where {T<:Real} la = lower(a) ua = upper(a) if ua isa Infinity{T} && !(la isa RayOrigin{T}) return la elseif la isa RayOrigin{T} && !(ua isa Infinity{T}) return ua else return throw(ErrorException("Not a half-space: $a")) end end """ closestintersection(a::Union{EmptyInterval{T},Interval{T},DisjointUnion{T}}, ignorenull::Bool = true) -> Union{Nothing,Intersection{T,3}} Returns the closest [`Intersection`](@ref) from an [`Interval`](@ref) or [`DisjointUnion`](@ref). Ignores intersection with null interfaces if `ignorenull` is true. Will return `nothing` if there is no valid intersection. """ closestintersection(::EmptyInterval, ::Bool = true) = nothing function closestintersection(a::Interval{T}, ignorenull::Bool = true)::Union{Nothing,Intersection{T,3}} where {T<:Real} la = lower(a) ua = upper(a) if la isa RayOrigin{T} if !(ua isa Infinity{T}) && !(ignorenull && interface(ua) isa NullInterface{T}) return ua else return nothing end elseif !(ignorenull && interface(la) isa NullInterface{T}) return la else return nothing end end function closestintersection(a::DisjointUnion{T}, ignorenull::Bool = true)::Union{Nothing,Intersection{T,3}} where {T<:Real} for i in intervals(a) c = closestintersection(i, ignorenull) if c !== nothing return c end end return nothing end export closestintersection function reversenormal(a::Interval{T})::Interval{T} where {T<:Real} la = lower(a) ua = upper(a) if la isa RayOrigin{T} if ua isa Infinity{T} return a else return Interval(la, reversenormal(ua)) end else if ua isa Infinity{T} return Interval(reversenormal(la), ua) else return Interval(reversenormal(la), reversenormal(ua)) end end end function reversenormal(a::DisjointUnion{R})::DisjointUnion{R} where {R<:Real} intvls = newinintervalpool!(R) for i in intervals(a) push!(intvls, reversenormal(i)) end return DisjointUnion(intvls) end ######################################################################################################################## macro intervalintersectionhigh(low) esc(quote if ua isa Infinity{R} if ub isa Infinity{R} return Interval($low, Infinity(R)) else if ub <= $low return EmptyInterval(R) end return Interval($low, ub) end else if ub isa Infinity{R} if ua <= $low return EmptyInterval(R) end return Interval($low, ua) else high = min(ua, ub) if high <= $low return EmptyInterval(R) end return Interval($low, high) end end end) end function intervalintersection(a::Interval{R}, b::Interval{R})::Union{EmptyInterval{R},Interval{R}} where {R<:Real} # This method is just doing the below, but to avoid type ambiguities things have to be much more complicated # if upper(a) <= lower(b) || upper(b) <= lower(a) # return EmptyInterval(R) # end # low = max(lower(a), lower(b)) # high = min(upper(a), upper(b)) # return Interval(low, high) la = lower(a) lb = lower(b) ua = upper(a) ub = upper(b) if la isa RayOrigin{R} if lb isa RayOrigin{R} @intervalintersectionhigh(RayOrigin(R)) else @intervalintersectionhigh(lb) end else if lb isa RayOrigin{R} @intervalintersectionhigh(la) else low = max(la, lb) @intervalintersectionhigh(low) end end end intervalintersection(::EmptyInterval{T}, ::EmptyInterval{T}) where {T<:Real} = EmptyInterval(T) intervalintersection(::EmptyInterval{T}, ::Interval{T}) where {T<:Real} = EmptyInterval(T) intervalintersection(::Interval{T}, ::EmptyInterval{T}) where {T<:Real} = EmptyInterval(T) intervalintersection(::EmptyInterval{T}, ::DisjointUnion{T}) where {T<:Real} = EmptyInterval(T) intervalintersection(::DisjointUnion{T}, ::EmptyInterval{T}) where {T<:Real} = EmptyInterval(T) intervalintersection(a::Interval{T}, b::DisjointUnion{T}) where {T<:Real} = intervalintersection(a, intervals(b)) intervalintersection(a::DisjointUnion{T}, b::Interval{T}) where {T<:Real} = intervalintersection(b, intervals(a)) intervalintersection(a::DisjointUnion{T}, b::DisjointUnion{T}) where {T<:Real} = intervalintersection(intervals(a), intervals(b)) function intervalintersection(a::Interval{T}, b::AbstractVector{Interval{T}})::Union{EmptyInterval{T},Interval{T},DisjointUnion{T}} where {T<:Real} temp = nothing int1 = nothing for bint in b intsct = intervalintersection(a, bint) if !(intsct isa EmptyInterval{T}) if int1 === nothing int1 = intsct elseif temp === nothing temp = newinintervalpool!(T) push!(temp, int1) push!(temp, intsct) else push!(temp, intsct) end end end if int1 === nothing return EmptyInterval(T) elseif int1 !== nothing && (temp === nothing) return int1 else return DisjointUnion(temp) end end function intervalintersection(a::AbstractVector{Interval{T}}, b::AbstractVector{Interval{T}})::Union{EmptyInterval{T},Interval{T},DisjointUnion{T}} where {T<:Real} temp = newinintervalpool!(T) for aint in a for bint in b intsct = intervalintersection(aint, bint) if !(intsct isa EmptyInterval{T}) push!(temp, intsct) end end end if length(temp) == 0 return EmptyInterval(T) else return DisjointUnion(temp) end end ######################################################################################################################## macro intervalunionhigh(low) esc(quote if ua isa Infinity{R} if ub isa Infinity{R} return Interval($low, Infinity(R)) else if ub < la return DisjointUnion(a, b) end return Interval($low, Infinity(R)) end else if ub isa Infinity{R} if ua < lb return DisjointUnion(a, b) end return Interval($low, Infinity(R)) else if ua < lb || ub < la return DisjointUnion(a, b) end return Interval($low, max(ua, ub)) end end end) end function intervalunion(a::Interval{R}, b::Interval{R})::Union{Interval{R},DisjointUnion{R}} where {R<:Real} # This method is just doing the below, but to avoid type ambiguities things have to be much more complicated # if upper(a) < lower(b) || upper(b) < lower(a) # return DisjointUnion(a, b) # else # low = min(lower(a), lower(b)) # high = max(upper(a), upper(b)) # return Interval(low, high) # end ua = upper(a) ub = upper(b) la = lower(a) lb = lower(b) if la isa RayOrigin{R} if lb isa RayOrigin{R} @intervalunionhigh(RayOrigin(R)) else @intervalunionhigh(RayOrigin(R)) end else if lb isa RayOrigin{R} @intervalunionhigh(RayOrigin(R)) else low = min(la, lb) @intervalunionhigh(low) end end end intervalunion(a::Interval{T}, b::DisjointUnion{T}) where {T<:Real} = intervalunion(b, a) function intervalunion(a::DisjointUnion{T}, b::Interval{T}) where {T<:Real} temp = newinintervalpool!(T) for intvl in intervals(a) push!(temp, intvl) end push!(temp, b) return DisjointUnion(temp) end function intervalunion(a::DisjointUnion{T}, b::DisjointUnion{T}) where {T<:Real} temp = newinintervalpool!(T) for intvl in intervals(a) push!(temp, intvl) end for intvl in intervals(b) push!(temp, intvl) end return DisjointUnion(temp) end intervalunion(::EmptyInterval{T}, ::EmptyInterval{T}) where {T<:Real} = EmptyInterval(T) intervalunion(::EmptyInterval{T}, b::Interval{T}) where {T<:Real} = b intervalunion(a::Interval{T}, ::EmptyInterval{T}) where {T<:Real} = a intervalunion(::EmptyInterval{T}, b::DisjointUnion{T}) where {T<:Real} = b intervalunion(a::DisjointUnion{T}, ::EmptyInterval{T}) where {T<:Real} = a ######################################################################################################################## function intervalcomplement(a::DisjointUnion{T}) where {T<:Real} res = rayorigininterval(Infinity(T)) for intrval in intervals(a) @assert !(intrval isa EmptyInterval{T}) "should never have an empty interval in a DisjointUnion" compl = intervalcomplement(intrval)::Union{Interval{T},DisjointUnion{T}} if compl isa Interval{T} res = intervalintersection(res, compl) else res = intervalintersection(res, compl) end end return res end intervalcomplement(::EmptyInterval{T}) where {T<:Real} = Interval(RayOrigin(T), Infinity(T)) function intervalcomplement(a::Interval{T}) where {T<:Real} ua = upper(a) la = lower(a) if la isa RayOrigin{T} if ua isa Infinity{T} return EmptyInterval(T) else return positivehalfspace(ua) # this is not strictly correct end else if ua isa Infinity{T} return rayorigininterval(la) else return DisjointUnion(rayorigininterval(la), positivehalfspace(ua)) end end end difference(a::DisjointUnion, b::DisjointUnion) = intervalintersection(a, intervalcomplement(b)) """ Apply a Transform to an Interval object """ function Base.:*(transformation::Transform{T}, a::Interval{T}) where {T<:Real} # looks ridiculous but necessary to dissambiguate the elements of the interval u = upper(a) l = lower(a) if l isa RayOrigin{T} if u isa Infinity{T} return Interval(l, u) else u = transformation * u return Interval(l, u) end else l = transformation * l if u isa Infinity{T} return Interval(l, u) else u = transformation * u return Interval(l, u) end end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
14163
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. ######################################################################################################### #"pseudo-types" of aspheres """ AphericSurfaces polynomial evaluation is optimized for no terms `CONIC`, odd terms `ODD`, even terms `EVEN` or any `ODDEVEN` """ @enum AsphericSurfaceType CONIC ODD EVEN ODDEVEN """ AsphericSurface{T,N,Q,M} <: ParametricSurface{T,N} Surface incorporating an aspheric polynomial - radius, conic and aspherics are defined relative to absolute semi-diameter,. `T` is the datatype, `N` is the dimensionality, `Q` is the number of aspheric terms, and `M` is the type of aspheric polynomial. ```julia AsphericSurface(semidiameter; radius, conic, aspherics=nothing, normradius = semidiameter) ``` The surface is centered at the origin and treated as being the cap of an infinite cylinder, thus creating a true half-space. Outside of `0 <= ρ <= 1` the height of the surface is not necessarily well defined, so NaN may be returned. `aspherics` aspherics should be vectors containing tuples of the form (i, v) where i is the polynomial power of the aspheric term. An empty vector is not permitted. Use `nothing` instead. The sag is defined by the equation ```math z(r,\\phi) = \\frac{cr^2}{1 + \\sqrt{1 - (1+k)c^2r^2}} + \\sum_{i}^{Q}\\alpha_ir^{i} ``` where ``\\rho = \\frac{r}{\\texttt{normradius}}``, ``c = \\frac{1}{\\texttt{radius}}``, and ``k = \\texttt{conic}`` . The function checks if the aspheric terms are missing, even, odd or both and uses an efficient polynomial evaluation strategy. """ struct AsphericSurface{T,N,Q,M} <: ParametricSurface{T,N} semidiameter::T curvature::T conic::T aspherics::SVector{Q,T} normradius::T boundingcylinder::Cylinder{T,N} function AsphericSurface(M::AsphericSurfaceType, semidiameter::T, curvature::T, conic::T, aspherics::SVector{Q,T}, normradius::T, boundingcylinder) where {T<:Real,Q} new{T,3,Q,M}(semidiameter, curvature, conic, aspherics, normradius, boundingcylinder) end function AsphericSurface(semidiameter::T; radius::T = typemax(T), conic::T = zero(T), aspherics::Union{Nothing,Vector{Tuple{Int,T}}} = nothing, normradius::T = semidiameter) where {T<:Real} @assert semidiameter > 0 @assert !isnan(semidiameter) && !isnan(radius) && !isnan(conic) @assert one(T) - (1 / radius)^2 * (conic + one(T)) * semidiameter^2 > 0 "Invalid surface (conic/radius combination: $radius, $conic)" @assert aspherics != [] acs = [] if aspherics===nothing M = CONIC else asphericTerms = [i for (i, ) in aspherics] minAsphericTerm = minimum(asphericTerms) maxAsphericTerm = maximum(asphericTerms) @assert minAsphericTerm > 0 "Aspheric Terms must be Order 1 or higher ($minAsphericTerm)" acs = zeros(T, maxAsphericTerm ) for (i, k) in aspherics acs[i] = k end odd = any([isodd(i) && a != zero(T) for (i, a) in enumerate(acs)]) even = any([iseven(i) && a != zero(T) for (i, a) in enumerate(acs)]) if odd && even M = ODDEVEN elseif even M = EVEN acs = [acs[2i] for i in 1:(maxAsphericTerm ÷ 2)] elseif odd M = ODD acs = [acs[2i-1] for i in 1:((maxAsphericTerm+1) ÷ 2)] else #there are no nonzero aspherics terms in the list M = CONIC acs = [] end end Q = length(acs) surf = new{T,3, Q, M}(semidiameter, 1/radius, conic, acs, normradius, Cylinder(semidiameter, interface = opaqueinterface(T))) return surf end end """ EvenAsphericSurface(semidiameter, curvature::T, conic::T, aspherics::Vector{T}; normradius::T=semidiameter) Surface incorporating an aspheric polynomial - radius, conic and aspherics are defined relative to absolute semi-diameter. `aspherics` should be an array of the even coefficients of the aspheric polynomial starting with A2 """ function EvenAsphericSurface(semidiameter::T, curvature::T, conic::T, aspherics::Vector{T}; normradius::T=semidiameter) where T<:Real Q=length(aspherics) AsphericSurface(EVEN, semidiameter, curvature, conic, SVector{Q,T}(aspherics), normradius, Cylinder(semidiameter, interface = opaqueinterface(T))) end """ OddAsphericSurface(semidiameter, curvature::T, conic::T, aspherics::Vector{T}; normradius::T=semidiameter) Surface incorporating an aspheric polynomial - radius, conic and aspherics are defined relative to absolute semi-diameter. `aspherics` should be an array of the odd coefficients of the aspheric polynomial starting with A1 """ function OddAsphericSurface(semidiameter::T, curvature::T, conic::T, aspherics::Vector{T}; normradius::T=semidiameter) where T<:Real Q=length(aspherics) AsphericSurface(ODD, semidiameter, curvature, conic, SVector{Q,T}(aspherics), normradius, Cylinder(semidiameter, interface = opaqueinterface(T))) end """ OddEvenAsphericSurface(semidiameter, curvature::T, conic::T, aspherics::Vector{T}; normradius::T=semidiameter) Surface incorporating an aspheric polynomial - radius, conic and aspherics are defined relative to absolute semi-diameter. `aspherics` should be an array of the both odd and even coefficients of the aspheric polynomial starting with A1 """ function OddEvenAsphericSurface(semidiameter::T, curvature::T, conic::T, aspherics::Vector{T}; normradius::T=semidiameter) where T<:Real Q=length(aspherics) AsphericSurface(ODDEVEN, semidiameter, curvature, conic, SVector{Q,T}(aspherics), normradius, Cylinder(semidiameter, interface = opaqueinterface(T))) end #don't have a function for CONIC as it would better to directly solve for the surface intersection instead of the rootfinding of a ParametricSurface """ asphericType(surf::AsphericSurface) Query the polynomial type of `asp. Returns CONIC, ODD, EVEN, or ODDEVEN. CONIC corresponds to no aspheric terms, ODD means it only has odd aspheric terms, EVEN means only even aspheric terms and ODDEVEN means both even and odd terms. This function is to enable proper interpretation of `surf.aspherics` by any optimization routines that directly query the aspheric coefficients. """ asphericType(z::AsphericSurface{T,3,Q,M}) where {T<:Real,Q,M} = M export AsphericSurface, EvenAsphericSurface, OddAsphericSurface, OddEvenAsphericSurface, asphericType, EVEN, CONIC, ODD, ODDEVEN uvrange(::AsphericSurface{T,N}) where {T<:Real,N} = ((zero(T), one(T)), (-T(π), T(π))) # ρ and ϕ semidiameter(z::AsphericSurface{T}) where {T<:Real} = z.semidiameter halfsizeu(z::AsphericSurface{T}) where {T<:Real} = semidiameter(z) halfsizev(z::AsphericSurface{T}) where {T<:Real} = semidiameter(z) boundingobj(z::AsphericSurface{T}) where {T<:Real} = z.boundingcylinder prod_step(z::AsphericSurface{T,N,Q,ODDEVEN}, r, r2) where {T<:Real,N,Q} = r, r prod_step(z::AsphericSurface{T,N,Q,ODD}, r, r2) where {T<:Real,N,Q} = r, r2 prod_step(z::AsphericSurface{T,N,Q,EVEN}, r, r2) where {T<:Real,N,Q} = r2, r2 function point(z::AsphericSurface{T,3,Q,M}, ρ::T, ϕ::T)::SVector{3,T} where {T<:Real,Q,M} rad = z.semidiameter r = ρ * rad r2 = r^2 t = one(T) - z.curvature^2 * (z.conic + one(T)) * r^2 if t < zero(T) return SVector{3,T}(NaN, NaN, NaN) end h = z.curvature * r2 / (one(T) + sqrt(t)) # sum aspheric if M != CONIC prod, step = prod_step(z, r, r2) #multiple dispatch on M asp,rest = Iterators.peel(z.aspherics) h += asp * prod for asp in rest prod *= step h += asp * prod end end return SVector{3,T}(r * cos(ϕ), r * sin(ϕ), h) end partial_prod_step(z::AsphericSurface{T,3,Q,EVEN}, r::T, r2::T) where {T<:Real,Q} = r, r2, 2:2:2Q partial_prod_step(z::AsphericSurface{T,3,Q,ODD}, r::T, r2::T) where {T<:Real,Q} = one(T), r2, 1:2:(2Q-1) partial_prod_step(z::AsphericSurface{T,3,Q,ODDEVEN}, r::T, r2::T) where {T<:Real,Q} = one(T), r, 1:1:Q function partials(z::AsphericSurface{T,3,Q,M}, ρ::T, ϕ::T)::Tuple{SVector{3,T},SVector{3,T}} where {T<:Real,Q,M} rad = z.semidiameter r = ρ * rad r2 = r*r t = one(T) - z.curvature^2 * (z.conic + one(T)) * r^2 if t < zero(T) return SVector{3,T}(NaN, NaN, NaN), SVector{3,T}(NaN, NaN, NaN) end dhdρ = rad * z.curvature * r * sqrt(t) / t # sum aspherics partial if M != CONIC prod, step, mIter = partial_prod_step(z, r, r2) ((m, asp), rest) = Iterators.peel(zip(mIter,z.aspherics)) dhdρ += rad * asp * 2 * prod #first term m=1*2 and prod = r for (m,asp) in rest prod *= step dhdρ += rad * m * asp * prod end end dhdϕ = zero(T) cosϕ = cos(ϕ) sinϕ = sin(ϕ) return SVector{3,T}(rad * cosϕ, rad * sinϕ, dhdρ), SVector{3,T}(r * -sinϕ, r * cosϕ, dhdϕ) end function normal(z::AsphericSurface{T,3}, ρ::T, ϕ::T)::SVector{3,T} where {T<:Real} du, dv = partials(z, ρ, ϕ) if ρ == zero(T) && norm(dv) == zero(T) # in cases where there is no δϕ at ρ = 0 (i.e. anything which is rotationally symetric) # then we get some big problems, hardcoding this case solves the problems return SVector{3,T}(0, 0, 1) end return normalize(cross(du, dv)) end function uv(z::AsphericSurface{T,3}, p::SVector{3,T}) where {T<:Real} # avoid divide by zero for ForwardDiff ϕ = NaNsafeatan(p[2], p[1]) if p[1] == zero(T) && p[2] == zero(T) ρ = zero(T) else ρ = sqrt(p[1]^2 + p[2]^2) / semidiameter(z) end return SVector{2,T}(ρ, ϕ) end function onsurface(surf::AsphericSurface{T,3}, p::SVector{3,T}) where {T<:Real} ρ, ϕ = uv(surf, p) if ρ > one(T) return false else surfpoint = point(surf, ρ, ϕ) return samepoint(p[3], surfpoint[3]) end end function inside(surf::AsphericSurface{T,3}, p::SVector{3,T}) where {T<:Real} ρ, ϕ = uv(surf, p) if ρ > one(T) return false else surfpoint = point(surf, ρ, ϕ) return p[3] < surfpoint[3] end end ######################################################################################################### # Assumes the ray has been transformed into the canonical coordinate frame which has the vertical axis passing through (0,0,0) and aligned with the z axis. function surfaceintersection(surf::AcceleratedParametricSurface{T,3,AsphericSurface{T,3}}, r::AbstractRay{T,3}) where {T<:Real} cylint = surfaceintersection(surf.surface.boundingcylinder, r) if cylint isa EmptyInterval{T} return EmptyInterval(T) else if doesintersect(surf.triangles_bbox, r) || inside(surf.triangles_bbox, origin(r)) surfint = triangulatedintersection(surf, r) if !(surfint isa EmptyInterval{T}) return intervalintersection(cylint, surfint) end end # hasn't hit the surface if lower(cylint) isa RayOrigin{T} && upper(cylint) isa Infinity{T} if inside(surf.surface, origin(r)) return Interval(RayOrigin(T), Infinity(T)) else return EmptyInterval(T) end # otherwise check that the intersection is underneath the surface else p = point(closestintersection(cylint, false)) ρ, ϕ = uv(surf, p) surfpoint = point(surf.surface, ρ, ϕ) if p[3] < surfpoint[3] return cylint # TODO!! UV (and interface) issues? else return EmptyInterval(T) end end end end function AcceleratedParametricSurface(surf::T, numsamples::Int = 17; interface::NullOrFresnel{S} = NullInterface(S)) where {S<:Real,N,T<:AsphericSurface{S,N}} # Zernike uses ρ, ϕ uv space so need to modify extension of triangulation a = AcceleratedParametricSurface(surf, triangulate(surf, numsamples, true, false, true, false), interface = interface) emptytrianglepool!(S) return a end function asphericSag(surf::AsphericSurface{T,3,Q, EVEN}) where {T<:Real,Q} amin = sum(k < zero(T) ? k * surf.semidiameter^(2m) : zero(T) for (m, k) in enumerate(surf.aspherics)) amax = sum(k > zero(T) ? k * surf.semidiameter^(2m) : zero(T) for (m, k) in enumerate(surf.aspherics)) return amin, amax end function asphericSag(surf::AsphericSurface{T,3,Q, ODD}) where {T<:Real,Q} amin = sum(k < zero(T) ? k * surf.semidiameter^(2m-1) : zero(T) for (m, k) in enumerate(surf.aspherics)) amax = sum(k > zero(T) ? k * surf.semidiameter^(2m-1) : zero(T) for (m, k) in enumerate(surf.aspherics)) return amin, amax end function asphericSag(surf::AsphericSurface{T,3,Q, ODDEVEN}) where {T<:Real,Q} amin = sum(k < zero(T) ? k * surf.semidiameter^(m) : zero(T) for (m, k) in enumerate(surf.aspherics)) amax = sum(k > zero(T) ? k * surf.semidiameter^(m) : zero(T) for (m, k) in enumerate(surf.aspherics)) return amin, amax end function asphericSag(surf::AsphericSurface{T,3,Q, CONIC}) where {T<:Real,Q} amin = zero(T) amax = zero(T) return amin, amax end function BoundingBox(surf::AsphericSurface{T,3}) where {T<:Real} xmin = -semidiameter(surf) xmax = semidiameter(surf) ymin = -semidiameter(surf) ymax = semidiameter(surf) # aspherics can be more comlpicated, so just take sum of all negative and all positives amin, amax = asphericSag(surf) zmin = amin zmax = amax # curvature only goes one way q = one(T) - (one(T) + surf.conic) * surf.curvature^2 * surf.semidiameter^2 if q < zero(T) throw(ErrorException("The surface is invalid, no bounding box can be constructed")) end hmax = surf.curvature * surf.semidiameter^2 / (one(T) + sqrt(q)) if hmax > zero(T) zmax += hmax else zmin += hmax end return BoundingBox(xmin, xmax, ymin, ymax, zmin, zmax) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
9980
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Module to enclose [Chebyshev polynomial](https://en.wikipedia.org/wiki/Chebyshev_polynomials) specific functionality. """ module Chebyshev using OpticSim: NaNsafeacos """ T(n::Int, q::R, fast::Bool = true) -> R Evaluate Chebyshev polynomial of the first kind ``T_n(q)``. `fast` will use trigonometric definition, rather than the recursive definition which is much faster but slightly less precise. """ @inline function T(n::Int, q::R, fast::Bool = true)::R where {R<:Real} @assert n >= 0 if n === 0 return one(R) elseif n === 1 return q elseif fast && n > 3 if abs(q) < one(R) return cos(n * NaNsafeacos(q)) elseif q >= one(R) return cosh(n * acosh(q)) else return (-1)^n * cosh(n * acosh(-q)) end else return 2q * T(n - 1, q, fast) - T(n - 2, q, fast) end end """ U(n::Int, q::R, fast::Bool = true) -> R Evaluate Chebyshev polynomial of the second kind ``U_n(q)``. `fast` will use trigonometric definition, rather than the recursive definition which is much faster but slightly less precise. """ @inline function U(n::Int, q::R, fast::Bool = true)::R where {R<:Real} @assert n >= 0 if n === 0 return one(R) elseif n === 1 return 2q elseif abs(q) < one(R) && fast && q > 3 # much faster but not stable at |q| = 1 aq = NaNsafeacos(q) return sin((n + 1) * aq) / sin(aq) else return 2q * U(n - 1, q, fast) - U(n - 2, q, fast) end end """ dTdq(n::Int, q::R, fast::Bool = true) -> R Evaluate derivative of Chebyshev polynomial of the first kind ``\\frac{dT_n}{dq}(q)``. `fast` will use trigonometric definition, rather than the recursive definition which is much faster but slightly less precise. """ @inline function dTdq(n::Int, q::R, fast::Bool = true)::R where {R<:Real} @assert n >= 0 if n === 0 return zero(R) elseif n === 1 return one(R) elseif fast && n > 4 if abs(q) == one(R) return q^(n + 1) * n^2 elseif abs(q) < one(R) return n * sin(n * acos(q)) / sqrt(1 - q^2) elseif q > one(R) return n * sinh(n * acosh(q)) / sqrt(q^2 - 1) else return -n * (-1)^n * sinh(n * acosh(-q)) / sqrt(q^2 - 1) end else return n * U(n - 1, q, fast) end end # dUdq(n::Int, q::R)::R where {R<:Real} = ((n + 1) * T(n + 1, q) - q * U(n, q)) / (q^2 - one(T)) # d2Tq2(n::Int, q::R)::R where {R<:Real} = n * ((n + 1) * T(n, q) - U(n, q)) / (q^2 - 1) end # module Chebyshev """ ChebyshevSurface{T,N,P,Q} <: ParametricSurface{T,N} Rectangular surface incorporating Chebyshev polynomials as well as radius and conic terms. `T` is the datatype, `N` is the dimensionality, `P` is the number of Chebyshev terms in u and `Q` is the number of Chebyshev terms in v. The surface is centered at the origin and treated as being the cap of an infinite rectangular prism, thus creating a true half-space. **Note that the surface is vertically offset so that the center (i.e., `(u,v) == (0,0)`) lies at 0 on the z-axis.** ```julia ChebyshevSurface(halfsizeu, halfsizev, chebycoeff; radius = Inf, conic = 0) ``` `chebycoeff` is a vector containing tuples of the form `(i, j, v)` where `v` is the value of the coefficient ``c_{ij}``. The sag is defined by the equation ```math z(u,v) = \\frac{c(u^2 + v^2)^2}{1 + \\sqrt{1 - (1+k)c^2(u^2 + v^2)}} + \\sum_{i}^{P}\\sum_{j}^{Q}c_{ij}T_i(u)T_j(v) ``` where ``c = \\frac{1}{\\texttt{radius}}``, ``k = \\texttt{conic}`` and ``T_n`` is the nᵗʰ Chebyshev polynomial of the first kind. """ struct ChebyshevSurface{T,N,P} <: ParametricSurface{T,N} halfsizeu::T halfsizev::T curvature::T conic::T boundingprism::BoundingBox{T} chebycoeff::SVector{P,Tuple{Int,Int,T}} offset::T function ChebyshevSurface(halfsizeu::T, halfsizev::T, chebycoeff::Union{Nothing,Vector{Tuple{Int,Int,T}}}; radius::T = typemax(T), conic::T = zero(T)) where {T<:Real} @assert !isnan(halfsizeu) && !isnan(halfsizev) && !isnan(radius) && !isnan(conic) @assert halfsizeu > zero(T) && halfsizev > zero(T) @assert one(T) - (1 / radius)^2 * (conic + one(T)) * (halfsizeu^2 + halfsizev^2) > 0 "Invalid surface (conic/radius combination: $radius, $conic)" offset = zero(T) if chebycoeff === nothing P = 0 else for (i, j, c) in chebycoeff @assert i >= 0 && j >= 0 "i and j must be non-negative" if i % 2 == 0 && j % 2 == 0 offset += c * (-1)^(i ÷ 2) * (-1)^(j ÷ 2) end end chebycoeff = filter(k -> abs(k[3]) > zero(T), chebycoeff) P = length(chebycoeff) end bounding_prism = BoundingBox(-halfsizeu, halfsizeu, -halfsizev, halfsizev, typemin(T), typemax(T)) return new{T,3,P}(halfsizeu, halfsizev, 1 / radius, conic, bounding_prism, SVector{P,Tuple{Int,Int,T}}(P === 0 ? [] : chebycoeff), offset) end end export ChebyshevSurface uvrange(::Type{ChebyshevSurface{T,N,P}}) where {T<:Real,N,P} = ((-one(T), one(T)), (-one(T), one(T))) boundingobj(z::ChebyshevSurface{T}) where {T<:Real} = z.boundingprism halfsizeu(z::ChebyshevSurface{T}) where {T<:Real} = z.halfsizeu halfsizev(z::ChebyshevSurface{T}) where {T<:Real} = z.halfsizev function point(s::ChebyshevSurface{T,3,P}, u::T, v::T)::SVector{3,T} where {T<:Real,P} x = u * s.halfsizeu y = v * s.halfsizev r2 = (x^2 + y^2) q = (one(T) + s.conic) * s.curvature^2 * r2 if q > one(T) return SVector{3,T}(NaN, NaN, NaN) end z = s.curvature * r2 / (one(T) + sqrt(one(T) - q)) @inbounds @simd for ci in 1:P i, j, c = s.chebycoeff[ci] z += c * Chebyshev.T(i, u) * Chebyshev.T(j, v) end return SVector{3,T}(x, y, z - s.offset) end function partials(s::ChebyshevSurface{T,3,P}, u::T, v::T)::Tuple{SVector{3,T},SVector{3,T}} where {T<:Real,P} x = u * s.halfsizeu y = v * s.halfsizev r2 = x^2 + y^2 t = one(T) - s.curvature^2 * (1 + s.conic) * r2 if t < zero(T) return SVector{3,T}(NaN, NaN, NaN), SVector{3,T}(NaN, NaN, NaN) end q = s.curvature * sqrt(t) / t dhdu = x * q * s.halfsizeu dhdv = y * q * s.halfsizev @inbounds @simd for k in s.chebycoeff i, j, c = k dhdu += c * Chebyshev.dTdq(i, u) * Chebyshev.T(j, v) dhdv += c * Chebyshev.T(i, u) * Chebyshev.dTdq(j, v) end return SVector{3,T}(s.halfsizeu, 0.0, dhdu), SVector{3,T}(0.0, s.halfsizev, dhdv) end function normal(s::ChebyshevSurface{T,3,P}, u::T, v::T)::SVector{3,T} where {T<:Real,P} du, dv = partials(s, u, v) return normalize(cross(du, dv)) end function uv(s::ChebyshevSurface{T,3,P}, p::SVector{3,T}) where {T<:Real,P} return SVector{2,T}(p[1] / s.halfsizeu, p[2] / s.halfsizev) end function onsurface(surf::ChebyshevSurface{T,3,P}, p::SVector{3,T}) where {T<:Real,P} u, v = uv(surf, p) if abs(u) > one(T) || abs(v) > one(T) return false else surfpoint = point(surf, u, v) return samepoint(p[3], surfpoint[3]) end end function inside(surf::ChebyshevSurface{T,3,P}, p::SVector{3,T}) where {T<:Real,P} u, v = uv(surf, p) if abs(u) > one(T) || abs(v) > one(T) return false else surfpoint = point(surf, u, v) return p[3] < surfpoint[3] end end ######################################################################################################### # Assumes the ray has been transformed into the canonical coordinate frame which has the vertical axis passing through (0,0,0) and aligned with the z axis. function surfaceintersection(surf::AcceleratedParametricSurface{T,3,ChebyshevSurface{T,3,P}}, r::AbstractRay{T,3}) where {T<:Real,P} bboxint = surfaceintersection(surf.surface.boundingprism, r) if bboxint isa EmptyInterval{T} return EmptyInterval(T) else if doesintersect(surf.triangles_bbox, r) || inside(surf.triangles_bbox, origin(r)) surfint = triangulatedintersection(surf, r) if !(surfint isa EmptyInterval{T}) return intervalintersection(bboxint, surfint) end end # hasn't hit the surface if lower(bboxint) isa RayOrigin{T} && upper(bboxint) isa Infinity{T} if inside(surf.surface, origin(r)) return Interval(RayOrigin(T), Infinity(T)) else return EmptyInterval(T) end # otherwise check that the intersection is underneath the surface else p = point(closestintersection(bboxint, false)) ρ, ϕ = uv(surf, p) surfpoint = point(surf.surface, ρ, ϕ) if p[3] < surfpoint[3] return bboxint # TODO!! UV (and interface) issues? else return EmptyInterval(T) end end end end function BoundingBox(surf::ChebyshevSurface{T,3,P}) where {T<:Real,P} xmin = -surf.halfsizeu xmax = surf.halfsizeu ymin = -surf.halfsizev ymax = surf.halfsizev # polynomials range between -1 and 1 so we have to sum the absolute value of every coefficient to get the theoretical max zmax = P > 0 ? sum(abs(c) for (_, _, c) in surf.chebycoeff) : zero(T) zmin = -zmax q = one(T) - (one(T) + surf.conic) * surf.curvature^2 * (surf.halfsizeu^2 + surf.halfsizev^2) if q < zero(T) throw(ErrorException("The surface is invalid, no bounding box can be constructed")) end hmax = surf.curvature * (surf.halfsizeu^2 + surf.halfsizev^2) / (one(T) + sqrt(q)) if hmax > zero(T) zmax += hmax else zmin += hmax end return BoundingBox(xmin, xmax, ymin, ymax, zmin, zmax) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
4246
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Cylinder{T,N} <: ParametricSurface{T,N} Cylinder of infinite height centered at the origin, oriented along the z-axis. `visheight` is used for visualization purposes only, **note that this does not fully represent the surface**. ```julia Cylinder(radius::T, visheight::T = 2.0; interface::NullOrFresnel{T} = nullinterface(T)) ``` """ struct Cylinder{T,N} <: ParametricSurface{T,N} radius::T visheight::T # Only used for visualization purposes. interface::NullOrFresnel{T} function Cylinder(radius::T, visheight::T = T(2.0); interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert radius > zero(T) && visheight > zero(T) @assert !isnan(radius) new{T,3}(radius, visheight, interface) end end export Cylinder Base.show(io::IO, a::Cylinder{T}) where {T<:Real} = print(io, "Cylinder{$T}($(a.radius), $(interface(a)))") interface(a::Cylinder{T}) where {T<:Real} = a.interface radius(a::Cylinder{T}) where {T<:Real} = a.radius uvrange(::Type{Cylinder{T,N}}) where {T<:Real,N} = ((-T(π), T(π)), (-one(T), one(T))) onsurface(cyl::Cylinder{T,3}, x::T, y::T, ::T) where {T<:Real} = samepoint(x^2 + y^2, radius(cyl)^2) inside(cyl::Cylinder{T,3}, x::T, y::T, ::T) where {T<:Real} = x^2 + y^2 - radius(cyl)^2 < zero(T) point(cyl::Cylinder{T,3}, u::T, v::T) where {T<:Real} = SVector{3,T}(radius(cyl) * cos(u), radius(cyl) * sin(u), v * cyl.visheight / 2) normal(::Cylinder{T,3}, u::T, ::T) where {T<:Real} = SVector{3,T}(cos(u), sin(u), 0.0) partials(::Cylinder{T,3}, u::T, ::T) where {T<:Real} = SVector{3,T}(-sin(u), cos(u), 0.0), SVector{3,T}(0.0, 0.0, 1.0) uv(cyl::Cylinder{T,3}, x::T, y::T, z::T) where {T<:Real} = SVector{2,T}(atan(y, x), 2 * z / cyl.visheight) # Assumes the ray has been transformed into the canonical cylinder coordinate frame which has the cylinder axis passing through (0,0,0) and aligned with the z axis. function surfaceintersection(cyl::Cylinder{T,N}, r::AbstractRay{T,N}) where {T<:Real,N} # in the cylinder coordinate frame the cylinder axis is (0,0,1). project ray into plane perpendicular to cylinder axis by dropping z coordinate ox, oy, oz = origin(r) dx, dy, dz = direction(r) rad = radius(cyl) c = (ox^2 + oy^2) - rad^2 if samepoint(one(T), abs(dz)) # ray is parallel to the cylinder axis if c > zero(T) # if strictly outside the cylinder then no intersection return EmptyInterval(T) else # ray is contained entirely in the cylinder return rayorigininterval(Infinity(T)) end end a = dx^2 + dy^2 b = 2 * (ox * dx + oy * dy) temp = quadraticroots(a, b, c) if temp === nothing return EmptyInterval(T) # no intersection with cylinder and ray not contained entirely in cylinder end t1, t2 = temp if isapprox(t1, t2, rtol = 1e-12, atol = 2 * eps(T)) return EmptyInterval(T) # single root which indicates a tangent ray cylinder intersection end if t1 > zero(T) pt1 = point(r, t1) else pt1 = nothing end if t2 > zero(T) pt2 = point(r, t2) else pt2 = nothing end let int1 = nothing, int2 = nothing if pt1 !== nothing u, v = uv(cyl, pt1) int1 = Intersection(t1, pt1, SVector{3,T}(pt1[1], pt1[2], 0.0), u, v, interface(cyl)) end if pt2 !== nothing u, v = uv(cyl, pt2) int2 = Intersection(t2, pt2, SVector{3,T}(pt2[1], pt2[2], 0.0), u, v, interface(cyl)) end if int1 !== nothing && int2 !== nothing if t1 <= t2 return Interval(int1, int2) else return Interval(int2, int1) end elseif int1 !== nothing return rayorigininterval(int1) elseif int2 !== nothing return rayorigininterval(int2) else return EmptyInterval(T) end end end BoundingBox(cyl::Cylinder{T,3}) where {T<:Real} = BoundingBox(-radius(cyl), radius(cyl), -radius(cyl), radius(cyl), typemin(T), typemax(T))
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
17720
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Either `GridSagLinear` or `GridSagBicubic` - determines the interpolation between sample points in the grid for a [`GridSagSurface`](@ref). """ @enum GridSagInterpolation GridSagLinear GridSagBicubic export GridSagInterpolation, GridSagLinear, GridSagBicubic """ GridSagSurface{T,N,S<:Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}},Nu,Nv} <: ParametricSurface{T,N} Either a Zernike (circular) or Chebyshev (rectangular) surface with grid sag height added to the base sag. The surface shape is determined by either a linear or a bicubic spline interpolation of the `Nu×Nv` grid of sag values, set by the `interpolation` argument taking either `GridSagLinear` or `GridSagBicubic`. Each entry in the grid is a vector of the form ``[z, \\frac{\\partial z}{\\partial x}, \\frac{\\partial z}{\\partial y}, \\frac{\\partial^2 z}{\\partial x \\partial y}]``. The first data item corresponds to the lower left corner of the surface, that is, the corner defined by the -u and -v limit. Each point that follows is read across the face of the surface from left to right moving upwards. If zero is given for the partials (and using bicubic interpolation) then the partials will be approximated using finite differences. The sag grid can be decentered from the surface in uv space, if so the surface may become wild outside of the area over which the grid is defined. It is advised to clip the surface to the valid area using CSG operations in this case. A surface can also be generated from a `.GRD` file by passing in the filename as the first and only positional argument. In this case the surface will be rectangular with optional radius and conic. See docs for [`ZernikeSurface`](@ref) and [`ChebyshevSurface`](@ref) for details of the base surface. ```julia GridSagSurface(basesurface::Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}}, sag_grid::AbstractArray{T,3}; interpolation = GridSagBicubic, decenteruv = (0, 0)) GridSagSurface{T}(filename::String; radius = Inf, conic = 0, interpolation = GridSagBicubic) ``` """ struct GridSagSurface{T,N,S<:Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}},Nu,Nv} <: ParametricSurface{T,N} basesurface::S gridsag::SVector{Nu,SVector{Nv,SVector{4,T}}} interpolation::GridSagInterpolation decenteruv::Tuple{T,T} function GridSagSurface(basesurface::S, sag_grid::AbstractArray{T,2}; interpolation::GridSagInterpolation = GridSagBicubic, decenteruv::Tuple{T,T} = (zero(T), zero(T))) where {T<:Real,N,S<:Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}}} grid = [] Nv, Nu, d = size(sag_grid) @assert d == 4 for r in 1:Nu row = [] for c in 1:Nv push!(row, SVector{4,T}(sag_grid[c, r], 0, 0, 0)) end push!(grid, row) end grid = SVector{Nu,SVector{Nv,SVector{4,T}}}(grid) return GridSagSurface(basesurface, grid, interpolation = interpolation, decenteruv = decenteruv) end function GridSagSurface(basesurface::S, sag_grid::AbstractArray{T,3}; interpolation::GridSagInterpolation = GridSagBicubic, decenteruv::Tuple{T,T} = (zero(T), zero(T))) where {T<:Real,N,S<:Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}}} grid = [] Nv, Nu, d = size(sag_grid) @assert d == 4 for r in 1:Nu row = [] for c in 1:Nv push!(row, SVector{4,T}(sag_grid[c, r, :])) end push!(grid, row) end grid = SVector{Nu,SVector{Nv,SVector{4,T}}}(grid) return GridSagSurface(basesurface, grid, interpolation = interpolation, decenteruv = decenteruv) end function GridSagSurface(basesurface::S, sag_grid::AbstractArray{<:AbstractVector{T},2}; interpolation::GridSagInterpolation = GridSagBicubic, decenteruv::Tuple{T,T} = (zero(T), zero(T))) where {T<:Real,N,S<:Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}}} grid = [] Nv, Nu = size(sag_grid) @assert length(sag_grid[1, 1]) == 4 for r in 1:Nu push!(grid, sag_grid[:, r]) end grid = SVector{Nu,SVector{Nv,SVector{4,T}}}(grid) return GridSagSurface(basesurface, grid, interpolation = interpolation, decenteruv = decenteruv) end function GridSagSurface(basesurface::S, sag_grid::SVector{Nu,SVector{Nv,SVector{4,T}}}; interpolation::GridSagInterpolation = GridSagBicubic, decenteruv::Tuple{T,T} = (zero(T), zero(T))) where {T<:Real,N,S<:Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}},Nu,Nv} # TODO can probably simplify this? if interpolation === GridSagLinear @warn "Linear interpolation doesn't ensure C1 continuity, may cause problems..." end Δx = 2 * halfsizeu(basesurface) / (Nu - 1) Δy = 2 * halfsizev(basesurface) / (Nv - 1) kx = 1 / 2Δx ky = 1 / 2Δy kxy = kx * ky dxdκ = 2 * halfsizeu(basesurface) / (Nu - 1) dydγ = 2 * halfsizev(basesurface) / (Nv - 1) grid = MVector{Nu,MVector{Nv,SVector{4,T}}}(sag_grid) # if no derivs are provided (and we need them, i.e. bicubic) then approximate them here calcderivs = interpolation === GridSagBicubic && all(all.(iszero.(getindex.(v, [2:4])) for v in sag_grid)) for u in 1:Nu for v in 1:Nv if calcderivs # use finite differences if missing derivatives z = sag_grid[u][v][1] # at the edges just assume the derivative continues unchanged from that between the adjacent and current points # in this case we need to half Δx and/or Δy hence umod and vmod below u₊₁ = u + 1 u₋₁ = u - 1 umod = 1.0 if u === Nu u₊₁ = u umod = 2 elseif u === 1 u₋₁ = 1 umod = 2 end v₊₁ = v + 1 v₋₁ = v - 1 vmod = 1.0 if v === Nv v₊₁ = v vmod = 2 elseif v === 1 v₋₁ = 1 vmod = 2 end dzdx = kx * (sag_grid[u₊₁][v][1] - sag_grid[u₋₁][v][1]) * umod dzdy = ky * (sag_grid[u][v₊₁][1] - sag_grid[u][v₋₁][1]) * vmod dzdxdy = kxy * ((sag_grid[u₊₁][v₊₁][1] - sag_grid[u₊₁][v₋₁][1]) - (sag_grid[u₋₁][v₊₁][1] - sag_grid[u₋₁][v₋₁][1])) * umod * vmod else z, dzdx, dzdy, dzdxdy = sag_grid[u][v] end # transform the derivatives from xy to κγ (i.e [0,1] in each patch) dzdκ = dzdx * dxdκ dzdγ = dzdy * dydγ dzdκdγ = dzdxdy * dxdκ * dydγ grid[u][v] = SVector{4,T}(z, dzdκ, dzdγ, dzdκdγ) end end return new{T,N,S,Nu,Nv}(basesurface, SVector{Nu,SVector{Nv,SVector{4,T}}}(grid), interpolation, decenteruv) end function GridSagSurface{T}(filename::String; radius::T = typemax(T), conic::T = zero(T), interpolation::GridSagInterpolation = GridSagBicubic) where {T<:Real} @assert !isnan(radius) && !isnan(conic) @assert isfile(filename) if !isvalid(readuntil(filename, " ")) f = open(filename, enc"UTF-16LE", "r") else f = open(filename, "r") end spec = readline(f) spec = replace(spec, "\ufeff" => "") specs = split(spec) Nv = parse(Int, specs[1]) Nu = parse(Int, specs[2]) Δx = parse(Float64, specs[3]) Δy = parse(Float64, specs[4]) units = parse(Int, specs[5]) if units == 0 unitmod = 1 elseif units == 1 unitmod = 10 elseif units == 2 unitmod = 25.4 elseif units == 3 unitmod = 1000 else throw(ErrorException("Invalid units")) end halfsizeu = (Nu - 1) * Δx / 2 / unitmod halfsizev = (Nv - 1) * Δy / 2 / unitmod xdec = parse(Float64, specs[6]) / unitmod ydec = parse(Float64, specs[7]) / unitmod decenteruv = (xdec / halfsizeu, ydec / halfsizev) grid = Array{Float64,3}(undef, Nv, Nu, 4) thisrowcount = 1 thisrownum = 1 for l in readlines(f) vs = [parse(Float64, x) for x in split(l)] if vs[5] == 1 z, dzdx, dzdy, d2zdxdy = zeros(4) # nodata else z, dzdx, dzdy, d2zdxdy = vs[1:4] end # flip the y direction as GRD goes from -x, +y right and down while we go from -x, -y right and up grid[Nv - thisrownum + 1, thisrowcount, :] = [z / unitmod, dzdx / unitmod, dzdy / unitmod, d2zdxdy / unitmod^2] if thisrowcount == Nu thisrownum += 1 thisrowcount = 1 else thisrowcount += 1 end end close(f) return GridSagSurface(ChebyshevSurface(halfsizeu, halfsizev, nothing, radius = radius, conic = conic), grid, interpolation = interpolation, decenteruv = decenteruv) end end export GridSagSurface uvrange(::Type{GridSagSurface{T,N,S,Nu,Nv}}) where {T<:Real,N,S<:Union{ZernikeSurface{T,N},ChebyshevSurface{T,N}},Nu,Nv} = uvrange(S) @inline function gridsag(s::GridSagSurface{T,3,S,Nu,Nv}, ui::Int, vi::Int, i::Int = 0) where {T<:Real,S,Nu,Nv} @assert 0 <= ui < Nu @assert 0 <= vi < Nv @assert i <= 4 if i <= 0 return @inbounds s.gridsag[ui + 1][vi + 1] else return @inbounds s.gridsag[ui + 1][vi + 1][i] end end @inline function bicubicα(surf::GridSagSurface{T,3,S,Nu,Nv}, uli::Int, uui::Int, vli::Int, vui::Int) where {T<:Real,S,Nu,Nv} f00, fu00, fv00, fuv00 = gridsag(surf, uli, vli) f01, fu01, fv01, fuv01 = gridsag(surf, uli, vui) f11, fu11, fv11, fuv11 = gridsag(surf, uui, vui) f10, fu10, fv10, fuv10 = gridsag(surf, uui, vli) return SMatrix{4,4,T,16}(1, 0, -3, 2, 0, 0, 3, -2, 0, 1, -2, 1, 0, 0, -1, 1) * SMatrix{4,4,T,16}(f00, f10, fu00, fu10, f01, f11, fu01, fu11, fv00, fv10, fuv00, fuv10, fv01, fv11, fuv01, fuv11) * SMatrix{4,4,T,16}(1, 0, 0, 0, 0, 0, 1, 0, -3, 3, -2, -1, 2, -2, 1, 1) end @inline function bicubicζ(surf::GridSagSurface{T,3,S,Nu,Nv}, uli::Int, uui::Int, vli::Int, vui::Int, κ::T, γ::T) where {T<:Real,S,Nu,Nv} return (SMatrix{1,4,T,4}(1, κ, κ^2, κ^3) * bicubicα(surf, uli, uui, vli, vui) * SMatrix{4,1,T,4}(1, γ, γ^2, γ^3))[1] end @inline function bicubicdζ(surf::GridSagSurface{T,3,S,Nu,Nv}, uli::Int, uui::Int, vli::Int, vui::Int, κ::T, γ::T) where {T<:Real,S,Nu,Nv} α = bicubicα(surf, uli, uui, vli, vui) dκ = (SMatrix{1,4,T,4}(0, 1, 2κ, 3κ^2) * α * SMatrix{4,1,T,4}(1, γ, γ^2, γ^3))[1] dγ = (SMatrix{1,4,T,4}(1, κ, κ^2, κ^3) * α * SMatrix{4,1,T,4}(0, 1, 2γ, 3γ^2))[1] return dκ, dγ end @inline function normalizedcoords(Nu::Int, Nv::Int, u::T, v::T, decenter::Tuple{T,T}) where {T<:Real} u = u - decenter[1] v = v - decenter[2] û = (u + 1) / 2 v̂ = (v + 1) / 2 uli = max(min(floor(Int, û * (Nu - 1)), Nu - 2), 0) uui = min(uli + 1, Nu - 1) vli = max(min(floor(Int, v̂ * (Nv - 1)), Nv - 2), 0) vui = min(vli + 1, Nv - 1) κ = û * (Nu - 1) - uli γ = v̂ * (Nv - 1) - vli return uli, uui, vli, vui, κ, γ end @inline function ζ(surf::GridSagSurface{T,3,S,Nu,Nv}, u::T, v::T) where {T<:Real,S,Nu,Nv} uli, uui, vli, vui, κ, γ = normalizedcoords(Nu, Nv, u, v, surf.decenteruv) if surf.interpolation === GridSagLinear sagll = gridsag(surf, uli, vli, 1) saglu = gridsag(surf, uli, vui, 1) sagul = gridsag(surf, uui, vli, 1) saguu = gridsag(surf, uui, vui, 1) z = κ * (γ * saguu + (1 - γ) * sagul) + (1 - κ) * (γ * saglu + (1 - γ) * sagll) elseif surf.interpolation === GridSagBicubic z = bicubicζ(surf, uli, uui, vli, vui, κ, γ) end return z end @inline function dζ(surf::GridSagSurface{T,3,S,Nu,Nv}, u::T, v::T) where {T<:Real,S,Nu,Nv} uli, uui, vli, vui, κ, γ = normalizedcoords(Nu, Nv, u, v, surf.decenteruv) # calculate sag derivative at point if surf.interpolation === GridSagLinear sagll = gridsag(surf, uli, vli, 1) saglu = gridsag(surf, uli, vui, 1) sagul = gridsag(surf, uui, vli, 1) saguu = gridsag(surf, uui, vui, 1) dζdκ = (γ * saguu + (1 - γ) * sagul) - (γ * saglu + (1 - γ) * sagll) dζdγ = (κ * saguu + (1 - κ) * saglu) - (κ * sagul + (1 - κ) * sagll) # NOT C1 CONTINUOUS!!! elseif surf.interpolation === GridSagBicubic dζdκ, dζdγ = bicubicdζ(surf, uli, uui, vli, vui, κ, γ) # C1 continuous, but not C2 continuous (at grid boundaries) end # change variables dζdu = dζdκ * (Nu - 1) / 2 dζdv = dζdγ * (Nv - 1) / 2 return dζdu, dζdv end function point(surf::GridSagSurface{T,3,S}, ρ::T, ϕ::T)::SVector{3,T} where {T<:Real,S<:ZernikeSurface{T,3}} x, y, z = point(surf.basesurface, ρ, ϕ) u = ρ * cos(ϕ) v = ρ * sin(ϕ) return SVector{3,T}(x, y, z + ζ(surf, u, v)) end function point(surf::GridSagSurface{T,3,S}, u::T, v::T)::SVector{3,T} where {T<:Real,S<:ChebyshevSurface{T,3}} x, y, z = point(surf.basesurface, u, v) return SVector{3,T}(x, y, z + ζ(surf, u, v)) end function partials(surf::GridSagSurface{T,3,S}, ρ::T, ϕ::T)::Tuple{SVector{3,T},SVector{3,T}} where {T<:Real,S<:ZernikeSurface{T,3}} pρ, pϕ = partials(surf.basesurface, ρ, ϕ) u = ρ * cos(ϕ) v = ρ * sin(ϕ) dζdu, dζdv = dζ(surf, u, v) dζdρ = dζdu * cos(ϕ) + dζdv * sin(ϕ) dζdϕ = dζdv * u - dζdu * v return SVector{3,T}(pρ[1], pρ[2], pρ[3] + dζdρ), SVector{3,T}(pϕ[1], pϕ[2], pϕ[3] + dζdϕ) end function partials(surf::GridSagSurface{T,3,S}, u::T, v::T)::Tuple{SVector{3,T},SVector{3,T}} where {T<:Real,S<:ChebyshevSurface{T,3}} pu, pv = partials(surf.basesurface, u, v) du, dv = dζ(surf, u, v) return SVector{3,T}(pu[1], pu[2], pu[3] + du), SVector{3,T}(pv[1], pv[2], pv[3] + dv) end function normal(z::GridSagSurface{T,N}, u::T, v::T)::SVector{N,T} where {T<:Real,N} du, dv = partials(z, u, v) return normalize(cross(du, dv)) end uv(s::GridSagSurface{T,3}, p::SVector{3,T}) where {T<:Real} = uv(s.basesurface, p) function onsurface(surf::GridSagSurface{T,3,S}, p::SVector{3,T}) where {T<:Real,S} u, v = uv(surf, p) if abs(u) > one(T) || (abs(v) > one(T) && S <: ChebyshevSurface{T,3}) return false else # not sure it's really necessary/correct to include the cylinder here surfpoint = point(surf, u, v) return @inbounds samepoint(p[3], surfpoint[3]) # || (ρ == 1 && p[3] < z) end end function inside(surf::GridSagSurface{T,3,S}, p::SVector{3,T}) where {T<:Real,S} u, v = uv(surf, p) if abs(u) > one(T) || (abs(v) > one(T) && S <: ChebyshevSurface{T,3}) return false else surfpoint = point(surf, u, v) return @inbounds p[3] < surfpoint[3] end end ######################################################################################################### # Assumes the ray has been transformed into the canonical coordinate frame which has the vertical axis passing through (0,0,0) and aligned with the z axis. function surfaceintersection(surf::AcceleratedParametricSurface{T,3,GridSagSurface{T,3,S,Nu,Nv}}, r::AbstractRay{T,3}) where {T<:Real,S,Nu,Nv} boundingintvl = surfaceintersection(boundingobj(surf.surface.basesurface), r) if boundingintvl isa EmptyInterval{T} return EmptyInterval(T) else if doesintersect(surf.triangles_bbox, r) || inside(surf.triangles_bbox, origin(r)) surfint = triangulatedintersection(surf, r) if !(surfint isa EmptyInterval{T}) return intervalintersection(boundingintvl, surfint) end end # hasn't hit the surface if lower(boundingintvl) isa RayOrigin{T} && upper(boundingintvl) isa Infinity{T} if inside(surf.surface, origin(r)) return Interval(RayOrigin(T), Infinity(T)) else return EmptyInterval(T) end # otherwise check that the intersection is underneath the surface else p = point(closestintersection(boundingintvl, false)) ρ, ϕ = uv(surf, p) surfpoint = point(surf.surface, ρ, ϕ) if @inbounds p[3] < surfpoint[3] return boundingintvl # TODO!! UV (and interface) issues? else return EmptyInterval(T) end end end end function AcceleratedParametricSurface(surf::GridSagSurface{T,N,Z}, numsamples::Int = 17; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real,N,Z<:ZernikeSurface{T,N}} # Zernike uses ρ, ϕ uv space so need to modify extension of triangulation a = AcceleratedParametricSurface(surf, triangulate(surf, numsamples, true, false, true, false), interface = interface) emptytrianglepool!(T) return a end function BoundingBox(surf::GridSagSurface{T,3}) where {T<:Real} bbox = BoundingBox(surf.basesurface) maxsag = maximum(maximum.(getindex.(surf.gridsag[i], 1) for i in 1:length(surf.gridsag))) minsag = minimum(minimum.(getindex.(surf.gridsag[i], 1) for i in 1:length(surf.gridsag))) return BoundingBox(bbox.xmin, bbox.xmax, bbox.ymin, bbox.ymax, bbox.zmin + minsag, bbox.zmax + maxsag) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
6154
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Plane{T,N} <: ParametricSurface{T,N} Infinite planar surface where the positive normal side is outside the surface. By default this will not create any geometry for visualization, the optional `vishalfsizeu` and `vishalfsizev` arguments can be used to draw the plane as a rectangle for visualization **note that this does not fully represent the surface**. In this case, the rotation of the rectangle around the normal to the plane is defined by `visvec` - `surfacenormal×visvec` is taken as the vector along the u axis. ```julia Plane(surfacenormal::SVector{N,T}, pointonplane::SVector{N,T}; interface::NullOrFresnel{T} = nullinterface(T), vishalfsizeu::T = 0.0, vishalfsizev::T = 0.0, visvec::SVector{N,T} = [0.0, 1.0, 0.0]) Plane(nx::T, ny::T, nz::T, x::T, y::T, z::T; interface::NullOrFresnel{T} = nullinterface(T), vishalfsizeu::T = 0.0, vishalfsizev::T = 0.0, visvec::SVector{N,T} = [0.0, 1.0, 0.0]) ``` """ struct Plane{T,N} <: ParametricSurface{T,N} normal::SVector{N,T} d::T pointonplane::SVector{N,T} interface::NullOrFresnel{T} # below only for visualization purposes vishalfsizeu::T vishalfsizev::T visuvec::SVector{N,T} visvvec::SVector{N,T} function Plane(surfacenormal::AbstractArray{T,1}, pointonplane::AbstractArray{T,1}; interface::NullOrFresnel{T} = NullInterface(T), vishalfsizeu::T = zero(T), vishalfsizev::T = zero(T), visvec::AbstractArray{T,1} = [0.0, 1.0, 0.0]) where {T} @assert length(surfacenormal) == length(pointonplane) == length(visvec) N = length(surfacenormal) return Plane(SVector{N,T}(surfacenormal), SVector{N,T}(pointonplane), interface = interface, vishalfsizeu = vishalfsizeu, vishalfsizev = vishalfsizev, visvec = SVector{N,T}(visvec)) end function Plane(surfacenormal::SVector{N,T}, pointonplane::SVector{N,T}; interface::NullOrFresnel{T} = NullInterface(T), vishalfsizeu::T = zero(T), vishalfsizev::T = zero(T), visvec::SVector{N,T} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real,N} norml = normalize(surfacenormal) d = dot(norml, pointonplane) if abs(dot(visvec, norml)) == one(T) visvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(visvec), norml)) vvec = normalize(cross(norml, uvec)) return new{T,N}(norml, d, pointonplane, interface, vishalfsizeu, vishalfsizev, uvec, vvec) end function Plane(nx::T, ny::T, nz::T, x::T, y::T, z::T; interface::NullOrFresnel{T} = NullInterface(T), vishalfsizeu::T = zero(T), vishalfsizev::T = zero(T), visvec = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} return Plane(SVector{3,T}(nx, ny, nz), SVector{3,T}(x, y, z), interface = interface, vishalfsizeu = vishalfsizeu, vishalfsizev = vishalfsizev, visvec = visvec) end end export Plane Base.show(io::IO, a::Plane{T}) where {T<:Real} = print(io, "Plane{$T}($(a.pointonplane), $(normal(a)), $(interface(a)))") interface(a::Plane{T,N}) where {T<:Real,N} = a.interface normal(pln::Plane{T,N}) where {T<:Real,N} = pln.normal inside(pln::Plane{T,3}, p::SVector{3,T}) where {T<:Real} = dot(normal(pln), p) - pln.d < zero(T) onsurface(pln::Plane{T,3}, p::SVector{3,T}) where {T<:Real} = samepoint(dot(normal(pln), p), pln.d) distancefromplane(p::Plane{T,N}, point::SVector{N,T}) where {N,T<:Real} = dot(normal(p), point) - p.d uvrange(::Type{Plane{T,N}}) where {T<:Real,N} = ((-one(T), one(T)), (-one(T), one(T))) point(p::Plane{T}, u::T, v::T) where {T<:Real} = p.pointonplane + p.vishalfsizeu * u * p.visuvec + p.vishalfsizev * v * p.visvvec normal(p::Plane{T}, ::T, ::T) where {T<:Real} = normal(p) pointonplane(p::Plane{T}) where{T<:Real} = p.pointonplane function surfaceintersection(pln::Plane{T,N}, r::AbstractRay{T,N}) where {T<:Real,N} n̂ = normal(pln) d = direction(r) o = origin(r) nd = dot(n̂, d) if samepoint(nd, zero(T)) # ray and plane are parallel if inside(pln, o) || onsurface(pln, o) return rayorigininterval(Infinity(T)) else # no intersection only if the ray is strictly outside of the palne return EmptyInterval(T) end end t = (pln.d - dot(n̂, o)) / nd if t < zero(T) if inside(pln, o) # if the ray starts 'inside' the surface then we want to return a ray so intersection works return rayorigininterval(Infinity(T)) else return EmptyInterval(T) # no ray plane intersection end end temp = Intersection(t, point(r, t), n̂, zero(T), zero(T), interface(pln)) if nd < zero(T) return positivehalfspace(temp) else return rayorigininterval(temp) end end function BoundingBox(pln::Plane{T,3}) where {T<:Real} # TODO! this is far from ideal, we should try and do something better for intersection with non-axis-algined planes # valid for axis aligned planes, otherwise we have to assume an infinite bounding box if normal(pln) === SVector{3,T}(0, 0, 1) return BoundingBox(typemin(T), typemax(T), typemin(T), typemax(T), typemin(T), pln.pointonplane[3]) elseif normal(pln) === SVector{3,T}(0, 0, -1) return BoundingBox(typemin(T), typemax(T), typemin(T), typemax(T), pln.pointonplane[3], typemax(T)) elseif normal(pln) === SVector{3,T}(0, 1, 0) return BoundingBox(typemin(T), typemax(T), typemin(T), pln.pointonplane[2], typemin(T), typemax(T)) elseif normal(pln) === SVector{3,T}(0, -1, 0) return BoundingBox(typemin(T), typemax(T), pln.pointonplane[2], typemax(T), typemin(T), typemax(T)) elseif normal(pln) === SVector{3,T}(1, 0, 0) return BoundingBox(typemin(T), pln.pointonplane[1], typemin(T), typemax(T), typemin(T), typemax(T)) elseif normal(pln) === SVector{3,T}(-1, 0, 0) return BoundingBox(pln.pointonplane[1], typemax(T), typemin(T), typemax(T), typemin(T), typemax(T)) else return BoundingBox(typemin(T), typemax(T), typemin(T), typemax(T), typemin(T), typemax(T)) end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
993
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. struct ConvexPolygon{T,N,M} <: ParametricSurface{T,N} plane::Plane{T,N} origin::SVector{N,T} vertices::SMatrix{N,M,T} end # uv(surface::ParametricSurface{T,N}, p::SVector{N,T}) -> SVector{2,T} # uvrange(surface::ParametricSurface{T,N}) -> Tuple{Tuple{T,T},Tuple{T,T}} # point(surface::ParametricSurface{T,N}, u::T, v::T) -> SVector{N,T} # partials(surface::ParametricSurface{T,N}, u::T, v::T) -> Tuple{SVector{N,T}, SVector{N,T}} # normal(surface::ParametricSurface{T,N}, u::T, v::T) -> SVector{N,T} # inside(surface::ParametricSurface{T,N}, p: :SVector{N,T}) -> Bool # onsurface(surface::ParametricSurface{T,N}, p::SVector{N,T}) -> Bool # surfaceintersection(surface::ParametricSurface{T,N}, AbstractRay::Ray{T,N}) -> Union{EmptyInterval{T},Interval{T},DisjointUnion{T}} # interface(surface::ParametricSurface{T,N}) -> OpticalInterface{T}
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
24948
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Module to enclose QType polynomial specific functionality. For reference see: 1. [_Robust, efficient computational methods for axially symmetric optical aspheres_ - G. W. Forbes, 2010](https://www.osapublishing.org/viewmedia.cfm?uri=oe-18-19-19700&seq=0) 2. [_Characterizing the shape of freeform optics_ - G. W. Forbes, 2012](https://www.osapublishing.org/viewmedia.cfm?uri=oe-20-3-2483&seq=0) """ module QType using StaticArrays using Plots using ..OpticSim: QTYPE_PRECOMP function F(m::Int, n::Int)::Float64 # 2 eq A.13 @assert m > 0 if n === 0 return Float64((m^2 * factorial2(big(2m - 3))) / (2^(m + 1) * factorial(big(m - 1)))) elseif n > 0 && m === 1 return Float64((4(n - 1)^2 * n^2 + 1) / (8 * (2n - 1)^2) + 11 * Int(n === 1) / 32) elseif n > 0 && m > 1 χ = m + n - 2 return Float64((2n * χ * (3 - 5m + 4n * χ) + m^2 * (3 - m + 4n * χ)) / ((m + 2n - 3) * (m + 2n - 2) * (m + 2n - 1) * (2n - 1)) * γ(m, n)) else throw(ErrorException("Invalid n and m")) end end # 2 eq A.14 γ(a::Int, b::Int) = (factorial(big(b)) * factorial2(big(2a + 2b - 3))) / (2^(a + 1) * factorial(big(a + b - 3)) * factorial2(big(2b - 1))) function G(m::Int, n::Int)::Float64 # 2 eq A.15 @assert m > 0 if n === 0 return Float64(factorial2(big(2m - 1)) / (2^(m + 1) * factorial(big(m - 1)))) elseif n > 0 && m === 1 return Float64(-((2 * n^2 - 1) * (n^2 - 1)) / (8 * (4 * n^2 - 1)) - Int(n === 1) / 24) elseif n > 0 && m > 0 return Float64(-((2n * (m + n - 1) - m) * (n + 1) * (2m + 2n - 1)) / ((m + 2n - 2) * (m + 2n - 1) * (m + 2n) * (2n + 1)) * γ(m, n)) else throw(ErrorException("Invalid n and m")) end end function factorial2(n::I)::I where {I<:Signed} # Defined in 2 appendix A @assert n <= 21 || n isa BigInt # not sure what number is the limit but this should do it... if n <= 0 return I(1) else return n * factorial2(n - 2) end end function f(m::Int, n::Int, force::Bool = false)::Float64 # 2 eq A.18b @assert m > 0 if m <= QTYPE_PRECOMP && n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_f[m, n + 1] else if n === 0 return sqrt(F(m, 0)) else return sqrt(F(m, n) - g(m, n - 1, force)^2) end end end function g(m::Int, n::Int, force::Bool = false)::Float64 # 2 eq A.18a @assert m > 0 if m <= QTYPE_PRECOMP && n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_g[m, n + 1] else return G(m, n) / f(m, n, force) end end @inline function A(m::Int, n::Int, force::Bool = false)::Float64 # 2 eq A.3a @assert m > 0 if m <= QTYPE_PRECOMP && n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_A[m, n + 1] else if m === 1 && n === 0 return 2.0 elseif m === 1 && n === 1 return -4.0 / 3.0 elseif n === 0 && m > 1 return 2m - 1.0 else return (2n - 1) * (m + 2n - 2) * (4n * (m + n - 2) + (m - 3) * (2m - 1)) / D(m, n) end end end @inline function B(m::Int, n::Int, force::Bool = false)::Float64 # 2 eq A.3b @assert m > 0 if m <= QTYPE_PRECOMP && n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_B[m, n + 1] else if n === 1 && m === 1 return -8.0 / 3.0 elseif n === 0 if m === 1 return -1.0 else return 2.0 * (1.0 - m) end else return -2.0 * (2n - 1) * (m + 2n - 3) * (m + 2n - 2) * (m + 2n - 1) / D(m, n) end end end @inline function C(m::Int, n::Int, force::Bool = false)::Float64 # 2 eq A.3c @assert m > 0 if n === 0 return NaN elseif m <= QTYPE_PRECOMP && n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_C[m, n + 1] else if m === 1 && n === 1 return -11.0 / 3.0 elseif m === 1 && n === 2 return 0.0 else return n * (2n - 3) * (m + 2n - 1) * (2m + 2n - 3) / D(m, n) end end end @inline function D(m::Int, n::Int)::Float64 # 2 eq A.3d @assert m > 0 return Float64((4n^2 - 1) * (m + n - 2) * (m + 2n - 3)) end const PRECOMP_g = Matrix{Float64}(reshape(collect(g(m, n, true) for n in 0:(QTYPE_PRECOMP - 1) for m in 1:QTYPE_PRECOMP), (QTYPE_PRECOMP, QTYPE_PRECOMP))) const PRECOMP_f = Matrix{Float64}(reshape(collect(f(m, n, true) for n in 0:(QTYPE_PRECOMP - 1) for m in 1:QTYPE_PRECOMP), (QTYPE_PRECOMP, QTYPE_PRECOMP))) const PRECOMP_A = Matrix{Float64}(reshape(collect(A(m, n, true) for n in 0:(QTYPE_PRECOMP - 1) for m in 1:QTYPE_PRECOMP), (QTYPE_PRECOMP, QTYPE_PRECOMP))) const PRECOMP_B = Matrix{Float64}(reshape(collect(B(m, n, true) for n in 0:(QTYPE_PRECOMP - 1) for m in 1:QTYPE_PRECOMP), (QTYPE_PRECOMP, QTYPE_PRECOMP))) const PRECOMP_C = Matrix{Float64}(reshape(collect(C(m, n, true) for n in 0:(QTYPE_PRECOMP - 1) for m in 1:QTYPE_PRECOMP), (QTYPE_PRECOMP, QTYPE_PRECOMP))) """ S(coeffs::SVector{NP1,T}, m::Int x::T) -> T Evaluates ``\\sum_{n=0}^{N}c_n^mQ_n^m(x)`` where ``c_n^m`` is either an ``\\alpha`` or ``\\beta`` QType coefficient and ``m \\gt 0``. """ function S(coeffs::SVector{NP1,T}, m::Int, x::T)::T where {T<:Real,NP1} @assert m > 0 if all(iszero.(coeffs)) return zero(T) end N = NP1 - 1 # offset for indexing if N === 0 return coeffs[1] end αₙ₊₂ = zero(T) αₙ₊₁ = zero(T) αₙ = zero(T) @inbounds for n in N:-1:0 # 2 eq B.6 αₙ = coeffs[n + 1] + (A(m, n) + B(m, n) * x) * αₙ₊₁ - C(m, n + 1) * αₙ₊₂ if n > 0 αₙ₊₂ = αₙ₊₁ αₙ₊₁ = αₙ end end # 2 eq B.9 if m === 1 && N > 2 return αₙ / 2 - 2 / 5 * αₙ₊₂ else return αₙ / 2 end end """ dSdx(coeffs::SVector{NP1,T}, x::T) -> T Evaluates ``\\frac{\\partial}{\\partial x}\\sum_{n=0}^{N}c_n^mQ_n^m(x)`` where ``c_n^m`` is either an ``\\alpha`` or ``\\beta`` QType coefficient and ``m \\gt 0``. """ function dSdx(coeffs::SVector{NP1,T}, m::Int, x::T)::T where {T<:Real,NP1} @assert m > 0 if all(iszero.(coeffs)) return zero(T) end N = NP1 - 1 # offset for indexing if N === 0 return zero(T) end αₙ₊₂ = zero(T) αₙ₊₁ = zero(T) dαₙ₊₂ = zero(T) dαₙ₊₁ = zero(T) dαₙ = zero(T) @inbounds for n in N:-1:0 # calcualte deriv Bmn = B(m, n) k = (A(m, n) + Bmn * x) Cmnp1 = C(m, n + 1) if n < N # derivative calcualted from N-1 to 0, so ignore first iteration # 2 eq B.11 dαₙ = Bmn * αₙ₊₁ + k * dαₙ₊₁ - Cmnp1 * dαₙ₊₂ if n > 0 dαₙ₊₂ = dαₙ₊₁ dαₙ₊₁ = dαₙ end end # calculate height for use in next iter deriv # 2 eq B.6 αₙ = coeffs[n + 1] + k * αₙ₊₁ - Cmnp1 * αₙ₊₂ αₙ₊₂ = αₙ₊₁ αₙ₊₁ = αₙ end # 2 eq B.10 if m === 1 && N > 2 return dαₙ / 2 - 2 / 5 * dαₙ₊₂ else return dαₙ / 2 end end # for cases where m == 0 below: function f0(n::Int, force::Bool = false)::Float64 if n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_f0[n + 1] elseif n === 0 return 2.0 elseif n === 1 return sqrt(19) / 2 else # 1 eq A.16 return sqrt(n * (n + 1) + 3.0 - g0(n - 1, force)^2 - h0(n - 2, force)^2) end end function g0(n::Int, force::Bool = false)::Float64 if n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_g0[n + 1] elseif n === 0 return -0.5 else # 1 eq A.15 return -(1 + g0(n - 1, force) * h0(n - 1, force)) / f0(n, force) end end function h0(n::Int, force::Bool = false)::Float64 if n < QTYPE_PRECOMP && !force return @inbounds PRECOMP_h0[n + 1] else # 1 eq A.14 return -(n + 2) * (n + 1) / (2 * f0(n, force)) end end const PRECOMP_g0 = Vector{Float64}(collect(g0(n, true) for n in 0:(QTYPE_PRECOMP - 1))) const PRECOMP_f0 = Vector{Float64}(collect(f0(n, true) for n in 0:(QTYPE_PRECOMP - 1))) const PRECOMP_h0 = Vector{Float64}(collect(h0(n, true) for n in 0:(QTYPE_PRECOMP - 1))) """ S0(coeffs::SVector{NP1,T}, x::T) -> T Evaluates ``\\sum_{n=0}^{N}\\alpha_n^0Q_n^0(x)``. """ function S0(coeffs::SVector{NP1,T}, x::T)::T where {T<:Real,NP1} if all(iszero.(coeffs)) return zero(T) end N = NP1 - 1 # offset for indexing if N === 0 return coeffs[1] end k = T(2) - 4 * x # 1 eq 3.7a αₙ₊₂ = coeffs[N + 1] # 1 eq 3.7b αₙ₊₁ = coeffs[N] + k * αₙ₊₂ for n in (N - 2):-1:0 # 1 eq 3.8 αₙ = coeffs[n + 1] + k * αₙ₊₁ - αₙ₊₂ αₙ₊₂ = αₙ₊₁ αₙ₊₁ = αₙ end # 1 eq 3.9 return 2 * (αₙ₊₁ + αₙ₊₂) # a0 and a1 end """ dS0dx(coeffs::SVector{NP1,T}, x::T) -> T Evaluates ``\\frac{\\partial}{\\partial x}\\sum_{n=0}^{N}\\alpha_n^0Q_n^0(x)``. """ function dS0dx(coeffs::SVector{NP1,T}, x::T)::T where {T<:Real,NP1} if all(iszero.(coeffs)) return zero(T) end N = NP1 - 1 # offset for indexing if N == 0 return zero(T) end k = T(2) - 4 * x αₙ₊₂ = coeffs[N + 1] αₙ₊₁ = coeffs[N] + k * αₙ₊₂ # 1 eq 3.10a dαₙ₊₂ = zero(T) # 1 eq 3.10b dαₙ₊₁ = -4 * αₙ₊₂ for n in (N - 2):-1:0 # 1 eq 3.11 dαₙ = k * dαₙ₊₁ - dαₙ₊₂ - 4 * αₙ₊₁ dαₙ₊₂ = dαₙ₊₁ dαₙ₊₁ = dαₙ αₙ = coeffs[n + 1] + k * αₙ₊₁ - αₙ₊₂ αₙ₊₂ = αₙ₊₁ αₙ₊₁ = αₙ end # 1 eq 3.12 return 2 * (dαₙ₊₁ + dαₙ₊₂) # a0 and a1 end ######################################## # for testing, not used in actual calculation because there is a more efficient method to find the sum directly (as in S and S0) function P(m::Int, n::Int, x::T)::T where {T<:Real} if m === 0 if n === 0 return T(2) elseif n === 1 return T(6) - 8 * x else # 1 eq 2.6 return (T(2) - 4 * x) * P(0, n - 1, x) - P(0, n - 2, x) end else if n === 0 return one(T) / 2 elseif n === 1 if m === 1 # 2 eq A.5a return one(T) - x / 2 else # 2 eq A.5b return m - 1 / 2 - (m - 1) * x end else # 2 eq A.2 return (A(m, n - 1) + B(m, n - 1) * x) * P(m, n - 1, x) - C(m, n - 1) * P(m, n - 2, x) end end end function Q(m::Int, n::Int, x::T)::T where {T<:Real} if m === 0 if n === 0 return one(T) elseif n === 1 return (T(13) - 16x) / sqrt(19) else # 1 eq 2.7 return (P(0, n, x) - g0(n - 1) * Q(0, n - 1, x) - h0(n - 2) * Q(0, n - 2, x)) / f0(n) end else if n === 0 return 1 / (2 * f(m, 0)) else # 2 eq A.22 return (P(m, n, x) - g(m, n - 1) * Q(m, n - 1, x)) / f(m, n) end end end function plot!(m::Int, n::Int) @assert m >= 0 && n >= 0 us = 0:0.01:1 vs = [] for u in us if m === 0 push!(vs, u^2 * (1 - u^2) * Q(m, n, u^2)) else push!(vs, u^m * Q(m, n, u^2)) end end Plots.plot!(us, vs, label = m === 0 ? "\$u^2(1-u^2)Q^{$m}_{$n}(u^2)\$" : "\$u^mQ^{$m}_{$n}(u^2)\$") end end # module QType ######################################################################################################### """ QTypeSurface{T,D,M,N} <: ParametricSurface{T,D} Surface incorporating the QType polynomials - radius and conic are defined relative to absolute semi-diameter, QType terms are normalized according to the `normradius` parameter. `T` is the datatype, `D` is the dimensionality, `M` and `N` are the maximum QType terms used. The surface is centered at the origin and treated as being the cap of an infinite cylinder, thus creating a true half-space. Outside of 0 <= ρ <= 1 the height of the surface is not necessarily well defined, so NaN may be returned. ```julia QTypeSurface(semidiameter; radius = Inf, conic = 0.0, αcoeffs = nothing, βcoeffs = nothing, normradius = semidiameter) ``` `αcoeffs` and `βcoeffs` should be a vector of tuples of the form `(m, n, v)` where `v` is the value of the coefficient ``α_n^m`` or ``β_n^m`` respectively. The sag is defined by the equation ```math \\begin{aligned} z(r,\\phi) = & \\frac{cr^2}{1 + \\sqrt{1 - (1+k)c^2r^2}} + \\frac{\\sqrt{1 + kc^2r^2}}{\\sqrt{1-(1+k)c^2r^2}} \\cdot \\\\ & \\left\\{ \\rho^2(1-\\rho^2)\\sum_{n=0}^{N}\\alpha_n^0 Q_n^0 (\\rho^2) + \\sum_{m=1}^{M}\\rho^m\\sum_{n=0}^N \\left[ \\alpha_n^m\\cos{m\\phi} +\\beta_n^m\\sin{m\\phi}\\right]Q_n^m(\\rho^2) \\right\\} \\end{aligned} ``` where ``\\rho = \\frac{r}{\\texttt{normradius}}``, ``c = \\frac{1}{\\texttt{radius}}``, ``k = \\texttt{conic}`` and ``Q_n^m`` is the QType polynomial index ``m``, ``n``. """ struct QTypeSurface{T,D,M,N} <: ParametricSurface{T,D} semidiameter::T curvature::T conic::T boundingcylinder::Cylinder{T,D} b0coeffs::SVector{N,T} dαcoeffs::SVector{M,SVector{N,T}} # m goes from 1:M while n goes from 0:N-1 dβcoeffs::SVector{M,SVector{N,T}} normradius::T maxheight::T function QTypeSurface(semidiameter::T; radius::T = typemax(T), conic::T = zero(T), αcoeffs::Union{Nothing,Vector{Tuple{Int,Int,T}}} = nothing, βcoeffs::Union{Nothing,Vector{Tuple{Int,Int,T}}} = nothing, normradius::T = semidiameter) where {T<:Real} @assert !isnan(semidiameter) && !isnan(radius) && !isnan(conic) @assert semidiameter > zero(T) @assert one(T) - (1 / radius)^2 * (conic + one(T)) * semidiameter^2 > 0 "Invalid surface (conic/radius combination: $radius, $conic)" # work out maximum coefficient value N = -1 M = 0 if αcoeffs !== nothing αcoeffs = αcoeffs::Vector{Tuple{Int,Int,T}} for α in αcoeffs m, n, v = α if n > N N = n end if m > M M = m end end end if βcoeffs !== nothing βcoeffs = βcoeffs::Vector{Tuple{Int,Int,T}} for β in βcoeffs m, n, v = β if n > N N = n end if m > M M = m end end end # process the inputs to get parameter matrices α0coeffs = zeros(MVector{N + 1,T}) αcoeffsproc = zeros(MMatrix{M,N + 1,T}) βcoeffsproc = zeros(MMatrix{M,N + 1,T}) if αcoeffs !== nothing for α in αcoeffs m, n, v = α @assert m >= 0 && n >= 0 if m == 0 α0coeffs[n + 1] = v else αcoeffsproc[m, n + 1] = v end end end if βcoeffs !== nothing for β in βcoeffs m, n, v = β @assert m >= 0 && n >= 0 βcoeffsproc[m, n + 1] = v end end # calculate the α term coefficients for m = 0 b0coeffs = zeros(MVector{N + 1,T}) if N >= 0 # 1 eq 3.4a bₙp2 = α0coeffs[N + 1] / QType.f0(N) b0coeffs[N + 1] = bₙp2 if N > 0 #1 eq 3.4b bₙp1 = (α0coeffs[N] - QType.g0(N - 1) * bₙp2) / QType.f0(N - 1) b0coeffs[N] = bₙp1 if N > 1 for n in (N - 2):-1:0 # 1 eq 3.5 bₙ = (α0coeffs[n + 1] - QType.g0(n) * bₙp1 - QType.h0(n) * bₙp2) / QType.f0(n) b0coeffs[n + 1] = bₙ bₙp2 = bₙp1 bₙp1 = bₙ end end end end # m==0 max value is <0.4 for any n, otherwise max is 1 for any m and n, for simplicity just sum everything though it may not be the tightest maxheight = zero(T) maxheight += 0.4 * sum(abs.(α0coeffs)) maxheight += 0.4 * sum(abs.(b0coeffs)) @inbounds @simd for m in 1:M maxheight += sum(abs.(αcoeffsproc[m, :])) maxheight += sum(abs.(βcoeffsproc[m, :])) end # calculate the α and β term coefficients dαcoeffs = zeros(MVector{M,SVector{N + 1,T}}) dβcoeffs = zeros(MVector{M,SVector{N + 1,T}}) for m in 1:M thisα = zeros(MVector{N + 1,T}) thisβ = zeros(MVector{N + 1,T}) if N >= 0 fmN = QType.f(m, N) lastdαₙ = αcoeffsproc[m, N + 1] / fmN thisα[N + 1] = lastdαₙ lastdβₙ = βcoeffsproc[m, N + 1] / fmN thisβ[N + 1] = lastdβₙ for n in (N - 1):-1:0 gmn = QType.g(m, n) fmn = QType.f(m, n) # 2 eq B.4 dαₙ = (αcoeffsproc[m, n + 1] - gmn * lastdαₙ) / fmn dβₙ = (βcoeffsproc[m, n + 1] - gmn * lastdβₙ) / fmn lastdαₙ = dαₙ lastdβₙ = dβₙ thisα[n + 1] = dαₙ thisβ[n + 1] = dβₙ end end dαcoeffs[m] = SVector{N + 1,T}(thisα) dβcoeffs[m] = SVector{N + 1,T}(thisβ) end NP1 = N + 1 new{T,3,M,NP1}(semidiameter, 1 / radius, conic, Cylinder(semidiameter, interface = opaqueinterface(T)), SVector{NP1,T}(b0coeffs), SVector{M,SVector{NP1,T}}(dαcoeffs), SVector{M,SVector{NP1,T}}(dβcoeffs), normradius, maxheight) # TODO!! incorrect interface on cylinder end end export QTypeSurface uvrange(::Type{QTypeSurface{T,D,M,N}}) where {T<:Real,D,M,N} = ((zero(T), one(T)), (-T(π), T(π))) # ρ and θ semidiameter(z::QTypeSurface{T}) where {T<:Real} = z.semidiameter function point(z::QTypeSurface{T,3,M,N}, ρ::T, θ::T)::SVector{3,T} where {T<:Real,M,N} rad = z.semidiameter r = ρ * rad # ρ is normalised [0, 1] # r is absolute r2 = r^2 ρ2 = ρ^2 c2 = z.curvature^2 q = (one(T) + z.conic) * c2 * r2 if q > one(T) return SVector{3,T}(NaN, NaN, NaN) end sqrtq = sqrt(one(T) - q) h = z.curvature * r2 / (one(T) + sqrtq) if N > 0 # 2 eq B.1 p = one(T) + z.conic * c2 * r2 if p < zero(T) return SVector{3,T}(NaN, NaN, NaN) end u = ρ * rad / z.normradius u2 = u^2 tot = u2 * (one(T) - u2) * QType.S0(z.b0coeffs, u2) @inbounds @simd for m in 1:M tot += u^m * (cos(m * θ) * QType.S(z.dαcoeffs[m], m, u2)::T + sin(m * θ) * QType.S(z.dβcoeffs[m], m, u2)::T) end h += (sqrt(p) / sqrtq) * tot end return SVector{3,T}(r * cos(θ), r * sin(θ), h) end function partials(z::QTypeSurface{T,3,M,N}, ρ::T, θ::T)::Tuple{SVector{3,T},SVector{3,T}} where {T<:Real,M,N} rad = z.semidiameter r = ρ * rad # ρ is normalised [0, 1] # r is absolute r2 = r^2 ρ2 = ρ^2 k = z.conic c = z.curvature c2 = c^2 q = (one(T) + k) * c2 * r2 if q > one(T) return SVector{3,T}(NaN, NaN, NaN), SVector{3,T}(NaN, NaN, NaN) end sqrtq = sqrt(one(T) - q) dhdρ = -((rad * c * r * sqrtq) / (q - one(T))) dhdθ = zero(T) if N > 0 p = one(T) + k * c2 * r2 if p < zero(T) return SVector{3,T}(NaN, NaN, NaN), SVector{3,T}(NaN, NaN, NaN) end sqrtp = sqrt(p) a = sqrtp / sqrtq dadρ = (c2 * (2k + one(T)) * rad * r) / (sqrtp * sqrtq^3) n = rad / z.normradius u = ρ * n u2 = u^2 S0v = QType.S0(z.b0coeffs, u2)::T b = u2 * (one(T) - u2) * S0v dbdu = 2 * u * (one(T) - 2 * u2) * S0v + 2 * u^3 * (one(T) - u2) * QType.dS0dx(z.b0coeffs, u2)::T c = zero(T) dcdu = zero(T) if M > 0 @inbounds @simd for m in 1:M Sα = QType.S(z.dαcoeffs[m], m, u2)::T Sβ = QType.S(z.dβcoeffs[m], m, u2)::T sinmθ = sin(m * θ) cosmθ = cos(m * θ) dhdθ += u^m * m * (-sinmθ * Sα + cosmθ * Sβ) c += u^m * (cosmθ * Sα + sinmθ * Sβ) dcdu += u^(m - 1) * (m * (cosmθ * Sα + sinmθ * Sβ) + 2 * u2 * (cosmθ * QType.dSdx(z.dαcoeffs[m], m, u2)::T + sinmθ * QType.dSdx(z.dβcoeffs[m], m, u2)::T)) end end dhdθ *= a dhdρ += dadρ * (b + c) + a * n * (dbdu + dcdu) # want the derivative wrt ρ, not u end cosθ = cos(θ) sinθ = sin(θ) pu = SVector{3,T}(rad * cosθ, rad * sinθ, dhdρ) pv = SVector{3,T}(r * -sinθ, r * cosθ, dhdθ) return pu, pv end function normal(z::QTypeSurface{T,D,M,N}, ρ::T, θ::T)::SVector{3,T} where {T<:Real,D,M,N} du, dv = partials(z, ρ, θ) if ρ == zero(T) && norm(dv) == zero(T) # in cases where there is no δθ at ρ = 0 (i.e. anything which is rotationally symetric) # then we get some big problems, hardcoding this case solves the problems return SVector{3,T}(0, 0, 1) end return normalize(cross(du, dv)) end function uv(z::QTypeSurface{T,3,M,N}, p::SVector{3,T})::SVector{2,T} where {T<:Real,M,N} # avoid divide by zero for ForwardDiff ϕ = NaNsafeatan(p[2], p[1]) if p[1] == zero(T) && p[2] == zero(T) ρ = zero(T) else ρ = sqrt(p[1]^2 + p[2]^2) / semidiameter(z) end return SVector{2,T}(ρ, ϕ) end function onsurface(surf::QTypeSurface{T,3,M,N}, p::SVector{3,T}) where {T<:Real,M,N} ρ, θ = uv(surf, p) if ρ > one(T) return false else surfpoint = point(surf, ρ, θ) return samepoint(p[3], surfpoint[3]) end end function inside(surf::QTypeSurface{T,3,M,N}, p::SVector{3,T}) where {T<:Real,M,N} ρ, θ = uv(surf, p) if ρ > one(T) return false else surfpoint = point(surf, ρ, θ) return p[3] < surfpoint[3] end end ######################################################################################################### # Assumes the ray has been transformed into the canonical coordinate frame which has the vertical axis passing through (0,0,0) and aligned with the z axis. function surfaceintersection(surf::AcceleratedParametricSurface{T,3,QTypeSurface{T,3,M,N}}, r::AbstractRay{T,3}) where {T<:Real,M,N} cylint = surfaceintersection(surf.surface.boundingcylinder, r) if cylint isa EmptyInterval{T} return EmptyInterval(T) else if doesintersect(surf.triangles_bbox, r) || inside(surf.triangles_bbox, origin(r)) surfint = triangulatedintersection(surf, r) if !(surfint isa EmptyInterval{T}) return intervalintersection(cylint, surfint) end end # hasn't hit the surface if lower(cylint) isa RayOrigin{T} && upper(cylint) isa Infinity{T} if inside(surf.surface, origin(r)) return Interval(RayOrigin(T), Infinity(T)) else return EmptyInterval(T) end # otherwise check that the intersection is underneath the surface else p = point(closestintersection(cylint, false)) ρ, ϕ = uv(surf, p) surfpoint = point(surf.surface, ρ, ϕ) if p[3] < surfpoint[3] return cylint # TODO!! UV (and interface) issues? else return EmptyInterval(T) end end end end function AcceleratedParametricSurface(surf::S, numsamples::Int = 17; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real,N,S<:QTypeSurface{T,N}} # Zernike users ρ, ϕ uv space so need to modify extension of triangulation a = AcceleratedParametricSurface(surf, triangulate(surf, numsamples, true, false, true, false), interface = interface) emptytrianglepool!(T) return a end function BoundingBox(surf::QTypeSurface{T,3}) where {T<:Real} xmin = -semidiameter(surf) xmax = semidiameter(surf) ymin = -semidiameter(surf) ymax = semidiameter(surf) # curvature only goes one way q = one(T) - (one(T) + surf.conic) * surf.curvature^2 * surf.semidiameter^2 if q < zero(T) throw(ErrorException("The surface is invalid, no bounding box can be constructed")) end hmax = surf.curvature * surf.semidiameter^2 / (one(T) + sqrt(q)) if hmax > zero(T) zmax = hmax + surf.maxheight zmin = -surf.maxheight else zmax = surf.maxheight zmin = hmax - surf.maxheight end return BoundingBox(xmin, xmax, ymin, ymax, zmin, zmax) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
3668
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Sphere{T,N} <: ParametricSurface{T,N} Spherical surface centered at the origin. ```julia Sphere(radius::T = 1.0; interface::NullOrFresnel{T} = nullinterface(T)) ``` """ struct Sphere{T,N} <: ParametricSurface{T,N} radius::T interface::NullOrFresnel{T} function Sphere(radius::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert !isnan(radius) @assert radius > zero(T) return new{T,3}(radius, interface) end end export Sphere interface(a::Sphere{T,N}) where {T<:Real,N} = a.interface radius(a::Sphere{T}) where {T<:Real} = a.radius uvrange(::Type{Sphere{T,N}}) where {T<:Real,N} = ((-T(π), T(π)), (zero(T), T(π))) onsurface(sph::Sphere{T,3}, x::T, y::T, z::T) where {T<:Real} = samepoint(x^2 + y^2 + z^2, radius(sph)^2) inside(sph::Sphere{T,3}, x::T, y::T, z::T) where {T<:Real} = x^2 + y^2 + z^2 - radius(sph)^2 < zero(T) point(sph::Sphere{T,3}, ϕ::T, θ::T) where {T<:Real} = SVector{3,T}(radius(sph) * sin(θ) * cos(-ϕ), radius(sph) * sin(θ) * sin(-ϕ), radius(sph) * cos(θ)) normal(::Sphere{T,3}, ϕ::T, θ::T) where {T<:Real} = SVector{3,T}(sin(θ) * cos(-ϕ), sin(θ) * sin(-ϕ), cos(θ)) partials(sph::Sphere{T,3}, ϕ::T, θ::T) where {T<:Real} = SVector{3,T}(radius(sph) * sin(θ) * -sin(-ϕ), radius(sph) * sin(θ) * cos(-ϕ), 0.0), SVector{3,T}(radius(sph) * cos(θ) * cos(-ϕ), radius(sph) * cos(θ) * sin(-ϕ), radius(sph) * -sin(θ)) function uv(::Sphere{T,3}, x::T, y::T, z::T) where {T<:Real} # avoid divide by zero for ForwardDiff ϕ = -NaNsafeatan(y, x) if x == zero(T) && y == zero(T) θ = zero(T) else θ = NaNsafeatan(sqrt(x^2 + y^2), z) end return SVector{2,T}(ϕ, θ) end # Assumes the ray has been transformed into the canonical sphere coordinate frame which has the vertical axis passing through (0,0,0) and aligned with the z axis. function surfaceintersection(sph::Sphere{T,N}, r::AbstractRay{T,N}) where {T<:Real,N} ox, oy, oz = origin(r) dx, dy, dz = direction(r) rad = radius(sph) a = dx^2 + dy^2 + dz^2 b = 2 * (ox * dx + oy * dy + oz * dz) c = (ox^2 + oy^2 + oz^2) - rad^2 temp = quadraticroots(a, b, c) if temp === nothing return EmptyInterval(T) # no intersection with sphere and ray not contained entirely in sphere end t1, t2 = temp if isapprox(t1, t2, rtol = 1e-12, atol = 2 * eps(T)) return EmptyInterval(T) # single root which indicates a tangent ray sphere intersection end if t1 > zero(T) pt1 = point(r, t1) else pt1 = nothing end if t2 > zero(T) pt2 = point(r, t2) else pt2 = nothing end let int1 = nothing, int2 = nothing if pt1 !== nothing θ, ρ = uv(sph, pt1) int1 = Intersection(t1, pt1, pt1, θ, ρ, interface(sph)) end if pt2 !== nothing θ, ρ = uv(sph, pt2) int2 = Intersection(t2, pt2, pt2, θ, ρ, interface(sph)) end if int1 !== nothing && int2 !== nothing if t1 <= t2 return Interval(int1, int2) else return Interval(int2, int1) end elseif int1 !== nothing return rayorigininterval(int1) elseif int2 !== nothing return rayorigininterval(int2) else return EmptyInterval(T) end end end BoundingBox(sph::Sphere{T,3}) where {T<:Real} = BoundingBox(-radius(sph), radius(sph), -radius(sph), radius(sph), -radius(sph), radius(sph))
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
6825
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ SphericalCap{T} <: ParametricSurface{T} Spherical cap surface, creates a half-space which is essentially the subtraction of a sphere from an infinite plane. Only the spherical cap itself is visualized, not the plane. The positive normal side is outside the surface. **Can be used as a detector in [`AbstractOpticalSystem`](@ref)s.** ```julia SphericalCap(radius::T, ϕmax::T, [surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}]; interface::NullOrFresnel{T} = nullinterface(T)) ``` The minimal case returns a spherical cap centered at the origin with `surfacenormal = [0, 0, 1]`. """ struct SphericalCap{T} <: ParametricSurface{T,3} radius::T ϕmax::T zmax::T centrenormal::SVector{3,T} centrepoint::SVector{3,T} interface::NullOrFresnel{T} uvec::SVector{3,T} vvec::SVector{3,T} function SphericalCap(radius::T, ϕmax::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert !isnan(radius) @assert radius > zero(T) && zero(T) < ϕmax < T(π) zmax = radius * (one(T) + sin(-(π / 2 - ϕmax))) new{T}(radius, ϕmax, zmax, SVector{3,T}(0.0, 0.0, 1.0), SVector{3,T}(0.0, 0.0, 0.0), interface, SVector{3,T}(1.0, 0.0, 0.0), SVector{3,T}(0.0, 1.0, 0.0)) end function SphericalCap(radius::T, ϕmax::T, centrenormal::SVector{3,T}, centrepoint::SVector{3,T}; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert radius > zero(T) && zero(T) < ϕmax < T(π) n̂ = normalize(centrenormal) rotationvec = SVector{3,T}(0.0, 1.0, 0.0) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) zmax = radius * (one(T) + sin(-(π / 2 - ϕmax))) new{T}(radius, ϕmax, zmax, n̂, centrepoint, interface, uvec, vvec) end end export SphericalCap Base.show(io::IO, a::SphericalCap{T}) where {T<:Real} = print(io, "SphericalCap{$T}($(a.radius), $(a.centrepoint), $(a.centrenormal), $(a.ϕmax), $(interface(a)))") interface(a::SphericalCap{T}) where {T<:Real} = a.interface radius(a::SphericalCap{T}) where {T<:Real} = a.radius centroid(r::SphericalCap{T}) where {T<:Real} = r.centrepoint uvrange(::Type{SphericalCap{T}}) where {T<:Real} = ((-T(π), T(π)), (zero(T), one(T))) # θ and ρ function normal(r::SphericalCap{T}, θ::T, ρ::T) where {T<:Real} ϕ = π / 2 - ρ * r.ϕmax return -normalize(cos(-ϕ) * (cos(-θ) * r.uvec + sin(-θ) * r.vvec) + sin(-ϕ) * r.centrenormal) end function point(r::SphericalCap{T}, θ::T, ρ::T) where {T<:Real} ϕ = π / 2 - ρ * r.ϕmax return centroid(r) + radius(r) * (cos(-ϕ) * (cos(-θ) * r.uvec + sin(-θ) * r.vvec) + sin(-ϕ) * r.centrenormal + r.centrenormal) end uv(r::SphericalCap{T}, x::T, y::T, z::T) where {T<:Real} = uv(r, SVector{3,T}(x, y, z)) function uv(r::SphericalCap{T}, p::SVector{3,T}) where {T<:Real} prel = p - centroid(r) - radius(r) * r.centrenormal v = dot(prel, r.vvec) / radius(r) u = dot(prel, r.uvec) / radius(r) θ = -NaNsafeatan(v, u) z = clamp(dot(prel, -r.centrenormal) / radius(r), -one(T), one(T)) ϕ = NaNsafeasin(z) ρ = (π / 2 - ϕ) / r.ϕmax return θ, ρ end function inside(r::SphericalCap{T}, p::SVector{3,T}) where {T<:Real} prel = (p - centroid(r) - radius(r) * r.centrenormal) / radius(r) v = dot(prel, r.vvec) u = dot(prel, r.uvec) if (u == zero(T) && v == zero(T)) || sqrt(u^2 + v^2) < sin(r.ϕmax) l = norm(prel) if l < one(T) return false end end return dot(r.centrenormal, p - centroid(r)) < r.zmax end function onsurface(r::SphericalCap{T}, p::SVector{3,T}) where {T<:Real} prel = (p - centroid(r) - radius(r) * r.centrenormal) / radius(r) v = dot(prel, r.vvec) u = dot(prel, r.uvec) if (u == zero(T) && v == zero(T)) || sqrt(u^2 + v^2) < sin(r.ϕmax) return norm(prel) == one(T) && dot(r.centrenormal, p - centroid(r)) < r.zmax else false end end function uvtopix(::SphericalCap{T}, uv::SVector{2,T}, imsize::Tuple{Int,Int}) where {T<:Real} θ, ρ = uv h, w = imsize u = (cos(θ) * ρ + one(T)) / 2 v = (sin(θ) * ρ + one(T)) / 2 pixu = Int(floor((w - 1) * u)) + 1 pixv = Int(floor((h - 1) * v)) + 1 return pixu, pixv end function surfaceintersection(sph::SphericalCap{T}, r::AbstractRay{T,3}) where {T<:Real} rad = radius(sph) orel = origin(r) - centroid(sph) - rad * sph.centrenormal ox, oy, oz = orel dx, dy, dz = direction(r) a = dx^2 + dy^2 + dz^2 b = 2 * (ox * dx + oy * dy + oz * dz) c = (ox^2 + oy^2 + oz^2) - rad^2 temp = quadraticroots(a, b, c) if temp === nothing if inside(sph, origin(r)) return rayorigininterval(Infinity(T)) else return EmptyInterval(T) end end t1, t2 = temp if isapprox(t1, t2, rtol = 1e-12, atol = 2 * eps(T)) if inside(sph, origin(r)) return rayorigininterval(Infinity(T)) else return EmptyInterval(T) end end if t1 > zero(T) pt1 = point(r, t1) else pt1 = nothing end if t2 > zero(T) pt2 = point(r, t2) else pt2 = nothing end let int1 = nothing, int2 = nothing if pt1 !== nothing θ, ρ = uv(sph, pt1) if zero(T) <= ρ <= one(T) int1 = Intersection(t1, pt1, normal(sph, θ, ρ), θ, ρ, interface(sph)) end end if pt2 !== nothing θ, ρ = uv(sph, pt2) if zero(T) <= ρ <= one(T) int2 = Intersection(t2, pt2, normal(sph, θ, ρ), θ, ρ, interface(sph)) end end if int1 !== nothing && int2 !== nothing if t1 <= t2 return Interval(int1, int2) else return Interval(int2, int1) end elseif int1 !== nothing if inside(sph, origin(r)) return rayorigininterval(int1) else return positivehalfspace(int1) end elseif int2 !== nothing if inside(sph, origin(r)) return rayorigininterval(int2) else return positivehalfspace(int2) end else if inside(sph, origin(r)) return rayorigininterval(Infinity(T)) else return EmptyInterval(T) end end end end BoundingBox(a::SphericalCap{T}) where {T<:Real} = BoundingBox(Plane(a.centrenormal, a.centrepoint + a.radius * a.centrenormal))
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
11352
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Module to enclose [Zernike polynomial](https://en.wikipedia.org/wiki/Zernike_polynomials) specific functionality. """ module Zernike """ OSAtoNM(j::Int) -> Tuple{Int, Int} Convert OSA zernike index `j` to `(N,M)` form according to formula `J = N * (N + 2) + M`. """ function OSAtoNM(j::Int)::Tuple{Int,Int} n = Int(ceil((-3 + sqrt(9 + 8j)) / 2)) m = 2j - n * (n + 2) return (Int(n), Int(m)) end """ NolltoNM(j::Int) -> Tuple{Int, Int} Convert Noll zernike index `j` to `(N,M)` form. """ function NolltoNM(j::Int) n = Int(ceil((-3 + sqrt(1 + 8j)) / 2)) jr = j - Int(n * (n + 1) / 2) if mod(n, 4) ∈ (0, 1) m1 = jr m2 = -(jr - 1) if iseven(n - m1) m = m1 else m = m2 end else # mod(n,4) ∈ (2,3) m1 = jr - 1 m2 = -(jr) if iseven(n - m1) m = m1 else m = m2 end end return (Int(n), Int(m)) end """ normalisation(::Type{T}, N::Int, M::Int) -> T Normalisation coefficient for Zernike polynomial term ``Z_{n}^{m}``. """ @inline normalisation(::Type{T}, N::Int, M::Int) where {T<:Real} = T(sqrt((2 * (N + 1)) / (1 + (M == 0 ? 1 : 0)))) """ ζ(N::Int, M::Int, ρ::T, ϕ::T) -> Tuple{T,T} Evaluate Zernike polynomial term ``Z_{n}^{m}(\\rho, \\phi)``. """ @inline function ζ(N::Int, M::Int, ρ::T, ϕ::T)::T where {T<:Real} aM = abs(M) if M < 0 return normalisation(T, N, M) * R(N, aM, ρ) * sin(aM * ϕ) else return normalisation(T, N, M) * R(N, aM, ρ) * cos(aM * ϕ) end end """ δζ(N::Int, M::Int, ρ::T, ϕ::T) -> Tuple{T,T} Evaluate partial derivatives of Zernike polynomial term ``Z_{n}^{m}(\\rho, \\phi)``. """ @inline function δζ(N::Int, M::Int, ρ::T, ϕ::T)::Tuple{T,T} where {T<:Real} n = normalisation(T, N, M) aM = abs(M) RNM = R(N, aM, ρ) ρ2 = ρ^2 δRNM = ((2 * N * aM * (ρ2 - 1) + (N - aM) * (aM + N * (2 * ρ2 - 1))) * RNM - (N + aM) * (N - aM) * R(N - 2, aM, ρ)) / (2 * N * ρ * (ρ2 - 1)) Mϕ = aM * ϕ if M < 0 δρ = n * δRNM * sin(Mϕ) δϕ = n * RNM * aM * cos(Mϕ) else δρ = n * δRNM * cos(Mϕ) δϕ = n * RNM * aM * -sin(Mϕ) end return δρ, δϕ end """ R(N::Int, M::Int, ρ::T) -> T Evaluate radial polynomial ``R_{n}^{m}(\\rho)``. """ @inline function R(N::Int, M::Int, ρ::T)::T where {T<:Real} if (N - M) % 2 === 1 return zero(T) end total = zero(T) @simd for k in 0:((N - M) ÷ 2) total += ((-1)^k * factorial(N - k)) / (factorial(k) * factorial((N + M) ÷ 2 - k) * factorial((N - M) ÷ 2 - k)) * ρ^(N - 2 * k) end return total end end # module Zernike ######################################################################################################### """ Either `ZernikeIndexingOSA` or `ZernikeIndexingNoll`, see [Zernike polynomials wikipedia entry](https://en.wikipedia.org/wiki/Zernike_polynomials) for details. """ @enum ZernikeIndexType ZernikeIndexingOSA ZernikeIndexingNoll export ZernikeIndexType, ZernikeIndexingOSA, ZernikeIndexingNoll """ ZernikeSurface{T,N,P,Q,M} <: ParametricSurface{T,N} Surface incorporating the Zernike polynomials - radius, conic and aspherics are defined relative to absolute semi-diameter, Zernike terms are normalized according to the `normradius` parameter. `T` is the datatype, `N` is the dimensionality, `P` is the number of Zernike terms, `Q` is the number of aspheric terms and `M` is the Aspheric Type. The surface is centered at the origin and treated as being the cap of an infinite cylinder, thus creating a true half-space. Outside of `0 <= ρ <= 1` the height of the surface is not necessarily well defined, so NaN may be returned. For convenience the input `zcoeff` can be indexed using either OSA or Noll convention, indicated using the `indexing` argument as either `ZernikeIndexingOSA` or `ZernikeIndexingNoll`. ```julia ZernikeSurface(semidiameter, radius = Inf, conic = 0, zcoeff = nothing, aspherics = nothing, normradius = semidiameter, indexing = ZernikeIndexingOSA) ``` `zcoeff` and `aspherics` should be vectors containing tuples of the form `(i, v)` where `i` is either the index of the Zernike term for the corresponding `indexing`, or the polynomial power of the aspheric term (may be even or odd) and `v` is the corresponding coefficient ``A_i`` or ``\\alpha_i`` respectively.. `M` will be determined from the terms entered to optimize the evaluation of the aspheric polynomial. The sag is defined by the equation ```math z(r,\\phi) = \\frac{cr^2}{1 + \\sqrt{1 - (1+k)c^2r^2}} + \\sum_{i}^{Q}\\alpha_ir^{2i} + \\sum_{i}^PA_iZ_i(\\rho, \\phi) ``` where ``\\rho = \\frac{r}{\\texttt{normradius}}``, ``c = \\frac{1}{\\texttt{radius}}``, ``k = \\texttt{conic}`` and ``Z_n`` is the nᵗʰ Zernike polynomial. """ struct ZernikeSurface{T,N,P,Q,M} <: ParametricSurface{T,N} asp::AsphericSurface{T,N,Q,M} coeffs::SVector{P,Tuple{Int,Int,T}} boundingcylinder::Cylinder{T,N} function ZernikeSurface(semidiameter::T; radius::T = typemax(T), conic::T = zero(T), zcoeff::Union{Nothing,Vector{Tuple{Int,T}}} = nothing, aspherics::Union{Nothing,Vector{Tuple{Int,T}}} = nothing, normradius::T = semidiameter, indexing::ZernikeIndexType = ZernikeIndexingOSA) where {T<:Real} asp = AsphericSurface(semidiameter; radius, conic, aspherics, normradius) Q = length(asp.aspherics) #this is not the same as the aspherics variable passed to the function! zcs = [] if zcoeff !== nothing for (i, k) in zcoeff if abs(k) > zero(T) if indexing === ZernikeIndexingOSA R, S = Zernike.OSAtoNM(i) else R, S = Zernike.NolltoNM(i) end push!(zcs, (R, S, k)) end end end P = length(zcs) M = asphericType(asp) new{T,3,P,Q,M}(asp::AsphericSurface{T,3,Q,M}, SVector{P,Tuple{Int,Int,T}}(zcs), Cylinder(semidiameter, interface = opaqueinterface(T))) # TODO!! incorrect interface on cylinder end end export ZernikeSurface uvrange(::Type{ZernikeSurface{T,N,P,Q,M}}) where {T<:Real,N,P,Q,M} = ((zero(T), one(T)), (-T(π), T(π))) # ρ and ϕ semidiameter(z::ZernikeSurface{T}) where {T<:Real} = z.asp.semidiameter halfsizeu(z::ZernikeSurface{T}) where {T<:Real} = semidiameter(z) halfsizev(z::ZernikeSurface{T}) where {T<:Real} = semidiameter(z) boundingobj(z::ZernikeSurface{T}) where {T<:Real} = z.boundingcylinder function point(z::ZernikeSurface{T,3,P,Q,M}, ρ::T, ϕ::T)::SVector{3,T} where {T<:Real,P,Q,M} pnt = point(z.asp, ρ, ϕ) # sum zernike rad = semidiameter(z.asp) r = ρ * rad u = r / z.asp.normradius h = zero(T) @inbounds @simd for m in 1:P (R, S, k) = z.coeffs[m] h += k * Zernike.ζ(R, S, u, ϕ) end return SVector{3,T}(pnt[1], pnt[2], pnt[3] + h) end function partials(z::ZernikeSurface{T,3,P,Q,M}, ρ::T, ϕ::T)::Tuple{SVector{3,T},SVector{3,T}} where {T<:Real,P,Q,M} pρ,pϕ = partials(z.asp, ρ, ϕ) # sum zernike partials rad=z.asp.semidiameter n = rad / z.asp.normradius u = ρ * n dhdρ = zero(T) dhdϕ = zero(T) @inbounds @simd for m in 1:P (R, S, k) = z.coeffs[m] du, dϕ = Zernike.δζ(R, S, u, ϕ) dhdρ += k * du * n # want the derivative wrt ρ, not u dhdϕ += k * dϕ end return SVector{3,T}(pρ[1], pρ[2], pρ[3] + dhdρ), SVector{3,T}(pϕ[1], pϕ[2], pϕ[3] + dhdϕ) end function normal(z::ZernikeSurface{T,3,P,Q,M}, ρ::T, ϕ::T)::SVector{3,T} where {T<:Real,P,Q,M} du, dv = partials(z, ρ, ϕ) if ρ == zero(T) && norm(dv) == zero(T) # in cases where there is no δϕ at ρ = 0 (i.e. anything which is rotationally symetric) # then we get some big problems, hardcoding this case solves the problems return SVector{3,T}(0, 0, 1) end return normalize(cross(du, dv)) end function uv(z::ZernikeSurface{T,3,P,Q,M}, p::SVector{3,T}) where {T<:Real,P,Q,M} # avoid divide by zero for ForwardDiff ϕ = NaNsafeatan(p[2], p[1]) if p[1] == zero(T) && p[2] == zero(T) ρ = zero(T) else ρ = sqrt(p[1]^2 + p[2]^2) / semidiameter(z) end return SVector{2,T}(ρ, ϕ) end function onsurface(surf::ZernikeSurface{T,3,P,Q,M}, p::SVector{3,T}) where {T<:Real,P,Q,M} ρ, ϕ = uv(surf, p) if ρ > one(T) return false else surfpoint = point(surf, ρ, ϕ) return samepoint(p[3], surfpoint[3]) end end function inside(surf::ZernikeSurface{T,3,P,Q,M}, p::SVector{3,T}) where {T<:Real,P,Q,M} ρ, ϕ = uv(surf, p) if ρ > one(T) return false else surfpoint = point(surf, ρ, ϕ) return p[3] < surfpoint[3] end end ######################################################################################################### # Assumes the ray has been transformed into the canonical coordinate frame which has the vertical axis passing through (0,0,0) and aligned with the z axis. function surfaceintersection(surf::AcceleratedParametricSurface{T,3,ZernikeSurface{T,3,P,Q,M}}, r::AbstractRay{T,3}) where {T<:Real,P,Q,M} cylint = surfaceintersection(surf.surface.boundingcylinder, r) if cylint isa EmptyInterval{T} return EmptyInterval(T) else if doesintersect(surf.triangles_bbox, r) || inside(surf.triangles_bbox, origin(r)) surfint = triangulatedintersection(surf, r) if !(surfint isa EmptyInterval{T}) return intervalintersection(cylint, surfint) end end # hasn't hit the surface if lower(cylint) isa RayOrigin{T} && upper(cylint) isa Infinity{T} if inside(surf.surface, origin(r)) return Interval(RayOrigin(T), Infinity(T)) else return EmptyInterval(T) end # otherwise check that the intersection is underneath the surface else p = point(closestintersection(cylint, false)) ρ, ϕ = uv(surf, p) surfpoint = point(surf.surface, ρ, ϕ) if p[3] < surfpoint[3] return cylint # TODO!! UV (and interface) issues? else return EmptyInterval(T) end end end end function AcceleratedParametricSurface(surf::T, numsamples::Int = 17; interface::NullOrFresnel{S} = NullInterface(S)) where {S<:Real,N,T<:ZernikeSurface{S,N}} # Zernike uses ρ, ϕ uv space so need to modify extension of triangulation a = AcceleratedParametricSurface(surf, triangulate(surf, numsamples, true, false, true, false), interface = interface) emptytrianglepool!(S) return a end function BoundingBox(surf::ZernikeSurface{T,3,P,Q,M}) where {T<:Real,P,Q,M} bb = BoundingBox(surf.asp) # zernike terms have condition than |Zᵢ| <= 1 # so this gives us a (loose) bounding box ak = P > 0 ? sum(abs.(Zernike.normalisation(T, n, m) * k for (n, m, k) in surf.coeffs)) : zero(T) bb.zmin -= ak bb.zmax += ak return BoundingBox(bb.xmin, bb.xmax, bb.ymin, bb.ymax, bb.zmin, bb.zmax) #could just return bb, but this way is safer end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
13466
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ BSplineCurve{P,S,N,M} <: Spline{P,S,N,M} `N` is the spatial dimension of the curve. `M` is the curve order, i.e., the highest power of the parameterizing variable, `u`. All curve segments are assumed to be of the same order. ```julia BSplineCurve{P,S,N,M}(knots::KnotVector{S}, controlpoints::AbstractArray{MVector{N,S},1}) ``` """ struct BSplineCurve{P,S,N,M} <: Spline{P,S,N,M} knotvector::KnotVector{S} controlpolygon::Array{MVector{N,S},1} # may have to allow different orders on different curve segments function BSplineCurve{P,S,N,M}(knots::KnotVector{S}, controlpoints::AbstractArray{MVector{N,S},1}) where {P,S,N,M} bsplineinvariant(numknots(knots), length(controlpoints), M) newpoints = [MVector{N,S}(point) for point in controlpoints] new{P,S,N,M}(knots, newpoints) end end export BSplineCurve numknots(curve::BSplineCurve) = numknots(curve.knotvector) function findspan(curve::BSplineCurve{T,S,N,M}, u) where {T,S,N,M} findspan(curve.knotvector, M, u) end function numspans(curve::BSplineCurve{T,S,N,M}) where {T,S,N,M} return numknots(curve) - M - 1 # number of spans = numknots - curveorder - 1 end spatialdimension(::Spline{T,S,N,M}) where {T,S,N,M} = N curveorder(::Spline{T,S,N,M}) where {T,S,N,M} = M function point(curve::BSplineCurve{P,S,N,M}, u::T)::SVector{N,S} where {T<:Real,P,S,N,M} # returns the raw point type of the curve - for Homogeneous curve types this will be a homogenous point span = findspan(curve, u) bases = basisfunctions(curve.knotvector, u, M) c = zeros(MVector{N,S}) for i in 1:(M + 1) pt = curve.controlpolygon[span - (M + 1) + i] c .= c .+ bases[i] .* pt end return SVector{N,S}(c) end function euclideanpoint(curve::BSplineCurve{Euclidean,S,N,M}, ::T)::SVector where {T<:Real,S,N,M} # might seem weird to have this function for Euclidean curves. But in user code can use euclidean point without worrying about whether curve is homogeneous and still get correct results. return point(curve) end function euclideanpoint(curve::BSplineCurve{Rational,S,N,M}, u::T)::SVector where {T<:Real,S,N,M} return toeuclidean(point(curve, u)) end """ BSplineSurface{P,S,N,M} <: SplineSurface{P,S,N,M} Curve order is the same in the u and v direction and fixed over all spans. u and v knot vectors are allowed to be different - _may change this to make them both the same_. Control points in the u direction correspond to columns, with the lowest value of u corresponding to row 1. Control points in the v direction correspond to rows, with the lowest value of v corresponding to col 1. !!! danger This surface does not create a valid half-space, requires updates to function correctly. ```julia BSplineSurface{P,S,N,M}(knots::KnotVector{S}, controlpoints::AbstractArray{<:AbstractArray{S,1},2}) BSplineSurface{P,S,N,M}(uknots::KnotVector{S}, vknots::KnotVector{S}, controlpoints::AbstractArray{<:AbstractArray{S,1},2}) ``` """ struct BSplineSurface{P,S,N,M} <: SplineSurface{P,S,N,M} uknotvector::KnotVector{S} vknotvector::KnotVector{S} controlpolygon::Array{MVector{N,S},2} # may have to allow different orders on different curve segments function BSplineSurface{P,S,N,M}(knots::KnotVector{S}, controlpoints::AbstractArray{<:AbstractArray{S,1},2}) where {P,S,N,M} return BSplineSurface(knots, knots, controlpoints) end function BSplineSurface{P,S,N,M}(uknots::KnotVector{S}, vknots::KnotVector{S}, controlpoints::AbstractArray{<:AbstractArray{S,1},2}) where {P,S,N,M} # m == n + M + 1 # relation between number of knots = m + 1, number of control points = n + 1, and curve order M n_u, n_v = size(controlpoints) bsplineinvariant(numknots(uknots), n_u, M) bsplineinvariant(numknots(vknots), n_v, M) newpoints = [MVector{N,S}(point) for point in controlpoints] new{P,S,N,M}(uknots, vknots, newpoints) end end export BSplineSurface numknots(surf::BSplineSurface) = (numknots(surf.uknotvector), numknots(surf.vknotvector)) uvrange(surface::BSplineSurface) = (urange(surface.uknotvector), urange(surface.vknotvector)) function findspan(surface::BSplineSurface{T,S,N,M}, u, v) where {T,S,N,M} return (findspan(surface.uknotvector, M, u), findspan(surface.vknotvector, M, v)) end function insertknot(knots::AbstractArray{S,1}, knotindex::Int, controlpoints::Array{MVector{N,S},1}, curveorder::Int) where {N,S} knotvalue = knots[knotindex] M = curveorder K = [zeros(MVector{N,S}) for i in 1:(M + 1)] newknots = vcat(knots[1:knotindex], [knotvalue], knots[(knotindex + 1):end]) newcontrolpoints = vcat(controlpoints[1:(knotindex - M)], K, controlpoints[(knotindex + 1):end]) for i in (knotindex - M + 1):knotindex αᵢ = (knotvalue - knots[i]) / (knots[i + M] - knots[i]) @. newcontrolpoints[i] = αᵢ * controlpoints[i] + (1 - αᵢ) * controlpoints[i - 1] end for i in (knotindex + 1):length(newcontrolpoints) newcontrolpoints[i] .= controlpoints[i - 1] end return (newknots, newcontrolpoints) end function insertknot(curve::BSplineCurve{T,S,N,M}, knotindex::Int) where {T,S,N,M} newknots, newcontrolpoints = insertknot(curve.knotvector.knots, knotindex, curve.controlpolygon, M) return BSplineCurve{T,S,N,M}(KnotVector{S}(newknots), newcontrolpoints) end function insertknots(curve::BSplineCurve{T,S,N,M}) where {T,S,N,M} newknots, newcontrolpoints = insertknots(curve.knotvector.knots, curve.controlpolygon, M) return BSplineCurve{T,S,N,M}(newknots, newcontrolpoints) end function insertknots(surf::BSplineSurface{T,S,N,M}) where {T,S,N,M} # TODO avoid using ' newvknots, temppoints = expandcontrolpoints(surf.vknotvector.knots, surf.controlpolygon, M) newuknots, temppoints = expandcontrolpoints(surf.uknotvector.knots, copy(temppoints'), M) # TODO this adjoint is a pain for messing up all the types, ideally we wouldn't need to deepcopy # should have an arg for expandcontrolpoints that controls direction or something return BSplineSurface{T,S,N,M}(KnotVector{S}(newuknots), KnotVector{S}(newvknots), copy(temppoints')) end function expandcontrolpoints(vknots::AbstractArray{S,1}, controlpolygon::Array{MVector{N,S},2}, curveorder::Int) where {N,S} upts, vpts = size(controlpolygon) temp = Array{Array{MVector{N,S},1},1}(undef, 0) # TODO static array let newknots = vknots for i in 1:upts newknots, newcontrolpoints = insertknots(vknots, view(controlpolygon, i, :), curveorder) # not the most efficient since new knot arrays are being computed for reach row when all rows of knots are the same. Optimize later if necessary. # println("temp $temp newpts $newcontrolpoints") push!(temp, newcontrolpoints) end newcontrolpolygon = hcat(temp[:]...) # TODO more efficient way # make new 2D control point array return newknots, newcontrolpolygon end end function insertknots(knots::AbstractArray{S,1}, controlpoints::AbstractArray{MVector{N,S},1}, curveorder::Int) where {N,S} insertionknots = knotstoinsert(knots, curveorder) newknots = copy(knots) newcontrolpoints = Array{MVector{N,S},1}(controlpoints) offset = 0 for insertion in insertionknots for i in 1:insertion[2] newknots, newcontrolpoints = insertknot(newknots, insertion[1] + offset, newcontrolpoints, curveorder) end offset += insertion[2] # inserting knots changes the index where the next set of knots needs to be inserted. end return (newknots, newcontrolpoints) end function knotstoinsert(curve::Spline{T,S,N,M}) where {T,S,N,M} return knotstoinsert(curve.knotvector) end function knotstoinsert(knots::AbstractArray{S,1}, curveorder::Int) where {S} numknots = length(knots) index = curveorder + 2 knotcounts = Array{Tuple{Int64,Int64},1}(undef, 0) while index < numknots - curveorder stop = index + 1 while knots[index] == knots[stop] stop += 1 # stop will have the index after the last repeated knot in this sequence end numtoinsert = (curveorder) - (stop - index) if numtoinsert != 0 push!(knotcounts, (index, numtoinsert)) end # println("index $index stop $stop") index = stop end return knotcounts end function tobeziersegments(curve::BSplineCurve{T,S,N,M}) where {T,S,N,M} # returns an array of arrays of groups of M+1 Bezier control points, where M is the curve order. return tobeziersegments(curve.knotvector.knots, curve.controlpolygon, M) end function tobeziersegments(knots::AbstractArray{S,1}, controlpoints::Array{MVector{N,S},1}, curveorder::Int) where {N,S} # returns an array of arrays of groups of M+1 Bezier control points, where M is the curve order. Inefficient because it creates a new curve for every knot insertion. Optimize when necessary M = curveorder _, newcontrolpoints = insertknots(knots, controlpoints, curveorder) # each knot is now inserted M times, except for the first and last, which are repeated M+1 times. numsegments = length(knots) - 2 * (M + 1) + 1 # println(newcurve.controlpolygon) # println("numsegments $numsegments") segments = Array{Array{MVector{N,S},1}}(undef, numsegments) for i in 1:numsegments start = (i - 1) * M + 1 segments[i] = newcontrolpoints[start:(start + M)] end return segments end function tobeziersegments(surf::BSplineSurface{P,S,N,M}) where {P,S,N,M} newsurf = insertknots(surf) newcontrolpoints = newsurf.controlpolygon # each knot is now inserted M times, except for the first and last, which are repeated M+1 times. uknots, vknots = numknots(newsurf) numusegments = (uknots - 2 * (M + 1)) ÷ M + 1 numvsegments = (vknots - 2 * (M + 1)) ÷ M + 1 # println(newcurve.controlpolygon) # println("numsegments $numsegments") segments = Array{BezierSurface{P,S,N,M}}(undef, numusegments, numvsegments) # println("usges $numusegments vseg $numvsegments") for i in 1:numusegments for j in 1:numvsegments startu = (i - 1) * M + 1 startv = (j - 1) * M + 1 segments[i, j] = BezierSurface{P,S,N,M}(newcontrolpoints[startu:(startu + M), startv:(startv + M)]) end end return segments end function point(surface::BSplineSurface{P,S,N,M}, u::T, v::T)::SVector{N,S} where {T<:Real,P,S,N,M} spanu, spanv = findspan(surface, u, v) ubases = basisfunctions(surface.uknotvector, u, M) vbases = basisfunctions(surface.vknotvector, v, M) sum = zeros(MVector{N,S}) c = zeros(MVector{N,S}) for j in 1:(M + 1) for i in 1:(M + 1) pt = surface.controlpolygon[spanu - (M + 1) + i, spanv - (M + 1) + j] c .= c .+ ubases[i] .* pt end sum .= sum .+ vbases[j] .* c c .= 0 end return SVector{N,S}(sum) end function bsplineinvariant(numknots::Int, numcontrolpoints::Int, curveorder::Int) m = numknots - 1 n = numcontrolpoints - 1 @assert m == n + curveorder + 1 "This invariant should hold: m = n + curveorder + 1. Actual values: m=$m n=$n curveorder=$curveorder" end # Note TO SELF: need code to extract curves in the u and v directions from BSpline surfaces to work with the conversion to Bezier form. # "converts a NURBS curve into Bezier curve segments, represented as Bezier control points. For an m degree NURBS with n knots this will return n - (m+1) + 1 Bezier segments, each with m+1 control points." # function toBezier(curve::BSplineCurve{T,S,N,M}) where {T,S,N,M} # #this code follows that in the NURBS book closely. Use OffsetArrays to index by zero to avoid the nightmare of converting to indexing by 1. # U = curve.knots # Pw = curve.controlpolygon # Qw = OffsetArray{Array{OffestArray{Array{SVector{N,S},1}},1}}(undef,0) # temppoints = Array{SVector{N,S},1}(undef,0) # m = M + numknots(curve) + 1 # a = M # b = M+1 # nb = 0 # for i in 0:M # push!(temppoints,Pw[i]) # end # Qw[nb] = temppoints # while b < m # i = b # while b < m && U[b+1] == U[b] # b += 1; # end # mult = b-i+1 # if mult < M # numerator = U[b] - U[a] #numerator of alpha # #compute and store alphas # for j in p:-1:mult+1 # alphas[j-mult-1] = numerator/(U[a+j] - U[a]) # end # r = p - mult #insert knot r times # for j in 1:r # save = r-j # s = mult+j # This many new points # for k in p:-1:s # alpha = alphas[k-s] # Qw[nb][k] = alpha*Qw[nb][k] + (1-alpha)*Qw[nb][k-1] # end # if b < m #control point of next segment # Qw[nb+1][save] = Qw[nb][p] # end # end # end # nb += 1 #Bezier segment completed # if b < m #initialize for next segment # for i in p-mult:pairs # Qw[nb][i] = Pw[b-p+1] # end # a = b # b = b+1 # end # end # end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
15726
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ BezierCurve{P,S,N,M} <: Spline{P,S,N,M} `N` is the dimension of the curve, `M` is the curve order ```julia BezierCurve{P,S,N,M}(controlpoints::AbstractArray{<:AbstractArray{S,1},1}) ``` """ struct BezierCurve{P,S,N,M} <: Spline{P,S,N,M} # this has a funny name because of name conflict with Plots. controlpolygon::Array{SVector{N,S},1} function BezierCurve{P,S,N,M}(controlpoints::AbstractArray{<:AbstractArray{S,1},1}) where {P<:CurveType,S<:Number,N,M} @assert length(controlpoints) == M + 1 && length(controlpoints[1]) == N return new{P,S,N,M}([SVector{N,S}(point) for point in controlpoints]) end end export BezierCurve # m is the order of the moving lines, n is the order of the curve, d is the spatial dimension of the curve _arraysize(m, n, d) = (2m + n + 2, (m + 1) * (d + 1)) # computes the proper row index so control point Pj gets multiplied by correct non-redundant basis function. # The m term is to offset all the Pj values below the first m+1 rows to allow for the correct summation of the final g(d+1,k) terms. _rowindex(k, j, movinglineorder) = k + j + movinglineorder + 2 function movinglinearray(curve::BezierCurve{P,S,N,M}) where {P,S,N,M} # curveorder = M, spatialdimension = N movinglineorder = M - 1 # minimum order of moving line polynomial necessary to represent curve of order M. result = zeros(S, _arraysize(movinglineorder, M, N)) ctrlpts = curve.controlpolygon # upper right corner will contain just Bc(k,m) coefficients that get multiplied by the moving line vector g[movinglineorder*(d+1) + k] term start = movinglineorder * (N + 1) + 1 for index in start:(start + movinglineorder) k = index - start println("$k $movinglineorder $index") result[k + 1, index] = Bc(k, movinglineorder) end for spatialindex in 0:(N - 1) colblock = spatialindex * (movinglineorder + 1) + 1 for j in 0:M for k in 0:movinglineorder row = _rowindex(k, j, movinglineorder) result[row, colblock + k] = Bc(j, M) * Bc(k, movinglineorder) * ctrlpts[j + 1][spatialindex + 1] end end end return result end ################################################################################################################################### """ BezierSurface{P,S,N,M} <: SplineSurface{P,S,N,M} Bezier surface defined by grid of control points. !!! danger This surface does not create a valid half-space, requires updates to function correctly. ```julia BezierSurface{P,S,N,M}(controlpoints::AbstractArray{<:AbstractArray{S,1},2}) ``` """ struct BezierSurface{P,S,N,M} <: SplineSurface{P,S,N,M} controlpolygon::Array{SVector{N,S},2} function BezierSurface{P,S,N,M}(controlpoints::AbstractArray{<:AbstractArray{S,1},2}) where {P<:CurveType,S<:Real,N,M} @assert (M + 1, M + 1) == size(controlpoints) && length(controlpoints[1, 1]) == N return new([SVector{N,S}(point) for point in controlpoints]) end # function BezierSurface{P,S,N,M}(controlpoints::Array{SVector{N,S},2}) where {P<:CurveType,S<:Number,N,M} # @assert (M + 1, M + 1) == size(controlpoints) # newpoints = [copy(point) for point in controlpoints] # # temp1 = SVector{M + 1,SVector{N,S}}(undef, M + 1) # # temp2 = SVector{M + 1,SVector{N,S}}(undef, M + 1) # return new(newpoints) # end end export BezierSurface # """this function transforms the control points of the Bezier patch before ray tracing. Probably a better idea to use transforms in CSG operators, # although this could be a little less computation at run time.""" # function Base.:*(a::Transform{T}, surf::BezierSurface{P,T,N,M}) where {P,T,N,M} # result = deepcopy(surf) # for index in CartesianIndices(surf.controlpolygon) # result.controlpolygon[index] = a * result.controlpolygon[index] # end # return result # end deepcopy(a::BezierSurface{P,S,N,M}) where {P,S,N,M} = BezierSurface{P,S,N,M}(a.controlpolygon) uvrange(::Type{BezierSurface{P,S}}) where {P,S<:Real} = ((zero(S), one(S)), (zero(S), one(S))) uvrange(::BezierSurface{P,S}) where {P,S<:Real} = uvrange(BezierSurface{P,S}) onsurface(::BezierSurface{P,S,3,M}, ::SVector{3,S}) where {P,S<:Real,M} = false # DECASTELJAU @inline function decasteljau(controlpoints::AbstractArray{SVector{N,S},1}, ::Val{2}, u::T) where {T<:Real,S,N} w = 1 - u return (controlpoints[1] * w + controlpoints[2] * u) * w + (controlpoints[2] * w + controlpoints[3] * u) * u end @inline function decasteljau(controlpoints::AbstractArray{SVector{N,S},1}, ::Val{3}, u::T) where {T<:Real,S,N} w = 1 - u np1 = controlpoints[1] * w + controlpoints[2] * u np2 = controlpoints[2] * w + controlpoints[3] * u np3 = controlpoints[3] * w + controlpoints[4] * u np1 = np1 * w + np2 * u np2 = np2 * w + np3 * u np1 = np1 * w + np2 * u return np1 end @inline function decasteljau(controlpoints::AbstractArray{SVector{N,S},1}, ::Val{4}, u::T) where {T<:Real,S,N} w = 1 - u np1 = controlpoints[1] * w + controlpoints[2] * u np2 = controlpoints[2] * w + controlpoints[3] * u np3 = controlpoints[3] * w + controlpoints[4] * u np4 = controlpoints[4] * w + controlpoints[5] * u np1 = np1 * w + np2 * u np2 = np2 * w + np3 * u np3 = np3 * w + np4 * u np1 = np1 * w + np2 * u np2 = np2 * w + np3 * u np1 = np1 * w + np2 * u return np1 end @inline function decasteljau(controlpoints::AbstractArray{SVector{N,S},1}, ::Val{M}, u::T) where {T<:Real,S,N,M} # general solution for decasteljau for arbitrary curve order newpoints = MVector{M + 1,SVector{N,T}}(controlpoints) # do this to force newpoints to have the type of u rather than controlpoints. When u is a dual number this makes the array the correct type. @inbounds for i in 1:M @inbounds for k in 1:(M + 1 - i) newpoints[k] = newpoints[k] * (1 - u) + newpoints[k + 1] * u # this kills forwarddiff and zygote. ForwardDiff doesn't work because newpoints has the type of controlpoints, which is going to be Float64 most times, # when it needs to be of type dual number. Zygote doesn't support mutable arrays. Arrrrgggghhh! Useless! end end return newpoints[1] end # POINT function point(surf::BezierSurface{P,S,N,3}, u::T, v::T) where {T<:Real,P,S,N} q1 = decasteljau(view(surf.controlpolygon, :, 1), Val(3), u) q2 = decasteljau(view(surf.controlpolygon, :, 2), Val(3), u) q3 = decasteljau(view(surf.controlpolygon, :, 3), Val(3), u) q4 = decasteljau(view(surf.controlpolygon, :, 4), Val(3), u) return decasteljau(SVector{4,SVector{N,S}}(q1, q2, q3, q4), Val(3), v) end function point(surf::BezierSurface{P,S,N,4}, u::T, v::T) where {T<:Real,P,S,N} q1 = decasteljau(view(surf.controlpolygon, :, 1), Val(4), u) q2 = decasteljau(view(surf.controlpolygon, :, 2), Val(4), u) q3 = decasteljau(view(surf.controlpolygon, :, 3), Val(4), u) q4 = decasteljau(view(surf.controlpolygon, :, 4), Val(4), u) q5 = decasteljau(view(surf.controlpolygon, :, 5), Val(4), u) return decasteljau(SVector{5,SVector{N,S}}(q1, q2, q3, q4, q5), Val(4), v) end function point(surf::BezierSurface{P,S,N,M}, u::T, v::T) where {T<:Real,P,S,N,M} qi = zeros(MVector{M + 1,SVector{N,S}}) @inbounds for i in 1:(M + 1) qi[i] = decasteljau(view(surf.controlpolygon, :, i), Val(M), u) end return decasteljau(qi, Val(M), v) end # DERIVATIVE @inline function derivative(controlpoints::SVector{4,SVector{N,S}}, u::T) where {T<:Real,N,S} d1 = controlpoints[2] .- controlpoints[1] d2 = controlpoints[3] .- controlpoints[2] d3 = controlpoints[4] .- controlpoints[3] return 3 * decasteljau(SVector{3,SVector{N,S}}(d1, d2, d3), Val(2), u) end @inline function derivative(controlpoints::SVector{5,SVector{N,S}}, u::T) where {T<:Real,N,S} d1 = controlpoints[2] .- controlpoints[1] d2 = controlpoints[3] .- controlpoints[2] d3 = controlpoints[4] .- controlpoints[3] d4 = controlpoints[5] .- controlpoints[4] return 4 * decasteljau(SVector{4,SVector{N,S}}(d1, d2, d3, d4), Val(3), u) end @inline function derivative(controlpoints::MVector{Q,SVector{N,S}}, u::T) where {T<:Real,N,S,Q} derivpoints = zeros(MVector{Q - 1,SVector{N,T}}) @inbounds for i in 1:(Q - 1) derivpoints[i] = controlpoints[i + 1] .- controlpoints[i] end return (Q - 1) * decasteljau(derivpoints, Val(Q - 2), u) end # PARTIALS function partials(surf::BezierSurface{Euclidean,S,N,3}, u::T, v::T) where {T<:Real,S,N} q1 = decasteljau(view(surf.controlpolygon, :, 1), Val(3), u) q2 = decasteljau(view(surf.controlpolygon, :, 2), Val(3), u) q3 = decasteljau(view(surf.controlpolygon, :, 3), Val(3), u) q4 = decasteljau(view(surf.controlpolygon, :, 4), Val(3), u) partialv = derivative(SVector{4,SVector{N,S}}(q1, q2, q3, q4), v) q1 = decasteljau(view(surf.controlpolygon, 1, :), Val(3), v) q2 = decasteljau(view(surf.controlpolygon, 2, :), Val(3), v) q3 = decasteljau(view(surf.controlpolygon, 3, :), Val(3), v) q4 = decasteljau(view(surf.controlpolygon, 4, :), Val(3), v) partialu = derivative(SVector{4,SVector{N,S}}(q1, q2, q3, q4), u) return (partialu, partialv) end function partials(surf::BezierSurface{Euclidean,S,N,4}, u::T, v::T) where {T<:Real,S,N} q1 = decasteljau(view(surf.controlpolygon, :, 1), Val(4), u) q2 = decasteljau(view(surf.controlpolygon, :, 2), Val(4), u) q3 = decasteljau(view(surf.controlpolygon, :, 3), Val(4), u) q4 = decasteljau(view(surf.controlpolygon, :, 4), Val(4), u) q5 = decasteljau(view(surf.controlpolygon, :, 5), Val(4), u) partialv = derivative(SVector{5,SVector{N,S}}(q1, q2, q3, q4, q5), v) q1 = decasteljau(view(surf.controlpolygon, 1, :), Val(4), v) q2 = decasteljau(view(surf.controlpolygon, 2, :), Val(4), v) q3 = decasteljau(view(surf.controlpolygon, 3, :), Val(4), v) q4 = decasteljau(view(surf.controlpolygon, 4, :), Val(4), v) q5 = decasteljau(view(surf.controlpolygon, 5, :), Val(4), v) partialu = derivative(SVector{5,SVector{N,S}}(q1, q2, q3, q4, q5), u) return (partialu, partialv) end function partials(surf::BezierSurface{Euclidean,S,N,M}, u::T, v::T) where {T<:Real,S,N,M} qi = zeros(MVector{M + 1,SVector{N,T}}) # do this to force newpoints to have the type of u rather than controlpoints. When u is a dual number this makes the array the correct type. @inbounds for i in 1:(M + 1) qi[i] = decasteljau(view(surf.controlpolygon, :, i), Val(M), u) end partialv = derivative(qi, v) @inbounds for i in 1:(M + 1) qi[i] = decasteljau(view(surf.controlpolygon, i, :), Val(M), v) end partialu = derivative(qi, u) return (partialu, partialv) end # "computes partials and point simultaneously for Euclidean surface" # function pointandpartials(surf::BezierSurface{Euclidean,S,N,M}, u::T, v::T) where {T<:Real,S,N,M} # qi = zeros(MVector{M + 1,SVector{N,T}}) # # do this to force newpoints to have the type of u rather than controlpoints. When u is a dual number this makes the array the correct type. # @inbounds for i in 1:(M + 1) # qi[i] = decasteljau(view(surf.controlpolygon, :, i), M, u) # end # pt = decasteljau(qi, M, v) # partialv = derivative(qi, v) # @inbounds for i in 1:(M + 1) # qi[i] = decasteljau(view(surf.controlpolygon, i, :), M, v) # end # partialu = derivative(qi, u) # return (pt, partialu, partialv) # end function partials(surf::BezierSurface{Rational,S,N,M}, u::T, v::T) where {T<:Real,S,N,M} # computes Euclidean space partials for Rational surface. Not consistent with point, which has euclideanpoint function, but not sure why user would ever want Rational partials. pt = point(surf, u, v) du, dv = partials(surf, u, v) rdu = rationalcorrection(pt, du) rdv = rationalcorrection(pt, dv) return (rdu, rdv) end function normal(surf::BezierSurface, u::T, v::T) where {T<:Real} du, dv = partials(surf, u, v) return normalize(cross(du, dv)) end function rationalcorrection(pt::SVector{N,S}, dpt::SVector{N,S}) where {N,S} # have form A/B where A = (x,y,z) and B = w component of vector. Want partial(A/B,u). Get (B*partial(A,u) - A*partial(B,u))/B*B A = pt[1:(N - 1)] B = pt[N] dB = dpt[N] dA = dpt[1:(N - 1)] return (B .* dA - A .* dB) / B^2 end # """attempt to generate inline code so Zygote and Forwarddiff could differentatiate properly. Didn't work.""" # function inlinedecasteljau(curveorder, N) # a = "(u,$(reduce(*, ("newpoints$(k)_$j," for k in 1:curveorder,j in 1:N)))) -> let # " # for i in 1:curveorder # for k in 1:(curveorder + 1 - i) # for j in 1:N # a *= "newpoints$(k)_$j = newpoints$(k)_$j * (1-u) + newpoints$(k + 1)_$j * u # " # end # end # end # a *= "return ($(reduce(*, ("newpoints1_$j," for j in 1:N)))) # end" # return eval(Meta.parse(a)) # end # "Creates a differentiable function to evaluate a surface point. Zygote has trouble with mutable arrays so this creates a function # which unrolls all loops and converts array indexing to variables. Stopped working on this because it became so diffult to make it work." # function pointinline(surf::BezierSurface{P,S,N,M}, u::T, v::T) where {T<:Real,P,S,N,M} # controlpoints = surf.controlpolygon # qi = zeros(MVector{N * (M + 1),MVector{N,S},1}) # pointinl = inlinedecasteljau(M, N) # @inbounds for i in 1:(M + 1) # start = (i - 1) * N + 1 # @inbounds for j in 1:N # temp = pointinl(u, controlpoints[:, i]...) # qi[start + j - 1] = temp[j] # end # end # return pointinl(v, qi...) # end function point(curve::BezierCurve{P,S,N,M}, u::T) where {T<:Real,P,S,N,M} # Will return homogeneous curve point if curve is homogeneous and euclidean point if curve is Euclidean. return decasteljau(curve.controlpolygon, M, u) end euclideanpoint(curve::BezierCurve{Euclidean,S,N,M}, u::T) where {T<:Real,S,N,M} = point(curve, u) function euclideanpoint(curve::BezierCurve{Rational,S,N,M}, u::T) where {T<:Real,S,N,M} temp = point(curve, u) return toeuclidean(temp) end ######################################################################################################################### function inside(surf::AcceleratedParametricSurface{S,3,BezierSurface{P,S,3,M}}, p::SVector{3,S}) where {P,S<:Real,M} # approximate the normal to the bezier surface as a whole by taking the average of the normals of the triangles # defined by the extreme points of the surface A = point(surf, 0.0, 0.0) B = point(surf, 0.0, 1.0) C = point(surf, 1.0, 0.0) D = point(surf, 1.0, 1.0) n1 = cross(C - A, B - A) n2 = cross(B - D, C - D) approx_normal = (n1 + n2) / (norm(n1) + norm(n2)) r = Ray(p, approx_normal) @inbounds for i in 1:length(surf.triangles) intv = surfaceintersection(surf.triangles[i], r) if !(intv isa EmptyInterval) return true end end return false end function BoundingBox(surf::BezierSurface{P,S,N,M}) where {P,S,N,M} big = fill(typemin(S), MVector{N,S}) small = fill(typemax(S), MVector{N,S}) for pt in surf.controlpolygon small .= min.(small, pt) big .= max.(big, pt) end return BoundingBox(small[1], big[1], small[2], big[2], small[3], big[3]) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
2644
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ KnotVector{T<:Number} Vector to define knots used for [`BSplineCurve`](@ref) and [`BSplineSurface`](@ref). """ struct KnotVector{T<:Number} knots::Array{T,1} function KnotVector{T}(a::Array{T,1}) where {T<:Number} temp = a[1] for i in 2:lastindex(a) # ensure knot vector is non-decreasing @assert a[i] >= temp temp = a[i] end return new(copy(a)) end end export KnotVector Base.copy(knots::KnotVector{S}) where {S} = KnotVector{S}(knots.knots) urange(knots::KnotVector) = (knots.knots[1], knots.knots[end]) numknots(knots::KnotVector) = size(knots.knots)[1] struct InvalidParameterValue <: Exception invalid_u::Any validrange::Any end Base.showerror(io::IO, e::InvalidParameterValue) = print(io, "invalid parameter value: $(e.invalid_u) allowable parameter range: $(e.validrange)") function findspan(knots::KnotVector, curveorder, u) pmin = curveorder + 1 nknots = numknots(knots) pmax = nknots - (curveorder + 1) if knots.knots[pmax + 1] == u return pmax end for i in pmin:pmax # if u == ui+1 then the span goes from i to i+1. if u <= knots.knots[i + 1] return i end end # this might be too extreme. round off error could cause parameter value to go a little above max value. Might need to loosen this later. throw(InvalidParameterValue(u, (knots.knots[1], knots.knots[end]))) # return the bad u value and the legal range of u values end function basisfunctions(knots::KnotVector{T}, u::T, curveorder) where {T<:Number} # computes values of p+1 basis functions where p is the curve order. knotsegment is the index of the knot vector segment, u is the value of the curve parameter knotsegment = findspan(knots, curveorder, u) U = knots.knots tempsize = curveorder + 1 left = zeros(T, tempsize) # later rewrite this code to have a struct that stores these temps so they aren't being allocated on every curve evaluation right = zeros(T, tempsize) N = zeros(T, tempsize) N[1] = one(T) for j in 1:curveorder left[j + 1] = u - U[knotsegment + 1 - j] right[j + 1] = U[knotsegment + j] - u saved = zero(T) for r in 0:(j - 1) leftindex = j - r + 1 temp = N[r + 1] / (right[r + 2] + left[leftindex]) N[r + 1] = saved + right[r + 2] * temp saved = left[leftindex] * temp end N[j + 1] = saved end return N end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
1788
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. struct PowerBasisCurve{P,S,N,M} <: Spline{P,S,N,M} controlpolygon::Array{S,2} #not exactly the right name, should be coefficients instead, but consistent with the other splines #data stored like this: # a0x a1x ... aM+1x # a0y a1y ... aM+1x # and so on for however many spatial dimensions function PowerBasisCurve{P,S,N,M}(coefficients::Array{S,2}) where {P,S,N,M} @assert (N, M + 1) == size(coefficients) return new{P,S,N,M}(copy(coefficients)) end end export PowerBasisCurve function coefficients(curve::PowerBasisCurve{P,S,N,M}, spatialindex) where {P,S,N,M} return curve.controlpolygon[spatialindex, :] end function PowerBasisCurve{P,S,N,M}(curve::BezierCurve{P,S,N,M}) where {P,S,N,M} controlpolygon = curve.controlpolygon coefficients = Array{S,2}(undef, N, M + 1) # array stores coefficients for all N spatial dimensions #this is probably not the most efficient way to convert from Bernstein to Power basis. Optimize later if necessary. for k in 0:M for i in k:M @. coefficients[:, i + 1] += (-1)^(i - k) * binomial(M, i) * binomial(i, k) * controlpolygon[k + 1] end end return PowerBasisCurve{P,S,N,M}(coefficients) end function beziertopowerbasis(k, n) coefficient = 0 for i in k:n @. coefficients[:, i + 1] += (-1)^(i - k) * binomial(n, i) * binomial(i, k) end end function point(curve::PowerBasisCurve, u::T) where {T<:Number} _, n = size(curve.controlpolygon) sum = curve.controlpolygon[:, n] for i in (n - 1):-1:1 @. sum = u * sum + curve.controlpolygon[:, i] end return sum end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
1755
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Either `Rational` or `Euclidean`, used for [`Spline`](@ref)s and [`SplineSurface`](@ref)s. """ abstract type CurveType end abstract type Rational <: CurveType end abstract type Euclidean <: CurveType end export CurveType """ Spline{P<:CurveType,S<:Number,N,M} `M` is the curve order, i.e., the highest power of the parameterizing variable, u. `P` determines the [`CurveType`](@ref). All Spline types must implement: ```julia point(curve,u) ``` and have field `controlpolygon` """ abstract type Spline{P<:CurveType,S<:Number,N,M} end """ SplineSurface{P,S,N,M} <: ParametricSurface{S,N} Curve order, `M`, is the same in the u and v direction and fixed over all spans. `P` determines the [`CurveType`](@ref). """ abstract type SplineSurface{P<:CurveType,S,N,M} <: ParametricSurface{S,N} end export Spline, SplineSurface function toeuclidean(point) return SVector{length(point) - 1}([point[i] / point[end] for i in 1:(lastindex(point) - 1)]) end function euclideancontrolpoints(curve::Spline{Rational,S,N,M}) where {S,N,M} return toeuclidean.(curve.controlpolygon) end function euclideancontrolpoints(curve::Spline{Euclidean,S,N,M}) where {S,N,M} return curve.controlpolygon end #Bernstein polynomial functions #B(i,n,u) is broken into Bc,Bu because these two functions will be needed when constructing the matrics to compute moving lines or moving planes Bc(i, n) = factorial(n) ÷ (factorial(i) * factorial(n - i)) #coefficient of the i,n Bernstein basis polynomial Bu(i, n, u) = u^i * (1 - u)^(n - i) #polynomial part of Bernstein basis polynomial B(i, n, u) = Bc(i, n) * Bu(i, n, u)
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
6366
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. import Statistics const _abs_err_orientation_2d = 2*eps(Float64) """ ConvexPolygon{N, T<:Real} <: PlanarShape{T} General Convex Polygon surface, not a valid CSG object. The rotation of the polygon around its normal is defined by `rotationvec`. `rotationvec×surfacenormal` is taken as the vector along the u axis. ```julia ConvexPolygon(local_frame::Transform{T}, local_polygon_points::Vector{SVector{2, T}}, interface::NullOrFresnel{T} = nullinterface(T)) ``` The local frame defines the plane (spans by the right and up vectors) with the plane normal given by the forward vector. the local_polygon_points are given with respect to the local frame and are 2D points. NOTE: This class uses static vectors to hold the points which will lead to more efficient performance, but should not be used with polygons with more than 20-30 points. """ struct ConvexPolygon{N,T<:Real} <: PlanarShape{T} plane::Plane{T,3} local_frame::Transform{T} # local_points::Vector{SVector{2, T}} local_points::SMatrix{2,N,T} # for efficency _local_frame_inv::Transform{T} # cache the inverse matrix to avoid computing it for every intersection test _local_lines::Vector{SVector{3, SVector{2, T}}} # defines the edge points + a third point representing the slopes in order to save some calculationsduring ray checking _length::Int64 # cache the length of the polygon function ConvexPolygon( local_frame::Transform{T}, local_polygon_points::Vector{SVector{2, T}}, interface::NullOrFresnel{T} = NullInterface(T) ) where {T<:Real} # need at least 3 points to define apolygon @assert length(local_polygon_points) >= 3 local_center = Statistics.mean(local_polygon_points) world_center = local2world(local_frame) * Vec3(local_center[1], local_center[2], zero(T)) # poly_points = [GeometricalPredicates.Point2D(p[1], p[2]) for p in local_polygon_points] # poly = GeometricalPredicates.Polygon2D(poly_points...) pts = local_polygon_points local_lines = SVector( [SVector( pts[i], # A pts[mod(i, length(pts))+1], # B # bx = Bx - Ax, by = By - Ay SVector(pts[mod(i, length(pts))+1][1] - pts[i][1], pts[mod(i, length(pts))+1][2] - pts[i][2])) for i in 1:length(pts)]... ) plane = Plane(forward(local_frame), world_center, interface = interface) N = length(local_polygon_points) temp = MMatrix{2,N,T}(undef) for (i,pt) in pairs(local_polygon_points) temp[:,i] = pt end N2 = 2*N new{N,T}(plane, local_frame, SMatrix{2,N,T,N2}(temp), inv(local_frame), local_lines, length(local_lines)) end end export ConvexPolygon centroid(poly::ConvexPolygon) = poly.plane.pointonplane normal(poly::ConvexPolygon) = normal(poly.plane) localframe(poly::ConvexPolygon) = poly.local_frame export localframe #function barrier to make vertices allocate less and be faster. function to3d(pts::SMatrix{2,N,T,L}) where{N,L,T} temp = MMatrix{3,N,T}(undef) for row in 1:2 for col in 1:N temp[row,col] = pts[row,col] end end for col in 1:N temp[3,col] = T(0) end return SMatrix{3,N,T}(temp) return temp end #this function allocates. Don't know why, it shouldn't but it does. function vertices(poly::ConvexPolygon{N,T}) where{N,T<:Real} return poly.local_frame * to3d(poly.local_points) end function surfaceintersection(poly::ConvexPolygon{N,T}, r::AbstractRay{T,3}) where {N,T<:Real} interval = surfaceintersection(poly.plane, r) if interval isa EmptyInterval{T} || isinfiniteinterval(interval) return EmptyInterval(T) # no ray plane intersection or inside plane but no hit else intersect = halfspaceintersection(interval) p = point(intersect) local_p = poly._local_frame_inv * p @inline function orientation(l::SVector{3, SVector{2, T}})::Int8 where {T<:Real} cx = local_p[1] - l[1][1] # getx(p) - getx(geta(l)) cy = local_p[2] - l[1][2] # gety(p) - gety(geta(l)) _pr2 = -(l[3][1]*cy) + l[3][2]*cx # _pr2 = -l._bx*cy + l._by*cx if _pr2 < -_abs_err_orientation_2d 1 elseif _pr2 > _abs_err_orientation_2d -1 else 0 # can implement something more accurate in the future to minimize numerical errors end end @inline function inpolygon() side = orientation(poly._local_lines[1]) for i = 2:poly._length orientation(poly._local_lines[i]) == side || return false end return true end if !inpolygon() return EmptyInterval(T) else if dot(normal(poly), direction(r)) < zero(T) return positivehalfspace(intersect) else return rayorigininterval(intersect) end end end end """ makemesh(poly::ConvexPolygon{N, T}, ::Int = 0) where {N, T<:Real} -> TriangleMesh Create a triangle mesh that can be rendered by iterating on the polygon's edges and for each edge use the centroid as the third vertex of the triangle. """ function makemesh(poly::ConvexPolygon{N,T}, ::Int = 0) where {N,T<:Real} c = centroid(poly) l2w = local2world(poly.local_frame) len = Size(poly.local_points)[2] triangles = [] for i in 1:len p1 = poly.local_points[:,i] p2 = poly.local_points[:,mod(i,len) + 1] tri = Triangle( Vector(l2w * Vec3(p2[1], p2[2], zero(T))), Vector(c), Vector(l2w * Vec3(p1[1], p1[2], zero(T)))) push!(triangles, tri) end triangles = Vector{Triangle{T}}(triangles) return TriangleMesh(triangles) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
5945
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Ellipse{T} <: Surface{T} Elliptical surface, not a valid CSG object. The rotation of the rectangle around its normal is defined by `rotationvec`. `rotationvec×surfacenormal` is taken as the vector along the u axis. **Can be used as a detector in [`AbstractOpticalSystem`](@ref)s.** ```julia Ellipse(halfsizeu::T, halfsizev::T, [surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}]; interface::NullOrFresnel{T} = nullinterface(T)) ``` The minimal case returns an ellipse centered at the origin with `surfacenormal = [0, 0, 1]`. """ struct Ellipse{T} <: PlanarShape{T} plane::Plane{T,3} halfsizeu::T halfsizev::T uvec::SVector{3,T} vvec::SVector{3,T} function Ellipse(halfsizeu::T, halfsizev::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert halfsizeu > zero(T) && halfsizev > zero(T) new{T}(Plane(SVector{3,T}(0, 0, 1), SVector{3,T}(0, 0, 0), interface = interface), halfsizeu, halfsizev, SVector{3,T}(1.0, 0.0, 0.0), SVector{3,T}(0.0, 1.0, 0.0)) end function Ellipse(halfsizeu::T, halfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; interface::NullOrFresnel{T} = NullInterface(T), rotationvec::SVector{3,T} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} @assert halfsizeu > zero(T) && halfsizev > zero(T) n̂ = normalize(surfacenormal) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) new{T}(Plane(n̂, centrepoint, interface = interface), halfsizeu, halfsizev, uvec, vvec) end function Ellipse(plane::Plane{T,3}, halfsizeu::T, halfsizev::T, uvec::SVector{3,T}, vvec::SVector{3,T}) where {T<:Real} new{T}(plane, halfsizeu, halfsizev, uvec, vvec) end end export Ellipse Base.show(io::IO, a::Ellipse{T}) where {T<:Real} = print(io, "Ellipse{$T}($(centroid(a)), $(normal(a)), $(a.halfsizeu), $(a.halfsizev), $(interface(a)))") uvrange(::Type{Ellipse{T}}) where {T<:Real} = ((-T(π), T(π)), (zero(T), one(T))) # θ and ρ point(r::Ellipse{T}, θ::T, ρ::T) where {T<:Real} = centroid(r) + ρ * (r.halfsizeu * cos(θ) * r.uvec + r.halfsizev * sin(θ) * r.vvec) partials(r::Ellipse{T}, θ::T, ρ::T) where {T<:Real} = (ρ * (r.halfsizeu * -sin(θ) * r.uvec + r.halfsizev * cos(θ) * r.vvec), (r.halfsizeu * cos(θ) * r.uvec + r.halfsizev * sin(θ) * r.vvec)) uv(r::Ellipse{T}, x::T, y::T, z::T) where {T<:Real} = uv(r, SVector{3,T}(x, y, z)) function uv(r::Ellipse{T}, p::SVector{3,T}) where {T<:Real} v = dot(p - centroid(r), r.vvec) u = dot(p - centroid(r), r.uvec) θ = NaNsafeatan(v, u) rad = norm(r.halfsizeu * cos(θ) * r.uvec + r.halfsizev * sin(θ) * r.vvec) return SVector{2,T}(θ, norm(p - centroid(r)) / rad) end onsurface(a::Ellipse{T}, point::SVector{3,T}) where {T<:Real} = onsurface(a.plane, point) && zero(T) <= uv(a, point)[2] <= one(T) function uvtopix(::Ellipse{T}, uv::SVector{2,T}, imsize::Tuple{Int,Int}) where {T<:Real} θ, ρ = uv h, w = imsize u = (cos(θ) * ρ + one(T)) / 2 v = (sin(θ) * ρ + one(T)) / 2 pixu = Int(floor((w - 1) * u)) + 1 pixv = h - Int(floor((h - 1) * v)) return pixu, pixv end centroid(r::Ellipse{T}) where {T<:Real} = r.plane.pointonplane function surfaceintersection(ell::Ellipse{T}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(ell.plane, r) if interval isa EmptyInterval{T} || isinfiniteinterval(interval) return EmptyInterval(T) # no ray plane intersection or inside plane but no hit else intersect = halfspaceintersection(interval) p = point(intersect) θ, ρ = uv(ell, p) if ρ > one(T) return EmptyInterval(T) # no ray plane intersection else intuv = Intersection(α(intersect), p, normal(ell), θ, ρ, interface(ell)) if dot(normal(ell), direction(r)) < zero(T) return positivehalfspace(intuv) else return rayorigininterval(intuv) end end end end vertices(e::Ellipse,subdivisions::Int = 10) = vertices3d(e,subdivisions)[1:2,:] function vertices3d(e::Ellipse{R},::Type{Val{subdivisions}} = Val{10}) where{R<:Real,subdivisions} verts = MMatrix{3,subdivisions,R}(undef) dθ = R(2π) / subdivisions for i in 0:(subdivisions - 1) θ1 = i * dθ - π pt = point(e, θ1, one(R)) for j in 1:3 verts[j,i+1] = pt[j] end end return SMatrix{3,subdivisions,R}(verts) end vertices3d(e::Ellipse{R}, subdivisions::Int = 10) where{R} = vertices3d(e) function makemesh(c::Ellipse{T}, subdivisions::Int = 30) where {T<:Real} dθ = T(2π) / subdivisions centre = point(c, zero(T), zero(T)) tris = Vector{Triangle{T}}(undef, subdivisions) for i in 0:(subdivisions - 1) θ1 = i * dθ - π θ2 = (i + 1) * dθ - π p1 = point(c, θ1, one(T)) p2 = point(c, θ2, one(T)) tris[i + 1] = Triangle(centre, p1, p2) end return TriangleMesh(tris) end ########################### function Circle(radius::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} return Ellipse(radius, radius; interface = interface) end """ Circle(radius, [surfacenormal, centrepoint]; interface = nullinterface(T)) Shortcut method to create a circle. The minimal case returns a circle centred at the origin with `normal = [0, 0, 1]`. """ function Circle(radius::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} return Ellipse(radius, radius, surfacenormal, centrepoint; interface = interface, rotationvec = SVector{3,T}(0.0, 1.0, 0.0)) end export Circle
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
5078
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Hexagon{T} <: Surface{T} Hexagonal surface, not a valid CSG object. The rotation of the hexagon around its normal is defined by `rotationvec`. `rotationvec×surfacenormal` is taken as the vector along the u axis. ```julia Hexagon(side_length::T, [surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}]; rotationvec::SVector{3,T} = [0.0, 1.0, 0.0], interface::NullOrFresnel{T} = nullinterface(T)) ``` The minimal case returns a rectangle centered at the origin with `surfacenormal = [0, 0, 1]`. """ struct Hexagon{T} <: PlanarShape{T} plane::Plane{T,3} side_length::T uvec::SVector{3,T} vvec::SVector{3,T} function Hexagon(side_length::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert side_length > zero(T) new{T}(Plane(zero(T), zero(T), one(T), zero(T), zero(T), zero(T), interface = interface), side_length, SVector{3,T}(1.0, 0.0, 0.0), SVector{3,T}(0.0, 1.0, 0.0)) end function Hexagon(side_length::T, surfacenormal::AbstractArray{T,1}, centrepoint::AbstractArray{T,1}; interface::NullOrFresnel{T} = NullInterface(T), rotationvec::AbstractArray{T,1} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} @assert length(surfacenormal) == 3 && length(centrepoint) == 3 return Hexagon(side_length, SVector{3,T}(surfacenormal), SVector{3,T}(centrepoint), interface = interface, rotationvec = SVector{3,T}(rotationvec)) end function Hexagon(side_length::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; rotationvec::SVector{3,T} = SVector{3,T}(0.0, 1.0, 0.0), interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert side_length > zero(T) n̂ = normalize(surfacenormal) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) new{T}(Plane(n̂, centrepoint, interface = interface), side_length, uvec, vvec) end end export Hexagon Base.show(io::IO, hex::Hexagon{T}) where {T<:Real} = print(io, "Hexagon{$T}($(centroid(hex)), $(normal(hex)), $(hex.side_length), $(interface(hex)))") centroid(hex::Hexagon{T}) where {T<:Real} = hex.plane.pointonplane function surfaceintersection(hex::Hexagon{T}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(hex.plane, r) if interval isa EmptyInterval{T} || isinfiniteinterval(interval) return EmptyInterval(T) # no ray plane intersection or inside plane but no hit else intersect = halfspaceintersection(interval) p = point(intersect) q2u = abs(dot(p - centroid(hex), hex.uvec)) q2v = abs(dot(p - centroid(hex), hex.vvec)) h = hex.side_length * sqrt(3) / 2 if q2u > h || q2v > hex.side_length return EmptyInterval(T) else if hex.side_length * h - hex.side_length / 2 * q2u - h * q2v >= 0 if dot(normal(hex), direction(r)) < zero(T) return positivehalfspace(intersect) else return rayorigininterval(intersect) end else return EmptyInterval(T) end end end end """Returns the vertices of the Hexagon represented in the local coordinate frame. The vertices lie in the z = 0 plane and are 2D""" function vertices3d(hex::Hexagon{T}) where{T<:Real} #written this way to ensure 0 allocations. Higher level features like ... allocate. uvec = hex.side_length * hex.uvec vvec = hex.side_length * hex.vvec c = centroid(hex) h = sin(π\3) pts = SVector{6,SVector{3,T}}( uvec + c, (.5*uvec + vvec*h)+ c, (-.5*uvec + vvec*h)+ c, (-uvec)+ c, (-.5*uvec - vvec*h)+ c, (.5*uvec - vvec*h)+ c, ) temp = MMatrix{3,6,T}(undef) for (j,pt) in pairs(pts) for i in 1:3 temp[i,j] = pts[j][i] end end return SMatrix{3,6,T}(temp) end function makemesh(hex::Hexagon{T}, ::Int = 0) where {T<:Real} uvec = hex.side_length * hex.uvec vvec = hex.side_length * hex.vvec c = centroid(hex) triangles = [Triangle(c + sin(0 * π / 3) * uvec + cos(0 * π / 3) * vvec, c, c + sin(1 * π / 3) * uvec + cos(1 * π / 3) * vvec), Triangle(c + sin(1 * π / 3) * uvec + cos(1 * π / 3) * vvec, c, c + sin(2 * π / 3) * uvec + cos(2 * π / 3) * vvec), Triangle(c + sin(2 * π / 3) * uvec + cos(2 * π / 3) * vvec, c, c + sin(3 * π / 3) * uvec + cos(3 * π / 3) * vvec), Triangle(c + sin(3 * π / 3) * uvec + cos(3 * π / 3) * vvec, c, c + sin(4 * π / 3) * uvec + cos(4 * π / 3) * vvec), Triangle(c + sin(4 * π / 3) * uvec + cos(4 * π / 3) * vvec, c, c + sin(5 * π / 3) * uvec + cos(5 * π / 3) * vvec), Triangle(c + sin(5 * π / 3) * uvec + cos(5 * π / 3) * vvec, c, c + sin(0 * π / 3) * uvec + cos(0 * π / 3) * vvec)] return TriangleMesh(triangles) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
1840
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """The PlanarShape interface: `distancefromplane(p::PlanarShape,point)` returns distance of the point from the plane the planar shape lies within `normal(p::PlanarShape)` returns normal of plane `interface(p::PlanarShape)` returns optical interface of plane `vertices(p::PlanarShape)` returns vertices of shape. For Ellipse this is an approximation. There are default functions for plane,normal,interface,vertices which assume each PlanarShape type has a field of the same name ` plane(a::PlanarShape) = a.plane normal(a::PlanaShape) = a.plane.normal ` etc. If your type doesn't have these fields then you should define a more specialized method to handle this. """ abstract type PlanarShape{T} <: Surface{T} end """All planar shapes lie on a plane. This function computes the distance from a point to that plane. This is a signed distance. If the point is on the positive side of the plane (the side the normal points toward) the distance will be positive, otherwise negative or 0 if the point lies in the plane.""" distancefromplane(p::PlanarShape, point::SVector{3}) = distancefromplane(p.plane,point) normal(p::PlanarShape) = normal(p.plane) interface(p::PlanarShape) = interface(p.plane) """The vertices of planar shapes are defined in a plane so they are two dimensional. In the local coordinate frame this is the x,y plane, so the implied z coordinate is 0""" vertices(p::PlanarShape) = throw(ErrorException("This function should be defined for any concrete type that is a subtype of PlanarShape")) #don't think this function can ever be called because you can't instantiate something of PlanarShape type; it's an abstract type. export vertices plane(p::PlanarShape) = p.plane
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
6951
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Rectangle{T} <: Surface{T} Rectangular surface, not a valid CSG object. The rotation of the rectangle around its normal is defined by `rotationvec`. `rotationvec×surfacenormal` is taken as the vector along the u axis. **Can be used as a detector in [`AbstractOpticalSystem`](@ref)s.** ```julia Rectangle(halfsizeu::T, halfsizev::T, [surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}]; rotationvec::SVector{3,T} = [0.0, 1.0, 0.0], interface::NullOrFresnel{T} = nullinterface(T)) ``` The minimal case returns a rectangle centered at the origin with `surfacenormal = [0, 0, 1]`. """ struct Rectangle{T} <: PlanarShape{T} plane::Plane{T,3} halfsizeu::T halfsizev::T uvec::SVector{3,T} vvec::SVector{3,T} function Rectangle(halfsizex::T, halfsizey::T; interface::NullOrFresnel{T} = NullInterface(T)) where {T<:Real} @assert halfsizex > zero(T) && halfsizey > zero(T) new{T}(Plane(zero(T), zero(T), one(T), zero(T), zero(T), zero(T), interface = interface), halfsizex, halfsizey, SVector{3,T}(1.0, 0.0, 0.0), SVector{3,T}(0.0, 1.0, 0.0)) end function Rectangle(halfsizeu::T, halfsizev::T, surfacenormal::AbstractArray{T,1}, centrepoint::AbstractArray{T,1}; interface::NullOrFresnel{T} = NullInterface(T), rotationvec::AbstractArray{T,1} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} @assert length(surfacenormal) == 3 && length(centrepoint) == 3 return Rectangle(halfsizeu, halfsizev, SVector{3,T}(surfacenormal), SVector{3,T}(centrepoint), interface = interface, rotationvec = SVector{3,T}(rotationvec)) end function Rectangle(halfsizeu::T, halfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; interface::NullOrFresnel{T} = NullInterface(T), rotationvec::SVector{3,T} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} @assert halfsizeu > zero(T) && halfsizev > zero(T) n̂ = normalize(surfacenormal) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) new{T}(Plane(n̂, centrepoint, interface = interface), halfsizeu, halfsizev, uvec, vvec) end function Rectangle(plane::Plane{T,3}, halfsizeu::T, halfsizev::T, uvec::SVector{3,T}, vvec::SVector{3,T}) where {T<:Real} new{T}(plane, halfsizeu, halfsizev, uvec, vvec) end end export Rectangle Base.show(io::IO, a::Rectangle{T}) where {T<:Real} = print(io, "Rectangle{$T}($(centroid(a)), $(normal(a)), $(a.halfsizeu), $(a.halfsizev), $(interface(a)))") centroid(r::Rectangle{T}) where {T<:Real} = r.plane.pointonplane uvrange(::Type{Rectangle{T}}) where {T<:Real} = ((-one(T), one(T)), (-one(T), one(T))) """returns a 3D point. This takes into account the offset of centerpoint and the rotation vector used to construct the Rectangle. u and v are scaled by the size of the rectangle so that u=0,v=0 is one corner and u=v=1 is the diagonal corner. This function should go away once we have a sensible object transform hierarchy system.""" function point(r::Rectangle{T},uvs::SMatrix{2,N,T}) where{N,T<:Real} result = MMatrix{3,N,T}(undef) for i in 1:N result[:,i] = point(r,uvs[1,i],uvs[2,i]) end return SMatrix{3,N,T}(result) end """returns a 3D point in the plane of the rectangle. This takes into account the offset of centerpoint and the rotation vector used to construct the Rectangle. u and v are scaled by the size of the rectangle so that u=0,v=0 is one corner and u=v=1 is the diagonal corner. This function should go away once we have a sensible object transform hierarchy system.""" point(r::Rectangle{T}, u::T, v::T) where {T<:Real} = centroid(r) + (r.halfsizeu * u * r.uvec) + (r.halfsizev * v * r.vvec) partials(r::Rectangle{T}, ::T, ::T) where {T<:Real} = r.halfsizeu * r.uvec, r.halfsizev * r.vvec uv(r::Rectangle{T}, p::SVector{3,T}) where {T<:Real} = SVector{2,T}(dot(p - centroid(r), r.uvec) / r.halfsizeu, dot(p - centroid(r), r.vvec) / r.halfsizev) onsurface(a::Rectangle{T}, point::SVector{3,T}) where {T<:Real} = onsurface(a.plane, point) && abs(uv(a, point)[1]) <= one(T) && abs(uv(a, point)[2]) <= one(T) """ uvtopix(surf::Surface{T}, uv::SVector{2,T}, imsize::Tuple{Int,Int}) -> Tuple{Int,Int} Converts a uvcoordinate on `surf` to an integer index to a pixel in an image of size `imsize`. Not implemented on all `Surface` objects. Used to determine where in the detector image a ray has hit when in intersects the detector surface of an [`AbstractOpticalSystem`](@ref). """ function uvtopix(::Rectangle{T}, uv::SVector{2,T}, imsize::Tuple{Int,Int}) where {T<:Real} u, v = uv h, w = imsize pixu = Int(floor((w - 1) * ((u + 1) / 2))) + 1 pixv = h - Int(floor((h - 1) * ((v + 1) / 2))) return pixu, pixv end function surfaceintersection(rect::Rectangle{T}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(rect.plane, r) if interval isa EmptyInterval{T} || isinfiniteinterval(interval) return EmptyInterval(T) # no ray plane intersection or inside plane but no hit else intersect = halfspaceintersection(interval) p = point(intersect) if abs(dot(p - centroid(rect), rect.uvec)) > rect.halfsizeu || abs(dot(p - centroid(rect), rect.vvec)) > rect.halfsizev return EmptyInterval(T) # point outside rect else u, v = uv(rect, p) intuv = Intersection(α(intersect), p, normal(rect), u, v, interface(rect)) if dot(normal(rect), direction(r)) < zero(T) return positivehalfspace(intuv) else return rayorigininterval(intuv) end end end end """returns the 2D vertices in the plane of the rectangle""" vertices(r::Rectangle{T},::Int = 0) where{T<:Real} = SMatrix{2,4}(vertices3d(r)[1:2,:]) """returns the vertices of the rectangle in 3D""" function vertices3d(r::Rectangle{T},::Int = 0) where{T<:Real} pts = SVector{4,SVector{3,T}}( point(r, -one(T), -one(T)), point(r, -one(T), one(T)), point(r, one(T), one(T)), point(r, one(T), -one(T)) ) temp = MMatrix{3,4,T}(undef) for (j,pt) in pairs(pts) for i in 1:3 temp[i,j] = pts[j][i] end end return SMatrix{3,4,T}(temp) end export vertices3d function makemesh(r::Rectangle{T}, ::Int = 0) where {T<:Real} # p00,p01,p10,p11 = vertices(r) p00 = point(r, -one(T), -one(T)) p01 = point(r, -one(T), one(T)) p10 = point(r, one(T), -one(T)) p11 = point(r, one(T), one(T)) if validtri(p00, p11, p01) && validtri(p00, p10, p11) return TriangleMesh([Triangle(p00, p11, p01), Triangle(p00, p10, p11)]) else return nothing end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
14916
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. abstract type StopShape end """ CircularStopShape <: StopShape """ abstract type CircularStopShape <: StopShape end """ RectangularStopShape <: StopShape """ abstract type RectangularStopShape <: StopShape end """ StopSurface{T} <: Surface{T} Abstract type to encapsulate any surfaces acting as a stop. """ abstract type StopSurface{T} <: Surface{T} end """ InfiniteStop{T,P<:StopShape} <: Surface{T} Stop surface with infinite extent (outside of the aperture). `P` refers to the shape of the aperture. """ struct InfiniteStop{T,P<:StopShape} <: StopSurface{T} plane::Plane{T,3} uvec::SVector{3,T} vvec::SVector{3,T} aphalfsizeu::T aphalfsizev::T end export InfiniteStop function surfaceintersection(stop::InfiniteStop{T,CircularStopShape}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(stop.plane, r) if interval isa EmptyInterval{T} return EmptyInterval(T) # no ray plane intersection else intersect = closestintersection(interval) if intersect === nothing # inside plane but no hit return EmptyInterval(T) else d = point(intersect) - centroid(stop) if all(iszero.(d)) || norm(d) < stop.aphalfsizeu return EmptyInterval(T) # no ray plane intersection else return interval # forward interval from plane end end end end function surfaceintersection(stop::InfiniteStop{T,RectangularStopShape}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(stop.plane, r) if interval isa EmptyInterval{T} return EmptyInterval(T) # no ray plane intersection else intersect = closestintersection(interval) if intersect === nothing # inside plane but no hit return EmptyInterval(T) else dif = point(intersect) - centroid(stop) if abs(dot(dif, stop.uvec)) < stop.aphalfsizeu && abs(dot(dif, stop.vvec)) < stop.aphalfsizev return EmptyInterval(T) # no ray plane intersection else return interval # forward interval from plane end end end end interface(::InfiniteStop{T}) where {T<:Real} = opaqueinterface(T) centroid(r::InfiniteStop{T}) where {T<:Real} = r.plane.pointonplane """ FiniteStop{T,P<:StopShape,Q<:StopShape} <: Surface{T} Stop surface with finite extent. `P` refers to the shape of the aperture and `Q` represents the shape of the bounds of the stop surface. """ struct FiniteStop{T,P<:StopShape,Q<:StopShape} <: StopSurface{T} plane::Plane{T,3} uvec::SVector{3,T} vvec::SVector{3,T} innerhalfsizeu::T innerhalfsizev::T outerhalfsizeu::T outerhalfsizev::T end export FiniteStop interface(::FiniteStop{T}) where {T<:Real} = opaqueinterface(T) normal(r::FiniteStop{T}) where {T<:Real} = normal(r.plane) normal(r::FiniteStop{T}, ::T, ::T) where {T<:Real} = normal(r.plane) centroid(r::FiniteStop{T}) where {T<:Real} = r.plane.pointonplane function surfaceintersection(stop::FiniteStop{T,CircularStopShape,CircularStopShape}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(stop.plane, r) if interval isa EmptyInterval{T} return EmptyInterval(T) # no ray plane intersection else intersect = closestintersection(interval) if intersect === nothing # inside plane but no hit return EmptyInterval(T) else d = point(intersect) - centroid(stop) if !all(iszero.(d)) && stop.innerhalfsizeu <= norm(d) <= stop.outerhalfsizeu return interval # forward interval from plane else return EmptyInterval(T) # no ray plane intersection end end end end function surfaceintersection(stop::FiniteStop{T,CircularStopShape,RectangularStopShape}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(stop.plane, r) if interval isa EmptyInterval{T} return EmptyInterval(T) # no ray plane intersection else intersect = closestintersection(interval) if intersect === nothing # inside plane but no hit return EmptyInterval(T) else p = point(intersect) d = p - centroid(stop) if all(iszero.(d)) || norm(d) < stop.innerhalfsizeu return EmptyInterval(T) else dif = p - centroid(stop) du = abs(dot(dif, stop.uvec)) dv = abs(dot(dif, stop.vvec)) if du > stop.outerhalfsizeu || dv > stop.outerhalfsizev return EmptyInterval(T) else return interval end end end end end function surfaceintersection(stop::FiniteStop{T,RectangularStopShape,RectangularStopShape}, r::AbstractRay{T,3}) where {T<:Real} interval = surfaceintersection(stop.plane, r) if interval isa EmptyInterval{T} return EmptyInterval(T) # no ray plane intersection else intersect = closestintersection(interval) if intersect === nothing # inside plane but no hit return EmptyInterval(T) else p = point(intersect) du = abs(dot(p - centroid(stop), stop.uvec)) dv = abs(dot(p - centroid(stop), stop.vvec)) if (du < stop.innerhalfsizeu && dv < stop.innerhalfsizev) || du > stop.outerhalfsizeu || dv > stop.outerhalfsizev return EmptyInterval(T) else return interval end end end end """ RectangularAperture(aphalfsizeu::T, aphalfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; rotationvec::SVector{3,T} = [0.0, 1.0, 0.0]) Creates a rectangular aperture in a plane i.e. `InfiniteStop{T,RectangularStopShape}`. The rotation of the rectangle around its normal is defined by `rotationvec`. `rotationvec×surfacenormal` is taken as the vector along the u axis. """ function RectangularAperture(aphalfsizeu::T, aphalfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; rotationvec::SVector{3,T} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} @assert aphalfsizeu > 0 && aphalfsizev > 0 p = Plane(surfacenormal, centrepoint, interface = opaqueinterface(T)) n̂ = normal(p) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) return InfiniteStop{T,RectangularStopShape}(p, uvec, vvec, aphalfsizeu, aphalfsizev) end """ RectangularAperture(innerhalfsizeu::T, innerhalfsizev::T, outerhalfsizeu::T, outerhalfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; rotationvec::SVector{3,T} = [0.0, 1.0, 0.0]) Creates a rectangular aperture in a rectangle i.e. `FiniteStop{T,RectangularStopShape,RectangularStopShape}`. The rotation of the rectangle around its normal is defined by `rotationvec`. `rotationvec×surfacenormal` is taken as the vector along the u axis. """ function RectangularAperture(innerhalfsizeu::T, innerhalfsizev::T, outerhalfsizeu::T, outerhalfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; rotationvec::SVector{3,T} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} @assert innerhalfsizeu < outerhalfsizeu && innerhalfsizev < outerhalfsizev && innerhalfsizeu > 0 && innerhalfsizev > 0 p = Plane(surfacenormal, centrepoint, interface = opaqueinterface(T)) n̂ = normal(p) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) return FiniteStop{T,RectangularStopShape,RectangularStopShape}(p, uvec, vvec, innerhalfsizeu, innerhalfsizev, outerhalfsizeu, outerhalfsizev) end export RectangularAperture """ CircularAperture(radius::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}) Creates a circular aperture in a plane i.e. `InfiniteStop{T,CircularStopShape}`. """ function CircularAperture(radius::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}) where {T<:Real} @assert radius > 0 p = Plane(surfacenormal, centrepoint, interface = opaqueinterface(T)) return InfiniteStop{T,CircularStopShape}(p, SVector{3,T}(0.0, 0.0, 0.0), SVector{3,T}(0.0, 0.0, 0.0), radius, radius) end """ CircularAperture(radius::T, outerhalfsizeu::T, outerhalfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; rotationvec::SVector{3,T} = [0.0, 1.0, 0.0]) Creates a circular aperture in a rectangle i.e. `FiniteStop{T,CircularStopShape,RectangularStopShape}`. The rotation of the rectangle around its normal is defined by `rotationvec`. `rotationvec×surfacenormal` is taken as the vector along the u axis. """ function CircularAperture(radius::T, outerhalfsizeu::T, outerhalfsizev::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}; rotationvec::SVector{3,T} = SVector{3,T}(0.0, 1.0, 0.0)) where {T<:Real} @assert radius < outerhalfsizeu && radius < outerhalfsizev && radius > 0 p = Plane(surfacenormal, centrepoint, interface = opaqueinterface(T)) n̂ = normal(p) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) return FiniteStop{T,CircularStopShape,RectangularStopShape}(p, uvec, vvec, radius, radius, outerhalfsizeu, outerhalfsizev) end export CircularAperture """ Annulus(innerradius::T, outerradius::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}) Creates a circular aperture in a circle i.e. `FiniteStop{T,CircularStopShape,CircularStopShape}`. """ function Annulus(innerradius::T, outerradius::T, surfacenormal::SVector{3,T}, centrepoint::SVector{3,T}) where {T<:Real} @assert outerradius > innerradius && innerradius > 0 p = Plane(surfacenormal, centrepoint, interface = opaqueinterface(T)) n̂ = normal(p) rotationvec = SVector{3,T}(0.0, 1.0, 0.0) if abs(dot(rotationvec, n̂)) == one(T) rotationvec = SVector{3,T}(1.0, 0.0, 0.0) end uvec = normalize(cross(normalize(rotationvec), n̂)) vvec = normalize(cross(n̂, uvec)) return FiniteStop{T,CircularStopShape,CircularStopShape}(p, uvec, vvec, innerradius, innerradius, outerradius, outerradius) end export Annulus # override makemesh so that we use as few triangles as possible - these can't be CSG objects so we don't need small triangles function makemesh(s::FiniteStop{T,CircularStopShape,CircularStopShape}, subdivisions::Int = 30) where {T<:Real} point(u::T, v::T) = centroid(s) + ((s.innerhalfsizeu + v * (s.outerhalfsizeu - s.innerhalfsizeu)) * (sin(u) * s.uvec + cos(u) * s.vvec)) dθ = T(2π) / subdivisions tris = Vector{Triangle{T}}(undef, subdivisions * 2) @inbounds for i in 0:(subdivisions - 1) θ1 = i * dθ - π θ2 = (i + 1) * dθ - π ip1 = point(θ1, zero(T)) ip2 = point(θ2, zero(T)) op1 = point(θ1, one(T)) op2 = point(θ2, one(T)) tris[i * 2 + 1] = Triangle(ip1, op2, op1) tris[i * 2 + 2] = Triangle(ip1, ip2, op2) end return TriangleMesh(tris) end function makemesh(s::FiniteStop{T,CircularStopShape,RectangularStopShape}, subdivisions::Int = 30) where {T<:Real} point(u::T) = centroid(s) + (s.innerhalfsizeu * (sin(u) * s.uvec + cos(u) * s.vvec)) outeru = s.outerhalfsizeu * s.uvec outerv = s.outerhalfsizev * s.vvec o00 = centroid(s) - outeru - outerv o01 = centroid(s) - outeru + outerv o11 = centroid(s) + outeru + outerv o10 = centroid(s) + outeru - outerv dθ = T(2π) / subdivisions tris = Vector{Triangle{T}}(undef, subdivisions + 4) @inbounds for i in 0:(subdivisions - 1) θ1 = i * dθ - π θ2 = (i + 1) * dθ - π ip1 = point(θ1) ip2 = point(θ2) closestcorner = θ1 < -π / 2 ? o00 : θ1 < 0.0 ? o01 : θ1 < π / 2 ? o11 : o10 tris[i + 1] = Triangle(ip1, ip2, closestcorner) end tris[end - 3] = Triangle(o00, point(ceil(subdivisions / 4) * dθ - π), o01) tris[end - 2] = Triangle(o01, point(ceil(subdivisions / 2) * dθ - π), o11) tris[end - 1] = Triangle(o11, point(ceil(3 * subdivisions / 4) * dθ - π), o10) tris[end] = Triangle(o10, point(-π), o00) return TriangleMesh(tris) end function makemesh(s::FiniteStop{T,RectangularStopShape,RectangularStopShape}, ::Int = 0) where {T<:Real} outeru = s.outerhalfsizeu * s.uvec outerv = s.outerhalfsizev * s.vvec inneru = s.innerhalfsizeu * s.uvec innerv = s.innerhalfsizev * s.vvec o00 = centroid(s) - outeru - outerv o01 = centroid(s) - outeru + outerv o11 = centroid(s) + outeru + outerv o10 = centroid(s) + outeru - outerv i00 = centroid(s) - inneru - innerv i01 = centroid(s) - inneru + innerv i11 = centroid(s) + inneru + innerv i10 = centroid(s) + inneru - innerv u00 = centroid(s) - outeru - innerv u01 = centroid(s) - outeru + innerv u11 = centroid(s) + outeru + innerv u10 = centroid(s) + outeru - innerv t1 = Triangle(o00, o10, u10) t2 = Triangle(o00, u10, u00) t3 = Triangle(u00, i01, u01) t4 = Triangle(u00, i00, i01) t5 = Triangle(u01, o11, o01) t6 = Triangle(u01, u11, o11) t7 = Triangle(i11, i10, u11) t8 = Triangle(u11, i10, u10) return TriangleMesh([t1, t2, t3, t4, t5, t6, t7, t8]) end makemesh(::InfiniteStop, ::Int = 0) = nothing # ----------------------------------------------------- # define the convex polygon stop shape # ----------------------------------------------------- struct InfiniteStopConvexPoly{N, T<:Real} <: OpticSim.StopSurface{T} poly::ConvexPolygon{N,T} end export InfiniteStopConvexPoly function surfaceintersection(stop::InfiniteStopConvexPoly{N, T}, r::AbstractRay{T,3}) where {N, T<:Real} interval = surfaceintersection(stop.poly.plane, r) if interval isa EmptyInterval{T} # check if ray intersect with the polygon plane return EmptyInterval(T) # no ray polygon intersection else if surfaceintersection(stop.poly, r) isa EmptyInterval{T} # check if ray intersects with the actual polygon return interval # if ray do not intersect the polygon than we return the interval else return EmptyInterval(T) # otherwise we indicate no intersection end end end interface(::InfiniteStopConvexPoly) = opaqueinterface(T) centroid(r::InfiniteStopConvexPoly{N, T}) where {N, T<:Real} = r.plane.pointonplane makemesh(::InfiniteStopConvexPoly, ::Int = 0) = nothing
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
6701
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ Triangle{T} <: Surface{T} Triangular surface, not a valid CSG object. Primarily used as a component part of [`TriangleMesh`](@ref) or to enable intersection of [`AcceleratedParametricSurface`](@ref)s. Can never be used directly as an optical surface as it doesn't have an [`OpticalInterface`](@ref). ```julia Triangle(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}, [uv1::SVector{2,T}, uv2::SVector{2,T}, uv3::SVector{2,T}]) ``` """ struct Triangle{T} <: Surface{T} A::SVector{3,T} B::SVector{3,T} C::SVector{3,T} uv1::SVector{2,T} uv2::SVector{2,T} uv3::SVector{2,T} BA::SVector{3,T} CA::SVector{3,T} normal::SVector{3,T} function Triangle(A::SVector{3,T}, B::SVector{3,T}, C::SVector{3,T}, uv1::SVector{2,T}, uv2::SVector{2,T}, uv3::SVector{2,T}) where {T<:Real} BA = B - A CA = C - A crs = cross(BA, CA) lcrs = norm(crs) # make sure the triangle is valid @assert !samepoint(lcrs, zero(T)) n̂ = crs / lcrs return new{T}(A, B, C, uv1, uv2, uv3, BA, CA, n̂) end function Triangle(v1::AbstractArray{T,1}, v2::AbstractArray{T,1}, v3::AbstractArray{T,1}, uv1::AbstractArray{T,1}, uv2::AbstractArray{T,1}, uv3::AbstractArray{T,1}) where {T<:Real} @assert length(v1) == length(v2) == length(v3) == 3 @assert length(uv1) == length(uv2) == length(uv3) == 2 return Triangle(SVector{3}(v1), SVector{3}(v2), SVector{3}(v3), SVector{2}(uv1), SVector{2}(uv2), SVector{2}(uv3)) end end export Triangle Base.show(io::IO, a::Triangle{T}) where {T<:Real} = print(io, "Triangle{$T}($(a.A), $(a.B), $(a.C))") function Triangle(v1::AbstractArray{T,1}, v2::AbstractArray{T,1}, v3::AbstractArray{T,1}) where {T<:Real} return Triangle(v1, v2, v3, zeros(T, 2), zeros(T, 2), zeros(T, 2)) end function Triangle(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}) where {T<:Real} return Triangle(v1, v2, v3, zeros(SVector{2,T}), zeros(SVector{2,T}), zeros(SVector{2,T})) end centroid(tri::Triangle{T}) where {T<:Real} = (vertex(tri, 1) + vertex(tri, 2) + vertex(tri, 3)) / 3 validtri(v1::SVector{3,T}, v2::SVector{3,T}, v3::SVector{3,T}) where {T<:Real} = !any(isnan.(v1)) && !any(isnan.(v2)) && !any(isnan.(v3)) && !samepoint(norm(cross(v2 - v1, v3 - v1)), zero(T)) vertex(tri::Triangle{T}, i::Int) where {T<:Real} = i == 1 ? tri.A : i == 2 ? tri.B : i == 3 ? tri.C : throw(ErrorException("Invalid index: $i")) vertices(tri::Triangle{T}) where {T<:Real} = (tri.A, tri.B, tri.C) uvvertex(tri::Triangle{T}, i::Int) where {T<:Real} = i == 1 ? tri.uv1 : i == 2 ? tri.uv2 : i == 3 ? tri.uv3 : throw(ErrorException("Invalid index: $i")) point(tri::Triangle{T}, a1::T, a2::T, a3::T) where {T<:Real} = vertex(tri, 1) * a1 + vertex(tri, 2) * a2 + vertex(tri, 3) * a3 uv(tri::Triangle{T}, a1::T, a2::T, a3::T) where {T<:Real} = uvvertex(tri, 1) * a1 + uvvertex(tri, 2) * a2 + uvvertex(tri, 3) * a3 normal(tri::Triangle{T}) where {T<:Real} = tri.normal # returns an Interval representing a half-space. If the ray and normal are pointing in opposite directions then the ray is entering the surface and the half-space will be Interval(surface intersection, +inf). If the ray and normal are pointing in the same directions then the ray is leaving the surface and the half-space will be Interval(-inf,surface intersection) function surfaceintersection(tri::Triangle{T}, r::AbstractRay{T,3}) where {T<:Real} # Möller–Trumbore ray-triangle intersection algorithm D = direction(r) BA = tri.BA CA = tri.CA h = cross(D, CA) a = dot(BA, h) if samepoint(a, zero(T)) return EmptyInterval(T) # This ray is parallel to this triangle end f = one(T) / a s = origin(r) - tri.A δ = f * dot(s, h) if (δ < zero(T) || δ > one(T)) return EmptyInterval(T) # outside tri end q = cross(s, BA) β = f * dot(D, q) if (β < zero(T) || δ + β > one(T)) return EmptyInterval(T) # outside tri end # At this stage we can compute t to find out where the intersection point is on the line. t = f * dot(CA, q) if (t > zero(T)) u, v = δ * uvvertex(tri, 2) + β * uvvertex(tri, 3) + (1 - δ - β) * uvvertex(tri, 1) # these are the uvcoords want to use as starting point for newton iteration. Don't want the u,v which has already computed for the basis vecors BA,CA. n̂ = normal(tri) int = Intersection(t, point(r, t), n̂, u, v, NullInterface(T)) if dot(n̂, D) < zero(T) return positivehalfspace(int) else return rayorigininterval(int) end else return EmptyInterval(T) # wrong side of ray origin end end function makemesh(t::Triangle{T}, ::Int = 0) where {T<:Real} return TriangleMesh([t]) end ########################################################################################################## """ TriangleMesh{T} <: Surface{T} An array of [`Triangle`](@ref)s forming a mesh. Used for visualization purposes only. ```julia TriangleMesh(tris::Vector{Triangle{T}}) ``` """ struct TriangleMesh{T} <: Surface{T} # TODO - make this more efficient, e.g. store unique vertices and indices triangles::Vector{Triangle{T}} function TriangleMesh(tris::Vector{Triangle{T}}) where {T<:Real} return new{T}(tris) end end export TriangleMesh Base.eltype(::TriangleMesh{T}) where {T<:Real} = Triangle{T} function makiemesh(tmesh::TriangleMesh{T}) where {T<:Real} # TODO probably should unify shared verts at this point or already have this stored in the trimesh points = Vector{SVector{3,T}}(undef, length(tmesh.triangles) * 3) indices = Array{UInt32,2}(undef, length(tmesh.triangles), 3) @inbounds @simd for i in 0:(length(tmesh.triangles) - 1) t = tmesh.triangles[i + 1] points[i * 3 + 1] = vertex(t, 1) points[i * 3 + 2] = vertex(t, 2) points[i * 3 + 3] = vertex(t, 3) indices[i + 1, :] = [i * 3 + 1, i * 3 + 2, i * 3 + 3] end return (points, indices) end """ Apply a Transform to a TriangleMesh object """ function Base.:*(a::Transform{T}, tmesh::TriangleMesh{T})::TriangleMesh{T} where {T<:Real} newT = Vector{Triangle{T}}(undef, length(tmesh.triangles)) @inbounds @simd for i in 1:length(tmesh.triangles) newT[i] = a * tmesh.triangles[i] end return TriangleMesh(newT) end """ Apply a Transform to a Triangle object """ Base.:*(a::Transform{T}, t::Triangle{T}) where {T<:Real} = Triangle(a * vertex(t, 1), a * vertex(t, 2), a * vertex(t, 3))
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
812
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. struct AirType <: AbstractGlass end Base.show(io::IO, ::AirType) = print(io, "Air") glassid(::AirType) = GlassID(AIR, 0) glassname(::AirType) = "GlassCat.Air" """ isair(a) -> Bool Tests if a is Air. """ isair(::AirType) = true isair(::AbstractGlass) = false isair(a::GlassID) = a.type === AIR function info(io::IO, ::AirType) println(io, "GlassCat.Air") println(io, "Material representing air, RI is always 1.0 at system temperature and pressure, absorption is always 0.0.") end """ Special glass to represent air. Refractive index is defined to always be 1.0 for any temperature and pressure (other indices are relative to this). """ const Air = AirType()
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
1484
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. module GlassCat using Polynomials using Plots using StringEncodings using Unitful using StaticArrays using Base: @. import Unitful: Length, Temperature, Quantity, Units using Unitful.DefaultSymbols using Pkg using ForwardDiff include("constants.jl") include("GlassTypes.jl") export GlassID, info, glassid, glassname, glassforid include("Air.jl") export Air, isair # include built glass cat source files @assert AGFGLASSCAT_PATH === joinpath(@__DIR__, "data", "jl", "AGFGlassCat.jl") if !isfile(AGFGLASSCAT_PATH) @warn "$(basename(AGFGLASSCAT_PATH)) not found! Running build steps." Pkg.build("OpticSim"; verbose=true) end include("data/jl/AGFGlassCat.jl") # this needs to be literal for intellisense to work include("data/jl/OTHER.jl") # include functionality for managing runtime (dynamic) glass cats: MIL_GLASSES and MODEL_GLASSES include("runtime.jl") export glassfromMIL, modelglass # include functions for searching the glass cats include("search.jl") export glasscatalogs, glassnames, findglass include("utilities.jl") export plot_indices, index, polyfit_indices, absairindex, absorption, drawglassmap # include utility functions for maintaining the AGF source list include("sources.jl") export add_agf # include build utility scripts to make testing them a bit easier include("generate.jl") end # module export GlassCat
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
15493
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. using StaticArrays @enum GlassType MODEL MIL AGF OTHER AIR TEST """ Object identifying a glass, containing a type (e.g. `MODEL`, `MIL`, `OTHER` or `AGF`) depending on how the glass is defined, and an integer ID. Air is `AIR:0`, others are on the form `AGF:N`, for example. """ struct GlassID type::GlassType num::Int end Base.show(io::IO, a::GlassID) = print(io, "$(string(a.type)):$(a.num)") """ Abstract type encapsulating all glasses. """ abstract type AbstractGlass end """ Stores all attributes relating to a glass type specified in an .AGF glass catalog. Never used directly, instead created using catalog glasses, e.g. `GlassCat.SCHOTT.N_BK7`. In order to prevent type ambiguities in OpticSim.jl we can't have this type paramaterized. """ struct Glass <: AbstractGlass ID::GlassID dispform::Int C1::Float64 C2::Float64 C3::Float64 C4::Float64 C5::Float64 C6::Float64 C7::Float64 C8::Float64 C9::Float64 C10::Float64 λmin::Float64 λmax::Float64 D₀::Float64 D₁::Float64 D₂::Float64 E₀::Float64 E₁::Float64 λₜₖ::Float64 temp::Float64 ΔPgF::Float64 PR::Float64 relcost::Float64 TCE::Float64 CR::Float64 status::Int SR::Float64 transmission::Union{Nothing,SVector{100,SVector{3,Float64}}} # could use Vector on 1.5.X, but on 1.6 this causes allocs so we need to use a SVector... transmissionN::Int Nd::Float64 AR::Float64 FR::Float64 exclude_sub::Int Vd::Float64 ignore_thermal_exp::Int p::Float64 meltfreq::Int """Use this function to create custom glasses after build time. This will automatically update internal data structures consistently. The convention is for a family of glasses to be in their own module. Example: module MyGlasses const myglass1 = Glass("$(@__MODULE__).myglass1",....) end using the @__MODULE__ macro is safer then typing the module name. If you decide to change the module name the glass names will automatically be updated. """ function Glass(glassname::String, dispform, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, λmin, λmax, D₀, D₁, D₂, E₀, E₁, λₜₖ, temp, ΔPgF, PR, relcost, TCE, CR, status, SR, transmission, Nd, AR, FR, exclude_sub, Vd, ignore_thermal_exp, p, meltfreq) index = length(AGF_GLASSES) + 1 if any(==(glassname,AGF_GLASS_NAMES)) throw(ErrorException("attempt to add a glass to the glass table that has the same name as an existing glass")) end push!(AGF_GLASS_NAMES,glassname) tempid = GlassID(AGF,index) newglass = Glass(tempid,dispform, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, λmin, λmax, D₀, D₁, D₂, E₀, E₁, λₜₖ, temp, ΔPgF, PR, relcost, TCE, CR, status, SR, transmission, Nd, AR, FR, exclude_sub, Vd, ignore_thermal_exp, p, meltfreq) #add the new glass to the glasses table push!(AGF_GLASSES,newglass) return newglass end """For internal use only. End users should use the other Glass constructor that accepts a glassname rather than an id""" function Glass(ID::GlassID, dispform, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, λmin, λmax, D₀, D₁, D₂, E₀, E₁, λₜₖ, temp, ΔPgF, PR, relcost, TCE, CR, status, SR, transmission, Nd, AR, FR, exclude_sub, Vd, ignore_thermal_exp, p, meltfreq) # need a constructor to massage the transmission data if transmission === nothing transmission_s = nothing transmissionN = -1 else fill = [SVector(0.0, 0.0, 0.0) for _ in 1:(100 - length(transmission))] transmission_s = SVector{100,SVector{3,Float64}}(transmission..., fill...) transmissionN = length(transmission) end return new(ID, dispform, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, λmin, λmax, D₀, D₁, D₂, E₀, E₁, λₜₖ, temp, ΔPgF, PR, relcost, TCE, CR, status, SR, transmission_s, transmissionN, Nd, AR, FR, exclude_sub, Vd, ignore_thermal_exp, p, meltfreq) end end """ glassid(g::AbstractGlass) -> GlassID Get the ID of the glass, see [`GlassID`](@ref). """ glassid(g::Glass) = g.ID """ glassname(g::Union{AbstractGlass,GlassID}) Get the name (including catalog) of the glass, or glass with this ID. """ glassname(g::Glass) = glassname(g.ID) function glassname(ID::GlassID) t, n = ID.type, ID.num if t === MODEL return "GlassCat.ModelGlass.$(n)" elseif t === MIL return "GlassCat.GlassFromMIL.$(n)" elseif t === AIR return "GlassCat.Air" elseif t === OTHER return OTHER_GLASS_NAMES[n] elseif t === AGF return AGF_GLASS_NAMES[n] elseif t === TEST return TEST_GLASS_NAMES[n] else throw(ArgumentError("unsupported GlassID type $t")) end end function Base.show(io::IO, g::Glass) print(io, glassname(g)) end """ glassforid(ID::GlassID) Get the glass for a given ID. """ function glassforid(ID::GlassID) t, n = ID.type, ID.num if t === MODEL return MODEL_GLASSES[n]::Glass elseif t === MIL return MIL_GLASSES[n]::Glass elseif t === AIR return GlassCat.Air elseif t === OTHER return OTHER_GLASSES[n]::Glass elseif t === AGF return AGF_GLASSES[n]::Glass elseif t === TEST return TEST_GLASSES[n]::Glass else throw(ArgumentError("unsupported GlassID type $t")) end end """ info([io::IO], glass::AbstractGlass) Print out all data associated with `glass` in an easily readable format. # Examples ```julia-repl julia> info(GlassCat.RPO.IG4) ID: AGF:52 Dispersion formula: Schott (1) Dispersion formula coefficients: a₀: 6.91189161 a₁: -0.000787956404 a₂: -4.22296071 a₃: 142.900646 a₄: -1812.32748 a₅: 7766.33028 Valid wavelengths: 3.0μm to 12.0μm Reference temperature: 20.0°C Thermal ΔRI coefficients: D₀: 3.24e-5 D₁: 0.0 D₂: 0.0 E₀: 0.0 E₁: 0.0 λₜₖ: 0.0 TCE (÷1e-6): 20.4 Ignore thermal expansion: false Density (p): 4.47g/m³ ΔPgF: 0.0 RI at sodium D-Line (587nm): 1.0 Abbe Number: 0.0 Cost relative to N_BK7: ? Status: Standard (0) Melt frequency: 0 Exclude substitution: false ``` """ function info(io::IO, glass::Glass) D = glass.dispform println(io, "$(rpad("ID:", 50)) $(glass.ID)") if (D == -2) println(io, "$(rpad("Dispersion formula:", 50)) Cauchy (-2)") elseif (D == -1) println(io, "$(rpad("Dispersion formula:", 50)) Fitted for model/MIL glass") else println(io, "$(rpad("Dispersion formula:", 50)) $(DISPFORM_NAMES[D]) ($D)") end println(io, "Dispersion formula coefficients:") if (D == -2) # Cauchy println(io, " $(rpad("A:", 45)) $(glass.C1)") println(io, " $(rpad("B:", 45)) $(glass.C2)") println(io, " $(rpad("C:", 45)) $(glass.C3)") println(io, " $(rpad("D:", 45)) $(glass.C4)") println(io, " $(rpad("E:", 45)) $(glass.C5)") println(io, " $(rpad("F:", 45)) $(glass.C6)") elseif (D == -1) println(io, " $(rpad("C₀:", 45)) $(glass.C1)") println(io, " $(rpad("C₁:", 45)) $(glass.C2)") println(io, " $(rpad("C₂:", 45)) $(glass.C3)") println(io, " $(rpad("C₃:", 45)) $(glass.C4)") elseif (D == 1) # Schott println(io, " $(rpad("a₀:", 45)) $(glass.C1)") println(io, " $(rpad("a₁:", 45)) $(glass.C2)") println(io, " $(rpad("a₂:", 45)) $(glass.C3)") println(io, " $(rpad("a₃:", 45)) $(glass.C4)") println(io, " $(rpad("a₄:", 45)) $(glass.C5)") println(io, " $(rpad("a₅:", 45)) $(glass.C6)") elseif (D == 2) # Sellmeier1 println(io, " $(rpad("K₁:", 45)) $(glass.C1)") println(io, " $(rpad("L₁:", 45)) $(glass.C2)") println(io, " $(rpad("K₂:", 45)) $(glass.C3)") println(io, " $(rpad("L₂:", 45)) $(glass.C4)") println(io, " $(rpad("K₃:", 45)) $(glass.C5)") println(io, " $(rpad("L₃:", 45)) $(glass.C6)") elseif (D == 3) # Herzberger println(io, " $(rpad("A:", 45)) $(glass.C1)") println(io, " $(rpad("B:", 45)) $(glass.C2)") println(io, " $(rpad("C:", 45)) $(glass.C3)") println(io, " $(rpad("D:", 45)) $(glass.C4)") println(io, " $(rpad("E:", 45)) $(glass.C5)") println(io, " $(rpad("F:", 45)) $(glass.C6)") elseif (D == 4) # Sellmeier2 println(io, " $(rpad("A:", 45)) $(glass.C1)") println(io, " $(rpad("B₁:", 45)) $(glass.C2)") println(io, " $(rpad("λ₁:", 45)) $(glass.C3)") println(io, " $(rpad("B₂:", 45)) $(glass.C4)") println(io, " $(rpad("λ₂:", 45)) $(glass.C5)") elseif (D == 5) # Conrady println(io, " $(rpad("n₀:", 45)) $(glass.C1)") println(io, " $(rpad("A:", 45)) $(glass.C2)") println(io, " $(rpad("B:", 45)) $(glass.C3)") elseif (D == 6) # Sellmeier3 println(io, " $(rpad("K₁:", 45)) $(glass.C1)") println(io, " $(rpad("L₁:", 45)) $(glass.C2)") println(io, " $(rpad("K₂:", 45)) $(glass.C3)") println(io, " $(rpad("L₂:", 45)) $(glass.C4)") println(io, " $(rpad("K₃:", 45)) $(glass.C5)") println(io, " $(rpad("L₃:", 45)) $(glass.C6)") println(io, " $(rpad("K₄:", 45)) $(glass.C7)") println(io, " $(rpad("L₄:", 45)) $(glass.C8)") elseif (D == 7) || (D == 8) # HandbookOfOptics1/2 println(io, " $(rpad("A:", 45)) $(glass.C1)") println(io, " $(rpad("B:", 45)) $(glass.C2)") println(io, " $(rpad("C:", 45)) $(glass.C3)") println(io, " $(rpad("D:", 45)) $(glass.C4)") elseif (D == 9) # Sellmeier4 println(io, " $(rpad("A:", 45)) $(glass.C1)") println(io, " $(rpad("B:", 45)) $(glass.C2)") println(io, " $(rpad("C:", 45)) $(glass.C3)") println(io, " $(rpad("D:", 45)) $(glass.C4)") println(io, " $(rpad("E:", 45)) $(glass.C5)") elseif (D == 10) || (D == 12) # Extended1/2 println(io, " $(rpad("a₀:", 45)) $(glass.C1)") println(io, " $(rpad("a₁:", 45)) $(glass.C2)") println(io, " $(rpad("a₂:", 45)) $(glass.C3)") println(io, " $(rpad("a₃:", 45)) $(glass.C4)") println(io, " $(rpad("a₄:", 45)) $(glass.C5)") println(io, " $(rpad("a₅:", 45)) $(glass.C6)") println(io, " $(rpad("a₆:", 45)) $(glass.C7)") println(io, " $(rpad("a₇:", 45)) $(glass.C8)") elseif (D == 11) # Sellmeier5 println(io, " $(rpad("K₁:", 45)) $(glass.C1)") println(io, " $(rpad("L₁:", 45)) $(glass.C2)") println(io, " $(rpad("K₂:", 45)) $(glass.C3)") println(io, " $(rpad("L₂:", 45)) $(glass.C4)") println(io, " $(rpad("K₃:", 45)) $(glass.C5)") println(io, " $(rpad("L₃:", 45)) $(glass.C6)") println(io, " $(rpad("K₄:", 45)) $(glass.C7)") println(io, " $(rpad("L₄:", 45)) $(glass.C8)") println(io, " $(rpad("K₅:", 45)) $(glass.C9)") println(io, " $(rpad("L₅:", 45)) $(glass.C10)") elseif (D == 13) # Extended3 println(io, " $(rpad("a₀:", 45)) $(glass.C1)") println(io, " $(rpad("a₁:", 45)) $(glass.C2)") println(io, " $(rpad("a₂:", 45)) $(glass.C3)") println(io, " $(rpad("a₃:", 45)) $(glass.C4)") println(io, " $(rpad("a₄:", 45)) $(glass.C5)") println(io, " $(rpad("a₅:", 45)) $(glass.C6)") println(io, " $(rpad("a₆:", 45)) $(glass.C7)") println(io, " $(rpad("a₇:", 45)) $(glass.C8)") println(io, " $(rpad("a₈:", 45)) $(glass.C9)") else println(io, " INVALID DISPERSION FORMULA!!") end println(io, "$(rpad("Valid wavelengths:", 50)) $(glass.λmin)μm to $(glass.λmax)μm") println(io, "$(rpad("Reference temperature:", 50)) $(glass.temp)°C") if !isnan(glass.D₀) && (glass.D₀ != 0 || glass.D₁ != 0 || glass.D₂ != 0 || glass.E₀ != 0 || glass.E₁ != 0) println(io, "Thermal ΔRI coefficients:") println(io, " $(rpad("D₀:", 45)) $(glass.D₀)") println(io, " $(rpad("D₁:", 45)) $(glass.D₁)") println(io, " $(rpad("D₂:", 45)) $(glass.D₂)") println(io, " $(rpad("E₀:", 45)) $(glass.E₀)") println(io, " $(rpad("E₁:", 45)) $(glass.E₁)") println(io, " $(rpad("λₜₖ:", 45)) $(glass.λₜₖ)") end println(io, "$(rpad("TCE (÷1e-6):", 50)) $(glass.TCE)") println(io, "$(rpad("Ignore thermal expansion:", 50)) $(glass.ignore_thermal_exp == 1)") println(io, "$(rpad("Density (p):", 50)) $(glass.p)g/m³") println(io, "$(rpad("ΔPgF:", 50)) $(glass.ΔPgF)") println(io, "$(rpad("RI at sodium D-Line (587nm):", 50)) $(glass.Nd)") println(io, "$(rpad("Abbe Number:", 50)) $(glass.Vd)") println(io, "$(rpad("Cost relative to N_BK7:", 50)) $(glass.relcost == -1 ? "?" : glass.relcost)") if glass.CR != -1 || glass.FR != -1 || glass.SR != -1 || glass.AR != -1 || glass.PR != -1 println(io, "Environmental resistance:") println(io, " $(rpad("Climate (CR):", 45)) $(glass.CR == -1 ? "?" : glass.CR)") println(io, " $(rpad("Stain (FR):", 45)) $(glass.FR == -1 ? "?" : glass.FR)") println(io, " $(rpad("Acid (SR):", 45)) $(glass.SR == -1 ? "?" : glass.SR)") println(io, " $(rpad("Alkaline (AR):", 45)) $(glass.AR == -1 ? "?" : glass.AR)") println(io, " $(rpad("Phosphate (PR):", 45)) $(glass.PR == -1 ? "?" : glass.PR)") end println(io, "$(rpad("Status:", 50)) $(STATUS[glass.status + 1]) ($(glass.status))") println(io, "$(rpad("Melt frequency:", 50)) $(glass.meltfreq == -1 ? "?" : glass.meltfreq)") println(io, "$(rpad("Exclude substitution:", 50)) $(glass.exclude_sub == 1)") if glass.transmission !== nothing println(io, "Transmission data:") println(io, "$(lpad("Wavelength", 15))$(lpad("Transmission", 15))$(lpad("Thickness", 15))") for i in 1:(glass.transmissionN) λ, t, τ = glass.transmission[i] println(io, "$(lpad("$(λ)μm", 15))$(lpad(t, 15))$(lpad("$(τ)mm", 15))") end end end info(g::AbstractGlass) = info(stdout, g)
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
1094
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. using Unitful const TEMP_REF = 20.0 const PRESSURE_REF = 1.0 const TEMP_REF_UNITFUL = TEMP_REF * u"°C" export TEMP_REF, PRESSURE_REF const DISPFORM_NAMES = ["Schott", "Sellmeier1", "Herzberger", "Sellmeier2", "Conrady", "Sellmeier3", "HandbookOfOptics1", "HandbookOfOptics2", "Sellmeier4", "Extended1", "Sellmeier5", "Extended2", "Extended3"] const STATUS = ["Standard", "Preferred", "Obsolete", "Special", "Melt"] # paths for GlassCat source file builds const GLASSCAT_DIR = @__DIR__ # contains GlassCat.jl (pre-existing) const AGF_DIR = joinpath(GLASSCAT_DIR, "data", "agf") # contains SCHOTT.agf, SUMITA.agf, etc. const JL_DIR = joinpath(GLASSCAT_DIR, "data", "jl") # contains AGFGlasscat.jl, SCHOTT.jl, etc. const SOURCES_PATH = joinpath(GLASSCAT_DIR, "data", "sources.txt") const AGFGLASSCAT_PATH = joinpath(JL_DIR, "AGFGlassCat.jl") # NOTE: if you change JL_DIR or AGFGLASSCAT_PATH, you also need to change the include statement in GlassCat.jl
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
10074
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. using DelimitedFiles: readdlm # used in agffile_to_catalog using StringEncodings using StaticArrays using Unitful import Unitful: Length, Temperature """ generate_jls(sourcenames::Vector{<:AbstractString}, mainfile::AbstractString, jldir::AbstractString, agfdir::AbstractString; test::Bool = false) Generates .jl files in `jldir`: a `mainfile` and several catalog files. Each catalog file is a module representing a distinct glass catalog (e.g. NIKON, SCHOTT), generated from corresponding AGF files in `agfdir`. These are then included and exported in `mainfile`. In order to avoid re-definition of constants `AGF_GLASS_NAMES` and `AGF_GLASSES` during testing, we have an optional `test` argument. If `true`, we generate a .jl file that defines glasses with `GlassType.TEST` to avoid namespace/ID clashes. """ function generate_jls( sourcenames::Vector{<:AbstractString}, mainfile::AbstractString, jldir::AbstractString, agfdir::AbstractString; test::Bool = false ) glasstype = test ? "TEST" : "AGF" id = 1 catalogfiles = [] glassnames = [] # generate several catalog files (.jl) for catalogname in sourcenames # parse the agffile (.agf) into a catalog (native Julia dictionary) agffile = joinpath(agfdir, "$(catalogname).agf") catalog = agffile_to_catalog(agffile) # parse the catalog into a module string and write it to a catalog file (.jl) id, modstring = catalog_to_modstring(id, catalogname, catalog, glasstype) push!(catalogfiles, "$(catalogname).jl") catalogpath = joinpath(jldir, catalogfiles[end]) @info "Writing $catalogpath" open(catalogpath, "w") do io write(io, modstring) end # track glass names for lookup purposes append!(glassnames, ["$(catalogname).$(glassname)" for glassname in keys(catalog)]) end # generate the parent main file (.jl) agfstrings = [ "export $(join(sourcenames, ", "))", "", ["include(\"$(catalogfile)\")" for catalogfile in catalogfiles]..., "", "const $(glasstype)_GLASS_NAMES = [$(join(repr.(glassnames), ", "))]", "const $(glasstype)_GLASSES = [$(join(glassnames, ", "))]", "" ] @info "Writing $mainfile" open(mainfile, "w") do io write(io, join(agfstrings, "\n")) end end """ Parse a `agffile` (.agf) into a native Dict, `catalogdict`, where each `kvp = (glassname, glassinfo)` is a glass. | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | |:---|:---------|:----------|:------|:------|:----------------------|:--------------|:----------|:----------|:------|:------| | NM | raw name | dispform | ? | Nd | Vd | [exclude_sub | status | meltfreq] | | ED | TCE | ? | p | ΔPgF | [ignore_thermal_exp] | | CD | C1 | C2 | C3 | C4 | C5 | C6 | C7 | C8 | C9 | C10 | | TD | D₀ | D₁ | D₂ | E₀ | E₁ | λₜₖ | temp | | OD | relcost | CR | FR | SR | AR | PR | LD | λmin | λmax | | IT | T1 | T2 | T3 | """ function agffile_to_catalog(agffile::AbstractString) catalogdict = Dict{String,Dict{String}}() # store persistent variables between loops glassname = "" rowbuffer = [] # `rowspecs` provides tuples (keys, defaultvalues) which describe how to parse each tokenized row nullspec = ("", []) rowspecs = Dict( "CC" => nullspec, "GC" => nullspec, "NM" => ( "raw_name dispform _ Nd Vd exclude_sub status meltfreq", [nothing, NaN, nothing, NaN, NaN, 0, 0, 0 ] ), "ED" => ( "TCE _ p ΔPgF ignore_thermal_exp", [NaN, nothing, NaN, NaN, 0 ] ), "CD" => ( join([string('C', i) for i in 1:10], ' '), repeat([NaN], 10) ), "TD" => ( "D₀ D₁ D₂ E₀ E₁ λₜₖ temp", [0, 0, 0, 0, 0, 0, 20 ] ), "OD" => ( "relcost CR FR SR AR PR", repeat([-1], 6) ), "LD" => ( "λmin λmax", [NaN, NaN ] ), "IT" => nullspec, ) # call process_rowbuffer!() when rowbuffer is a vector corresponding to a full AGF row # e.g. rowbuffer = ["OD", -1.0, 5.0, 5.0, 5.0, -1.0, -1.0] # the function will parse the row data into catalogdict and flush the row buffer function process_rowbuffer!() # an empty rowbuffer gets passed at the beginning of each file if isempty(rowbuffer) return end token = rowbuffer[1] # NM and IT need special treatment if token == "NM" glassname = make_valid_name(string(rowbuffer[2])) catalogdict[glassname] = Dict{String,Any}() catalogdict[glassname]["transmission"] = Vector{SVector{3,Float64}}(undef, 0) elseif token == "IT" if rowbuffer[2] != 0 && length(rowbuffer) == 4 push!(catalogdict[glassname]["transmission"], SVector{3,Float64}(rowbuffer[2:4])) end end if token ∉ keys(rowspecs) # unrecognized token: treat the row as a comment (ignore) token = "CC" end rowspec = rowspecs[token] # parse row buffer into catalogdict, according to rowspec for (i, (key, defaultvalue)) in enumerate(zip(split(rowspec[1]), rowspec[2])) value = length(rowbuffer) < i + 1 || rowbuffer[i + 1] == "-" ? defaultvalue : rowbuffer[i + 1] catalogdict[glassname][key] = value end # flush rowbuffer rowbuffer = [] end is_utf8 = isvalid(readuntil(agffile, " ")) # use DelimitedFiles.readdlm to parse the source file conveniently (with type inference) for line in eachrow(readdlm(agffile)) for item in line if !is_utf8 item = decode(Vector{UInt8}(item), "UTF-16") _item = tryparse(Float64, item) item = _item === nothing ? item : _item end if item == "" # eol break elseif item ∈ keys(rowspecs) # process buffer when a token is reached, instead of at eol (see Issue #106) process_rowbuffer!() end push!(rowbuffer, item) end end process_rowbuffer!() return catalogdict end """ Make a valid Julia variable name from an arbitrary string. """ function make_valid_name(name::AbstractString) # remove invalid characters name = replace(name, "*" => "_STAR") name = replace(name, r"""[ ,.:;?!()&-]""" => "_") # cant have module names which are just numbers so add a _ to the start if tryparse(Int, "$(name[1])") !== nothing name = "_" * name end return name end """ Convert a `catalog` dict into a `modstring` which can be written to a Julia source file. """ function catalog_to_modstring( start_id::Integer, catalogname::AbstractString, catalog::Dict{<:AbstractString}, glasstype::AbstractString ) id = start_id isCI = haskey(ENV, "CI") modstrings = [ "module $catalogname", "using ..GlassCat: Glass, GlassID, $glasstype", "export $(join(keys(catalog), ", "))", "" ] for (glassname, glassinfo) in catalog argstring = glassinfo_to_argstring(glassinfo, id, glasstype) push!(modstrings, "const $glassname = Glass($argstring)") id += 1 end append!(modstrings, ["end # module", ""]) # last "" is for \n at EOF return id, join(modstrings, "\n") end """ Convert a `glassinfo` dict into a `docstring` to be prepended to a `Glass` const. """ function glassinfo_to_docstring( glassinfo::Dict{<:AbstractString}, id::Integer, catalogname::AbstractString, glassname::AbstractString, glasstype::AbstractString ) raw_name = glassinfo["raw_name"] == glassname ? "" : " ($(glassinfo["raw_name"]))" pad(str, padding=25) = rpad(str, padding) getinfo(key, default=0.0) = get(glassinfo, key, default) return join([ "\"\"\" $catalogname.$glassname$raw_name", "```", "$(pad("ID:"))$glasstype:$id", "$(pad("RI @ 587nm:"))$(getinfo("Nd"))", "$(pad("Abbe Number:"))$(getinfo("Vd"))", "$(pad("ΔPgF:"))$(getinfo("ΔPgF"))", "$(pad("TCE (÷1e-6):"))$(getinfo("TCE"))", "$(pad("Density:"))$(getinfo("p"))g/m³", "$(pad("Valid wavelengths:"))$(getinfo("λmin"))μm to $(getinfo("λmax"))μm", "$(pad("Reference Temp:"))$(getinfo("temp", 20.0))°C", "```", "\"\"\"" ], "\n") end """ Convert a `glassinfo` dict into an `argstring` to be passed into a `Glass` constructor. """ function glassinfo_to_argstring(glassinfo::Dict{<:AbstractString}, id::Integer, glasstype::AbstractString) argstrings = [] for fn in string.(fieldnames(Glass)) if fn == "ID" push!(argstrings, "GlassID($glasstype, $id)") elseif fn in ["D₀", "D₁", "D₂", "E₀", "E₁", "λₜₖ"] push!(argstrings, repr(get(glassinfo, fn, 0.0))) elseif fn == "temp" push!(argstrings, repr(get(glassinfo, fn, 20.0))) elseif fn == "transmission" v = get(glassinfo, "transmission", nothing) if v === nothing push!(argstrings, repr(nothing)) else str = join(["($(join(a, ", ")))" for a in v], ", ") push!(argstrings, "[$str]") end elseif fn == "transmissionN" continue else push!(argstrings, repr(get(glassinfo, fn, NaN))) end end return join(argstrings, ", ") end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
3827
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. # runtime glass cats const MIL_GLASSES = Dict{Int,Glass}() const MODEL_GLASSES = Vector{Glass}(undef, 0) """ glassfromMIL(glasscode::Union{Float64,Int}) -> Glass Generates a glass object for the given glass code based on U.S. military standard MIL-G-174, see [the MIL specification](http://www.newportglass.com/GeneCd.htm) for further details. The glass code is a six-digit number specifying the glass according to its refractive index `Nd` at d-light (587.5618nm), and its Abbe number `Vd` also taken at d-light. The resulting glass code is the value of `Nd - 1` rounded to three digits, followed by `Vd` rounded to three digits, with all decimal points ignored. For example, N_BK7 has `Nd = 1.5168` and `Vd = 64.17`, giving a six-digit glass code of `517642`. For `Nd > 1.999` the format `1.123642` can be used representing `Nd = 2.123` and `Vd = 64.2`. **Accuracy is poor given the low precision of the input parameters**, the mean error to measured data may be significant. Behavior may differ from other optical simulation tools when using MIL glasses. The approximate dispersion calculation used these glasses is generally only valid for visible wavelengths, in this case a limit of 360nm to 750nm is imposed. # Examples ```julia-repl julia> index(glassfromMIL(517642), 0.5875618) 1.5170003960064509 julia> index(glassfromMIL(1.134642), 0.5875618) 2.1340008686098946 ``` """ function glassfromMIL(glasscode::Int) Nd = floor(Int, glasscode / 1000) / 1000 + 1 Vd = (glasscode - floor(Int, glasscode / 1000) * 1000) / 10 g = _modelglass(Nd, Vd, 0.0, GlassID(MIL, glasscode)) MIL_GLASSES[glasscode] = g return g end function glassfromMIL(glasscode::Float64) @assert glasscode > 1.0 glasscodeid = round(Int, glasscode * 1000000) Nd = floor(Int, glasscode * 1000) / 1000 + 1 Vd = round((glasscode * 1000 - floor(Int, glasscode * 1000)) * 100, digits = 1) g = _modelglass(Nd, Vd, 0.0, GlassID(MIL, glasscodeid)) MIL_GLASSES[glasscodeid] = g return g end """ modelglass(Nd::Float64, Vd::Float64, ΔPgF::Float64) -> Glass Generates a glass object for the given refractive index at d-light (587.5618nm), `Nd`, the Abbe number also at d-light, `Vd`, and partial dispersion, `ΔPgF`. The mean error to measured data for these models is typically small - usually < 0.0001. Behavior may differ from other optical simulation tools when using model glasses. The approximate dispersion calculation used for these glasses is generally only valid for visible wavelengths, in this case a limit of 360nm to 750nm is imposed. # Examples ```julia-repl julia> index(modelglass(1.5168, 64.17, 0.0), 0.5875618) 1.5168003970108495 julia> index(modelglass(1.2344, 61.57, 0.003), 0.678) 1.2329425902693352 ``` """ function modelglass(Nd::Float64, Vd::Float64, ΔPgF::Float64) g = _modelglass(Nd, Vd, ΔPgF, GlassID(MODEL, length(MODEL_GLASSES) + 1)) push!(MODEL_GLASSES, g) return g end function _modelglass(Nd::Float64, Vd::Float64, ΔPgF::Float64, ID::GlassID) # from Schott "TIE-29: Refractive Index and Dispersion" a = ΔPgF + 0.6438 - 0.001682 * Vd # Using fitting results from https://www.gnu.org/software/goptical/manual/Material_Abbe_class_reference.html C1 = a * -6.11873891971188577088 + 1.17752614766485175224 C2 = a * 18.27315722388047447566 + -8.93204522498095698779 C3 = a * -14.55275321129051135927 + 7.91015964461522003148 C4 = a * 3.48385106908642905310 + -1.80321117937358499361 return Glass(ID, -1, C1, C2, C3, C4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.36, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, TEMP_REF, ΔPgF, -1.0, -1.0, 0.0, -1.0, 0, -1.0, nothing, Nd, -1.0, -1.0, 0, Vd, 1, 0.0, 0.0) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
2976
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ glasscatalogs() Returns the complete list of glass catalogs available from GlassCat. ## Example ```julia-repl julia> glasscatalogs() 41-element Array{Any,1}: OpticSim.GlassCat.AMTIR OpticSim.GlassCat.ANGSTROMLINK OpticSim.GlassCat.APEL OpticSim.GlassCat.ARCHER OpticSim.GlassCat.ARTON OpticSim.GlassCat.AUER_LIGHTING OpticSim.GlassCat.BIREFRINGENT ⋮ ``` """ glasscatalogs() = _child_modules(GlassCat) """ glassnames(catalog::Module) Returns the glass names available from a given catalog. # Example ```julia-repl julia> glassnames(GlassCat.CARGILLE) 3-element Array{Any,1}: "OG0607" "OG0608" "OG081160" ``` """ function glassnames(catalog::Module) glass_names = names(catalog, all = true, imported = false) glasses = [] for glass_name in glass_names glass_name_str = string(glass_name) if !occursin("#", glass_name_str) && glass_name_str != "eval" && glass_name_str != "include" && glass_name != nameof(catalog) push!(glasses, glass_name) end end return glasses end """ glassnames() Returns the glass names available from all catalogs. # Example ```julia-repl julia> glassnames() 6-element Array{Pair{Module,Array{Any,1}},1}: OpticSim.GlassCat.CARGILLE => ["OG0607", "OG0608", "OG081160"] OpticSim.GlassCat.HOYA => ["BAC4", "BACD11" … "TAFD65"] OpticSim.GlassCat.NIKON => ["BAF10", "BAF11" … "_7054"] OpticSim.GlassCat.OHARA => ["L_BAL35", "L_BAL35P" … "S_TIM8"] OpticSim.GlassCat.SCHOTT => ["AF32ECO", "BAFN6" … "SFL6"] OpticSim.GlassCat.SUMITA => ["BAF1", "BAF10" … "ZNSF8"] ``` """ glassnames() = [m => glassnames(m) for m in _child_modules(GlassCat)] """ findglass(condition::Function) -> Vector{Glass} Returns the list of glasses which satisfy `condition` where `condition::(Glass -> Bool)`. # Example ```julia-repl julia> findglass(x -> (x.Nd > 2.3 && x.λmin < 0.5 && x.λmax > 0.9)) 8-element Array{GlassCat.Glass,1}: BIREFRINGENT.TEO2_E BIREFRINGENT.PBMOO4 BIREFRINGENT.LINBO3 INFRARED.CLEARTRAN_OLD INFRARED.CLEARTRAN INFRARED.SRTIO3 INFRARED.ZNS_BROAD INFRARED.ZNS_VIS ``` """ function findglass(condition::Function) # TODO - make the condition easier to specify (accessor functions for fields?) out = Vector{Glass}(undef, 0) for g in AGF_GLASSES if condition(g) push!(out, g) end end for g in OTHER_GLASSES if condition(g) push!(out, g) end end return out end function _child_modules(m::Module) ns = names(m, imported = false, all = true) ms = [] for n in ns if n != nameof(m) try x = Core.eval(m, n) if x isa Module push!(ms, x) end catch end end end return ms end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
5629
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. import HTTP import SHA import ZipFile using Pkg function match_agf_basename(s::AbstractString) m = match(r"^([a-zA-Z]+)\.(agf|AGF)$", basename(s)) return m === nothing ? nothing : m[1] end is_alphabetical(s::AbstractString) = match(r"^([a-zA-Z]+)$", s) !== nothing is_duplicate(name::AbstractString, sourcefile::AbstractString) = name ∈ first.(split.(readlines(sourcefile))) """ add_agf(agffile; agfdir = AGF_DIR, sourcefile = SOURCES_PATH, name = nothing, rebuild = true) Copies a file at `agffile` (this can be either a download link or local path) to `agfdir` and appends a corresponding entry to the source list at `sourcefile`. If a `name` is not provided for the catalog, an implicit name is derived from `agffile`. If `rebuild` is true, Pkg.build is called at the end to install the new catalog. """ function add_agf( agffile::AbstractString; agfdir::AbstractString = AGF_DIR, sourcefile::AbstractString = SOURCES_PATH, name::Union{Nothing, AbstractString} = nothing, rebuild::Bool = true ) # check name if name === nothing name = match_agf_basename(agffile) if name === nothing @error "invalid implicit catalog name \"$(basename(agffile))\". Should be purely alphabetical with a .agf/.AGF extension." return end name = uppercase(name) end if !is_alphabetical(name) @error "invalid catalog name \"$name\". Should be purely alphabetical." return end if is_duplicate(name, sourcefile) @error "adding the catalog name \"$name\" would create a duplicate entry in source file $sourcefile" return end # download agffile from url if necessary mkpath(agfdir) dest = joinpath(agfdir, name * ".agf") if isfile(agffile) cp(agffile, dest, force=true) else download_source(dest, agffile) if !isfile(dest) @error "failed to download from $agffile" return end end # append a corresponding entry to the source list at sourcefile sha256sum = SHA.bytes2hex(SHA.sha256(read(dest))) open(sourcefile, "a") do io source = isfile(agffile) ? [name, sha256sum] : [name, sha256sum, agffile] write(io, join(source, ' ') * '\n') end # optional rebuild if rebuild @info "Re-building OpticSim.jl" Pkg.build("OpticSim"; verbose=true) end end """ verify_sources!(sources::AbstractVector{<:AbstractVector{<:AbstractString}}, agfdir::AbstractString) Verify a list of `sources` located in `agfdir`. If AGF files are missing or invalid, try to download them using the information provided in `sources`. Each `source ∈ sources` is a collection of strings in the format `name, sha256sum, url [, POST_data]`, where the last optional string is used to specify data to be sent in a POST request. This allows us to download a greater range of sources (e.g. SUMITA). Modifies `sources` in-place such that only verified sources remain. """ function verify_sources!(sources::AbstractVector{<:AbstractVector{<:AbstractString}}, agfdir::AbstractString) # track missing sources as we go and delete them afterwards to avoid modifying our iterator missing_sources = [] for (i, source) in enumerate(sources) name, sha256sum = source[1:2] agffile = joinpath(agfdir, "$(name).agf") verified = verify_source(agffile, sha256sum) if !verified && length(source) >= 3 # try downloading and re-verifying the source if download information is provided (sources[3:end]) download_source(agffile, source[3:end]...) verified = verify_source(agffile, sha256sum) end if !verified push!(missing_sources, i) end end deleteat!(sources, missing_sources) end """ verify_source(agffile::AbstractString, expected_sha256sum::AbstractString) Verify a source file using SHA256, returning true if successful. Otherwise, remove the file and return false. """ function verify_source(agffile::AbstractString, expected_sha256sum::AbstractString) if !isfile(agffile) @info "[-] Missing file at $agffile" else sha256sum = SHA.bytes2hex(SHA.sha256(read(agffile))) if expected_sha256sum == sha256sum @info "[✓] Verified file at $agffile" return true else @info "[x] Removing unverified file at $agffile (expected $expected_sha256sum, got $sha256sum)" rm(agffile) end end return false end """ download_source(dest::AbstractString, url::AbstractString, POST_data::Union{Nothing,AbstractString} = nothing) Download and unzip an AGF glass catalog from a publicly available source. Supports POST requests. """ function download_source(dest::AbstractString, url::AbstractString, POST_data::Union{Nothing,AbstractString} = nothing) @info "Downloading source file from $url" try headers = ["Content-Type" => "application/x-www-form-urlencoded"] resp = POST_data === nothing ? HTTP.get(url) : HTTP.post(url, headers, POST_data) # save agf file, unzipping if necessary if endswith(url, ".agf") agfdata = resp.body else reader = ZipFile.Reader(IOBuffer(resp.body)) agfdata = read(reader.files[findfirst(f -> endswith(lowercase(f.name), ".agf"), reader.files)]) end write(dest, agfdata) catch e @error e end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
17167
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ absorption(glass::AbstractGlass, wavelength; temperature=20°C, pressure=1Atm) Compute the intensity absorption per mm of `glass` at `wavelength`, optionally at specified `temperature` and `pressure`. Transmission values are linearly interpolated from the adjacent values in the data table of `glass`, if `wavelength` is below the minimum or above the maximum in the table then the nearest value is taken. Absorption is defined as ``\\frac{-\\log(t)}{\\tau}`` where ``t`` is the transmission value and ``\\tau`` is the thickness, both of which are provided in the data table. If unitless, arguments are interpretted as μm, °C and Atm respectively. # Examples ```julia-repl julia> absorption(GlassCat.SUMITA.LAK7, 700u"nm") 0.0006018072325563021 julia> absorption(GlassCat.SCHOTT.N_BK7, 0.55, temperature = 22.0) 0.00016504471175660636 julia> absorption(GlassCat.SCHOTT.PSK3, 532u"nm", temperature = 25u"°C", pressure = 1.3) 0.00020855284788532435 ``` """ function absorption(glass::Glass, wavelength::Length; temperature::Temperature = TEMP_REF_UNITFUL, pressure::Float64 = PRESSURE_REF)::Float64 λ = Float64(ustrip(u"μm", wavelength)) return absorption(glass, λ, temperature = ustrip(Float64, u"°C", temperature), pressure = pressure) end function absorption(glass::Glass, λ::T; temperature::T = T(TEMP_REF), pressure::T = T(PRESSURE_REF))::T where {T<:Real} # if the glass has no transmission data then assume no absorption if glass.transmission === nothing return zero(T) end reference_temp = T(glass.temp) # to work out the wavelength at the reference temperature we need the RIs of air at system temp and at reference temp n_air_at_sys = absairindex(λ, temperature = temperature, pressure = pressure) n_air_at_ref = absairindex(λ, temperature = reference_temp) # scale the wavelength to air at the reference temperature/pressure λ = λ * (n_air_at_sys / n_air_at_ref) tdata = glass.transmission N = glass.transmissionN if λ < tdata[1][1] t = tdata[1][2] τ = tdata[1][3] return T(-log1p(t - 1.0) / τ) elseif λ > tdata[N][1] t = tdata[N][2] τ = tdata[N][3] return T(-log1p(t - 1.0) / τ) else let λlow = 0.0, tlow = 0.0, τlow = 0.0, λhigh = 0.0, thigh = 0.0, τhigh = 0.0 for i in 2:N if λ <= tdata[i][1] λlow, tlow, τlow = tdata[i - 1] λhigh, thigh, τhigh = tdata[i] break end end λhigh = T(λhigh) λlow = T(λlow) δλ = λhigh - λlow @assert τlow == τhigh t = (tlow * (λhigh - λ) / δλ) + (thigh * (λ - λlow) / δλ) return -log1p(t - 1.0) / τhigh end end end function absorption(::AirType, ::Length; temperature::Temperature = TEMP_REF_UNITFUL, pressure::Float64 = PRESSURE_REF)::Float64 return 0.0 end function absorption(::AirType, ::T; temperature::T = T(TEMP_REF), pressure::T = T(PRESSURE_REF))::T where {T<:Real} return zero(T) end """ index(glass::AbstractGlass, wavelength; temperature=20°C, pressure=1Atm) Compute the refractive index of `glass` at `wavelength`, optionally at specified `temperature` and `pressure`. Result is relative to the refractive index of air at given temperature and pressure. If unitless, arguments are interpretted as μm, °C and Atm respectively. **This is defined to always equal 1.0 for Air at any temperature and pressure**, use [`absairindex`](@ref) for the absolute refractive index of air at a given temperature and pressure. # Examples ```julia-repl julia> index(GlassCat.SUMITA.LAK7, 700u"nm") 1.646494204478318 julia> index(GlassCat.SCHOTT.N_BK7, 0.55, temperature = 22.0) 1.51852824383283 julia> index(GlassCat.HOYA.FF1, 532u"nm", temperature = 25u"°C", pressure = 1.3) 1.5144848290944655 ``` """ function index(glass::Glass, wavelength::Length; temperature::Temperature = TEMP_REF_UNITFUL, pressure::Float64 = PRESSURE_REF)::Float64 λ = Float64(ustrip(uconvert(u"μm", wavelength))) return index(glass, λ, temperature = ustrip(Float64, u"°C", temperature), pressure = pressure) end function index(glass::Glass, λ::T; temperature::T = T(TEMP_REF), pressure::T = T(PRESSURE_REF))::T where {T<:Real} # all calculations for the material must be done at the refernce temperature reference_temp = T(glass.temp) # to work out the wavelength at the reference temperature we need the RIs of air at system temp and at reference temp n_air_at_sys = absairindex(λ, temperature = temperature, pressure = pressure) n_air_at_ref = absairindex(λ, temperature = reference_temp) # scale the wavelength to air at the reference temperature/pressure λabs = λ * n_air_at_sys λ = λabs / n_air_at_ref if (λ < glass.λmin) || (λ > glass.λmax) error("Cannot calculate an index for the specified wavelength: $λ, valid range: [$(glass.λmin), $(glass.λmax)].\n") end if glass.dispform == -2 # Cauchy n_rel = T(glass.C1) + (glass.C2 * λ^(-2)) + (glass.C3 * λ^(-4)) + (glass.C4 * λ^(-6)) + (glass.C5 * λ^(-8)) + (glass.C6 * λ^(-10)) elseif glass.dispform == -1 # use fitted result from GOptical: n_rel = T(glass.Nd + (glass.Nd - one(T)) / glass.Vd * (glass.C1 + glass.C2 / λ + glass.C3 / λ^2 + glass.C4 / λ^3)) elseif glass.dispform == 1 # Schott formula_rhs = T(glass.C1) + (glass.C2 * λ^2) + (glass.C3 * λ^(-2)) + (glass.C4 * λ^(-4)) + (glass.C5 * λ^(-6)) + (glass.C6 * λ^(-8)) n_rel = sqrt(formula_rhs) elseif glass.dispform == 2 # Sellmeier1 formula_rhs = (glass.C1 * λ^2 / (λ^2 - glass.C2)) + (glass.C3 * λ^2 / (λ^2 - glass.C4)) + (glass.C5 * λ^2 / (λ^2 - glass.C6)) n_rel = sqrt(formula_rhs + one(T)) elseif glass.dispform == 3 # Herzberger L = one(T) / (λ^2 - T(0.028)) n_rel = T(glass.C1) + (glass.C2 * L) + (glass.C3 * L^2) + (glass.C4 * λ^2) + (glass.C5 * λ^4) + (glass.C6 * λ^6) elseif glass.dispform == 4 # Sellmeier2 formula_rhs = T(glass.C1) + (glass.C2 * λ^2 / (λ^2 - (glass.C3)^2)) + (glass.C4 * λ^2 / (λ^2 - (glass.C5)^2)) n_rel = sqrt(formula_rhs + one(T)) elseif glass.dispform == 5 # Conrady n_rel = T(glass.C1) + (glass.C2 / λ) + (glass.C3 / λ^3.5) elseif glass.dispform == 6 # Sellmeier3 formula_rhs = (glass.C1 * λ^2 / (λ^2 - glass.C2)) + (glass.C3 * λ^2 / (λ^2 - glass.C4)) + (glass.C5 * λ^2 / (λ^2 - glass.C6)) + (glass.C7 * λ^2 / (λ^2 - glass.C8)) n_rel = sqrt(formula_rhs + one(T)) elseif glass.dispform == 7 # HandbookOfOptics1 formula_rhs = T(glass.C1) + (glass.C2 / (λ^2 - glass.C3)) - (glass.C4 * λ^2) n_rel = sqrt(formula_rhs) elseif glass.dispform == 8 # HandbookOfOptics2 formula_rhs = T(glass.C1) + (glass.C2 * λ^2 / (λ^2 - glass.C3)) - (glass.C4 * λ^2) n_rel = sqrt(formula_rhs) elseif glass.dispform == 9 # Sellmeier4 formula_rhs = T(glass.C1) + (glass.C2 * λ^2 / (λ^2 - glass.C3)) + (glass.C4 * λ^2 / (λ^2 - glass.C5)) n_rel = sqrt(formula_rhs) elseif glass.dispform == 10 # Extended1 formula_rhs = T(glass.C1) + (glass.C2 * λ^2) + (glass.C3 * λ^(-2)) + (glass.C4 * λ^(-4)) + (glass.C5 * λ^(-6)) + (glass.C6 * λ^(-8)) + (glass.C7 * λ^(-10)) + (glass.C8 * λ^(-12)) n_rel = sqrt(formula_rhs) elseif glass.dispform == 11 # Sellmeier5 formula_rhs = (glass.C1 * λ^2 / (λ^2 - glass.C2)) + (glass.C3 * λ^2 / (λ^2 - glass.C4)) + (glass.C5 * λ^2 / (λ^2 - glass.C6)) + (glass.C7 * λ^2 / (λ^2 - glass.C8)) + (glass.C9 * λ^2 / (λ^2 - glass.C10)) n_rel = sqrt(formula_rhs + one(T)) elseif glass.dispform == 12 # Extended2 formula_rhs = T(glass.C1) + (glass.C2 * λ^2) + (glass.C3 * λ^(-2)) + (glass.C4 * λ^(-4)) + (glass.C5 * λ^(-6)) + (glass.C6 * λ^(-8)) + (glass.C7 * λ^4) + (glass.C8 * λ^6) n_rel = sqrt(formula_rhs) elseif glass.dispform == 13 # Extended3 formula_rhs = T(glass.C1) + (glass.C2 * λ^2) + (glass.C3 * λ^(4)) + (glass.C4 * λ^(-2)) + (glass.C5 * λ^(-4)) + (glass.C6 * λ^(-6)) + (glass.C7 * λ^(-8)) + (glass.C8 * λ^(-10)) + (glass.C9 * λ^(-12)) n_rel = sqrt(formula_rhs) else @error "Invalid glass dispersion formula" end # get the absolute index of the material n_abs = n_rel * n_air_at_ref # If "TD" is included in the glass data, then include pressure and temperature dependence of the lens # environment. From Schott"s technical report "TIE-19: Temperature Coefficient of the Refractive Index". # The above "n_rel" data are assumed to be from the reference temperature T_ref. Now we add a small change # delta_n to it due to a change in temperature. ΔT = temperature - reference_temp if !isnan(glass.D₀) && abs(ΔT) > 0.0 && (glass.D₀ != 0 || glass.D₁ != 0 || glass.D₂ != 0 || glass.E₀ != 0 || glass.E₁ != 0) Sₜₖ = glass.λₜₖ < 0.0 ? -one(T) : one(T) Δn_abs = ((n_rel^2 - one(T)) / (2.0 * n_rel)) * (glass.D₀ * ΔT + glass.D₁ * ΔT^2 + glass.D₂ * ΔT^3 + ((glass.E₀ * ΔT + glass.E₁ * ΔT^2) / (λ^2 - Sₜₖ * glass.λₜₖ^2))) n_abs = n_abs + Δn_abs end # make the index relative to the RI of the air at the system temperature/pressure again n_rel = n_abs / n_air_at_sys return n_rel end function index(::AirType, ::Length; temperature::Temperature = TEMP_REF_UNITFUL, pressure::Float64 = PRESSURE_REF)::Float64 return 1.0 end function index(::AirType, ::T; temperature::T = T(TEMP_REF), pressure::T = T(PRESSURE_REF))::T where {T<:Real} return one(T) end """ absairindex(wavelength; temperature=20°C, pressure=1Atm) Compute the absolute refractive index of air at `wavelength`, optionally at specified `temperature` and `pressure`. If unitless, arguments are interpretted as μm, °C and Atm respectively. # Examples ```julia-repl julia> absairindex(700u"nm") 1.000271074905147 julia> absairindex(0.7, temperature=27.0) 1.000264738846504 julia> absairindex(532u"nm", temperature = 25u"°C", pressure = 1.3) 1.0003494991178161 ``` """ function absairindex(wavelength::Length; temperature::Temperature = TEMP_REF_UNITFUL, pressure::Float64 = PRESSURE_REF)::Float64 # convert to required units λ = Float64(ustrip(uconvert(u"μm", wavelength))) return absairindex(λ, temperature = ustrip(Float64, u"°C", temperature), pressure = pressure) end function absairindex(λ::T; temperature::T = T(TEMP_REF), pressure::T = T(PRESSURE_REF))::T where {T<:Real} # convert to required units n_ref = one(T) + ((6432.8 + ((2949810.0 * λ^2) / (146.0 * λ^2 - one(T))) + ((25540.0 * λ^2) / (41.0 * λ^2 - one(T)))) * 1e-8) n_rel = one(T) + ((n_ref - one(T)) / (one(T) + (temperature - 15.0) * 0.0034785)) * (pressure / PRESSURE_REF) return n_rel end """ polyfit_indices(wavelengths, n_rel; degree=5) Fit a polynomial to `indices` at `wavelengths`, optionally specifying the `degree` of the polynomial. Returns tuple of array of fitted indices at wavelengths and the polynomial. """ function polyfit_indices(wavelengths::Union{AbstractRange{<:Length},AbstractArray{<:Length,1}}, indices::AbstractArray{<:Number,1}; degree::Int = 5) w = ustrip.(uconvert.(u"μm", wavelengths)) okay = (indices .> 0.0) if !any(okay) return (ones(Float64, size(w)) .* NaN, nothing) end xs = range(-1.0, stop = 1.0, length = length(w[okay])) poly = fit(xs, indices[okay], degree) interp_indices = poly.(xs) # ensure output has all entries out = ones(Float64, size(w)) .* NaN out[okay] = interp_indices return (out, poly) end """ plot_indices(glass::AbstractGlass; polyfit=false, fiterror=false, degree=5, temperature=20°C, pressure=1Atm, nsamples=300, sampling_domain="wavelength") Plot the refractive index for `glass` for `nsamples` within its valid range of wavelengths, optionally at `temperature` and `pressure`. `polyfit` will show a polynomial of optionally specified `degree` fitted to the data, `fiterror` will also show the fitting error of the result. `sampling_domain` specifies whether the samples will be spaced uniformly in "wavelength" or "wavenumber". """ function plot_indices(glass::AbstractGlass; polyfit::Bool = false, fiterror::Bool = false, degree::Int = 5, temperature::Temperature = TEMP_REF_UNITFUL, pressure::Float64 = PRESSURE_REF, nsamples::Int = 300, sampling_domain::String = "wavelength") if isair(glass) wavemin = 380 * u"nm" wavemax = 740 * u"nm" else wavemin = glass.λmin * u"μm" wavemax = glass.λmax * u"μm" end if (sampling_domain == "wavelength") waves = range(wavemin, stop = wavemax, length = nsamples) # wavelength in um elseif (sampling_domain == "wavenumber") sigma_min = 1.0 / wavemax sigma_max = 1.0 / wavemin wavenumbers = range(sigma_min, stop = sigma_max, length = nsamples) # wavenumber in um.^-1 waves = 1.0 ./ wavenumbers else error("Invalid sampling domain, should be \"wavelength\" or \"wavenumber\"") end p = plot(xlabel = "wavelength (um)", ylabel = "refractive index") f = w -> begin try return index(glass, w, temperature = temperature, pressure = pressure) catch return NaN end end indices = [f(w) for w in waves] plot!(ustrip.(waves), indices, color = :blue, label = "From Data") if polyfit (p_indices, _) = polyfit_indices(waves, indices, degree = degree) plot!(ustrip.(waves), p_indices, color = :black, markersize = 4, label = "Polyfit") end if polyfit && fiterror err = p_indices - indices p2 = plot(xlabel = "wavelength (um)", ylabel = "fit error") plot!(ustrip.(waves), err, color = :red, label = "Fit Error") p = plot(p, p2, layout = 2) end plot!(title = "$(glassname(glass)) dispersion") gui(p) end """ drawglassmap(glasscatalog::Module; λ::Length = 550nm, glassfontsize::Integer = 3, showprefixglasses::Bool = false) Draw a scatter plot of index vs dispersion (the derivative of index with respect to wavelength). Both index and dispersion are computed at wavelength λ. Choose glasses to graph using the glassfilterprediate argument. This is a function that receives a Glass object and returns true if the glass should be graphed. If showprefixglasses is true then glasses with names like `F_BAK7` will be displayed. Otherwise glasses that have a leading letter prefix followed by an underscore, such as `F_`, will not be displayed. The index formulas for some glasses may give incorrect results if λ is outside the valid range for that glass. This can give anomalous results, such as indices less than zero or greater than 6. To filter out these glasses set maximumindex to a reasonable value such as 3.0. example: plot only glasses that do not contain the strings "E_" and "J_" drawglassmap(NIKON,showprefixglasses = true,glassfilterpredicate = (x) -> !occursin("J_",string(x)) && !occursin("E_",string(x))) """ function drawglassmap(glasscatalog::Module; λ::Length = 550nm, glassfontsize::Integer = 3, showprefixglasses::Bool = false, minindex = 1.0, maxindex = 3.0, mindispersion = -.3, maxdispersion = 0.0, glassfilterpredicate = (x)->true) wavelength = Float64(ustrip(uconvert(μm, λ))) indices = Vector{Float64}(undef,0) dispersions = Vector{Float64}(undef,0) glassnames = Vector{String}(undef,0) for name in names(glasscatalog) glass = eval(:($glasscatalog.$name)) glassstring = String(name) hasprefix = occursin("_", glassstring) if typeof(glass) !== Module && (minindex <= index(glass, wavelength) <= maxindex) f(x) = index(glass,x) g = x -> ForwardDiff.derivative(f, x); dispersion = g(wavelength) # don't show glasses that have an _ in the name. This prevents cluttering the map with many glasses of # similar (index, dispersion). if glassfilterpredicate(glass) && (mindispersion <= dispersion <= maxdispersion) && (showprefixglasses || !hasprefix) push!(indices, index(glass, wavelength)) push!(dispersions, dispersion) push!(glassnames, String(name)) end end end font = Plots.font(family = "Sans", pointsize = glassfontsize, color = RGB(0.0,0.0,.4)) series_annotations = Plots.series_annotations(glassnames, font) scatter( dispersions, indices; series_annotations, markeralpha = 0.0, legends = :none, xaxis = "dispersion @$λ", yaxis = "index", title = "Glass Catalog: $glasscatalog", xflip = true) #should use markershape = :none to prevent markers from being drawn but this option doesn't work. Used markeralpha = 0 so the markers are invisible. A hack which works. end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
6103
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. export CARGILLE, EYE # all other glasses should follow the format below, new glasses must be added to OTHER_GLASSES and OTHER_GLASS_NAMES where the index in the array matches the numeric part of the GlassID module CARGILLE using ..GlassCat: Glass, GlassID, OTHER const OG0608 = Glass(GlassID(OTHER, 1), -2, 1.4451400, 0.0043176, -1.80659e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.0009083144750540808, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.008, -1.0, -1.0, 800.0, -1.0, 0, -1.0, [(0.32, 0.03, 10.0), (0.365, 0.16, 100.0), (0.4047, 0.40, 100.0), (0.480, 0.71, 100.0), (0.4861, 0.72, 100.0), (0.5461, 0.80, 100.0), (0.5893, 0.90, 100.0), (0.6328, 0.92, 100.0), (0.6439, 0.95, 100.0), (0.6563, 0.96, 100.0), (0.6943, 0.99, 100.0), (0.840, 0.99, 100.0), (0.10648, 0.74, 100.0), (0.1300, 0.39, 100.0), (0.1550, 0.16, 100.0)], 1.457518, -1.0, -1.0, 0, 57.18978, 0, 0.878, -1) const OG0607 = Glass(GlassID(OTHER, 2), -2, 1.44503, 0.0044096, -2.85878e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.0009083144750540808, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.008, -1.0, -1.0, 700.0, -1.0, 0, -1.0, [(0.32, 0.15, 10.0), (0.365, 0.12, 100.0), (0.4047, 0.42, 100.0), (0.480, 0.78, 100.0), (0.4861, 0.79, 100.0), (0.5461, 0.86, 100.0), (0.5893, 0.90, 100.0), (0.6328, 0.92, 100.0), (0.6439, 0.90, 100.0), (0.6563, 0.92, 100.0), (0.6943, 0.98, 100.0), (0.840, 0.99, 100.0), (0.10648, 0.61, 100.0), (0.1300, 0.39, 100.0), (0.1550, 0.11, 100.0)], 1.457587, -1.0, -1.0, 0, 57.19833, 0, 0.878, -1) const OG081160 = Glass(GlassID(OTHER, 3), -2, 1.49614, 0.00692199, -8.07052e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.000885983052189022, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.014, -1.0, -1.0, 700.0, -1.0, 0, -1.0, [(0.32, 0.04, 100.0), (0.365, 0.13, 100.0), (0.4047, 0.26, 100.0), (0.480, 0.48, 100.0), (0.4861, 0.49, 100.0), (0.5461, 0.60, 100.0), (0.5893, 0.68, 100.0), (0.6328, 0.71, 100.0), (0.6439, 0.73, 100.0), (0.6563, 0.74, 100.0), (0.6943, 0.76, 100.0), (0.840, 0.83, 100.0), (0.10648, 0.86, 100.0), (0.1300, 0.89, 100.0), (0.1550, 0.90, 100.0)], 1.515549, -1.0, -1.0, 0, 36.82493, 0, 1.11, -1) end module EYE using ..GlassCat: Glass, GlassID, OTHER """ EYE.AQUEOUS ``` ID: OTHER:4 RI @ 587nm: 1.336981 Abbe Number: 52.658991 ΔPgF: 0.0 TCE (÷1e-6): 0.0 Density: 1.0g/m³ Valid wavelengths: 0.38μm to 0.78μm Reference Temp: 20.0°C ``` """ const AQUEOUS = Glass(GlassID(OTHER, 4), 5, 1.32107278, 0.00847113739, 0.000231825063, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.336981, -1.0, -1.0, 0, 52.658991, 0, 1.0, 0) """ EYE.LENS ``` ID: OTHER:5 RI @ 587nm: 1.419976 Abbe Number: 51.226142 ΔPgF: 0.0 TCE (÷1e-6): 0.0 Density: 1.0g/m³ Valid wavelengths: 0.38μm to 0.78μm Reference Temp: 20.0°C ``` """ const LENS = Glass(GlassID(OTHER, 5), 5, 1.4014679, 0.00938901135, 0.000393175776, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.419976, -1.0, -1.0, 0, 51.226142, 0, 1.0, 0) """ EYE.CORNEA ``` ID: OTHER:6 RI @ 587nm: 1.376981 Abbe Number: 56.279936 ΔPgF: 0.0 TCE (÷1e-6): 0.0 Density: 1.0g/m³ Valid wavelengths: 0.38μm to 0.78μm Reference Temp: 20.0°C ``` """ const CORNEA = Glass(GlassID(OTHER, 6), 5, 1.36313817, 0.00667127181, 0.000386916734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.376981, -1.0, -1.0, 0, 56.279936, 0, 1.0, 0) """ EYE.VITREOUS ``` ID: OTHER:7 RI @ 587nm: 1.335982 Abbe Number: 53.342173 ΔPgF: 0.0 TCE (÷1e-6): 0.0 Density: 1.0g/m³ Valid wavelengths: 0.38μm to 0.78μm Reference Temp: 20.0°C ``` """ const VITREOUS = Glass(GlassID(OTHER, 7), 5, 1.32238376, 0.00672767909, 0.000333967702, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.335982, -1.0, -1.0, 0, 53.342173, 0, 1.0, 0) end const OTHER_GLASSES = [CARGILLE.OG0607, CARGILLE.OG0608, CARGILLE.OG081160, EYE.AQUEOUS, EYE.LENS, EYE.CORNEA, EYE.VITREOUS] const OTHER_GLASS_NAMES = ["CARGILLE.OG0607", "CARGILLE.OG0608", "CARGILLE.OG081160", "EYE.AQUEOUS", "EYE.LENS", "EYE.CORNEA", "EYE.VITREOUS"]
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
14364
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. module NotebooksUtils import ...OpticSim # import Pluto import PlutoUI # import Markdown import Format import Makie import WGLMakie import GLMakie import JSServe mutable struct Defs authors::String # authors desc::String # description of the notebook width::Int64 html::String # work area to accumulate html syntaxt in order to save cell space (ouput at the end of a single cell) end Defs() = Defs("?Authors?") Defs(authors) = Defs(authors, "") Defs(authors, desc) = Defs(authors, desc, 1000, "") function fix_path(path) return replace(abspath(path), "\\"=>"/") end """ function run(notebook_filename) Launch Pluto and allow teh user to open a specific notebook. """ function run(notebook_filename) run(; path=notebook_filename) end """ function run(; port=nothing, path=nothing, sysimage_file=nothing ) Launch Pluto and allow teh user to open a specific notebook. Also allow the usage of a sysimage file for faster loading. """ function run(; port=nothing, path=nothing, sysimage_file=nothing, auto_detect_sysimage = false ) @eval begin import Pluto local file_path = $path local sysimage_file_path = $sysimage_file if (file_path === nothing) @info "Launching Pluto" else file_path = fix_path(file_path) if (!isfile(file_path)) @warn "Can't find the notebook file [$(file_path)] - trying to locate it in samples" base_filename = splitdir(file_path)[2] file_path = fix_path(joinpath(splitdir(splitdir(@__DIR__)[1])[1], "samples", "notebooks", base_filename)) if (!isfile(file_path)) @warn "Can't find the notebook file [$(file_path)] in the samples folder - launching Pluto without a file" else @info "Launching Notebook [$(file_path)]" end else @info "Launching Notebook [$(file_path)]" end end # handling the sysimage file if (sysimage_file_path !== nothing) if (!isfile(sysimage_file_path)) @warn "Can't find the sysimage file [$(sysimage_file_path)] - launching Pluto without a sysimage" sysimage_file_path = nothing end else if ($auto_detect_sysimage) if Sys.iswindows() if (!isfile("JuliaSysimage.dll")) sysimage_file_path = "JuliaSysimage.dll" end elseif Sys.islinux() if (!isfile("JuliaSysimage.so")) sysimage_file_path = "JuliaSysimage.so" end end end end local options = Pluto.Configuration.from_flat_kwargs( port=$port, notebook=file_path, launch_browser=true, host="127.0.0.1", require_secret_for_open_links = false, require_secret_for_access = false, run_notebook_on_load = true, sysimage=sysimage_file_path, # banner = "yes", ) session = Pluto.ServerSession(options=options) Pluto.run(session) end end """ run_sample(sample_name::String) Launch Pluto and allow the user to open a specific sample notebook. If a notebook of the same name exists in the current working folder, it will be opened in Pluto, otherwise, the original sample notebook will be copied to the current folder and be used. This beheviour will prevent users from updating the original sample notebook. """ function run_sample(sample_name::String, edit_original::Bool = false) folder, basename = splitdir(sample_name) filename = "DummyFile,jl" if isempty(folder) if (isfile(basename)) # file already exists in current folder - launch pluto and point to it filename = fix_path(abspath(basename)) else # file does not exists in current directory file_in_samples = fix_path(joinpath(splitdir(splitdir(@__DIR__)[1])[1], "samples", "notebooks", basename)) if (isfile(file_in_samples)) if (edit_original) @warn "You are about to edit the original sample notebook" filename = file_in_samples else # file exists - need to be copied into the current folder src_fn = file_in_samples dst_fn = fix_path(abspath(basename)) @info "Copying the sample notebook [$basename] from the samples directory to the current one\n$src_fn ->\n$dst_fn" cp(src_fn, dst_fn) filename = dst_fn end else # file does not exist in samples - need to issue an error # @error "Can't find a sample notebook named [file_in_samples] - please check again" throw(ArgumentError("Can't find a sample notebook named [$file_in_samples] - please check again" )) end end end @info "Running sample notebook from [$filename]" run(; path=filename) end mutable struct VariableInfo bond::Any html::String end function GetVarInfo(bond) res = VariableInfo(bond, HTMLFromObj(bond)) return res end struct UISlider range::AbstractRange default::Number dec::Int16 end UISlider() = UISlider(1:10, 1, -1) UISlider(r) = UISlider(r, r.start, -1) UISlider(r, def) = UISlider(r, def, -1) # UISlider(r, def, format::String) = UISlider(r, def, format) function Base.show(io::IO, ::MIME"text/html", slider::UISlider) if (slider.dec == -1) print(io, """ <input type="range" min="$(first(slider.range))" step="$(step(slider.range))" max="$(last(slider.range))" value="$(slider.default)" oninput="this.nextElementSibling.value=this.value"> <output>$(slider.default)</output>""") else fmt = "%.$(slider.dec)f" print(io, """ <input type="range" min="$(first(slider.range))" step="$(step(slider.range))" max="$(last(slider.range))" value="$(slider.default)" oninput="this.nextElementSibling.value=parseFloat(this.value).toFixed($(slider.dec))"> <output>$(Format.cfmt( fmt, slider.default ))</output>""") end end function SetDefs(defs::Defs) @info "I'm in SetDefs" ret = PlutoUI.Show(MIME"text/html"(), """ <style> main { max-width: $(defs.width)px; } </style> """) #@info "The return type $(typeof(ret))" return ret end function DefsClearHTML(defs::Defs) defs.html = "" end function DefsAddHTML(defs::Defs, html::String) defs.html = defs.html * html end function DefsHTML(defs::Defs) return defs.html end # we don't need to use this function anymore - we can extract the html of items and use it using the PlutoUI.show command # function SetHTMLMarkdown(val::Bool) # if (val) # @info "SetHTMLMarkdown: Allow Raw HTML Tags in Markdown" # @eval Markdown.htmlesc(io::IO, s::AbstractString) = print(io,s) # else # @info "SetHTMLMarkdown: Original process - Raw HTML is not allowed" # @eval Markdown.htmlesc(io::IO, s::AbstractString) = # for ch in s # print(io, get(Markdown._htmlescape_chars, ch, ch)) # end # end # end """ function SetBackend(defs::Defs, be::String) this is my first comment try """ function SetBackend(defs::Defs, be::String) if (be == "Web") @info "Makie backend set to WEB (WGLMakie)" WGLMakie.activate!() Makie.inline!(true) # for version 0.13 and above else @info "Makie backend set to STATIC (GLMakie)" GLMakie.activate!() Makie.inline!(true) # for version 0.13 and above end end """ function SetDocsBackend(be::String) Sets the backend for documantation images. """ function SetDocsBackend(be::String) if (be == "Web") WGLMakie.activate!() Makie.__init__(); Makie.inline!(true) return JSServe.Page(exportable=true, offline=true) else GLMakie.activate!() Makie.__init__(); Makie.inline!(false) return nothing end end """ InitNotebook(; port=8449) initialize the JSServe package. """ function InitNotebook(; port=8449) @eval begin try import JSServe local port = 8449 # the port you want JSServe.JSSERVE_CONFIGURATION.listen_port[] = port JSServe.JSSERVE_CONFIGURATION.external_url[] = "http://localhost:$(port)" JSServe.JSSERVE_CONFIGURATION.content_delivery_url[] = "http://localhost:$(port)" return JSServe.Page() # needs to get displayed by Pluto catch e @warn "Can't initialize the JSServe package\n$e" end end end function HTMLFromObj(obj) io = IOBuffer() Base.show(io, MIME"text/html"(), obj) res = String(take!(io)) return res end # function MDFromString(str) # # SetHTMLMarkdown(true) # io = IOBuffer(str) # res_md = Markdown.parse(io, ) # # SetHTMLMarkdown(false) # return res_md # end function HTMLFix(html::String) html = replace(html, "\r" => "") html = replace(html, "\n" => "") return html end function HTMLFloatingBox(items; name="plutoui-genericfloatingbox", header="?? header ??", kwargs...) res = "" res = res * """<nav class="$name aside indent">""" * """<header>$header</header>""" * """<section>""" * """<span>""" for item in items item_level = 1 if (startswith(item, "@ ")) item_level = 2 elseif (startswith(item, "@@ ")) item_level = 3 elseif (startswith(item, "@@@ ")) item_level = 4 elseif (startswith(item, "@@@@ ")) item_level = 5 elseif (startswith(item, "@@@@@ ")) item_level = 6 elseif (startswith(item, "@@@@@@ ")) item_level = 7 end if (startswith(item, "@")) item2 = item[item_level+2:end] else item2 = item end # println("Item [$item] Level [$item_level]") res = res * """<div class="params-row">""" * """<p class = "H$item_level">""" * item2 * """</p>""" * """</div>""" * """\n""" #Input: $(@bind nnnn MySlider(1:100, 10)) end # closing the nav tags res = res * """</span>""" * """</section>""" * """</nav>""" # add the style for this floating box res = res * HTMLFloatingBoxStyle(name; kwargs...) return HTMLFix(res) end function HTMLFloatingBoxStyle(name::String; right="1rem", top="20rem", width="25%", kwargs...) @info "HTMLFloatingBoxStyle: right=$right, top=$top, width=$width" res = """<style> @media screen and (min-width: 1081px) { .$name.aside { position: fixed; right: $right; top: $top; width: $width; padding: 10px; border: 3px solid rgba(0, 0, 0, 0.15); border-radius: 10px; box-shadow: 0 0 11px 0px #00000010; max-height: 500px; overflow: auto; z-index: 5; background: white; } } .$name header { display: block; font-size: 1.5em; margin-top: 0.67em; margin-bottom: 0.67em; margin-left: 0; margin-right: 0; font-weight: bold; border-bottom: 2px solid rgba(0, 0, 0, 0.15); } .$name section .params-row { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding-bottom: 2px; } .highlight-pluto-cell-shoulder { background: rgba(0, 0, 0, 0.05); background-clip: padding-box; } .$name section a { text-decoration: none; font-weight: normal; color: gray; } /* hover */ .$name section a:hover { color: black; } /* a-ref indentation */ .$name.indent section a.H1 { font-weight: 700; line-height: 1em; } .$name.indent section a.H1 { padding-left: 0px; } .$name.indent section a.H2 { padding-left: 10px; } .$name.indent section a.H3 { padding-left: 20px; } .$name.indent section a.H4 { padding-left: 30px; } .$name.indent section a.H5 { padding-left: 40px; } .$name.indent section a.H6 { padding-left: 50px; } /* paragraph indentation */ .$name.indent section p.H1 { font-weight: 700; line-height: 1em; } .$name.indent section p.H1 { padding-left: 0px; } .$name.indent section p.H2 { padding-left: 10px; } .$name.indent section p.H3 { padding-left: 20px; } .$name.indent section p.H4 { padding-left: 30px; } .$name.indent section p.H5 { padding-left: 40px; } .$name.indent section p.H6 { padding-left: 50px; } </style>""" return HTMLFix(res) end function HTMLNewDocLayout() res = """ <style> body { display: block; } main { max-width: 73%; padding-left: 50px; width: 100%; } </style> """ return HTMLFix(res) end function HTMLFixTOC() res = """ <style> @media screen and (min-width: 1081px) { .plutoui-toc.aside { top: 4%; max-height: 40%; } } </style """ return HTMLFix(res) end end # module NotebooksUtils export NotebooksUtils
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
8575
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. mᵢandmₜ(matout, matin, surfacenormal::SVector{N,T}, r::AbstractRay{T,N}) where {T<:Real,N} = dot(surfacenormal, direction(r)) < zero(T) ? (matout, matin) : (matin, matout) """ snell(surfacenormal::AbstractVector{T}, raydirection::AbstractVector{T}, nᵢ::T, nₜ::T) -> Tuple{T,T} `nᵢ` is the index of refraction on the incidence side of the interface. `nₜ` is the index of refraction on the transmission side. Returns `sinθᵢ` and `sinθₜ` according to [Snell's law](https://en.wikipedia.org/wiki/Snell%27s_law). """ function snell(surfacenormal::S, raydirection::S, nᵢ::T, nₜ::T) where {T<:Real,S<:AbstractArray{T}} # snells law: nᵢsin(θᵢ) = nₜsin(θₜ) # sin(θ) = sin(180-θ) so don't have to worry about reversing sign of r # prevent div by 0 if surfacenormal == raydirection || surfacenormal == -raydirection return zero(T), zero(T) end sinθᵢ = norm(cross(surfacenormal, raydirection)) #only interested in magnitude not direction of the vector normal to surfacenormal and raydirection. # If wanted vector then should use -raydirection. @assert zero(T) <= sinθᵢ sinθₜ = nᵢ / nₜ * sinθᵢ @assert zero(T) <= sinθₜ return sinθᵢ, sinθₜ end function reflectedray(surfacenormal::S, raydirection::S) where {T<:Real,S<:AbstractArray{T}} r = raydirection nₛ = surfacenormal tdot = dot(r, nₛ) if tdot == zero(T) return -r end return r - 2 * nₛ * (tdot) end function refractedray(incidenceindex::T, transmittedindex::T, surfacenormal::S, raydirection::S) where {T<:Real,S<:AbstractArray{T,1}} sinθᵢ, sinθₜ = snell(surfacenormal, raydirection, incidenceindex, transmittedindex) # (nᵢ, nₜ) = nᵢandnₜ(incidenceindex, transmittedindex, surfacenormal, raydirection) #redundant computation here checking for nₛ⋅r < 0 in two places. # Optimize later if compiler doesn't optimize this away by inlining. if (sinθᵢ >= transmittedindex / incidenceindex) # 100% reflectance, zero transmission return nothing else nₛ = surfacenormal r = raydirection sgn = sign(dot(nₛ, r)) pₜ = r - nₛ * dot(r, nₛ) if sinθᵢ == zero(T) refractedparallel = SVector{3,T}(0.0, 0.0, 0.0) else refractedparallel = pₜ * sinθₜ / sinθᵢ end refractedperpendicular = sgn * nₛ * sqrt(one(T) - sinθₜ^2) refracted = refractedparallel + refractedperpendicular return normalize(refracted) end end """ fresnel(nᵢ::T, nₜ::T, sinθᵢ::T, sinθₜ::T) -> Tuple{T,T} Returns reflectance and tranmission power coefficients according to the [Fresnel equations](https://en.wikipedia.org/wiki/Fresnel_equations). For geometric ray tracing this coefficient can be used directly to compute intensity on the detector plane. For Huygens phase optics need to take the square root to compute the amplitude. The power of the transmitted and refracted rays may not sum to one because of the area correction applied to the transmitted component. The intensity per area can increase or decrease depending on the indices of refraction. `nᵢ` is the RI of the material which the incident ray travels in, `nₜ` is the RI of the material the transmitted ray travels in. `sinθᵢ` and `sinθₜ` are the sin of the angles of incidence and transmission respectively. """ function fresnel(nᵢ::T, nₜ::T, sinθᵢ::T, sinθₜ::T) where {T<:Real} if (sinθᵢ >= nₜ / nᵢ) # 100% reflectance, zero transmission return (one(T), zero(T)) end cosθₜ = sqrt(one(T) - sinθₜ^2) cosθᵢ = sqrt(one(T) - sinθᵢ^2) # nᵢ*sin(θᵢ) = nₜ*sin(θₜ) rparallel = ((nᵢ * cosθₜ - nₜ * cosθᵢ) / (nᵢ * cosθₜ + nₜ * cosθᵢ))^2 tparallel = (2nᵢ * cosθᵢ / (nᵢ * cosθₜ + nₜ * cosθᵢ))^2 rperp = ((nᵢ * cosθᵢ - nₜ * cosθₜ) / (nᵢ * cosθᵢ + nₜ * cosθₜ))^2 tperp = (2nᵢ * cosθᵢ / (nᵢ * cosθᵢ + nₜ * cosθₜ))^2 # transmitted amplitude scale factor Tₐ = ((nₜ * cosθₜ) / (nᵢ * cosθᵢ)) # assuming random polarization ravg = 0.5 * (rparallel + rperp) tavg = 0.5 * (tparallel + tperp) * Tₐ #compensate for change in intensity per area caused by the differing angles of incidence and refraction as well as differing indices. return (ravg, tavg) end ############################################################################################################################ """ processintersection(opticalinterface::OpticalInterface{T}, point::SVector{N,T}, normal::SVector{N,T}, incidentray::OpticalRay{T,N}, temperature::T, pressure::T, ::Bool, firstray::Bool = false) -> Tuple{SVector{N,T}, T, T} Processes an intersection of an [`OpticalRay`](@ref) with an [`OpticalInterface`](@ref), distinct behaviors must be implemented for each subclass of `OpticalInterface`. `point` is the 3D intersection point in global space, `normal` is the surface normal at the intersection point. If `test` is true then the behavior of the ray should be deterministic. `firstray` indicates that this ray is the first segment of the trace and therefore the origin is not offset. The values returned are the normalized direction of the ray after the intersection, the _instantaneous_ power of the ray after the intersection and the optical path length of the ray up to the intersection. `nothing` is returned if the ray should stop here, in order to obtain the correct intensity on the detector through monte carlo integration `nothing` should be returned proportionally to create the correct power distribution. i.e. If the interface should modulate power to 76% then 24% of calls to this function should return `nothing`. """ function processintersection(opticalinterface::FresnelInterface{T}, point::SVector{N,T}, normal::SVector{N,T}, incidentray::OpticalRay{T,N}, temperature::T, pressure::T, test::Bool, firstray::Bool = false) where {T<:Real,N} λ = wavelength(incidentray) mᵢ, mₜ = mᵢandmₜ(outsidematerialid(opticalinterface), insidematerialid(opticalinterface), normal, incidentray) nᵢ = one(T) nₜ = one(T) α = zero(T) if !isair(mᵢ) mat = glassforid(mᵢ)::OpticSim.GlassCat.Glass nᵢ = index(mat, λ, temperature = temperature, pressure = pressure)::T α = absorption(mat, λ, temperature = temperature, pressure = pressure)::T end if !isair(mₜ) nₜ = index(glassforid(mₜ)::OpticSim.GlassCat.Glass, λ, temperature = temperature, pressure = pressure)::T end (sinθᵢ, sinθₜ) = snell(normal, direction(incidentray), nᵢ, nₜ) (powᵣ, powₜ) = fresnel(nᵢ, nₜ, sinθᵢ, sinθₜ) incident_pow = power(incidentray) # optical distance from ray origin to point of intersection in mm. Compensate for the fact that the ray has been slightly shortened. geometricpathlength = norm(point - origin(incidentray)) + (firstray ? zero(T) : T(RAY_OFFSET)) thisraypathlength = nᵢ * geometricpathlength raypathlength = pathlength(incidentray) + thisraypathlength # compute updated power based on absorption coefficient of material using Beer's law internal_trans = one(T) if α > zero(T) internal_trans = exp(-α * geometricpathlength) end # TODO - this is an approximation (total hack) for now until we get better modeling of thin film reflectors, antireflection coatings, etc. powᵣ = max(powᵣ, reflectance(opticalinterface)) * internal_trans powₜ = powₜ * transmission(opticalinterface) * internal_trans # generate new rays using Monte Carlo sampling proportional to power. For most optical surfaces the vast majority of rays will be refracted rays. # So could leave this turned on all the time with little impact on performance and get approximate scattering effects for free. r = !test * rand() # assuming (powᵣ + powₜ) <= 1 (asserted in constructor) if interfacemode(opticalinterface) == Transmit || (interfacemode(opticalinterface) == ReflectOrTransmit && r < powₜ) # refraction raydirection = refractedray(nᵢ, nₜ, normal, direction(incidentray)) raypower = powₜ * incident_pow elseif interfacemode(opticalinterface) == Reflect || (interfacemode(opticalinterface) == ReflectOrTransmit && r < (powᵣ + powₜ)) # reflection raypower = powᵣ * incident_pow raydirection = reflectedray(normal, direction(incidentray)) else return nothing end if raydirection === nothing return nothing else return normalize(raydirection), raypower, raypathlength end end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git
[ "MIT" ]
0.6.0
525b470e4e94930a59024823b40a24756c750a89
code
16597
# MIT license # Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE in the project root for full license information. """ WrapperSurface{T,S<:Surface{T}} <: Surface{T} A generic surface type which serves as a basis for extension of [`Surface`](@ref)s for custom [`OpticalInterface`](@ref) subclasses. Essentially just forwards all `Surface` and `ParametricSurface` methods to a field of the `WrapperSurface` named `surface`. Also provides a generic implementation of [`surfaceintersection`](@ref) which tests for an intersection with the underlying surface and returns either an [`EmptyInterval`](@ref) or a half space (never a closed interval). """ abstract type WrapperSurface{T,S<:Surface{T}} <: Surface{T} end export WrapperSurface # forward all methods, can be specialised if not applicable for subclass interface(r::WrapperSurface{T}) where {T<:Real} = r.interface centroid(r::WrapperSurface{T,S}) where {T<:Real,S<:Surface{T}} = centroid(r.surface::S) normal(r::WrapperSurface{T,S}) where {T<:Real,S<:Surface{T}} = normal(r.surface::S) normal(r::WrapperSurface{T}, ::T, ::T) where {T<:Real} = normal(r) point(r::WrapperSurface{T,S}, u::T, v::T) where {T<:Real,S<:Surface{T}} = point(r.surface::S, u, v) uv(r::WrapperSurface{T,S}, x::T, y::T, z::T) where {T<:Real,S<:Surface{T}} = uv(r, SVector{3,T}(x, y, z)) uv(r::WrapperSurface{T,S}, p::SVector{3,T}) where {T<:Real,S<:Surface{T}} = uv(r.surface::S, p) uvrange(::Type{WrapperSurface{T,S}}) where {T<:Real,S<:Surface{T}} = uvrange(S) uvrange(::WrapperSurface{T,S}) where {T<:Real,S<:Surface{T}} = uvrange(S) onsurface(a::WrapperSurface{T,S}, x::T, y::T, z::T) where {T<:Real,S<:Surface{T}} = onsurface(a.surface::S, x, y, z) onsurface(a::WrapperSurface{T,S}, p::SVector{3,T}) where {T<:Real,S<:Surface{T}} = onsurface(a.surface::S, p) inside(a::WrapperSurface{T,S}, x::T, y::T, z::T) where {T<:Real,S<:Surface{T}} = inside(a.surface::S, x, y, z) inside(a::WrapperSurface{T,S}, p::SVector{3,T}) where {T<:Real,S<:Surface{T}} = inside(a.surface::S, p) partials(a::WrapperSurface{T,S}, u::T, v::T) where {T<:Real,S<:Surface{T}} = partials(a.surface::S, u, v) makemesh(l::WrapperSurface{T,S}, subdivisions::Int = 20) where {T<:Real,S<:Surface{T}} = makemesh(l.surface::S, subdivisions) function surfaceintersection(l::WrapperSurface{T,S}, r::AbstractRay{T,3}) where {T<:Real,S<:Surface{T}} itvl = surfaceintersection(l.surface::S, r) if itvl isa EmptyInterval{T} return EmptyInterval(T) elseif itvl isa DisjointUnion{T} throw(ErrorException("Grating/HOE must use a simple (planar) surface for now")) else intsct = halfspaceintersection(itvl) u, v = uv(intsct) intsct = Intersection(α(intsct), point(intsct), normal(intsct), u, v, interface(l), flippednormal = flippednormal(intsct)) if dot(normal(intsct), direction(r)) > zero(T) return rayorigininterval(intsct) else return positivehalfspace(intsct) end end end ###################################################################### """ ThinGratingSurface{T,S} <: WrapperSurface{T,S} Surface type for use with [`ThinGratingInterface`](@ref). ```julia ThinGratingSurface(surface::Surface{T}, interface::ThinGratingInterface{T}) ``` """ struct ThinGratingSurface{T,S} <: WrapperSurface{T,S} surface::S interface::ThinGratingInterface{T} ThinGratingSurface(surface::S, interface::ThinGratingInterface{T}) where {T<:Real,S<:Surface{T}} = new{T,S}(surface, interface) end export ThinGratingSurface interface(r::ThinGratingSurface{T}) where {T<:Real} = r.interface function processintersection(opticalinterface::ThinGratingInterface{T}, point::SVector{N,T}, normal::SVector{N,T}, incidentray::OpticalRay{T,N}, temperature::T, pressure::T, test::Bool, firstray::Bool = false) where {T<:Real,N} # we want the surface to work if hit from either side, so we just reverse the normal if it is hit on the back side if dot(direction(incidentray), normal) > zero(T) normal = -normal end mᵢ, mₜ = mᵢandmₜ(outsidematerialid(opticalinterface), insidematerialid(opticalinterface), normal, incidentray) nᵢ = one(T) nₜ = one(T) α = zero(T) if !isair(mᵢ) mat = glassforid(mᵢ)::OpticSim.GlassCat.Glass nᵢ = index(mat, λ, temperature = temperature, pressure = pressure)::T α = absorption(mat, λ, temperature = temperature, pressure = pressure)::T end if !isair(mₜ) nₜ = index(glassforid(mₜ)::OpticSim.GlassCat.Glass, λ, temperature = temperature, pressure = pressure)::T end incident_pow = power(incidentray) # compute updated power based on absorption coefficient of material using Beer's law internal_trans = one(T) if α > zero(T) internal_trans = exp(-α * geometricpathlength) end # optical distance from ray origin to point of intersection in mm. Compensate for the fact that the ray has been slightly shortened. geometricpathlength = norm(point - origin(incidentray)) + (firstray ? zero(T) : T(RAY_OFFSET)) thisraypathlength = nᵢ * geometricpathlength raypathlength = pathlength(incidentray) + thisraypathlength λ = wavelength(incidentray) r = !test * rand() if opticalinterface.period < λ / nₜ # TODO!! what to do in this case? raypower = transmission(opticalinterface, 0) * internal_trans if r >= raypower return nothing end raydirection = direction(incidentray) else # do the diffraction order = rand((opticalinterface.minorder):(opticalinterface.maxorder)) # TODO not the most sensible way to sample this... refl = reflectance(opticalinterface, order) * internal_trans trans = transmission(opticalinterface, order) * internal_trans if r < refl raypower = refl * incident_pow normal = -normal elseif r < trans raypower = trans * incident_pow else return nothing end incident_mag = 2π * nᵢ / λ grating_dir = order * opticalinterface.vector * (2π / opticalinterface.period) u = cross(normal, ((direction(incidentray) * incident_mag) + grating_dir)) output_mag = 2π * nₜ / λ q = output_mag^2 - sum(u .^ 2) if q < zero(T) @warn "Order $order not valid for this configuration, skipping this ray" maxlog = 1 return nothing else raydirection = normalize(normal * sqrt(q) - cross(normal, u)) end end return raydirection, raypower, raypathlength end ###################################################################### """ HologramSurface{T,S} <: WrapperSurface{T,S} Surface type for use with [`HologramInterface`](@ref). ```julia HologramSurface(surface::Surface{T}, interface::HologramInterface{T}) ``` """ struct HologramSurface{T,S} <: WrapperSurface{T,S} surface::S interface::HologramInterface{T} HologramSurface(surface::S, interface::HologramInterface{T}) where {T<:Real,S<:Surface{T}} = new{T,S}(surface, interface) end export HologramSurface """ MultiHologramSurface{T,S} <: WrapperSurface{T,S} Surface type for use with [`MultiHologramInterface`](@ref). ```julia MultiHologramSurface(surface::Surface{T}, interface::MultiHologramInterface{T}) ``` """ struct MultiHologramSurface{T,S} <: WrapperSurface{T,S} surface::S interface::MultiHologramInterface{T} MultiHologramSurface(surface::S, interface::MultiHologramInterface{T}) where {T<:Real,S<:Surface{T}} = new{T,S}(surface, interface) end export MultiHologramSurface function processintersection(opticalinterface::HologramInterface{T}, point::SVector{N,T}, normal::SVector{N,T}, incidentray::OpticalRay{T,N}, temperature::T, pressure::T, test::Bool, firstray::Bool = false) where {T<:Real,N} hitback = dot(direction(incidentray), normal) > zero(T) # we want the surface to work if hit from either side, so we just reverse the normal and interfaces if it is hit on the back side if hitback frontinterface = FresnelInterface{T}(opticalinterface.substratematerial, opticalinterface.aftermaterial) backinterface = FresnelInterface{T}(opticalinterface.substratematerial, opticalinterface.beforematerial) normal = -normal else frontinterface = FresnelInterface{T}(opticalinterface.substratematerial, opticalinterface.beforematerial) backinterface = FresnelInterface{T}(opticalinterface.substratematerial, opticalinterface.aftermaterial) end # refract the incoming ray going from beforematerial to substrate material, can have Fresnel/TI reflections tmp = processintersection(frontinterface, point, normal, incidentray, temperature, pressure, test, firstray) if tmp === nothing return nothing end input_ray, input_power, input_opl = tmp if dot(input_ray, normal) > zero(T) # just reflected of the surface through fresenel reflection or TIR, so return without diffraction return input_ray, input_power, input_opl end λ = wavelength(incidentray) mat = glassforid(opticalinterface.substratematerial)::OpticSim.GlassCat.Glass # get the index of the playback ray in the substrate nₛ = index(mat, λ, temperature = temperature, pressure = pressure)::T # get the index of the recording ray in the substrate nₛrec = index(mat, opticalinterface.recordingλ, temperature = temperature, pressure = pressure)::T # get the index of the recording ray in the material of the signal beam if !isair(opticalinterface.signalrecordingmaterial) signalbeammaterial = glassforid(opticalinterface.signalrecordingmaterial)::OpticSim.GlassCat.Glass nsig = index(signalbeammaterial, opticalinterface.recordingλ, temperature = temperature, pressure = pressure)::T else nsig = one(T) end # get the signal magnitue in the substrate mag_Ksig = 2π * nₛ / opticalinterface.recordingλ # and direction if opticalinterface.signalbeamstate === CollimatedBeam Ksig_raw = opticalinterface.signalpointordir elseif opticalinterface.signalbeamstate === ConvergingBeam Ksig_raw = normalize(opticalinterface.signalpointordir - point) elseif opticalinterface.signalbeamstate === DivergingBeam Ksig_raw = normalize(point - opticalinterface.signalpointordir) else throw(ErrorException("Invalide beam state")) end # refract it for the substrate interface sigonside = dot(Ksig_raw, normal) < zero(T) refr = refractedray(nsig, nₛrec, sigonside ? -normal : normal, Ksig_raw) # TODO not sure normal flip is needed if refr === nothing return nothing end Ksig_refracted = mag_Ksig * refr # get the index of the recording ray in the material of the reference beam if !isair(opticalinterface.referencerecordingmaterial) referencebeammaterial = glassforid(opticalinterface.referencerecordingmaterial)::OpticSim.GlassCat.Glass nref = index(referencebeammaterial, opticalinterface.recordingλ, temperature = temperature, pressure = pressure)::T else nref = one(T) end # get the reference magnitue in the substrate mag_Kref = 2π * nₛ / opticalinterface.recordingλ if opticalinterface.referencebeamstate === CollimatedBeam Kref_raw = opticalinterface.referencepointordir elseif opticalinterface.referencebeamstate === ConvergingBeam Kref_raw = normalize(opticalinterface.referencepointordir - point) elseif opticalinterface.referencebeamstate === DivergingBeam Kref_raw = normalize(point - opticalinterface.referencepointordir) else throw(ErrorException("Invalide beam state")) end # refract it for the substrate interface refonside = dot(Kref_raw, normal) < zero(T) refr = refractedray(nref, nₛrec, refonside ? -normal : normal, Kref_raw) # TODO not sure normal flip is needed if refr === nothing return nothing end Kref_refracted = mag_Kref * refr # check whether we should be doing reflection or transmission isreflection = sigonside != refonside if isreflection # if the vectors are opposite in relation to the normal then the HOE should work in reflection dnormal = normal else # otherwise it is transmission dnormal = -normal end # calulcate the grating vector grating_vec = (Ksig_refracted - Kref_refracted) # choose random order for which Kogelnik is valid if !opticalinterface.include0order order = 1 else order = rand(0:1) end # calculate the magnitudes of input and output incident_mag = 2π * nₛ / λ incident_ray = incident_mag * input_ray # do the diffraction u = cross(dnormal, (incident_ray + order * grating_vec)) output_mag = 2π * nₛ / λ q = output_mag^2 - sum(u .^ 2) if q < zero(T) @warn "Order $order not valid for this configuration, skipping this ray" maxlog = 1 return nothing else diffracted_out = dnormal * sqrt(q) - cross(dnormal, u) end diffracted_out = normalize(diffracted_out) # calculate the efficiency in this case d = opticalinterface.thickness # in microns as λ in microns Δn = opticalinterface.RImodulation σ = incident_ray + grating_vec cₒ = dot(σ, -normal) / incident_mag cᵣ = dot(incident_ray, -normal) / incident_mag υ = (norm(incident_ray)^2 - norm(σ)^2) / (2 * incident_mag) # Kick from Kogelnik eq. 17 ξ = (υ * d) / (2 * cₒ) # Kogelnik eq. 42 ν = (π * Δn * d) / (λ * sqrt(complex(cₒ * cᵣ))) # Kogelnik eq. 42 refl = dot(diffracted_out, normal) > zero(T) if refl # reflected # modulate the power according to Kogelnik - Lossless Dielectric Grating (Reflection) ν = 1im * ν # Kogelnik eq. 55 ξ = -ξ # Kogelnik eq. 55 η = 1 / (1 + (1 - (ξ / ν)^2) / (sinh(sqrt(ν^2 - ξ^2))^2)) # Kogelnik eq. 57, Kick eq. 6 else # refracted # modulate the power according to Kogelnik - Lossless Dielectric Grating (Transmission) η = sin(sqrt(ν^2 + ξ^2))^2 / (1 + (ξ / ν)^2) # Kogelnik eq. 43, Kick eq. 4 end # kill the ray based on efficiency for monte carlo if !(imag(η) == zero(T) && real(η) > zero(T)) @warn "Invalid η: $η" return nothing else if order === 0 k = (1 - real(η)) if !test * rand() >= k return nothing end diffracted_power = input_power * k else k = real(η) if !test * rand() >= k return nothing end diffracted_power = input_power * k end end outray = OpticalRay(point, diffracted_out, diffracted_power, λ) # refract the output ray for the substrate/aftermaterial interface # for refraction back interface is the other way around so reverse normal tmp = processintersection(refl ? frontinterface : backinterface, point, refl ? normal : -normal, outray, temperature, pressure, test, true) if tmp === nothing return nothing end outpur_dir, output_pow, _ = tmp # TODO nothing happening to OPL currently return outpur_dir, output_pow, input_opl end function processintersection(opticalinterface::MultiHologramInterface{T}, point::SVector{N,T}, normal::SVector{N,T}, incidentray::OpticalRay{T,N}, temperature::T, pressure::T, test::Bool, firstray::Bool = false) where {T<:Real,N} # minη = typemax(T) # r = rand(T) # Ση = zero(T) # for i in 1:(opticalinterface.numinterfaces) # int = interface(opticalinterface, i)::HologramInterface{T} # tmp = processintersection(int, point, normal, incidentray, temperature, pressure, scatter, firstray) # if tmp !== nothing # dir, pow, opl = tmp # η = pow / power(incidentray) # Ση += η / opticalinterface.numinterfaces # # @assert Ση <= 1.0 # if r < Ση # # don't modulate the power because we sample the efficiencies proportionally # return dir, power(incidentray), opl # end # end # end # return nothing # when test = true behavior is totally invalid so that the test is deteministic... i = test ? 1 : rand(1:(opticalinterface.numinterfaces)) # TODO definitely not the best way to sample this... int = interface(opticalinterface, i)::HologramInterface{T} return processintersection(int, point, normal, incidentray, temperature, pressure, test, firstray) end
OpticSim
https://github.com/brianguenter/OpticSim.jl.git