text:
"""
optimize : functions associated with optimization of the sequences via MRF (through our ICM-like maximization step).
"""

module optimize

include("utils.jl")
include("types.jl")
include("math.jl")
include("bio_seq.jl")
include("mrf.jl")

using Logging, Distributions

loc_dna_to_num = Dict{Char, Int64}('A' => 1, 'C' => 2, 'G' => 3, 'T' => 4)
mut_base_options = bio_seq.get_base_dict()
precomputed_dicodons = bio_seq.precompute_dicodons()

function compute_partitions(perturbed_sums::Array{Float64, 2}, w1::Array{Float32, 2}, nNodes::Int64, num_rows)
	naive_partitions = perturbed_sums .+ w1'
	many_partitions = sum(reshape(math.mylogsumexp(reshape(naive_partitions', 21, nNodes * num_rows)'), nNodes, num_rows), dims=1)'
	partition_rows = reshape(many_partitions, num_rows, 1)
	return partition_rows
end

#consider all di-states, keep track.
#Basically given positions for mutations, we consider all possible products of mutations and return best options.
#We "keep-track" in the sense that we calculate the score while avoiding unnecessary computation as most factors to pseudolikelihood remain unchanged by local variations.
function ca_ds_kt(wt_vec, nNodes, w1, w2, wt_ull, pv_w1, pv_w2, mut_start, mut_end, possibilities)
	necessary_rows = length(possibilities)

	did_change = 0
	region = utils.define_region(mut_start, mut_end)
	cur_aas = Int64[]
	sub_prot = wt_vec[region][1:end]
	cur_aa = findnext(isone, sub_prot, 1)
	while cur_aa != nothing
		push!(cur_aas, cur_aa)
		cur_aa = findnext(isone, sub_prot, cur_aa + 1)
	end

	muts = region[1] .+ (cur_aas .- 1)
	mod_aa = length(cur_aas)

	take_off = sum(w2[muts, 1:end], dims=1)
	new_pv_w2 = pv_w2 .- take_off

	base_spot = region[1] - 1
	additions = zeros(Float64, necessary_rows, nNodes * 21)
	additional_count = 1

	mapping = Dict{Tuple{Int64, Int64}, Int64}()
	for j in 1:21
		for i in 1:21
			if (i, j) in possibilities #Hopefully this is relatively fast to check... could probably be more efficient.
				mapping[(i, j)] = additional_count #we're going to use this mapping to figure out partition based on (i, j) location.
				additions[additional_count, 1:end] = w2[base_spot + i, 1:end] + w2[base_spot + 21 + j, 1:end]
				additional_count += 1
			end
		end
	end

	perturbed_sums = additions .+ new_pv_w2

	needed_partitions = compute_partitions(perturbed_sums, w1, nNodes, necessary_rows)

	true_ull = new_pv_w2 * wt_vec' .- (wt_vec[region]' * new_pv_w2[region])
	#println(true_ull)
	ull_mat = ones(21) * true_ull[1] * ones(21)'
	all_aa_ull = ull_mat .+ 2*new_pv_w2[1:1, region[1:21]]'
	all_aa_ull = all_aa_ull .+ 2*new_pv_w2[1:1, region[22:42]]
	all_aa_ull = all_aa_ull .+ 2*w2[region[1:21], region[22:42]]

	#Then we are only interested in some of these, so...
	all_aa_ull_rows = Float64[]
	for j in 1:21
		for i in 1:21
			if (i, j) in possibilities
				push!(all_aa_ull_rows, all_aa_ull[i, j])
			end
		end
	end

	w1_ull = ones(21) * ((pv_w1 - w1[region]' * wt_vec[region]) * ones(21)')
	w1_ull = w1_ull .+ w1[region[1:21]]
	w1_ull = w1_ull .+ w1[region[22:42]]'

	w1_ull_rows = Float64[]
	for j in 1:21
		for i in 1:21
			if (i, j) in possibilities
				push!(w1_ull_rows, w1_ull[i, j])
			end
		end
	end

	full_ull_rows = all_aa_ull_rows + w1_ull_rows
	psl_rows = needed_partitions - full_ull_rows

	return full_ull_rows, w1_ull_rows, perturbed_sums, psl_rows, mapping
end

#This is not currently used in CAMEOS but the general form of ca_ds_kt to non-contiguous and possibly more mutations is...
#prot_vec is current protein in one-hot form, aas_to_change is positions of aas to change, aa_possibilities is the possible new aas you can get
#w1, w2, pv_w1, pv_w2, nNodes is w1, w2 (MRF), prot_vec * w1, prot_vec * w2, and nodes in MRF.
#using Combinatorics
#=function general_mut(prot_vec, aas_to_change, aa_possibilities, w1, w2, pv_w1, pv_w2, nNodes)
	#let's assume these are given. Let's further require they be in order for uniqueness sake.
	#sorted_aas = sort(aas_to_change)
	num_poss = length(aa_possibilities)
	num_to_change = length(aas_to_change)

	aa_regions = [((21 * (aa - 1)) + 1: aa * 21) for aa in aas_to_change]
	selected_aa = vcat(aa_regions...)
	active_aa = find(y -> y in selected_aa && prot_vec[y] == 1.0, 1:length(prot_vec))

	take_off = sum(w2[active_aa, 1:end], dims=1)
	new_pv_w2 = pv_w2 .- take_off
	additions = zeros(Float64, num_poss, nNodes * 21) #not sure how to define considered_changes.
	additional_count = 1

	for change_vec in aa_possibilities
		aa_indices = [a_r[1] - 1 for a_r in aa_regions] .+ change_vec #warning that I would've expected a_r[1] - 1 but we got rid of it since didn't match.
		additions[additional_count, 1:end] = sum([w2[aa_i, :] for aa_i in aa_indices], dims=1)[1] #w2[aa_indices[1], :] + w2[aa_indices[2], :]
		additional_count += 1
	end

	jiggle_sums = additions .+ new_pv_w2

	needed_partitions = compute_partitions(jiggle_sums, w1, nNodes, num_poss)

	value = pv_w1 - w1[selected_aa]' * prot_vec[selected_aa]

	aa_coordinates = [[aa_regions[i][aa_possibilities[j][i]] for i in 1:num_to_change] for j in 1:num_poss]

	w1_ull = value .+ [sum([w1[aa_regions[i][aa_possibilities[j][i]]] for i in 1:num_to_change]) for j in 1:num_poss]
	#w1_ull = value .+ [sum([w1[aa_i] for aa_i in aa_coordinates[j]]) for j in 1:num_poss] is a different untested way.
	true_ull = new_pv_w2 * prot_vec' - (prot_vec[selected_aa]' * new_pv_w2[selected_aa])

	outside_w2 = true_ull .+ [2 * sum([new_pv_w2[aa_i] for aa_i in aa_coordinates[j]]) for j in 1:num_poss]
	inner_w2 = 2 * [sum([w2[coord[1], coord[2]] for coord in combinations(aa_coordinates[j], 2)]) for j in 1:num_poss]

	w2_full = outside_w2 + inner_w2

	full_ull_rows = w2_full + w1_ull
	psl_rows = needed_partitions - full_ull_rows

	return psl_rows
end=#

#We avoid mutating in regions with insertions, deletions, or at start/end. This function defines acceptable mutation locations.
function acceptable_muts(site, mutated_nucs, individual, deg_nNodes, mark_nNodes)
	all_mark_aa_pos = Int64[]; all_deg_aa_pos = Int64[]; not_set = false;

	for each_nuc in mutated_nucs
		if each_nuc in individual.deg_skip || each_nuc in individual.mark_skip
			not_set = true
			empty!(all_mark_aa_pos)
			empty!(all_deg_aa_pos)
			break
		end

		if each_nuc in keys(individual.deg_map) && individual.deg_map[each_nuc] < deg_nNodes
			deg_aa_pos = individual.deg_map[each_nuc]
			push!(all_deg_aa_pos, deg_aa_pos)
		elseif each_nuc < individual.deg_trns || each_nuc >= (individual.deg_trne - 6) #-6 because we don't want to mess up last codon and each site hits two.
			push!(all_deg_aa_pos, -1) #-1 will be our indication of "outside bounds"
		else
			not_set = true
			empty!(all_mark_aa_pos)
			empty!(all_deg_aa_pos)
			break
		end

		if each_nuc in keys(individual.mark_map) && individual.mark_map[each_nuc] < mark_nNodes
			mark_aa_pos = individual.mark_map[each_nuc]
			push!(all_mark_aa_pos, mark_aa_pos)
		elseif each_nuc < individual.mark_trns || each_nuc >= (individual.mark_trne - 6)
			push!(all_mark_aa_pos, -1)
		else
			not_set = true
			empty!(all_mark_aa_pos)
			empty!(all_deg_aa_pos)
			break
		end

		if -1 in all_mark_aa_pos || -1 in all_deg_aa_pos #remove if this case is handled.
			not_set = true
		end

	end

	#I don't want to modify the start ATGs so I reject mutations on aa_pos of 1.
	if 1 in all_deg_aa_pos || 1 in all_mark_aa_pos
		not_set = true
	end

	#This is the infA array condition (we don't modify some of the amino acids just by design of array)
	#if 1 in all_deg_aa_pos || 2 in all_deg_aa_pos || 3 in all_deg_aa_pos || 4 in all_deg_aa_pos || 69 in all_deg_aa_pos || 70 in all_deg_aa_pos || 71 in all_deg_aa_pos || 72 in all_deg_aa_pos || 73 in all_deg_aa_pos | 74 in all_deg_aa_pos
		#not_set = true
	#end

	if !(not_set) && ((minimum(all_deg_aa_pos) != (maximum(all_deg_aa_pos) - 1)) || (minimum(all_mark_aa_pos) != (maximum(all_mark_aa_pos) - 1)))
		not_set = true
	end

	return not_set, all_mark_aa_pos, all_deg_aa_pos
end

function icm_multi_kt(population, deg_grem, mark_grem, deg_normal = false, mark_normal = false; use_energy = false, score_cutoff = 0) #this expects Normal objects for logpdf fun.
	#This will allow for than one nucleotide to be changed at once by doing a 2-way aa psl calculation.
	mark_seqs = AbstractString[]
	deg_seqs = AbstractString[]
	mark_psls = Float32[]
	deg_psls = Float32[]
	changed_seq = 0
	iss = Any[]
	deg_w1 = deg_grem.w1
	deg_w2 = deg_grem.w2
	deg_nNodes = deg_grem.nNodes
	mark_w1 = mark_grem.w1
	mark_w2 = mark_grem.w2
	mark_nNodes = mark_grem.nNodes

	the_debug_counter = 0
	for individual in population
		the_debug_counter += 1
		if div(length(individual.deg_vec), 21) != deg_nNodes || div(length(individual.mark_vec), 21) != mark_nNodes
			@debug("Trouble with individual $the_debug_counter at icm_mlti_kt")
			continue
		end

		if score_cutoff != 0 && (abs(individual.deg_prob) + abs(individual.mark_prob)) > score_cutoff #we can choose to only optimize individuals below a score cut-off past a certain point of optimization.
			continue #we skip this guy, the sequence stops changing.
		end

		num_muts = 1
		full_len = length(individual.full_sequence)
		unif_len = DiscreteUniform(1, full_len - 3)
		ind_seq = individual.full_sequence[1:end]
		new_seq = ""
		for mut in 1:num_muts
			site = rand(unif_len)
			mut_len = 3 #floor(Int64, rand() * 3) + 2 #number of nucleotides modified (from 2-4).
			mutated_nucs = site:(site+mut_len)
			all_deg_aa_pos = Int64[]
			all_mark_aa_pos = Int64[] #potentially more than one aa getting hit.
			not_set = false

			not_set, all_mark_aa_pos, all_deg_aa_pos = acceptable_muts(site, mutated_nucs, individual, deg_nNodes, mark_nNodes)
			while not_set
				site = rand(unif_len)
				mut_len = 3 #4 guarantees two aas hit... more generally, floor(Int64, rand() * 3) + 2 migh work.
				mutated_nucs = site:(site+mut_len)
				not_set, all_mark_aa_pos, all_deg_aa_pos = acceptable_muts(site, mutated_nucs, individual, deg_nNodes, mark_nNodes)
			end

			unique_all_mark_aa_pos = sort(unique(all_mark_aa_pos))
			unique_all_deg_aa_pos = sort(unique(all_deg_aa_pos))

			deg_codon = Char[]
			mark_codon = Char[]
			deg_start_pos = -1
			mark_start_pos = -1
			original_nuc = '?'

			for nuc in sort(collect(keys(individual.deg_map)))
				if individual.deg_map[nuc] in all_deg_aa_pos
					push!(deg_codon, uppercase(individual.full_sequence[nuc]))
				end
				if nuc == site
					deg_start_pos = length(deg_codon) #should still work, in order.
					original_nuc = loc_dna_to_num[uppercase(individual.full_sequence[nuc])]
				end
			end
			for nuc in sort(collect(keys(individual.mark_map)))
				if individual.mark_map[nuc] in all_mark_aa_pos
					push!(mark_codon, uppercase(individual.full_sequence[nuc]))
				end
				if nuc == site
					mark_start_pos = length(mark_codon)
				end
			end

			resulting_deg_aas = Tuple{Int64, Int64}[]
			resulting_mark_aas = Tuple{Int64, Int64}[]
			mut_dna_options = mut_base_options[mut_len]

			original_nucs = ""
			dna_nuc_counter = 1
			for dna_nucs in mut_dna_options

				tmp_deg_codon = join(deg_codon[1:(deg_start_pos - 1)]) * (dna_nucs) * join(deg_codon[(deg_start_pos + mut_len):end])
				if tmp_deg_codon == join(deg_codon)
					original_nucs = dna_nuc_counter
				end

				push!(resulting_deg_aas, precomputed_dicodons[tmp_deg_codon])
				dna_nuc_counter += 1
			end
			dna_nuc_counter = 1
			for dna_nucs in mut_dna_options

				tmp_mark_codon = join(mark_codon[1:(mark_start_pos - 1)]) * (dna_nucs) * join(mark_codon[(mark_start_pos + mut_len):end])
				if tmp_mark_codon == join(mark_codon)
					original_nucs = dna_nuc_counter
				end

				push!(resulting_mark_aas, precomputed_dicodons[tmp_mark_codon])
				dna_nuc_counter += 1
			end

			deg_possibilities = filter(z -> !(21 in z), unique(resulting_deg_aas))
			mark_possibilities = filter(z -> !(21 in z), unique(resulting_mark_aas))

			#And then it becomes time to actually compute all these options via some _kt() function.
			deg_ull_opt, deg_pv_w1_opt, deg_pv_w2_opt, deg_psl_opt, deg_cads_map = ca_ds_kt(individual.deg_vec, deg_nNodes, deg_w1, deg_w2, individual.deg_ull, individual.deg_pv_w1, individual.deg_pv_w2, unique_all_deg_aa_pos[1], unique_all_deg_aa_pos[2], deg_possibilities)

			mark_ull_opt, mark_pv_w1_opt, mark_pv_w2_opt, mark_psl_opt, mark_cads_map = ca_ds_kt(individual.mark_vec, mark_nNodes, mark_w1, mark_w2, individual.mark_ull, individual.mark_pv_w1, individual.mark_pv_w2, unique_all_mark_aa_pos[1], unique_all_mark_aa_pos[2], mark_possibilities)

			final_options = zeros(Float32, length(mut_dna_options))
			for iii in 1:length(mut_dna_options)
				if !(21 in resulting_deg_aas[iii]) && !(21 in resulting_mark_aas[iii]) #no stop codons allowed!
					if use_energy && mark_normal && deg_normal
						#We multiply by 2.0 so that the "weight" is more intuitively set from 0-1 but values remain reflective of real psls.
						final_options[iii] = 2.0 * individual.first_weight * abs(logpdf(mark_normal, mark_psl_opt[mark_cads_map[resulting_mark_aas[iii]]])) #abs(logpdf(mark_normal, mark_psl_opt[mark_cads_map[resulting_mark_aas[iii]]]))
						final_options[iii] += 2.0 * (1.0 - individual.first_weight) * abs(logpdf(deg_normal, deg_psl_opt[deg_cads_map[resulting_deg_aas[iii]]]))
					else
						final_options[iii] = 2.0 * individual.first_weight * (mark_psl_opt[mark_cads_map[resulting_mark_aas[iii]]] - individual.mark_base_E)
						final_options[iii] += 2.0 * (1.0 - individual.first_weight) * (deg_psl_opt[deg_cads_map[resulting_deg_aas[iii]]] - individual.deg_base_E)
					end
				else
					final_options[iii] = 1_000_000.0
				end
			end

			min_score, min_choice = findmin(final_options)

			best_deg_aa = resulting_deg_aas[min_choice]
			best_mark_aa = resulting_mark_aas[min_choice]

			new_seq = ind_seq[1:(site - 1)] * mut_dna_options[min_choice] * ind_seq[(site + mut_len):end]

			if new_seq != ind_seq
				changed_seq += 1
			end

			new_deg_dna = new_seq[individual.deg_trns:individual.deg_trne]
			new_mark_dna = new_seq[individual.mark_trns:individual.mark_trne]

			individual.deg_nuc = types.MRF_nuc(new_deg_dna, individual.deg_nuc.skip_sam, individual.deg_nuc.skip_trn, individual.deg_nuc.gap_pos)
			individual.mark_nuc = types.MRF_nuc(new_mark_dna, individual.mark_nuc.skip_sam, individual.mark_nuc.skip_trn, individual.mark_nuc.gap_pos)

			individual.deg_seq = strip(uppercase(bio_seq.translate_constrained_maybe_map(individual.deg_nuc, individual.deg_trns, do_map = false)), '*')
			individual.mark_seq = strip(uppercase(bio_seq.translate_constrained_maybe_map(individual.mark_nuc, individual.mark_trns, do_map = false)), '*')

			individual.deg_vec, individual.deg_ull = bio_seq.convert_protein(individual.deg_seq), deg_ull_opt[deg_cads_map[best_deg_aa]]
			individual.deg_pv_w1, individual.deg_pv_w2 = deg_pv_w1_opt[deg_cads_map[best_deg_aa]], vec(deg_pv_w2_opt[deg_cads_map[best_deg_aa], 1:end])'
			individual.deg_prob = deg_psl_opt[deg_cads_map[best_deg_aa]]

			individual.mark_vec, individual.mark_ull = bio_seq.convert_protein(individual.mark_seq), mark_ull_opt[mark_cads_map[best_mark_aa]]
			individual.mark_pv_w1, individual.mark_pv_w2 = mark_pv_w1_opt[mark_cads_map[best_mark_aa]], vec(mark_pv_w2_opt[mark_cads_map[best_mark_aa], 1:end])'
			individual.mark_prob = mark_psl_opt[mark_cads_map[best_mark_aa]]

			individual.full_sequence = new_seq[1:end]

		end
	end
	return population, changed_seq
end

function mask_prot(prot_vec, region)
	new_prot_vec = prot_vec[1:end]
	new_prot_vec[region] = map(Float64, zeros(region))
	return new_prot_vec'
end

function invert_map(nuc_map)
	inverted_map = Dict{Int64, Array{Int64, 1}}()
	for nuc in sort(collect(keys(nuc_map)))
		resulting_aa = nuc_map[nuc]
		if !(resulting_aa in keys(inverted_map))
			inverted_map[resulting_aa] = Int64[]
			push!(inverted_map[resulting_aa], nuc)
		else
			push!(inverted_map[resulting_aa], nuc)
		end
	end
	return inverted_map
end

#Once we end up with generation of samples from the big tensor, we evaluate their pseudolikelihoods.
#This sets a benchmark and also allows us to compute all the quantities we'll need to conpute these values
#faster in the future.
function assess_founders(population, mark_nNodes, mark_w1, mark_w2, deg_nNodes, deg_w1, deg_w2)
	#Need a specific function for first generation. Hereafter we check partitions in icm_mutate().
	#fitness_values = Dict{Chromosome, Float64}()
	fitness_values = Float32[]
	new_degs = String[]
	new_marks = String[]
	successes = 0
	successful_chromosomes = Any[]
	individual_mark_maps = Dict{Int64, Int64}[]
	individual_deg_maps = Dict{Int64, Int64}[]
	for individual in population
		#Translate the chromosomes so that they are protein sequences...
		#We are now going to explicitly map these proteins in this step.
		new_deg_aa, individual_deg_map = bio_seq.translate_constrained_maybe_map(individual.deg_nuc, individual.deg_trns, do_map = true)
		new_deg_aa = uppercase(new_deg_aa)
		new_mark_aa, individual_mark_map = bio_seq.translate_constrained_maybe_map(individual.mark_nuc, individual.mark_trns, do_map = true)
		new_mark_aa = uppercase(new_mark_aa)

		if length(new_deg_aa) >= deg_nNodes && length(new_mark_aa) >= mark_nNodes
			successes += 1
			push!(new_marks, new_mark_aa)
			push!(new_degs, new_deg_aa)
			push!(successful_chromosomes, individual)
			push!(individual_mark_maps, individual_mark_map)
			push!(individual_deg_maps, individual_deg_map)
		else
			@debug("We do hit an issue!") #don't hit any issues.
		end
	end
	#Fill up a prot_mat with these values...
	mark_prot_mat = zeros(Float32, successes, mark_nNodes * 21)
	deg_prot_mat = zeros(Float32, successes, deg_nNodes * 21)
	for i in 1:successes
		mark_prot_mat[i, 1:end] = bio_seq.convert_protein(new_marks[i])[1:mark_nNodes * 21]
		deg_prot_mat[i, 1:end] = bio_seq.convert_protein(new_degs[i])[1:deg_nNodes * 21]
	end

	#Get their partitions and their fitnesses. We mutate based on this info.
	#full_deg_probs, deg_ull, deg_pv_w1, deg_pv_w2 = cuda_assess(deg_prot_mat, deg_cuda_facts)
	#full_mark_probs, mark_ull, mark_pv_w1, mark_pv_w2 = cuda_assess(mark_prot_mat, mark_cuda_facts)

	full_deg_probs, deg_ull, deg_pv_w1, deg_pv_w2 = mrf.cpu_assess(deg_prot_mat, deg_w1, deg_w2, deg_nNodes, successes)
	full_mark_probs, mark_ull, mark_pv_w1, mark_pv_w2 = mrf.cpu_assess(mark_prot_mat, mark_w1, mark_w2, mark_nNodes, successes)

	for i in 1:successes
		if rand() < 0.05
			@debug("Randomly reporting this... deg is $(full_deg_probs[i]) and mark is $(full_mark_probs[i])")
		end
		push!(fitness_values, -full_deg_probs[i] + -full_mark_probs[i])
	end

	#Also we should sum up each of the probs to be a single fitness value.
	return successful_chromosomes, full_deg_probs, full_mark_probs, fitness_values, individual_deg_maps, individual_mark_maps, deg_ull, deg_pv_w1, deg_pv_w2, deg_prot_mat, mark_ull, mark_pv_w1, mark_pv_w2, mark_prot_mat
end

function assess_pop(population)
	fitness_values = Float32[]
	for i in 1:length(population)
		push!(fitness_values, abs(population[i].deg_prob) + abs(population[i].mark_prob))
	end
	return fitness_values
end

end


text:
include("utils.jl") # contains most dependencies and the saving function
using GenerativeAD.Models: anomaly_score, generalized_anomaly_score_gpu

s = ArgParseSettings()
@add_arg_table! s begin
	"dataset"
		default = "MNIST"
		arg_type = String
		help = "dataset"
	"class"
		default = 1
		arg_type = Int
		help = "dataset"
end
parsed_args = parse_args(ARGS, s)
@unpack dataset, class = parsed_args

#######################################################################################
################ THIS PART IS TO BE PROVIDED FOR EACH MODEL SEPARATELY ################
modelname = "Conv-SkipGANomaly"

"""
This returns encodings, parameters and scoring functions in order to reconstruct the experiment.
This is a slightly updated version of the original run script.
"""
function evaluate(model_data, data, parameters)
	# load the model file, extract params and model
	model = model_data["model"] |> gpu

	# construct return information - put e.g. the model structure here for generative models
	training_info = (
		fit_t = get(model_data, "fit_t", nothing),
		history = get(model_data, "history", nothing),
		iters = get(model_data, "iters", nothing),
		npars = get(model_data, "npars", nothing),
		model = model |> cpu
		)

	return training_info, [(x -> generalized_anomaly_score_gpu(model|>cpu, x, R=r, L=l, lambda=lam),
		merge(parameters, (R=r, L=l, test_lambda=lam,)))
		for r in ["mae", "mse"] for l in ["mae", "mse"] for lam = 0.1:0.1:0.9 ]
end

##################
# this is common #
##################
seed = 1
method = "leave-one-in"
contamination = 0.0
ac = class

main_inpath = datadir("experiments/images_leave-one-in_backup/$(modelname)/$(dataset)")
main_savepath = datadir("experiments/images_leave-one-in/$(modelname)/$(dataset)")
mkpath(main_savepath)

# this loop unfortunately cannot be in a function, since loading of bson is only safe ot top level
global data = GenerativeAD.load_data(dataset, seed=seed, anomaly_class_ind=ac, method=method,
	contamination=contamination)
in_ch = size(data[1][1],3)
isize = maximum([size(data[1][1],1),size(data[1][1],2)])
isize = (isize % 16 != 0) ? isize + 16 - isize % 16 : isize

inpath = joinpath(main_inpath, "ac=$ac/seed=$seed")
savepath = joinpath(main_savepath, "ac=$ac/seed=$seed")
mkpath(savepath)
fs = readdir(inpath, join=true)
sfs = filter(x->!(occursin("model", x)), fs)
mfs = filter(x->(occursin("model", x)), fs)

@info "Loaded $(length(mfs)) modelfiles in $inpath, processing..."
for mf in mfs
	# load the bson file on top level, otherwise we get world age problems
	model_data = load(mf)
	if haskey(model_data, "parameters")
		parameters = model_data["parameters"]
	else # this is in case parameters are not saved in the model file
		init_seed = DrWatson.parse_savename(mf)[2]["init_seed"]
		sf = sfs[map(x->DrWatson.parse_savename(x)[2]["init_seed"], sfs) .== init_seed][1]
		score_data = load(sf)
		parameters = score_data[:parameters]
	end
	parameters = merge(parameters, (isize=isize, in_ch = in_ch, out_ch = 1))
	# update parameter
	global data = GenerativeAD.Models.preprocess_images(data, parameters)

	try
		training_info, results = evaluate(model_data, data, parameters) # this produces parameters, encodings, score funs
		save_results(parameters, training_info, results, savepath, data,
			ac, modelname, seed, dataset, contamination) # this computes and saves score and model files
	catch e
		if isa(e, LoadError)
			@warn "$mf failed during result evaluation due to $e"
		else
			rethrow(e)
		end
	end
end

ext: jl


text:
"""
This module provides:

- An interface for physical fields, basis of physical fields and related objects.
- Helpers functions to work with fields and arrays of fields.
- Helpers functions to create lazy operation trees from fields and arrays of fields

The exported names are:

$(EXPORTS)
"""
module Fields

using Gridap.Helpers
using Gridap.Inference
using Gridap.TensorValues
using Gridap.Arrays
using Gridap.Arrays: BCasted
using Gridap.Arrays: NumberOrArray
using Gridap.Arrays: AppliedArray
using Gridap.Arrays: Contracted
using LinearAlgebra: ⋅
using BlockArrays

using Test
using DocStringExtensions
using FillArrays
import ForwardDiff

export Point
export field_gradient
export evaluate_field!
export evaluate_field
export field_cache
export field_return_type
export evaluate
export evaluate!
export gradient
export ∇
export Field
export test_field
export apply_kernel_to_field
export apply_to_field_array
export test_array_of_fields
export compose
export compose_fields
export compose_field_arrays
export lincomb
export apply_lincomb
export attachmap
export integrate
export field_caches
export field_return_types
export evaluate_fields
export evaluate_fields!
export field_gradients
export field_array_cache
export evaluate_field_array
export evaluate_field_arrays
export field_array_gradient
export gradient_type
export curl
export grad2curl
export laplacian
export divergence
export Δ
export ε
export symmetric_gradient

export Homothecy
export AffineMap

export VectorOfBlockBasisCoo
export insert_array_of_bases_in_block
export create_array_of_blocked_axes

export operate_fields
export operate_arrays_of_fields
export trialize_basis
export trialize_array_of_bases
export field_operation_axes
export field_operation_metasize

export function_field

import Gridap.Arrays: kernel_cache
import Gridap.Arrays: apply_kernel!
import Gridap.Arrays: kernel_return_type
import Gridap.Arrays: kernel_testitem!
import Gridap.Arrays: apply
import Gridap.Arrays: reindex
import Gridap.TensorValues: outer
import Gridap.TensorValues: inner
import Gridap.TensorValues: symmetric_part
import Base: +, - , *
import LinearAlgebra: cross
import LinearAlgebra: tr
import LinearAlgebra: dot
import Base: transpose
import Base: adjoint

include("FieldInterface.jl")

include("MockFields.jl")

include("FunctionFields.jl")

include("ConstantFields.jl")

include("Homothecies.jl")

include("AffineMaps.jl")

include("FieldApply.jl")

include("FieldArrays.jl")

include("Lincomb.jl")

include("Compose.jl")

include("Attachmap.jl")

include("Integrate.jl")

include("FieldOperations.jl")

include("VectorsOfBlockBasisCoo.jl")

include("DiffOperators.jl")

include("UnimplementedFields.jl")

end # module


text:
# ------------------------------------------------------------------
# Licensed under the MIT License. See LICENSE in the project root.
# ------------------------------------------------------------------

"""
    HullMethod

A method for computing hulls of point sets or
collections of geometries.
"""
abstract type HullMethod end

"""
    hull(object, method)

Compute the hull of `object` with given `method`.
"""
function hull end

# ----------------
# IMPLEMENTATIONS
# ----------------

include("hulls/graham.jl")


text:
function semideviation(a; kwargs...)
    return std(map(x -> x < 0 ? x : 0.0, a); kwargs...)
end

function semideviation(ta::TimeArray; kwargs...)
    return semideviation(values(ta); kwargs...)
end


text:
# Use `mpiexec` from MPICH_jll to get a PMI environment.
using MPICH_jll
using Test

nprocs_str = get(ENV, "JULIA_PMI_TEST_NPROCS","")
nprocs = nprocs_str == "" ? clamp(Sys.CPU_THREADS, 2, 4) : parse(Int, nprocs_str)

testdir = @__DIR__
istest(f) = endswith(f, ".jl") && startswith(f, "test_")
testfiles = sort(filter(istest, readdir(testdir)))

@info "Running PMI tests"

@testset "$f" for f in testfiles
    mpiexec() do cmd
        run(`$cmd -n $nprocs $(Base.julia_cmd()) $(joinpath(testdir, f))`)
        @test true
    end
end


text:
macro import_text_huge()
    :(
        using ComplexVisual:
            CV_TextExtents, cv_get_text_extents,
            cv_anchor, cv_create_context, cv_text
    )
end

"""
TextExtends (including computed height and depth)
"""
struct CV_TextExtents  # {{{
    x_bearing    :: Float64
    y_bearing    :: Float64
    bb_width     :: Float64     # complete width of bounding box
    bb_height    :: Float64     # complete height of bounding box
    x_adv        :: Float64
    y_adv        :: Float64
    height       :: Float64     # height above baseline
    depth        :: Float64     # depth below baseline
end

"""
compute text extents for given string w.r.t. given cairo context.
"""
function cv_get_text_extents(
        ctx, text::AbstractString;
        use_mem=Vector{Float64}(undef, 6)::Vector{Float64})
    text_extents(ctx, text, use_mem)
    height = -use_mem[2]
    depth = use_mem[4] + use_mem[2]
    return CV_TextExtents(
        use_mem[1], use_mem[2], use_mem[3],
        use_mem[4], use_mem[5], use_mem[6],
        height, depth)
end
# }}}

"""
`CV_2DCanvas` with rendered text.
"""
struct CV_2DTextCanvas <: CV_2DCanvas # {{{
    surface         :: Cairo.CairoSurfaceImage{UInt32}
    pixel_width     :: Int32
    pixel_height    :: Int32
    bounding_box    :: CV_Rectangle{Int32} # zero-based
    baseline        :: Int32

    function CV_2DTextCanvas(width::Integer, height::Integer, baseline::Integer)
        pixel_width, pixel_height = Int32(width), Int32(height)
        surface = cv_create_cairo_image_surface(pixel_width, pixel_height)
        self = new(
            surface, pixel_width, pixel_height,
            CV_Rectangle(pixel_height, Int32(0), Int32(0), pixel_width),
            Int32(baseline))
        return self
    end
end

function cv_anchor(can::CV_2DTextCanvas, anchor_name::Symbol)
    if anchor_name === :baseline  || anchor_name === :baseline_west
        return (Int32(0), can.baseline)
    elseif anchor_name === :baseline_center
        return (cv_half(can.pixel_width), can.baseline)
    elseif anchor_name === :baseline_east
        return (can.pixel_width, can.baseline)
    else
        return cv_anchor(can.bounding_box, anchor_name)
    end
end

function cv_create_context(canvas::CV_2DTextCanvas; prepare::Bool=true)
    con = CV_2DCanvasContext(canvas)
    if prepare
        ctx = con.ctx
        reset_transform(ctx)

        set_operator(ctx, Cairo.OPERATOR_SOURCE)
        set_source_rgba(ctx, 0, 0, 0, 0)
        rectangle(ctx, 0, 0, canvas.pixel_width, canvas.pixel_height)
        fill(ctx)

        set_operator(ctx, Cairo.OPERATOR_OVER)
    end
    return con
end

"""
Create 2DCanvas with given text (rendered inside).
"""
function cv_text(text::AbstractString,
                 style::CV_ContextStyle=cv_black →
                    cv_fontface("serif") → cv_fontsize(15);
                use_temp_can=nothing,
                use_mem=Vector{Float64}(undef, 6)::Vector{Float64})
    temp_can = (use_temp_can isa Nothing) ? CV_Std2DCanvas(5, 5) : use_temp_can
    con = cv_create_context(temp_can)

    cv_prepare(con, style)
    ext = cv_get_text_extents(con.ctx, text; use_mem=use_mem)
    if ext.bb_width <= 0 || ext.bb_height <= 0
        return CV_2DTextCanvas(1, 1, 1)   # everything is empty
    end
    cv_destroy(con)
    if !(use_temp_can isa Nothing)
        cv_destroy(temp_can)
    end

    canvas = CV_2DTextCanvas(
        ceil(Int32, ext.bb_width), ceil(Int32, ext.bb_height),
        round(Int32, ext.height))
    con = cv_create_context(canvas)
    try
        cv_prepare(con, style)
        move_to(con.ctx, 0 - round(Int32, ext.x_bearing), canvas.baseline)
        show_text(con.ctx, text)
    finally
        cv_destroy(con)
    end
    return canvas
end

# }}}

# vim:syn=julia:cc=79:fdm=marker:sw=4:ts=4:


text:
# epsxc only version
function XC_c_pw_E( Rhoe )

    third = 1.0/3.0
    pi34 = 0.6203504908994
    rs = pi34/Rhoe^third

    a = 0.031091
    a1 = 0.21370
    b1 = 7.5957
    b2 = 3.5876
    b3 = 1.6382
    b4 = 0.49294

    # interpolation formula
    rs12 = sqrt(rs)
    rs32 = rs * rs12
    rs2 = rs^2

    om = 2.0 * a * (b1 * rs12 + b2 * rs + b3 * rs32 + b4 * rs2)
    olog = log(1.0 + 1.0/om)
    ec = -2.0 * a * (1.0 + a1 * rs) * olog

    return ec
end


text:
#!/usr/bin/env julia

const DATA_DIR = "../07_data"
const INPUT_FILE = "input.txt"
# const INPUT_FILE = "input_test_a.txt"
# const INPUT_FILE = "input_tiny_a.txt"

const PAT_PARENT   = r"^(\w+\s\w+) bags contain (.+)"
const PAT_CHILDREN = r"(\d) (\w+\s\w+) bag"

macro assert(boolean)
    message = string("Assertion: ", boolean, " failed")
    :($(esc(boolean)) || error($message))
end

mutable struct TreeNode
    name::String
    children::Array{Tuple{TreeNode, Int}}
    parents::Array{TreeNode}
    #--------------------
    function TreeNode(name::String)
        return new(name, [], [])
    end
end

mutable struct Registry
    nodeDict::Dict{String, TreeNode}
    #--------------------
    function Registry()
        return new(Dict{String, TreeNode}())
    end
end

# ----------------------------------------

function countDescendents(node::TreeNode)
    result = 0
    for (child, subcount) in getNode(registry, node.name).children
        result += subcount * (1 + countDescendents(child))
    end
    return result
end

function getNode(reg::Registry, name::String)
    if get(reg.nodeDict, name, nothing) != nothing
        return reg.nodeDict[name]
    else
        newNode = TreeNode(name)
        reg.nodeDict[name] = newNode
        return newNode
    end
end

registry = Registry()
lines = readlines("$DATA_DIR/$INPUT_FILE")

for line in lines
    # println("Processling line: ", line)
    mparent = match(PAT_PARENT, line)
    parent_name = string(mparent.captures[1])
    parent_node = getNode(registry, parent_name)
    @assert mparent != nothing
    # println("Match = ", mparent.captures[1])
    for mchild in eachmatch(PAT_CHILDREN, mparent.captures[2])
        child_count = parse(Int32, mchild.captures[1])
        child_name = string(mchild.captures[2])
        child_node = getNode(registry, child_name)
        push!(parent_node.children, (child_node, child_count))
        push!(child_node.parents, parent_node)
        # println("Recorded that ", parent_node.name, " is a parent of ", child_node.name)
        # println("\tMatch: ", mchild)
        # println("\tMatch Details: $child_name, $child_count")
    end
    # println("====================")
end

# println("nodeDict has length: ", length(registry.nodeDict))
# println("nodeDict.keys has length: ", length(registry.nodeDict.keys))
# for (key, val) in registry.nodeDict
#     println(key)
# end

# TODO: Improve efficiency
shinyGoldNode = getNode(registry, "shiny gold")
searchNames = Set()
ancestryNames = Set()
push!(searchNames, shinyGoldNode.name)
while !isempty(searchNames)
    currentName = pop!(searchNames)
    if (currentName != "shiny gold") && !(currentName in ancestryNames)
        push!(ancestryNames, currentName)
    end
    for parentNode in getNode(registry, currentName).parents
        if !(parentNode.name in searchNames)
            push!(searchNames, parentNode.name)
        end
    end
end

println("========== PART 1 ==========")
println(length(ancestryNames))
println()
println("========== PART 2 ==========")
println(countDescendents(getNode(registry, "shiny gold")))

max_stars_repo_name: jaycoskey/AdventOfCode

max_issues_repo_name: jaycoskey/AdventOfCode

max_forks_repo_name: jaycoskey/AdventOfCode


text:
# The Computer Language Benchmarks Game
# https://salsa.debian.org/benchmarksgame-team/benchmarksgame/

# contributed by Jarret Revels and Alex Arslan
# based on an OCaml program
# *reset*

using Distributed
using Printf

@everywhere abstract type BTree end

@everywhere struct Node <: BTree
  left::Union{Nothing,Node}
  right::Union{Nothing,Node}
end

@everywhere function make(d)
    if d == 0
        Node(nothing, nothing)
    else
        Node(make(d-1), make(d-1))
    end
end

@everywhere check(t::Nothing) = 0
@everywhere check(t::Node) = 1 + check(t.left) + check(t.right)

function loop_depths(min_depth, max_depth)
    out = @distributed vcat for d in min_depth:2:max_depth
        niter = 1 << (max_depth - d + min_depth)
        c = 0
        for j = 1:niter
            c += check(make(d))
        end
        @sprintf("%i\t trees of depth %i\t check: %i\n", niter, d, c)
    end
    for s in out
      print(s)
    end

end

function perf_binary_trees(N::Int=10)
    min_depth = 4
    max_depth = N
    stretch_depth = max_depth + 1

    # create and check stretch tree
    let c = check(make(stretch_depth))
        @printf("stretch tree of depth %i\t check: %i\n", stretch_depth, c)
    end

    long_lived_tree = make(max_depth)

    loop_depths(min_depth, max_depth)
    @printf("long lived tree of depth %i\t check: %i\n", max_depth, check(long_lived_tree))

end

n = parse(Int,ARGS[1])
perf_binary_trees(n)


text:
using Statistics
using Printf

using OffsetArrays
using DifferentialEquations
using Turing
using DynamicHMC
using CairoMakie
using ElectronDisplay

# Turing.setadbackend(:forwarddiff)

# Exact solution
# Convert x to periodic range in [0, L].
@inline x′(x, t, L, U) = mod(x + L - U * t, L)
@inline ϕ_exact(x, t, L, U) = exp(-100 * (x′(x, t, L, U) - 0.5)^2)

# Numerical solution
@inline advective_flux(i, u, ϕ) = u * (ϕ[i-1] + ϕ[i]) / 2
@inline ∂x_advective_flux(i, Δx, u, ϕ) = (advective_flux(i+1, u, ϕ) - advective_flux(i, u, ϕ)) / Δx

function advection(∂ϕ∂t, ϕ, p, t)
    Nx, Hx, Δx, u = p
    Nx = Int(Nx)
    Hx = Int(Hx)

    # filling periodic halos
    ϕ[-Hx+1:0] .= ϕ[Nx]
    ϕ[Nx+1:Nx+Hx] .= ϕ[1]

    for i in 1:Nx
        ∂ϕ∂t[i] = - ∂x_advective_flux(i, Δx, u, ϕ)
    end
end

Nx = 64
Hx = 1
Lx = 1
Δx = Lx / Nx
u = 0.2
p = [Nx, Hx, Δx, u]

xC = range(Δx/2, Lx - Δx/2, length=Nx)
xF = range(0, Lx, length=Nx+1)

ϕ₀ = OffsetArray(zeros(Nx+2Hx), -Hx+1:Nx+Hx)
@. ϕ₀[1:Nx] = ϕ_exact.(xC, 0, Lx, u)

tspan = (0.0, 10.0)
prob = ODEProblem(advection, ϕ₀, tspan, p, saveat=0.1)
sol = solve(prob, Tsit5())

function animate_advection(ϕ, ϕ_correct, x, t; framerate=30)
    n = Observable(1)
    ϕₙ = @lift ϕ[:, $n]
    ϕₙ_correct = @lift ϕ_correct[:, $n]

    title = @lift "Advection: t = $(round(t[$n], digits=1))"

    fig = Figure()
    ax = Axis(fig[1, 1], title=title, xlabel="x", ylabel="ϕ")
    lines!(ax, x, ϕₙ_correct)
    lines!(ax, x, ϕₙ)

    time_indices = 1:length(t)
    record(fig, "advection_1d.mp4", time_indices; framerate) do time_index
        @info "Animating 1D advection: frame $time_index/$(length(t))"
        n[] = time_index
    end
end

ϕ = Array(sol)[Hx+1:Nx+Hx, :]
ϕ_correct = ϕ_exact.(xC, sol.t', Lx, u)
animate_advection(ϕ, ϕ_correct, xC, sol.t)

function predict_advection(prob, u)
    Nx, Hx, Δx, _ = prob.p
    Nx = Int(Nx)
    Hx = Int(Hx)

    p = [Nx, Hx, Δx, u]
    prob = remake(prob, p=p)
    prediction = solve(prob, Tsit5())

    return prediction
end

function plot_likelihood(prob; saveat=0.1, N=1001, u_range=(-1, 1), chains=nothing)
    prob = remake(prob; saveat)
    Nx, Hx, _, u = prob.p
    Nx = Int(Nx)
    Hx = Int(Hx)

    losses = zeros(N)
    us = range(u_range[1], u_range[2], length=N)

    for (i, ũ) in enumerate(us)
        prediction = predict_advection(prob, ũ)
        ϕ_correct = ϕ_exact.(xC, prediction.t', Lx, u)
        prediction_array = Array(prediction)[1+Hx:Nx+Hx, :]
        losses[i] = mean((prediction_array .- ϕ_correct).^2)
    end

    fig = Figure()
    ax = Axis(fig[1, 1], title="Likelihood of model prediction for 1D advection with saveat=$saveat", xlabel="u", ylabel="likelihood ~ -loss (relative to max loss, arbitrary units)")
    lines!(ax, us, maximum(losses) .- losses)

    if !isnothing(chains)
        n_chains = size(chains, 3)
        for c in 1:n_chains
            vlines!(ax, mode(chains[:u].data[:, c]), color=(:red, 0.5))
        end
    end

    save("advection_1d_likelihood_saveat$saveat.png", fig)

    return
end

for sa in [0.01, 0.1, 0.2, 0.5, 1.0]
    plot_likelihood(prob, saveat=sa)
end

@model function probabilistic_advection(data, prob)
    σ ~ InverseGamma(3, 0.5)
    u ~ Normal(0.2, 0.05)

    prediction = predict_advection(prob, u)

    for i = 1:length(prediction)
        data[:, i] ~ MvNormal(prediction[i][1:Nx], σ)
    end
end

# prior_chain = sample(probabilistic_advection(ϕ_correct, prob), Prior(), 1000)

function callback_single_chain(rng, model, sampler, sample, state, iter; loss_history, kwargs...)
    u = sample.θ.u[1][1]
    σ = sample.θ.σ[1][1]

    prediction = Array(predict_advection(prob, u))[1+Hx:Nx+Hx, :]
    loss_history[iter] = loss = mean((prediction .- ϕ_correct).^2)

    @info "Iteration $iter: u=$u, σ=$σ, ℒ=$loss"
end

# sampler = MH(:u => x -> Normal(x, 0.05), :σ => x -> Normal(x, 5e-3))
# sampler = HMC(1e-3, 10)
sampler = NUTS(100, 0.65)

θ₀ = [0.05, 0.2] # Use with the init_params=θ₀ kwarg.

# n_samples = 10000
# loss_history = zeros(n_samples)
# chain = sample(probabilistic_advection(ϕ_correct, prob), sampler, n_samples, progress=true, callback=callback_single_chain; loss_history)

function callback_multi_chain(rng, model, sampler, sample, state, iter; loss_history, kwargs...)
    n = Threads.threadid()

    u = sample.θ.u[1][1]
    σ = sample.θ.σ[1][1]

    prediction = Array(predict_advection(prob, u))[1+Hx:Nx+Hx, :]
    loss_history[n, iter] = loss = mean((prediction .- ϕ_correct).^2)

    @info "Chain $n, Iteration $iter: u=$u, σ=$σ, ℒ=$loss"
end

n_chains = 8
@assert Threads.nthreads() >= n_chains

n_samples = 1000
loss_history = zeros(n_chains, n_samples)

chains_no_init = sample(probabilistic_advection(ϕ_correct, prob), sampler, MCMCThreads(), n_samples, n_chains, progress=true, callback=callback_multi_chain; loss_history)
plot_likelihood(prob, saveat=0.1, u_range=(-1, 1.5); chains)

chains_init = sample(probabilistic_advection(ϕ_correct, prob), sampler, MCMCThreads(), n_samples, n_chains, init_params=θ₀, progress=true, callback=callback_multi_chain; loss_history)

function plot_chains_and_densities(chains, vars; q_ADVI=nothing, n_ADVI_samples=10000)
    n_chains = size(chains, 3)

    fig = Figure()

    if !isnothing(q_ADVI)
        ADVI_samples = rand(q_ADVI, n_ADVI_samples)
    end

    for (n, var) in enumerate(vars)
        ax1 = Axis(fig[n, 1], ylabel="$var", xlabel="iteration")
        for c in 1:n_chains
            lines!(ax1, chains[var].data[:, c])
        end

        ax2 = Axis(fig[n, 2], ylabel="P($var)", xlabel="$var", yticklabelsvisible=false)
        density!(ax2, chains[var][:].data, label="NUTS")

        if !isnothing(q_ADVI)
            density!(ax2, ADVI_samples[n, :], label="ADVI")
        end

        axislegend(ax2)
    end

    save("chains_and_densities.png", fig)

    return
end

plot_chains_and_densities(chains_init, [:u, :σ])

# q_ADVI = vi(probabilistic_advection(ϕ_correct, prob), ADVI(100, 1000))
# plot_chains_and_densities(chains_init, [:u, :σ]; q_ADVI)


text:
# Methods in this file should move to their corresponding solver repositories
# These are created only to make DiffOpt run with different solvers


text:
function FDivGrad2VecDSS!(divCG,cCG,CG,Param)
nz=Param.Grid.nz;
OP=CG.OrdPoly+1;
NF=Param.Grid.NumFaces;

D1cCG = Param.CacheC1
D2cCG = Param.CacheC2
grad1CG = Param.CacheC3
grad2CG = Param.CacheC4
D1gradCG = Param.CacheC1
D2gradCG = Param.CacheC2
vC1 = Param.CacheC3
vC2 = Param.CacheC4
div = Param.Cache1
JC = Param.cache.JC;

mul!(reshape(D1cCG,OP,OP*NF*nz),CG.DS,reshape(cCG,OP,OP*nz*NF))
mul!(reshape(PermutedDimsArray(D2cCG,(2,1,3,4)),OP,OP*NF*nz),CG.DS,reshape(PermutedDimsArray(cCG,(2,1,3,4)),OP,OP*nz*NF))

grad1CG .= Param.dXdxIC11.*D1cCG .+ Param.dXdxIC21.*D2cCG
grad2CG .= Param.dXdxIC12.*D1cCG .+ Param.dXdxIC22.*D2cCG

D1gradCG .= Param.dXdxIC11.*grad1CG .+ Param.dXdxIC12.*grad2CG
D2gradCG .= Param.dXdxIC21.*grad1CG .+ Param.dXdxIC22.*grad2CG

mul!(reshape(vC1,OP,OP*NF*nz),CG.DW,reshape(D1gradCG,OP,OP*nz*NF))
mul!(reshape(PermutedDimsArray(vC2,(2,1,3,4)),OP,OP*NF*nz),CG.DW,reshape(PermutedDimsArray(D2gradCG,(2,1,3,4)),OP,OP*nz*NF))
vC1 .= (vC1 .+ vC2) ./ JC

div .= 0
for iM=1:size(CG.FaceGlob,1)
  i = CG.FaceGlob[iM].Ind
  arr = reshape(CG.Glob[:,i,:],OP*OP*size(i,1))
  div[arr,:] .= div[arr,:] .+
    reshape(vC1[:,:,i,:]
    ,OP*OP*size(i,1),nz);
end
div=div./CG.M;
divCG .= reshape(div[reshape(CG.Glob,OP*OP*NF,1),:]
  ,OP,OP,NF,nz);
end

function FDivGrad2VecDSS(cCG,CG,Param)
nz=Param.Grid.nz;
OP=CG.OrdPoly+1;
NF=Param.Grid.NumFaces;
dXdxIC = Param.cache.dXdxIC
JC = Param.cache.JC
D1cCG=reshape(
  CG.DS*reshape(cCG,OP,OP*NF*nz)
  ,OP,OP,NF,nz);
D2cCG=permute(reshape(
  CG.DS
  *reshape(
  permute(
  reshape(cCG,OP,OP,NF,nz)
  ,[2 1 3 4])
  ,OP,OP*NF*nz)
  ,OP,OP,NF,nz)
  ,[2 1 3 4]);

gradCG1=dXdxIC[:,:,:,:,1,1].*D1cCG +
  dXdxIC[:,:,:,:,2,1].*D2cCG;
gradCG2=dXdxIC[:,:,:,:,1,2].*D1cCG +
  dXdxIC[:,:,:,:,2,2].*D2cCG;

vC1=(reshape(
  CG.DW*(reshape(gradCG1,OP,OP*NF*nz) .*
  reshape(dXdxIC[:,:,:,:,1,1],OP,OP*NF*nz) +
  reshape(gradCG2,OP,OP*NF*nz) .*
  reshape(dXdxIC[:,:,:,:,1,2],OP,OP*NF*nz))
  ,OP,OP,NF,nz) +
  permute(
  reshape(
  CG.DW*reshape(
  permute(
  (reshape(gradCG1,OP,OP,NF,nz).*dXdxIC[:,:,:,:,2,1] +
   reshape(gradCG2,OP,OP,NF,nz).*dXdxIC[:,:,:,:,2,2])
  ,[2 1 3 4])
  ,OP,OP*NF*nz)
  ,OP,OP,NF,nz)
  ,[2 1 3 4]))./JC;

div=zeros(CG.NumG,nz);
for iM=1:size(CG.FaceGlob,1)
  i = CG.FaceGlob[iM].Ind
  arr = reshape(CG.Glob[:,i,:],OP*OP*size(i,1))
  div[arr,:] .= div[arr,:] .+
    reshape(vC1[:,:,i,:]
    ,OP*OP*size(i,1),nz);
end
div=div./CG.M;
divCG=reshape(div[reshape(CG.Glob,OP*OP*NF,1),:]
  ,OP,OP,NF,nz);
return divCG
end


text:
# Improving this algorithm will likely improve the performance of the
# Change-of-Basis model

""" Implements Cholesky-like decomposition X=VV' for PSD matrices """
function cholesky_like(X)
        u, s, v = svd(X)
        q, r = qr(sqrt(Diagonal(s)) * u')
        r
end


text:
module FirstPassageTools

include("utilities.jl")
export rescale!
export setup

include("firstpassagedistributions.jl")
export splittingprobabilities
export fpdistribution
export @distr_support
export minimum
export maximum
export mean
export var
export pdf
export logpdf
export cdf
export quantile
export rand
export quasistationary

end


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

"""
    add_listener_certificates(certificates, listener_arn)
    add_listener_certificates(certificates, listener_arn, params::Dict{String,<:Any})

Adds the specified SSL server certificate to the certificate list for the specified HTTPS
or TLS listener. If the certificate in already in the certificate list, the call is
successful but the certificate is not added again. For more information, see HTTPS
listeners in the Application Load Balancers Guide or TLS listeners in the Network Load
Balancers Guide.

# Arguments
- `certificates`: The certificate to add. You can specify one certificate per call. Set
  CertificateArn to the certificate ARN but do not set IsDefault.
- `listener_arn`: The Amazon Resource Name (ARN) of the listener.

"""
add_listener_certificates(Certificates, ListenerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("AddListenerCertificates", Dict{String, Any}("Certificates"=>Certificates, "ListenerArn"=>ListenerArn); aws_config=aws_config)
add_listener_certificates(Certificates, ListenerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("AddListenerCertificates", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Certificates"=>Certificates, "ListenerArn"=>ListenerArn), params)); aws_config=aws_config)

"""
    add_tags(resource_arns, tags)
    add_tags(resource_arns, tags, params::Dict{String,<:Any})

Adds the specified tags to the specified Elastic Load Balancing resource. You can tag your
Application Load Balancers, Network Load Balancers, Gateway Load Balancers, target groups,
listeners, and rules. Each tag consists of a key and an optional value. If a resource
already has a tag with the same key, AddTags updates its value.

# Arguments
- `resource_arns`: The Amazon Resource Name (ARN) of the resource.
- `tags`: The tags.

"""
add_tags(ResourceArns, Tags; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("AddTags", Dict{String, Any}("ResourceArns"=>ResourceArns, "Tags"=>Tags); aws_config=aws_config)
add_tags(ResourceArns, Tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("AddTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArns"=>ResourceArns, "Tags"=>Tags), params)); aws_config=aws_config)

"""
    create_listener(default_actions, load_balancer_arn)
    create_listener(default_actions, load_balancer_arn, params::Dict{String,<:Any})

Creates a listener for the specified Application Load Balancer, Network Load Balancer, or
Gateway Load Balancer. For more information, see the following:    Listeners for your
Application Load Balancers     Listeners for your Network Load Balancers     Listeners for
your Gateway Load Balancers    This operation is idempotent, which means that it completes
at most one time. If you attempt to create multiple listeners with the same settings, each
call succeeds.

# Arguments
- `default_actions`: The actions for the default rule.
- `load_balancer_arn`: The Amazon Resource Name (ARN) of the load balancer.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AlpnPolicy"`: [TLS listeners] The name of the Application-Layer Protocol Negotiation
  (ALPN) policy. You can specify one policy name. The following are the possible values:
  HTTP1Only     HTTP2Only     HTTP2Optional     HTTP2Preferred     None    For more
  information, see ALPN policies in the Network Load Balancers Guide.
- `"Certificates"`: [HTTPS and TLS listeners] The default certificate for the listener. You
  must provide exactly one certificate. Set CertificateArn to the certificate ARN but do not
  set IsDefault.
- `"Port"`: The port on which the load balancer is listening. You cannot specify a port for
  a Gateway Load Balancer.
- `"Protocol"`: The protocol for connections from clients to the load balancer. For
  Application Load Balancers, the supported protocols are HTTP and HTTPS. For Network Load
  Balancers, the supported protocols are TCP, TLS, UDP, and TCP_UDP. You can’t specify the
  UDP or TCP_UDP protocol if dual-stack mode is enabled. You cannot specify a protocol for a
  Gateway Load Balancer.
- `"SslPolicy"`: [HTTPS and TLS listeners] The security policy that defines which protocols
  and ciphers are supported. For more information, see Security policies in the Application
  Load Balancers Guide and Security policies in the Network Load Balancers Guide.
- `"Tags"`: The tags to assign to the listener.
"""
create_listener(DefaultActions, LoadBalancerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateListener", Dict{String, Any}("DefaultActions"=>DefaultActions, "LoadBalancerArn"=>LoadBalancerArn); aws_config=aws_config)
create_listener(DefaultActions, LoadBalancerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateListener", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DefaultActions"=>DefaultActions, "LoadBalancerArn"=>LoadBalancerArn), params)); aws_config=aws_config)

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

Creates an Application Load Balancer, Network Load Balancer, or Gateway Load Balancer. For
more information, see the following:    Application Load Balancers     Network Load
Balancers     Gateway Load Balancers    This operation is idempotent, which means that it
completes at most one time. If you attempt to create multiple load balancers with the same
settings, each call succeeds.

# Arguments
- `name`: The name of the load balancer. This name must be unique per region per account,
  can have a maximum of 32 characters, must contain only alphanumeric characters or hyphens,
  must not begin or end with a hyphen, and must not begin with \"internal-\".

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"CustomerOwnedIpv4Pool"`: [Application Load Balancers on Outposts] The ID of the
  customer-owned address pool (CoIP pool).
- `"IpAddressType"`: The type of IP addresses used by the subnets for your load balancer.
  The possible values are ipv4 (for IPv4 addresses) and dualstack (for IPv4 and IPv6
  addresses). Internal load balancers must use ipv4.
- `"Scheme"`: The nodes of an Internet-facing load balancer have public IP addresses. The
  DNS name of an Internet-facing load balancer is publicly resolvable to the public IP
  addresses of the nodes. Therefore, Internet-facing load balancers can route requests from
  clients over the internet. The nodes of an internal load balancer have only private IP
  addresses. The DNS name of an internal load balancer is publicly resolvable to the private
  IP addresses of the nodes. Therefore, internal load balancers can route requests only from
  clients with access to the VPC for the load balancer. The default is an Internet-facing
  load balancer. You cannot specify a scheme for a Gateway Load Balancer.
- `"SecurityGroups"`: [Application Load Balancers] The IDs of the security groups for the
  load balancer.
- `"SubnetMappings"`: The IDs of the public subnets. You can specify only one subnet per
  Availability Zone. You must specify either subnets or subnet mappings. [Application Load
  Balancers] You must specify subnets from at least two Availability Zones. You cannot
  specify Elastic IP addresses for your subnets. [Application Load Balancers on Outposts] You
  must specify one Outpost subnet. [Application Load Balancers on Local Zones] You can
  specify subnets from one or more Local Zones. [Network Load Balancers] You can specify
  subnets from one or more Availability Zones. You can specify one Elastic IP address per
  subnet if you need static IP addresses for your internet-facing load balancer. For internal
  load balancers, you can specify one private IP address per subnet from the IPv4 range of
  the subnet. For internet-facing load balancer, you can specify one IPv6 address per subnet.
  [Gateway Load Balancers] You can specify subnets from one or more Availability Zones. You
  cannot specify Elastic IP addresses for your subnets.
- `"Subnets"`: The IDs of the public subnets. You can specify only one subnet per
  Availability Zone. You must specify either subnets or subnet mappings. [Application Load
  Balancers] You must specify subnets from at least two Availability Zones. [Application Load
  Balancers on Outposts] You must specify one Outpost subnet. [Application Load Balancers on
  Local Zones] You can specify subnets from one or more Local Zones. [Network Load Balancers]
  You can specify subnets from one or more Availability Zones. [Gateway Load Balancers] You
  can specify subnets from one or more Availability Zones.
- `"Tags"`: The tags to assign to the load balancer.
- `"Type"`: The type of load balancer. The default is application.
"""
create_load_balancer(Name; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateLoadBalancer", Dict{String, Any}("Name"=>Name); aws_config=aws_config)
create_load_balancer(Name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name), params)); aws_config=aws_config)

"""
    create_rule(actions, conditions, listener_arn, priority)
    create_rule(actions, conditions, listener_arn, priority, params::Dict{String,<:Any})

Creates a rule for the specified listener. The listener must be associated with an
Application Load Balancer. Each rule consists of a priority, one or more actions, and one
or more conditions. Rules are evaluated in priority order, from the lowest value to the
highest value. When the conditions for a rule are met, its actions are performed. If the
conditions for no rules are met, the actions for the default rule are performed. For more
information, see Listener rules in the Application Load Balancers Guide.

# Arguments
- `actions`: The actions.
- `conditions`: The conditions.
- `listener_arn`: The Amazon Resource Name (ARN) of the listener.
- `priority`: The rule priority. A listener can't have multiple rules with the same
  priority.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Tags"`: The tags to assign to the rule.
"""
create_rule(Actions, Conditions, ListenerArn, Priority; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateRule", Dict{String, Any}("Actions"=>Actions, "Conditions"=>Conditions, "ListenerArn"=>ListenerArn, "Priority"=>Priority); aws_config=aws_config)
create_rule(Actions, Conditions, ListenerArn, Priority, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateRule", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Actions"=>Actions, "Conditions"=>Conditions, "ListenerArn"=>ListenerArn, "Priority"=>Priority), params)); aws_config=aws_config)

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

Creates a target group. For more information, see the following:    Target groups for your
Application Load Balancers     Target groups for your Network Load Balancers     Target
groups for your Gateway Load Balancers    This operation is idempotent, which means that it
completes at most one time. If you attempt to create multiple target groups with the same
settings, each call succeeds.

# Arguments
- `name`: The name of the target group. This name must be unique per region per account,
  can have a maximum of 32 characters, must contain only alphanumeric characters or hyphens,
  and must not begin or end with a hyphen.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"HealthCheckEnabled"`: Indicates whether health checks are enabled. If the target type
  is lambda, health checks are disabled by default but can be enabled. If the target type is
  instance or ip, health checks are always enabled and cannot be disabled.
- `"HealthCheckIntervalSeconds"`: The approximate amount of time, in seconds, between
  health checks of an individual target. If the target group protocol is TCP, TLS, UDP, or
  TCP_UDP, the supported values are 10 and 30 seconds. If the target group protocol is HTTP
  or HTTPS, the default is 30 seconds. If the target group protocol is GENEVE, the default is
  10 seconds. If the target type is lambda, the default is 35 seconds.
- `"HealthCheckPath"`: [HTTP/HTTPS health checks] The destination for health checks on the
  targets. [HTTP1 or HTTP2 protocol version] The ping path. The default is /. [GRPC protocol
  version] The path of a custom health check method with the format /package.service/method.
  The default is /AWS.ALB/healthcheck.
- `"HealthCheckPort"`: The port the load balancer uses when performing health checks on
  targets. If the protocol is HTTP, HTTPS, TCP, TLS, UDP, or TCP_UDP, the default is
  traffic-port, which is the port on which each target receives traffic from the load
  balancer. If the protocol is GENEVE, the default is port 80.
- `"HealthCheckProtocol"`: The protocol the load balancer uses when performing health
  checks on targets. For Application Load Balancers, the default is HTTP. For Network Load
  Balancers and Gateway Load Balancers, the default is TCP. The TCP protocol is not supported
  for health checks if the protocol of the target group is HTTP or HTTPS. The GENEVE, TLS,
  UDP, and TCP_UDP protocols are not supported for health checks.
- `"HealthCheckTimeoutSeconds"`: The amount of time, in seconds, during which no response
  from a target means a failed health check. For target groups with a protocol of HTTP,
  HTTPS, or GENEVE, the default is 5 seconds. For target groups with a protocol of TCP or
  TLS, this value must be 6 seconds for HTTP health checks and 10 seconds for TCP and HTTPS
  health checks. If the target type is lambda, the default is 30 seconds.
- `"HealthyThresholdCount"`: The number of consecutive health checks successes required
  before considering an unhealthy target healthy. For target groups with a protocol of HTTP
  or HTTPS, the default is 5. For target groups with a protocol of TCP, TLS, or GENEVE, the
  default is 3. If the target type is lambda, the default is 5.
- `"Matcher"`: [HTTP/HTTPS health checks] The HTTP or gRPC codes to use when checking for a
  successful response from a target.
- `"Port"`: The port on which the targets receive traffic. This port is used unless you
  specify a port override when registering the target. If the target is a Lambda function,
  this parameter does not apply. If the protocol is GENEVE, the supported port is 6081.
- `"Protocol"`: The protocol to use for routing traffic to the targets. For Application
  Load Balancers, the supported protocols are HTTP and HTTPS. For Network Load Balancers, the
  supported protocols are TCP, TLS, UDP, or TCP_UDP. For Gateway Load Balancers, the
  supported protocol is GENEVE. A TCP_UDP listener must be associated with a TCP_UDP target
  group. If the target is a Lambda function, this parameter does not apply.
- `"ProtocolVersion"`: [HTTP/HTTPS protocol] The protocol version. Specify GRPC to send
  requests to targets using gRPC. Specify HTTP2 to send requests to targets using HTTP/2. The
  default is HTTP1, which sends requests to targets using HTTP/1.1.
- `"Tags"`: The tags to assign to the target group.
- `"TargetType"`: The type of target that you must specify when registering targets with
  this target group. You can't specify targets for a target group using more than one target
  type.    instance - Register targets by instance ID. This is the default value.    ip -
  Register targets by IP address. You can specify IP addresses from the subnets of the
  virtual private cloud (VPC) for the target group, the RFC 1918 range (10.0.0.0/8,
  172.16.0.0/12, and 192.168.0.0/16), and the RFC 6598 range (100.64.0.0/10). You can't
  specify publicly routable IP addresses.    lambda - Register a single Lambda function as a
  target.
- `"UnhealthyThresholdCount"`: The number of consecutive health check failures required
  before considering a target unhealthy. If the target group protocol is HTTP or HTTPS, the
  default is 2. If the target group protocol is TCP or TLS, this value must be the same as
  the healthy threshold count. If the target group protocol is GENEVE, the default is 3. If
  the target type is lambda, the default is 2.
- `"VpcId"`: The identifier of the virtual private cloud (VPC). If the target is a Lambda
  function, this parameter does not apply. Otherwise, this parameter is required.
"""
create_target_group(Name; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateTargetGroup", Dict{String, Any}("Name"=>Name); aws_config=aws_config)
create_target_group(Name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("CreateTargetGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name), params)); aws_config=aws_config)

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

Deletes the specified listener. Alternatively, your listener is deleted when you delete the
load balancer to which it is attached.

# Arguments
- `listener_arn`: The Amazon Resource Name (ARN) of the listener.

"""
delete_listener(ListenerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteListener", Dict{String, Any}("ListenerArn"=>ListenerArn); aws_config=aws_config)
delete_listener(ListenerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteListener", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ListenerArn"=>ListenerArn), params)); aws_config=aws_config)

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

Deletes the specified Application Load Balancer, Network Load Balancer, or Gateway Load
Balancer. Deleting a load balancer also deletes its listeners. You can't delete a load
balancer if deletion protection is enabled. If the load balancer does not exist or has
already been deleted, the call succeeds. Deleting a load balancer does not affect its
registered targets. For example, your EC2 instances continue to run and are still
registered to their target groups. If you no longer need these EC2 instances, you can stop
or terminate them.

# Arguments
- `load_balancer_arn`: The Amazon Resource Name (ARN) of the load balancer.

"""
delete_load_balancer(LoadBalancerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteLoadBalancer", Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn); aws_config=aws_config)
delete_load_balancer(LoadBalancerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteLoadBalancer", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn), params)); aws_config=aws_config)

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

Deletes the specified rule. You can't delete the default rule.

# Arguments
- `rule_arn`: The Amazon Resource Name (ARN) of the rule.

"""
delete_rule(RuleArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteRule", Dict{String, Any}("RuleArn"=>RuleArn); aws_config=aws_config)
delete_rule(RuleArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteRule", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RuleArn"=>RuleArn), params)); aws_config=aws_config)

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

Deletes the specified target group. You can delete a target group if it is not referenced
by any actions. Deleting a target group also deletes any associated health checks. Deleting
a target group does not affect its registered targets. For example, any EC2 instances
continue to run until you stop or terminate them.

# Arguments
- `target_group_arn`: The Amazon Resource Name (ARN) of the target group.

"""
delete_target_group(TargetGroupArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteTargetGroup", Dict{String, Any}("TargetGroupArn"=>TargetGroupArn); aws_config=aws_config)
delete_target_group(TargetGroupArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeleteTargetGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TargetGroupArn"=>TargetGroupArn), params)); aws_config=aws_config)

"""
    deregister_targets(target_group_arn, targets)
    deregister_targets(target_group_arn, targets, params::Dict{String,<:Any})

Deregisters the specified targets from the specified target group. After the targets are
deregistered, they no longer receive traffic from the load balancer.

# Arguments
- `target_group_arn`: The Amazon Resource Name (ARN) of the target group.
- `targets`: The targets. If you specified a port override when you registered a target,
  you must specify both the target ID and the port when you deregister it.

"""
deregister_targets(TargetGroupArn, Targets; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeregisterTargets", Dict{String, Any}("TargetGroupArn"=>TargetGroupArn, "Targets"=>Targets); aws_config=aws_config)
deregister_targets(TargetGroupArn, Targets, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DeregisterTargets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TargetGroupArn"=>TargetGroupArn, "Targets"=>Targets), params)); aws_config=aws_config)

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

Describes the current Elastic Load Balancing resource limits for your AWS account. For more
information, see the following:    Quotas for your Application Load Balancers     Quotas
for your Network Load Balancers     Quotas for your Gateway Load Balancers

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"PageSize"`: The maximum number of results to return with this call.
"""
describe_account_limits(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeAccountLimits"; aws_config=aws_config)
describe_account_limits(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeAccountLimits", params; aws_config=aws_config)

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

Describes the default certificate and the certificate list for the specified HTTPS or TLS
listener. If the default certificate is also in the certificate list, it appears twice in
the results (once with IsDefault set to true and once with IsDefault set to false). For
more information, see SSL certificates in the Application Load Balancers Guide or Server
certificates in the Network Load Balancers Guide.

# Arguments
- `listener_arn`: The Amazon Resource Names (ARN) of the listener.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"PageSize"`: The maximum number of results to return with this call.
"""
describe_listener_certificates(ListenerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeListenerCertificates", Dict{String, Any}("ListenerArn"=>ListenerArn); aws_config=aws_config)
describe_listener_certificates(ListenerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeListenerCertificates", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ListenerArn"=>ListenerArn), params)); aws_config=aws_config)

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

Describes the specified listeners or the listeners for the specified Application Load
Balancer, Network Load Balancer, or Gateway Load Balancer. You must specify either a load
balancer or one or more listeners.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ListenerArns"`: The Amazon Resource Names (ARN) of the listeners.
- `"LoadBalancerArn"`: The Amazon Resource Name (ARN) of the load balancer.
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"PageSize"`: The maximum number of results to return with this call.
"""
describe_listeners(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeListeners"; aws_config=aws_config)
describe_listeners(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeListeners", params; aws_config=aws_config)

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

Describes the attributes for the specified Application Load Balancer, Network Load
Balancer, or Gateway Load Balancer. For more information, see the following:    Load
balancer attributes in the Application Load Balancers Guide     Load balancer attributes in
the Network Load Balancers Guide     Load balancer attributes in the Gateway Load Balancers
Guide

# Arguments
- `load_balancer_arn`: The Amazon Resource Name (ARN) of the load balancer.

"""
describe_load_balancer_attributes(LoadBalancerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeLoadBalancerAttributes", Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn); aws_config=aws_config)
describe_load_balancer_attributes(LoadBalancerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeLoadBalancerAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn), params)); aws_config=aws_config)

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

Describes the specified load balancers or all of your load balancers.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LoadBalancerArns"`: The Amazon Resource Names (ARN) of the load balancers. You can
  specify up to 20 load balancers in a single call.
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"Names"`: The names of the load balancers.
- `"PageSize"`: The maximum number of results to return with this call.
"""
describe_load_balancers(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeLoadBalancers"; aws_config=aws_config)
describe_load_balancers(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeLoadBalancers", params; aws_config=aws_config)

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

Describes the specified rules or the rules for the specified listener. You must specify
either a listener or one or more rules.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ListenerArn"`: The Amazon Resource Name (ARN) of the listener.
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"PageSize"`: The maximum number of results to return with this call.
- `"RuleArns"`: The Amazon Resource Names (ARN) of the rules.
"""
describe_rules(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeRules"; aws_config=aws_config)
describe_rules(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeRules", params; aws_config=aws_config)

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

Describes the specified policies or all policies used for SSL negotiation. For more
information, see Security policies in the Application Load Balancers Guide or Security
policies in the Network Load Balancers Guide.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"Names"`: The names of the policies.
- `"PageSize"`: The maximum number of results to return with this call.
"""
describe_sslpolicies(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeSSLPolicies"; aws_config=aws_config)
describe_sslpolicies(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeSSLPolicies", params; aws_config=aws_config)

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

Describes the tags for the specified Elastic Load Balancing resources. You can describe the
tags for one or more Application Load Balancers, Network Load Balancers, Gateway Load
Balancers, target groups, listeners, or rules.

# Arguments
- `resource_arns`: The Amazon Resource Names (ARN) of the resources. You can specify up to
  20 resources in a single call.

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

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

Describes the attributes for the specified target group. For more information, see the
following:    Target group attributes in the Application Load Balancers Guide     Target
group attributes in the Network Load Balancers Guide     Target group attributes in the
Gateway Load Balancers Guide

# Arguments
- `target_group_arn`: The Amazon Resource Name (ARN) of the target group.

"""
describe_target_group_attributes(TargetGroupArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeTargetGroupAttributes", Dict{String, Any}("TargetGroupArn"=>TargetGroupArn); aws_config=aws_config)
describe_target_group_attributes(TargetGroupArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeTargetGroupAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TargetGroupArn"=>TargetGroupArn), params)); aws_config=aws_config)

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

Describes the specified target groups or all of your target groups. By default, all target
groups are described. Alternatively, you can specify one of the following to filter the
results: the ARN of the load balancer, the names of one or more target groups, or the ARNs
of one or more target groups.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LoadBalancerArn"`: The Amazon Resource Name (ARN) of the load balancer.
- `"Marker"`: The marker for the next set of results. (You received this marker from a
  previous call.)
- `"Names"`: The names of the target groups.
- `"PageSize"`: The maximum number of results to return with this call.
- `"TargetGroupArns"`: The Amazon Resource Names (ARN) of the target groups.
"""
describe_target_groups(; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeTargetGroups"; aws_config=aws_config)
describe_target_groups(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeTargetGroups", params; aws_config=aws_config)

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

Describes the health of the specified targets or all of your targets.

# Arguments
- `target_group_arn`: The Amazon Resource Name (ARN) of the target group.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Targets"`: The targets.
"""
describe_target_health(TargetGroupArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeTargetHealth", Dict{String, Any}("TargetGroupArn"=>TargetGroupArn); aws_config=aws_config)
describe_target_health(TargetGroupArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("DescribeTargetHealth", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TargetGroupArn"=>TargetGroupArn), params)); aws_config=aws_config)

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

Replaces the specified properties of the specified listener. Any properties that you do not
specify remain unchanged. Changing the protocol from HTTPS to HTTP, or from TLS to TCP,
removes the security policy and default certificate properties. If you change the protocol
from HTTP to HTTPS, or from TCP to TLS, you must add the security policy and default
certificate properties. To add an item to a list, remove an item from a list, or update an
item in a list, you must provide the entire list. For example, to add an action, specify a
list with the current actions plus the new action.

# Arguments
- `listener_arn`: The Amazon Resource Name (ARN) of the listener.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"AlpnPolicy"`: [TLS listeners] The name of the Application-Layer Protocol Negotiation
  (ALPN) policy. You can specify one policy name. The following are the possible values:
  HTTP1Only     HTTP2Only     HTTP2Optional     HTTP2Preferred     None    For more
  information, see ALPN policies in the Network Load Balancers Guide.
- `"Certificates"`: [HTTPS and TLS listeners] The default certificate for the listener. You
  must provide exactly one certificate. Set CertificateArn to the certificate ARN but do not
  set IsDefault.
- `"DefaultActions"`: The actions for the default rule.
- `"Port"`: The port for connections from clients to the load balancer. You cannot specify
  a port for a Gateway Load Balancer.
- `"Protocol"`: The protocol for connections from clients to the load balancer. Application
  Load Balancers support the HTTP and HTTPS protocols. Network Load Balancers support the
  TCP, TLS, UDP, and TCP_UDP protocols. You can’t change the protocol to UDP or TCP_UDP if
  dual-stack mode is enabled. You cannot specify a protocol for a Gateway Load Balancer.
- `"SslPolicy"`: [HTTPS and TLS listeners] The security policy that defines which protocols
  and ciphers are supported. For more information, see Security policies in the Application
  Load Balancers Guide or Security policies in the Network Load Balancers Guide.
"""
modify_listener(ListenerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyListener", Dict{String, Any}("ListenerArn"=>ListenerArn); aws_config=aws_config)
modify_listener(ListenerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyListener", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ListenerArn"=>ListenerArn), params)); aws_config=aws_config)

"""
    modify_load_balancer_attributes(attributes, load_balancer_arn)
    modify_load_balancer_attributes(attributes, load_balancer_arn, params::Dict{String,<:Any})

Modifies the specified attributes of the specified Application Load Balancer, Network Load
Balancer, or Gateway Load Balancer. If any of the specified attributes can't be modified as
requested, the call fails. Any existing attributes that you do not modify retain their
current values.

# Arguments
- `attributes`: The load balancer attributes.
- `load_balancer_arn`: The Amazon Resource Name (ARN) of the load balancer.

"""
modify_load_balancer_attributes(Attributes, LoadBalancerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyLoadBalancerAttributes", Dict{String, Any}("Attributes"=>Attributes, "LoadBalancerArn"=>LoadBalancerArn); aws_config=aws_config)
modify_load_balancer_attributes(Attributes, LoadBalancerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyLoadBalancerAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Attributes"=>Attributes, "LoadBalancerArn"=>LoadBalancerArn), params)); aws_config=aws_config)

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

Replaces the specified properties of the specified rule. Any properties that you do not
specify are unchanged. To add an item to a list, remove an item from a list, or update an
item in a list, you must provide the entire list. For example, to add an action, specify a
list with the current actions plus the new action.

# Arguments
- `rule_arn`: The Amazon Resource Name (ARN) of the rule.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Actions"`: The actions.
- `"Conditions"`: The conditions.
"""
modify_rule(RuleArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyRule", Dict{String, Any}("RuleArn"=>RuleArn); aws_config=aws_config)
modify_rule(RuleArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyRule", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RuleArn"=>RuleArn), params)); aws_config=aws_config)

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

Modifies the health checks used when evaluating the health state of the targets in the
specified target group.

# Arguments
- `target_group_arn`: The Amazon Resource Name (ARN) of the target group.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"HealthCheckEnabled"`: Indicates whether health checks are enabled.
- `"HealthCheckIntervalSeconds"`: The approximate amount of time, in seconds, between
  health checks of an individual target. For TCP health checks, the supported values are 10
  or 30 seconds. With Network Load Balancers, you can't modify this setting.
- `"HealthCheckPath"`: [HTTP/HTTPS health checks] The destination for health checks on the
  targets. [HTTP1 or HTTP2 protocol version] The ping path. The default is /. [GRPC protocol
  version] The path of a custom health check method with the format /package.service/method.
  The default is /AWS.ALB/healthcheck.
- `"HealthCheckPort"`: The port the load balancer uses when performing health checks on
  targets.
- `"HealthCheckProtocol"`: The protocol the load balancer uses when performing health
  checks on targets. The TCP protocol is supported for health checks only if the protocol of
  the target group is TCP, TLS, UDP, or TCP_UDP. The GENEVE, TLS, UDP, and TCP_UDP protocols
  are not supported for health checks. With Network Load Balancers, you can't modify this
  setting.
- `"HealthCheckTimeoutSeconds"`: [HTTP/HTTPS health checks] The amount of time, in seconds,
  during which no response means a failed health check. With Network Load Balancers, you
  can't modify this setting.
- `"HealthyThresholdCount"`: The number of consecutive health checks successes required
  before considering an unhealthy target healthy.
- `"Matcher"`: [HTTP/HTTPS health checks] The HTTP or gRPC codes to use when checking for a
  successful response from a target. With Network Load Balancers, you can't modify this
  setting.
- `"UnhealthyThresholdCount"`: The number of consecutive health check failures required
  before considering the target unhealthy. For target groups with a protocol of TCP or TLS,
  this value must be the same as the healthy threshold count.
"""
modify_target_group(TargetGroupArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyTargetGroup", Dict{String, Any}("TargetGroupArn"=>TargetGroupArn); aws_config=aws_config)
modify_target_group(TargetGroupArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyTargetGroup", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TargetGroupArn"=>TargetGroupArn), params)); aws_config=aws_config)

"""
    modify_target_group_attributes(attributes, target_group_arn)
    modify_target_group_attributes(attributes, target_group_arn, params::Dict{String,<:Any})

Modifies the specified attributes of the specified target group.

# Arguments
- `attributes`: The attributes.
- `target_group_arn`: The Amazon Resource Name (ARN) of the target group.

"""
modify_target_group_attributes(Attributes, TargetGroupArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyTargetGroupAttributes", Dict{String, Any}("Attributes"=>Attributes, "TargetGroupArn"=>TargetGroupArn); aws_config=aws_config)
modify_target_group_attributes(Attributes, TargetGroupArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("ModifyTargetGroupAttributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Attributes"=>Attributes, "TargetGroupArn"=>TargetGroupArn), params)); aws_config=aws_config)

"""
    register_targets(target_group_arn, targets)
    register_targets(target_group_arn, targets, params::Dict{String,<:Any})

Registers the specified targets with the specified target group. If the target is an EC2
instance, it must be in the running state when you register it. By default, the load
balancer routes requests to registered targets using the protocol and port for the target
group. Alternatively, you can override the port for a target when you register it. You can
register each EC2 instance or IP address with the same target group multiple times using
different ports. With a Network Load Balancer, you cannot register instances by instance ID
if they have the following instance types: C1, CC1, CC2, CG1, CG2, CR1, CS1, G1, G2, HI1,
HS1, M1, M2, M3, and T1. You can register instances of these types by IP address.

# Arguments
- `target_group_arn`: The Amazon Resource Name (ARN) of the target group.
- `targets`: The targets.

"""
register_targets(TargetGroupArn, Targets; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("RegisterTargets", Dict{String, Any}("TargetGroupArn"=>TargetGroupArn, "Targets"=>Targets); aws_config=aws_config)
register_targets(TargetGroupArn, Targets, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("RegisterTargets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("TargetGroupArn"=>TargetGroupArn, "Targets"=>Targets), params)); aws_config=aws_config)

"""
    remove_listener_certificates(certificates, listener_arn)
    remove_listener_certificates(certificates, listener_arn, params::Dict{String,<:Any})

Removes the specified certificate from the certificate list for the specified HTTPS or TLS
listener.

# Arguments
- `certificates`: The certificate to remove. You can specify one certificate per call. Set
  CertificateArn to the certificate ARN but do not set IsDefault.
- `listener_arn`: The Amazon Resource Name (ARN) of the listener.

"""
remove_listener_certificates(Certificates, ListenerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("RemoveListenerCertificates", Dict{String, Any}("Certificates"=>Certificates, "ListenerArn"=>ListenerArn); aws_config=aws_config)
remove_listener_certificates(Certificates, ListenerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("RemoveListenerCertificates", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Certificates"=>Certificates, "ListenerArn"=>ListenerArn), params)); aws_config=aws_config)

"""
    remove_tags(resource_arns, tag_keys)
    remove_tags(resource_arns, tag_keys, params::Dict{String,<:Any})

Removes the specified tags from the specified Elastic Load Balancing resources. You can
remove the tags for one or more Application Load Balancers, Network Load Balancers, Gateway
Load Balancers, target groups, listeners, or rules.

# Arguments
- `resource_arns`: The Amazon Resource Name (ARN) of the resource.
- `tag_keys`: The tag keys for the tags to remove.

"""
remove_tags(ResourceArns, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("RemoveTags", Dict{String, Any}("ResourceArns"=>ResourceArns, "TagKeys"=>TagKeys); aws_config=aws_config)
remove_tags(ResourceArns, TagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("RemoveTags", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceArns"=>ResourceArns, "TagKeys"=>TagKeys), params)); aws_config=aws_config)

"""
    set_ip_address_type(ip_address_type, load_balancer_arn)
    set_ip_address_type(ip_address_type, load_balancer_arn, params::Dict{String,<:Any})

Sets the type of IP addresses used by the subnets of the specified Application Load
Balancer or Network Load Balancer.

# Arguments
- `ip_address_type`: The IP address type. The possible values are ipv4 (for IPv4 addresses)
  and dualstack (for IPv4 and IPv6 addresses). Internal load balancers must use ipv4. You
  can’t specify dualstack for a load balancer with a UDP or TCP_UDP listener.
- `load_balancer_arn`: The Amazon Resource Name (ARN) of the load balancer.

"""
set_ip_address_type(IpAddressType, LoadBalancerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetIpAddressType", Dict{String, Any}("IpAddressType"=>IpAddressType, "LoadBalancerArn"=>LoadBalancerArn); aws_config=aws_config)
set_ip_address_type(IpAddressType, LoadBalancerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetIpAddressType", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IpAddressType"=>IpAddressType, "LoadBalancerArn"=>LoadBalancerArn), params)); aws_config=aws_config)

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

Sets the priorities of the specified rules. You can reorder the rules as long as there are
no priority conflicts in the new order. Any existing rules that you do not specify retain
their current priority.

# Arguments
- `rule_priorities`: The rule priorities.

"""
set_rule_priorities(RulePriorities; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetRulePriorities", Dict{String, Any}("RulePriorities"=>RulePriorities); aws_config=aws_config)
set_rule_priorities(RulePriorities, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetRulePriorities", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RulePriorities"=>RulePriorities), params)); aws_config=aws_config)

"""
    set_security_groups(load_balancer_arn, security_groups)
    set_security_groups(load_balancer_arn, security_groups, params::Dict{String,<:Any})

Associates the specified security groups with the specified Application Load Balancer. The
specified security groups override the previously associated security groups. You can't
specify a security group for a Network Load Balancer or Gateway Load Balancer.

# Arguments
- `load_balancer_arn`: The Amazon Resource Name (ARN) of the load balancer.
- `security_groups`: The IDs of the security groups.

"""
set_security_groups(LoadBalancerArn, SecurityGroups; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetSecurityGroups", Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn, "SecurityGroups"=>SecurityGroups); aws_config=aws_config)
set_security_groups(LoadBalancerArn, SecurityGroups, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetSecurityGroups", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn, "SecurityGroups"=>SecurityGroups), params)); aws_config=aws_config)

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

Enables the Availability Zones for the specified public subnets for the specified
Application Load Balancer or Network Load Balancer. The specified subnets replace the
previously enabled subnets. When you specify subnets for a Network Load Balancer, you must
include all subnets that were enabled previously, with their existing configurations, plus
any additional subnets.

# Arguments
- `load_balancer_arn`: The Amazon Resource Name (ARN) of the load balancer.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"IpAddressType"`: [Network Load Balancers] The type of IP addresses used by the subnets
  for your load balancer. The possible values are ipv4 (for IPv4 addresses) and dualstack
  (for IPv4 and IPv6 addresses). You can’t specify dualstack for a load balancer with a UDP
  or TCP_UDP listener. Internal load balancers must use ipv4.
- `"SubnetMappings"`: The IDs of the public subnets. You can specify only one subnet per
  Availability Zone. You must specify either subnets or subnet mappings. [Application Load
  Balancers] You must specify subnets from at least two Availability Zones. You cannot
  specify Elastic IP addresses for your subnets. [Application Load Balancers on Outposts] You
  must specify one Outpost subnet. [Application Load Balancers on Local Zones] You can
  specify subnets from one or more Local Zones. [Network Load Balancers] You can specify
  subnets from one or more Availability Zones. You can specify one Elastic IP address per
  subnet if you need static IP addresses for your internet-facing load balancer. For internal
  load balancers, you can specify one private IP address per subnet from the IPv4 range of
  the subnet. For internet-facing load balancer, you can specify one IPv6 address per subnet.
- `"Subnets"`: The IDs of the public subnets. You can specify only one subnet per
  Availability Zone. You must specify either subnets or subnet mappings. [Application Load
  Balancers] You must specify subnets from at least two Availability Zones. [Application Load
  Balancers on Outposts] You must specify one Outpost subnet. [Application Load Balancers on
  Local Zones] You can specify subnets from one or more Local Zones. [Network Load Balancers]
  You can specify subnets from one or more Availability Zones.
"""
set_subnets(LoadBalancerArn; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetSubnets", Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn); aws_config=aws_config)
set_subnets(LoadBalancerArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = elastic_load_balancing_v2("SetSubnets", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LoadBalancerArn"=>LoadBalancerArn), params)); aws_config=aws_config)