{"text": "#=\n\n####\n#### Reads profiles needed for RRTMGP and related\n#### calculations assuming a certain netCDF file layout\n####\n\nThis file reads an example file containing atmospheric conditions (temperature, pressure, gas concentrations)\n and surface properties (emissivity, temperature), defined on `nlay` layers across a set of `ncol` columns subject to\n `nexp` perturbations, and returns them in data structures suitable for use in rte and rrtmpg. The input data\n are partitioned into a user-specified number of blocks.\nFor the moment only quantities relevant to longwave calculations are provided.\n\nThe example files comes from the Radiative Forcing MIP (https://www.earthsystemcog.org/projects/rfmip/)\n The protocol for this experiment allows for different specifications of which gases to consider:\nall gases, (CO2, CH4, N2O) + {CFC11eq; CFC12eq + HFC-134eq}. Ozone is always included\nThe protocol does not specify the treatment of gases like CO\n\n# Convention\n\nNote that `ds` is used to denote an NC dataset.\n=#\n\nusing RRTMGP.GasConcentrations\nusing RRTMGP.Utilities\nusing RRTMGP.Gases\nusing NCDatasets\n\n\"\"\"\n read_atmos(ds, FT, I, gases_prescribed)\n\nRead profiles for all columns\n - `p_lay` pressure (layers)\n - `t_lay` temperature (layers)\n - `p_lev` pressure (levels)\n - `t_lev` temperature (levels)\n - `col_dry` gas concentrations\n\"\"\"\nfunction read_atmos(ds, FT, I, gases_prescribed)\n\n ncol = ds.dim[\"col\"]\n nlay = ds.dim[\"lay\"]\n nlev = ds.dim[\"lev\"]\n @assert nlev == nlay + 1\n\n p_lay = Array{FT}(ds[\"p_lay\"][:])\n t_lay = Array{FT}(ds[\"t_lay\"][:])\n p_lev = Array{FT}(ds[\"p_lev\"][:])\n t_lev = Array{FT}(ds[\"t_lev\"][:])\n\n gases_to_look_for = [\n h2o(),\n co2(),\n o3(),\n n2o(),\n co(),\n ch4(),\n o2(),\n n2(),\n ccl4(),\n cfc11(),\n cfc12(),\n cfc22(),\n hfc143a(),\n hfc125(),\n hfc23(),\n hfc32(),\n hfc134a(),\n cf4(),\n no2(),\n ]\n\n gases_in_database = filter(ug -> haskey(ds, \"vmr_\" * chem_name(ug)), gases_to_look_for)\n\n gas_concs = GasConcs(FT, I, gases_prescribed, ncol, nlay, length(gases_in_database))\n\n for eg in gases_in_database\n set_vmr!(gas_concs, eg, Array{FT}(ds[\"vmr_\" * chem_name(eg)][:]))\n end\n\n # col_dry has unchanged allocation status on return if the variable isn't present in the netCDF file\n col_dry = haskey(ds, \"col_dry\") ? Array{FT}(ds[\"col_dry\"][:]) : nothing\n\n return p_lay, t_lay, p_lev, t_lev, gas_concs, col_dry\nend\n\n\n\"\"\"\n is_sw(ds)\n\nDoes this file contain variables needed to do SW calculations?\n\"\"\"\nis_sw(ds) = haskey(ds, \"solar_zenith_angle\")\n\n\"\"\"\n is_lw(ds)\n\nDoes this file contain variables needed to do LW calculations?\n\"\"\"\nis_lw(ds) = !is_sw(ds)\n\n\"\"\"\n read_lw_bc(ds)\n\nRead LW boundary conditions for all columns\n\"\"\"\nread_lw_bc(ds) = ds[\"t_sfc\"][:], ds[\"emis_sfc\"][:]\n\n\"\"\"\n read_lw_rt(ds)\n\nRead LW radiative transfer parameters\n\"\"\"\nread_lw_rt(ds) = length(size(ds[\"angle\"]))\n\n\"\"\"\n read_sw_bc(ds)\n\nRead SW boundary conditions for all columns\n\"\"\"\nread_sw_bc(ds) = (\n ds[\"solar_zenith_angle\"][:],\n ds[\"total_solar_irradiance\"][:],\n ds[\"sfc_alb_direct\"],\n ds[\"sfc_alb_diffuse\"],\n haskey(ds, \"tsi_scaling\") ? ds[\"tsi_scaling\"][:] : nothing,\n)\n\n\n\"\"\"\n read_spectral_disc!(ds, spectral_disc::AbstractOpticalProps)\n\nRead spectral discretization\n\"\"\"\nfunction read_spectral_disc!(ds, spectral_disc::AbstractOpticalProps)\n @assert ds.dim[\"pair\"] == 2\n band_lims_wvn = ds[\"band_lims_wvn\"][:]\n band_lims_gpt = ds[\"band_lims_gpt\"][:]\n spectral_disc.base = OpticalPropsBase(\"read_spectral_disc!\", band_lims_wvn, band_lims_gpt)\nend\n\n\"\"\"\n read_sfc_test_file(ds)\n\nRead surface SW albedo and LW emissivity spectra from the surface test file\n\"\"\"\nread_sfc_test_file(ds) = (ds[\"SW_albedo\"][:], ds[\"LW_emissivity\"][:])\n\n\"\"\"\n read_direction(ds)\n\nWhich direction is up? Stored as a global attribute.\n\"\"\"\nread_direction(ds) = (ds.attrib[\"top_at_1\"] == 1)\n\n\"\"\"\n read_sources(ds)\n\nSources of upward and downward diffuse radiation, for each layer and at the surface\n\"\"\"\nread_sources(ds) = ds[\"source_up\"][:], ds[\"source_dn\"][:], ds[\"source_sfc\"][:]\n\n\"\"\"\n read_lw_Planck_sources!(ds, sources::SourceFuncLongWave{FT}) where FT\n\nLongwave sources at layer centers; edges in two directions; surface\n Also directionality since this will be needed for solution\n\"\"\"\nfunction read_lw_Planck_sources!(ds, sources::SourceFuncLongWave{FT}) where {FT}\n ncol = ds.dim[\"col\"]\n nlay = ds.dim[\"lay\"]\n ngpt = ds.dim[\"gpt\"]\n nband = ds.dim[\"band\"]\n # Error checking\n @assert ds.dim[\"pair\"] == 2\n @assert haskey(ds, \"lay_src\")\n\n # Spectral discretization\n band_lims_wvn = ds[\"band_lims_wvn\"][:]\n band_lims_gpt = ds[\"band_lims_gpt\"][:]\n\n sources.optical_props = OpticalPropsBase(\"SourceFuncLongWave\", band_lims_wvn, band_lims_gpt)\n sources.τ .= Array{FT}(undef, ncol, nlay)\n\n sources.lay_source .= ds[\"lay_src\"][:]\n sources.lev_source_inc .= ds[\"lev_src_inc\"][:]\n sources.lev_source_dec .= ds[\"lev_src_dec\"][:]\n sources.sfc_source .= ds[\"sfc_src\"][:]\n return nothing\n\nend\n\n\"\"\"\n read_sw_solar_sources(ds)\n\nShortwave source at TOA\n Also directionality since this will be needed for solution\n\"\"\"\nread_sw_solar_sources(ds) = ds[\"toa_src\"][:]\n\n\"\"\"\n read_two_stream(ds)\n\nTwo-stream results: reflection and transmission for diffuse and direct radiation; also extinction\n\"\"\"\nfunction read_two_stream(ds)\n Rdif = ds[\"Rdif\"][:]\n Tdif = ds[\"Tdif\"][:]\n Rdir = haskey(ds, \"Rdir\") ? ds[\"Rdir\"][:] : nothing\n Tdir = haskey(ds, \"Tdir\") ? ds[\"Tdir\"][:] : nothing\n Tnoscat = haskey(ds, \"Tnoscat\") ? ds[\"Tnoscat\"][:] : nothing\n return Rdif, Tdif, Rdir, Tdir, Tnoscat\nend\n\n\"\"\"\n read_gpt_fluxes(ds)\n\ng-point fluxes\n\"\"\"\nread_gpt_fluxes(ds) =\n (ds[\"gpt_flux_up\"][:], ds[\"gpt_flux_dn\"][:], haskey(ds, \"gpt_flux_dn_dir\") ? ds[\"gpt_flux_dn_dir\"][:] : nothing)\n\n\"\"\"\n read_size(ds)\n\nFind the size of the problem: columns, layers, perturbations (experiments)\n\"\"\"\nfunction read_size(ds)\n ncol = Int(ds.dim[\"site\"])\n nlay = Int(ds.dim[\"layer\"])\n nexp = Int(ds.dim[\"expt\"])\n @assert ds.dim[\"level\"] == nlay + 1\n return ncol, nlay, nexp\nend\n\n\"\"\"\n read_and_block_pt(ds)\n\nReturn layer and level\n\n - `p_lay` layer pressure dimensions (ncol, nlay, nblocks)\n - `p_lev` level pressure dimensions (ncol, nlay+1, nblocks)\n - `t_lay` layer temperature dimensions (ncol, nlay, nblocks)\n - `t_lev` level temperature dimensions (ncol, nlay+1, nblocks)\n\"\"\"\nfunction read_and_block_pt(ds)\n FT = Float64\n ncol_l, nlay_l, nexp_l = read_size(ds)\n @assert !any([ncol_l, nlay_l, nexp_l] .== 0)\n\n # Read p, T data; reshape to suit RRTMGP dimensions\n p_lay = Array(transpose(kron(ones(1, nexp_l), Array{FT}(ds[\"pres_layer\"][:]))))\n p_lev = Array(transpose(kron(ones(1, nexp_l), Array{FT}(ds[\"pres_level\"][:]))))\n t_lay = Array(transpose(reshape(Array{FT}(ds[\"temp_layer\"][:]), nlay_l, ncol_l * nexp_l)))\n t_lev = Array(transpose(reshape(Array{FT}(ds[\"temp_level\"][:]), nlay_l + 1, ncol_l * nexp_l)))\n\n return p_lay, p_lev, t_lay, t_lev\nend\n\n\"\"\"\n read_and_block_sw_bc(ds, blocksize)\n\nRead and reshape shortwave boundary conditions\n\n - `surface_albedo` surface albedo\n - `total_solar_irradiance` total solar irradiance\n - `solar_zenith_angle` solar zenith angle\n\"\"\"\nfunction read_and_block_sw_bc(ds)\n FT = Float64\n ncol_l, nlay_l, nexp_l = read_size(ds)\n blocksize = ncol_l * nexp_l\n @assert !any([ncol_l, nlay_l, nexp_l] .== 0)\n\n # Check that output arrays are sized correctly : blocksize, nlay, (ncol * nexp)/blocksize\n surface_albedo = repeat(Array{FT}(ds[\"surface_albedo\"][:]), nexp_l)\n total_solar_irradiance = repeat(Array{FT}(ds[\"total_solar_irradiance\"][:]), nexp_l)\n solar_zenith_angle = repeat(Array{FT}(ds[\"solar_zenith_angle\"][:]), nexp_l)\n return surface_albedo, total_solar_irradiance, solar_zenith_angle\nend\n\n\"\"\"\n read_and_block_lw_bc(ds, blocksize)\n\nRead and reshape longwave boundary conditions\n\n - `surface_emissivity` surface emissivity\n - `surface_temperature` surface temperature\n\"\"\"\nfunction read_and_block_lw_bc(ds)\n FT = Float64\n ncol_l, nlay_l, nexp_l = read_size(ds)\n ncols = ncol_l * nexp_l\n @assert !any([ncol_l, nlay_l, nexp_l] .== 0)\n\n surface_emissivity = Array{FT}(reshape(repeat(ds[\"surface_emissivity\"][:], 1, nexp_l), ncols))\n surface_temperature = Array{FT}(reshape(ds[\"surface_temperature\"][:], ncols)) # alternate version\n\n return surface_emissivity, surface_temperature\nend\n\n\"\"\"\n determine_gas_names(ds, forcing_index)\n\nCreate a pair of string arrays - one containing the chemical name of each gas, used by the k-distribution, and\none containing the name as contained in the RFMIP input files - depending on the forcing scenario:\n\n - `forcing_index` (1 = all available greenhouse gases;\n 2 = CO2, CH4, N2O, CFC11eq\n 3 = CO2, CH4, N2O, CFC12eq, HFC-134eq\n All scenarios use 3D values of ozone, water vapor so those aren't listed here\n\"\"\"\nfunction determine_gas_names(ds, forcing_index)\n\n @assert any(forcing_index .== [1, 2, 3])\n if forcing_index == 1\n names_in_kdist = convert.(AbstractGas, read_kdist_gas_names(ds))\n\n # elseif forcing_index == 2\n\n # # Not part of the RFMIP specification, but oxygen is included because it's a major\n # # gas in some bands in the SW\n # names_in_kdist = [co2(), ch4(), n2o(), o2(), cfc12(), cfc11()]\n # elseif forcing_index == 3\n\n # # Not part of the RFMIP specification, but oxygen is included because it's a major\n # # gas in some bands in the SW\n # names_in_kdist = [co2(), ch4(), n2o(), o2(), cfc12(), hfc134a()]\n end\n return names_in_kdist\n\nend\n\n\"\"\"\n read_kdist_gas_names(ds)\n\nRead the names of the gases known to the k-distribution\n\"\"\"\nread_kdist_gas_names(ds) = lowercase.(strip.(String[join(ds[\"gas_names\"][:][:, i]) for i in 1:ds.dim[\"absorber\"]]))\n\n\"\"\"\n read_and_block_gases_ty(ds, gas_names)\n\nRead and reshape gas concentrations. RRTMGP requires gas concentrations to be supplied via a class\n(GasConcs). Gas concentrations are set via a call to set_vmr!(gas_concs, name, values)\nwhere `name` is nominally the chemical formula for the gas in question and `values` may be\na scalar, a 1-d profile assumed to apply to all columns, or an array of dimension (`ncol`, `nlay`).\n\nThis routine outputs a vector `nblocks` long of these types so each element of the array can be passed to\nthe rrtmgp gas optics calculation in turn.\n\nThis routine exploits RFMIP conventions: only water vapor and ozone vary by column within\neach experiment.\n\nFields in the RFMIP file have a trailing _GM (global mean); some fields use a chemical formula and other\na descriptive name, so a map is provided between these.\n\n - `gas_names` Names used by the k-distribution/gas concentration type\n - `gas_conc_array` vector of [`GasConcs`](@ref)\n\"\"\"\nfunction read_and_block_gases_ty(ds, gas_names::Vector{AbstractGas})\n ncol_l, nlay_l, nexp_l = read_size(ds)\n ncols = ncol_l * nexp_l\n @assert !any([ncol_l, nlay_l, nexp_l] .== 0)\n FT = Float64\n I = Int\n gas_conc_array = GasConcs(FT, I, gas_names, ncols, nlay_l)\n\n # Experiment index for each column\n exp_num = repeat(collect(1:nexp_l)', ncol_l, 1)[:]\n # Water vapor and ozone depend on col, lay, exp: look just like other fields\n for gas in (h2o(), o3())\n gas_conc = Array{FT}(ds[rfmip_name(gas)][:])\n gas_conc_scaling = read_scaling(ds, FT, rfmip_name(gas))\n gas_conc_temp_3d = reshape(gas_conc, nlay_l, ncols) .* gas_conc_scaling\n gas_conc_temp_3d_t = convert(Array, transpose(gas_conc_temp_3d))\n set_vmr!(gas_conc_array, gas, gas_conc_temp_3d_t)\n end\n\n # All other gases are a function of experiment only\n for gas in gas_names\n\n # Skip 3D fields above, also NO2 since RFMIP doesn't have this\n if gas in [h2o(), o3(), no2()]\n continue\n end\n\n # Read the values as a function of experiment\n gas_conc_scaling = read_scaling(ds, FT, rfmip_name(gas) * \"_GM\")\n gas_conc_temp_1d = ds[rfmip_name(gas) * \"_GM\"][:] * gas_conc_scaling\n\n # Does every value in this block belong to the same experiment?\n if all(exp_num[2:end] .- exp_num[1] .== 0)\n # Provide a scalar value\n set_vmr!(gas_conc_array, gas, gas_conc_temp_1d[exp_num[1]])\n else\n # Create 2D field, ncols x nlay, with scalar values from each experiment\n set_vmr!(gas_conc_array, gas, repeat(gas_conc_temp_1d[exp_num[:]], 1, nlay_l))\n end\n end\n return gas_conc_array\nend\n\nread_scaling(ds, FT, varName) = parse(FT, ds[varName].attrib[\"units\"])\n", "meta": {"hexsha": "9bce7743a0db9b67b0b1688b6f0537822b47d3f8", "size": 12808, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ReadInputData/ReadInputs.jl", "max_stars_repo_name": "climate-machine/JRRTMGP", "max_stars_repo_head_hexsha": "e5c0c735a68bc2fff965fce1b9d066ffea17d6b1", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ReadInputData/ReadInputs.jl", "max_issues_repo_name": "climate-machine/JRRTMGP", "max_issues_repo_head_hexsha": "e5c0c735a68bc2fff965fce1b9d066ffea17d6b1", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2019-09-16T21:51:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-15T23:08:28.000Z", "max_forks_repo_path": "ReadInputData/ReadInputs.jl", "max_forks_repo_name": "climate-machine/JRRTMGP", "max_forks_repo_head_hexsha": "e5c0c735a68bc2fff965fce1b9d066ffea17d6b1", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.624691358, "max_line_length": 117, "alphanum_fraction": 0.6755933791, "num_tokens": 3774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}} {"text": "\"\"\"\n\ttraversal(potree::String, params::ParametersOrthophoto)\n\nTrie traversal.\nIf entire point cloud falls in volume process all files of Potree project\nelse travers trie, depth search first, and process nodes falling in region of interest.\n\nInput:\n - params: initial parameters\n - potree: potree hierarchy\n\"\"\"\nfunction traversal(potree::String, params::ParametersOrthophoto)\n flushprintln(\"= \")\n flushprintln(\"= PROJECT: $potree\")\n flushprintln(\"= \")\n\n metadata = CloudMetadata(potree) # metadata of current potree project\n trie = potree2trie(potree)\n params.numNodes = length(keys(trie))\n\n # if model contains the whole point cloud ( == 2)\n #\tprocess all files\n # else\n # \tnavigate potree\n\n intersection =\n Common.modelsdetection(params.model, metadata.tightBoundingBox)\n\n if intersection == 2\n flushprintln(\"FULL model\")\n for k in keys(trie)\n params.numFilesProcessed = params.numFilesProcessed + 1\n if params.numFilesProcessed % 100 == 0\n flushprintln(\n params.numFilesProcessed,\n \" files processed of \",\n params.numNodes,\n )\n end\n\n file = trie[k]\n updateWithoutControl!(params, file)\n\n end\n elseif intersection == 1\n flushprintln(\"DFS\")\n dfs(trie, params)\n\n if params.numNodes - params.numFilesProcessed > 0\n flushprintln(\"$(params.numNodes-params.numFilesProcessed) file of $(params.numNodes) not processed - out of region of interest\")\n end\n elseif intersection == 0\n flushprintln(\"OUT OF REGION OF INTEREST\")\n end\n\nend\n\n\n\"\"\"\n\tdfs(t::DataStructures.Trie{String},\n\tparams::Union{ParametersOrthophoto,ParametersExtraction},\n\ts::Union{Nothing,IOStream},n::Int64,nfiles::Int64,l::Int64)\n\nDepth search first.\n\"\"\"\nfunction dfs(trie::DataStructures.Trie{String}, params::ParametersOrthophoto)# due callback: 1 con controllo e 1 senza controllo\n\n file = trie.value # path to node file\n nodebb = FileManager.las2aabb(file) # aabb of current octree\n inter = Common.modelsdetection(params.model, nodebb)\n\n if inter == 1\n # intersecato ma non contenuto\n # alcuni punti ricadono nel modello altri no\n params.numFilesProcessed = params.numFilesProcessed + 1\n if params.numFilesProcessed % 100 == 0\n flushprintln(\n params.numFilesProcessed,\n \" files processed of \",\n params.numNodes,\n )\n end\n\n updateWithControl!(params, file) # update with check\n for key in collect(keys(trie.children)) # for all children\n dfs(trie.children[key], params)\n end\n elseif inter == 2\n # contenuto: tutti i punti del albero sono nel modello\n for k in keys(trie)\n params.numFilesProcessed = params.numFilesProcessed + 1\n if params.numFilesProcessed % 100 == 0\n flushprintln(\n params.numFilesProcessed,\n \" files processed of \",\n params.numNodes,\n )\n end\n file = trie[k]\n updateWithoutControl!(params, file) # update without check\n end\n end\n\nend\n", "meta": {"hexsha": "5fac0aa0bc0b02c07edeededc8a8e635a2f8857e", "size": 3289, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trie_traversal.jl", "max_stars_repo_name": "marteresagh/OrthographicProjection.jl", "max_stars_repo_head_hexsha": "74c75f8d816ad296bbb7e5c0061de841f59efcb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/trie_traversal.jl", "max_issues_repo_name": "marteresagh/OrthographicProjection.jl", "max_issues_repo_head_hexsha": "74c75f8d816ad296bbb7e5c0061de841f59efcb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/trie_traversal.jl", "max_forks_repo_name": "marteresagh/OrthographicProjection.jl", "max_forks_repo_head_hexsha": "74c75f8d816ad296bbb7e5c0061de841f59efcb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3238095238, "max_line_length": 140, "alphanum_fraction": 0.6202493159, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}} {"text": "###### This file is part of the MendelImpute.jl package.\n###### It contains relevant code to search breakpoints. \n###### Currently code for double breakpoint search is broken and commented out. \n\n\"\"\"\n continue_haplotype(X, compressed_Hunique, window, happair_prev, happair_next)\n\nSearches the breakpoint between `happair_prev` and `happair_next`, if there is\none. \n\n# Arguments:\n- `X`: Genotype vector spanning 2 windows. \n- `compressed_Hunique`: A `CompressedHaplotypes` keeping track of unique\n haplotypes for each window and some other information\n- `window`: The current window being considered. It is the 2nd window of `X`. \n- `happair_prev`: Haplotype pair for first window\n- `happair_next`: Haplotype pair for second window\n\n# Optional arguments:\n- `phased`: Boolean indicating whether `happair_prev` and `happair_next` have\n been phased. If `false`, will try 2 different orientations. \n- `search_double_bkpts`: If `true`, will search double breakpoints. If false \n the output `bkpt = (-2, -2)`\n\n# Output\n- `happair_next`: If `phase = false`, this is equal to `happair_next` for input. \n Otherwise it may be flipped\n- `bkpt`: Tuple of integer indicating optimal breakpoint starting from the \n previous window. `-1` indicates no breakpoints and `-2` indicates double \n breakpoint. \n\"\"\"\nfunction continue_haplotype(\n X::AbstractVector,\n compressed_Hunique::CompressedHaplotypes,\n window::Int,\n happair_prev::Tuple,\n happair_next::Tuple;\n phased::Bool = false,\n search_double_bkpts::Bool = false\n )\n\n # indices for complete reference panel\n i, j = happair_prev\n k, l = happair_next\n\n # both strands match\n if i == k && j == l\n return (k, l), (-1, -1)\n end\n if i == l && j == k && !phased\n return (l, k), (-1, -1)\n end\n\n # get unique haplotypes with only typed snps\n overlap = compressed_Hunique.overlap\n if overlap\n # create views on non-overlapping regions\n rprev = nonoverlap_range(compressed_Hunique, window - 1)\n rcurr = nonoverlap_range(compressed_Hunique, window)\n Hprev = view(compressed_Hunique.CW_typed[window - 1].uniqueH, rprev, :)\n Hcurr = view(compressed_Hunique.CW_typed[window].uniqueH, rcurr, :)\n else\n Hprev = compressed_Hunique.CW_typed[window - 1].uniqueH\n Hcurr = compressed_Hunique.CW_typed[window].uniqueH\n end\n\n # only one strand matches\n if i == k && j ≠ l\n iu = complete_idx_to_unique_typed_idx(i, window - 1, compressed_Hunique)\n ku = complete_idx_to_unique_typed_idx(k, window, compressed_Hunique)\n ju1 = complete_idx_to_unique_typed_idx(j, window - 1, compressed_Hunique)\n ju2 = complete_idx_to_unique_typed_idx(j, window, compressed_Hunique)\n lu1 = complete_idx_to_unique_typed_idx(l, window - 1, compressed_Hunique)\n lu2 = complete_idx_to_unique_typed_idx(l, window, compressed_Hunique)\n\n # lazy concatenation \n s1 = ApplyArray(vcat, view(Hprev, :, iu), view(Hcurr, :, ku))\n s21 = ApplyArray(vcat, view(Hprev, :, ju1), view(Hcurr, :, ju2))\n s22 = ApplyArray(vcat, view(Hprev, :, lu1), view(Hcurr, :, lu2))\n\n breakpt, errors = search_breakpoint(X, s1, s21, s22)\n return (k, l), (-1, breakpt)\n elseif i == l && j ≠ k && !phased\n iu = complete_idx_to_unique_typed_idx(i, window - 1, compressed_Hunique)\n lu = complete_idx_to_unique_typed_idx(l, window, compressed_Hunique)\n ju1 = complete_idx_to_unique_typed_idx(j, window - 1, compressed_Hunique)\n ju2 = complete_idx_to_unique_typed_idx(j, window, compressed_Hunique)\n ku1 = complete_idx_to_unique_typed_idx(k, window - 1, compressed_Hunique)\n ku2 = complete_idx_to_unique_typed_idx(k, window, compressed_Hunique)\n\n # lazy concatenation \n s1 = ApplyArray(vcat, view(Hprev, :, iu), view(Hcurr, :, lu))\n s21 = ApplyArray(vcat, view(Hprev, :, ju1), view(Hcurr, :, ju2))\n s22 = ApplyArray(vcat, view(Hprev, :, ku1), view(Hcurr, :, ku2))\n\n breakpt, errors = search_breakpoint(X, s1, s21, s22)\n return (l, k), (-1, breakpt)\n elseif j == k && i ≠ l && !phased\n ju = complete_idx_to_unique_typed_idx(j, window - 1, compressed_Hunique)\n ku = complete_idx_to_unique_typed_idx(k, window, compressed_Hunique)\n iu1 = complete_idx_to_unique_typed_idx(i, window - 1, compressed_Hunique)\n iu2 = complete_idx_to_unique_typed_idx(i, window, compressed_Hunique)\n lu1 = complete_idx_to_unique_typed_idx(l, window - 1, compressed_Hunique)\n lu2 = complete_idx_to_unique_typed_idx(l, window, compressed_Hunique)\n \n # lazy concatenation \n s1 = ApplyArray(vcat, view(Hprev, :, ju), view(Hcurr, :, ku))\n s21 = ApplyArray(vcat, view(Hprev, :, iu1), view(Hcurr, :, iu2))\n s22 = ApplyArray(vcat, view(Hprev, :, lu1), view(Hcurr, :, lu2))\n\n breakpt, errors = search_breakpoint(X, s1, s21, s22)\n return (l, k), (breakpt, -1)\n elseif j == l && i ≠ k\n ju = complete_idx_to_unique_typed_idx(j, window - 1, compressed_Hunique)\n lu = complete_idx_to_unique_typed_idx(l, window, compressed_Hunique)\n iu1 = complete_idx_to_unique_typed_idx(i, window - 1, compressed_Hunique)\n iu2 = complete_idx_to_unique_typed_idx(i, window, compressed_Hunique)\n ku1 = complete_idx_to_unique_typed_idx(k, window - 1, compressed_Hunique)\n ku2 = complete_idx_to_unique_typed_idx(k, window, compressed_Hunique)\n\n # lazy concatenation \n s1 = ApplyArray(vcat, view(Hprev, :, ju), view(Hcurr, :, lu))\n s21 = ApplyArray(vcat, view(Hprev, :, iu1), view(Hcurr, :, iu2))\n s22 = ApplyArray(vcat, view(Hprev, :, ku1), view(Hcurr, :, ku2))\n\n breakpt, errors = search_breakpoint(X, s1, s21, s22)\n return (k, l), (breakpt, -1)\n end\n\n # both strand mismatch\n if search_double_bkpts\n iu1 = complete_idx_to_unique_typed_idx(i, window - 1, compressed_Hunique)\n iu2 = complete_idx_to_unique_typed_idx(i, window, compressed_Hunique)\n ku1 = complete_idx_to_unique_typed_idx(k, window - 1, compressed_Hunique)\n ku2 = complete_idx_to_unique_typed_idx(k, window, compressed_Hunique)\n ju1 = complete_idx_to_unique_typed_idx(j, window - 1, compressed_Hunique)\n ju2 = complete_idx_to_unique_typed_idx(j, window, compressed_Hunique)\n lu1 = complete_idx_to_unique_typed_idx(l, window - 1, compressed_Hunique)\n lu2 = complete_idx_to_unique_typed_idx(l, window, compressed_Hunique)\n\n # lazy concatenation \n s11 = ApplyArray(vcat, view(Hprev, :, iu1), view(Hcurr, :, iu2))\n s12 = ApplyArray(vcat, view(Hprev, :, ku1), view(Hcurr, :, ku2))\n s21 = ApplyArray(vcat, view(Hprev, :, ju1), view(Hcurr, :, ju2))\n s22 = ApplyArray(vcat, view(Hprev, :, lu1), view(Hcurr, :, lu2))\n\n breakpt, errors = search_breakpoint(X, s11, s12, s21, s22)\n return (k, l), breakpt\n\n # Always assume double bkpt searches are phased. \n # breakpt1, errors1 = search_breakpoint(X, H, (i, k), (j, l))\n # breakpt2, errors2 = search_breakpoint(X, H, (i, l), (j, k))\n # if errors1 < errors2\n # return (k, l), breakpt1\n # else\n # return (l, k), breakpt2\n # end\n else\n return (k, l), (-2, -2)\n end\nend\n\n\"\"\"\n search_single_breakpoint(X, s1, s21, s22)\n\nFind the optimal break point between s21 and s22 in configuration\ns1 | s21\ns1 | s22\n\"\"\"\nfunction search_breakpoint(\n X::AbstractVector,\n s1::AbstractVector,\n s21::AbstractVector,\n s22::AbstractVector,\n )\n\n n = length(X)\n length(s1) == length(s21) == length(s22) == n ||error(\"search_breakpoint:\" * \n \" all vectors should have same length but length X = $n, s1 =\" * \n \" $(length(s1)), s21 = $(length(s21)), s22 = $(length(s22))\")\n\n # count number of errors if second haplotype is all from s22\n errors = 0\n @inbounds for pos in 1:n\n if !ismissing(X[pos])\n errors += X[pos] ≠ s1[pos] + s22[pos]\n end\n end\n bkpt_optim, err_optim = 0, errors\n\n # quick return if perfect match\n err_optim == 0 && return 0, 0\n\n # extend haplotype s21 position by position\n @inbounds for bkpt in 1:n\n if !ismissing(X[bkpt]) && s21[bkpt] ≠ s22[bkpt]\n errors -= X[bkpt] ≠ s1[bkpt] + s22[bkpt]\n errors += X[bkpt] ≠ s1[bkpt] + s21[bkpt]\n if errors :: Int < err_optim\n bkpt_optim, err_optim = bkpt, errors\n # quick return if perfect match\n err_optim == 0 && return bkpt_optim, err_optim :: Int\n end\n end\n end\n\n return bkpt_optim, err_optim :: Int\nend\n\n\"\"\"\n search_breakpoint(X, s11, s12, s21, s22)\n\nFind the optimal break point between s11 and s12 as well as between s21 and s22\nin configuration\ns11 | s21\ns12 | s22\n\"\"\"\nfunction search_breakpoint(\n X::AbstractVector,\n s11::AbstractVector,\n s12::AbstractVector,\n s21::AbstractVector,\n s22::AbstractVector,\n )\n n = length(X)\n length(s11) == length(s12) == length(s21) == length(s22) == n || \n error(\"search_breakpoint: all vectors should have same length but \" *\n \"length X = $n, s11 = $(length(s11)), s12 = $(length(s12)), s21 = \" *\n \"$(length(s21)), s22 = $(length(s22))\")\n\n err_optim = typemax(Int)\n bkpts_optim = (0, 0)\n\n # search over all combintations of break points in two strands\n @inbounds for bkpt1 in 0:n\n\n # count number of errors if second haplotype is all from s22\n errors = 0\n for pos in 1:bkpt1\n if !ismissing(X[pos])\n errors += X[pos] ≠ s11[pos] + s22[pos]\n end\n end\n for pos in (bkpt1 + 1):length(X)\n if !ismissing(X[pos])\n errors += X[pos] ≠ s12[pos] +s22[pos]\n end\n end\n if errors :: Int < err_optim\n err_optim = errors\n bkpts_optim = (bkpt1, 0)\n\n # quick return if perfect match\n err_optim == 0 && return bkpts_optim, err_optim :: Int\n end\n\n # extend haplotype s21 position by position\n for bkpt2 in 1:bkpt1\n if !ismissing(X[bkpt2]) && s21[bkpt2] ≠ s22[bkpt2]\n errors -= X[bkpt2] ≠ s11[bkpt2] + s22[bkpt2]\n errors += X[bkpt2] ≠ s11[bkpt2] + s21[bkpt2]\n if errors :: Int < err_optim\n err_optim = errors\n bkpts_optim = (bkpt1, bkpt2)\n end\n end\n end\n for bkpt2 in (bkpt1 + 1):length(X)\n if !ismissing(X[bkpt2]) && s21[bkpt2] ≠ s22[bkpt2]\n errors -= X[bkpt2] ≠ s12[bkpt2] + s22[bkpt2]\n errors += X[bkpt2] ≠ s12[bkpt2] + s21[bkpt2]\n if errors :: Int < err_optim\n err_optim = errors\n bkpts_optim = (bkpt1, bkpt2)\n # quick return if perfect match\n err_optim == 0 && return bkpts_optim, err_optim :: Int\n end\n end\n end\n end\n\n return bkpts_optim, err_optim :: Int\nend\n", "meta": {"hexsha": "2e722e01e90d5d1d1b6951c9ce35a530bb20bcc1", "size": 11169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/breakpoints.jl", "max_stars_repo_name": "biona001/MendelImpute", "max_stars_repo_head_hexsha": "b29e584f9b4bae1df6bff09eb3f2106108f1e12d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-24T08:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-24T08:02:59.000Z", "max_issues_repo_path": "src/breakpoints.jl", "max_issues_repo_name": "biona001/MendelImpute", "max_issues_repo_head_hexsha": "b29e584f9b4bae1df6bff09eb3f2106108f1e12d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/breakpoints.jl", "max_forks_repo_name": "biona001/MendelImpute", "max_forks_repo_head_hexsha": "b29e584f9b4bae1df6bff09eb3f2106108f1e12d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3274647887, "max_line_length": 81, "alphanum_fraction": 0.621810368, "num_tokens": 3266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}} {"text": "function DiffEqBase.__solve(\n prob::DiffEqBase.AbstractODEProblem{uType,tuptType,isinplace},\n alg::AlgType,\n timeseries=[],ts=[],ks=[];\n saveat = Float64[],\n verbose=true,save_everystep = isempty(saveat),\n save_on = true,\n save_start = save_everystep || isempty(saveat) || typeof(saveat) <: Number ? true : prob.tspan[1] in saveat,\n timeseries_errors=true,dense_errors=false,\n callback=nothing, alias_u0=false, kwargs...) where\n {uType,tuptType,isinplace,AlgType<:ODEInterfaceAlgorithm}\n\n tType = eltype(tuptType)\n\n isstiff = alg isa ODEInterfaceImplicitAlgorithm\n if verbose\n warned = !isempty(kwargs) && check_keywords(alg, kwargs, warnlist)\n if !(typeof(prob.f) <: DiffEqBase.AbstractParameterizedFunction) && isstiff\n if DiffEqBase.has_tgrad(prob.f)\n @warn(\"Explicit t-gradient given to this stiff solver is ignored.\")\n warned = true\n end\n end\n warned && warn_compat()\n end\n\n callbacks_internal = CallbackSet(callback)\n\n max_len_cb = DiffEqBase.max_vector_callback_length(callbacks_internal)\n if max_len_cb isa VectorContinuousCallback\n callback_cache = DiffEqBase.CallbackCache(max_len_cb.len,uBottomEltype,uBottomEltype)\n else\n callback_cache = nothing\n end\n\n tspan = prob.tspan\n\n o = KW(kwargs)\n\n u0 = prob.u0\n\n if typeof(u0) <: Number\n u = [u0]\n else\n if alias_u0\n u = u0\n else\n u = deepcopy(u0)\n end\n end\n\n tdir = sign(tspan[2]-tspan[1])\n\n saveat_internal =\n saveat_disc_handling(saveat,tdir,tspan,tType)\n\n sizeu = size(u)\n\n o[:RHS_CALLMODE] = ODEInterface.RHS_CALL_INSITU\n\n if save_everystep\n _timeseries = Vector{uType}(undef,0)\n ts = Vector{tType}(undef,0)\n else\n _timeseries = [copy(u0)]\n ts = [tspan[1]]\n end\n\n uprev = similar(u)\n\n sol = DiffEqBase.build_solution(prob, alg, ts, _timeseries,\n timeseries_errors = timeseries_errors,\n calculate_error = false,\n destats = DiffEqBase.DEStats(0),\n retcode = :Default)\n\n opts = DEOptions(saveat_internal,save_on,save_everystep,callbacks_internal)\n if !isinplace && typeof(u)<:AbstractArray\n f! = (t,u,du) -> (du[:] = vec(prob.f(reshape(u,sizeu),integrator.p,t)); nothing)\n elseif !(typeof(u)<:Vector{Float64})\n f! = (t,u,du) -> (prob.f(reshape(du,sizeu),reshape(u,sizeu),integrator.p,t);\n du=vec(du); nothing)\n else\n f! = (t,u,du) -> prob.f(du,u,integrator.p,t)\n end\n\n integrator = ODEInterfaceIntegrator(prob.f,u,uprev,tspan[1],tspan[1],prob.p,opts,\n false,tdir,sizeu,sol,\n (t)->[t],0,1,callback_cache,alg,0.)\n initialize_callbacks!(integrator)\n\n outputfcn = OutputFunction(integrator)\n o[:OUTPUTFCN] = outputfcn\n if !(typeof(callbacks_internal.continuous_callbacks)<:Tuple{}) || !isempty(saveat)\n if typeof(alg) <: Union{ddeabm,ddebdf}\n @warn(\"saveat and continuous callbacks ignored for ddeabm and ddebdf\")\n o[:OUTPUTMODE] = ODEInterface.OUTPUTFCN_WODENSE\n else\n o[:OUTPUTMODE] = ODEInterface.OUTPUTFCN_DENSE\n end\n else\n o[:OUTPUTMODE] = ODEInterface.OUTPUTFCN_WODENSE\n end\n\n dict = buildOptions(o,\n ODEINTERFACE_OPTION_LIST,\n ODEINTERFACE_ALIASES,\n ODEINTERFACE_ALIASES_REVERSED)\n if prob.f.mass_matrix != I\n if typeof(prob.f.mass_matrix) <: Matrix && isstiff\n dict[:MASSMATRIX] = prob.f.mass_matrix\n elseif !isstiff\n error(\"This solver does not support mass matrices\")\n else\n error(\"This solver must use full or banded mass matrices.\")\n end\n end\n if DiffEqBase.has_jac(prob.f)\n dict[:JACOBIMATRIX] = (t,u,J) -> prob.f.jac(J,u,prob.p,t)\n end\n\n if isstiff && alg.jac_lower !== nothing\n dict[:JACOBIBANDSSTRUCT] = (alg.jac_lower,alg.jac_upper)\n end\n\n # Convert to the strings\n opts = ODEInterface.OptionsODE([Pair(ODEINTERFACE_STRINGS[k],v) for (k,v) in dict]...)\n\n\n if typeof(alg) <: dopri5\n tend, uend, retcode, stats =\n ODEInterface.dopri5(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: dop853\n tend, uend, retcode, stats =\n ODEInterface.dop853(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: odex\n tend, uend, retcode, stats =\n ODEInterface.odex(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: seulex\n tend, uend, retcode, stats =\n ODEInterface.seulex(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: radau\n tend, uend, retcode, stats =\n ODEInterface.radau(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: radau5\n tend, uend, retcode, stats =\n ODEInterface.radau5(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: rodas\n tend, uend, retcode, stats =\n ODEInterface.rodas(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: ddeabm\n tend, uend, retcode, stats =\n ODEInterface.ddeabm(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n elseif typeof(alg) <: ddebdf\n tend, uend, retcode, stats =\n ODEInterface.ddebdf(f!, tspan[1], tspan[2], vec(integrator.u), opts)\n end\n\n if !save_everystep\n push!(ts,tend)\n save_value!(_timeseries,uend,uType,sizeu)\n end\n\n if retcode < 0\n if retcode == -1\n verbose && @warn(\"Input is not consistent.\")\n return_retcode = :Failure\n elseif retcode == -2\n verbose && @warn(\"Interrupted. Larger maxiters is needed.\")\n return_retcode = :MaxIters\n elseif retcode == -3\n verbose && @warn(\"Step size went too small.\")\n return_retcode = :DtLessThanMin\n elseif retcode == -4\n verbose && @warn(\"Interrupted. Problem is probably stiff.\")\n return_retcode = :Unstable\n end\n else\n return_retcode = :Success\n end\n\n if DiffEqBase.has_analytic(prob.f)\n DiffEqBase.calculate_solution_errors!(integrator.sol;\n timeseries_errors=timeseries_errors,\n dense_errors=dense_errors)\n end\n\n destats = sol.destats\n destats.nf = stats[\"no_rhs_calls\"]\n if haskey(stats,\"no_steps_rejected\")\n destats.nreject = stats[\"no_steps_rejected\"]\n destats.naccept = stats[\"no_steps_accepted\"]\n end\n if haskey(stats,\"no_jac_calls\")\n destats.njacs = stats[\"no_jac_calls\"]\n end\n if haskey(stats,\"no_lu_decomp\")\n destats.nw = stats[\"no_lu_decomp\"]\n end\n DiffEqBase.solution_new_retcode(sol,return_retcode)\nend\n\nfunction save_value!(_timeseries,u,::Type{T},sizeu) where T<:Number\n push!(_timeseries,first(u))\nend\n\nfunction save_value!(_timeseries,u,::Type{T},sizeu) where T<:Vector\n push!(_timeseries,u)\nend\n\nfunction save_value!(_timeseries,u,::Type{T},sizeu) where T<:Array\n push!(_timeseries,reshape(u,sizeu))\nend\n\nfunction buildOptions(o, optionlist, aliases, aliases_reversed)\n dict1 = Dict{Symbol,Any}([Pair(k,o[k]) for k in (keys(o) ∩ optionlist)])\n dict2 = Dict([Pair(aliases_reversed[k],o[k]) for k in (keys(o) ∩ values(aliases))])\n merge(dict1,dict2)\nend\n\nfunction saveat_disc_handling(saveat,tdir,tspan,tType)\n\n if typeof(saveat) <: Number\n if (tspan[1]:saveat:tspan[end])[end] == tspan[end]\n saveat_vec = convert(Vector{tType},collect(tType,tspan[1]+saveat:saveat:tspan[end]))\n else\n saveat_vec = convert(Vector{tType},collect(tType,tspan[1]+saveat:saveat:(tspan[end]-saveat)))\n end\n else\n saveat_vec = vec(collect(tType,Iterators.filter(x->tdir*tspan[1]0\n saveat_internal = BinaryMinHeap(saveat_vec)\n else\n saveat_internal = BinaryMaxHeap(saveat_vec)\n end\n\n saveat_internal\nend\n\nconst ODEINTERFACE_OPTION_LIST =\n Set([:RTOL, :ATOL, :OUTPUTFCN, :OUTPUTMODE, :MAXSTEPS, :STEST, :EPS, :RHO, :SSMINSEL,\n :SSMAXSEL, :SSBETA, :MAXSS, :INITIALSS, :MAXEXCOLUMN, :STEPSIZESEQUENCE,\n :MAXSTABCHECKS, :MAXSTABCHECKLINE, :DENSEOUTPUTWOEE, :INTERPOLDEGRE,\n :SSREDUCTION, :SSSELECTPAR1, :SSSELECTPAR2, :ORDERDECFRAC, :ORDERINCFRAC,\n :OPT_RHO, :OPT_RHO2, :RHSAUTONOMOUS, :M1, :M2, :LAMBDADENSE, :TRANSJTOH,\n :STEPSIZESEQUENCE, :JACRECOMPFACTOR, :MASSMATRIX, :JACOBIMATRIX, :JACOBIBANDSSTRUCT,\n :WORKFORRHS, :WORKFORJAC, :WORKFORDEC, :WORKFORSOL,\n :MAXNEWTONITER, :NEWTONSTARTZERO, :NEWTONSTOPCRIT, :DIMFIND1VAR,\n :MAXSTAGES, :MINSTAGES, :INITSTAGES, :STEPSIZESTRATEGY,\n :FREEZESSLEFT, :FREEZESSRIGHT, :ORDERDECFACTOR,\n :ORDERINCFACTOR, :ORDERDECCSTEPFAC1, :ORDERDECSTEPFAC2, :RHS_CALLMODE\n ])\n\nconst ODEINTERFACE_ALIASES =\n Dict{Symbol,Symbol}(:RTOL=>:reltol,\n :ATOL=>:abstol,\n :MAXSTEPS=> :maxiters,\n :MAXSS=>:dtmax,\n :INITIALSS=>:dt,\n #:SSMINSEL=>:qmin,\n :SSBETA=>:beta2,\n :SSMAXSEL=>:qmax)\n\nconst ODEINTERFACE_ALIASES_REVERSED =\n Dict{Symbol,Symbol}([(v,k) for (k,v) in ODEINTERFACE_ALIASES])\n\nconst ODEINTERFACE_STRINGS = Dict{Symbol,String}(\n :LOGIO => \"logio\",\n :LOGLEVEL => \"loglevel\",\n :RHS_CALLMODE => \"RightHandSideCallMode\",\n\n :RTOL => \"RelTol\",\n :ATOL => \"AbsTol\",\n :MAXSTEPS => \"MaxNumberOfSteps\",\n :EPS => \"eps\",\n\n :OUTPUTFCN => \"OutputFcn\",\n :OUTPUTMODE => \"OutputFcnMode\",\n\n :STEST => \"StiffTestAfterStep\",\n :RHO => \"rho\",\n :SSMINSEL => \"StepSizeMinSelection\",\n :SSMAXSEL => \"StepSizeMaxSelection\",\n :SSBETA => \"StepSizeBeta\",\n :MAXSS => \"MaxStep\",\n :INITIALSS => \"InitialStep\",\n\n\n :MAXEXCOLUMN => \"MaxExtrapolationColumn\",\n :MAXSTABCHECKS => \"MaxNumberOfStabilityChecks\",\n :MAXSTABCHECKLINE => \"MaxLineForStabilityCheck\",\n :INTERPOLDEGREE => \"DegreeOfInterpolation\",\n :ORDERDECFRAC => \"OrderDecreaseFraction\",\n :ORDERINCFRAC => \"OrderIncreaseFraction\",\n :STEPSIZESEQUENCE => \"StepSizeSequence\",\n :SSREDUCTION => \"StepSizeReduction\",\n :SSSELECTPAR1 => \"StepSizeSelectionParam1\",\n :SSSELECTPAR2 => \"StepSizeSelectionParam2\",\n :RHO2 => \"rho2\",\n :DENSEOUTPUTWOEE => \"DeactivateErrorEstInDenseOutput\",\n\n :TRANSJTOH => \"TransfromJACtoHess\",\n :MAXNEWTONITER => \"MaxNewtonIterations\",\n :NEWTONSTARTZERO => \"StartNewtonWithZeros\",\n :DIMOFIND1VAR => \"DimensionOfIndex1Vars\",\n :DIMOFIND2VAR => \"DimensionOfIndex2Vars\",\n :DIMOFIND3VAR => \"DimensionOfIndex3Vars\",\n :STEPSIZESTRATEGY => \"StepSizeStrategy\",\n :M1 => \"M1\",\n :M2 => \"M2\",\n :JACRECOMPFACTOR => \"RecomputeJACFactor\",\n :NEWTONSTOPCRIT => \"NewtonStopCriterion\",\n :FREEZESSLEFT => \"FreezeStepSizeLeftBound\",\n :FREEZESSRIGHT => \"FreezeStepSizeRightBound\",\n :MASSMATRIX => \"MassMatrix\",\n :JACOBIMATRIX => \"JacobiMatrix\",\n :JACOBIBANDSTRUCT => \"JacobiBandStructure\",\n\n :MAXSTAGES => \"MaximalNumberOfStages\",\n :MINSTAGES => \"MinimalNumberOfStages\",\n :INITSTAGES => \"InitialNumberOfStages\",\n :ORDERINCFACTOR => \"OrderIncreaseFactor\",\n :ORDERDECFACTOR => \"OrderDecreaseFactor\",\n :ORDERDECSTEPFAC1 => \"OrderDecreaseStepFactor1\",\n :ORDERDECSTEPFAC2 => \"OrderDecreaseStepFactor2\",\n\n :RHSAUTONOMOUS => \"AutonomousRHS\",\n :LAMBDADENSE => \"LambdaForDenseOutput\",\n :WORKFORRHS => \"WorkForRightHandSide\",\n :WORKFORJAC => \"WorkForJacobimatrix\",\n :WORKFORDEC => \"WorkForLuDecomposition\",\n :WORKFORSOL => \"WorkForSubstitution\",\n\n :BVPCLASS => \"BoundaryValueProblemClass\",\n :SOLMETHOD => \"SolutionMethod\",\n :IVPOPT => \"OptionsForIVPsolver\")\n\nstruct OutputFunction{T} <: Function\n integrator::T\nend\n\nfunction (f::OutputFunction)(reason::ODEInterface.OUTPUTFCN_CALL_REASON,\n tprev::Float64, t::Float64, u::Vector{Float64},\n eval_sol_fcn, extra_data::Dict)\n\n if reason == ODEInterface.OUTPUTFCN_CALL_STEP\n\n integrator = f.integrator\n\n integrator.uprev .= integrator.u\n if eltype(integrator.sol.u) <: Vector\n integrator.u .= u\n else\n integrator.u .= reshape(u,integrator.sizeu)\n end\n integrator.t = t\n integrator.tprev = tprev\n integrator.eval_sol_fcn = eval_sol_fcn\n\n handle_callbacks!(integrator,eval_sol_fcn)\n\n if integrator.u_modified\n\n if eltype(integrator.sol.u) <: Vector\n u .= integrator.u\n else\n tmp = reshape(u,integrator.sizeu)\n tmp .= integrator.u\n end\n\n return ODEInterface.OUTPUTFCN_RET_CONTINUE_XCHANGED\n else\n return ODEInterface.OUTPUTFCN_RET_CONTINUE\n end\n # TODO: ODEInterface.OUTPUTFCN_RET_STOP for terminate!\n\n end\n\n ODEInterface.OUTPUTFCN_RET_CONTINUE\nend\n", "meta": {"hexsha": "1db4e93a1436c4742030be3597bfa096a4167851", "size": 13363, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solve.jl", "max_stars_repo_name": "AnasAbdelR/ODEInterfaceDiffEq.jl", "max_stars_repo_head_hexsha": "490c25fe96e379a313c660423f1eec2d1e8f758b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-04-08T18:57:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-25T03:03:27.000Z", "max_issues_repo_path": "src/solve.jl", "max_issues_repo_name": "AnasAbdelR/ODEInterfaceDiffEq.jl", "max_issues_repo_head_hexsha": "490c25fe96e379a313c660423f1eec2d1e8f758b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2017-05-10T18:26:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-22T22:14:06.000Z", "max_forks_repo_path": "src/solve.jl", "max_forks_repo_name": "AnasAbdelR/ODEInterfaceDiffEq.jl", "max_forks_repo_head_hexsha": "490c25fe96e379a313c660423f1eec2d1e8f758b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2016-12-14T03:45:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:37:11.000Z", "avg_line_length": 34.8903394256, "max_line_length": 112, "alphanum_fraction": 0.6219411809, "num_tokens": 3914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.19954527822674611}} {"text": "@everywhere using JuMP\n\n@everywhere using PowerModels\n\n@everywhere using InfrastructureModels\n\n@everywhere using Memento\n\n@everywhere const LOGGER = getlogger(\"GOC\")\n\n@everywhere const vm_eq_tol = 1e-4\n\n@everywhere import Statistics: mean\n\n\n@everywhere function build_pm_model(goc_data) # Function to build a model based on the input data\n scenario = goc_data.scenario\n network = goc_data.network\n\n ##### General Helpers #####\n gen_lookup = Dict(tuple(gen[\"source_id\"][2], strip(gen[\"source_id\"][3])) => gen for (i,gen) in network[\"gen\"]) # Dic\n\n branch_lookup = Dict()\n for (i,branch) in network[\"branch\"]\n if !branch[\"transformer\"] # Checks if the branch is not the transformer\n branch_id = tuple(branch[\"source_id\"][2], branch[\"source_id\"][3], strip(branch[\"source_id\"][4]))\n else\n branch_id = tuple(branch[\"source_id\"][2], branch[\"source_id\"][3], strip(branch[\"source_id\"][5]))\n @assert branch[\"source_id\"][4] == 0 # Assert macro allows to optionally specify error message, instead of just printing the failed expression\n @assert branch[\"source_id\"][6] == 0\n end\n branch_lookup[branch_id] = branch \n end\n\n\n\n ##### Link Generator Cost Data #####\n\n @assert network[\"per_unit\"] # Assert macro allows to optionally specify error message, instead of just printing the failed expression\n mva_base = network[\"baseMVA\"] # Assigns baseMVA from network as mva_base\n\n dispatch_tbl_lookup = Dict() # Creates a dictionary named dispatch_tbl_lookup\n for dispatch_tbl in goc_data.cost[\"disptbl\"] \n dispatch_tbl_lookup[dispatch_tbl[\"ctbl\"]] = dispatch_tbl # Assigns dispatch_tbl to dictionary named dispatch_tbl_lookup\n end\n\n cost_tbl_lookup = Dict() # Creates a dictionary named cost_tbl_lookup\n for cost_tbl in goc_data.cost[\"ctbl\"]\n cost_tbl_lookup[cost_tbl[\"ltbl\"]] = cost_tbl # Assigns cost_tbl to dictionary named cost_tbl_lookup\n end\n\n gen_cost_models = Dict() # Defines an empty dictionary for generation cost models\n for gen_dispatch in goc_data.cost[\"gen\"] # Looks for the cost of gen in goc_data\n gen_id = (gen_dispatch[\"bus\"], strip(gen_dispatch[\"genid\"])) # Removes the leading and trailing characters from genid\n dispatch_tbl = dispatch_tbl_lookup[gen_dispatch[\"disptbl\"]] # Calls the function named dispatch_tbl_lookup for gen dispatch table\n cost_tbl = cost_tbl_lookup[dispatch_tbl[\"ctbl\"]] # Calls the function named cost_tbl_lookup for dispatch table cost\n\n gen_cost_models[gen_id] = cost_tbl # Assigns the cost_tbl to the specific gen cost model id\n end\n\n if length(gen_cost_models) != length(network[\"gen\"]) # Checks if the length of both generator network and generator cost model is same\n error(LOGGER, \"cost model data missing, network has $(length(network[\"gen\"])) generators, the cost model has $(length(gen_cost_models)) generators\") # Mismatch error\n end\n\n for (gen_id, cost_model) in gen_cost_models\n pm_gen = gen_lookup[gen_id] # Calls gen_lookup for gen_id & stores the result in pm_gen\n pm_gen[\"model\"] = 1 \n pm_gen[\"model_lable\"] = cost_model[\"label\"] # Assigns label for cost model to model lable for pm_gen\n pm_gen[\"ncost\"] = length(cost_model[\"points\"]) # Finds the length of points in cost_model\n\n #println(cost_model[\"points\"])\n point_list = Float64[]\n for point in cost_model[\"points\"]\n push!(point_list, point.x/mva_base) \n push!(point_list, point.y) # Inserts point.y at the end of point_list\n end\n pm_gen[\"cost\"] = point_list # Assigns point_list to cost in pm_gen\n end\n\n\n\n ##### Link Generator Participation Data #####\n\n if length(goc_data.response) != length(network[\"gen\"]) # Checks if all the generators are active or not\n error(LOGGER, \"generator response model data missing, network has $(length(network[\"gen\"])) generators, the response model has $(length(goc_data.response)) generators\") # Error to mention the out of service generators\n end\n\n for gen_response in goc_data.response # Looks for response in goc_data\n gen_id = (gen_response[\"i\"], strip(gen_response[\"id\"])) \n\n pm_gen = gen_lookup[gen_id]\n\n pm_gen[\"alpha\"] = gen_response[\"r\"]\n end\n\n\n\n ##### Flexible Shunt Data #####\n\n for (i,shunt) in network[\"shunt\"]\n if shunt[\"source_id\"][1] == \"switched shunt\"\n @assert shunt[\"source_id\"][3] == 0\n @assert shunt[\"gs\"] == 0.0\n shunt[\"dispatchable\"] = true\n\n bmin = 0.0\n bmax = 0.0\n for (n_name,b_name) in [(\"n1\",\"b1\"),(\"n2\",\"b2\"),(\"n3\",\"b3\"),(\"n4\",\"b4\"),(\"n5\",\"b5\"),(\"n6\",\"b6\"),(\"n7\",\"b7\"),(\"n8\",\"b8\")]\n if shunt[b_name] <= 0.0\n bmin += shunt[n_name]*shunt[b_name] # bmin = bmin + nt[n_name]*shunt[b_name]\n else\n bmax += shunt[n_name]*shunt[b_name] # bmax = bmax + nt[n_name]*shunt[b_name]\n end\n end\n shunt[\"bmin\"] = bmin/mva_base\n shunt[\"bmax\"] = bmax/mva_base\n else\n shunt[\"dispatchable\"] = false\n end\n end\n\n\n\n ##### Add Contingency Lists #####\n\n generator_ids = []\n branch_ids = []\n\n for (i,cont) in enumerate(goc_data.contingencies)\n if cont[\"component\"] == \"branch\" # Checks if there is branch contingency\n branch_id = (cont[\"i\"], cont[\"j\"], cont[\"ckt\"])\n pm_branch = branch_lookup[branch_id]\n push!(branch_ids, (idx=pm_branch[\"index\"], label=cont[\"label\"], type=\"branch\")) # Inserts idx, label, and type at the end of branch_ids\n\n elseif cont[\"component\"] == \"generator\" # Checks if there is generator contingency\n gen_id = (cont[\"i\"], cont[\"id\"])\n pm_gen = gen_lookup[gen_id]\n push!(generator_ids, (idx=pm_gen[\"index\"], label=cont[\"label\"], type=\"gen\")) # Inserts idx, label, and type at the end of generator_ids\n\n else\n error(LOGGER, \"unrecognized contingency component type $(cont[\"component\"]) at contingency $(i)\")\n end\n end\n\n network[\"branch_contingencies\"] = branch_ids\n network[\"gen_contingencies\"] = generator_ids\n\n network[\"branch_contingencies_active\"] = []\n network[\"gen_contingencies_active\"] = []\n\n\n\n ##### Fix Broken Data #####\n\n PowerModels.correct_cost_functions!(network)\n\n # FYI, this breaks output API\n #PowerModels.propagate_topology_status!(network)\n\n for (i,shunt) in network[\"shunt\"]\n # test checks if a \"switched shunt\" in the orginal data model\n if shunt[\"dispatchable\"]\n if shunt[\"bs\"] < shunt[\"bmin\"]\n warn(LOGGER, \"update bs on shunt $(i) to be in bounds $(shunt[\"bs\"]) -> $(shunt[\"bmin\"])\")\n shunt[\"bs\"] = shunt[\"bmin\"]\n end\n if shunt[\"bs\"] > shunt[\"bmax\"]\n warn(LOGGER, \"update bs on shunt $(i) to be in bounds $(shunt[\"bs\"]) -> $(shunt[\"bmax\"])\")\n shunt[\"bs\"] = shunt[\"bmax\"]\n end\n end\n end\n\n return network\nend\n\n\nfunction build_pm_opf_model(goc_data)\n scenario = goc_data.scenario\n network = goc_data.network\n\n ##### General Helpers #####\n\n gen_lookup = Dict(tuple(gen[\"source_id\"][2], strip(gen[\"source_id\"][3])) => gen for (i,gen) in network[\"gen\"])\n\n branch_lookup = Dict()\n for (i,branch) in network[\"branch\"]\n if !branch[\"transformer\"] # Checks if branch is other than transformer\n branch_id = tuple(branch[\"source_id\"][2], branch[\"source_id\"][3], strip(branch[\"source_id\"][4]))\n else\n branch_id = tuple(branch[\"source_id\"][2], branch[\"source_id\"][3], strip(branch[\"source_id\"][5]))\n @assert branch[\"source_id\"][4] == 0\n @assert branch[\"source_id\"][6] == 0\n end\n branch_lookup[branch_id] = branch\n end\n\n\n\n ##### Link Generator Cost Data #####\n\n @assert network[\"per_unit\"]\n mva_base = network[\"baseMVA\"]\n\n dispatch_tbl_lookup = Dict() # Creates a dictionary for dispatch_tbl_lookup\n for dispatch_tbl in goc_data.cost[\"disptbl\"]\n dispatch_tbl_lookup[dispatch_tbl[\"ctbl\"]] = dispatch_tbl\n end\n\n cost_tbl_lookup = Dict()\n for cost_tbl in goc_data.cost[\"ctbl\"]\n cost_tbl_lookup[cost_tbl[\"ltbl\"]] = cost_tbl\n end\n\n gen_cost_models = Dict()\n for gen_dispatch in goc_data.cost[\"gen\"]\n gen_id = (gen_dispatch[\"bus\"], strip(gen_dispatch[\"genid\"]))\n dispatch_tbl = dispatch_tbl_lookup[gen_dispatch[\"disptbl\"]]\n cost_tbl = cost_tbl_lookup[dispatch_tbl[\"ctbl\"]]\n\n gen_cost_models[gen_id] = cost_tbl\n end\n\n if length(gen_cost_models) != length(network[\"gen\"]) # Checks if the length of generator networks is not equal to generator cost model\n error(LOGGER, \"cost model data missing, network has $(length(network[\"gen\"])) generators, the cost model has $(length(gen_cost_models)) generators\") # Mentions there is error due to mismatch\n end\n\n for (gen_id, cost_model) in gen_cost_models\n pm_gen = gen_lookup[gen_id]\n pm_gen[\"model\"] = 1\n pm_gen[\"model_lable\"] = cost_model[\"label\"]\n pm_gen[\"ncost\"] = length(cost_model[\"points\"])\n\n #println(cost_model[\"points\"])\n point_list = Float64[]\n for point in cost_model[\"points\"]\n push!(point_list, point.x/mva_base)\n push!(point_list, point.y)\n end\n pm_gen[\"cost\"] = point_list\n end\n\n PowerModels.correct_cost_functions!(network)\n\n return network\nend\n\n\n\n@everywhere function read_solution1(network; output_dir=\"\", state_file=\"solution1.txt\") # Function to read solution 1 of base case\n if length(output_dir) > 0\n solution1_path = joinpath(output_dir, state_file)\n else\n solution1_path = state_file\n end\n\n return build_pm_solution(network, solution1_path) # Calls the functin named build_pm_solution to initiate the parsing of solution1.txt\nend\n\n@everywhere function build_pm_solution(network, goc_sol_file::String) # build_pm_solution function\n info(LOGGER, \"loading solution file: $(goc_sol_file)\")\n goc_sol = parse_solution1_file(goc_sol_file)\n\n info(LOGGER, \"converting GOC solution to PowerModels solution\")\n pm_sol = build_pm_solution(network, goc_sol) \n\n return pm_sol\nend\n\n@everywhere function build_pm_solution(network, goc_sol)\n bus_lookup = Dict(parse(Int, bus[\"source_id\"][2]) => bus for (i,bus) in network[\"bus\"])\n gen_lookup = Dict((gen[\"source_id\"][2], strip(gen[\"source_id\"][3])) => gen for (i,gen) in network[\"gen\"])\n shunt_lookup = Dict{Int,Any}()\n for (i,shunt) in network[\"shunt\"]\n if shunt[\"source_id\"][1] == \"switched shunt\"\n @assert shunt[\"source_id\"][3] == 0\n shunt_lookup[shunt[\"source_id\"][2]] = shunt\n end\n end\n\n base_mva = network[\"baseMVA\"]\n\n bus_data = Dict{String,Any}()\n shunt_data = Dict{String,Any}()\n for bus_sol in goc_sol.bus\n pm_bus = bus_lookup[bus_sol.bus]\n bus_data[\"$(pm_bus[\"index\"])\"] = Dict(\n \"vm\" => bus_sol.vm,\n \"va\" => deg2rad(bus_sol.va)\n )\n\n if haskey(shunt_lookup, bus_sol.bus)\n pm_shunt = shunt_lookup[bus_sol.bus]\n shunt_data[\"$(pm_shunt[\"index\"])\"] = Dict(\n \"gs\" => 0.0,\n \"bs\" => bus_sol.bcs/base_mva\n )\n else\n @assert bus_sol.bcs == 0.0\n end\n end\n\n gen_data = Dict{String,Any}()\n for gen_sol in goc_sol.gen\n pm_gen = gen_lookup[(gen_sol.bus, gen_sol.id)]\n gen_data[\"$(pm_gen[\"index\"])\"] = Dict(\n \"pg\" => gen_sol.pg/base_mva,\n \"qg\" => gen_sol.qg/base_mva\n )\n end\n\n solution = Dict(\n \"per_unit\" => true,\n \"bus\" => bus_data,\n \"shunt\" => shunt_data,\n \"gen\" => gen_data\n )\n\n return solution\nend\n\n@everywhere function gens_by_bus(network) # Function to see which are generation buses\n bus_gens = Dict(i => Any[] for (i,bus) in network[\"bus\"])\n for (i,gen) in network[\"gen\"]\n if gen[\"gen_status\"] != 0\n push!(bus_gens[\"$(gen[\"gen_bus\"])\"], gen)\n end\n end\n return bus_gens\nend\n\n\n\n@everywhere function run_fixpoint_pf_v2_2!(network, pg_lost, model_constructor, solver; iteration_limit=typemax(Int64)) # Core algorithm\n time_start = time()\n\n delta = apply_pg_response!(network, pg_lost)\n #delta = 0.0\n\n debug(LOGGER, \"pg lost: $(pg_lost)\")\n debug(LOGGER, \"delta: $(network[\"delta\"])\")\n debug(LOGGER, \"pre-solve time: $(time() - time_start)\")\n\n base_solution = extract_solution(network)\n base_solution[\"delta\"] = delta\n final_result = Dict(\n \"termination_status\" => LOCALLY_SOLVED,\n \"solution\" => base_solution\n )\n\n bus_gens = gens_by_bus(network)\n\n #network[\"delta_start\"] = network[\"delta\"]\n for (i,gen) in network[\"gen\"]\n gen[\"qg_fixed\"] = false # Set to false to allow variations in qg_fixed \n gen[\"pg_start\"] = gen[\"pg\"]\n if isapprox(gen[\"qmin\"],gen[\"qmax\"]) \n gen[\"qg_fixed\"] = true\n gen[\"qg\"] = gen[\"qmin\"]\n end\n gen[\"qg_start\"] = gen[\"qg\"]\n end\n\n for (i,bus) in network[\"bus\"]\n active_gens = [gen for gen in bus_gens[i] if !gen[\"qg_fixed\"]]\n if length(active_gens) == 0\n bus[\"vm_fixed\"] = false\n else\n bus[\"vm_fixed\"] = true\n end\n #bus[\"vm_start\"] = bus[\"vm\"]\n #bus[\"va_start\"] = bus[\"va\"]\n bus[\"vr_start\"] = bus[\"vm\"]*cos(bus[\"va\"])\n bus[\"vi_start\"] = bus[\"vm\"]*sin(bus[\"va\"])\n end\n\n time_start = time()\n result = run_fixed_pf_nbf_rect2(network, model_constructor, solver)\n debug(LOGGER, \"pf solve time: $(time() - time_start)\")\n if result[\"termination_status\"] == LOCALLY_SOLVED || result[\"termination_status\"] == ALMOST_LOCALLY_SOLVED\n correct_qg!(network, result[\"solution\"], bus_gens=bus_gens)\n PowerModels.update_data!(network, result[\"solution\"])\n final_result = result\n else\n warn(LOGGER, \"contingency pf solver FAILED with status $(result[\"termination_status\"]) on iteration 0\") # Warning if solver is failed to resolve the contingency\n return final_result\n end\n\n\n\n\n\n\n pg_switched = true\n qg_switched = true\n vm_switched = true\n\n iteration = 1\n deltas = [result[\"solution\"][\"delta\"]]\n while (pg_switched || qg_switched || vm_switched) && iteration <= iteration_limit\n debug(LOGGER, \"obj: $(result[\"objective\"])\")\n debug(LOGGER, \"delta: $(result[\"solution\"][\"delta\"])\")\n pg_switched = false\n qg_switched = false\n vm_switched = false\n\n for (i,gen) in network[\"gen\"]\n pg = gen[\"pg_base\"] + network[\"delta\"]*gen[\"alpha\"] # To find the real output power of a responding generator\n\n if gen[\"pg_fixed\"]\n if !isapprox(gen[\"pmax\"], gen[\"pmin\"]) && pg < gen[\"pmax\"] && pg > gen[\"pmin\"]\n gen[\"pg\"] = pg\n gen[\"pg_fixed\"] = false\n pg_switched = true\n #info(LOGGER, \"unfix pg on gen $(i)\")\n end\n else\n if pg >= gen[\"pmax\"]\n gen[\"pg\"] = gen[\"pmax\"]\n gen[\"pg_fixed\"] = true\n pg_switched = true\n #info(LOGGER, \"fix pg to ub on gen $(i)\")\n elseif gen[\"pg\"] <= gen[\"pmin\"]\n gen[\"pg\"] = gen[\"pmin\"]\n gen[\"pg_fixed\"] = true\n pg_switched = true\n #info(LOGGER, \"fix pg to lb on gen $(i)\")\n end\n end\n end\n\n for (i,bus) in network[\"bus\"]\n if length(bus_gens[i]) > 0\n qg = sum(gen[\"qg\"] for gen in bus_gens[i])\n qmin = sum(gen[\"qmin\"] for gen in bus_gens[i])\n qmax = sum(gen[\"qmax\"] for gen in bus_gens[i])\n\n if isapprox(qmin,qmax)\n @assert !bus[\"vm_fixed\"]\n for gen in bus_gens[i]\n @assert gen[\"qg_fixed\"]\n @assert isapprox(gen[\"qg\"],gen[\"qmin\"])\n end\n elseif bus[\"vm_fixed\"]\n if qg >= qmax\n bus[\"vm_fixed\"] = false\n vm_switched = true\n for gen in bus_gens[i]\n gen[\"qg\"] = gen[\"qmax\"]\n gen[\"qg_fixed\"] = true\n end\n #info(LOGGER, \"fix qg to ub on bus $(i)\")\n end\n\n if qg <= qmin\n bus[\"vm_fixed\"] = false\n vm_switched = true\n for gen in bus_gens[i]\n gen[\"qg\"] = gen[\"qmin\"]\n gen[\"qg_fixed\"] = true\n end\n #info(LOGGER, \"fix qg to lb on bus $(i)\")\n end\n else\n if qg < qmax && qg > qmin\n bus[\"vm_fixed\"] = true\n\n vm_switched = true\n for gen in bus_gens[i]\n gen[\"qg_fixed\"] = false\n gen[\"qg_start\"] = gen[\"qg\"]\n end\n #info(LOGGER, \"fix vm to on bus $(i)\")\n end\n if qg >= qmax && bus[\"vm\"] > bus[\"vm_base\"]\n bus[\"vm_fixed\"] = true\n vm_switched = true\n for gen in bus_gens[i]\n gen[\"qg_fixed\"] = false\n end\n #info(LOGGER, \"fix vm to on bus $(i)\")\n end\n if qg <= qmin && bus[\"vm\"] < bus[\"vm_base\"]\n bus[\"vm_fixed\"] = true\n vm_switched = true\n for gen in bus_gens[i]\n gen[\"qg_fixed\"] = false\n end\n #info(LOGGER, \"fix vm to on bus $(i)\")\n end\n end\n end\n end\n\n\n for (i,gen) in network[\"gen\"]\n gen[\"pg_start\"] = gen[\"pg\"]\n gen[\"qg_start\"] = gen[\"qg\"]\n end\n\n for (i,bus) in network[\"bus\"]\n bus[\"vm_start\"] = bus[\"vm\"]\n bus[\"va_start\"] = bus[\"va\"]\n end\n\n\n if pg_switched || qg_switched || vm_switched # || means OR\n debug(LOGGER, \"bus or gen swtiched: $iteration\")\n time_start = time()\n result = run_fixed_pf_nbf_rect2(network, model_constructor, solver)\n debug(LOGGER, \"pf solve time: $(time() - time_start)\")\n if result[\"termination_status\"] == LOCALLY_SOLVED || result[\"termination_status\"] == ALMOST_LOCALLY_SOLVED\n correct_qg!(network, result[\"solution\"], bus_gens=bus_gens)\n PowerModels.update_data!(network, result[\"solution\"])\n final_result = result\n else\n warn(LOGGER, \"contingency pf solver FAILED with status $(result[\"termination_status\"]) on iteration 0\")\n return final_result\n end\n\n push!(deltas, result[\"solution\"][\"delta\"])\n iteration += 1\n if iteration >= iteration_limit\n warn(LOGGER, \"hit iteration limit\")\n end\n if length(deltas) > 3 && isapprox(deltas[end-2], deltas[end])\n warn(LOGGER, \"cycle detected, stopping\")\n break\n end\n end\n end\n\n return final_result\nend\n\n\n\n@everywhere function apply_pg_response!(network, pg_delta) # Function to compute good starting guess for delta\n for (i,gen) in network[\"gen\"]\n gen[\"pg_fixed\"] = false\n end\n\n pg_total = 0.0\n for (i,gen) in network[\"gen\"]\n if gen[\"gen_status\"] != 0\n pg_total += gen[\"pg\"]\n end\n end\n\n pg_target = pg_total + pg_delta\n #info(LOGGER, \"total gen: $(pg_total)\")\n #info(LOGGER, \"target gen: $(pg_target)\")\n\n\n delta_est = 0.0\n while !isapprox(pg_total, pg_target)\n alpha_total = 0.0\n for (i,gen) in network[\"gen\"]\n if gen[\"gen_status\"] != 0 && !gen[\"pg_fixed\"]\n alpha_total += gen[\"alpha\"]\n end\n end\n #info(LOGGER, \"alpha total: $(alpha_total)\")\n\n if isapprox(alpha_total, 0.0) && !isapprox(pg_total, pg_target)\n warn(LOGGER, \"insufficient generator response to meet demand, remaining pg $(pg_total - pg_target), remaining alpha $(alpha_total)\")\n break\n end\n\n delta_est += pg_delta/alpha_total\n #info(LOGGER, \"detla: $(delta_est)\")\n\n for (i,gen) in network[\"gen\"]\n if gen[\"gen_status\"] != 0\n pg_cont = gen[\"pg_base\"] + delta_est*gen[\"alpha\"]\n\n if pg_cont <= gen[\"pmin\"]\n gen[\"pg\"] = gen[\"pmin\"]\n if !gen[\"pg_fixed\"]\n gen[\"pg_fixed\"] = true\n #info(LOGGER, \"gen $(i) hit lb $(gen[\"pmin\"]) with target value of $(pg_cont)\")\n end\n elseif pg_cont >= gen[\"pmax\"]\n gen[\"pg\"] = gen[\"pmax\"]\n if !gen[\"pg_fixed\"]\n gen[\"pg_fixed\"] = true\n #info(LOGGER, \"gen $(i) hit ub $(gen[\"pmax\"]) with target value of $(pg_cont)\")\n end\n else\n gen[\"pg\"] = pg_cont\n end\n end\n end\n\n pg_total = 0.0\n for (i,gen) in network[\"gen\"]\n if gen[\"gen_status\"] != 0\n pg_total += gen[\"pg\"]\n end\n end\n #pg_comp = comp_pg_response_total(network, delta_est)\n #info(LOGGER, \"detla: $(delta_est)\")\n #info(LOGGER, \"total gen comp $(pg_comp) - gen inc $(pg_total)\")\n #info(LOGGER, \"total gen $(pg_total) - target gen $(pg_target)\")\n\n pg_delta = pg_target - pg_total\n end\n\n network[\"delta\"] = delta_est\n return delta_est\nend\n\n\n\n@everywhere function extract_solution(network; branch_flow=false)\n sol = Dict{String,Any}()\n\n sol[\"bus\"] = Dict{String,Any}()\n for (i,bus) in network[\"bus\"]\n bus_dict = Dict{String,Any}()\n bus_dict[\"va\"] = get(bus, \"va\", 0.0)\n bus_dict[\"vm\"] = get(bus, \"vm\", 1.0)\n sol[\"bus\"][i] = bus_dict\n end\n\n sol[\"shunt\"] = Dict{String,Any}()\n for (i,shunt) in network[\"shunt\"]\n shunt_dict = Dict{String,Any}()\n shunt_dict[\"gs\"] = get(shunt, \"gs\", 0.0)\n shunt_dict[\"bs\"] = get(shunt, \"bs\", 0.0)\n sol[\"shunt\"][i] = shunt_dict\n end\n\n sol[\"gen\"] = Dict{String,Any}()\n for (i,gen) in network[\"gen\"]\n gen_dict = Dict{String,Any}()\n gen_dict[\"pg\"] = get(gen, \"pg\", 0.0)\n gen_dict[\"qg\"] = get(gen, \"qg\", 0.0)\n sol[\"gen\"][i] = gen_dict\n end\n\n if branch_flow\n sol[\"branch\"] = Dict{String,Any}()\n for (i,branch) in network[\"branch\"]\n branch_dict = Dict{String,Any}()\n branch_dict[\"pf\"] = get(branch, \"pf\", 0.0)\n branch_dict[\"qf\"] = get(branch, \"qf\", 0.0)\n branch_dict[\"pt\"] = get(branch, \"pt\", 0.0)\n branch_dict[\"qt\"] = get(branch, \"qt\", 0.0)\n sol[\"branch\"][i] = branch_dict\n end\n end\n\n return sol\nend\n\n\n\"\"\n\n@everywhere function run_fixed_pf_nbf_rect2(file, model_constructor, solver; kwargs...) # Calls function to check out-of-bound values\n return run_model(file, model_constructor, solver, post_fixed_pf_nbf_rect2; solution_builder = solution_second_stage!, kwargs...)\nend\n\n\n\"\"\n\n@everywhere function post_fixed_pf_nbf_rect2(pm::GenericPowerModel) # Function to look for out-of-bound calues after initial pf.\n start_time = time()\n PowerModels.variable_voltage(pm, bounded=false)\n PowerModels.variable_active_generation(pm, bounded=false)\n PowerModels.variable_reactive_generation(pm, bounded=false)\n #PowerModels.variable_branch_flow(pm, bounded=false)\n #PowerModels.variable_dcline_flow(pm, bounded=false)\n\n #PowerModels.variable_branch_flow(pm, bounded=false)\n\n # TODO set bounds bounds on alpha and total gen capacity\n var(pm)[:delta] = @variable(pm.model, delta, base_name=\"delta\", start=0.0)\n #var(pm)[:delta] = @variable(pm.model, delta, base_name=\"delta\", start=ref(pm, :delta_start))\n #Memento.info(LOGGER, \"post variable time: $(time() - start_time)\")\n\n start_time = time()\n\n vr = var(pm, :vr)\n vi = var(pm, :vi)\n\n PowerModels.constraint_model_voltage(pm)\n\n for (i,bus) in ref(pm, :bus)\n if bus[\"vm_fixed\"]\n @constraint(pm.model, vr[i]^2 + vi[i]^2 == bus[\"vm_base\"]^2)\n end\n end\n\n for i in ids(pm, :ref_buses)\n PowerModels.constraint_theta_ref(pm, i)\n end\n #Memento.info(LOGGER, \"misc constraints time: $(time() - start_time)\")\n\n\n start_time = time()\n p = Dict{Tuple{Int64,Int64,Int64},GenericQuadExpr{Float64,VariableRef}}()\n q = Dict{Tuple{Int64,Int64,Int64},GenericQuadExpr{Float64,VariableRef}}()\n for (i,branch) in ref(pm, :branch)\n #PowerModels.constraint_ohms_yt_from(pm, i)\n #PowerModels.constraint_ohms_yt_to(pm, i)\n\n f_bus_id = branch[\"f_bus\"]\n t_bus_id = branch[\"t_bus\"]\n f_idx = (i, f_bus_id, t_bus_id)\n t_idx = (i, t_bus_id, f_bus_id)\n\n f_bus = ref(pm, :bus, f_bus_id)\n t_bus = ref(pm, :bus, t_bus_id)\n\n #g, b = PowerModels.calc_branch_y(branch)\n #tr, ti = PowerModels.calc_branch_t(branch)\n g = branch[\"g\"]\n b = branch[\"b\"]\n tr = branch[\"tr\"]\n ti = branch[\"ti\"]\n\n g_fr = branch[\"g_fr\"]\n b_fr = branch[\"b_fr\"]\n g_to = branch[\"g_to\"]\n b_to = branch[\"b_to\"]\n tm = branch[\"tap\"]\n\n #p_fr = var(pm, :p, f_idx)\n #q_fr = var(pm, :q, f_idx)\n #p_to = var(pm, :p, t_idx)\n #q_to = var(pm, :q, t_idx)\n vr_fr = vr[f_bus_id] #var(pm, :vr, f_bus_id)\n vr_to = vr[t_bus_id] #var(pm, :vr, t_bus_id)\n vi_fr = vi[f_bus_id] #var(pm, :vi, f_bus_id)\n vi_to = vi[t_bus_id] #var(pm, :vi, t_bus_id)\n\n p[f_idx] = (g+g_fr)/tm^2*(vr_fr^2 + vi_fr^2) + (-g*tr+b*ti)/tm^2*(vr_fr*vr_to + vi_fr*vi_to) + (-b*tr-g*ti)/tm^2*(vi_fr*vr_to - vr_fr*vi_to)\n q[f_idx] = -(b+b_fr)/tm^2*(vr_fr^2 + vi_fr^2) - (-b*tr-g*ti)/tm^2*(vr_fr*vr_to + vi_fr*vi_to) + (-g*tr+b*ti)/tm^2*(vi_fr*vr_to - vr_fr*vi_to)\n p[t_idx] = (g+g_to)*(vr_to^2 + vi_to^2) + (-g*tr-b*ti)/tm^2*(vr_fr*vr_to + vi_fr*vi_to) + (-b*tr+g*ti)/tm^2*(-(vi_fr*vr_to - vr_fr*vi_to))\n q[t_idx] = -(b+b_to)*(vr_to^2 + vi_to^2) - (-b*tr+g*ti)/tm^2*(vr_fr*vr_to + vi_fr*vi_to) + (-g*tr-b*ti)/tm^2*(-(vi_fr*vr_to - vr_fr*vi_to))\n end\n #Memento.info(LOGGER, \"flow expr time: $(time() - start_time)\")\n\n\n start_time = time()\n pg = Dict{Int,Any}()\n qg = Dict{Int,Any}()\n for (i,gen) in ref(pm, :gen)\n if gen[\"pg_fixed\"]\n pg[i] = gen[\"pg\"]\n @constraint(pm.model, var(pm, :pg, i) == gen[\"pg\"])\n else\n pg[i] = gen[\"pg_base\"] + gen[\"alpha\"]*delta\n @constraint(pm.model, var(pm, :pg, i) == gen[\"pg_base\"] + gen[\"alpha\"]*delta)\n end\n\n if gen[\"qg_fixed\"]\n qg[i] = gen[\"qg\"]\n @constraint(pm.model, var(pm, :qg, i) == gen[\"qg\"])\n else\n qg[i] = var(pm, :qg, i)\n end\n end\n #Memento.info(LOGGER, \"gen expr time: $(time() - start_time)\")\n\n\n start_time = time()\n for (i,bus) in ref(pm, :bus)\n #PowerModels.constraint_kcl_shunt(pm, i)\n\n bus_arcs = ref(pm, :bus_arcs, i)\n bus_arcs_dc = ref(pm, :bus_arcs_dc, i)\n bus_gens = ref(pm, :bus_gens, i)\n bus_loads = ref(pm, :bus_loads, i)\n bus_shunts = ref(pm, :bus_shunts, i)\n\n bus_pd = Dict(k => ref(pm, :load, k, \"pd\") for k in bus_loads)\n bus_qd = Dict(k => ref(pm, :load, k, \"qd\") for k in bus_loads)\n\n bus_gs = Dict(k => ref(pm, :shunt, k, \"gs\") for k in bus_shunts)\n bus_bs = Dict(k => ref(pm, :shunt, k, \"bs\") for k in bus_shunts)\n\n #p = var(pm, :p)\n #q = var(pm, :q)\n #pg = var(pm, :pg)\n #qg = var(pm, :qg)\n\n @constraint(pm.model, sum(p[a] for a in bus_arcs) == sum(pg[g] for g in bus_gens) - sum(pd for pd in values(bus_pd)) - sum(gs for gs in values(bus_gs))*(vr[i]^2 + vi[i]^2))\n @constraint(pm.model, sum(q[a] for a in bus_arcs) == sum(qg[g] for g in bus_gens) - sum(qd for qd in values(bus_qd)) + sum(bs for bs in values(bus_bs))*(vr[i]^2 + vi[i]^2))\n end\n #Memento.info(LOGGER, \"power balance constraint time: $(time() - start_time)\")\n\nend\n\n\n\"\"\n\n@everywhere function solution_second_stage!(pm::GenericPowerModel, sol::Dict{String,Any})\n #start_time = time()\n PowerModels.add_setpoint_bus_voltage!(sol, pm)\n #Memento.info(LOGGER, \"voltage solution time: $(time() - start_time)\")\n\n #start_time = time()\n PowerModels.add_setpoint_generator_power!(sol, pm)\n #Memento.info(LOGGER, \"generator solution time: $(time() - start_time)\")\n\n #start_time = time()\n PowerModels.add_setpoint_branch_flow!(sol, pm)\n #Memento.info(LOGGER, \"branch solution time: $(time() - start_time)\")\n\n sol[\"delta\"] = JuMP.value(var(pm, :delta))\n\n #start_time = time()\n PowerModels.add_setpoint_fixed!(sol, pm, \"shunt\", \"bs\", default_value = (item) -> item[\"bs\"])\n #Memento.info(LOGGER, \"shunt solution time: $(time() - start_time)\")\n\n #PowerModels.print_summary(sol)\nend\n\n\n\"fixes solution degeneracy issues when qg is a free variable, as is the case in PowerFlow\"\n\n@everywhere function correct_qg!(network, solution; bus_gens=gens_by_bus(network))\n for (i,gens) in bus_gens\n if length(gens) > 1\n gen_ids = [gen[\"index\"] for gen in gens]\n qgs = [solution[\"gen\"][\"$(j)\"][\"qg\"] for j in gen_ids]\n if !isapprox(abs(sum(qgs)), sum(abs.(qgs)))\n #info(LOGGER, \"$(i) - $(gen_ids) - $(qgs) - output requires correction!\")\n qg_total = sum(qgs)\n\n qg_remaining = sum(qgs)\n qg_assignment = Dict(j => 0.0 for j in gen_ids)\n for (i,gen) in enumerate(gens)\n gen_qg = qg_remaining\n gen_qg = max(gen_qg, gen[\"qmin\"])\n gen_qg = min(gen_qg, gen[\"qmax\"])\n qg_assignment[gen[\"index\"]] = gen_qg\n qg_remaining = qg_remaining - gen_qg\n if i == length(gens) && abs(qg_remaining) > 0.0\n qg_assignment[gen[\"index\"]] = gen_qg + qg_remaining\n end\n end\n #info(LOGGER, \"$(qg_assignment)\")\n for (j,qg) in qg_assignment\n solution[\"gen\"][\"$(j)\"][\"qg\"] = qg\n end\n\n sol_qg_total = sum(solution[\"gen\"][\"$(j)\"][\"qg\"] for j in gen_ids)\n #info(LOGGER, \"$(qg_total) - $(sol_qg_total)\")\n @assert isapprox(qg_total, sol_qg_total)\n\n #info(LOGGER, \"updated to $([solution[\"gen\"][\"$(j)\"][\"qg\"] for j in gen_ids])\")\n end\n end\n end\nend\n\n\n\"\"\"\nassumes there is one reference bus and one connected component and adjusts voltage\nangles to be centered around zero at the reference bus.\n\"\"\"\n\n@everywhere function correct_voltage_angles!(network)\n ref_bus = -1\n for (i,bus) in network[\"bus\"]\n if bus[\"bus_type\"] == 3\n @assert ref_bus == -1\n ref_bus = bus\n end\n end\n\n if !isapprox(ref_bus[\"va\"], 0.0, atol=1e-8)\n warn(LOGGER, \"shifting voltage angles by $(-ref_bus[\"va\"]) to set reference bus to 0.0\")\n shift_voltage_anlges!(network, -ref_bus[\"va\"])\n end\nend\n\n\n\"shift networks voltage angles by a specified amount\"\n\n@everywhere function shift_voltage_anlges!(network, shift::Number)\n for (i,bus) in network[\"bus\"]\n bus[\"va\"] = bus[\"va\"] + shift\n end\nend\n\n\n\"build a static ordering of all contigencies\"\n\n@everywhere function contingency_order(pm_network)\n gen_cont_order = sort(pm_network[\"gen_contingencies\"], by=(x) -> x.label)\n branch_cont_order = sort(pm_network[\"branch_contingencies\"], by=(x) -> x.label)\n\n gen_cont_total = length(gen_cont_order)\n branch_cont_total = length(branch_cont_order)\n\n gen_rate = 1.0\n branch_rate = 1.0\n steps = 1\n\n if gen_cont_total == 0 && branch_cont_total == 0\n # defaults are good\n elseif gen_cont_total == 0 && branch_cont_total != 0\n steps = branch_cont_total\n elseif gen_cont_total != 0 < branch_cont_total == 0\n steps = gen_cont_total\n elseif gen_cont_total == branch_cont_total\n steps = branch_cont_total\n elseif gen_cont_total < branch_cont_total\n gen_rate = 1.0\n branch_rate = branch_cont_total/gen_cont_total\n steps = gen_cont_total\n elseif gen_cont_total > branch_cont_total\n gen_rate = gen_cont_total/branch_cont_total\n branch_rate = 1.0 \n steps = branch_cont_total\n end\n\n cont_order = []\n gen_cont_start = 1\n branch_cont_start = 1\n for s in 1:steps\n gen_cont_end = min(gen_cont_total, trunc(Int,ceil(s*gen_rate)))\n #println(gen_cont_start:gen_cont_end)\n for j in gen_cont_start:gen_cont_end\n push!(cont_order, gen_cont_order[j])\n end\n gen_cont_start = gen_cont_end+1\n\n branch_cont_end = min(branch_cont_total, trunc(Int,ceil(s*branch_rate)))\n #println(\"$(s) - $(branch_cont_start:branch_cont_end)\")\n for j in branch_cont_start:branch_cont_end\n push!(cont_order, branch_cont_order[j])\n end\n branch_cont_start = branch_cont_end+1\n end\n\n @assert(length(cont_order) == gen_cont_total + branch_cont_total)\n\n return cont_order\nend\n\n\n\n\"checks feasibility criteria of contingencies, corrects when possible\"\n\n@everywhere function correct_contingency_solution!(network, cont_sol; bus_gens = gens_by_bus(network)) # Function for post-processing\n label = cont_sol[\"label\"]\n vm_changes = [0.0]\n for (i,bus) in cont_sol[\"bus\"]\n nw_bus = network[\"bus\"][i]\n\n if nw_bus[\"bus_type\"] != 4\n if length(bus_gens[i]) > 0\n qg = sum(cont_sol[\"gen\"][\"$(gen[\"index\"])\"][\"qg\"] for gen in bus_gens[i])\n qmin = sum(gen[\"qmin\"] for gen in bus_gens[i])\n qmax = sum(gen[\"qmax\"] for gen in bus_gens[i])\n\n if !isapprox(abs(qmin - qmax), 0.0)\n if qg >= qmax && bus[\"vm\"] > nw_bus[\"vm\"]\n #println(qmin, \" \", qg, \" \", qmax)\n #warn(LOGGER, \"update qg $(qmin) $(qg) $(qmax)\")\n warn(LOGGER, \"update vm on bus $(i) in contingency $(label) to match set-point $(bus[\"vm\"]) -> $(nw_bus[\"vm\"]) due to qg upper bound and vm direction\")\n push!(vm_changes, abs(bus[\"vm\"] - nw_bus[\"vm\"]))\n bus[\"vm\"] = nw_bus[\"vm\"]\n end\n\n if qg <= qmin && bus[\"vm\"] < nw_bus[\"vm\"]\n #println(qmin, \" \", qg, \" \", qmax)\n #warn(LOGGER, \"update qg $(qmin) $(qg) $(qmax)\")\n warn(LOGGER, \"update vm on bus $(i) in contingency $(label) to match set-point $(bus[\"vm\"]) -> $(nw_bus[\"vm\"]) due to qg lower bound and vm direction\")\n push!(vm_changes, abs(bus[\"vm\"] - nw_bus[\"vm\"]))\n bus[\"vm\"] = nw_bus[\"vm\"]\n end\n end\n end\n\n if bus[\"vm\"] > nw_bus[\"vmax\"]\n warn(LOGGER, \"update vm on bus $(i) in contingency $(label) to match ub $(bus[\"vm\"]) -> $(nw_bus[\"vmax\"]) due to out of bounds\")\n push!(vm_changes, bus[\"vm\"] - nw_bus[\"vmax\"])\n bus[\"vm\"] = nw_bus[\"vmax\"]\n end\n\n if bus[\"vm\"] < nw_bus[\"vmin\"]\n warn(LOGGER, \"update vm on bus $(i) in contingency $(label) to match lb $(bus[\"vm\"]) -> $(nw_bus[\"vmin\"]) due to out of bounds\")\n push!(vm_changes, nw_bus[\"vmin\"] - bus[\"vm\"])\n bus[\"vm\"] = nw_bus[\"vmin\"]\n end\n else\n bus[\"vm\"] = 0.0\n bus[\"va\"] = 0.0\n end\n end\n\n\n bs_changes = [0.0]\n for (i,shunt) in cont_sol[\"shunt\"]\n nw_shunt = network[\"shunt\"][i]\n if haskey(nw_shunt, \"dispatchable\") && nw_shunt[\"dispatchable\"]\n @assert nw_shunt[\"gs\"] == 0.0\n @assert haskey(nw_shunt, \"bmin\") && haskey(nw_shunt, \"bmax\")\n if shunt[\"bs\"] > nw_shunt[\"bmax\"]\n warn(LOGGER, \"update bs on shunt $(i) in contingency $(label) to be in bounds $(shunt[\"bs\"]) -> $(nw_shunt[\"bmax\"])\")\n push!(bs_changes, shunt[\"bs\"] - nw_shunt[\"bmax\"])\n shunt[\"bs\"] = nw_shunt[\"bmax\"]\n end\n if shunt[\"bs\"] < nw_shunt[\"bmin\"]\n warn(LOGGER, \"update bs on shunt $(i) in contingency $(label) to be in bounds $(shunt[\"bs\"]) -> $(nw_shunt[\"bmin\"])\")\n push!(bs_changes, nw_shunt[\"bmin\"] - shunt[\"bs\"])\n shunt[\"bs\"] = nw_shunt[\"bmin\"]\n end\n end\n end\n\n gen_id = -1\n if cont_sol[\"cont_type\"] == \"gen\"\n gen_id = cont_sol[\"cont_comp_id\"]\n end\n\n pg_changes = [0.0]\n qg_changes = [0.0]\n delta = cont_sol[\"delta\"]\n for (i,gen) in cont_sol[\"gen\"]\n nw_gen = network[\"gen\"][i]\n\n if !(nw_gen[\"gen_status\"] == 0 || (gen_id >= 0 && nw_gen[\"index\"] == gen_id))\n bus_id = nw_gen[\"gen_bus\"]\n nw_bus = network[\"bus\"][\"$(bus_id)\"]\n\n if gen[\"qg\"] < nw_gen[\"qmax\"] && gen[\"qg\"] > nw_gen[\"qmin\"]\n bus = cont_sol[\"bus\"][\"$(bus_id)\"]\n #if !isapprox(bus[\"vm\"], nw_bus[\"vm\"])\n if !isapprox(bus[\"vm\"], nw_bus[\"vm\"], atol=vm_eq_tol/2)\n #debug(LOGGER, \"bus $(bus_id) : vm_base $(nw_bus[\"vm\"]) - vm $(bus[\"vm\"]) : reactive bounds $(nw_gen[\"qmin\"]) - $(gen[\"qg\"]) - $(nw_gen[\"qmax\"])\")\n warn(LOGGER, \"update vm on bus $(bus_id) in contingency $(label) to match base case $(bus[\"vm\"]) -> $(nw_bus[\"vm\"]) due to within reactive bounds\")\n end\n bus[\"vm\"] = nw_bus[\"vm\"]\n end\n\n pg_calc = nw_gen[\"pg\"] + nw_gen[\"alpha\"]*delta\n pg_calc = max(pg_calc, nw_gen[\"pmin\"])\n pg_calc = min(pg_calc, nw_gen[\"pmax\"])\n\n if !isapprox(gen[\"pg\"], pg_calc, atol=1e-5)\n warn(LOGGER, \"pg value on gen $(i) $(nw_gen[\"source_id\"]) in contingency $(label) is not consistent with the computed value given:$(gen[\"pg\"]) calc:$(pg_calc)\")\n end\n\n if gen[\"pg\"] > nw_gen[\"pmax\"]\n warn(LOGGER, \"update pg on gen $(i) $(nw_gen[\"source_id\"]) in contingency $(label) to match ub $(gen[\"pg\"]) -> $(nw_gen[\"pmax\"])\")\n push!(pg_changes, gen[\"pg\"] - nw_gen[\"pmax\"])\n gen[\"pg\"] = nw_gen[\"pmax\"]\n end\n\n if gen[\"pg\"] < nw_gen[\"pmin\"]\n warn(LOGGER, \"update pg on gen $(i) $(nw_gen[\"source_id\"]) in contingency $(label) to match lb $(gen[\"pg\"]) -> $(nw_gen[\"pmin\"])\")\n push!(pg_changes, nw_gen[\"pmin\"] - gen[\"pg\"])\n gen[\"pg\"] = nw_gen[\"pmin\"]\n end\n\n if gen[\"qg\"] > nw_gen[\"qmax\"]\n warn(LOGGER, \"update qg on gen $(i) $(nw_gen[\"source_id\"]) in contingency $(label) to match ub $(gen[\"qg\"]) -> $(nw_gen[\"qmax\"])\")\n push!(qg_changes, gen[\"qg\"] - nw_gen[\"qmax\"])\n gen[\"qg\"] = nw_gen[\"qmax\"]\n end\n\n if gen[\"qg\"] < nw_gen[\"qmin\"]\n warn(LOGGER, \"update qg on gen $(i) $(nw_gen[\"source_id\"]) in contingency $(label) to match lb $(gen[\"qg\"]) -> $(nw_gen[\"qmin\"])\")\n push!(qg_changes, nw_gen[\"qmin\"] - gen[\"qg\"])\n gen[\"qg\"] = nw_gen[\"qmin\"]\n end\n else\n gen[\"pg\"] = 0.0\n gen[\"qg\"] = 0.0\n end\n end\n\n # test imbalance on branch conts after flow corrections\n #=\n network_tmp = deepcopy(network)\n cont_type = cont_sol[\"cont_type\"]\n cont_idx = cont_sol[\"cont_comp_id\"]\n network_tmp[\"branch\"][\"$(cont_idx)\"][\"br_status\"] = 0\n PowerModels.update_data!(network_tmp, cont_sol)\n deltas = compute_power_balance_deltas!(network_tmp)\n println(\"$(label): $(deltas)\")\n =#\n\n cont_changed = length(vm_changes) > 1 || length(bs_changes) > 1 || length(pg_changes) > 1 || length(qg_changes) > 1\n\n if cont_changed\n _summary_changes(network, label, vm_changes, bs_changes, pg_changes, qg_changes)\n end\n\n return (changed=Int(cont_changed), vm_changes_max=maximum(vm_changes), bs_changes_max=maximum(bs_changes), pg_changes_max=maximum(pg_changes), qg_changes_max=maximum(qg_changes))\nend\n\n\n@everywhere function _summary_changes(network, contingency, vm_changes, bs_changes, pg_changes, qg_changes)\n println(\"\")\n\n data = [\n \"----\",\n \"contingency\",\n \"bus\",\n \"branch\",\n \"gen_cont\",\n \"branch_cont\",\n \"vm_count\",\n \"bs_count\",\n \"pg_count\",\n \"qg_count\",\n \"vm_max\",\n \"bs_max\",\n \"pg_max\",\n \"qg_max\",\n \"vm_mean\",\n \"bs_mean\",\n \"pg_mean\",\n \"qg_mean\",\n ]\n println(join(data, \", \"))\n\n data = [\n \"DATA_CHANGES\",\n contingency,\n length(network[\"bus\"]),\n length(network[\"branch\"]),\n length(network[\"gen_contingencies\"]),\n length(network[\"branch_contingencies\"]),\n length(vm_changes)-1,\n length(bs_changes)-1,\n length(pg_changes)-1,\n length(qg_changes)-1,\n maximum(vm_changes),\n maximum(bs_changes),\n maximum(pg_changes),\n maximum(qg_changes),\n mean(vm_changes),\n mean(bs_changes),\n mean(pg_changes),\n mean(qg_changes),\n ]\n println(join(data, \", \"))\nend\n\n\n@everywhere function write_solution2_contingency(io::IO, pm_network, contingency_solution) # Writes solution2 for contingency\n base_mva = pm_network[\"baseMVA\"]\n\n bus_switched_shunt_b = Dict(i => 0.0 for (i,bus) in pm_network[\"bus\"])\n for (i,nw_shunt) in pm_network[\"shunt\"]\n if nw_shunt[\"dispatchable\"] && nw_shunt[\"status\"] == 1\n #@assert nw_shunt[\"gs\"] == 0.0\n shunt = contingency_solution[\"shunt\"][i]\n bus_switched_shunt_b[\"$(nw_shunt[\"shunt_bus\"])\"] += shunt[\"bs\"]\n end\n end\n\n write(io, \"-- contingency\\n\")\n write(io, \"label\\n\")\n write(io, \"$(contingency_solution[\"label\"])\\n\")\n\n write(io, \"-- bus section\\n\")\n write(io, \"i, v(p.u.), theta(deg), bcs(MVAR at v = 1 p.u.)\\n\")\n for (i,bus) in contingency_solution[\"bus\"]\n nw_bus = pm_network[\"bus\"][i]\n write(io, \"$(nw_bus[\"index\"]), $(bus[\"vm\"]), $(rad2deg(bus[\"va\"])), $(base_mva*bus_switched_shunt_b[i])\\n\")\n end\n\n write(io, \"-- generator section\\n\")\n write(io, \"i, id, p(MW), q(MVAR)\\n\")\n for (i,gen) in contingency_solution[\"gen\"]\n nw_gen = pm_network[\"gen\"][i]\n bus_index = nw_gen[\"source_id\"][2]\n gen_id = nw_gen[\"source_id\"][3]\n write(io, \"$(bus_index), $(gen_id), $(base_mva*gen[\"pg\"]), $(base_mva*gen[\"qg\"])\\n\")\n end\n\n write(io, \"-- delta section\\n\")\n write(io, \"delta(MW)\\n\")\n write(io, \"$(base_mva*contingency_solution[\"delta\"])\\n\")\nend\n\n\n\"checks feasibility criteria of network solution, produces an error if a problem is found\"\nfunction check_network_solution(network)\n for (i,bus) in network[\"bus\"]\n if bus[\"bus_type\"] != 4\n if bus[\"vm\"] > bus[\"vmax\"] || bus[\"vm\"] < bus[\"vmin\"]\n error(LOGGER, \"vm on $(bus[\"source_id\"]) is not in bounds $(bus[\"vmin\"]) to $(bus[\"vmax\"]), given $(bus[\"vm\"])\")\n end\n end\n end\n\n for (i,shunt) in network[\"shunt\"]\n if shunt[\"status\"] != 0\n if haskey(shunt, \"dispatchable\")\n if shunt[\"dispatchable\"]\n @assert shunt[\"gs\"] == 0.0\n @assert haskey(shunt, \"bmin\") && haskey(shunt, \"bmax\")\n if shunt[\"bs\"] > shunt[\"bmax\"] || shunt[\"bs\"] < shunt[\"bmin\"]\n error(LOGGER, \"bs on $(shunt[\"source_id\"]) is not in bounds $(shunt[\"bmin\"]) to $(shunt[\"bmax\"]), given $(shunt[\"bs\"])\")\n end\n end\n end\n end\n end\n\n for (i,gen) in network[\"gen\"]\n if gen[\"gen_status\"] != 0\n if gen[\"pg\"] > gen[\"pmax\"] || gen[\"pg\"] < gen[\"pmin\"]\n error(LOGGER, \"pg on gen $(gen[\"source_id\"]) not in bounds $(gen[\"pmin\"]) to $(gen[\"pmax\"]), given $(gen[\"pg\"])\")\n end\n\n if gen[\"qg\"] > gen[\"qmax\"] || gen[\"qg\"] < gen[\"qmin\"]\n error(LOGGER, \"pg on gen $(gen[\"source_id\"]) not in bounds $(gen[\"qmin\"]) to $(gen[\"qmax\"]), given $(gen[\"qg\"])\")\n end\n end\n end\nend\n\n\nfunction compute_power_balance_deltas!(network)\n flows = PowerModels.calc_branch_flow_ac(network)\n PowerModels.update_data!(network, flows)\n\n balance = PowerModels.calc_power_balance(network)\n PowerModels.update_data!(network, balance)\n\n p_delta_abs = [abs(bus[\"p_delta\"]) for (i,bus) in network[\"bus\"] if bus[\"bus_type\"] != 4]\n q_delta_abs = [abs(bus[\"q_delta\"]) for (i,bus) in network[\"bus\"] if bus[\"bus_type\"] != 4]\n\n return (\n p_delta_abs_max = maximum(p_delta_abs),\n p_delta_abs_mean = mean(p_delta_abs),\n q_delta_abs_max = maximum(q_delta_abs),\n q_delta_abs_mean = mean(q_delta_abs),\n )\nend\n\n\nfunction combine_files(files, output_file_name; output_dir=\"\")\n if length(output_dir) > 0\n output_path = joinpath(output_dir, output_file_name)\n else\n output_path = output_file_name\n end\n\n open(output_path, \"w\") do output\n for file in files\n open(file, \"r\") do input\n for line in readlines(input, keep=true)\n write(output, line)\n end\n end\n end\n end\n\n return output_path\nend\n\n\nfunction remove_files(files)\n for file in files\n if isfile(file)\n info(LOGGER, \"deleting: $(file)\")\n rm(file)\n else\n info(LOGGER, \"skipping file: $(file)\")\n end\n end\nend\n", "meta": {"hexsha": "e0c45fdf576fdce627ec097c545b75a8f4a8f2d5", "size": 46450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code-2-lib/lib.jl", "max_stars_repo_name": "mwasm/goc-solution2-solver", "max_stars_repo_head_hexsha": "51b3b5833ca6f468095c02f4c0fa76b121c176d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code-2-lib/lib.jl", "max_issues_repo_name": "mwasm/goc-solution2-solver", "max_issues_repo_head_hexsha": "51b3b5833ca6f468095c02f4c0fa76b121c176d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code-2-lib/lib.jl", "max_forks_repo_name": "mwasm/goc-solution2-solver", "max_forks_repo_head_hexsha": "51b3b5833ca6f468095c02f4c0fa76b121c176d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4028213166, "max_line_length": 225, "alphanum_fraction": 0.5599138859, "num_tokens": 12560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19954527247435525}} {"text": "# Main DG data structure that contains all relevant data for the DG solver\nmutable struct Dg2D{Eqn<:AbstractEquation, MeshType, NVARS, POLYDEG,\n SurfaceFlux, VolumeFlux, InitialConditions, SourceTerms, BoundaryConditions,\n MortarType, VolumeIntegralType, ShockIndicatorVariable,\n VectorNnodes, MatrixNnodes, MatrixNnodes2,\n InverseVandermondeLegendre, MortarMatrix,\n VectorAnalysisNnodes, AnalysisVandermonde} <: AbstractDg{2, POLYDEG, MeshType}\n equations::Eqn\n\n surface_flux_function::SurfaceFlux\n volume_flux_function::VolumeFlux\n\n initial_conditions::InitialConditions\n source_terms::SourceTerms\n\n elements::ElementContainer2D{NVARS, POLYDEG}\n n_elements::Int\n\n interfaces::InterfaceContainer2D{NVARS, POLYDEG}\n n_interfaces::Int\n\n mpi_interfaces::MpiInterfaceContainer2D{NVARS, POLYDEG}\n n_mpi_interfaces::Int\n\n boundaries::BoundaryContainer2D{NVARS, POLYDEG}\n n_boundaries::Int\n n_boundaries_per_direction::SVector{4, Int}\n\n mortar_type::MortarType\n l2mortars::L2MortarContainer2D{NVARS, POLYDEG}\n n_l2mortars::Int\n ecmortars::EcMortarContainer2D{NVARS, POLYDEG}\n n_ecmortars::Int\n\n boundary_conditions::BoundaryConditions\n\n nodes::VectorNnodes\n weights::VectorNnodes\n inverse_weights::VectorNnodes\n inverse_vandermonde_legendre::InverseVandermondeLegendre\n lhat::MatrixNnodes2\n\n volume_integral_type::VolumeIntegralType\n dhat::MatrixNnodes\n dsplit::MatrixNnodes\n dsplit_transposed::MatrixNnodes\n\n mortar_forward_upper::MortarMatrix\n mortar_forward_lower::MortarMatrix\n l2mortar_reverse_upper::MortarMatrix\n l2mortar_reverse_lower::MortarMatrix\n ecmortar_reverse_upper::MortarMatrix\n ecmortar_reverse_lower::MortarMatrix\n\n analysis_nodes::VectorAnalysisNnodes\n analysis_weights::VectorAnalysisNnodes\n analysis_weights_volume::VectorAnalysisNnodes\n analysis_vandermonde::AnalysisVandermonde\n analysis_total_volume::Float64\n analysis_quantities::Vector{Symbol}\n save_analysis::Bool\n analysis_filename::String\n\n shock_indicator_variable::ShockIndicatorVariable\n shock_alpha_max::Float64\n shock_alpha_min::Float64\n shock_alpha_smooth::Bool\n amr_indicator::Symbol\n amr_alpha_max::Float64\n amr_alpha_min::Float64\n amr_alpha_smooth::Bool\n\n mpi_neighbor_ranks::Vector{Int}\n mpi_neighbor_interfaces::Vector{Vector{Int}}\n mpi_send_buffers::Vector{Vector{Float64}}\n mpi_recv_buffers::Vector{Vector{Float64}}\n mpi_send_requests::Vector{MPI.Request}\n mpi_recv_requests::Vector{MPI.Request}\n n_elements_by_rank::OffsetArray{Int, 1, Array{Int, 1}}\n n_elements_global::Int\n first_element_global_id::Int\n\n element_variables::Dict{Symbol, Union{Vector{Float64}, Vector{Int}}}\n cache::Dict{Symbol, Any}\n thread_cache::Any # to make fully-typed output more readable\n\n initial_state_integrals::Vector{Float64}\nend\n\n\n# Convenience constructor to create DG solver instance\nfunction Dg2D(equation::AbstractEquation{NDIMS, NVARS}, surface_flux_function, volume_flux_function, initial_conditions, source_terms, mesh::TreeMesh, POLYDEG) where {NDIMS, NVARS}\n # Get local cells for which an element needs to be created (i.e., all leaf cells)\n if mpi_isparallel()\n leaf_cell_ids = local_leaf_cells(mesh.tree)\n else\n leaf_cell_ids = leaf_cells(mesh.tree)\n end\n\n # Initialize element container\n elements = init_elements(leaf_cell_ids, mesh, Val(NVARS), Val(POLYDEG))\n n_elements = nelements(elements)\n\n # Initialize interface container\n interfaces = init_interfaces(leaf_cell_ids, mesh, Val(NVARS), Val(POLYDEG), elements)\n n_interfaces = ninterfaces(interfaces)\n\n # Initialize MPI interface container\n mpi_interfaces = init_mpi_interfaces(leaf_cell_ids, mesh, Val(NVARS), Val(POLYDEG), elements)\n n_mpi_interfaces = nmpiinterfaces(mpi_interfaces)\n\n # Initialize boundaries\n boundaries, n_boundaries_per_direction = init_boundaries(leaf_cell_ids, mesh, Val(NVARS), Val(POLYDEG), elements)\n n_boundaries = nboundaries(boundaries)\n\n # Initialize mortar containers\n mortar_type = Val(Symbol(parameter(\"mortar_type\", \"l2\", valid=[\"l2\", \"ec\"])))\n l2mortars, ecmortars = init_mortars(leaf_cell_ids, mesh, Val(NVARS), Val(POLYDEG), elements, mortar_type)\n n_l2mortars = nmortars(l2mortars)\n n_ecmortars = nmortars(ecmortars)\n\n # Sanity checks\n if isperiodic(mesh.tree) && n_l2mortars == 0 && n_ecmortars == 0 && mpi_isserial()\n @assert n_interfaces == 2*n_elements (\"For 2D and periodic domains and conforming elements, \"\n * \"n_surf must be the same as 2*n_elem\")\n end\n\n # Initialize boundary conditions\n boundary_conditions = init_boundary_conditions(n_boundaries_per_direction, mesh)\n\n # Initialize interpolation data structures\n n_nodes = POLYDEG + 1\n nodes, weights = gauss_lobatto_nodes_weights(n_nodes)\n inverse_weights = 1 ./ weights\n _, inverse_vandermonde_legendre = vandermonde_legendre(nodes)\n lhat = zeros(n_nodes, 2)\n lhat[:, 1] = calc_lhat(-1.0, nodes, weights)\n lhat[:, 2] = calc_lhat( 1.0, nodes, weights)\n\n # Initialize differentiation operator\n volume_integral_type = Val(Symbol(parameter(\"volume_integral_type\", \"weak_form\",\n valid=[\"weak_form\", \"split_form\", \"shock_capturing\"])))\n # FIXME: This should be removed as soon as it possible to set solver-specific parameters\n if equation isa HyperbolicDiffusionEquations2D && globals[:euler_gravity]\n volume_integral_type = Val(:weak_form)\n end\n dhat = calc_dhat(nodes, weights)\n dsplit = calc_dsplit(nodes, weights)\n dsplit_transposed = transpose(calc_dsplit(nodes, weights))\n\n # Initialize L2 mortar projection operators\n mortar_forward_upper = calc_forward_upper(n_nodes)\n mortar_forward_lower = calc_forward_lower(n_nodes)\n l2mortar_reverse_upper = calc_reverse_upper(n_nodes, Val(:gauss))\n l2mortar_reverse_lower = calc_reverse_lower(n_nodes, Val(:gauss))\n ecmortar_reverse_upper = calc_reverse_upper(n_nodes, Val(:gauss_lobatto))\n ecmortar_reverse_lower = calc_reverse_lower(n_nodes, Val(:gauss_lobatto))\n\n # Initialize data structures for error analysis (by default, we use twice the\n # number of analysis nodes as the normal solution)\n analysis_polydeg = 2 * (n_nodes) - 1\n analysis_nodes, analysis_weights = gauss_lobatto_nodes_weights(analysis_polydeg + 1)\n analysis_weights_volume = analysis_weights\n analysis_vandermonde = polynomial_interpolation_matrix(nodes, analysis_nodes)\n analysis_total_volume = mesh.tree.length_level_0^ndims(mesh)\n\n # Store which quantities should be analyzed in `analyze_solution`\n if parameter_exists(\"extra_analysis_quantities\")\n extra_analysis_quantities = Symbol.(parameter(\"extra_analysis_quantities\"))\n else\n extra_analysis_quantities = Symbol[]\n end\n analysis_quantities = vcat(collect(Symbol.(default_analysis_quantities(equation))),\n extra_analysis_quantities)\n\n # If analysis should be saved to file, create file with header\n save_analysis = parameter(\"save_analysis\", false)\n if save_analysis\n # Create output directory (if it does not exist)\n output_directory = parameter(\"output_directory\", \"out\")\n mkpath(output_directory)\n\n # Determine filename\n analysis_filename = joinpath(output_directory, \"analysis.dat\")\n\n # Open file and write header\n save_analysis_header(analysis_filename, analysis_quantities, equation)\n else\n analysis_filename = \"\"\n end\n\n # Initialize AMR\n amr_indicator = Symbol(parameter(\"amr_indicator\", \"n/a\",\n valid=[\"n/a\", \"gauss\", \"isentropic_vortex\", \"blast_wave\", \"khi\", \"blob\", \"sedov_self_gravity\"]))\n\n # Initialize storage for element variables\n element_variables = Dict{Symbol, Union{Vector{Float64}, Vector{Int}}}()\n if amr_indicator === :khi || amr_indicator === :blob\n element_variables[:amr_indicator_values] = zeros(n_elements)\n end\n # maximum and minimum alpha for shock capturing\n shock_alpha_max = parameter(\"shock_alpha_max\", 0.5)\n shock_alpha_min = parameter(\"shock_alpha_min\", 0.001)\n shock_alpha_smooth = parameter(\"shock_alpha_smooth\", true)\n\n # variable used to compute the shock capturing indicator\n # \"eval is evil\"\n # This is a temporary hack until we have switched to a library based approach\n # with pure Julia code instead of parameter files.\n shock_indicator_variable = eval(Symbol(parameter(\"shock_indicator_variable\", \"density_pressure\")))\n\n # maximum and minimum alpha for amr control\n amr_alpha_max = parameter(\"amr_alpha_max\", 0.5)\n amr_alpha_min = parameter(\"amr_alpha_min\", 0.001)\n amr_alpha_smooth = parameter(\"amr_alpha_smooth\", false)\n\n # Set up MPI neighbor connectivity and communication data structures\n if mpi_isparallel()\n (mpi_neighbor_ranks,\n mpi_neighbor_interfaces) = init_mpi_neighbor_connectivity(elements, mpi_interfaces, mesh)\n (mpi_send_buffers,\n mpi_recv_buffers,\n mpi_send_requests,\n mpi_recv_requests) = init_mpi_data_structures(mpi_neighbor_interfaces,\n Val(NDIMS), Val(NVARS), Val(POLYDEG))\n\n # Determine local and total number of elements\n n_elements_by_rank = Vector{Int}(undef, mpi_nranks())\n n_elements_by_rank[mpi_rank() + 1] = n_elements\n MPI.Allgather!(n_elements_by_rank, 1, mpi_comm())\n n_elements_by_rank = OffsetArray(n_elements_by_rank, 0:(mpi_nranks() - 1))\n n_elements_global = MPI.Allreduce(n_elements, +, mpi_comm())\n @assert n_elements_global == sum(n_elements_by_rank) \"error in total number of elements\"\n\n # Determine the global element id of the first element\n first_element_global_id = MPI.Exscan(n_elements, +, mpi_comm())\n if mpi_isroot()\n # With Exscan, the result on the first rank is undefined\n first_element_global_id = 1\n else\n # On all other ranks we need to add one, since Julia has one-based indices\n first_element_global_id += 1\n end\n else\n mpi_neighbor_ranks = Int[]\n mpi_neighbor_interfaces = Vector{Int}[]\n mpi_send_buffers = Vector{Float64}[]\n mpi_recv_buffers = Vector{Float64}[]\n mpi_send_requests = MPI.Request[]\n mpi_recv_requests = MPI.Request[]\n n_elements_by_rank = OffsetArray([n_elements], 0:0)\n n_elements_global = n_elements\n first_element_global_id = 1\n end\n\n # Initialize element variables such that they are available in the first solution file\n if volume_integral_type === Val(:shock_capturing)\n element_variables[:blending_factor] = zeros(n_elements)\n end\n\n # Initialize storage for the cache\n cache = Dict{Symbol, Any}()\n thread_cache = create_thread_cache_2d(NVARS, POLYDEG+1)\n\n # Store initial state integrals for conservation error calculation\n initial_state_integrals = Vector{Float64}()\n\n # Convert all performance-critical fields to StaticArrays types\n nodes = SVector{POLYDEG+1}(nodes)\n weights = SVector{POLYDEG+1}(weights)\n inverse_weights = SVector{POLYDEG+1}(inverse_weights)\n lhat = SMatrix{POLYDEG+1,2}(lhat)\n dhat = SMatrix{POLYDEG+1,POLYDEG+1}(dhat)\n dsplit = SMatrix{POLYDEG+1,POLYDEG+1}(dsplit)\n dsplit_transposed = SMatrix{POLYDEG+1,POLYDEG+1}(dsplit_transposed)\n mortar_forward_upper = SMatrix{POLYDEG+1,POLYDEG+1}(mortar_forward_upper)\n mortar_forward_lower = SMatrix{POLYDEG+1,POLYDEG+1}(mortar_forward_lower)\n l2mortar_reverse_upper = SMatrix{POLYDEG+1,POLYDEG+1}(l2mortar_reverse_upper)\n l2mortar_reverse_lower = SMatrix{POLYDEG+1,POLYDEG+1}(l2mortar_reverse_lower)\n ecmortar_reverse_upper = SMatrix{POLYDEG+1,POLYDEG+1}(ecmortar_reverse_upper)\n ecmortar_reverse_lower = SMatrix{POLYDEG+1,POLYDEG+1}(ecmortar_reverse_lower)\n analysis_nodes = SVector{analysis_polydeg+1}(analysis_nodes)\n analysis_weights = SVector{analysis_polydeg+1}(analysis_weights)\n analysis_weights_volume = SVector{analysis_polydeg+1}(analysis_weights_volume)\n\n # Create actual DG solver instance\n dg = Dg2D{typeof(equation), typeof(mesh), NVARS, POLYDEG,\n typeof(surface_flux_function), typeof(volume_flux_function), typeof(initial_conditions),\n typeof(source_terms), typeof(boundary_conditions),\n typeof(mortar_type), typeof(volume_integral_type), typeof(shock_indicator_variable),\n typeof(nodes), typeof(dhat), typeof(lhat), typeof(inverse_vandermonde_legendre),\n typeof(mortar_forward_upper), typeof(analysis_nodes), typeof(analysis_vandermonde)}(\n equation,\n surface_flux_function, volume_flux_function,\n initial_conditions, source_terms,\n elements, n_elements,\n interfaces, n_interfaces,\n mpi_interfaces, n_mpi_interfaces,\n boundaries, n_boundaries, n_boundaries_per_direction,\n mortar_type,\n l2mortars, n_l2mortars,\n ecmortars, n_ecmortars,\n boundary_conditions,\n nodes, weights, inverse_weights,\n inverse_vandermonde_legendre, lhat,\n volume_integral_type,\n dhat, dsplit, dsplit_transposed,\n mortar_forward_upper, mortar_forward_lower,\n l2mortar_reverse_upper, l2mortar_reverse_lower,\n ecmortar_reverse_upper, ecmortar_reverse_lower,\n analysis_nodes, analysis_weights, analysis_weights_volume,\n analysis_vandermonde, analysis_total_volume,\n analysis_quantities, save_analysis, analysis_filename,\n shock_indicator_variable, shock_alpha_max, shock_alpha_min, shock_alpha_smooth,\n amr_indicator, amr_alpha_max, amr_alpha_min, amr_alpha_smooth,\n mpi_neighbor_ranks, mpi_neighbor_interfaces,\n mpi_send_buffers, mpi_recv_buffers, mpi_send_requests, mpi_recv_requests,\n n_elements_by_rank, n_elements_global, first_element_global_id,\n element_variables, cache, thread_cache,\n initial_state_integrals)\n\n return dg\nend\n\n\nfunction create_thread_cache_2d(n_variables, n_nodes)\n # Type alias only for convenience\n A4d = Array{Float64, 4}\n A3d = Array{Float64, 3}\n A3dp1_x = Array{Float64, 3}\n A3dp1_y = Array{Float64, 3}\n MA2d = MArray{Tuple{n_variables, n_nodes}, Float64}\n A2d = Array{Float64, 2}\n\n # Pre-allocate data structures to speed up computation (thread-safe)\n f1_threaded = A4d[A4d(undef, n_variables, n_nodes, n_nodes, n_nodes) for _ in 1:Threads.nthreads()]\n f2_threaded = A4d[A4d(undef, n_variables, n_nodes, n_nodes, n_nodes) for _ in 1:Threads.nthreads()]\n fstar1_threaded = A3dp1_x[A3dp1_x(undef, n_variables, n_nodes+1, n_nodes) for _ in 1:Threads.nthreads()]\n fstar2_threaded = A3dp1_y[A3dp1_y(undef, n_variables, n_nodes, n_nodes+1) for _ in 1:Threads.nthreads()]\n fstar_upper_threaded = [MA2d(undef) for _ in 1:Threads.nthreads()]\n fstar_lower_threaded = [MA2d(undef) for _ in 1:Threads.nthreads()]\n noncons_diamond_upper_threaded = [MA2d(undef) for _ in 1:Threads.nthreads()]\n noncons_diamond_lower_threaded = [MA2d(undef) for _ in 1:Threads.nthreads()]\n\n indicator_threaded = [A3d(undef, 1, n_nodes, n_nodes) for _ in 1:Threads.nthreads()]\n modal_threaded = [A3d(undef, 1, n_nodes, n_nodes) for _ in 1:Threads.nthreads()]\n modal_tmp1_threaded = [A3d(undef, 1, n_nodes, n_nodes) for _ in 1:Threads.nthreads()]\n\n return (; f1_threaded, f2_threaded,\n fstar1_threaded, fstar2_threaded,\n fstar_upper_threaded, fstar_lower_threaded,\n noncons_diamond_upper_threaded, noncons_diamond_lower_threaded,\n indicator_threaded, modal_threaded, modal_tmp1_threaded)\nend\n\n\n# Count the number of interfaces that need to be created\nfunction count_required_interfaces(mesh::TreeMesh2D, cell_ids)\n count = 0\n\n # Iterate over all cells\n for cell_id in cell_ids\n for direction in 1:n_directions(mesh.tree)\n # Only count interfaces in positive direction to avoid double counting\n if direction % 2 == 1\n continue\n end\n\n # If no neighbor exists, current cell is small or at boundary and thus we need a mortar\n if !has_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # Skip if neighbor has children\n neighbor_cell_id = mesh.tree.neighbor_ids[direction, cell_id]\n if has_children(mesh.tree, neighbor_cell_id)\n continue\n end\n\n # Skip if neighbor is on different rank -> create MPI interface instead\n if mpi_isparallel() && !is_own_cell(mesh.tree, neighbor_cell_id)\n continue\n end\n\n count += 1\n end\n end\n\n return count\nend\n\n\n# Count the number of boundaries that need to be created\nfunction count_required_boundaries(mesh::TreeMesh2D, cell_ids)\n count = 0\n\n # Iterate over all cells\n for cell_id in cell_ids\n for direction in 1:n_directions(mesh.tree)\n # If neighbor exists, current cell is not at a boundary\n if has_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # If coarse neighbor exists, current cell is not at a boundary\n if has_coarse_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # No neighbor exists in this direction -> must be a boundary\n count += 1\n end\n end\n\n return count\nend\n\n\n# Count the number of mortars that need to be created\nfunction count_required_mortars(mesh::TreeMesh2D, cell_ids)\n count = 0\n\n # Iterate over all cells and count mortars from perspective of coarse cells\n for cell_id in cell_ids\n for direction in 1:n_directions(mesh.tree)\n # If no neighbor exists, cell is small with large neighbor or at boundary -> do nothing\n if !has_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # If neighbor has no children, this is a conforming interface -> do nothing\n neighbor_id = mesh.tree.neighbor_ids[direction, cell_id]\n if !has_children(mesh.tree, neighbor_id)\n continue\n end\n\n count +=1\n end\n end\n\n return count\nend\n\n\n# Create element container, initialize element data, and return element container for further use\n#\n# NVARS: number of variables\n# POLYDEG: polynomial degree\nfunction init_elements(cell_ids, mesh::TreeMesh2D, ::Val{NVARS}, ::Val{POLYDEG}) where {NVARS, POLYDEG}\n # Initialize container\n n_elements = length(cell_ids)\n elements = ElementContainer2D{NVARS, POLYDEG}(n_elements)\n\n # Store cell ids\n elements.cell_ids .= cell_ids\n\n # Determine node locations\n n_nodes = POLYDEG + 1\n nodes, _ = gauss_lobatto_nodes_weights(n_nodes)\n\n # Calculate inverse Jacobian and node coordinates\n for element_id in 1:nelements(elements)\n # Get cell id\n cell_id = cell_ids[element_id]\n\n # Get cell length\n dx = length_at_cell(mesh.tree, cell_id)\n\n # Calculate inverse Jacobian as 1/(h/2)\n elements.inverse_jacobian[element_id] = 2/dx\n\n # Calculate node coordinates\n for j in 1:n_nodes\n for i in 1:n_nodes\n elements.node_coordinates[1, i, j, element_id] = (\n mesh.tree.coordinates[1, cell_id] + dx/2 * nodes[i])\n elements.node_coordinates[2, i, j, element_id] = (\n mesh.tree.coordinates[2, cell_id] + dx/2 * nodes[j])\n end\n end\n end\n\n return elements\nend\n\n\n# Create interface container, initialize interface data, and return interface container for further use\n#\n# NVARS: number of variables\n# POLYDEG: polynomial degree\nfunction init_interfaces(cell_ids, mesh::TreeMesh2D, ::Val{NVARS}, ::Val{POLYDEG}, elements) where {NVARS, POLYDEG}\n # Initialize container\n n_interfaces = count_required_interfaces(mesh, cell_ids)\n interfaces = InterfaceContainer2D{NVARS, POLYDEG}(n_interfaces)\n\n # Connect elements with interfaces\n init_interface_connectivity!(elements, interfaces, mesh)\n\n return interfaces\nend\n\n\n# Create boundaries container, initialize boundary data, and return boundaries container\n#\n# NVARS: number of variables\n# POLYDEG: polynomial degree\nfunction init_boundaries(cell_ids, mesh::TreeMesh2D, ::Val{NVARS}, ::Val{POLYDEG}, elements) where {NVARS, POLYDEG}\n # Initialize container\n n_boundaries = count_required_boundaries(mesh, cell_ids)\n boundaries = BoundaryContainer2D{NVARS, POLYDEG}(n_boundaries)\n\n # Connect elements with boundaries\n n_boundaries_per_direction = init_boundary_connectivity!(elements, boundaries, mesh)\n\n return boundaries, n_boundaries_per_direction\nend\n\n\n# Create mortar container, initialize mortar data, and return mortar container for further use\n#\n# NVARS: number of variables\n# POLYDEG: polynomial degree\nfunction init_mortars(cell_ids, mesh::TreeMesh2D, ::Val{NVARS}, ::Val{POLYDEG}, elements, mortar_type) where {NVARS, POLYDEG}\n # Initialize containers\n n_mortars = count_required_mortars(mesh, cell_ids)\n if mortar_type === Val(:l2)\n n_l2mortars = n_mortars\n n_ecmortars = 0\n elseif mortar_type === Val(:ec)\n n_l2mortars = 0\n n_ecmortars = n_mortars\n else\n error(\"unknown mortar type '$(mortar_type)'\")\n end\n l2mortars = L2MortarContainer2D{NVARS, POLYDEG}(n_l2mortars)\n ecmortars = EcMortarContainer2D{NVARS, POLYDEG}(n_ecmortars)\n\n # Connect elements with interfaces and l2mortars\n if mortar_type === Val(:l2)\n init_mortar_connectivity!(elements, l2mortars, mesh)\n elseif mortar_type === Val(:ec)\n init_mortar_connectivity!(elements, ecmortars, mesh)\n else\n error(\"unknown mortar type '$(mortar_type)'\")\n end\n\n return l2mortars, ecmortars\nend\n\n\n# Initialize connectivity between elements and interfaces\nfunction init_interface_connectivity!(elements, interfaces, mesh::TreeMesh2D)\n # Construct cell -> element mapping for easier algorithm implementation\n tree = mesh.tree\n c2e = zeros(Int, length(tree))\n for element_id in 1:nelements(elements)\n c2e[elements.cell_ids[element_id]] = element_id\n end\n\n # Reset interface count\n count = 0\n\n # Iterate over all elements to find neighbors and to connect via interfaces\n for element_id in 1:nelements(elements)\n # Get cell id\n cell_id = elements.cell_ids[element_id]\n\n # Loop over directions\n for direction in 1:n_directions(mesh.tree)\n # Only create interfaces in positive direction\n if direction % 2 == 1\n continue\n end\n\n # If no neighbor exists, current cell is small and thus we need a mortar\n if !has_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # Skip if neighbor has children\n neighbor_cell_id = mesh.tree.neighbor_ids[direction, cell_id]\n if has_children(mesh.tree, neighbor_cell_id)\n continue\n end\n\n # Skip if neighbor is on different rank -> create MPI interface instead\n if mpi_isparallel() && !is_own_cell(mesh.tree, neighbor_cell_id)\n continue\n end\n\n # Create interface between elements (1 -> \"left\" of interface, 2 -> \"right\" of interface)\n count += 1\n interfaces.neighbor_ids[2, count] = c2e[neighbor_cell_id]\n interfaces.neighbor_ids[1, count] = element_id\n\n # Set orientation (x -> 1, y -> 2)\n interfaces.orientations[count] = div(direction, 2)\n end\n end\n\n @assert count == ninterfaces(interfaces) (\"Actual interface count ($count) does not match \" *\n \"expectations $(ninterfaces(interfaces))\")\nend\n\n\n# Initialize connectivity between elements and boundaries\nfunction init_boundary_connectivity!(elements, boundaries, mesh::TreeMesh2D)\n # Reset boundaries count\n count = 0\n\n # Initialize boundary counts\n counts_per_direction = MVector(0, 0, 0, 0)\n\n # OBS! Iterate over directions first, then over elements, and count boundaries in each direction\n # Rationale: This way the boundaries are internally sorted by the directions -x, +x, -y etc.,\n # obviating the need to store the boundary condition to be applied explicitly.\n # Loop over directions\n for direction in 1:n_directions(mesh.tree)\n # Iterate over all elements to find missing neighbors and to connect to boundaries\n for element_id in 1:nelements(elements)\n # Get cell id\n cell_id = elements.cell_ids[element_id]\n\n # If neighbor exists, current cell is not at a boundary\n if has_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # If coarse neighbor exists, current cell is not at a boundary\n if has_coarse_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # Create boundary\n count += 1\n counts_per_direction[direction] += 1\n\n # Set neighbor element id\n boundaries.neighbor_ids[count] = element_id\n\n # Set neighbor side, which denotes the direction (1 -> negative, 2 -> positive) of the element\n if direction in (2, 4)\n boundaries.neighbor_sides[count] = 1\n else\n boundaries.neighbor_sides[count] = 2\n end\n\n # Set orientation (x -> 1, y -> 2)\n if direction in (1, 2)\n boundaries.orientations[count] = 1\n else\n boundaries.orientations[count] = 2\n end\n\n # Store node coordinates\n enc = elements.node_coordinates\n if direction == 1 # -x direction\n boundaries.node_coordinates[:, :, count] .= enc[:, 1, :, element_id]\n elseif direction == 2 # +x direction\n boundaries.node_coordinates[:, :, count] .= enc[:, end, :, element_id]\n elseif direction == 3 # -y direction\n boundaries.node_coordinates[:, :, count] .= enc[:, :, 1, element_id]\n elseif direction == 4 # +y direction\n boundaries.node_coordinates[:, :, count] .= enc[:, :, end, element_id]\n else\n error(\"should not happen\")\n end\n end\n end\n\n @assert count == nboundaries(boundaries) (\"Actual boundaries count ($count) does not match \" *\n \"expectations $(nboundaries(boundaries))\")\n @assert sum(counts_per_direction) == count\n\n return SVector(counts_per_direction)\nend\n\n\n# Initialize connectivity between elements and mortars\nfunction init_mortar_connectivity!(elements, mortars, mesh::TreeMesh2D)\n # Construct cell -> element mapping for easier algorithm implementation\n tree = mesh.tree\n c2e = zeros(Int, length(tree))\n for element_id in 1:nelements(elements)\n c2e[elements.cell_ids[element_id]] = element_id\n end\n\n # Reset interface count\n count = 0\n\n # Iterate over all elements to find neighbors and to connect via interfaces\n for element_id in 1:nelements(elements)\n # Get cell id\n cell_id = elements.cell_ids[element_id]\n\n for direction in 1:n_directions(mesh.tree)\n # If no neighbor exists, cell is small with large neighbor -> do nothing\n if !has_neighbor(mesh.tree, cell_id, direction)\n continue\n end\n\n # If neighbor has no children, this is a conforming interface -> do nothing\n neighbor_cell_id = mesh.tree.neighbor_ids[direction, cell_id]\n if !has_children(mesh.tree, neighbor_cell_id)\n continue\n end\n\n # Create mortar between elements:\n # 1 -> small element in negative coordinate direction\n # 2 -> small element in positive coordinate direction\n # 3 -> large element\n count += 1\n mortars.neighbor_ids[3, count] = element_id\n if direction == 1\n mortars.neighbor_ids[1, count] = c2e[mesh.tree.child_ids[2, neighbor_cell_id]]\n mortars.neighbor_ids[2, count] = c2e[mesh.tree.child_ids[4, neighbor_cell_id]]\n elseif direction == 2\n mortars.neighbor_ids[1, count] = c2e[mesh.tree.child_ids[1, neighbor_cell_id]]\n mortars.neighbor_ids[2, count] = c2e[mesh.tree.child_ids[3, neighbor_cell_id]]\n elseif direction == 3\n mortars.neighbor_ids[1, count] = c2e[mesh.tree.child_ids[3, neighbor_cell_id]]\n mortars.neighbor_ids[2, count] = c2e[mesh.tree.child_ids[4, neighbor_cell_id]]\n elseif direction == 4\n mortars.neighbor_ids[1, count] = c2e[mesh.tree.child_ids[1, neighbor_cell_id]]\n mortars.neighbor_ids[2, count] = c2e[mesh.tree.child_ids[2, neighbor_cell_id]]\n else\n error(\"should not happen\")\n end\n\n # Set large side, which denotes the direction (1 -> negative, 2 -> positive) of the large side\n if direction in [2, 4]\n mortars.large_sides[count] = 1\n else\n mortars.large_sides[count] = 2\n end\n\n # Set orientation (x -> 1, y -> 2)\n if direction in [1, 2]\n mortars.orientations[count] = 1\n else\n mortars.orientations[count] = 2\n end\n end\n end\n\n @assert count == nmortars(mortars) (\"Actual mortar count ($count) does not match \" *\n \"expectations $(nmortars(mortars))\")\nend\n\n\nfunction init_boundary_conditions(n_boundaries_per_direction, mesh::TreeMesh2D)\n # \"eval is evil\"\n # This is a temporary hack until we have switched to a library based approach\n # with pure Julia code instead of parameter files.\n bcs = parameter(\"boundary_conditions\", [\"nothing\", \"nothing\", \"nothing\", \"nothing\"])\n if bcs isa AbstractArray\n boundary_conditions = eval_if_not_function.(bcs)\n else\n # This adds support for using a scalar boundary condition (like 'periodicity = \"false\"')\n boundary_conditions = eval_if_not_function.([bcs for _ in 1:n_directions(mesh.tree)])\n end\n\n # Sanity check about specifying boundary conditions\n for direction in 1:n_directions(mesh.tree)\n bc = boundary_conditions[direction]\n count = n_boundaries_per_direction[direction]\n if direction == 1\n dir = \"-x\"\n elseif direction == 2\n dir = \"+x\"\n elseif direction == 3\n dir = \"-y\"\n else\n dir = \"+y\"\n end\n\n # All directions with boundaries should have a boundary condition\n if count > 0 && isnothing(bc)\n error(\"Found $(count) boundaries in the $(dir)-direction, but corresponding boundary \" *\n \"condition is '$(get_name(bc))'\")\n end\n end\n\n return Tuple(boundary_conditions)\nend\n\n\n\"\"\"\n integrate(func, dg::Dg2D, args...; normalize=true)\n\nCall function `func` for each DG node and integrate the result over the computational domain.\n\nThe function `func` is called as `func(i, j, element_id, dg, args...)` for each\nvolume node `(i, j)` and each `element_id`. Additional positional\narguments `args...` are passed along as well. If `normalize` is true, the result\nis divided by the total volume of the computational domain.\n\n# Examples\nCalculate the integral of the time derivative of the entropy, i.e.,\n∫(∂S/∂t)dΩ = ∫(∂S/∂u ⋅ ∂u/∂t)dΩ:\n```julia\n# Calculate integral of entropy time derivative\ndsdu_ut = integrate(dg, dg.elements.u, dg.elements.u_t) do i, j, element_id, dg, u, u_t\n u_node = get_node_vars(u, dg, i, j, element_id)\n u_t_node = get_node_vars(u_t, dg, i, j, element_id)\n dot(cons2entropy(u_node, equations(dg)), u_t_node)\nend\n```\n\"\"\"\nintegrate(func, dg::Dg2D, args...; normalize=true) = integrate(func, dg, uses_mpi(dg), args...;\n normalize=normalize)\nfunction integrate(func, dg::Dg2D, uses_mpi::Val{false}, args...; normalize=true)\n # Initialize integral with zeros of the right shape\n integral = zero(func(1, 1, 1, dg, args...))\n\n # Use quadrature to numerically integrate over entire domain\n for element_id in 1:dg.n_elements\n jacobian_volume = inv(dg.elements.inverse_jacobian[element_id])^ndims(dg)\n for j in 1:nnodes(dg)\n for i in 1:nnodes(dg)\n integral += jacobian_volume * dg.weights[i] * dg.weights[j] * func(i, j, element_id, dg, args...)\n end\n end\n end\n\n # Normalize with total volume\n if normalize\n integral = integral/dg.analysis_total_volume\n end\n\n return integral\nend\n\n\n\"\"\"\n integrate(func, u, dg::Dg2D; normalize=true)\n integrate(u, dg::Dg2D; normalize=true)\n\nCall function `func` for each DG node and integrate the result over the computational domain.\n\nThe function `func` is called as `func(u_local)` for each volume node `(i, j)`\nand each `element_id`, where `u_local` is an `SVector`ized copy of\n`u[:, i, j, element_id]`. If `normalize` is true, the result is divided by the\ntotal volume of the computational domain. If `func` is omitted, it defaults to\n`identity`.\n\n# Examples\nCalculate the integral over all conservative variables:\n```julia\nstate_integrals = integrate(dg.elements.u, dg)\n```\n\"\"\"\nintegrate(func, u, dg::Dg2D; normalize=true) = integrate(func, u, dg, uses_mpi(dg);\n normalize=normalize)\nfunction integrate(func, u, dg::Dg2D, uses_mpi; normalize=true)\n func_wrapped = function(i, j, element_id, dg, u)\n u_local = get_node_vars(u, dg, i, j, element_id)\n return func(u_local)\n end\n return integrate(func_wrapped, dg, uses_mpi, u; normalize=normalize)\nend\nintegrate(u, dg::Dg2D; normalize=true) = integrate(identity, u, dg; normalize=normalize)\n\n\n# Calculate L2/Linf error norms based on \"exact solution\"\ncalc_error_norms(func, dg::Dg2D, t) = calc_error_norms(func, dg, t, uses_mpi(dg))\nfunction calc_error_norms(func, dg::Dg2D, t, uses_mpi::Val{false})\n # Gather necessary information\n equation = equations(dg)\n n_nodes_analysis = size(dg.analysis_vandermonde, 1)\n\n # pre-allocate buffers\n u = zeros(eltype(dg.elements.u),\n nvariables(dg), size(dg.analysis_vandermonde, 1), size(dg.analysis_vandermonde, 1))\n u_tmp1 = similar(u,\n nvariables(dg), size(dg.analysis_vandermonde, 1), size(dg.analysis_vandermonde, 2))\n x = zeros(eltype(dg.elements.node_coordinates),\n 2, size(dg.analysis_vandermonde, 1), size(dg.analysis_vandermonde, 1))\n x_tmp1 = similar(x,\n 2, size(dg.analysis_vandermonde, 1), size(dg.analysis_vandermonde, 2))\n\n # Set up data structures\n l2_error = zero(func(get_node_vars(dg.elements.u, dg, 1, 1, 1), equation))\n linf_error = zero(func(get_node_vars(dg.elements.u, dg, 1, 1, 1), equation))\n\n # Iterate over all elements for error calculations\n for element_id in 1:dg.n_elements\n # Interpolate solution and node locations to analysis nodes\n multiply_dimensionwise!(u, dg.analysis_vandermonde, view(dg.elements.u, :, :, :, element_id), u_tmp1)\n multiply_dimensionwise!(x, dg.analysis_vandermonde, view(dg.elements.node_coordinates, :, :, :, element_id), x_tmp1)\n\n # Calculate errors at each analysis node\n weights = dg.analysis_weights_volume\n jacobian_volume = inv(dg.elements.inverse_jacobian[element_id])^ndims(dg)\n for j in 1:n_nodes_analysis, i in 1:n_nodes_analysis\n u_exact = dg.initial_conditions(get_node_coords(x, dg, i, j), t, equation)\n diff = func(u_exact, equation) - func(get_node_vars(u, dg, i, j), equation)\n l2_error += diff.^2 * (weights[i] * weights[j] * jacobian_volume)\n linf_error = @. max(linf_error, abs(diff))\n end\n end\n\n # For L2 error, divide by total volume\n l2_error = @. sqrt(l2_error / dg.analysis_total_volume)\n\n return l2_error, linf_error\nend\n\n\n# Integrate ∂S/∂u ⋅ ∂u/∂t over the entire domain\ncalc_entropy_timederivative(dg::Dg2D, t) = calc_entropy_timederivative(dg, t, uses_mpi(dg))\nfunction calc_entropy_timederivative(dg::Dg2D, t, uses_mpi)\n # Compute ut = rhs(u) with current solution u\n @notimeit timer() rhs!(dg, t)\n\n # Calculate ∫(∂S/∂u ⋅ ∂u/∂t)dΩ\n dsdu_ut = integrate(dg, uses_mpi, dg.elements.u, dg.elements.u_t) do i, j, element_id, dg, u, u_t\n u_node = get_node_vars(u, dg, i, j, element_id)\n u_t_node = get_node_vars(u_t, dg, i, j, element_id)\n dot(cons2entropy(u_node, equations(dg)), u_t_node)\n end\n\n return dsdu_ut\nend\n\n\n# Calculate L2/Linf norms of a solenoidal condition ∇ ⋅ B = 0\n# OBS! This works only when the problem setup is designed such that ∂B₁/∂x + ∂B₂/∂y = 0. Cannot\n# compute the full 3D divergence from the given data\ncalc_mhd_solenoid_condition(dg::Dg2D, t) = calc_mhd_solenoid_condition(dg, t, mpi_parallel())\nfunction calc_mhd_solenoid_condition(dg::Dg2D, t, mpi_parallel::Val{false})\n @assert equations(dg) isa IdealGlmMhdEquations2D \"Only relevant for MHD\"\n\n # Local copy of standard derivative matrix\n d = polynomial_derivative_matrix(dg.nodes)\n # Quadrature weights\n weights = dg.weights\n # integrate over all elements to get the divergence-free condition errors\n linf_divb = 0.0\n l2_divb = 0.0\n for element_id in 1:dg.n_elements\n jacobian_volume = (1.0/dg.elements.inverse_jacobian[element_id])^ndims(dg)\n for j in 1:nnodes(dg)\n for i in 1:nnodes(dg)\n divb = 0.0\n for k in 1:nnodes(dg)\n divb += d[i,k]*dg.elements.u[6,k,j,element_id] + d[j,k]*dg.elements.u[7,i,k,element_id]\n end\n divb *= dg.elements.inverse_jacobian[element_id]\n linf_divb = max(linf_divb,abs(divb))\n l2_divb += jacobian_volume*weights[i]*weights[j]*divb^2\n end\n end\n end\n l2_divb = sqrt(l2_divb/dg.analysis_total_volume)\n\n return l2_divb, linf_divb\nend\n\n\n\n\"\"\"\n analyze_solution(dg::Dg2D, mesh::TreeMesh, time, dt, step, runtime_absolute, runtime_relative)\n\nCalculate error norms and other analysis quantities to analyze the solution\nduring a simulation, and return the L2 and Linf errors. `dg` and `mesh` are the\nDG and the mesh instance, respectively. `time`, `dt`, and `step` refer to the\ncurrent simulation time, the last time step size, and the current time step\ncount. The run time (in seconds) is given in `runtime_absolute`, while the\nperformance index is specified in `runtime_relative`.\n\n**Note:** Keep order of analysis quantities in sync with\n [`save_analysis_header`](@ref) when adding or changing quantities.\n\"\"\"\nfunction analyze_solution(dg::Dg2D, mesh::TreeMesh, time, dt, step,\n runtime_absolute, runtime_relative; solver_gravity=nothing)\n analyze_solution(dg, mesh, time, dt, step, runtime_absolute, runtime_relative, uses_mpi(dg),\n solver_gravity=solver_gravity)\nend\nfunction analyze_solution(dg::Dg2D, mesh::TreeMesh, time, dt, step, runtime_absolute,\n runtime_relative, uses_mpi::Val{false}; solver_gravity=nothing)\n equation = equations(dg)\n\n # General information\n println()\n println(\"-\"^80)\n println(\" Simulation running '\", get_name(equation), \"' with POLYDEG = \", polydeg(dg))\n println(\"-\"^80)\n println(\" #timesteps: \" * @sprintf(\"% 14d\", step) *\n \" \" *\n \" run time: \" * @sprintf(\"%10.8e s\", runtime_absolute))\n println(\" dt: \" * @sprintf(\"%10.8e\", dt) *\n \" \" *\n \" Time/DOF/step: \" * @sprintf(\"%10.8e s\", runtime_relative))\n println(\" sim. time: \" * @sprintf(\"%10.8e\", time))\n\n # Level information (only show for AMR)\n if parameter(\"amr_interval\", 0)::Int > 0\n levels = Vector{Int}(undef, dg.n_elements)\n for element_id in 1:dg.n_elements\n levels[element_id] = mesh.tree.levels[dg.elements.cell_ids[element_id]]\n end\n min_level = minimum(levels)\n max_level = maximum(levels)\n\n println(\" #elements: \" * @sprintf(\"% 14d\", dg.n_elements))\n for level = max_level:-1:min_level+1\n println(\" ├── level $level: \" * @sprintf(\"% 14d\", count(x->x==level, levels)))\n end\n println(\" └── level $min_level: \" * @sprintf(\"% 14d\", count(x->x==min_level, levels)))\n end\n println()\n\n # Open file for appending and store time step and time information\n if dg.save_analysis\n f = open(dg.analysis_filename, \"a\")\n @printf(f, \"% 9d\", step)\n @printf(f, \" %10.8e\", time)\n @printf(f, \" %10.8e\", dt)\n end\n\n # Calculate and print derived quantities (error norms, entropy etc.)\n # Variable names required for L2 error, Linf error, and conservation error\n if any(q in dg.analysis_quantities for q in\n (:l2_error, :linf_error, :conservation_error, :residual))\n print(\" Variable: \")\n for v in 1:nvariables(equation)\n @printf(\" %-14s\", varnames_cons(equation)[v])\n end\n println()\n end\n\n # Calculate L2/Linf errors, which are also returned by analyze_solution\n l2_error, linf_error = calc_error_norms(dg, time)\n\n # L2 error\n if :l2_error in dg.analysis_quantities\n print(\" L2 error: \")\n for v in 1:nvariables(equation)\n @printf(\" % 10.8e\", l2_error[v])\n dg.save_analysis && @printf(f, \" % 10.8e\", l2_error[v])\n end\n println()\n end\n\n # Linf error\n if :linf_error in dg.analysis_quantities\n print(\" Linf error: \")\n for v in 1:nvariables(equation)\n @printf(\" % 10.8e\", linf_error[v])\n dg.save_analysis && @printf(f, \" % 10.8e\", linf_error[v])\n end\n println()\n end\n\n # Conservation errror\n if :conservation_error in dg.analysis_quantities\n # Calculate state integrals\n state_integrals = integrate(dg.elements.u, dg)\n\n # Store initial state integrals at first invocation\n if isempty(dg.initial_state_integrals)\n dg.initial_state_integrals = zeros(nvariables(equation))\n dg.initial_state_integrals .= state_integrals\n end\n\n print(\" |∑U - ∑U₀|: \")\n for v in 1:nvariables(equation)\n err = abs(state_integrals[v] - dg.initial_state_integrals[v])\n @printf(\" % 10.8e\", err)\n dg.save_analysis && @printf(f, \" % 10.8e\", err)\n end\n println()\n end\n\n # Residual (defined here as the vector maximum of the absolute values of the time derivatives)\n if :residual in dg.analysis_quantities\n print(\" max(|Uₜ|): \")\n for v in 1:nvariables(equation)\n # Calculate maximum absolute value of Uₜ\n @views res = maximum(abs, view(dg.elements.u_t, v, :, :, :))\n @printf(\" % 10.8e\", res)\n dg.save_analysis && @printf(f, \" % 10.8e\", res)\n end\n println()\n end\n\n # L2/L∞ errors of the primitive variables\n if :l2_error_primitive in dg.analysis_quantities || :linf_error_primitive in dg.analysis_quantities\n l2_error_prim, linf_error_prim = calc_error_norms(cons2prim, dg, time)\n\n print(\" Variable: \")\n for v in 1:nvariables(equation)\n @printf(\" %-14s\", varnames_prim(equation)[v])\n end\n println()\n\n # L2 error\n if :l2_error_primitive in dg.analysis_quantities\n print(\" L2 error prim.: \")\n for v in 1:nvariables(equation)\n @printf(\"%10.8e \", l2_error_prim[v])\n dg.save_analysis && @printf(f, \" % 10.8e\", l2_error_prim[v])\n end\n println()\n end\n\n # L∞ error\n if :linf_error_primitive in dg.analysis_quantities\n print(\" Linf error pri.:\")\n for v in 1:nvariables(equation)\n @printf(\"%10.8e \", linf_error_prim[v])\n dg.save_analysis && @printf(f, \" % 10.8e\", linf_error_prim[v])\n end\n println()\n end\n end\n\n # Entropy time derivative\n if :dsdu_ut in dg.analysis_quantities\n dsdu_ut = calc_entropy_timederivative(dg, time)\n print(\" ∑∂S/∂U ⋅ Uₜ: \")\n @printf(\" % 10.8e\", dsdu_ut)\n dg.save_analysis && @printf(f, \" % 10.8e\", dsdu_ut)\n println()\n end\n\n # Entropy\n if :entropy in dg.analysis_quantities\n s = integrate(dg, dg.elements.u) do i, j, element_id, dg, u\n cons = get_node_vars(u, dg, i, j, element_id)\n return entropy(cons, equations(dg))\n end\n print(\" ∑S: \")\n @printf(\" % 10.8e\", s)\n dg.save_analysis && @printf(f, \" % 10.8e\", s)\n println()\n end\n\n # Total energy\n if :energy_total in dg.analysis_quantities\n e_total = integrate(dg, dg.elements.u) do i, j, element_id, dg, u\n cons = get_node_vars(u, dg, i, j, element_id)\n return energy_total(cons, equations(dg))\n end\n print(\" ∑e_total: \")\n @printf(\" % 10.8e\", e_total)\n dg.save_analysis && @printf(f, \" % 10.8e\", e_total)\n println()\n end\n\n # Kinetic energy\n if :energy_kinetic in dg.analysis_quantities\n e_kinetic = integrate(dg, dg.elements.u) do i, j, element_id, dg, u\n cons = get_node_vars(u, dg, i, j, element_id)\n return energy_kinetic(cons, equations(dg))\n end\n print(\" ∑e_kinetic: \")\n @printf(\" % 10.8e\", e_kinetic)\n dg.save_analysis && @printf(f, \" % 10.8e\", e_kinetic)\n println()\n end\n\n # Internal energy\n if :energy_internal in dg.analysis_quantities\n e_internal = integrate(dg, dg.elements.u) do i, j, element_id, dg, u\n cons = get_node_vars(u, dg, i, j, element_id)\n return energy_internal(cons, equations(dg))\n end\n print(\" ∑e_internal: \")\n @printf(\" % 10.8e\", e_internal)\n dg.save_analysis && @printf(f, \" % 10.8e\", e_internal)\n println()\n end\n\n # Magnetic energy\n if :energy_magnetic in dg.analysis_quantities\n e_magnetic = integrate(dg, dg.elements.u) do i, j, element_id, dg, u\n cons = get_node_vars(u, dg, i, j, element_id)\n return energy_magnetic(cons, equations(dg))\n end\n print(\" ∑e_magnetic: \")\n @printf(\" % 10.8e\", e_magnetic)\n dg.save_analysis && @printf(f, \" % 10.8e\", e_magnetic)\n println()\n end\n\n # Potential energy\n if :energy_potential in dg.analysis_quantities\n # FIXME: This should be implemented properly for multiple coupled solvers\n @assert !isnothing(solver_gravity) \"Only works if gravity solver is supplied\"\n @assert dg.initial_conditions == initial_conditions_jeans_instability \"Only works with Jeans instability setup\"\n\n e_potential = integrate(dg, dg.elements.u, solver_gravity.elements.u) do i, j, element_id, dg, u_euler, u_gravity\n cons_euler = get_node_vars(u_euler, dg, i, j, element_id)\n cons_gravity = get_node_vars(u_gravity, solver_gravity, i, j, element_id)\n # OBS! subtraction is specific to Jeans instability test where rho_0 = 1.5e7\n return (cons_euler[1] - 1.5e7) * cons_gravity[1]\n end\n print(\" ∑e_pot: \")\n @printf(\" % 10.8e\", e_potential)\n dg.save_analysis && @printf(f, \" % 10.8e\", e_potential)\n println()\n end\n\n # Solenoidal condition ∇ ⋅ B = 0\n if :l2_divb in dg.analysis_quantities || :linf_divb in dg.analysis_quantities\n l2_divb, linf_divb = calc_mhd_solenoid_condition(dg, time)\n end\n # L2 norm of ∇ ⋅ B\n if :l2_divb in dg.analysis_quantities\n print(\" L2 ∇ ⋅B: \")\n @printf(\" % 10.8e\", l2_divb)\n dg.save_analysis && @printf(f, \" % 10.8e\", l2_divb)\n println()\n end\n # Linf norm of ∇ ⋅ B\n if :linf_divb in dg.analysis_quantities\n print(\" Linf ∇ ⋅B: \")\n @printf(\" % 10.8e\", linf_divb)\n dg.save_analysis && @printf(f, \" % 10.8e\", linf_divb)\n println()\n end\n\n # Cross helicity\n if :cross_helicity in dg.analysis_quantities\n h_c = integrate(dg, dg.elements.u) do i, j, element_id, dg, u\n cons = get_node_vars(u, dg, i, j, element_id)\n return cross_helicity(cons, equations(dg))\n end\n print(\" ∑H_c: \")\n @printf(\" % 10.8e\", h_c)\n dg.save_analysis && @printf(f, \" % 10.8e\", h_c)\n println()\n end\n\n println(\"-\"^80)\n println()\n\n # Add line break and close analysis file if it was opened\n if dg.save_analysis\n println(f)\n close(f)\n end\n\n # Return errors for EOC analysis\n return l2_error, linf_error\nend\n\n\n\"\"\"\n save_analysis_header(filename, quantities, equation)\n\nTruncate file `filename` and save a header with the names of the quantities\n`quantities` that will subsequently written to `filename` by\n[`analyze_solution`](@ref). Since some quantities are equation-specific, the\nsystem of equations instance is passed in `equation`.\n\n**Note:** Keep order of analysis quantities in sync with\n [`analyze_solution`](@ref) when adding or changing quantities.\n\"\"\"\nfunction save_analysis_header(filename, quantities, equation::AbstractEquation{2})\n open(filename, \"w\") do f\n @printf(f, \"#%-8s\", \"timestep\")\n @printf(f, \" %-14s\", \"time\")\n @printf(f, \" %-14s\", \"dt\")\n if :l2_error in quantities\n for v in varnames_cons(equation)\n @printf(f, \" %-14s\", \"l2_\" * v)\n end\n end\n if :linf_error in quantities\n for v in varnames_cons(equation)\n @printf(f, \" %-14s\", \"linf_\" * v)\n end\n end\n if :conservation_error in quantities\n for v in varnames_cons(equation)\n @printf(f, \" %-14s\", \"cons_\" * v)\n end\n end\n if :residual in quantities\n for v in varnames_cons(equation)\n @printf(f, \" %-14s\", \"res_\" * v)\n end\n end\n if :l2_error_primitive in quantities\n for v in varnames_prim(equation)\n @printf(f, \" %-14s\", \"l2_\" * v)\n end\n end\n if :linf_error_primitive in quantities\n for v in varnames_prim(equation)\n @printf(f, \" %-14s\", \"linf_\" * v)\n end\n end\n if :dsdu_ut in quantities\n @printf(f, \" %-14s\", \"dsdu_ut\")\n end\n if :entropy in quantities\n @printf(f, \" %-14s\", \"entropy\")\n end\n if :energy_total in quantities\n @printf(f, \" %-14s\", \"e_total\")\n end\n if :energy_kinetic in quantities\n @printf(f, \" %-14s\", \"e_kinetic\")\n end\n if :energy_internal in quantities\n @printf(f, \" %-14s\", \"e_internal\")\n end\n if :energy_magnetic in quantities\n @printf(f, \" %-14s\", \"e_magnetic\")\n end\n if :energy_potential in quantities\n @printf(f, \" %-14s\", \"e_potential\")\n end\n if :l2_divb in quantities\n @printf(f, \" %-14s\", \"l2_divb\")\n end\n if :linf_divb in quantities\n @printf(f, \" %-14s\", \"linf_divb\")\n end\n if :cross_helicity in quantities\n @printf(f, \" %-14s\", \"cross_helicity\")\n end\n println(f)\n end\nend\n\n\n# Call equation-specific initial conditions functions and apply to all elements\nfunction set_initial_conditions!(dg::Dg2D, time)\n equation = equations(dg)\n # make sure that the random number generator is reseted and the ICs are reproducible in the julia REPL/interactive mode\n seed!(0)\n for element_id in 1:dg.n_elements\n for j in 1:nnodes(dg)\n for i in 1:nnodes(dg)\n dg.elements.u[:, i, j, element_id] .= dg.initial_conditions(\n dg.elements.node_coordinates[:, i, j, element_id], time, equation)\n end\n end\n end\nend\n\n\n# Calculate time derivative\n@inline rhs!(dg::Dg2D, t_stage) = rhs!(dg, t_stage, uses_mpi(dg))\nfunction rhs!(dg::Dg2D, t_stage, uses_mpi::Val{false})\n # Reset u_t\n @timeit timer() \"reset ∂u/∂t\" dg.elements.u_t .= 0\n\n # Calculate volume integral\n @timeit timer() \"volume integral\" calc_volume_integral!(dg)\n\n # Prolong solution to interfaces\n @timeit timer() \"prolong2interfaces\" prolong2interfaces!(dg)\n\n # Calculate interface fluxes\n @timeit timer() \"interface flux\" calc_interface_flux!(dg)\n\n # Prolong solution to boundaries\n @timeit timer() \"prolong2boundaries\" prolong2boundaries!(dg)\n\n # Calculate boundary fluxes\n @timeit timer() \"boundary flux\" calc_boundary_flux!(dg, t_stage)\n\n # Prolong solution to mortars\n @timeit timer() \"prolong2mortars\" prolong2mortars!(dg)\n\n # Calculate mortar fluxes\n @timeit timer() \"mortar flux\" calc_mortar_flux!(dg)\n\n # Calculate surface integrals\n @timeit timer() \"surface integral\" calc_surface_integral!(dg)\n\n # Apply Jacobian from mapping to reference element\n @timeit timer() \"Jacobian\" apply_jacobian!(dg)\n\n # Calculate source terms\n @timeit timer() \"source terms\" calc_sources!(dg, dg.source_terms, t_stage)\nend\n\n# TODO: implement 2D!!!\n# Apply positivity limiter of Zhang and Shu to nodal values elements.u\nfunction apply_positivity_preserving_limiter!(dg::Dg2D)\nend\n\n# Calculate volume integral and update u_t\ncalc_volume_integral!(dg::Dg2D) = calc_volume_integral!(dg.elements.u_t, dg.volume_integral_type, dg)\n\n\n# Calculate 2D twopoint flux (element version)\n@inline function calcflux_twopoint!(f1, f2, u, element_id, dg::Dg2D)\n @unpack volume_flux_function = dg\n\n for j in 1:nnodes(dg)\n for i in 1:nnodes(dg)\n # Set diagonal entries (= regular volume fluxes due to consistency)\n u_node = get_node_vars(u, dg, i, j, element_id)\n flux1 = calcflux(u_node, 1, equations(dg))\n flux2 = calcflux(u_node, 2, equations(dg))\n set_node_vars!(f1, flux1, dg, i, i, j)\n set_node_vars!(f2, flux2, dg, j, i, j)\n\n # Flux in x-direction\n for l in (i+1):nnodes(dg)\n u_ll = get_node_vars(u, dg, i, j, element_id)\n u_rr = get_node_vars(u, dg, l, j, element_id)\n flux = volume_flux_function(u_ll, u_rr, 1, equations(dg)) # 1-> x-direction\n for v in 1:nvariables(dg)\n f1[v, i, l, j] = f1[v, l, i, j] = flux[v]\n end\n end\n\n # Flux in y-direction\n for l in (j+1):nnodes(dg)\n u_ll = get_node_vars(u, dg, i, j, element_id)\n u_rr = get_node_vars(u, dg, i, l, element_id)\n flux = volume_flux_function(u_ll, u_rr, 2, equations(dg)) # 2 -> y-direction\n for v in 1:nvariables(dg)\n f2[v, j, i, l] = f2[v, l, i, j] = flux[v]\n end\n end\n end\n end\n\n calcflux_twopoint_nonconservative!(f1, f2, u, element_id, have_nonconservative_terms(equations(dg)), dg)\nend\n\nfunction calcflux_twopoint_nonconservative!(f1, f2, u, element_id, nonconservative_terms::Val{false}, dg::Dg2D)\n return nothing\nend\n\nfunction calcflux_twopoint_nonconservative!(f1, f2, u, element_id, nonconservative_terms::Val{true}, dg::Dg2D)\n #TODO: Create a unified interface, e.g. using non-symmetric two-point (extended) volume fluxes\n # For now, just dispatch to an existing function for the IdealMhdEquations\n calcflux_twopoint_nonconservative!(f1, f2, u, element_id, equations(dg), dg)\nend\n\n\n# Calculate volume integral (DGSEM in weak form)\nfunction calc_volume_integral!(u_t, ::Val{:weak_form}, dg::Dg2D)\n @unpack dhat = dg\n\n Threads.@threads for element_id in 1:dg.n_elements\n # Calculate volume integral\n for j in 1:nnodes(dg)\n for i in 1:nnodes(dg)\n u_node = get_node_vars(dg.elements.u, dg, i, j, element_id)\n\n flux1 = calcflux(u_node, 1, equations(dg))\n for l in 1:nnodes(dg)\n integral_contribution = dhat[l, i] * flux1\n add_to_node_vars!(u_t, integral_contribution, dg, l, j, element_id)\n end\n\n flux2 = calcflux(u_node, 2, equations(dg))\n for l in 1:nnodes(dg)\n integral_contribution = dhat[l, j] * flux2\n add_to_node_vars!(u_t, integral_contribution, dg, i, l, element_id)\n end\n end\n end\n end\nend\n\n\n# Calculate volume integral (DGSEM in split form)\n@inline function calc_volume_integral!(u_t, volume_integral_type::Val{:split_form}, dg::Dg2D)\n calc_volume_integral!(u_t, volume_integral_type, have_nonconservative_terms(equations(dg)), dg.thread_cache, dg)\nend\n\n\nfunction calc_volume_integral!(u_t, ::Val{:split_form}, nonconservative_terms, cache, dg::Dg2D)\n Threads.@threads for element_id in 1:dg.n_elements\n split_form_kernel!(u_t, element_id, nonconservative_terms, cache, dg)\n end\nend\n\n@inline function split_form_kernel!(u_t, element_id, nonconservative_terms::Val{false}, cache, dg::Dg2D, alpha=true)\n # true * [some floating point value] == [exactly the same floating point value]\n # This can get optimized away due to constant propagation.\n @unpack volume_flux_function, dsplit = dg\n\n # Calculate volume integral in one element\n for j in 1:nnodes(dg), i in 1:nnodes(dg)\n u_node = get_node_vars(dg.elements.u, dg, i, j, element_id)\n\n # x direction\n # use consistency of the volume flux to make this evaluation cheaper\n flux = calcflux(u_node, 1, equations(dg))\n integral_contribution = alpha * dsplit[i, i] * flux\n add_to_node_vars!(u_t, integral_contribution, dg, i, j, element_id)\n # use symmetry of the volume flux for the remaining terms\n for ii in (i+1):nnodes(dg)\n u_node_ii = get_node_vars(dg.elements.u, dg, ii, j, element_id)\n flux = volume_flux_function(u_node, u_node_ii, 1, equations(dg))\n integral_contribution = alpha * dsplit[i, ii] * flux\n add_to_node_vars!(u_t, integral_contribution, dg, i, j, element_id)\n integral_contribution = alpha * dsplit[ii, i] * flux\n add_to_node_vars!(u_t, integral_contribution, dg, ii, j, element_id)\n end\n\n # y direction\n # use consistency of the volume flux to make this evaluation cheaper\n flux = calcflux(u_node, 2, equations(dg))\n integral_contribution = alpha * dsplit[j, j] * flux\n add_to_node_vars!(u_t, integral_contribution, dg, i, j, element_id)\n # use symmetry of the volume flux for the remaining terms\n for jj in (j+1):nnodes(dg)\n u_node_jj = get_node_vars(dg.elements.u, dg, i, jj, element_id)\n flux = volume_flux_function(u_node, u_node_jj, 2, equations(dg))\n integral_contribution = alpha * dsplit[j, jj] * flux\n add_to_node_vars!(u_t, integral_contribution, dg, i, j, element_id)\n integral_contribution = alpha * dsplit[jj, j] * flux\n add_to_node_vars!(u_t, integral_contribution, dg, i, jj, element_id)\n end\n end\nend\n\n@inline function split_form_kernel!(u_t, element_id, nonconservative_terms::Val{true}, thread_cache, dg::Dg2D, alpha=true)\n @unpack volume_flux_function, dsplit_transposed = dg\n @unpack f1_threaded, f2_threaded = thread_cache\n\n # Choose thread-specific pre-allocated container\n f1 = f1_threaded[Threads.threadid()]\n f2 = f2_threaded[Threads.threadid()]\n\n # Calculate volume fluxes (one more dimension than weak form)\n calcflux_twopoint!(f1, f2, dg.elements.u, element_id, dg)\n\n # Calculate volume integral in one element\n for j in 1:nnodes(dg), i in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n # Use local accumulator to improve performance\n acc = zero(eltype(u_t))\n for l in 1:nnodes(dg)\n acc += dsplit_transposed[l, i] * f1[v, l, i, j] + dsplit_transposed[l, j] * f2[v, l, i, j]\n end\n u_t[v, i, j, element_id] += alpha * acc\n end\n end\nend\n\n\n# Calculate volume integral (DGSEM in split form with shock capturing)\nfunction calc_volume_integral!(u_t, ::Val{:shock_capturing}, dg::Dg2D)\n # (Re-)initialize element variable storage for blending factor\n if (!haskey(dg.element_variables, :blending_factor) ||\n length(dg.element_variables[:blending_factor]) != dg.n_elements)\n dg.element_variables[:blending_factor] = Vector{Float64}(undef, dg.n_elements)\n end\n if (!haskey(dg.element_variables, :blending_factor_tmp) ||\n length(dg.element_variables[:blending_factor_tmp]) != dg.n_elements)\n dg.element_variables[:blending_factor_tmp] = Vector{Float64}(undef, dg.n_elements)\n end\n\n # Initialize element variable storage for the cache\n if (!haskey(dg.cache, :element_ids_dg))\n dg.cache[:element_ids_dg] = Int[]\n sizehint!(dg.cache[:element_ids_dg], dg.n_elements)\n end\n if (!haskey(dg.cache, :element_ids_dgfv))\n dg.cache[:element_ids_dgfv] = Int[]\n sizehint!(dg.cache[:element_ids_dgfv], dg.n_elements)\n end\n\n calc_volume_integral!(u_t, Val(:shock_capturing),\n dg.element_variables[:blending_factor], dg.element_variables[:blending_factor_tmp],\n dg.cache[:element_ids_dg], dg.cache[:element_ids_dgfv],\n dg.thread_cache,\n dg)\nend\n\nfunction calc_volume_integral!(u_t, ::Val{:shock_capturing}, alpha, alpha_tmp,\n element_ids_dg, element_ids_dgfv, thread_cache, dg::Dg2D)\n @unpack dsplit_transposed, inverse_weights = dg\n @unpack fstar1_threaded, fstar2_threaded = thread_cache\n\n # Calculate blending factors α: u = u_DG * (1 - α) + u_FV * α\n @timeit timer() \"blending factors\" calc_blending_factors!(alpha, alpha_tmp, dg.elements.u,\n dg.shock_alpha_max,\n dg.shock_alpha_min,\n dg.shock_alpha_smooth,\n dg.shock_indicator_variable, thread_cache, dg)\n\n # Determine element ids for DG-only and blended DG-FV volume integral\n pure_and_blended_element_ids!(element_ids_dg, element_ids_dgfv, alpha, dg)\n\n # Loop over pure DG elements\n @timeit timer() \"pure DG\" Threads.@threads for element_id in element_ids_dg\n split_form_kernel!(u_t, element_id, have_nonconservative_terms(equations(dg)), thread_cache, dg)\n end\n\n # Loop over blended DG-FV elements\n @timeit timer() \"blended DG-FV\" Threads.@threads for element_id in element_ids_dgfv\n # Calculate DG volume integral contribution\n split_form_kernel!(u_t, element_id, have_nonconservative_terms(equations(dg)), thread_cache, dg, 1 - alpha[element_id])\n\n # Calculate FV two-point fluxes\n fstar1 = fstar1_threaded[Threads.threadid()]\n fstar2 = fstar2_threaded[Threads.threadid()]\n calcflux_fv!(fstar1, fstar2, dg.elements.u, element_id, dg)\n\n # Calculate FV volume integral contribution\n for j in 1:nnodes(dg), i in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n u_t[v, i, j, element_id] += ( alpha[element_id] *\n (inverse_weights[i] * (fstar1[v, i+1, j] - fstar1[v, i, j]) +\n inverse_weights[j] * (fstar2[v, i, j+1] - fstar2[v, i, j])) )\n\n end\n end\n end\nend\n\n\n\"\"\"\n calcflux_fv!(fstar1, fstar2, u_leftright, u, element_id, dg::Dg2D)\n\nCalculate the finite volume fluxes inside the elements.\n\n# Arguments\n- `fstar1::AbstractArray{T} where T<:Real`:\n- `fstar2::AbstractArray{T} where T<:Real`\n- `dg::Dg2D`\n- `u::AbstractArray{T} where T<:Real`\n- `element_id::Integer`\n\"\"\"\n@inline function calcflux_fv!(fstar1, fstar2, u, element_id, dg::Dg2D)\n @unpack surface_flux_function = dg\n\n fstar1[:, 1, :] .= zero(eltype(fstar1))\n fstar1[:, nnodes(dg)+1, :] .= zero(eltype(fstar1))\n\n for j in 1:nnodes(dg)\n for i in 2:nnodes(dg)\n u_ll = get_node_vars(u, dg, i-1, j, element_id)\n u_rr = get_node_vars(u, dg, i, j, element_id)\n flux = surface_flux_function(u_ll, u_rr, 1, equations(dg)) # orientation 1: x direction\n set_node_vars!(fstar1, flux, dg, i, j)\n end\n end\n\n fstar2[:, :, 1 ] .= zero(eltype(fstar2))\n fstar2[:, :, nnodes(dg)+1] .= zero(eltype(fstar2))\n\n for j in 2:nnodes(dg)\n for i in 1:nnodes(dg)\n u_ll = get_node_vars(u, dg, i, j-1, element_id)\n u_rr = get_node_vars(u, dg, i, j, element_id)\n flux = surface_flux_function(u_ll, u_rr, 2, equations(dg)) # orientation 2: y direction\n set_node_vars!(fstar2, flux, dg, i, j)\n end\n end\nend\n\n\n# Prolong solution to interfaces (for GL nodes: just a copy)\nfunction prolong2interfaces!(dg::Dg2D)\n equation = equations(dg)\n\n Threads.@threads for s in 1:dg.n_interfaces\n left_element_id = dg.interfaces.neighbor_ids[1, s]\n right_element_id = dg.interfaces.neighbor_ids[2, s]\n if dg.interfaces.orientations[s] == 1\n # interface in x-direction\n for j in 1:nnodes(dg), v in 1:nvariables(dg)\n dg.interfaces.u[1, v, j, s] = dg.elements.u[v, nnodes(dg), j, left_element_id]\n dg.interfaces.u[2, v, j, s] = dg.elements.u[v, 1, j, right_element_id]\n end\n else\n # interface in y-direction\n for i in 1:nnodes(dg), v in 1:nvariables(dg)\n dg.interfaces.u[1, v, i, s] = dg.elements.u[v, i, nnodes(dg), left_element_id]\n dg.interfaces.u[2, v, i, s] = dg.elements.u[v, i, 1, right_element_id]\n end\n end\n end\nend\n\n\n# Prolong solution to boundaries (for GL nodes: just a copy)\nfunction prolong2boundaries!(dg::Dg2D)\n equation = equations(dg)\n\n for b in 1:dg.n_boundaries\n element_id = dg.boundaries.neighbor_ids[b]\n if dg.boundaries.orientations[b] == 1 # Boundary in x-direction\n if dg.boundaries.neighbor_sides[b] == 1 # Element in -x direction of boundary\n for l in 1:nnodes(dg), v in 1:nvariables(dg)\n dg.boundaries.u[1, v, l, b] = dg.elements.u[v, nnodes(dg), l, element_id]\n end\n else # Element in +x direction of boundary\n for l in 1:nnodes(dg), v in 1:nvariables(dg)\n dg.boundaries.u[2, v, l, b] = dg.elements.u[v, 1, l, element_id]\n end\n end\n else # Boundary in y-direction\n if dg.boundaries.neighbor_sides[b] == 1 # Element in -y direction of boundary\n for l in 1:nnodes(dg), v in 1:nvariables(dg)\n dg.boundaries.u[1, v, l, b] = dg.elements.u[v, l, nnodes(dg), element_id]\n end\n else # Element in +y direction of boundary\n for l in 1:nnodes(dg), v in 1:nvariables(dg)\n dg.boundaries.u[2, v, l, b] = dg.elements.u[v, l, 1, element_id]\n end\n end\n end\n end\nend\n\n\n# Prolong solution to mortars (select correct method based on mortar type)\nprolong2mortars!(dg::Dg2D) = prolong2mortars!(dg, dg.mortar_type)\n\n# Prolong solution to mortars (l2mortar version)\nfunction prolong2mortars!(dg::Dg2D, mortar_type::Val{:l2})\n Threads.@threads for m in 1:dg.n_l2mortars\n\n large_element_id = dg.l2mortars.neighbor_ids[3, m]\n upper_element_id = dg.l2mortars.neighbor_ids[2, m]\n lower_element_id = dg.l2mortars.neighbor_ids[1, m]\n\n # Copy solution small to small\n if dg.l2mortars.large_sides[m] == 1 # -> small elements on right side\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.l2mortars.u_upper[2, v, l, m] = dg.elements.u[v, 1, l, upper_element_id]\n dg.l2mortars.u_lower[2, v, l, m] = dg.elements.u[v, 1, l, lower_element_id]\n end\n end\n else\n # L2 mortars in y-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.l2mortars.u_upper[2, v, l, m] = dg.elements.u[v, l, 1, upper_element_id]\n dg.l2mortars.u_lower[2, v, l, m] = dg.elements.u[v, l, 1, lower_element_id]\n end\n end\n end\n else # large_sides[m] == 2 -> small elements on left side\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.l2mortars.u_upper[1, v, l, m] = dg.elements.u[v, nnodes(dg), l, upper_element_id]\n dg.l2mortars.u_lower[1, v, l, m] = dg.elements.u[v, nnodes(dg), l, lower_element_id]\n end\n end\n else\n # L2 mortars in y-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.l2mortars.u_upper[1, v, l, m] = dg.elements.u[v, l, nnodes(dg), upper_element_id]\n dg.l2mortars.u_lower[1, v, l, m] = dg.elements.u[v, l, nnodes(dg), lower_element_id]\n end\n end\n end\n end\n\n # Interpolate large element face data to small interface locations\n if dg.l2mortars.large_sides[m] == 1 # -> large element on left side\n leftright = 1\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n u_large = view(dg.elements.u, :, nnodes(dg), :, large_element_id)\n element_solutions_to_mortars!(dg, mortar_type, leftright, m, u_large)\n else\n # L2 mortars in y-direction\n u_large = view(dg.elements.u, :, :, nnodes(dg), large_element_id)\n element_solutions_to_mortars!(dg, mortar_type, leftright, m, u_large)\n end\n else # large_sides[m] == 2 -> large element on right side\n leftright = 2\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n u_large = view(dg.elements.u, :, 1, :, large_element_id)\n element_solutions_to_mortars!(dg, mortar_type, leftright, m, u_large)\n else\n # L2 mortars in y-direction\n u_large = view(dg.elements.u, :, :, 1, large_element_id)\n element_solutions_to_mortars!(dg, mortar_type, leftright, m, u_large)\n end\n end\n end\nend\n\n\"\"\"\n element_solutions_to_mortars!(dg::Dg2D, ::Val{:l2}, leftright, m, u_large)\n\nInterpolate `u_large` to `dg.l2mortars.u_[upper/lower]` for mortar `m`\nusing the forward mortar operators of `dg`.\n\"\"\"\n@inline function element_solutions_to_mortars!(dg::Dg2D, ::Val{:l2}, leftright, m, u_large)\n multiply_dimensionwise!(view(dg.l2mortars.u_upper, leftright, :, :, m), dg.mortar_forward_upper, u_large)\n multiply_dimensionwise!(view(dg.l2mortars.u_lower, leftright, :, :, m), dg.mortar_forward_lower, u_large)\n return nothing\nend\n\n\n# Prolong solution to mortars (ecmortar version)\nfunction prolong2mortars!(dg::Dg2D, ::Val{:ec})\n equation = equations(dg)\n\n Threads.@threads for m in 1:dg.n_ecmortars\n large_element_id = dg.ecmortars.neighbor_ids[3, m]\n upper_element_id = dg.ecmortars.neighbor_ids[2, m]\n lower_element_id = dg.ecmortars.neighbor_ids[1, m]\n\n # Copy solution small to small\n if dg.ecmortars.large_sides[m] == 1 # -> small elements on right side, large element on left\n if dg.ecmortars.orientations[m] == 1\n # L2 mortars in x-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.ecmortars.u_upper[v, l, m] = dg.elements.u[v, 1, l, upper_element_id]\n dg.ecmortars.u_lower[v, l, m] = dg.elements.u[v, 1, l, lower_element_id]\n dg.ecmortars.u_large[v, l, m] = dg.elements.u[v, nnodes(dg), l, large_element_id]\n end\n end\n else\n # L2 mortars in y-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.ecmortars.u_upper[v, l, m] = dg.elements.u[v, l, 1, upper_element_id]\n dg.ecmortars.u_lower[v, l, m] = dg.elements.u[v, l, 1, lower_element_id]\n dg.ecmortars.u_large[v, l, m] = dg.elements.u[v, l, nnodes(dg), large_element_id]\n end\n end\n end\n else # large_sides[m] == 2 -> small elements on left side, large element on right\n if dg.ecmortars.orientations[m] == 1\n # L2 mortars in x-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.ecmortars.u_upper[v, l, m] = dg.elements.u[v, nnodes(dg), l, upper_element_id]\n dg.ecmortars.u_lower[v, l, m] = dg.elements.u[v, nnodes(dg), l, lower_element_id]\n dg.ecmortars.u_large[v, l, m] = dg.elements.u[v, 1, l, large_element_id]\n end\n end\n else\n # L2 mortars in y-direction\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.ecmortars.u_upper[v, l, m] = dg.elements.u[v, l, nnodes(dg), upper_element_id]\n dg.ecmortars.u_lower[v, l, m] = dg.elements.u[v, l, nnodes(dg), lower_element_id]\n dg.ecmortars.u_large[v, l, m] = dg.elements.u[v, l, 1, large_element_id]\n end\n end\n end\n end\n end\nend\n\n\n\"\"\"\n calc_fstar!(destination, u_interfaces_left, u_interfaces_right, interface_id, orientations, dg::Dg2D)\n\nCalculate the surface flux across interface with different states given by\n`u_interfaces_left, u_interfaces_right` on both sides (EC mortar version).\n\n# Arguments\n- `destination::AbstractArray{T,3} where T<:Real`:\n The array of surface flux values (updated inplace).\n- `u_interfaces_left::AbstractArray{T,3} where T<:Real``\n- `u_interfaces_right::AbstractArray{T,3} where T<:Real``\n- `interface_id::Integer`\n- `orientations::Vector{T} where T<:Integer`\n- `dg::Dg2D`\n\"\"\"\nfunction calc_fstar!(destination, u_interfaces_left, u_interfaces_right, interface_id, orientations, dg::Dg2D)\n @unpack surface_flux_function = dg\n\n # Call pointwise two-point numerical flux function\n # i -> left, j -> right\n for j in 1:nnodes(dg), i in 1:nnodes(dg)\n u_ll = get_node_vars(u_interfaces_left, dg, i, interface_id)\n u_rr = get_node_vars(u_interfaces_right, dg, j, interface_id)\n flux = surface_flux_function(u_ll, u_rr, orientations[interface_id], equations(dg))\n\n # Copy flux back to actual flux array\n set_node_vars!(destination, flux, dg, i, j)\n end\nend\n\n\"\"\"\n calc_fstar!(destination, u_interfaces, interface_id, orientations, dg::Dg2D)\n\nCalculate the surface flux across interface with different states given by\n`u_interfaces_left, u_interfaces_right` on both sides (interface version).\n\n# Arguments\n- `destination::AbstractArray{T,2} where T<:Real`:\n The array of surface flux values (updated inplace).\n- `u_interfaces::AbstractArray{T,4} where T<:Real``\n- `interface_id::Integer`\n- `orientations::Vector{T} where T<:Integer`\n- `dg::Dg2D`\n\"\"\"\nfunction calc_fstar!(destination, u_interfaces, interface_id, orientations, dg::Dg2D)\n @unpack surface_flux_function = dg\n\n for i in 1:nnodes(dg)\n # Call pointwise two-point numerical flux function\n u_ll, u_rr = get_surface_node_vars(u_interfaces, dg, i, interface_id)\n flux = surface_flux_function(u_ll, u_rr, orientations[interface_id], equations(dg))\n\n # Copy flux to left and right element storage\n set_node_vars!(destination, flux, dg, i)\n end\nend\n\n\n# Calculate and store the surface fluxes (standard Riemann and nonconservative parts) at an interface\n# OBS! Regarding the nonconservative terms: 1) currently only needed for the MHD equations\n# 2) not implemented for boundaries\ncalc_interface_flux!(dg::Dg2D) = calc_interface_flux!(dg.elements.surface_flux_values,\n have_nonconservative_terms(dg.equations), dg)\n\nfunction calc_interface_flux!(surface_flux_values, nonconservative_terms::Val{false}, dg::Dg2D)\n @unpack surface_flux_function = dg\n @unpack u, neighbor_ids, orientations = dg.interfaces\n\n Threads.@threads for s in 1:dg.n_interfaces\n # Get neighboring elements\n left_id = neighbor_ids[1, s]\n right_id = neighbor_ids[2, s]\n\n # Determine interface direction with respect to elements:\n # orientation = 1: left -> 2, right -> 1\n # orientation = 2: left -> 4, right -> 3\n left_direction = 2 * orientations[s]\n right_direction = 2 * orientations[s] - 1\n\n for i in 1:nnodes(dg)\n # Call pointwise Riemann solver\n u_ll, u_rr = get_surface_node_vars(u, dg, i, s)\n flux = surface_flux_function(u_ll, u_rr, orientations[s], equations(dg))\n\n # Copy flux to left and right element storage\n for v in 1:nvariables(dg)\n surface_flux_values[v, i, left_direction, left_id] = surface_flux_values[v, i, right_direction, right_id] = flux[v]\n end\n end\n end\nend\n\n# Calculate and store Riemann and nonconservative fluxes across interfaces\nfunction calc_interface_flux!(surface_flux_values, nonconservative_terms::Val{true}, dg::Dg2D)\n #TODO temporary workaround while implementing the other stuff\n calc_interface_flux!(surface_flux_values, dg.interfaces.neighbor_ids, dg.interfaces.u,\n nonconservative_terms, dg.interfaces.orientations, dg, dg.thread_cache)\nend\n\nfunction calc_interface_flux!(surface_flux_values, neighbor_ids,\n u_interfaces, nonconservative_terms::Val{true},\n orientations, dg::Dg2D, thread_cache)\n fstar_threaded = thread_cache.fstar_upper_threaded\n noncons_diamond_primary_threaded = thread_cache.noncons_diamond_upper_threaded\n noncons_diamond_secondary_threaded = thread_cache.noncons_diamond_lower_threaded\n\n Threads.@threads for s in 1:dg.n_interfaces\n # Choose thread-specific pre-allocated container\n fstar = fstar_threaded[Threads.threadid()]\n noncons_diamond_primary = noncons_diamond_primary_threaded[Threads.threadid()]\n noncons_diamond_secondary = noncons_diamond_secondary_threaded[Threads.threadid()]\n\n # Calculate flux\n calc_fstar!(fstar, u_interfaces, s, orientations, dg)\n\n # Compute the nonconservative numerical \"flux\" along an interface\n # Done twice because left/right orientation matters så\n # 1 -> primary element and 2 -> secondary element\n # See Bohm et al. 2018 for details on the nonconservative diamond \"flux\"\n for i in 1:nnodes(dg)\n # Call pointwise nonconservative term\n u_ll, u_rr = get_surface_node_vars(u_interfaces, dg, i, s)\n noncons_primary = noncons_interface_flux(u_ll, u_rr, orientations[s], equations(dg))\n noncons_secondary = noncons_interface_flux(u_rr, u_ll, orientations[s], equations(dg))\n # Save to primary and secondary temporay storage\n set_node_vars!(noncons_diamond_primary, noncons_primary, dg, i)\n set_node_vars!(noncons_diamond_secondary, noncons_secondary, dg, i)\n end\n\n # Get neighboring elements\n left_neighbor_id = neighbor_ids[1, s]\n right_neighbor_id = neighbor_ids[2, s]\n\n # Determine interface direction with respect to elements:\n # orientation = 1: left -> 2, right -> 1\n # orientation = 2: left -> 4, right -> 3\n left_neighbor_direction = 2 * orientations[s]\n right_neighbor_direction = 2 * orientations[s] - 1\n\n # Copy flux to left and right element storage\n for i in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n surface_flux_values[v, i, left_neighbor_direction, left_neighbor_id] = (fstar[v, i] +\n noncons_diamond_primary[v, i])\n surface_flux_values[v, i, right_neighbor_direction, right_neighbor_id] = (fstar[v, i] +\n noncons_diamond_secondary[v, i])\n end\n end\n end\nend\n\n\n# Calculate and store boundary flux across domain boundaries\n#NOTE: Do we need to dispatch on have_nonconservative_terms(dg.equations)?\ncalc_boundary_flux!(dg::Dg2D, time) = calc_boundary_flux!(dg.elements.surface_flux_values, dg, time)\n\nfunction calc_boundary_flux!(surface_flux_values, dg::Dg2D, time)\n @unpack n_boundaries_per_direction, boundary_conditions = dg\n\n # Calculate indices\n lasts = accumulate(+, n_boundaries_per_direction)\n firsts = lasts - n_boundaries_per_direction .+ 1\n\n # Calc boundary fluxes in each direction\n calc_boundary_flux_by_direction!(surface_flux_values, dg, time,\n boundary_conditions[1], 1, firsts[1], lasts[1])\n calc_boundary_flux_by_direction!(surface_flux_values, dg, time,\n boundary_conditions[2], 2, firsts[2], lasts[2])\n calc_boundary_flux_by_direction!(surface_flux_values, dg, time,\n boundary_conditions[3], 3, firsts[3], lasts[3])\n calc_boundary_flux_by_direction!(surface_flux_values, dg, time,\n boundary_conditions[4], 4, firsts[4], lasts[4])\nend\n\n\nfunction calc_boundary_flux_by_direction!(surface_flux_values, dg::Dg2D, time, boundary_condition,\n direction, first_boundary_id, last_boundary_id)\n @unpack surface_flux_function = dg\n @unpack u, neighbor_ids, neighbor_sides, node_coordinates, orientations = dg.boundaries\n\n Threads.@threads for b in first_boundary_id:last_boundary_id\n # Get neighboring element\n neighbor_id = neighbor_ids[b]\n\n for i in 1:nnodes(dg)\n # Get boundary flux\n u_ll, u_rr = get_surface_node_vars(u, dg, i, b)\n if neighbor_sides[b] == 1 # Element is on the left, boundary on the right\n u_inner = u_ll\n else # Element is on the right, boundary on the left\n u_inner = u_rr\n end\n x = get_node_coords(node_coordinates, dg, i, b)\n flux = boundary_condition(u_inner, orientations[b], direction, x, time, surface_flux_function,\n equations(dg))\n\n # Copy flux to left and right element storage\n for v in 1:nvariables(dg)\n surface_flux_values[v, i, direction, neighbor_id] = flux[v]\n end\n end\n end\nend\n\n\n# Calculate and store fluxes across mortars (select correct method based on mortar type)\ncalc_mortar_flux!(dg::Dg2D) = calc_mortar_flux!(dg, dg.mortar_type)\n\n# Calculate and store fluxes and nonconservative terms across L2 mortars\ncalc_mortar_flux!(dg::Dg2D, mortar_type::Val{:l2}) = calc_mortar_flux!(dg.elements.surface_flux_values, dg, mortar_type,\n have_nonconservative_terms(dg.equations), dg.l2mortars, dg.thread_cache)\n\n# Calculate and store fluxes across L2 mortars\nfunction calc_mortar_flux!(surface_flux_values, dg::Dg2D, mortar_type::Val{:l2},\n nonconservative_terms::Val{false}, mortars, cache)\n @unpack neighbor_ids, u_lower, u_upper, orientations = mortars\n @unpack fstar_upper_threaded, fstar_lower_threaded = cache\n\n Threads.@threads for m in 1:dg.n_l2mortars\n # Choose thread-specific pre-allocated container\n fstar_upper = fstar_upper_threaded[Threads.threadid()]\n fstar_lower = fstar_lower_threaded[Threads.threadid()]\n\n # Calculate fluxes\n calc_fstar!(fstar_upper, u_upper, m, orientations, dg)\n calc_fstar!(fstar_lower, u_lower, m, orientations, dg)\n\n mortar_fluxes_to_elements!(surface_flux_values, dg, mortar_type, m,\n fstar_upper, fstar_lower)\n end\nend\n\nfunction calc_mortar_flux!(surface_flux_values, dg::Dg2D, mortar_type::Val{:l2},\n nonconservative_terms::Val{true}, mortars, thread_cache)\n @unpack neighbor_ids, u_lower, u_upper, orientations = mortars\n @unpack fstar_upper_threaded, fstar_lower_threaded,\n noncons_diamond_upper_threaded, noncons_diamond_lower_threaded = thread_cache\n\n Threads.@threads for m in 1:dg.n_l2mortars\n # Choose thread-specific pre-allocated container\n fstar_upper = fstar_upper_threaded[Threads.threadid()]\n fstar_lower = fstar_lower_threaded[Threads.threadid()]\n\n noncons_diamond_upper = noncons_diamond_upper_threaded[Threads.threadid()]\n noncons_diamond_lower = noncons_diamond_lower_threaded[Threads.threadid()]\n\n # Calculate fluxes\n calc_fstar!(fstar_upper, u_upper, m, orientations, dg)\n calc_fstar!(fstar_lower, u_lower, m, orientations, dg)\n\n # Compute the nonconservative numerical terms along the upper and lower interface\n # Done twice because left/right orientation matters\n # 1 -> primary element and 2 -> secondary element\n # See Bohm et al. 2018 for details on the nonconservative diamond \"flux\"\n if dg.l2mortars.large_sides[m] == 1 # -> small elements on right side\n for i in 1:nnodes(dg)\n # pull the left and right solutions\n u_upper_ll, u_upper_rr = get_surface_node_vars(u_upper, dg, i, m)\n u_lower_ll, u_lower_rr = get_surface_node_vars(u_lower, dg, i, m)\n # Call pointwise nonconservative term\n noncons_upper = noncons_interface_flux(u_upper_ll, u_upper_rr, orientations[m], equations(dg))\n noncons_lower = noncons_interface_flux(u_lower_ll, u_lower_rr, orientations[m], equations(dg))\n # Save to primary and secondary temporay storage\n set_node_vars!(noncons_diamond_upper, noncons_upper, dg, i)\n set_node_vars!(noncons_diamond_lower, noncons_lower, dg, i)\n end\n else # large_sides[m] == 2 -> small elements on the left\n for i in 1:nnodes(dg)\n # pull the left and right solutions\n u_upper_ll, u_upper_rr = get_surface_node_vars(u_upper, dg, i, m)\n u_lower_ll, u_lower_rr = get_surface_node_vars(u_lower, dg, i, m)\n # Call pointwise nonconservative term\n noncons_upper = noncons_interface_flux(u_upper_rr, u_upper_ll, orientations[m], equations(dg))\n noncons_lower = noncons_interface_flux(u_lower_rr, u_lower_ll, orientations[m], equations(dg))\n # Save to primary and secondary temporay storage\n set_node_vars!(noncons_diamond_upper, noncons_upper, dg, i)\n set_node_vars!(noncons_diamond_lower, noncons_lower, dg, i)\n end\n end\n\n @. fstar_upper += noncons_diamond_upper\n @. fstar_lower += noncons_diamond_lower\n mortar_fluxes_to_elements!(surface_flux_values, dg, mortar_type, m,\n fstar_upper, fstar_lower)\n end\nend\n\n\"\"\"\n mortar_fluxes_to_elements!(surface_flux_values, dg::Dg2D, mortar_type::Val{:l2}, m, fstar_upper, fstar_lower)\n\nCopy/project `fstar_[upper/lower]` to `surface_flux_values` for mortar `m`\nusing the reverse mortar operators of `dg`.\n\"\"\"\n@inline function mortar_fluxes_to_elements!(surface_flux_values, dg::Dg2D, mortar_type::Val{:l2}, m,\n fstar_upper, fstar_lower)\n large_element_id = dg.l2mortars.neighbor_ids[3, m]\n upper_element_id = dg.l2mortars.neighbor_ids[2, m]\n lower_element_id = dg.l2mortars.neighbor_ids[1, m]\n\n # Copy flux small to small\n if dg.l2mortars.large_sides[m] == 1 # -> small elements on right side\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n direction = 1\n else\n # L2 mortars in y-direction\n direction = 3\n end\n else # large_sides[m] == 2 -> small elements on left side\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n direction = 2\n else\n # L2 mortars in y-direction\n direction = 4\n end\n end\n surface_flux_values[:, :, direction, upper_element_id] .= fstar_upper\n surface_flux_values[:, :, direction, lower_element_id] .= fstar_lower\n\n # Project small fluxes to large element\n if dg.l2mortars.large_sides[m] == 1 # -> large element on left side\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n direction = 2\n else\n # L2 mortars in y-direction\n direction = 4\n end\n else # large_sides[m] == 2 -> large element on right side\n if dg.l2mortars.orientations[m] == 1\n # L2 mortars in x-direction\n direction = 1\n else\n # L2 mortars in y-direction\n direction = 3\n end\n end\n\n for v in 1:nvariables(dg)\n @views surface_flux_values[v, :, direction, large_element_id] .=\n (dg.l2mortar_reverse_upper * fstar_upper[v, :] + dg.l2mortar_reverse_lower * fstar_lower[v, :])\n end\n # The code above could be replaced by the following code. However, the relative efficiency\n # depends on the types of fstar_upper/fstar_lower and dg.l2mortar_reverse_upper.\n # Using StaticArrays for both makes the code above faster for common test cases.\n # multiply_dimensionwise!(\n # view(surface_flux_values, :, :, direction, large_element_id), dg.l2mortar_reverse_upper, fstar_upper,\n # dg.l2mortar_reverse_lower, fstar_lower)\n\n return nothing\nend\n\n\n# Calculate and store fluxes across EC mortars\ncalc_mortar_flux!(dg::Dg2D, mortar_type::Val{:ec}) = calc_mortar_flux!(dg.elements.surface_flux_values, dg, mortar_type,\n dg.ecmortars.neighbor_ids,\n dg.ecmortars.u_lower,\n dg.ecmortars.u_upper,\n dg.ecmortars.u_large,\n dg.ecmortars.orientations)\nfunction calc_mortar_flux!(surface_flux_values, dg::Dg2D, mortar_type::Val{:ec},\n neighbor_ids,\n u_lower, u_upper, u_large,\n orientations)\n # Type alias only for convenience\n A3d = MArray{Tuple{nvariables(dg), nnodes(dg), nnodes(dg)}, Float64}\n A1d = MArray{Tuple{nvariables(dg)}, Float64}\n\n # Pre-allocate data structures to speed up computation (thread-safe)\n fstar_upper_threaded = [A3d(undef) for _ in 1:Threads.nthreads()]\n fstar_lower_threaded = [A3d(undef) for _ in 1:Threads.nthreads()]\n fstarnode_upper_threaded = [A1d(undef) for _ in 1:Threads.nthreads()]\n fstarnode_lower_threaded = [A1d(undef) for _ in 1:Threads.nthreads()]\n\n # Store matrix references for convenience (notation: R -> large, L -> small)\n # Note: the same notation is used in the publications of Lucas Friedrich\n PR2L_upper = dg.mortar_forward_upper\n PR2L_lower = dg.mortar_forward_lower\n PL2R_upper = dg.ecmortar_reverse_upper\n PL2R_lower = dg.ecmortar_reverse_lower\n\n Threads.@threads for m in 1:dg.n_ecmortars\n large_element_id = neighbor_ids[3, m]\n upper_element_id = neighbor_ids[2, m]\n lower_element_id = neighbor_ids[1, m]\n\n # Choose thread-specific pre-allocated container\n fstar_upper = fstar_upper_threaded[Threads.threadid()]\n fstar_lower = fstar_lower_threaded[Threads.threadid()]\n\n # Calculate fluxes\n if dg.ecmortars.large_sides[m] == 1 # -> small elements on right side, large element on left\n calc_fstar!(fstar_upper, u_large, u_upper, m, orientations, dg)\n calc_fstar!(fstar_lower, u_large, u_lower, m, orientations, dg)\n else # large_sides[m] == 2 -> small elements on left side, large element on right\n calc_fstar!(fstar_upper, u_upper, u_large, m, orientations, dg)\n calc_fstar!(fstar_lower, u_lower, u_large, m, orientations, dg)\n end\n\n # Transfer fluxes to elements\n if dg.ecmortars.large_sides[m] == 1 # -> small elements on right side, large element on left\n if dg.ecmortars.orientations[m] == 1\n # EC mortars in x-direction\n surface_flux_values[:, :, 2, large_element_id] .= 0.0\n surface_flux_values[:, :, 1, upper_element_id] .= 0.0\n surface_flux_values[:, :, 1, lower_element_id] .= 0.0\n for i in 1:nnodes(dg)\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n surface_flux_values[v, i, 2, large_element_id] += (PL2R_upper[i, l] * fstar_upper[v, i, l] +\n PL2R_lower[i, l] * fstar_lower[v, i, l])\n surface_flux_values[v, i, 1, upper_element_id] += PR2L_upper[i, l] * fstar_upper[v, l, i]\n surface_flux_values[v, i, 1, lower_element_id] += PR2L_lower[i, l] * fstar_lower[v, l, i]\n end\n end\n end\n else\n # EC mortars in y-direction\n surface_flux_values[:, :, 4, large_element_id] .= 0.0\n surface_flux_values[:, :, 3, upper_element_id] .= 0.0\n surface_flux_values[:, :, 3, lower_element_id] .= 0.0\n for i in 1:nnodes(dg)\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n surface_flux_values[v, i, 4, large_element_id] += (PL2R_upper[i, l] * fstar_upper[v, i, l] +\n PL2R_lower[i, l] * fstar_lower[v, i, l])\n surface_flux_values[v, i, 3, upper_element_id] += PR2L_upper[i, l] * fstar_upper[v, l, i]\n surface_flux_values[v, i, 3, lower_element_id] += PR2L_lower[i, l] * fstar_lower[v, l, i]\n end\n end\n end\n end\n else # large_sides[m] == 2 -> small elements on left side, large element on right\n if dg.ecmortars.orientations[m] == 1\n # EC mortars in x-direction\n surface_flux_values[:, :, 1, large_element_id] .= 0.0\n surface_flux_values[:, :, 2, upper_element_id] .= 0.0\n surface_flux_values[:, :, 2, lower_element_id] .= 0.0\n for i in 1:nnodes(dg)\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n surface_flux_values[v, i, 1, large_element_id] += (PL2R_upper[i, l] * fstar_upper[v, l, i] +\n PL2R_lower[i, l] * fstar_lower[v, l, i])\n surface_flux_values[v, i, 2, upper_element_id] += PR2L_upper[i, l] * fstar_upper[v, i, l]\n surface_flux_values[v, i, 2, lower_element_id] += PR2L_lower[i, l] * fstar_lower[v, i, l]\n end\n end\n end\n else\n # EC mortars in y-direction\n surface_flux_values[:, :, 3, large_element_id] .= 0.0\n surface_flux_values[:, :, 4, upper_element_id] .= 0.0\n surface_flux_values[:, :, 4, lower_element_id] .= 0.0\n for i in 1:nnodes(dg)\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n surface_flux_values[v, i, 3, large_element_id] += (PL2R_upper[i, l] * fstar_upper[v, l, i] +\n PL2R_lower[i, l] * fstar_lower[v, l, i])\n surface_flux_values[v, i, 4, upper_element_id] += PR2L_upper[i, l] * fstar_upper[v, i, l]\n surface_flux_values[v, i, 4, lower_element_id] += PR2L_lower[i, l] * fstar_lower[v, i, l]\n end\n end\n end\n end\n end\n end\nend\n\n\n# Calculate surface integrals and update u_t\ncalc_surface_integral!(dg::Dg2D) = calc_surface_integral!(dg.elements.u_t, dg.elements.surface_flux_values, dg)\nfunction calc_surface_integral!(u_t, surface_flux_values, dg::Dg2D)\n @unpack lhat = dg\n\n Threads.@threads for element_id in 1:dg.n_elements\n for l in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n # surface at -x\n u_t[v, 1, l, element_id] -= surface_flux_values[v, l, 1, element_id] * lhat[1, 1]\n # surface at +x\n u_t[v, nnodes(dg), l, element_id] += surface_flux_values[v, l, 2, element_id] * lhat[nnodes(dg), 2]\n # surface at -y\n u_t[v, l, 1, element_id] -= surface_flux_values[v, l, 3, element_id] * lhat[1, 1]\n # surface at +y\n u_t[v, l, nnodes(dg), element_id] += surface_flux_values[v, l, 4, element_id] * lhat[nnodes(dg), 2]\n end\n end\n end\nend\n\n\n# Apply Jacobian from mapping to reference element\nfunction apply_jacobian!(dg::Dg2D)\n Threads.@threads for element_id in 1:dg.n_elements\n factor = -dg.elements.inverse_jacobian[element_id]\n for j in 1:nnodes(dg)\n for i in 1:nnodes(dg)\n for v in 1:nvariables(dg)\n dg.elements.u_t[v, i, j, element_id] *= factor\n end\n end\n end\n end\nend\n\n\n# Calculate source terms and apply them to u_t\nfunction calc_sources!(dg::Dg2D, source_terms::Nothing, t)\n return nothing\nend\n\nfunction calc_sources!(dg::Dg2D, source_terms, t)\n Threads.@threads for element_id in 1:dg.n_elements\n source_terms(dg.elements.u_t, dg.elements.u,\n dg.elements.node_coordinates, element_id, t, nnodes(dg), equations(dg))\n end\nend\n\n\n# Calculate stable time step size\n@inline calc_dt(dg, cfl) = calc_dt(dg, cfl, uses_mpi(dg))\nfunction calc_dt(dg::Dg2D, cfl, uses_mpi::Val{false})\n min_dt = Inf\n for element_id in 1:dg.n_elements\n dt = calc_max_dt(dg.elements.u, element_id,\n dg.elements.inverse_jacobian[element_id], cfl, equations(dg), dg)\n min_dt = min(min_dt, dt)\n end\n\n return min_dt\nend\n\n# Calculate blending factors used for shock capturing, or amr control\nfunction calc_blending_factors!(alpha, alpha_pre_smooth, u,\n alpha_max, alpha_min, do_smoothing,\n indicator_variable, thread_cache, dg::Dg2D)\n calc_blending_factors!(alpha, alpha_pre_smooth, u, alpha_max, alpha_min, do_smoothing,\n indicator_variable, thread_cache, dg, uses_mpi(dg))\nend\nfunction calc_blending_factors!(alpha, alpha_pre_smooth, u,\n alpha_max, alpha_min, do_smoothing,\n indicator_variable, thread_cache, dg::Dg2D, uses_mpi::Val{false})\n # temporary buffers\n @unpack indicator_threaded, modal_threaded, modal_tmp1_threaded = thread_cache\n # magic parameters\n threshold = 0.5 * 10^(-1.8 * (nnodes(dg))^0.25)\n parameter_s = log((1 - 0.0001)/0.0001)\n\n Threads.@threads for element_id in 1:dg.n_elements\n indicator = indicator_threaded[Threads.threadid()]\n modal = modal_threaded[Threads.threadid()]\n modal_tmp1 = modal_tmp1_threaded[Threads.threadid()]\n\n # Calculate indicator variables at Gauss-Lobatto nodes\n cons2indicator!(indicator, u, element_id, indicator_variable, dg)\n\n # Convert to modal representation\n multiply_dimensionwise!(modal, dg.inverse_vandermonde_legendre, indicator, modal_tmp1)\n\n # Calculate total energies for all modes, without highest, without two highest\n total_energy = 0.0\n for j in 1:nnodes(dg), i in 1:nnodes(dg)\n total_energy += modal[1, i, j]^2\n end\n total_energy_clip1 = 0.0\n for j in 1:(nnodes(dg)-1), i in 1:(nnodes(dg)-1)\n total_energy_clip1 += modal[1, i, j]^2\n end\n total_energy_clip2 = 0.0\n for j in 1:(nnodes(dg)-2), i in 1:(nnodes(dg)-2)\n total_energy_clip2 += modal[1, i, j]^2\n end\n\n # Calculate energy in lower modes\n energy = max((total_energy - total_energy_clip1)/total_energy,\n (total_energy_clip1 - total_energy_clip2)/total_energy_clip1)\n\n alpha[element_id] = 1 / (1 + exp(-parameter_s/threshold * (energy - threshold)))\n\n # Take care of the case close to pure DG\n if (alpha[element_id] < alpha_min)\n alpha[element_id] = 0.\n end\n\n # Take care of the case close to pure FV\n if (alpha[element_id] > 1-alpha_min)\n alpha[element_id] = 1.\n end\n\n # Clip the maximum amount of FV allowed\n alpha[element_id] = min(alpha_max, alpha[element_id])\n end\n\n if (do_smoothing)\n smooth_alpha!(alpha, alpha_pre_smooth, dg, uses_mpi)\n end\nend\n\n\nsmooth_alpha!(alpha, alpha_pre_smooth, dg::Dg2D) = smooth_alpha!(alpha, alpha_pre_smooth, dg, uses_mpi(dg))\nfunction smooth_alpha!(alpha, alpha_pre_smooth, dg::Dg2D, uses_mpi::Val{false})\n # Diffuse alpha values by setting each alpha to at least 50% of neighboring elements' alpha\n # Copy alpha values such that smoothing is indpedenent of the element access order\n alpha_pre_smooth .= alpha\n\n # Loop over interfaces\n for interface_id in 1:dg.n_interfaces\n # Get neighboring element ids\n left = dg.interfaces.neighbor_ids[1, interface_id]\n right = dg.interfaces.neighbor_ids[2, interface_id]\n\n # Apply smoothing\n alpha[left] = max(alpha_pre_smooth[left], 0.5 * alpha_pre_smooth[right], alpha[left])\n alpha[right] = max(alpha_pre_smooth[right], 0.5 * alpha_pre_smooth[left], alpha[right])\n end\n\n # Loop over L2 mortars\n for l2mortar_id in 1:dg.n_l2mortars\n # Get neighboring element ids\n lower = dg.l2mortars.neighbor_ids[1, l2mortar_id]\n upper = dg.l2mortars.neighbor_ids[2, l2mortar_id]\n large = dg.l2mortars.neighbor_ids[3, l2mortar_id]\n\n # Apply smoothing\n alpha[lower] = max(alpha_pre_smooth[lower], 0.5 * alpha_pre_smooth[large], alpha[lower])\n alpha[upper] = max(alpha_pre_smooth[upper], 0.5 * alpha_pre_smooth[large], alpha[upper])\n alpha[large] = max(alpha_pre_smooth[large], 0.5 * alpha_pre_smooth[lower], alpha[large])\n alpha[large] = max(alpha_pre_smooth[large], 0.5 * alpha_pre_smooth[upper], alpha[large])\n end\n\n # Loop over EC mortars\n for ecmortar_id in 1:dg.n_ecmortars\n # Get neighboring element ids\n lower = dg.ecmortars.neighbor_ids[1, ecmortar_id]\n upper = dg.ecmortars.neighbor_ids[2, ecmortar_id]\n large = dg.ecmortars.neighbor_ids[3, ecmortar_id]\n\n # Apply smoothing\n alpha[lower] = max(alpha_pre_smooth[lower], 0.5 * alpha_pre_smooth[large], alpha[lower])\n alpha[upper] = max(alpha_pre_smooth[upper], 0.5 * alpha_pre_smooth[large], alpha[upper])\n alpha[large] = max(alpha_pre_smooth[large], 0.5 * alpha_pre_smooth[lower], alpha[large])\n alpha[large] = max(alpha_pre_smooth[large], 0.5 * alpha_pre_smooth[upper], alpha[large])\n end\nend\n\n\n# Convert conservative variables to indicator variable for discontinuities (elementwise version)\n@inline function cons2indicator!(indicator, u, element_id, indicator_variable, dg::Dg2D)\n eqs = equations(dg)\n\n for j in 1:nnodes(dg), i in 1:nnodes(dg)\n u_node = get_node_vars(u, dg, i, j, element_id)\n indicator[1, i, j] = indicator_variable(u_node, eqs)\n end\nend\n\n\n\"\"\"\n pure_and_blended_element_ids!(element_ids_dg, element_ids_dgfv, alpha, dg)\n\nGiven blending factors `alpha` and the solver `dg`, fill\n`element_ids_dg` with the IDs of elements using a pure DG scheme and\n`element_ids_dgfv` with the IDs of elements using a blended DG-FV scheme.\n\"\"\"\nfunction pure_and_blended_element_ids!(element_ids_dg, element_ids_dgfv, alpha, dg::Dg2D)\n empty!(element_ids_dg)\n empty!(element_ids_dgfv)\n\n for element_id in 1:dg.n_elements\n # Clip blending factor for values close to zero (-> pure DG)\n dg_only = isapprox(alpha[element_id], 0, atol=1e-12)\n if dg_only\n push!(element_ids_dg, element_id)\n else\n push!(element_ids_dgfv, element_id)\n end\n end\nend\n", "meta": {"hexsha": "503423e7b38fa66ebbd76d716013bb559468d178", "size": 98704, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solvers/dg/2d/dg.jl", "max_stars_repo_name": "sloede/Trixi.jl", "max_stars_repo_head_hexsha": "256ff44456725fd859bdf0903e105246e9893ae5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-13T11:11:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T15:11:05.000Z", "max_issues_repo_path": "src/solvers/dg/2d/dg.jl", "max_issues_repo_name": "sloede/Trixi.jl", "max_issues_repo_head_hexsha": "256ff44456725fd859bdf0903e105246e9893ae5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/dg/2d/dg.jl", "max_forks_repo_name": "sloede/Trixi.jl", "max_forks_repo_head_hexsha": "256ff44456725fd859bdf0903e105246e9893ae5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8598425197, "max_line_length": 180, "alphanum_fraction": 0.6817960772, "num_tokens": 27815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.19953808575054907}} {"text": "\n\"\"\"\nConverts a dictionary parsed by PowerModels to a System.\nCurrently Supports MATPOWER and PSSE data files parsed by PowerModels.\nSupports kwargs to supply formatters for different device types,\nsuch as `bus_name_formatter` or `gen_name_formatter`.\n\n# Examples\n```julia\nsys = PSY.pm2ps_dict(pm_data, configpath = \"ACTIVSg25k_validation.json\",\n bus_name_formatter = x->string(x[\"name\"]*\"-\"*string(x[\"index\"])),\n load_name_formatter = x->strip(join(x[\"source_id\"], \"_\")))\n```\n\"\"\"\nfunction pm2ps_dict(data::Dict{String, Any}; kwargs...)\n if length(data[\"bus\"]) < 1\n throw(DataFormatError(\"There are no buses in this file.\"))\n end\n\n @info \"Constructing System from Power Models\" data[\"name\"] data[\"source_type\"]\n\n sys = System(data[\"baseMVA\"]; kwargs...)\n\n bus_number_to_bus = read_bus!(sys, data; kwargs...)\n read_loads!(sys, data, bus_number_to_bus; kwargs...)\n read_loadzones!(sys, data, bus_number_to_bus; kwargs...)\n read_gen!(sys, data, bus_number_to_bus; kwargs...)\n read_branch!(sys, data, bus_number_to_bus; kwargs...)\n read_shunt!(sys, data, bus_number_to_bus; kwargs...)\n read_dcline!(sys, data, bus_number_to_bus; kwargs...)\n\n check!(sys)\n return sys\nend\n\n\"\"\"\nInternal component name retreval from pm2ps_dict\n\"\"\"\nfunction _get_pm_dict_name(device_dict)\n return get(device_dict, \"name\", string(device_dict[\"index\"]))\nend\n\n\"\"\"\nCreates a PowerSystems.Bus from a PowerSystems bus dictionary\n\"\"\"\nfunction make_bus(bus_dict::Dict{String, Any})\n bus = Bus(bus_dict[\"number\"],\n bus_dict[\"name\"],\n bus_dict[\"bustype\"],\n bus_dict[\"angle\"],\n bus_dict[\"voltage\"],\n bus_dict[\"voltagelimits\"],\n bus_dict[\"basevoltage\"]\n )\n return bus\n end\n\nfunction make_bus(bus_name, bus_number, d, bus_types)\n bus = make_bus(Dict{String, Any}(\"name\" => bus_name ,\n \"number\" => bus_number,\n \"bustype\" => bus_types[d[\"bus_type\"]],\n \"angle\" => d[\"va\"],\n \"voltage\" => d[\"vm\"],\n \"voltagelimits\" => (min=d[\"vmin\"], max=d[\"vmax\"]),\n \"basevoltage\" => d[\"base_kv\"]\n ))\n return bus\nend\n\n# \"From http://www.pserc.cornell.edu/matpower/MATPOWER-manual.pdf Table B-1\"\n@enum MatpowerBusType begin\n MATPOWER_PQ = 1\n MATPOWER_PV = 2\n MATPOWER_REF = 3\n MATPOWER_ISOLATED = 4\nend\n\nfunction Base.convert(::Type{BusType}, x::MatpowerBusType)\n map = Dict(MATPOWER_ISOLATED => ISOLATED,\n MATPOWER_PQ => PQ,\n MATPOWER_PV => PV,\n MATPOWER_REF => REF)\n return map[x]\nend\n\nfunction read_bus!(sys::System, data; kwargs...)\n @info \"Reading bus data\"\n bus_number_to_bus = Dict{Int, Bus}()\n\n bus_types = instances(MatpowerBusType)\n data = sort(collect(data[\"bus\"]), by = x->parse(Int64, x[1]))\n\n if length(data) == 0\n @error \"No bus data found\" # TODO : need for a model without a bus\n end\n\n _get_name = get(kwargs, :bus_name_formatter, _get_pm_dict_name)\n\n for (i, (d_key, d)) in enumerate(data)\n # d id the data dict for each bus\n # d_key is bus key\n d[\"name\"] = get(d, \"name\", string(d[\"bus_i\"]))\n bus_name = _get_name(d)\n bus_number = Int(d[\"bus_i\"])\n bus = make_bus(bus_name, bus_number, d, bus_types)\n bus_number_to_bus[bus.number] = bus\n add_component!(sys, bus; skip_validation=SKIP_PM_VALIDATION)\n end\n\n return bus_number_to_bus\nend\n\nfunction make_load(d, bus; kwargs...)\n _get_name = get(kwargs, :load_name_formatter, x->strip(join(x[\"source_id\"])))\n return PowerLoad(;\n name= _get_name(d),\n available=true,\n model = ConstantPower::LoadModel,\n bus=bus,\n activepower=d[\"pd\"],\n reactivepower=d[\"qd\"],\n maxactivepower=d[\"pd\"],\n maxreactivepower=d[\"qd\"],\n )\nend\n\nfunction read_loads!(sys::System, data, bus_number_to_bus::Dict{Int, Bus}; kwargs...)\n if !haskey(data, \"load\")\n @error \"There are no loads in this file\"\n return\n end\n\n for d_key in keys(data[\"load\"])\n d = data[\"load\"][d_key]\n if d[\"pd\"] != 0.0\n bus = bus_number_to_bus[d[\"load_bus\"]]\n load = make_load(d, bus; kwargs...)\n\n add_component!(sys, load; skip_validation=SKIP_PM_VALIDATION)\n end\n end\nend\n\nfunction make_loadzones(d, bus_l, activepower, reactivepower; kwargs...)\n _get_name = get(kwargs, :loadzone_name_formatter, _get_pm_dict_name)\n return LoadZones(;\n number=d[\"index\"],\n name=_get_name(d),\n buses=bus_l,\n maxactivepower=sum(activepower),\n maxreactivepower=sum(reactivepower),\n )\nend\n\nfunction read_loadzones!(sys::System, data, bus_number_to_bus::Dict{Int, Bus}; kwargs...)\n if !haskey(data, \"areas\")\n @info \"There are no Load Zones data in this file\"\n return\n end\n\n for (d_key, d) in data[\"areas\"]\n buses = [bus_number_to_bus[b[\"bus_i\"]] for (b_key, b) in data[\"bus\"]\n if b[\"area\"] == d[\"index\"]]\n bus_names = Set{String}()\n for bus in buses\n push!(bus_names, get_name(bus))\n end\n\n active_power = Vector{Float64}()\n reactive_power = Vector{Float64}()\n\n for (key, load) in data[\"load\"]\n load_bus = bus_number_to_bus[load[\"load_bus\"]]\n if get_name(load_bus) in bus_names\n push!(active_power, load[\"pd\"])\n push!(reactive_power, load[\"qd\"])\n end\n end\n\n d[\"name\"] = get(d, \"name\", d_key)\n\n load_zones = make_loadzones(d, buses, active_power, reactive_power; kwargs...)\n add_component!(sys, load_zones; skip_validation=SKIP_PM_VALIDATION)\n end\nend\n\nfunction make_hydro_gen(gen_name, d, bus)\n ramp_agc = get(d, \"ramp_agc\", get(d, \"ramp_10\", get(d, \"ramp_30\", d[\"pmax\"])))\n tech = TechHydro(;\n rating=calculate_rating(d[\"pmax\"], d[\"qmax\"]),\n primemover=convert(PrimeMovers, d[\"type\"]),\n activepowerlimits=(min=d[\"pmin\"], max=d[\"pmax\"]),\n reactivepowerlimits=(min=d[\"qmin\"], max=d[\"qmax\"]),\n ramplimits=(up=ramp_agc / d[\"mbase\"], down=ramp_agc / d[\"mbase\"]),\n timelimits=nothing,\n )\n\n curtailcost = TwoPartCost(0.0, 0.0)\n\n return HydroDispatch(name = gen_name,\n available = Bool(d[\"gen_status\"]),\n bus = bus,\n activepower = d[\"pg\"],\n reactivepower = d[\"qg\"],\n tech = tech,\n op_cost = curtailcost)\nend\n\nfunction make_tech_renewable(d)\n tech = TechRenewable(;\n rating=float(d[\"pmax\"]),\n primemover=convert(PrimeMovers, d[\"type\"]),\n reactivepowerlimits=(min=d[\"qmin\"], max=d[\"qmax\"]),\n powerfactor=1.0,\n )\n\n return tech\nend\n\nfunction make_renewable_dispatch(gen_name, d, bus)\n tech = make_tech_renewable(d)\n cost = TwoPartCost(0.0, 0.0)\n generator = RenewableDispatch(;\n name=gen_name,\n available=Bool(d[\"gen_status\"]),\n bus=bus,\n activepower = d[\"pg\"],\n reactivepower = d[\"qg\"],\n tech=tech,\n op_cost=cost,\n )\n\n return generator\nend\n\nfunction make_renewable_fix(gen_name, d, bus)\n tech = make_tech_renewable(d)\n generator = RenewableFix(;\n name=gen_name,\n available=Bool(d[\"gen_status\"]),\n bus=bus,\n activepower = d[\"pg\"],\n reactivepower = d[\"qg\"],\n tech=tech,\n )\n\n return generator\nend\n\nfunction make_generic_battery(gen_name, d, bus)\n\n # TODO: placeholder\n #battery=GenericBattery(;\n # name=gen_name,\n # available=Bool(d[\"gen_status\"]),\n # bus=bus,\n # energy=,\n # capacity=,\n # rating=,\n # activepower=,\n # inputactivepowerlimits=,\n # outputactivepowerlimits=,\n # efficiency=,\n # reactivepower=,\n # reactivepowerlimits=,\n #)\n #return battery\nend\n\n\"\"\"\nThe polynomial term follows the convention that for an n-degree polynomial, at least n + 1 components are needed.\n c(p) = c_n*p^n+...+c_1p+c_0\n c_o is stored in the field in of the Econ Struct\n\"\"\"\nfunction make_thermal_gen(gen_name::AbstractString, d::Dict, bus::Bus)\n if haskey(d, \"model\")\n model = GeneratorCostModel(d[\"model\"])\n if model == PIECEWISE_LINEAR::GeneratorCostModel\n cost_component = d[\"cost\"]\n power_p = [i for (ix, i) in enumerate(cost_component) if isodd(ix)]\n cost_p = [i for (ix, i) in enumerate(cost_component) if iseven(ix)]\n cost = [(p, c) for (p, c) in zip(cost_p, power_p)]\n fixed = max(0.0, cost[1][1] - (cost[2][1] - cost[1][1])/(cost[2][2] - cost[1][2])*cost[1][2])\n cost = [(c[1] - fixed, c[2]) for c in cost]\n elseif model == POLYNOMIAL::GeneratorCostModel\n if d[\"ncost\"] == 0\n cost = (0.0, 0.0)\n fixed = 0.0\n elseif d[\"ncost\"] == 1\n cost = (0.0, 0.0)\n fixed = d[\"cost\"][1]\n elseif d[\"ncost\"] == 2\n cost = (0.0, d[\"cost\"][1])\n fixed = d[\"cost\"][2]\n elseif d[\"ncost\"] == 3\n cost = (d[\"cost\"][1], d[\"cost\"][2])\n fixed = d[\"cost\"][3]\n else\n throw(DataFormatError(\"invalid value for ncost: $(d[\"ncost\"]). PowerSystems only supports polynomials up to second degree\"))\n end\n end\n startup = d[\"startup\"]\n shutdn = d[\"shutdown\"]\n else\n @warn \"Generator cost data not included for Generator: $gen_name\"\n tmpcost = ThreePartCost(nothing)\n cost = tmpcost.variable\n fixed = tmpcost.fixed\n startup = tmpcost.startup\n shutdn = tmpcost.shutdn\n end\n\n # TODO GitHub #148: ramp_agc isn't always present. This value may not be correct.\n ramp_agc = get(d, \"ramp_agc\", get(d, \"ramp_10\", get(d, \"ramp_30\", d[\"pmax\"])))\n\n tech = TechThermal(;\n rating = sqrt(d[\"pmax\"]^2 + d[\"qmax\"]^2),\n primemover = convert(PrimeMovers, d[\"type\"]),\n fuel = convert(ThermalFuels, d[\"fuel\"]),\n activepowerlimits = (min = d[\"pmin\"], max = d[\"pmax\"]),\n reactivepowerlimits = (min = d[\"qmin\"], max = d[\"qmax\"]),\n ramplimits = (up = ramp_agc / d[\"mbase\"], down = ramp_agc / d[\"mbase\"]),\n timelimits = nothing,\n )\n op_cost = ThreePartCost(;\n variable=cost,\n fixed=fixed,\n startup=startup,\n shutdn=shutdn,\n )\n\n thermal_gen = ThermalStandard(\n name=gen_name,\n available=Bool(d[\"gen_status\"]),\n bus=bus,\n activepower = d[\"pg\"],\n reactivepower = d[\"qg\"],\n tech=tech,\n op_cost=op_cost,\n )\n\n return thermal_gen\nend\n\n\"\"\"\nTransfer generators to ps_dict according to their classification\n\"\"\"\nfunction read_gen!(sys::System, data, bus_number_to_bus::Dict{Int, Bus}; kwargs...)\n @info \"Reading generator data\"\n\n if !haskey(data, \"gen\")\n @error \"There are no Generators in this file\"\n return nothing\n end\n\n genmap_file = get(kwargs, :genmap_file, nothing)\n genmap = get_generator_mapping(genmap_file)\n\n for (name, pm_gen) in data[\"gen\"]\n if haskey(kwargs, :gen_name_formatter)\n _get_name = kwargs[:gen_name_formatter]\n elseif haskey(pm_gen, \"name\")\n _get_name = _get_pm_dict_name\n elseif haskey(pm_gen, \"source_id\")\n _get_name = d -> strip(string(d[\"source_id\"][1]) * \"-\" * string(d[\"source_id\"][2]) * \"-\" * string(d[\"index\"]))\n end\n\n gen_name = _get_name(pm_gen)\n\n bus = bus_number_to_bus[pm_gen[\"gen_bus\"]]\n pm_gen[\"fuel\"] = get(pm_gen, \"fuel\", \"OTHER\")\n pm_gen[\"type\"] = get(pm_gen, \"type\", \"OT\")\n @debug \"Found generator\" gen_name bus pm_gen[\"fuel\"] pm_gen[\"type\"]\n\n gen_type = get_generator_type(pm_gen[\"fuel\"], pm_gen[\"type\"], genmap)\n if gen_type == ThermalStandard\n generator = make_thermal_gen(gen_name, pm_gen, bus)\n elseif gen_type == HydroDispatch\n generator = make_hydro_gen(gen_name, pm_gen, bus)\n elseif gen_type == RenewableDispatch\n generator = make_renewable_dispatch(gen_name, pm_gen, bus)\n elseif gen_type == RenewableFix\n generator = make_renewable_fix(gen_name, pm_gen, bus)\n elseif gen_type == GenericBattery\n @warn \"Skipping GenericBattery\"\n continue\n # TODO\n #generator = make_generic_battery(gen_name, pm_gen, bus)\n else\n @error \"Skipping unsupported generator\" gen_type\n continue\n end\n\n add_component!(sys, generator; skip_validation=SKIP_PM_VALIDATION)\n end\nend\n\nfunction make_branch(name, d, bus_f, bus_t)\n primary_shunt = d[\"b_fr\"]\n alpha = d[\"shift\"]\n branch_type = get_branch_type(d[\"tap\"], alpha)\n\n if d[\"transformer\"]\n if branch_type == Line\n throw(DataFormatError(\"Data is mismatched; this cannot be a line. $d\"))\n elseif branch_type == Transformer2W\n value = make_transformer_2w(name, d, bus_f, bus_t)\n elseif branch_type == TapTransformer\n value = make_tap_transformer(name, d, bus_f, bus_t)\n elseif branch_type == PhaseShiftingTransformer\n value = make_phase_shifting_transformer(name, d, bus_f, bus_t, alpha)\n else\n error(\"Unsupported branch type $branch_type\")\n end\n else\n # The get_branch_type() logic doesn't work for this data.\n # tap can be 1.0 for this data.\n value = make_line(name, d, bus_f, bus_t)\n end\n\n return value\nend\n\nfunction make_line(name, d, bus_f, bus_t)\n pf = get(d, \"pf\", 0.0)\n qf = get(d, \"qf\", 0.0)\n\n return Line(;\n name=name,\n available=Bool(d[\"br_status\"]),\n activepower_flow = pf,\n reactivepower_flow = qf,\n arc=Arc(bus_f, bus_t),\n r=d[\"br_r\"],\n x=d[\"br_x\"],\n b=(from=d[\"b_fr\"], to=d[\"b_to\"]),\n rate=d[\"rate_a\"],\n anglelimits=(min=d[\"angmin\"], max=d[\"angmax\"]),\n )\nend\n\nfunction make_transformer_2w(name, d, bus_f, bus_t)\n pf = get(d, \"pf\", 0.0)\n qf = get(d, \"qf\", 0.0)\n return Transformer2W(;\n name=name,\n available=Bool(d[\"br_status\"]),\n activepower_flow = pf,\n reactivepower_flow = qf,\n arc=Arc(bus_f, bus_t),\n r=d[\"br_r\"],\n x=d[\"br_x\"],\n primaryshunt=d[\"b_fr\"], # TODO: which b ??\n rate=d[\"rate_a\"],\n )\nend\n\nfunction make_tap_transformer(name, d, bus_f, bus_t)\n pf = get(d, \"pf\", 0.0)\n qf = get(d, \"qf\", 0.0)\n return TapTransformer(;\n name=name,\n available=Bool(d[\"br_status\"]),\n activepower_flow = pf,\n reactivepower_flow = qf,\n arc=Arc(bus_f, bus_t),\n r=d[\"br_r\"],\n x=d[\"br_x\"],\n tap=d[\"tap\"],\n primaryshunt=d[\"b_fr\"], # TODO: which b ??\n rate=d[\"rate_a\"],\n )\nend\n\nfunction make_phase_shifting_transformer(name, d, bus_f, bus_t, alpha)\n pf = get(d, \"pf\", 0.0)\n qf = get(d, \"qf\", 0.0)\n return PhaseShiftingTransformer(;\n name=name,\n available=Bool(d[\"br_status\"]),\n activepower_flow = pf,\n reactivepower_flow = qf,\n arc=Arc(bus_f, bus_t),\n r=d[\"br_r\"],\n x=d[\"br_x\"],\n tap=d[\"tap\"],\n primaryshunt=d[\"b_fr\"], # TODO: which b ??\n α=alpha,\n rate=d[\"rate_a\"],\n )\nend\n\nfunction read_branch!(sys::System, data, bus_number_to_bus::Dict{Int, Bus}; kwargs...)\n @info \"Reading branch data\"\n if !haskey(data, \"branch\")\n @info \"There is no Branch data in this file\"\n return\n end\n\n _get_name = get(kwargs, :branch_name_formatter, _get_pm_dict_name)\n\n for (d_key, d) in data[\"branch\"]\n d[\"name\"] = get(d, \"name\", d_key)\n name = _get_name(d)\n bus_f = bus_number_to_bus[d[\"f_bus\"]]\n bus_t = bus_number_to_bus[d[\"t_bus\"]]\n value = make_branch(name, d, bus_f, bus_t)\n\n add_component!(sys, value; skip_validation=SKIP_PM_VALIDATION)\n end\nend\n\nfunction make_dcline(name, d, bus_f, bus_t)\n return HVDCLine(;\n name=name,\n available=Bool(d[\"br_status\"]),\n activepower_flow = get(d, \"pf\", 0.0),\n arc=Arc(bus_f, bus_t),\n activepowerlimits_from=(min=d[\"pminf\"] , max=d[\"pmaxf\"]),\n activepowerlimits_to=(min=d[\"pmint\"], max=d[\"pmaxt\"]),\n reactivepowerlimits_from=(min=d[\"qminf\"], max=d[\"qmaxf\"]),\n reactivepowerlimits_to=(min=d[\"qmint\"], max=d[\"qmaxt\"]),\n loss=(l0=d[\"loss0\"], l1 =d[\"loss1\"]),\n )\nend\n\nfunction read_dcline!(sys::System, data, bus_number_to_bus::Dict{Int, Bus}; kwargs...)\n @info \"Reading DC Line data\"\n if !haskey(data, \"dcline\")\n @info \"There is no DClines data in this file\"\n return\n end\n\n _get_name = get(kwargs, :branch_name_formatter, _get_pm_dict_name)\n\n for (d_key, d) in data[\"dcline\"]\n d[\"name\"] = get(d, \"name\", d_key)\n name = _get_name(d)\n bus_f = bus_number_to_bus[d[\"f_bus\"]]\n bus_t = bus_number_to_bus[d[\"t_bus\"]]\n\n dcline = make_dcline(name, d, bus_f, bus_t)\n add_component!(sys, dcline, skip_validation=SKIP_PM_VALIDATION)\n end\nend\n\nfunction make_shunt(name, d, bus)\n return FixedAdmittance(;\n name=name,\n available=Bool(d[\"status\"]),\n bus=bus,\n Y=(-d[\"gs\"] + d[\"bs\"]im),\n )\nend\n\nfunction read_shunt!(sys::System, data, bus_number_to_bus::Dict{Int, Bus}; kwargs...)\n @info \"Reading branch data\"\n if !haskey(data, \"shunt\")\n @info \"There is no shunt data in this file\"\n return\n end\n\n _get_name = get(kwargs, :shunt_name_formatter, _get_pm_dict_name)\n\n for (d_key, d) in data[\"shunt\"]\n d[\"name\"] = get(d, \"name\", d_key)\n name = _get_name(d)\n bus = bus_number_to_bus[d[\"shunt_bus\"]]\n shunt = make_shunt(name, d, bus)\n\n add_component!(sys, shunt; skip_validation=SKIP_PM_VALIDATION)\n end\nend\n", "meta": {"hexsha": "136e9dc58d2ae7f240a1428e349e4b56043b3ed9", "size": 18227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parsers/pm2ps_parser.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PowerSystems.jl-bcd98974-b02a-5e2f-9ee0-a103f5c450dd", "max_stars_repo_head_hexsha": "800f9c29b4522a0ff402417600970edb91fbf4e2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-17T03:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-17T03:18:59.000Z", "max_issues_repo_path": "src/parsers/pm2ps_parser.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PowerSystems.jl-bcd98974-b02a-5e2f-9ee0-a103f5c450dd", "max_issues_repo_head_hexsha": "800f9c29b4522a0ff402417600970edb91fbf4e2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parsers/pm2ps_parser.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PowerSystems.jl-bcd98974-b02a-5e2f-9ee0-a103f5c450dd", "max_forks_repo_head_hexsha": "800f9c29b4522a0ff402417600970edb91fbf4e2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7543554007, "max_line_length": 140, "alphanum_fraction": 0.5819937455, "num_tokens": 4965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19953807839114804}} {"text": "\n\"\"\"\n`module JAC.DoubleAutoIonization` \n ... a submodel of JAC that contains all methods for computing double Auger and autoionization amplitudes and rates.\n\"\"\"\nmodule DoubleAutoIonization\n\n using Printf, JAC, ..AngularMomentum, ..AtomicState, ..AutoIonization, ..Basics, ..ManyElectron, ..TableStrings\n\n\n \"\"\"\n `struct DoubleAutoIonization.Settings` ... defines a type for the settings in estimating double-Auger and autoionization rates.\n\n + green ::Array{GreenChannel,1} ... Precalculated and user-specified Green function of the ion.\n + NoEnergySharings ::Int64 ... Number of energy sharings that are used in the computations for each line.\n + printBefore ::Bool ... True, if all energies and lines are printed before their evaluation.\n + minAugerEnergy ::Float64 ... Minimum energy of free (Auger) electrons to be included.\n + maxAugerEnergy ::Float64 ... Maximum energy of free (Auger) electrons to be included.\n + maxKappa ::Int64 ... Maximum kappa value of partial waves to be included.\n + operator ::AbstractEeInteraction ... Auger operator that is to be used for evaluating the Auger amplitudes: \n allowed values are: CoulombInteraction(), BreitInteraction(), ...\n + lineSelection ::LineSelection ... Specifies the selected levels, if any.\n \"\"\"\n struct Settings\n green ::Array{GreenChannel,1}\n NoEnergySharings ::Int64 \n printBefore ::Bool \n minAugerEnergy ::Float64\n maxAugerEnergy ::Float64\n maxKappa ::Int64 \n operator ::AbstractEeInteraction\n lineSelection ::LineSelection \n end \n\n\n \"\"\"\n `DoubleAutoIonization.Settings()` ... constructor for the default values of DoubleAutoIonization line computations\n \"\"\"\n function Settings()\n Settings(GreenChannel[], 0, false, 0., 10e5, 100, CoulombInteraction(), LineSelection())\n end\n\n\n # `Base.show(io::IO, settings::DoubleAutoIonization.Settings)` ... prepares a proper printout of the variable settings::DoubleAutoIonization.Settings.\n function Base.show(io::IO, settings::DoubleAutoIonization.Settings) \n println(io, \"green: (settings.green) \")\n println(io, \"NoEnergySharings: $(settings.NoEnergySharings) \")\n println(io, \"printBefore: $(settings.printBefore) \")\n println(io, \"minAugerEnergy: $(settings.minAugerEnergy) \")\n println(io, \"maxAugerEnergy: $(settings.maxAugerEnergy) \")\n println(io, \"maxKappa: $(settings.maxKappa) \")\n println(io, \"operator: $(settings.operator) \")\n println(io, \"lineSelection: $(settings.lineSelection) \")\n end\n\n\n \"\"\"\n `struct DoubleAutoIonization.ReducedChannel` \n ... defines a type for a DoubleAutoIonization (reduced) channel to help characterize a scattering (continuum) state of many \n electron-states with two free electrons.\n\n + energy1 ::Float64 ... energy of the partial wave_1\n + kappa1 ::Int64 ... partial-wave of the free electron_1\n + phase1 ::Float64 ... phase of the partial wave_1\n + xSymmetry ::LevelSymmetry ... angular momentum and parity after coupling electron1.\n + energy2 ::Float64 ... energy of the partial wave_2\n + kappa2 ::Int64 ... partial-wave of the free electron_2\n + phase2 ::Float64 ... phase of the partial wave_2\n + amplitude ::Complex{Float64} ... Auger amplitude associated with the given channel.\n \"\"\"\n struct ReducedChannel\n energy1 ::Float64 \n kappa1 ::Int64 \n phase1 ::Float64\n xSymmetry ::LevelSymmetry \n energy2 ::Float64 \n kappa2 ::Int64 \n phase2 ::Float64 \n amplitude ::Complex{Float64}\n end\n\n\n # `Base.show(io::IO, channel::DoubleAutoIonization.ReducedChannel)` \n # ... prepares a proper printout of the variable cannel::DoubleAutoIonization.ReducedChannel.\n function Base.show(io::IO, channel::DoubleAutoIonization.ReducedChannel) \n ## sa = \"reduced DA channel for J^P=(channel.tSymmetry) with \" * \n ## \"kappa1=$(channel.kappa1), energy1=$(channel.energy1), phase1=$(channel.phase1), \" *\n ## \"kappa2=$(channel.kappa2), energy2=$(channel.energy2), phase2=$(channel.phase2), amp=$(channel.amplitude) \"\n ## println(io, sa)\n println(io, \"multipole: $(channel.multipole) \")\n println(io, \"gauge: $(channel.gauge) \")\n println(io, \"omega: $(channel.omega) \")\n println(io, \"energy1: $(channel.energy1) \")\n println(io, \"kappa1: $(channel.kappa1) \")\n println(io, \"phase1: $(channel.phase1) \")\n println(io, \"xSymmetry: $(channel.xSymmetry) \")\n println(io, \"energy2: $(channel.energy2) \")\n println(io, \"kappa2: $(channel.kappa2) \")\n println(io, \"phase2: $(channel.phase2) \")\n println(io, \"amplitude: $(channel.amplitude) \")\n end\n\n\n \"\"\"\n `struct DoubleAutoIonization.Sharing` \n ... defines a type for a DoubleAutoIonization sharing to help characterize energy sharing between the two emitted electrons.\n\n + epsilon1 ::Float64 ... Energy of (free) electron 1.\n + epsilon2 ::Float64 ... Energy of (free) electron 2.\n + weight ::Float64 ... Gauss-Lengendre weight of this sharing for energy-integrated quantities.\n + differentialRate ::EmProperty ... differential cross section of this energy sharing.\n + channels ::Array{DoubleAutoIonization.ReducedChannel,1} ... List of DoubleAutoIonization (reduced) channels of this line.\n \"\"\"\n struct Sharing\n epsilon1 ::Float64\n epsilon2 ::Float64\n weight ::Float64 \n differentialRate ::EmProperty\n channels ::Array{DoubleAutoIonization.ReducedChannel,1}\n end\n\n\n # `Base.show(io::IO, sharing::DoubleAutoIonization.Sharing)` ... prepares a proper printout of the variable sharing::DoubleAutoIonization.Sharing.\n function Base.show(io::IO, sharing::DoubleAutoIonization.Sharing) \n println(io, \"epsilon1: $(sharing.epsilon1) \")\n println(io, \"epsilon2: $(sharing.epsilon2) \")\n println(io, \"differentialCs: $(sharing.differentialCs) \")\n println(io, \"channels: $(sharing.channels) \")\n end\n\n\n \"\"\"\n `struct DoubleAutoIonization.Line` ... defines a type for a double Auger line that includes sharings and their reduced amplitudes.\n\n + initialLevel ::Level ... initial-(state) level\n + finalLevel ::Level ... final-(state) level\n + totalRate ::EmProperty ... Total rate of this line.\n + sharings ::Array{DoubleAutoIonization.Sharing,1} ... List of DoubleAutoIonization sharings of this line.\n \"\"\"\n struct Line\n initialLevel ::Level\n finalLevel ::Level\n totalRate ::EmProperty\n sharings ::Array{DoubleAutoIonization.Sharing,1}\n end \n\n\n # `Base.show(io::IO, line::DoubleAutoIonization.Line)` ... prepares a proper printout of the variable line::DoubleAutoIonization.Line.\n function Base.show(io::IO, line::DoubleAutoIonization.Line) \n println(io, \"initialLevel: $(line.initialLevel) \")\n println(io, \"finalLevel: $(line.finalLevel) \")\n println(io, \"totalRate: $(line.totalRate) \")\n println(io, \"sharings: $(line.sharings) \")\n end\n\n\n \"\"\"\n `DoubleAutoIonization.computeAmplitudesProperties(line::DoubleAutoIonization.Line, grid::Radial.Grid, settings::DoubleAutoIonization.Settings)` \n ... to compute all amplitudes and properties of the given line; a line::DoubleAutoIonization.Line is returned for which the amplitudes \n and properties have now been evaluated.\n \"\"\"\n function computeAmplitudesProperties(line::DoubleAutoIonization.Line, grid::Radial.Grid, settings::DoubleAutoIonization.Settings)\n newSharings = DoubleAutoIonization.Sharing[]\n for sharing in line.sharings\n newChannels = DoubleAutoIonization.ReducedChannel[]\n for ch in sharing.channels\n # Generate a continuum orbital\n phase = 1.3\n amplitude = 1.0im \n push!( newChannels, ReducedChannel(ch.energy1, ch.kappa1, phase, ch.xSymmetry, ch.energy2, ch.kappa2, phase, amplitude) )\n end\n # Calculate the differential rate \n diffRate = EmProperty(-1., -1.)\n push!( newSharings, DoubleAutoIonization.Sharing(sharing.epsilon1, sharing.epsilon2, sharing.weight, diffRate, newChannels) )\n end\n # Calculate the total rate\n totalRate = EmProperty(-1., -1.)\n line = DoubleAutoIonization.Line(line.initialLevel, line.finalLevel, totalRate, newSharings)\n return( line )\n end\n\n\n \"\"\"\n `DoubleAutoIonization.computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, grid::Radial.Grid, \n settings::DoubleAutoIonization.Settings; output=true)` \n ... to compute the double-Auger transition amplitudes and all properties as requested by the given settings. A list of \n lines::Array{DoubleAutoIonization.Lines} is returned.\n \"\"\"\n function computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, grid::Radial.Grid, \n settings::DoubleAutoIonization.Settings; output=true)\n println(\"\")\n printstyled(\"DoubleAutoIonization.computeLines(): The computation of double-Auger rates starts now ... \\n\", color=:light_green)\n printstyled(\"----------------------------------------------------------------------------------------- \\n\", color=:light_green)\n println(\"\")\n #\n lines = DoubleAutoIonization.determineLines(finalMultiplet, initialMultiplet, settings)\n # Display all selected lines before the computations start\n if settings.printBefore DoubleAutoIonization.displayLines(lines) end\n # Calculate all amplitudes and requested properties\n newLines = DoubleAutoIonization.Line[]\n for line in lines\n newLine = DoubleAutoIonization.computeAmplitudesProperties(line, grid, settings) \n push!( newLines, newLine)\n end\n # Print all results to screen\n DoubleAutoIonization.displayTotalRates(stdout, lines, settings)\n DoubleAutoIonization.displayDifferentialRates(stdout, lines, settings)\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary DoubleAutoIonization.displayTotalRates(iostream, lines, settings)\n DoubleAutoIonization.displayDifferentialRates(iostream, lines, settings) end\n #\n if output return( lines )\n else return( nothing )\n end\n end\n\n\n \"\"\"\n `DoubleAutoIonization.determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, settings::DoubleAutoIonization.Settings)` \n ... to determine a list of DoubleAutoIonization.Line's for transitions between levels from the initial- and final-state multiplets, \n and by taking into account the particular selections and settings for this computation; an Array{DoubleAutoIonization.Line,1} is \n returned. Apart from the level specification and sharing, all physical properties are set to zero during the initialization process.\n \"\"\"\n function determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, settings::DoubleAutoIonization.Settings)\n lines = DoubleAutoIonization.Line[]\n for iLevel in initialMultiplet.levels\n for fLevel in finalMultiplet.levels\n if Basics.selectLevelPair(iLevel, fLevel, settings.lineSelection)\n energy = iLevel.energy - fLevel.energy\n if energy < settings.minAugerEnergy || energy > settings.maxAugerEnergy continue end \n sharings = DoubleAutoIonization.determineSharingsAndChannels(fLevel, iLevel, energy, settings) \n push!( lines, DoubleAutoIonization.Line(iLevel, fLevel, EmProperty(0., 0.,), sharings) )\n end\n end\n end\n return( lines )\n end\n\n\n \"\"\"\n `DoubleAutoIonization.determineSharingsAndChannels(finalLevel::Level, initialLevel::Level, energy::Float64, settings::DoubleAutoIonization.Settings)` \n ... to determine a list of DoubleAutoIonization Sharing's and Channel's for a transitions from the initial to final level and by taking into \n account the particular settings of for this computation; an Array{DoubleAutoIonization.Sharing,1} is returned.\n \"\"\"\n function determineSharingsAndChannels(finalLevel::Level, initialLevel::Level, energy::Float64, settings::DoubleAutoIonization.Settings)\n sharings = DoubleAutoIonization.Sharing[]; eSharings = Basics.determineEnergySharings(energy, settings.NoEnergySharings) \n for es in eSharings\n epsilon1 = es[1]; epsilon2 = es[2]; weight = es[3] \n channels = DoubleAutoIonization.ReducedChannel[]; \n symi = LevelSymmetry(initialLevel.J, initialLevel.parity); symf = LevelSymmetry(finalLevel.J, finalLevel.parity) \n couplings = AngularMomentum.allowedDoubleKappaCouplingSequence(symf, symi, settings.maxKappa)\n for coupling in couplings\n push!(channels, ReducedChannel(epsilon1, coupling[1], 0., coupling[2], epsilon2, coupling[3], 0., Complex(0.)) ) \n end\n push!(sharings, DoubleAutoIonization.Sharing(epsilon1, epsilon2, weight, EmProperty(0., 0.), channels) )\n end\n return( sharings ) \n end\n\n\n \"\"\"\n `DoubleAutoIonization.displayDifferentialRates(stream::IO, lines::Array{DoubleAutoIonization.Line,1}, settings::DoubleAutoIonization.Settings)` \n ... to display all differential rates, etc. of the selected lines. A neat table is printed but nothing is returned otherwise.\n \"\"\"\n function displayDifferentialRates(stream::IO, lines::Array{DoubleAutoIonization.Line,1}, settings::DoubleAutoIonization.Settings)\n #\n # First, print lines and sharings\n nx = 128\n println(stream, \" \")\n println(stream, \" Energy-differential rates of selected double-Auger lines:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\"; na=0); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(18, \"i--J^P--f\"; na=4); sb = sb * TableStrings.hBlank(22)\n sa = sa * TableStrings.flushleft(38, \"Energies (all in \" * TableStrings.inUnits(\"energy\") * \")\"; na=3); \n sb = sb * TableStrings.flushleft(38, \" i -- f epsilon_1 epsilon_2\"; na=3)\n sa = sa * TableStrings.center(14, \"Weight\"; na=0); sb = sb * TableStrings.hBlank(14)\n sa = sa * TableStrings.center(34, \"Cou -- diff. rate -- Bab\"; na=3) \n sb = sb * TableStrings.center(34, TableStrings.inUnits(\"rate\") * \" \" * \n TableStrings.inUnits(\"rate\"); na=3)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4) \n energy = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", energy)) * \" \"\n #\n for (is, sharing) in enumerate(line.sharings)\n if is == 1 sb = sa else sb = TableStrings.hBlank( length(sa) ) end\n sb = sb * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", sharing.epsilon1)) * \" \"\n sb = sb * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", sharing.epsilon2)) * \" \"\n sb = sb * @sprintf(\"%.4e\", sharing.weight) * \" \"\n sb = sb * @sprintf(\"%.5e\", Defaults.convertUnits(\"rate: from atomic\", sharing.differentialRate.Coulomb)) * \" \"\n sb = sb * @sprintf(\"%.5e\", Defaults.convertUnits(\"rate: from atomic\", sharing.differentialRate.Babushkin)) * \" \"\n println(stream, sb )\n end\n end\n println(stream, \" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\n\n \"\"\"\n `DoubleAutoIonization.displayLines(lines::Array{DoubleAutoIonization.Line,1})` \n ... to display a list of lines, sharings and channels that have been selected due to the prior settings. A neat table \n of all selected transitions and energies is printed but nothing is returned otherwise.\n \"\"\"\n function displayLines(lines::Array{DoubleAutoIonization.Line,1})\n #\n # First, print lines and sharings\n nx = 82\n println(\" \")\n println(\" Selected double-Auger lines & sharings:\")\n println(\" \")\n println(\" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\"; na=0); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(18, \"i--J^P--f\"; na=4); sb = sb * TableStrings.hBlank(22)\n sa = sa * TableStrings.flushleft(54, \"Energies (all in )\" * TableStrings.inUnits(\"energy\") * \")\"; na=5); \n sb = sb * TableStrings.flushleft(54, \" i -- f epsilon_1 epsilon_2\"; na=5)\n println(sa); println(sb); println(\" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4) \n energy = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", energy)) * \" \"\n #\n for (is, sharing) in enumerate(line.sharings)\n if is == 1 sb = sa else sb = TableStrings.hBlank( length(sa) ) end\n sb = sb * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", sharing.epsilon1)) * \" \"\n sb = sb * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", sharing.epsilon2)) * \" \"\n println( sb )\n end\n end\n println(\" \", TableStrings.hLine(nx))\n #\n #\n # Second, print lines and channles\n nx = 123\n println(\" \")\n println(\" Selected photo-double ionization lines & channels:\")\n println(\" \")\n println(\" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\"; na=0); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(18, \"i--J^P--f\"; na=4); sb = sb * TableStrings.hBlank(22)\n sa = sa * TableStrings.flushleft(77, \"Channels (all energies in \" * TableStrings.inUnits(\"energy\") * \")\" ; na=5); \n sb = sb * TableStrings.flushleft(77, \"(epsilon, kappa)_1 --> J^P_x --> (epsilon, kappa)_2 --> J^P_t = J^P_i\"; na=5)\n println(sa); println(sb); println(\" \", TableStrings.hLine(nx)) \n #\n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4)\n for (ic, ch) in enumerate(line.sharings[1].channels)\n if ic == 1 sb = sa else sb = TableStrings.hBlank( length(sa) ) end\n skappa1 = \" \" * string(ch.kappa1); skappa2 = \" \" * string(ch.kappa2); sxsym = \" \" * string(ch.xSymmetry)\n sb = sb * \" (\" * @sprintf(\"%.3e\", Defaults.convertUnits(\"energy: from atomic\", ch.energy1)) * \", \" * skappa1[end-2:end] * \") -->\"\n sb = sb * sxsym[end-8:end] * \" --> \"\n sb = sb * \" (\" * @sprintf(\"%.3e\", Defaults.convertUnits(\"energy: from atomic\", ch.energy2)) * \", \" * skappa2[end-2:end] * \") --> \"\n sb = sb * string(isym) \n println( sb )\n end\n end\n println(\" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\n\n \"\"\"\n `DoubleAutoIonization.displayTotalRates(stream::IO, lines::Array{DoubleAutoIonization.Line,1}, settings::DoubleAutoIonization.Settings)` \n ... to display all total rates, etc. of the selected lines. A neat table is printed but nothing is returned otherwise.\n \"\"\"\n function displayTotalRates(stream::IO, lines::Array{DoubleAutoIonization.Line,1}, settings::DoubleAutoIonization.Settings)\n #\n # First, print lines and sharings\n nx = 88\n println(stream, \" \")\n println(stream, \" Total rates of selected double-Auger lines:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\"; na=0); sb = sb * TableStrings.hBlank(18)\n sa = sa * TableStrings.center(18, \"i--J^P--f\"; na=2); sb = sb * TableStrings.hBlank(21)\n sa = sa * TableStrings.center(12, \"i--Energy--f\"; na=3) \n sb = sb * TableStrings.center(12,TableStrings.inUnits(\"energy\"); na=3)\n sa = sa * TableStrings.center(30, \"Cou -- total rate -- Bab\"; na=4) \n sb = sb * TableStrings.center(30, TableStrings.inUnits(\"rate\") * \" \" * \n TableStrings.inUnits(\"rate\"); na=3)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \"\"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4) \n energy = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", energy)) * \" \"\n #\n sb = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"rate: from atomic\", line.totalRate.Coulomb)) * \" \"\n sb = sb * @sprintf(\"%.5e\", Defaults.convertUnits(\"rate: from atomic\", line.totalRate.Babushkin)) * \" \"\n println(stream, sb )\n end\n println(stream, \" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\nend # module\n", "meta": {"hexsha": "d017a015c515ac58ae72240aad6f3907f352d16b", "size": 25093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-DoubleAutoIonization.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2019-03-11T11:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:33:28.000Z", "max_issues_repo_path": "src/module-DoubleAutoIonization.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-04-02T22:04:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T06:21:57.000Z", "max_forks_repo_path": "src/module-DoubleAutoIonization.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T12:51:19.000Z", "avg_line_length": 59.7452380952, "max_line_length": 155, "alphanum_fraction": 0.5809986849, "num_tokens": 5856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19943325222513325}} {"text": "\nstruct FaceToCellGlue{A,B,C,D} <: GridapType\n face_to_bgface::A\n bgface_to_lcell::B\n face_to_cell::Vector{Int32}\n face_to_lface::Vector{Int8}\n face_to_lcell::Vector{Int8}\n face_to_ftype::C\n cell_to_ctype::D\n cell_to_lface_to_pindex::Table{Int8,Vector{Int8},Vector{Int32}}\n ctype_to_lface_to_ftype::Vector{Vector{Int8}}\nend\n\nfunction FaceToCellGlue(\n topo::GridTopology,\n cell_grid::Grid,\n face_grid::Grid,\n face_to_bgface::AbstractVector,\n bgface_to_lcell::AbstractVector)\n\n D = num_cell_dims(cell_grid)\n cD = num_cell_dims(face_grid)\n bgface_to_cells = get_faces(topo,cD,D)\n cell_to_bgfaces = get_faces(topo,D,cD)\n cell_to_lface_to_pindex = Table(get_cell_permutations(topo,cD))\n\n bgface_to_cell = lazy_map(getindex,bgface_to_cells, bgface_to_lcell)\n bgface_to_lface = find_local_index(bgface_to_cell, cell_to_bgfaces)\n\n face_to_cell = collect(Int32,lazy_map(Reindex(bgface_to_cell), face_to_bgface))\n face_to_lface = collect(Int8,lazy_map(Reindex(bgface_to_lface), face_to_bgface))\n face_to_lcell = collect(Int8,lazy_map(Reindex(bgface_to_lcell), face_to_bgface))\n\n f = (p)->fill(Int8(UNSET),num_faces(p,cD))\n ctype_to_lface_to_ftype = map( f, get_reffes(cell_grid) )\n face_to_ftype = get_cell_type(face_grid)\n cell_to_ctype = get_cell_type(cell_grid)\n\n _fill_ctype_to_lface_to_ftype!(\n ctype_to_lface_to_ftype,\n face_to_cell,\n face_to_lface,\n face_to_ftype,\n cell_to_ctype)\n\n FaceToCellGlue(\n face_to_bgface,\n bgface_to_lcell,\n face_to_cell,\n face_to_lface,\n face_to_lcell,\n face_to_ftype,\n cell_to_ctype,\n cell_to_lface_to_pindex,\n ctype_to_lface_to_ftype)\nend\n\nfunction _fill_ctype_to_lface_to_ftype!(\n ctype_to_lface_to_ftype,\n face_to_cell,\n face_to_lface,\n face_to_ftype,\n cell_to_ctype)\n for (face, cell) in enumerate(face_to_cell)\n ctype = cell_to_ctype[cell]\n lface = face_to_lface[face]\n ftype = face_to_ftype[face]\n ctype_to_lface_to_ftype[ctype][lface] = ftype\n end\nend\n\nfunction get_children(n::TreeNode, a::FaceToCellGlue)\n (\n similar_tree_node(n,a.face_to_cell),\n similar_tree_node(n,a.face_to_lface),\n similar_tree_node(n,a.face_to_lcell),\n similar_tree_node(n,a.face_to_ftype),\n similar_tree_node(n,a.cell_to_ctype),\n similar_tree_node(n,a.cell_to_lface_to_pindex),\n similar_tree_node(n,a.ctype_to_lface_to_ftype)\n )\nend\n\n\"\"\"\n\"\"\"\nstruct BoundaryTriangulation{Dc,Dp,A,B} <: Triangulation{Dc,Dp}\n trian::A\n glue::B\n\n function BoundaryTriangulation(\n trian::BodyFittedTriangulation,\n glue::FaceToCellGlue)\n\n Dc = num_cell_dims(trian)\n Dp = num_point_dims(trian)\n A = typeof(trian)\n B = typeof(glue)\n new{Dc,Dp,A,B}(trian,glue)\n end\nend\n\nfunction Boundary(args...;kwargs...)\n BoundaryTriangulation(args...;kwargs...)\nend\n\n# Constructors\n\n\"\"\"\n BoundaryTriangulation(model::DiscreteModel,face_to_mask::Vector{Bool})\n BoundaryTriangulation(model::DiscreteModel)\n\"\"\"\nfunction BoundaryTriangulation(\n model::DiscreteModel,\n face_to_bgface::AbstractVector{<:Integer},\n bgface_to_lcell::AbstractVector{<:Integer})\n\n D = num_cell_dims(model)\n topo = get_grid_topology(model)\n bgface_grid = Grid(ReferenceFE{D-1},model)\n\n face_grid = view(bgface_grid,face_to_bgface)\n cell_grid = get_grid(model)\n glue = FaceToCellGlue(topo,cell_grid,face_grid,face_to_bgface,bgface_to_lcell)\n trian = BodyFittedTriangulation(model,face_grid,face_to_bgface)\n\n BoundaryTriangulation(trian,glue)\nend\n\nfunction BoundaryTriangulation(\n model::DiscreteModel,\n face_to_bgface::AbstractVector{<:Integer})\n BoundaryTriangulation(model,face_to_bgface,Fill(1,num_facets(model)))\nend\n\nfunction BoundaryTriangulation(\n model::DiscreteModel,\n bgface_to_mask::AbstractVector{Bool},\n bgface_to_lcell::AbstractVector{<:Integer})\n\n face_to_bgface = findall(bgface_to_mask)\n BoundaryTriangulation(model,face_to_bgface,bgface_to_lcell)\nend\n\nfunction BoundaryTriangulation(\n model::DiscreteModel, bgface_to_mask::AbstractVector{Bool}, lcell::Integer=1)\n BoundaryTriangulation(model,bgface_to_mask, Fill(lcell,num_facets(model)) )\nend\n\n\"\"\"\n BoundaryTriangulation(model::DiscreteModel,labeling::FaceLabeling;tags::Vector{Int})\n BoundaryTriangulation(model::DiscreteModel,labeling::FaceLabeling;tags::Vector{String})\n BoundaryTriangulation(model::DiscreteModel,labeling::FaceLabeling;tag::Int)\n BoundaryTriangulation(model::DiscreteModel,labeling::FaceLabeling;tag::String)\n\"\"\"\nfunction BoundaryTriangulation(model::DiscreteModel,labeling::FaceLabeling;tags=nothing)\n D = num_cell_dims(model)\n if tags == nothing\n topo = get_grid_topology(model)\n face_to_mask = get_isboundary_face(topo,D-1)\n else\n face_to_mask = get_face_mask(labeling,tags,D-1)\n end\n BoundaryTriangulation(model,face_to_mask)\nend\n\n\"\"\"\n BoundaryTriangulation(model::DiscreteModel,tags::Vector{Int})\n BoundaryTriangulation(model::DiscreteModel,tags::Vector{String})\n BoundaryTriangulation(model::DiscreteModel,tag::Int)\n BoundaryTriangulation(model::DiscreteModel,tag::String)\n\"\"\"\nfunction BoundaryTriangulation(model::DiscreteModel;tags=nothing)\n labeling = get_face_labeling(model)\n BoundaryTriangulation(model,labeling,tags=tags)\nend\n\nfunction BoundaryTriangulation(rtrian::Triangulation,args...;kwargs...)\n rmodel = get_active_model(rtrian)\n dtrian = BoundaryTriangulation(rmodel,args...;kwargs...)\n CompositeTriangulation(rtrian,dtrian)\nend\n\n# API\n\nget_background_model(t::BoundaryTriangulation) = get_background_model(t.trian)\nget_grid(t::BoundaryTriangulation) = get_grid(t.trian)\nget_glue(t::BoundaryTriangulation{D},::Val{D}) where D = get_glue(t.trian,Val(D))\n\nfunction get_glue(trian::BoundaryTriangulation,::Val{Dp}) where Dp\n model = get_background_model(trian)\n Dm = num_cell_dims(model)\n get_glue(trian,Val(Dp),Val(Dm))\nend\n\nfunction get_glue(trian::BoundaryTriangulation,::Val{Dp},::Val{Dm}) where {Dp,Dm}\n nothing\nend\n\nfunction get_glue(trian::BoundaryTriangulation,::Val{D},::Val{D}) where D\n tface_to_mface = trian.glue.face_to_cell\n face_to_q_vertex_coords = _compute_face_to_q_vertex_coords(trian)\n f(p) = get_shapefuns(LagrangianRefFE(Float64,get_polytope(p),1))\n ftype_to_shapefuns = map( f, get_reffes(trian) )\n face_to_shapefuns = expand_cell_data(ftype_to_shapefuns,trian.glue.face_to_ftype)\n face_s_q = lazy_map(linear_combination,face_to_q_vertex_coords,face_to_shapefuns)\n tface_to_mface_map = face_s_q\n mface_to_tface = nothing\n FaceToFaceGlue(tface_to_mface,tface_to_mface_map,mface_to_tface)\nend\n\nfunction get_facet_normal(trian::BoundaryTriangulation)\n\n glue = trian.glue\n cell_grid = get_grid(get_background_model(trian.trian))\n\n ## Reference normal\n function f(r)\n p = get_polytope(r)\n lface_to_n = get_facet_normal(p)\n lface_to_pindex_to_perm = get_face_vertex_permutations(p,num_cell_dims(p)-1)\n nlfaces = length(lface_to_n)\n lface_pindex_to_n = [ fill(lface_to_n[lface],length(lface_to_pindex_to_perm[lface])) for lface in 1:nlfaces ]\n lface_pindex_to_n\n end\n ctype_lface_pindex_to_nref = map(f, get_reffes(cell_grid))\n face_to_nref = FaceCompressedVector(ctype_lface_pindex_to_nref,glue)\n face_s_nref = lazy_map(constant_field,face_to_nref)\n\n # Inverse of the Jacobian transpose\n cell_q_x = get_cell_map(cell_grid)\n cell_q_Jt = lazy_map(∇,cell_q_x)\n cell_q_invJt = lazy_map(Operation(pinvJt),cell_q_Jt)\n face_q_invJt = lazy_map(Reindex(cell_q_invJt),glue.face_to_cell)\n\n # Change of domain\n D = num_cell_dims(cell_grid)\n glue = get_glue(trian,Val(D))\n face_s_q = glue.tface_to_mface_map\n face_s_invJt = lazy_map(∘,face_q_invJt,face_s_q)\n face_s_n = lazy_map(Broadcasting(Operation(push_normal)),face_s_invJt,face_s_nref)\n Fields.MemoArray(face_s_n)\nend\n\n@inline function push_normal(invJt,n)\n v = invJt⋅n\n m = sqrt(inner(v,v))\n if m < eps()\n return zero(n)\n else\n return v/m\n end\nend\n\nfunction _compute_face_to_q_vertex_coords(trian::BoundaryTriangulation)\n d = num_cell_dims(trian)\n cell_grid = get_grid(get_background_model(trian.trian))\n polytopes = map(get_polytope, get_reffes(cell_grid))\n cell_to_ctype = trian.glue.cell_to_ctype\n ctype_to_lvertex_to_qcoords = map(get_vertex_coordinates, polytopes)\n ctype_to_lface_to_lvertices = map((p)->get_faces(p,d,0), polytopes)\n ctype_to_lface_to_pindex_to_perm = map( (p)->get_face_vertex_permutations(p,d), polytopes)\n\n P = eltype(eltype(ctype_to_lvertex_to_qcoords))\n D = num_components(P)\n T = eltype(P)\n ctype_to_lface_to_pindex_to_qcoords = Vector{Vector{Vector{Point{D,T}}}}[]\n\n for (ctype, lface_to_pindex_to_perm) in enumerate(ctype_to_lface_to_pindex_to_perm)\n lvertex_to_qcoods = ctype_to_lvertex_to_qcoords[ctype]\n lface_to_pindex_to_qcoords = Vector{Vector{Point{D,T}}}[]\n for (lface, pindex_to_perm) in enumerate(lface_to_pindex_to_perm)\n cfvertex_to_lvertex = ctype_to_lface_to_lvertices[ctype][lface]\n nfvertices = length(cfvertex_to_lvertex)\n pindex_to_qcoords = Vector{Vector{Point{D,T}}}(undef,length(pindex_to_perm))\n for (pindex, cfvertex_to_ffvertex) in enumerate(pindex_to_perm)\n ffvertex_to_qcoords = zeros(Point{D,T},nfvertices)\n for (cfvertex, ffvertex) in enumerate(cfvertex_to_ffvertex)\n lvertex = cfvertex_to_lvertex[cfvertex]\n qcoords = lvertex_to_qcoods[lvertex]\n ffvertex_to_qcoords[ffvertex] = qcoords\n end\n pindex_to_qcoords[pindex] = ffvertex_to_qcoords\n end\n push!(lface_to_pindex_to_qcoords,pindex_to_qcoords)\n end\n push!(ctype_to_lface_to_pindex_to_qcoords,lface_to_pindex_to_qcoords)\n end\n\n FaceCompressedVector(ctype_to_lface_to_pindex_to_qcoords,trian.glue)\nend\n\nstruct FaceCompressedVector{T,G<:FaceToCellGlue} <: AbstractVector{T}\n ctype_lface_pindex_to_value::Vector{Vector{Vector{T}}}\n glue::G\nend\n\nBase.size(a::FaceCompressedVector) = (length(a.glue.face_to_cell),)\n\nBase.IndexStyle(::Type{<:FaceCompressedVector}) = IndexLinear()\n\nfunction Base.getindex(a::FaceCompressedVector,face::Integer)\n cell = a.glue.face_to_cell[face]\n ctype = a.glue.cell_to_ctype[cell]\n lface = a.glue.face_to_lface[face]\n p = a.glue.cell_to_lface_to_pindex.ptrs[cell]-1\n pindex = a.glue.cell_to_lface_to_pindex.data[p+lface]\n value = a.ctype_lface_pindex_to_value[ctype][lface][pindex]\n value\nend\n\nfunction get_children(n::TreeNode, a::FaceCompressedVector)\n (similar_tree_node(n,a.ctype_lface_pindex_to_value),similar_tree_node(n,a.glue))\nend\n\nfunction lazy_map(k::Fields.LinearCombinationMap,::Type{T},b::FaceCompressedVector,c::Fill) where T\n d = CompressedArray([c.value,],Fill(1,length(c)))\n lazy_map(k,T,a,b,d)\nend\n\nfunction lazy_map(k::Fields.LinearCombinationMap,::Type{T},b::FaceCompressedVector,c::CompressedArray) where T\n if c.ptrs === b.glue.face_to_ftype || c.ptrs == b.glue.face_to_ftype\n\n ctype_lface_pindex_to_r = Vector{Vector{Vector{T}}}(undef,length(b.ctype_lface_pindex_to_value))\n for (ctype, lface_pindex_to_value) in enumerate(b.ctype_lface_pindex_to_value)\n lface_pindex_to_r = Vector{Vector{T}}(undef,length(lface_pindex_to_value))\n for (lface, pindex_to_value) in enumerate(lface_pindex_to_value)\n pindex_to_r = Vector{T}(undef,length(pindex_to_value))\n ftype = b.glue.ctype_to_lface_to_ftype[ctype][lface]\n if ftype != UNSET\n for (pindex, value) in enumerate(pindex_to_value)\n pindex_to_r[pindex] = k(value,c.values[ftype])\n end\n end\n lface_pindex_to_r[lface] = pindex_to_r\n end\n ctype_lface_pindex_to_r[ctype] = lface_pindex_to_r\n end\n FaceCompressedVector(ctype_lface_pindex_to_r,b.glue)\n\n else\n @notimplemented\n end\nend\n\nfunction lazy_map(k::typeof(evaluate),::Type{T},a::Fill,b::FaceCompressedVector) where T\n @check length(a) == length(b)\n ctype_lface_pindex_to_r = Vector{Vector{Vector{T}}}(undef,length(b.ctype_lface_pindex_to_value))\n for (ctype, lface_pindex_to_value) in enumerate(b.ctype_lface_pindex_to_value)\n lface_pindex_to_r = Vector{Vector{T}}(undef,length(lface_pindex_to_value))\n for (lface, pindex_to_value) in enumerate(lface_pindex_to_value)\n pindex_to_r = Vector{T}(undef,length(pindex_to_value))\n ftype = b.glue.ctype_to_lface_to_ftype[ctype][lface]\n if ftype != UNSET\n for (pindex, value) in enumerate(pindex_to_value)\n pindex_to_r[pindex] = evaluate(a.value,value)\n end\n end\n lface_pindex_to_r[lface] = pindex_to_r\n end\n ctype_lface_pindex_to_r[ctype] = lface_pindex_to_r\n end\n FaceCompressedVector(ctype_lface_pindex_to_r,b.glue)\nend\n\nfunction lazy_map(\n k::typeof(evaluate),\n ::Type{T},\n a::CompressedArray,\n b::FaceCompressedVector) where T\n\n @check length(a) == length(b)\n ctype_lface_pindex_to_r = Vector{Vector{Vector{T}}}(undef,length(b.ctype_lface_pindex_to_value))\n for (ctype, lface_pindex_to_value) in enumerate(b.ctype_lface_pindex_to_value)\n lface_pindex_to_r = Vector{Vector{T}}(undef,length(lface_pindex_to_value))\n for (lface, pindex_to_value) in enumerate(lface_pindex_to_value)\n pindex_to_r = Vector{T}(undef,length(pindex_to_value))\n ftype = b.glue.ctype_to_lface_to_ftype[ctype][lface]\n if ftype != UNSET\n for (pindex, value) in enumerate(pindex_to_value)\n pindex_to_r[pindex] = evaluate(a.values[ctype],value)\n end\n end\n lface_pindex_to_r[lface] = pindex_to_r\n end\n ctype_lface_pindex_to_r[ctype] = lface_pindex_to_r\n end\n FaceCompressedVector(ctype_lface_pindex_to_r,b.glue)\nend\n\nfunction lazy_map(k::typeof(evaluate),::Type{T},b::FaceCompressedVector,a::Fill) where T\n @check length(a) == length(b)\n ctype_lface_pindex_to_r = Vector{Vector{Vector{T}}}(undef,length(b.ctype_lface_pindex_to_value))\n for (ctype, lface_pindex_to_value) in enumerate(b.ctype_lface_pindex_to_value)\n lface_pindex_to_r = Vector{Vector{T}}(undef,length(lface_pindex_to_value))\n for (lface, pindex_to_value) in enumerate(lface_pindex_to_value)\n pindex_to_r = Vector{T}(undef,length(pindex_to_value))\n ftype = b.glue.ctype_to_lface_to_ftype[ctype][lface]\n if ftype != UNSET\n for (pindex, value) in enumerate(pindex_to_value)\n pindex_to_r[pindex] = evaluate(value,a.value)\n end\n end\n lface_pindex_to_r[lface] = pindex_to_r\n end\n ctype_lface_pindex_to_r[ctype] = lface_pindex_to_r\n end\n FaceCompressedVector(ctype_lface_pindex_to_r,b.glue)\nend\n\nfunction lazy_map(k::typeof(evaluate),::Type{T},a::Fill,b::FaceCompressedVector,c::FaceCompressedVector) where T\n if b.glue !== c.glue\n return LazyArray(T,a,b,c)\n end\n @check length(a) == length(b)\n ctype_lface_pindex_to_r = Vector{Vector{Vector{T}}}(undef,length(b.ctype_lface_pindex_to_value))\n for (ctype, lface_pindex_to_value) in enumerate(b.ctype_lface_pindex_to_value)\n lface_pindex_to_r = Vector{Vector{T}}(undef,length(lface_pindex_to_value))\n for (lface, pindex_to_value) in enumerate(lface_pindex_to_value)\n pindex_to_r = Vector{T}(undef,length(pindex_to_value))\n ftype = b.glue.ctype_to_lface_to_ftype[ctype][lface]\n if ftype != UNSET\n for (pindex, bvalue) in enumerate(pindex_to_value)\n cvalue = c.ctype_lface_pindex_to_value[ctype][lface][pindex]\n pindex_to_r[pindex] = evaluate(a.value,bvalue,cvalue)\n end\n end\n lface_pindex_to_r[lface] = pindex_to_r\n end\n ctype_lface_pindex_to_r[ctype] = lface_pindex_to_r\n end\n FaceCompressedVector(ctype_lface_pindex_to_r,b.glue)\nend\n\n", "meta": {"hexsha": "21327297d7985afb11c36da6de67ca4bac4a4cf1", "size": 15468, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Geometry/BoundaryTriangulations.jl", "max_stars_repo_name": "davelee2804/Gridap.jl", "max_stars_repo_head_hexsha": "6082973440241759b15cc9cbbdc132d83153cf8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 390, "max_stars_repo_stars_event_min_datetime": "2019-05-16T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:59:17.000Z", "max_issues_repo_path": "src/Geometry/BoundaryTriangulations.jl", "max_issues_repo_name": "davelee2804/Gridap.jl", "max_issues_repo_head_hexsha": "6082973440241759b15cc9cbbdc132d83153cf8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 576, "max_issues_repo_issues_event_min_datetime": "2019-05-16T20:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:21:35.000Z", "max_forks_repo_path": "src/Geometry/BoundaryTriangulations.jl", "max_forks_repo_name": "davelee2804/Gridap.jl", "max_forks_repo_head_hexsha": "6082973440241759b15cc9cbbdc132d83153cf8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2019-12-30T23:35:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:56:24.000Z", "avg_line_length": 35.6405529954, "max_line_length": 113, "alphanum_fraction": 0.7578226015, "num_tokens": 4659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.19935273291952083}} {"text": "export iauApci13\n\"\"\"\nFor a terrestrial observer, prepare star-independent astrometry\nparameters for transformations between ICRS and geocentric CIRS\ncoordinates. The caller supplies the date, and SOFA models are used\nto predict the Earth ephemeris and CIP/CIO.\n\nThe parameters produced by this function are required in the\nparallax, light deflection, aberration, and bias-precession-nutation\nparts of the astrometric transformation chain.\n\nThis function is part of the International Astronomical Union's\nSOFA (Standards of Fundamental Astronomy) software collection.\n\nStatus: support function.\n\nGiven:\n date1 double TDB as a 2-part...\n date2 double ...Julian Date (Note 1)\n\nReturned:\n astrom iauASTROM* star-independent astrometry parameters:\n pmt double PM time interval (SSB, Julian years)\n eb double[3] SSB to observer (vector, au)\n eh double[3] Sun to observer (unit vector)\n em double distance from Sun to observer (au)\n v double[3] barycentric observer velocity (vector, c)\n bm1 double sqrt(1-|v|^2): reciprocal of Lorenz factor\n bpn double[3][3] bias-precession-nutation matrix\n along double unchanged\n xpl double unchanged\n ypl double unchanged\n sphi double unchanged\n cphi double unchanged\n diurab double unchanged\n eral double unchanged\n refa double unchanged\n refb double unchanged\n eo double* equation of the origins (ERA-GST)\n\nNotes:\n\n 1. The TDB date date1+date2 is a Julian Date, apportioned in any\n convenient way between the two arguments. For example,\n JD(TDB)=2450123.7 could be expressed in any of these ways, among\n others:\n\n date1 date2\n\n 2450123.7 0.0 (JD method)\n 2451545.0 -1421.3 (J2000 method)\n 2400000.5 50123.2 (MJD method)\n 2450123.5 0.2 (date & time method)\n\n The JD method is the most natural and convenient to use in cases\n where the loss of several decimal digits of resolution is\n acceptable. The J2000 method is best matched to the way the\n argument is handled internally and will deliver the optimum\n resolution. The MJD method and the date & time methods are both\n good compromises between resolution and convenience. For most\n applications of this function the choice will not be at all\n critical.\n\n TT can be used instead of TDB without any significant impact on\n accuracy.\n\n 2. All the vectors are with respect to BCRS axes.\n\n 3. In cases where the caller wishes to supply his own Earth\n ephemeris and CIP/CIO, the function iauApci can be used instead\n of the present function.\n\n 4. This is one of several functions that inserts into the astrom\n structure star-independent parameters needed for the chain of\n astrometric transformations ICRS <-> GCRS <-> CIRS <-> observed.\n\n The various functions support different classes of observer and\n portions of the transformation chain:\n\n functions observer transformation\n\n iauApcg iauApcg13 geocentric ICRS <-> GCRS\n iauApci iauApci13 terrestrial ICRS <-> CIRS\n iauApco iauApco13 terrestrial ICRS <-> observed\n iauApcs iauApcs13 space ICRS <-> GCRS\n iauAper iauAper13 terrestrial update Earth rotation\n iauApio iauApio13 terrestrial CIRS <-> observed\n\n Those with names ending in \"13\" use contemporary SOFA models to\n compute the various ephemerides. The others accept ephemerides\n supplied by the caller.\n\n The transformation from ICRS to GCRS covers space motion,\n parallax, light deflection, and aberration. From GCRS to CIRS\n comprises frame bias and precession-nutation. From CIRS to\n observed takes account of Earth rotation, polar motion, diurnal\n aberration and parallax (unless subsumed into the ICRS <-> GCRS\n transformation), and atmospheric refraction.\n\n 5. The context structure astrom produced by this function is used by\n iauAtciq* and iauAticq*.\n\nCalled:\n iauEpv00 Earth position and velocity\n iauPnm06a classical NPB matrix, IAU 2006/2000A\n iauBpn2xy extract CIP X,Y coordinates from NPB matrix\n iauS06 the CIO locator s, given X,Y, IAU 2006\n iauApci astrometry parameters, ICRS-CIRS\n iauEors equation of the origins, given NPB matrix and s\n\nThis revision: 2013 October 9\n\nSOFA release 2018-01-30\n\nCopyright (C) 2018 IAU SOFA Board. See notes at end.\n\"\"\"\nfunction iauApci13(date1::Real, date2::Real)\n # Allocate return value\n ref_astrom = Ref{iauASTROM}(iauASTROM())\n ref_eo = Ref{Float64}(0.0)\n\n ccall((:iauApci13, libsofa_c), Cvoid, \n (Cdouble, Cdouble, Ref{iauASTROM}, Ref{Cdouble}), \n convert(Float64, date1),\n convert(Float64, date2),\n ref_astrom, ref_eo)\n\n return ref_astrom[], ref_eo[]\nend", "meta": {"hexsha": "d3fadb183ea8d2a3a0e51e3ea17935ea3c3d3d72", "size": 4998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/apci13.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_stars_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-12-11T05:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T03:10:26.000Z", "max_issues_repo_path": "src/apci13.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_issues_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-02T00:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T06:42:23.000Z", "max_forks_repo_path": "src/apci13.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_forks_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:41:12.000Z", "avg_line_length": 38.7441860465, "max_line_length": 71, "alphanum_fraction": 0.6878751501, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.199296690589615}} {"text": "# Particle IDs used for testing. The definition is the same as in\n# the Python package 'particle' from the SciKit-HEP group:\n# https://github.com/scikit-hep/particle/blob/master/tests/conftest.py\n\n@enum PDGIDS begin\n # Gauge and Higgs bosons\n Gluon = 21\n Photon = 22\n Z0 = 23\n WMinus = -24\n HiggsBoson = 25\n ZPrime = 32\n # Charged leptons\n Electron = 11\n Positron = -11\n Muon = 13\n AntiMuon = -13\n Tau = 15\n TauPrime = 17\n # Neutrinos\n Nu_e = 12\n NuBar_tau = -16\n # Quarks\n DQuark = 1\n UQuark = 2\n SQuark = 3\n CQuark = 4\n BQuark = 5\n TQuark = 6\n BPrimeQuark = 7 # 4th generation\n TPrimeQuark = 8\n # Quarkonia\n jpsi = 443\n psi_2S = 100443\n Upsilon_1S = 553\n Upsilon_4S = 300553\n # Light hadrons\n Pi0 = 111\n PiPlus = 211\n eta = 221\n eta_prime = 331\n a_0_1450_plus = 10211\n KL = 130\n KS = 310\n KMinus = -321\n rho_770_minus = -213\n phi = 333\n omega = 223\n K1_1270_0 = 10313\n K1_1400_0 = 20313\n rho_1700_0 = 30113\n a2_1320_minus = -215\n omega_3_1670 = 227\n f_4_2300 = 9010229 # example of a not-well-known meson\n Proton = 2212\n AntiNeutron = -2112\n Lambda = 3122\n Sigma0 = 3212\n SigmaPlus = 3222\n SigmaMinus = 3112\n Xi0 = 3322\n AntiXiMinus = -3312\n OmegaMinus = 3334\n # Charm hadrons\n D0 = 421\n DPlus = 411\n DsPlus = 431\n LcPlus = 4122\n # Beauty hadrons\n B0 = 511\n BPlus = 521\n Bs = 531\n BcPlus = 541\n Lb = 5122\n # Top hadrons\n T0 = 621\n LtPlus = 6122\n # Special particles\n Graviton = 39\n Reggeon = 110\n Pomeron = 990\n Odderon = 9990\n # Supersymmetric particles\n Gluino = 1000021\n Gravitino = 1000039\n STildeL = 1000003\n CTildeR = 2000004\n # R-hadrons\n RPlus_TTildeDbar = 1000612\n R0_GTildeG = 1000993\n RPlusPlus_GTildeUUU = 1092224\n # Q-balls\n QBall1 = 10000150\n QBall2 = -10000200\n # Dyons\n DyonSameMagElecChargeSign = 4110010\n DyonOppositeMagElecChargeSign = 4120010\n # Di-quarks\n DD1 = 1103\n SD0 = 3101\n # Nuclei\n HydrogenNucleus = 1000010010\n Carbon12 = 1000060120\n # Pentaquarks\n AntiUCbarCUDPentaquark = -9422144\n # example of spin 3/2 u-cbar-c-u-d pentaquark decaying to J/psi proton\n UCbarCUDPentaquark = 9422144\n # Technicolor\n Pi0TC = 3000111\n PiMinusTC = -3000211\n # Composite quarks and leptons\n UQuarkStar = 4000002\n AntiElectronStar = -4000011\n # Generator specific pseudoparticles or concepts\n AntiCHadron = -84\n # Invalid ID\n Invalid1 = 0 # illegal ID\n Invalid2 = 99999999 # general form is a 7-digit number\nend\n", "meta": {"hexsha": "fe8ff74d14eba85b6dd374c32c5c18df64ee90a7", "size": 2667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/particles.jl", "max_stars_repo_name": "maxnoe/Corpuscles.jl", "max_stars_repo_head_hexsha": "91ded2eeddbe587e33baa01f4ff1c667d2f53b2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-09-29T19:34:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T15:23:21.000Z", "max_issues_repo_path": "test/particles.jl", "max_issues_repo_name": "maxnoe/Corpuscles.jl", "max_issues_repo_head_hexsha": "91ded2eeddbe587e33baa01f4ff1c667d2f53b2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2019-11-22T19:19:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-13T16:27:45.000Z", "max_forks_repo_path": "test/particles.jl", "max_forks_repo_name": "KM3NeT/Particles.jl", "max_forks_repo_head_hexsha": "990ac7e9427eb117c590bb74afbd42c8073c0fcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:44:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T21:26:27.000Z", "avg_line_length": 22.225, "max_line_length": 74, "alphanum_fraction": 0.6205474316, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255292}} {"text": "abstract type AbstractSimulation{T <: SSDFloat} end\n\n\"\"\"\n mutable struct Simulation{T <: SSDFloat} <: AbstractSimulation{T}\n\nCollection of all parts of a Simulation of a Solid State Detector.\n\"\"\"\nmutable struct Simulation{T <: SSDFloat} <: AbstractSimulation{T}\n detector::Union{SolidStateDetector{T}, Missing}\n ρ::Union{ChargeDensity{T}, Missing}\n ρ_fix::Union{ChargeDensity{T}, Missing}\n ϵ::Union{DielectricDistribution{T}, Missing}\n point_types::Union{PointTypes{T}, Missing}\n electric_potential::Union{ElectricPotential{T}, Missing}\n weighting_potentials::Vector{Any}\n electric_field::Union{ElectricField{T}, Missing}\n\n charge_drift_model::Union{<:AbstractChargeDriftModel{T}, Missing}\n\n electron_drift_field::Union{ElectricField{T}, Missing}\n hole_drift_field::Union{ElectricField{T}, Missing}\nend\n\nfunction Simulation{T}() where {T <: SSDFloat}\n Simulation{T}(\n SolidStateDetector{T}(),\n missing,\n missing,\n missing,\n missing,\n missing,\n [missing],\n missing,\n ElectricFieldChargeDriftModel{T}(),\n missing,\n missing\n )\nend\n\nfunction get_precision_type(sim::Simulation{T}) where {T}\n typeof(sim).parameters[1]\nend\n\nfunction NamedTuple(sim::Simulation{T}) where {T <: SSDFloat}\n wps_strings = AbstractString[]\n for contact in sim.detector.contacts\n if !ismissing(sim.weighting_potentials[contact.id])\n push!(wps_strings, \"WeightingPotential_$(contact.id)\")\n end\n end\n wps_syms = Symbol.(wps_strings)\n nt = (\n detector_json_string = NamedTuple(sim.detector.config_dict),\n electric_potential = NamedTuple(sim.electric_potential),\n ρ = NamedTuple(sim.ρ),\n ρ_fix = NamedTuple(sim.ρ_fix),\n ϵ = NamedTuple(sim.ϵ),\n point_types = NamedTuple(sim.point_types),\n electric_field = NamedTuple(sim.electric_field),\n electron_drift_field = NamedTuple(sim.electron_drift_field),\n hole_drift_field = NamedTuple(sim.hole_drift_field)\n )\n if length(wps_strings) > 0 \n nt = merge(nt, (weighting_potentials = NamedTuple{Tuple(wps_syms)}(NamedTuple.( skipmissing(sim.weighting_potentials))),))\n end\n return nt\nend\nBase.convert(T::Type{NamedTuple}, x::Simulation) = T(x)\n\nfunction Simulation(nt::NamedTuple)\n ep = ElectricPotential(nt.electric_potential)\n T = eltype(ep.data)\n det = SolidStateDetector{T}( Dict(nt.detector_json_string) )\n sim = Simulation( det )\n if !ismissing(nt.electric_potential) sim.electric_potential = ep end\n if !ismissing(nt.ρ) sim.ρ = ChargeDensity(nt.ρ) end\n if !ismissing(nt.ρ_fix) sim.ρ_fix = ChargeDensity(nt.ρ_fix) end\n if !ismissing(nt.ϵ) sim.ϵ = DielectricDistribution(nt.ϵ) end\n if !ismissing(nt.point_types) sim.point_types = PointTypes(nt.point_types) end\n if !ismissing(nt.electric_field) sim.electric_field = ElectricField(nt.electric_field) end\n sim.weighting_potentials = [missing for contact in sim.detector.contacts]\n if !ismissing(nt.weighting_potentials)\n for contact in sim.detector.contacts\n if !ismissing(values(nt.weighting_potentials[contact.id])[1])\n sim.weighting_potentials[contact.id] = WeightingPotential(nt.weighting_potentials[contact.id])\n end\n end\n end\n if !ismissing(nt.electron_drift_field) sim.electron_drift_field = ElectricField(nt.electron_drift_field) end\n if !ismissing(nt.hole_drift_field) sim.hole_drift_field = ElectricField(nt.hole_drift_field) end\n sim.charge_drift_model = ADLChargeDriftModel(T=T)\n @info \"I/O of charge drift model not yet supported. Loading default: ADLChargeDriftModel\"\n return sim\nend\nBase.convert(T::Type{Simulation}, x::NamedTuple) = T(x)\n\n\n\n\nfunction println(io::IO, sim::Simulation{T}) where {T <: SSDFloat}\n println(typeof(sim), \" - Coordinate system: \", get_coordinate_system(sim.detector))\n println(\" Detector: $(sim.detector.name)\")\n println(\" Electric potential: \", !ismissing(sim.electric_potential) ? size(sim.electric_potential) : missing)\n println(\" Charge density: \", !ismissing(sim.ρ) ? size(sim.ρ) : missing)\n println(\" Fix Charge density: \", !ismissing(sim.ρ_fix) ? size(sim.ρ_fix) : missing)\n println(\" Dielectric distribution: \", !ismissing(sim.ϵ) ? size(sim.ϵ) : missing)\n println(\" Point types: \", !ismissing(sim.point_types) ? size(sim.point_types) : missing)\n println(\" Electric field: \", !ismissing(sim.electric_field) ? size(sim.electric_field) : missing)\n println(\" Weighting potentials: \")\n for contact in sim.detector.contacts\n print(\" Contact $(contact.id): \")\n println(!ismissing(sim.weighting_potentials[contact.id]) ? size(sim.weighting_potentials[contact.id]) : missing)\n end\n println(\" Charge drift model: \", !ismissing(sim.electric_field) ? typeof(sim.charge_drift_model) : missing)\n println(\" Electron drift field: \", !ismissing(sim.electron_drift_field) ? size(sim.electron_drift_field) : missing)\n println(\" Hole drift field: \", !ismissing(sim.hole_drift_field) ? size(sim.hole_drift_field) : missing)\nend\n\nfunction print(io::IO, sim::Simulation{T}) where {T <: SSDFloat}\n print(io, \"Simulation{$T} - \", \"$(sim.detector.name)\")\nend\n\nfunction show(io::IO, sim::Simulation{T}) where {T <: SSDFloat} println(io, sim) end\n\nfunction show(io::IO, ::MIME\"text/plain\", sim::Simulation{T}) where {T <: SSDFloat}\n show(io, sim)\nend\n\n\nfunction Simulation(detector::SolidStateDetector{T})::Simulation{T} where {T <: SSDFloat}\n sim::Simulation{T} = Simulation{T}()\n sim.detector = detector\n sim.weighting_potentials = Missing[ missing for i in 1:length(sim.detector.contacts)]\n return sim\nend\n\nfunction Simulation{T}(config_file::AbstractString)::Simulation{T} where{T <: SSDFloat}\n return Simulation( SolidStateDetector{T}(config_file) )\nend\nfunction Simulation(config_file::AbstractString)::Simulation{Float32}\n return Simulation{Float32}( config_file )\nend\n\n# Functions\n\"\"\"\n function apply_initial_state!(sim::Simulation{T}, ::Type{ElectricPotential}, grid::Grid{T} = Grid(sim.detector))::Nothing\n\nApplies the initial state of the electric potential calculation.\nIt overwrites `sim.electric_potential`, `sim.ρ`, `sim.ρ_fix`, `sim.ϵ` and `sim.point_types`.\n\"\"\"\nfunction apply_initial_state!(sim::Simulation{T}, ::Type{ElectricPotential}, grid::Grid{T} = Grid(sim.detector))::Nothing where {T <: SSDFloat}\n fssrb::PotentialSimulationSetupRB{T, 3, 4, get_coordinate_system(sim.detector)} =\n PotentialSimulationSetupRB(sim.detector, grid);\n\n sim.ρ = ChargeDensity(ChargeDensityArray(fssrb), grid)\n sim.ρ_fix = ChargeDensity(FixedChargeDensityArray(fssrb), grid)\n sim.ϵ = DielectricDistribution(DielektrikumDistributionArray(fssrb), grid)\n sim.point_types = PointTypes(PointTypeArray(fssrb), grid)\n sim.electric_potential = ElectricPotential(ElectricPotentialArray(fssrb), grid)\n nothing\nend\n\n\"\"\"\n function apply_initial_state!(sim::Simulation{T}, ::Type{WeightingPotential}, contact_id::Int, grid::Grid{T} = Grid(sim.detector))::Nothing\n\nApplies the initial state of the weighting potential calculation for the contact with the id `contact_id`.\nIt overwrites `sim.weighting_potentials[contact_id]`.\n\"\"\"\nfunction apply_initial_state!(sim::Simulation{T}, ::Type{WeightingPotential}, contact_id::Int, grid::Grid{T} = Grid(sim.detector))::Nothing where {T <: SSDFloat}\n fssrb::PotentialSimulationSetupRB{T, 3, 4, get_coordinate_system(sim.detector)} =\n PotentialSimulationSetupRB(sim.detector, grid, weighting_potential_contact_id = contact_id);\n\n sim.weighting_potentials[contact_id] = WeightingPotential(ElectricPotentialArray(fssrb), grid)\n nothing\nend\n\n\n\"\"\"\n function update_till_convergence!( sim::Simulation{T} ::Type{ElectricPotential}, convergence_limit::Real; kwargs...)::T\n\nTakes the current state of `sim.electric_potential` and updates it until it has converged.\n\"\"\"\nfunction update_till_convergence!( sim::Simulation{T},\n ::Type{ElectricPotential},\n convergence_limit::Real = 1e-7;\n n_iterations_between_checks::Int = 500,\n max_n_iterations::Int = -1,\n depletion_handling::Bool = false,\n use_nthreads::Int = Base.Threads.nthreads(),\n sor_consts::Union{Missing, T, NTuple{2, T}} = missing\n )::T where {T <: SSDFloat}\n CS = get_coordinate_system(sim.detector)\n if ismissing(sor_consts)\n sor_consts = CS == :cylindrical ? (T(1.4), T(1.85)) : T(1.4)\n elseif length(sor_consts) == 1 && CS == :cylindrical\n sor_consts = (T(sor_consts), T(sor_consts))\n elseif length(sor_consts) > 1 && CS == :cartesian\n sor_consts = T(sor_consts[1])\n end\n only_2d::Bool = length(sim.electric_potential.grid.axes[2]) == 1\n\n fssrb::PotentialSimulationSetupRB{T, 3, 4, get_coordinate_system(sim.electric_potential.grid)} =\n PotentialSimulationSetupRB(sim.detector, sim.electric_potential.grid, sim.electric_potential.data, sor_consts = T.(sor_consts))\n\n cf::T = _update_till_convergence!( fssrb, T(convergence_limit);\n only2d = Val{only_2d}(),\n depletion_handling = Val{depletion_handling}(),\n is_weighting_potential = Val{false}(),\n use_nthreads = use_nthreads,\n n_iterations_between_checks = n_iterations_between_checks,\n max_n_iterations = max_n_iterations )\n\n grid::Grid = Grid(fssrb)\n sim.ρ = ChargeDensity(ChargeDensityArray(fssrb), grid)\n sim.ρ_fix = ChargeDensity(FixedChargeDensityArray(fssrb), grid)\n sim.ϵ = DielectricDistribution(DielektrikumDistributionArray(fssrb), grid)\n sim.electric_potential = ElectricPotential(ElectricPotentialArray(fssrb), grid)\n sim.point_types = PointTypes(PointTypeArray(fssrb), grid)\n\n if depletion_handling == false\n update_again::Bool = false # With SOR-Constant = 1\n if fssrb.bulk_is_ptype\n @inbounds for i in eachindex(sim.electric_potential.data)\n if sim.electric_potential.data[i] < fssrb.minimum_applied_potential\n sim.electric_potential.data[i] = fssrb.minimum_applied_potential\n update_again = true\n end\n end\n else # ntype\n @inbounds for i in eachindex(sim.electric_potential.data)\n if sim.electric_potential.data[i] > fssrb.maximum_applied_potential\n sim.electric_potential.data[i] = fssrb.maximum_applied_potential\n update_again = true\n end\n end\n end\n if update_again\n fssrb.sor_const[:] .= T(1)\n cf = _update_till_convergence!( fssrb, T(convergence_limit);\n only2d = Val{only_2d}(),\n depletion_handling = Val{depletion_handling}(),\n is_weighting_potential = Val{false}(),\n use_nthreads = use_nthreads,\n n_iterations_between_checks = n_iterations_between_checks,\n max_n_iterations = max_n_iterations )\n sim.electric_potential = ElectricPotential(ElectricPotentialArray(fssrb), grid)\n\n if fssrb.bulk_is_ptype\n @inbounds for i in eachindex(sim.electric_potential.data)\n if sim.electric_potential.data[i] < fssrb.minimum_applied_potential\n @warn \"\"\"Detector seems not to be fully depleted at a bias voltage of $(fssrb.bias_voltage) V.\n At least one grid point has a smaller potential value ($(sim.electric_potential.data[i]) V)\n than the minimum applied potential ($(fssrb.minimum_applied_potential) V). This should not be.\n However, small overshoots could be due to numerical precision.\"\"\"\n break\n end\n end\n else # ntype\n @inbounds for i in eachindex(sim.electric_potential.data)\n if sim.electric_potential.data[i] > fssrb.maximum_applied_potential\n @warn \"\"\"Detector seems not to be not fully depleted at a bias voltage of $(fssrb.bias_voltage) V.\n At least one grid point has a higher potential value ($(sim.electric_potential.data[i]) V)\n than the maximum applied potential ($(fssrb.maximum_applied_potential) V). This should not be.\n However, small overshoots could be due to numerical precision.\"\"\"\n break\n end\n end\n end\n end\n end\n\n cf\nend\n\n\"\"\"\n function update_till_convergence!( sim::Simulation{T} ::Type{WeightingPotential}, contact_id::Int, convergence_limit::Real; kwargs...)::T\n\nTakes the current state of `sim.weighting_potentials[contact_id]` and updates it until it has converged.\n\"\"\"\nfunction update_till_convergence!( sim::Simulation{T},\n ::Type{WeightingPotential},\n contact_id::Int,\n convergence_limit::Real;\n n_iterations_between_checks::Int = 500,\n max_n_iterations::Int = -1,\n depletion_handling::Bool = false,\n use_nthreads::Int = Base.Threads.nthreads(),\n sor_consts::Union{Missing, T, NTuple{2, T}} = missing\n )::T where {T <: SSDFloat}\n CS = get_coordinate_system(sim.detector)\n if ismissing(sor_consts)\n sor_consts = CS == :cylindrical ? (T(1.4), T(1.85)) : T(1.4)\n elseif length(sor_consts) == 1 && CS == :cylindrical\n sor_consts = (T(sor_consts), T(sor_consts))\n elseif length(sor_consts) > 1 && CS == :cartesian\n sor_consts = T(sor_consts[1])\n end\n\n only_2d::Bool = length(sim.weighting_potentials[contact_id].grid.axes[2]) == 1\n fssrb::PotentialSimulationSetupRB{T, 3, 4, get_coordinate_system(sim.weighting_potentials[contact_id].grid)} =\n PotentialSimulationSetupRB(sim.detector, sim.weighting_potentials[contact_id].grid, sim.weighting_potentials[contact_id].data,\n sor_consts = T.(sor_consts), weighting_potential_contact_id = contact_id)\n\n cf::T = _update_till_convergence!( fssrb, T(convergence_limit);\n only2d = Val{only_2d}(),\n depletion_handling = Val{depletion_handling}(),\n is_weighting_potential = Val{true}(),\n use_nthreads = use_nthreads,\n n_iterations_between_checks = n_iterations_between_checks,\n max_n_iterations = max_n_iterations )\n\n sim.weighting_potentials[contact_id] = WeightingPotential(ElectricPotentialArray(fssrb), sim.weighting_potentials[contact_id].grid)\n\n cf\nend\n\n\"\"\"\n function refine!(sim::Simulation{T}, ::Type{ElectricPotential}, max_diffs::Tuple{<:Real,<:Real,<:Real}, minimum_distances::Tuple{<:Real,<:Real,<:Real})\n\nTakes the current state of `sim.electric_potential` and refines it with respect to the input arguments\n`max_diffs` and `minimum_distances`.\n\"\"\"\nfunction refine!(sim::Simulation{T}, ::Type{ElectricPotential},\n max_diffs::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0)),\n minimum_distances::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0));\n update_other_fields::Bool = false) where {T <: SSDFloat}\n sim.electric_potential = refine(sim.electric_potential, max_diffs, minimum_distances)\n\n if update_other_fields\n fssrb::PotentialSimulationSetupRB{T, 3, 4, get_coordinate_system(sim.electric_potential.grid)} =\n PotentialSimulationSetupRB(sim.detector, sim.electric_potential.grid, sim.electric_potential.data)\n\n sim.ρ = ChargeDensity(ChargeDensityArray(fssrb), sim.electric_potential.grid)\n sim.ρ_fix = ChargeDensity(FixedChargeDensityArray(fssrb), sim.electric_potential.grid)\n sim.ϵ = DielectricDistribution(DielektrikumDistributionArray(fssrb), sim.electric_potential.grid)\n sim.point_types = PointTypes(PointTypeArray(fssrb), sim.electric_potential.grid)\n end\n nothing\nend\n\"\"\"\n function refine!(sim::Simulation{T}, ::Type{WeightingPotential}, max_diffs::Tuple{<:Real,<:Real,<:Real}, minimum_distances::Tuple{<:Real,<:Real,<:Real})\n\nTakes the current state of `sim.weighting_potentials[contact_id]` and refines it with respect to the input arguments\n`max_diffs` and `minimum_distances`.\n\"\"\"\nfunction refine!(sim::Simulation{T}, ::Type{WeightingPotential}, contact_id::Int,\n max_diffs::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0)),\n minimum_distances::Tuple{<:Real,<:Real,<:Real} = (T(0), T(0), T(0))) where {T <: SSDFloat}\n sim.weighting_potentials[contact_id] = refine(weighting_potentials[contact_id], max_diffs, minimum_distances)\n nothing\nend\n\n\nfunction _calculate_potential!( sim::Simulation{T}, potential_type::UnionAll, contact_id::Union{Missing, Int} = missing;\n init_grid_size::Union{Missing, NTuple{3, Int}} = missing,\n init_grid_spacing::Union{Missing, Tuple{<:Real,<:Real,<:Real}} = missing,\n grid::Union{Missing, Grid{T}} = missing,\n convergence_limit::Real = 1e-7,\n max_refinements::Int = 3,\n refinement_limits::Union{Missing, Tuple{<:Real,<:Real,<:Real}} = missing,\n min_grid_spacing::Union{Missing, Tuple{<:Real,<:Real,<:Real}} = missing,\n depletion_handling::Bool = false,\n use_nthreads::Int = Base.Threads.nthreads(),\n sor_consts::Union{Missing, <:Real, Tuple{<:Real,<:Real}} = missing,\n max_n_iterations::Int = 50000,\n verbose::Bool = true,\n )::Nothing where {T <: SSDFloat}\n\n begin # preperations\n convergence_limit::T = T(convergence_limit)\n isEP::Bool = potential_type == ElectricPotential\n isWP::Bool = !isEP\n if isWP depletion_handling = false end\n CS = get_coordinate_system(sim.detector)\n if ismissing(grid)\n grid = Grid(sim.detector, init_grid_size = init_grid_size, init_grid_spacing = init_grid_spacing, for_weighting_potential = isWP)\n end\n if ismissing(sor_consts)\n sor_consts = CS == :cylindrical ? (T(1.4), T(1.85)) : T(1.4)\n elseif length(sor_consts) == 1 && CS == :cylindrical\n sor_consts = (T(sor_consts), T(sor_consts))\n elseif length(sor_consts) > 1 && CS == :cartesian\n sor_consts = T(sor_consts[1])\n end\n if ismissing(refinement_limits)\n refinement_limits::NTuple{3, T} = CS == :cylindrical ? (T(1e-5), T(1e-5) / (0.25 * grid.axes[1][end]), T(1e-5)) : (T(1e-5), T(1e-5), T(1e-5))\n end\n if ismissing(min_grid_spacing)\n min_grid_spacing::NTuple{3, T} = CS == :cylindrical ? (T(1e-5), T(1e-5) / (0.25 * grid.axes[1][end]), T(1e-5)) : (T(1e-5), T(1e-5), T(1e-5))\n end\n n_iterations_between_checks::Int = div(10^7, length(grid))\n if n_iterations_between_checks < 20 n_iterations_between_checks = 20 end\n if use_nthreads > Base.Threads.nthreads()\n use_nthreads = Base.Threads.nthreads();\n @warn \"`use_nthreads` was set to `1`. The environment variable `JULIA_NUM_THREADS` must be set appropriately before the julia session is started.\"\n end\n refine::Bool = max_refinements > 0 ? true : false\n only_2d::Bool = length(grid.axes[2]) == 1 ? true : false\n if CS == :cylindrical\n cyclic::T = grid.axes[2].interval.right - grid.axes[2].interval.left\n n_φ_sym::Int = only_2d ? 1 : Int(round(T(2π) / cyclic, digits = 3))\n n_φ_sym_info_txt = if only_2d\n \"φ symmetry: Detector is φ-symmetric -> 2D computation.\"\n else\n \"φ symmetry: calculating just 1/$(n_φ_sym) in φ of the detector.\"\n end\n end\n contact_potentials::Vector{T} = [contact.potential for contact in sim.detector.contacts]\n bias_voltage::T = (length(contact_potentials) > 0) ? (maximum(contact_potentials) - minimum(contact_potentials)) : T(0)\n if isWP bias_voltage = T(1) end\n if verbose\n println(\n \"$(isEP ? \"Electric\" : \"Weighting\") Potential Calculation\\n\",\n if isEP \"Bias voltage: $(bias_voltage) V\\n\" else \"\" end,\n if CS == :cylindrical \"$n_φ_sym_info_txt\\n\" else \"\" end,\n \"Precision: $T\\n\",\n \"Convergence limit: $convergence_limit => $(round(abs(bias_voltage * convergence_limit), sigdigits=2)) V\\n\",\n \"Threads: $use_nthreads\\n\",\n \"Coordinate system: $(CS)\\n\",\n \"Initial grid dimension: $(size(grid))\\n\",\n \"Refine? -> $refine\\n\",\n \"Refinement parameters:\\n\",\n \"\\tmaximum number of refinements: $(max_refinements)\\n\",\n \"\\tminimum grid spacing:\\n\",\n \"\\t\\tr: $(min_grid_spacing[1]) m\\n\",\n \"\\t\\tφ: $(min_grid_spacing[2]) rad\\n\",\n \"\\t\\tz: $(min_grid_spacing[3]) m\\n\",\n \"\\tRefinement limits:\\n\",\n \"\\t\\tr: $(refinement_limits[1]) -> $(round(abs(bias_voltage * refinement_limits[1]), sigdigits=2)) V\\n\",\n \"\\t\\tφ: $(refinement_limits[2]) -> $(round(abs(bias_voltage * refinement_limits[2]), sigdigits=2)) V\\n\",\n \"\\t\\tz: $(refinement_limits[3]) -> $(round(abs(bias_voltage * refinement_limits[3]), sigdigits=2)) V\\n\",\n \"\"\n )\n end\n end\n if isEP\n apply_initial_state!(sim, potential_type, grid)\n update_till_convergence!( sim, potential_type, convergence_limit,\n n_iterations_between_checks = n_iterations_between_checks,\n max_n_iterations = max_n_iterations,\n depletion_handling = depletion_handling,\n use_nthreads = use_nthreads,\n sor_consts = sor_consts )\n else\n apply_initial_state!(sim, potential_type, contact_id, grid)\n update_till_convergence!( sim, potential_type, contact_id, convergence_limit,\n n_iterations_between_checks = n_iterations_between_checks,\n max_n_iterations = max_n_iterations,\n depletion_handling = depletion_handling,\n use_nthreads = use_nthreads,\n sor_consts = sor_consts )\n end\n\n refinement_counter::Int = 1\n if refine\n max_diffs::NTuple{3, T} = abs.(refinement_limits .* bias_voltage)\n refine_at_inds::NTuple{3, Vector{Int}} = if isEP\n _get_refinement_inds(sim.electric_potential.data, sim.electric_potential.grid, max_diffs, min_grid_spacing)\n else\n _get_refinement_inds(sim.weighting_potentials[contact_id].data, sim.weighting_potentials[contact_id].grid, max_diffs, min_grid_spacing)\n end\n while any(!isempty, refine_at_inds[1]) && refinement_counter <= max_refinements\n if isEP\n sim.electric_potential = ElectricPotential(add_points_and_interpolate(\n sim.electric_potential.data, sim.electric_potential.grid, refine_at_inds...)...)\n if verbose @info \"New Grid Size = $(size(sim.electric_potential.grid))\" end\n else\n sim.weighting_potentials[contact_id] = WeightingPotential(add_points_and_interpolate(\n sim.weighting_potentials[contact_id].data, sim.weighting_potentials[contact_id].grid, refine_at_inds...)...)\n if verbose @info \"New Grid Size = $(size(sim.weighting_potentials[contact_id].grid))\" end\n end\n n_iterations_between_checks = div(10^7, length(isEP ? sim.electric_potential.grid : sim.weighting_potentials[contact_id].grid))\n if n_iterations_between_checks < 20 n_iterations_between_checks = 20 end\n\n if isEP\n update_till_convergence!( sim, potential_type, convergence_limit,\n n_iterations_between_checks = n_iterations_between_checks,\n max_n_iterations = max_n_iterations,\n depletion_handling = depletion_handling,\n use_nthreads = use_nthreads,\n sor_consts = sor_consts )\n else\n update_till_convergence!( sim, potential_type, contact_id, convergence_limit,\n n_iterations_between_checks = n_iterations_between_checks,\n max_n_iterations = max_n_iterations,\n depletion_handling = depletion_handling,\n use_nthreads = use_nthreads,\n sor_consts = sor_consts )\n end\n\n refine_at_inds = if isEP\n _get_refinement_inds(sim.electric_potential.data, sim.electric_potential.grid, max_diffs, min_grid_spacing)\n else\n _get_refinement_inds(sim.weighting_potentials[contact_id].data, sim.weighting_potentials[contact_id].grid, max_diffs, min_grid_spacing)\n end\n refinement_counter += 1\n end\n end\n\n nothing\nend\n\n\"\"\"\n calculate_weighting_potential!(sim::Simulation{T}, contact_id::Int; kwargs...)::Nothing\n\nCompute the weighting potential for the contact with id `contact_id`\nfor the given Simulation `sim` on an adaptive grid through successive over relaxation.\n\nThere are serveral `` which can be used to tune the computation:\n\n# Keywords\n- `convergence_limit::Real`: `convergence_limit` times the bias voltage sets the convergence limit of the relaxation.\n The convergence value is the absolute maximum difference of the potential between two iterations of all grid points.\n Default of `convergence_limit` is `2e-6` (times bias voltage).\n- `max_refinements::Int`: Number of maximum refinements. Default is `2`. Set it to `0` to switch off refinement.\n- `refinement_limits::Tuple{<:Real, <:Real, <:Real}`: Tuple of refinement limits for each dimension\n (in case of cylindrical coordinates the order is `r`, `φ`, `z`).\n A refinement limit (e.g. `refinement_limits[1]`) times the bias voltage of the detector `det` is the\n maximum allowed voltage difference between two neighbouring grid points in the respective dimension.\n When the difference is larger, new points are created inbetween. Default is `[1e-5, 1e-5, 1e-5]`.\n- `init_grid_spacing::Tuple{<:Real, <:Real, <:Real}`: Tuple of the initial distances between two grid points for each dimension.\n For normal coordinates the unit is meter. For angular coordinates, the unit is radiance.\n It prevents the refinement to make the grid to fine. Default is `[0.005, 10.0, 0.005]``.\n- `min_grid_spacing::Tuple{<:Real, <:Real, <:Real}`: Tuple of the mimimum allowed distance between two grid points for each dimension.\n For normal coordinates the unit is meter. For angular coordinates, the unit is radiance.\n It prevents the refinement to make the grid to fine. Default is [`1e-6`, `1e-6`, `1e-6`].\n- `grid::Grid{T, N, S}`: Initial grid used to start the simulation. Default is `Grid(detector, init_grid_spacing=init_grid_spacing)`.\n- `depletion_handling::Bool`: Enables the handling of undepleted regions. Default is false.\n- `use_nthreads::Int`: Number of threads to use in the computation. Default is `Base.Threads.nthreads()`.\n The environment variable `JULIA_NUM_THREADS` must be set appropriately before the Julia session was\n started (e.g. `export JULIA_NUM_THREADS=8` in case of bash).\n- `sor_consts::Union{<:Real, NTuple{2, <:Real}}`: Two element tuple in case of cylindrical coordinates.\n First element contains the SOR constant for `r` = 0.\n Second contains the constant at the outer most grid point in `r`. A linear scaling is applied in between.\n First element should be smaller than the second one and both should be ∈ [1.0, 2.0]. Default is [1.4, 1.85].\n In case of cartesian coordinates only one value is taken.\n- `max_n_iterations::Int`: Set the maximum number of iterations which are performed after each grid refinement.\n Default is `10000`. If set to `-1` there will be no limit.\n- `verbose::Bool=true`: Boolean whether info output is produced or not.\n\"\"\"\nfunction calculate_weighting_potential!(sim::Simulation{T}, contact_id::Int, args...; n_points_in_φ::Union{Missing, Int} = missing, kwargs...)::Nothing where {T <: SSDFloat}\n # S = get_coordinate_system(sim.detector)\n # periodicity::T = get_periodicity(sim.detector.world.intervals[2])\n # if S == :cylindrical && periodicity == T(0)\n # if ismissing(n_points_in_φ)\n # @info \"\\tIn weighing potential calculation: Keyword `n_points_in_φ` not set.\\n\\t\\tDefault is `n_points_in_φ = 36`. 2D field will be extended to 36 points in φ.\"\n # n_points_in_φ = 36\n # else\n # if !(n_points_in_φ > 1 && iseven(n_points_in_φ))\n # @info \"\\tIn weighing potential calculation: Keyword `n_points_in_φ` is $(n_points_in_φ) but must be even and larger than 1.\\n\\t\\t`n_points_in_φ` is now set to 36. 2D field will be extended to 36 points in φ.\"\n # n_points_in_φ = 36\n # end\n # end\n # end\n # wps = calculate_weighting_potential(sim.detector, contact_id, args...; kwargs...)\n # if S == :cylindrical && size(wps.potential, 2) == 1 && !ismissing(n_points_in_φ)\n # wp = WeightingPotential(wps, n_points_in_φ = n_points_in_φ)\n # else\n # wp = WeightingPotential(wps)\n # end\n _calculate_potential!(sim, WeightingPotential, contact_id, args...; kwargs...)\n nothing\nend\n\n\"\"\"\n calculate_electric_potential!(sim::Simulation{T}; kwargs...)::Nothing\n\n\nCompute the electric potential for the given Simulation `sim` on an adaptive grid\nthrough successive over relaxation.\n\nThere are serveral `` which can be used to tune the computation:\n\n# Keywords\n- `convergence_limit::Real`: `convergence_limit` times the bias voltage sets the convergence limit of the relaxation.\n The convergence value is the absolute maximum difference of the potential between two iterations of all grid points.\n Default of `convergence_limit` is `2e-6` (times bias voltage).\n- `max_refinements::Int`: Number of maximum refinements. Default is `2`. Set it to `0` to switch off refinement.\n- `refinement_limits::Tuple{<:Real, <:Real, <:Real}`: Tuple of refinement limits for each dimension\n (in case of cylindrical coordinates the order is `r`, `φ`, `z`).\n A refinement limit (e.g. `refinement_limits[1]`) times the bias voltage of the detector `det` is the\n maximum allowed voltage difference between two neighbouring grid points in the respective dimension.\n When the difference is larger, new points are created inbetween. Default is `[1e-5, 1e-5, 1e-5]`.\n- `init_grid_spacing::Tuple{<:Real, <:Real, <:Real}`: Tuple of the initial distances between two grid points for each dimension.\n For normal coordinates the unit is meter. For angular coordinates, the unit is radiance.\n It prevents the refinement to make the grid to fine. Default is `[0.005, 10.0, 0.005]``.\n- `min_grid_spacing::Tuple{<:Real, <:Real, <:Real}`: Tuple of the mimimum allowed distance between two grid points for each dimension.\n For normal coordinates the unit is meter. For angular coordinates, the unit is radiance.\n It prevents the refinement to make the grid to fine. Default is [`1e-6`, `1e-6`, `1e-6`].\n- `grid::Grid{T, N, S}`: Initial grid used to start the simulation. Default is `Grid(detector, init_grid_spacing=init_grid_spacing)`.\n- `depletion_handling::Bool`: Enables the handling of undepleted regions. Default is false.\n- `use_nthreads::Int`: Number of threads to use in the computation. Default is `Base.Threads.nthreads()`.\n The environment variable `JULIA_NUM_THREADS` must be set appropriately before the Julia session was\n started (e.g. `export JULIA_NUM_THREADS=8` in case of bash).\n- `sor_consts::Union{<:Real, NTuple{2, <:Real}}`: Two element tuple in case of cylindrical coordinates.\n First element contains the SOR constant for `r` = 0.\n Second contains the constant at the outer most grid point in `r`. A linear scaling is applied in between.\n First element should be smaller than the second one and both should be ∈ [1.0, 2.0]. Default is [1.4, 1.85].\n In case of cartesian coordinates only one value is taken.\n- `max_n_iterations::Int`: Set the maximum number of iterations which are performed after each grid refinement.\n Default is `10000`. If set to `-1` there will be no limit.\n- `verbose::Bool=true`: Boolean whether info output is produced or not.\n\"\"\"\nfunction calculate_electric_potential!(sim::Simulation{T}, args...; kwargs...)::Nothing where {T <: SSDFloat}\n _calculate_potential!(sim, ElectricPotential, args...; kwargs...)\n nothing\nend\n\n\"\"\"\n calculate_electric_field!(sim::Simulation{T}, args...; n_points_in_φ::Union{Missing, Int} = missing, kwargs...)::Nothing\n\nToDo...\n\"\"\"\nfunction calculate_electric_field!(sim::Simulation{T}, args...; n_points_in_φ::Union{Missing, Int} = missing, kwargs...)::Nothing where {T <: SSDFloat}\n S = get_coordinate_system(sim.detector)\n periodicity::T = get_periodicity(sim.detector.world.intervals[2])\n e_pot, point_types = if S == :cylindrical && periodicity == T(0) # 2D, only one point in φ\n if ismissing(n_points_in_φ)\n @info \"\\tIn electric field calculation: Keyword `n_points_in_φ` not set.\\n\\t\\tDefault is `n_points_in_φ = 36`. 2D field will be extended to 36 points in φ.\"\n n_points_in_φ = 36\n else\n if !(n_points_in_φ > 1 && iseven(n_points_in_φ))\n @info \"\\tIn electric field calculation: Keyword `n_points_in_φ` is $(n_points_in_φ) but must be even and larger than 1.\\n\\t\\t`n_points_in_φ` is now set to 36. 2D field will be extended to 36 points in φ.\"\n n_points_in_φ = 36\n end\n end\n get_2π_potential(sim.electric_potential, n_points_in_φ = n_points_in_φ),\n get_2π_potential(sim.point_types, n_points_in_φ = n_points_in_φ);\n elseif S == :cylindrical\n get_2π_potential(sim.electric_potential),\n get_2π_potential(sim.point_types)\n else\n sim.electric_potential,\n sim.point_types\n end\n sim.electric_field = get_electric_field_from_potential(e_pot, point_types);\n nothing\nend\n\nfunction set_charge_drift_model!(sim::Simulation{T}, charge_drift_model::AbstractChargeDriftModel{T})::Nothing where {T <: SSDFloat}\n sim.charge_drift_model = charge_drift_model\n nothing\nend\n\nfunction calculate_drift_fields!(sim::Simulation{T};\n use_nthreads::Int = Base.Threads.nthreads())::Nothing where {T <: SSDFloat}\n sim.electron_drift_field = ElectricField(get_electron_drift_field(sim.electric_field.data, sim.charge_drift_model, use_nthreads = use_nthreads), sim.electric_field.grid)\n sim.hole_drift_field = ElectricField(get_hole_drift_field(sim.electric_field.data, sim.charge_drift_model, use_nthreads = use_nthreads), sim.electric_field.grid)\n nothing\nend\n@deprecate apply_charge_drift_model!(args...; kwargs...) calculate_drift_fields!(args...; kwargs...)\n\nfunction get_interpolated_drift_field(ef::ElectricField)\n get_interpolated_drift_field(ef.data, ef.grid)\nend\n\nfunction drift_charges( sim::Simulation{T}, starting_positions::Vector{CartesianPoint{T}};\n Δt::RealQuantity = 5u\"ns\", max_nsteps::Int = 1000, verbose::Bool = true )::Vector{EHDriftPath{T}} where {T <: SSDFloat}\n return _drift_charges( sim.detector, sim.point_types.grid, sim.point_types, starting_positions,\n get_interpolated_drift_field(sim.electron_drift_field), get_interpolated_drift_field(sim.hole_drift_field),\n Δt, max_nsteps = max_nsteps, verbose = verbose)::Vector{EHDriftPath{T}}\nend\n\nfunction get_signal(sim::Simulation{T}, drift_paths::Vector{EHDriftPath{T}}, energy_depositions::Vector{T}, contact_id::Int; Δt::TT = T(5) * u\"ns\") where {T <: SSDFloat, TT}\n dt::T = to_internal_units(internal_time_unit, Δt)\n wp::Interpolations.Extrapolation{T, 3} = interpolated_scalarfield(sim.weighting_potentials[contact_id])\n timestamps = _common_timestamps( drift_paths, dt )\n signal::Vector{T} = zeros(T, length(timestamps))\n add_signal!(signal, timestamps, drift_paths, energy_depositions, wp, Val(get_coordinate_system(sim.detector)))\n return RDWaveform( range(zero(T) * unit(Δt), step = T(ustrip(Δt)) * unit(Δt), length = length(signal)), signal )\nend\n\n\"\"\"\n function simulate!(sim::Simulation{T}; max_refinements::Int = 1, verbose::Bool = false,\n depletion_handling::Bool = false, convergence_limit::Real = 1e-5 ) where {T <: SSDFloat}\n\nToDo...\n\"\"\"\nfunction simulate!(sim::Simulation{T}; max_refinements::Int = 1, verbose::Bool = false,\n depletion_handling::Bool = false, convergence_limit::Real = 1e-7 ) where {T <: SSDFloat}\n calculate_electric_potential!( sim,\n max_refinements = max_refinements,\n verbose = verbose,\n init_grid_size = (10,10,10),\n depletion_handling = depletion_handling,\n convergence_limit = convergence_limit )\n for contact in sim.detector.contacts\n calculate_weighting_potential!(sim, contact.id, max_refinements = max_refinements,\n init_grid_size = (10,10,10),\n verbose = verbose, convergence_limit = convergence_limit)\n end\n calculate_electric_field!(sim)\n set_charge_drift_model!(sim, sim.charge_drift_model)\n calculate_drift_fields!(sim)\n @info \"Detector simulation done\"\nend\n\nfunction _get_abs_bias_voltage(det::SolidStateDetector{T}) where {T <: SSDFloat}\n potentials::Vector{T} = map(c -> c.potential, det.contacts)\n return (maximum(potentials) - minimum(potentials)) * u\"V\"\nend\n\n\n\n\ncalculate_stored_energy(sim::Simulation) = \n calculate_stored_energy(sim.electric_field, sim.ϵ)\n\nfunction calculate_stored_energy(ef::ElectricField{T,3,S}, ϵ::DielectricDistribution{T,3,S}) where {T <: SSDFloat, S}\n W::T = 0\n \n cylindric::Bool = S == :cylindrical\n cartesian::Bool = !cylindric\n r0_handling::Bool = typeof(ef.grid.axes[1]).parameters[2] == :r0\n\n ax1::Vector{T} = collect(ef.grid[1])\n ax2::Vector{T} = collect(ef.grid[2])\n ax3::Vector{T} = collect(ef.grid[3])\n mp1::Vector{T} = midpoints(get_extended_ticks(ef.grid[1]))\n mp2::Vector{T} = midpoints(get_extended_ticks(ef.grid[2]))\n mp3::Vector{T} = midpoints(get_extended_ticks(ef.grid[3]))\n Δax1::Vector{T} = diff(ax1)\n Δax2::Vector{T} = diff(ax2)\n Δax3::Vector{T} = diff(ax3)\n Δmp1::Vector{T} = diff(mp1)\n Δmp2::Vector{T} = diff(mp2)\n Δmp3::Vector{T} = diff(mp3)\n \n w1r::Vector{T} = inv.(Δmp1) .* (mp1[2:end] .- ax1)\n w1l::Vector{T} = inv.(Δmp1) .* (ax1 - mp1[1:end-1])\n w2r::Vector{T} = inv.(Δmp2) .* (mp2[2:end] .- ax2)\n w2l::Vector{T} = inv.(Δmp2) .* (ax2 - mp2[1:end-1])\n w3r::Vector{T} = inv.(Δmp3) .* (mp3[2:end] .- ax3)\n w3l::Vector{T} = inv.(Δmp3) .* (ax3 - mp3[1:end-1])\n\n if cylindric\n mp1[1] = 0\n mp1[end] = ax1[end]\n Δmp1 = ((mp1[2:end].^2) .- (mp1[1:end-1].^2)) ./ 2\n end\n V::T = 0\n for i3 in 1:size(ϵ, 3)-1\n _Δmp3::T = Δmp3[i3]\n if (i3 == 1 || i3 == size(ϵ, 3)-1) _Δmp3 /= 2 end\n for i2 in 1:size(ϵ, 2)-1\n _Δmp2::T = Δmp2[i2]\n if (cartesian && (i2 == 1 || i2 == size(ϵ, 2)-1)) _Δmp2 /= 2 end\n for i1 in 1:size(ϵ, 1)-1\n _Δmp1::T = Δmp1[i1]\n if (cartesian && (i1 == 1 || i1 == size(ϵ, 1)-1)) _Δmp1 /= 2 end\n ev::SArray{Tuple{3},Float32,1,3} = ef.data[i1, i2, i3]\n dV::T = _Δmp3 * _Δmp2 * _Δmp1\n _ϵ::T = sum([\n ϵ[i1, i2, i3] * w1l[i1] * w2l[i2] * w3l[i3], \n ϵ[i1 + 1, i2, i3] * w1r[i1] * w2l[i2] * w3l[i3],\n ϵ[i1, i2 + 1, i3] * w1l[i1] * w2r[i2] * w3l[i3], \n ϵ[i1, i2, i3 + 1] * w1l[i1] * w2l[i2] * w3r[i3],\n ϵ[i1 + 1, i2 + 1, i3] * w1r[i1] * w2r[i2] * w3l[i3], \n ϵ[i1 + 1, i2, i3 + 1] * w1r[i1] * w2l[i2] * w3r[i3],\n ϵ[i1, i2 + 1, i3 + 1] * w1l[i1] * w2r[i2] * w3r[i3],\n ϵ[i1 + 1, i2 + 1, i3 + 1] * w1r[i1] * w2r[i2] * w3r[i3]\n ])\n V += dV\n W += sum(ev.^2) * dV * _ϵ\n end\n end\n end\n E = W * ϵ0 / 2 * u\"J\"\n if cylindric && (size(ϵ, 2) - 1 != size(ef, 2))\n E *= size(ef, 2) / (size(ϵ, 2) - 1)\n end\n return E\nend\n\nexport calculate_capacitance\n\"\"\"\n calculate_capacitance(sim::Simulation{T})::T where {T <: SSDFloat}\n\nCalculates the capacitance of an detector in Farad.\n\"\"\"\nfunction calculate_capacitance(sim::Simulation{T}) where {T <: SSDFloat}\n W = calculate_stored_energy(sim)\n return uconvert(u\"pF\", 2 * W / (_get_abs_bias_voltage(sim.detector)^2))\nend", "meta": {"hexsha": "64568092c27e9cf6eba8ef4f64876fad36ab9470", "size": 42171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Simulation/Simulation.jl", "max_stars_repo_name": "rjtayl/SolidStateDetectors.jl", "max_stars_repo_head_hexsha": "1338685ea0af434efbe78d7cf87228badec16534", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Simulation/Simulation.jl", "max_issues_repo_name": "rjtayl/SolidStateDetectors.jl", "max_issues_repo_head_hexsha": "1338685ea0af434efbe78d7cf87228badec16534", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Simulation/Simulation.jl", "max_forks_repo_name": "rjtayl/SolidStateDetectors.jl", "max_forks_repo_head_hexsha": "1338685ea0af434efbe78d7cf87228badec16534", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.7895408163, "max_line_length": 226, "alphanum_fraction": 0.6421000213, "num_tokens": 10818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.1990081132596584}} {"text": "# This file establishes the default initial conditions, boundary conditions and sources\n# for the baroclinicwave_problem experiment, following\n#\n# Ullrich, P. A., Melvin, T., Jablonowski, C., and Staniforth, A.:\n# A proposed baroclinic wave test case for deep- and shallow atmosphere\n# dynamical cores, Q. J. Roy. Meteor. Soc., 140, 1590-1602, doi:10.1002/qj.2241, 2014.\n\n# Override default CLIMAParameters for consistency with literature on this case\nCLIMAParameters.Planet.press_triple(::EarthParameterSet) = 610.78\n\nstruct BaroclinicWaveProblem{BC, ISP, ISA, WP, BS, MP} <: AbstractAtmosProblem\n boundarycondition::BC\n init_state_prognostic::ISP\n init_state_auxiliary::ISA\n perturbation::WP\n base_state::BS\n moisture_profile::MP\nend\nfunction BaroclinicWaveProblem(;\n boundarycondition = (AtmosBC(), AtmosBC()),\n perturbation = nothing,\n base_state = nothing,\n moisture_profile = nothing,\n)\n # Set up defaults\n if isnothing(perturbation)\n perturbation = DeterministicPerturbation()\n end\n if isnothing(base_state)\n base_state = BCWaveBaseState()\n end\n if isnothing(moisture_profile)\n moisture_profile = MoistLowTropicsMoistureProfile()\n end\n\n problem = (\n boundarycondition,\n init_gcm_experiment!,\n (_...) -> nothing,\n perturbation,\n base_state,\n moisture_profile,\n )\n return BaroclinicWaveProblem{typeof.(problem)...}(problem...)\nend\n\nproblem_name(::BaroclinicWaveProblem) = \"BaroclinicWave\"\n\nsetup_source(::BaroclinicWaveProblem) = (Gravity(), Coriolis())\n", "meta": {"hexsha": "65567b794863b6eaa06ff8fa7ecba8ddb6566509", "size": 1582, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/AtmosGCM/GCMDriver/baroclinicwave_problem.jl", "max_stars_repo_name": "mwarusz/CLIMA", "max_stars_repo_head_hexsha": "af1bb8e2865bca9df9cf97c9bc1540080169676c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/AtmosGCM/GCMDriver/baroclinicwave_problem.jl", "max_issues_repo_name": "mwarusz/CLIMA", "max_issues_repo_head_hexsha": "af1bb8e2865bca9df9cf97c9bc1540080169676c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/AtmosGCM/GCMDriver/baroclinicwave_problem.jl", "max_forks_repo_name": "mwarusz/CLIMA", "max_forks_repo_head_hexsha": "af1bb8e2865bca9df9cf97c9bc1540080169676c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.64, "max_line_length": 87, "alphanum_fraction": 0.7142857143, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1990081078371907}} {"text": "# # Motivation\n\nusing InteractiveUtils # hide\nusing InteractiveUtils: subtypes # hide\n\n# Before going into details about Julia type system, we will spend a few minutes motivating \n# the two main roles of the type system, which are:\n# \n# 1. Structuring the code\n# 2. Communicating to the compiler how your type will be used.\n# \n# The first aspect is important for the convenience of the programmer and enables abstractions\n# in the language, the latter aspect is important for the speed of the generated code. \n# \n# Type systems according to [Wikipedia](https://en.wikipedia.org/wiki/Data_type):\n# * In computer science and computer programming, a **data type** or simply **type** is an attribute of data which tells the compiler or interpreter how the programmer intends to use the data.* \n# * A **type system** is a logical system comprising a set of rules that assigns a property called a type to the various constructs of a computer program, such as variables, expressions, functions or modules. These types formalize and enforce the otherwise implicit categories the programmer uses for algebraic data types, data structures, or other components.*\n# \n# ## Structuring the code / enforcing the categories\n# The role of **structuring** the code and imposing semantic restriction\n# means that the type system allows you to logically divide your program, \n# and to prevent certain types of errors.\n# Consider for example two types, `Wolf` and `Sheep` which share the same \n# definition but the types have different names.\n\nstruct Wolf\n name::String\n energy::Int\nend\n\nstruct Sheep\n name::String\n energy::Int\nend\n\n# This allows us to define functions applicable only to the corresponding type\n# \nhowl(wolf::Wolf) = println(wolf.name, \" has howled.\")\nbaa(sheep::Sheep) = println(sheep.name, \" has baaed.\")\nnothing # hide\n# \n# Therefore the compiler (or interpretter) **enforces** that a wolf can only `howl`\n# and never `baa` and vice versa a sheep can only `baa`. In this sense, it ensures \n# that `howl(sheep)` and `baa(wolf)` never happen.\n# For comparison, consider an alternative definition as follows\n# \nhowl(animal) = println(animal.name, \" has howled.\")\nbaa(animal) = println(animal.name, \" has baaed.\")\n# \n# in which case the burden of ensuring that a wolf will never baa rests upon the\n# programmer which inevitably leads to errors (note that severely constrained \n# type systems are difficult to use).\n\n# ## Intention of use and restrictions on compilers\n# The *intention of use* in types is related to how efficient code a compiler can\n# produce for that given intention. As an example, consider a following two \n# alternatives to represent a set of animals:\na = [Wolf(\"1\", 1), Wolf(\"2\", 2), Sheep(\"3\", 3)]\nb = (Wolf(\"1\", 1), Wolf(\"2\", 2), Sheep(\"3\", 3))\n# where `a` is an array which can contain arbitrary types and have arbitrary length\n# whereas `b` is a `Tuple` which has fixed length in which the first two items are of type `Wolf`\n# and the third item is of type `Sheep`. Moreover, consider a function which calculates the\n# energy of all animals as \nenergy(animals) = mapreduce(x -> x.energy, +, animals)\nnothing # hide\n# A good compiler makes use of the information provided by the type system to generate effiecint code\n# which we can verify by inspecting the compiled code using `@code_native` macro\n@code_native energy(a)\n#\n@code_native energy(b)\n# one observes the second version produces more optimal code. Why is that?\n# * In the first representation, `a`, the animals are stored in an `Array` which can have arbitrary size and can contain arbitrary animals. This means that the compiler has to compile `energy(a)` such that it works on such arrays.\n# * In the second representation, `b`, the animals are stored in a `Tuple`, which specializes for lengths and types of items. This means that the compiler knows the number of animals and the type of each animal on each position within the tuple, which allows it to specialize.\n\n# This difference will indeed have an impact on the time of code execution. \n# On my i5-8279U CPU, the difference (as measured by BenchmarkTools) is\nusing BenchmarkTools\n@benchmark energy(a)\n@benchmark energy(b)\n# Which nicely demonstrates that the choice of types affects performance. Does it mean that we should always use `Tuples` instead of `Arrays`? Surely not, it is just that each is better for different use-cases. Using Tuples means that the compiler will compile a special function for each length of tuple and each combination of types of items it contains, which is clearly wasteful.\n\n# # Julia's type system\n\n# ## Julia is dynamicaly typed\n# Julia's type system is dynamic, which means that all types are resolved during runtime. **But**, if the compiler can infer types of all variables of the called function, it can specialize the function for that given type of variables which leads to efficient code. Consider a modified example where we represent two wolfpacks:\nwolfpack_a = [Wolf(\"1\", 1), Wolf(\"2\", 2), Wolf(\"3\", 3)]\nwolfpack_b = Any[Wolf(\"1\", 1), Wolf(\"2\", 2), Wolf(\"3\", 3)]\n# `wolfpack_a` carries a type `Vector{Wolf}` while `wolfpack_b` has the type `Vector{Any}`. This means that in the first case, the compiler knows that all items are of the type `Wolf`and it can specialize functions using this information. In case of `wolfpack_b`, it does not know which animal it will encounter (although all are of the same type), and therefore it needs to dynamically resolve the type of each item upon its use. This ultimately leads to less performant code.\n@btime energy(wolfpack_a)\n@btime energy(wolfpack_b)\nnothing # hide\n\n# To conclude, julia is indeed a dynamically typed language, **but** if the compiler can infer \n# all types in a called function in advance, it does not have to perform the type resolution \n# during execution, which produces performant code.\n\n# ## Classes of types\n# Julia divides types into three classes: primitive, composite, and abstract.\n\n# ### Primitive types\n# Citing the [documentation](https://docs.julialang.org/en/v1/manual/types/#Primitive-Types): *A primitive type is a concrete type whose data consists of plain old bits. Classic examples of primitive types are integers and floating-point values. Unlike most languages, Julia lets you declare your own primitive types, rather than providing only a fixed set of built-in ones. In fact, the standard primitive types are all defined in the language itself.*\n\n# The definition of primitive types look as follows\n# ```julia\n# primitive type Float16 <: AbstractFloat 16 end\n# primitive type Float32 <: AbstractFloat 32 end\n# primitive type Float64 <: AbstractFloat 64 end\n# ```\n# and they are mainly used to jump-start julia's type system. It is rarely needed to \n# define a special primitive type, as it makes sense only if you define special functions \n# operating on its bits. This is almost excusively used for exposing special operations \n# provided by the underlying CPU / LLVM compiler. For example `+` for `Int32` is different \n# from `+` for `Float32` as they call a different intrinsic operations. You can inspect this \n# jump-starting of the type system yourself by looking at Julia's source.\n# ```julia\n# julia> @which +(1,2)\n# +(x::T, y::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} in Base at int.jl:87\n# ```\n\n# At `int.jl:87` \n# ```julia\n# (+)(x::T, y::T) where {T<:BitInteger} = add_int(x, y)\n# ```\n# we see that `+` of integers is calling the function `add_int(x, y)`, which is defined in the core \n# part of the compiler in `Intrinsics.cpp` (yes, in C++).\n\n# From Julia docs: *Core is the module that contains all identifiers considered \"built in\" to \n# the language, i.e. part of the core language and not libraries. Every module implicitly \n# specifies using Core, since you can't do anything without those definitions.*\n\n# Primitive types are rarely used, and they will not be used in this course. We mention them \n# for the sake of completeness and refer the reader to the official Documentation (and source code \n# of Julia).\n\n\n# ### Abstract Type \n# \n# An abstract type can be viewed as a set of concrete types. For example, an\n# `AbstractFloat` represents the set of concrete types `(BigFloat,Float64,Float32,Float16)`.\n# This is used mainly to define general methods for sets of types for which we expect the same behavior (recall the Julia design motivation: *if it quacks like a duck, waddles like a duck and looks like a duck, chances are it's a duck*). Abstract types are defined with `abstract type TypeName end`. For example the following set of abstract types defines part of julia's number system.\n# ```julia\n# abstract type Number end\n# abstract type Real <: Number end\n# abstract type Complex <: Number end\n# abstract type AbstractFloat <: Real end\n# abstract type Integer <: Real end\n# abstract type Signed <: Integer end\n# abstract type Unsigned <: Integer end\n# ```\n# where `<:` means \"is a subtype of\" and it is used in declarations where the right-hand is an immediate sypertype of a given type (`Integer` has the immediate supertype `Real`.) If the supertype is not supplied, it is considered to be Any, therefore in the above defition `Number` has the supertype `Any`. Children of a particular type can be viewed as \nusing AbstractTrees\nfunction AbstractTrees.children(t::Type)\n t === Function ? Vector{Type}() : filter!(x -> x !== Any,subtypes(t))\nend\nAbstractTrees.printnode(io::IO,t::Type) = print(io,t)\nprint_tree(Number)\n# As was mentioned, abstract types allows as to define functions that can be applied variebles of types with a given abstract type as a supertype. For example we can define a `sgn` function for **all** real numbers as \nsgn(x::Real) = x > 0 ? 1 : x < 0 ? -1 : 0\nnothing # hide\n# and we know it would be correct for all real numbers. This means that if anyone creates \n# a new subtype of `Real`, the above function can be used. This also means that \n# **it is expected** that comparison operations are defined for any real number. Also notice that \n# `Complex` numbers are excluded, since they do not have a total order.\n\n# For unsigned numbers, the `sgn` can be simplified, as it is sufficient to verify if they are different (greater) than zero, therefore the function can read\nsgn(x::Unsigned) = x > 0 ? 1 : 0\nnothing # hide\n# and again, it applies to all numbers derived from `Unsigned`. Recall that \n# `Unsigned <: Integer <: Real,` how does Julia decide, \n# which version of the function `sgn` to use for `UInt8(0)`? It chooses the most \n# specific version, and thus for `sgn(UInt8(0))` it will use `sgn(x::Unsinged)`. \n# If the compiler cannot decide, typically it encounters an ambiguity, it throws an error \n# and recommends which function you should define to resolve it.\n\n# The above behavior allows to define default \"fallback\" implementations and while allowing \n# to specialize for sub-types. A great example is matrix multiplication, which has a \n# generic (and slow) implementation with many specializations, which can take advantage \n# of structure (sparse, banded), or use optimized implementations (e.g. blas implementation \n# for dense matrices with eltype `Float32` and `Float64`).\n\n# Again, Julia does not make a difference between abstract types defined in `Base` \n# libraries shipped with the language and those defined by you (the user). All are treated \n# the same.\n\n# (![From Julia documentation](https://docs.julialang.org/en/v1/manual/types/#man-abstract-types))\n# Abstract types cannot be instantiated, which means that we cannot create a variable that \n# would have an abstract type (try `typeof(Number(1f0))`). Also, abstract types cannot have \n# any fields, therefore there is no composition (there are lengty discussions of why this is so,\n# one of the most definite arguments of creators is that abstract types with fields frequently lead\n# to children types not using some fields (consider circle vs. ellipse)).\n\n# ### [Composite types](@id composite_types)\n# Composite types are similar to `struct` in C (they even have the same memory layout) as they logically join together other types. It is not a great idea to think about them as objects (in OOP sense), because objects tie together *data* and *functions* on owned data. Contrary in Julia (as in C), functions operate on data of structures, but are not tied to them and they are defined outside them. Composite types are workhorses of Julia's type system, as user-defined types are mostly composite (or abstract).\n\n# Composite types are defined using `struct TypeName [fields] end`. To define a position of an animal on the Euclidean plane as a type, we would write\nstruct PositionF64\n x::Float64\n y::Float64\nend\n# which defines a structure with two fields `x` and `y` of type `Float64`. Julia's compiler creates a default constructor, where both (but generally all) arguments are converted using `(convert(Float64, x), convert(Float64, y)` to the correct type. This means that we can construct a PositionF64 with numbers of different type that are convertable to Float64, e.g. `PositionF64(1,1//2)` but we cannot construct `PositionF64` where the fields would be of different type (e.g. `Int`, `Float32`, etc.) or they are not trivially convertable (e.g. `String`).\n\n# Fields in composite types do not have to have a specified type. We can define a `VaguePosition` without specifying the type\nstruct VaguePosition\n x \n y \nend\n# This works as the definition above except that the arguments are not converted to `Float64` now. One can store different values in `x` and `y`, for example `String` (e.g. VaguePosition(\"Hello\",\"world\")). Although the above definition might be convenient, it limits the compiler's ability to specialize, as the type `VaguePosition` does not carry information about type of `x` and `y`, which has a negative impact on the performance. For example\nusing BenchmarkTools\nmove(a::T,b::T) where T = T(a.x + b.x, a.y + b.y)\nx = [PositionF64(rand(), rand()) for _ in 1:100]\ny = [VaguePosition(rand(), rand()) for _ in 1:100]\n@benchmark reduce(move, x)\n@benchmark reduce(move, y)\n# Giving fields of a composite type an abstract type does not really solve the problem of the compiler not knowing the type. In this example, it still does not know, if it should use instructions for `Float64` or `Int8`.\nstruct LessVaguePosition\n x::Real\n y::Real \nend\nz = [LessVaguePosition(rand(), rand()) for _ in 1:100];\n@benchmark reduce(move, z)\n# From the perspective of generating optimal code, both definitions are equally uninformative to the compiler as it cannot assume anything about the code. However, the `LessVaguePosition` will ensure that the position will contain only numbers, hence catching trivial errors like instantiating `VaguePosition` with non-numeric types for which arithmetic operators will not be defined (recall the discussion on the beginning of the lecture). \n\n# All structs defined above are immutable (as we have seen above in the case of `Tuple`), which means that one cannot change a field (unless the struct wraps a container, like and array, which allows that). For example this raises an error\na = LessVaguePosition(1,2)\na.x = 2\n\n# If one needs to make a struct mutable, use the keyword `mutable` before the keyword `struct` as\nmutable struct MutablePosition\n x::Float64\n y::Float64\nend\n# In mutable structures, we can change the values of fields.\na = MutablePosition(1e0, 2e0)\na.x = 2\na\n# Note, that the memory layout of mutable structures is different, as fields now contain references to memory locations, where the actual values are stored. \n\n# ### Parametric Types\n# So far, we had to trade-off flexibility for generality in type definitions. Can we have both? The answer is affirmative. The way to achieve this **flexibility** in definitions of the type while being able to generate optimal code is to **parametrize** the type definition. This is achieved by replacing types with a parameter (typically a single uppercase character) and decorating in definition by specifying different type in curly brackets. For example \nstruct PositionT{T}\n x::T\n y::T \nend\nu = [PositionT(rand(), rand()) for _ in 1:100];\n@btime reduce(move, u);\n# Notice that the compiler can take advantage of specializing for different types (which does not have an effect here as in modern processors addition of `Float` and `Int` takes the same time).\nv = [PositionT(rand(1:100), rand(1:100)) for _ in 1:100];\n@btime reduce(move, v);\n# The above definition suffers the same problem as `VaguePosition`, which is that it allows us to instantiate the `PositionT` with non-numeric types, e.g. `String`. We solve this by restricting the types `T` to be children of some supertype, in this case `Real`\nstruct Position{T<:Real}\n x::T\n y::T \nend\n# which will throw an error if we try to initialize it with `Position(\"1.0\", \"2.0\")`. \n# \n# Naturally, fields in structures can be of different types, as is in the below pointless example.\nstruct PositionXY{X<:Real, Y<:Real}\n x::X\n y::Y\nend\n\n# ### Abstract parametric types\n# Like Composite types, Abstract types can also have parameters. These parameters define types that are common for all child types. A very good example is Julia's definition of arrays of arbitrary dimension `N` and type `T` of its items as\n# ```julia\n# abstract type AbstractArray{T,N} end\n# ```\n# Different `T` and `N` give rise to different variants of `AbstractArrays`, \n# therefore `AbstractArray{Float32,2}` is different from `AbstractArray{Float64,2}` \n# and from `AbstractArray{Float64,1}.` Note that these are still `Abstract` types, \n# which means you cannot instantiate them. Their purpose is\n# * to allow to define operations for broad class of concrete types\n# * to inform the compiler about constant values, which can be used \n# Notice in the above example that parameters of types do not have to be types, but can also be values of primitive types, as in the above example of `AbstractArray` `N` is the number of dimensions which is an integer value.\n# \n# For convenience, it is common to give some important partially instantiated Abstract types an **alias**, for example `AbstractVector` as \n# ```julia\n# const AbstractVector{T} = AbstractArray{T,1}\n# ```\n# is defined in `array.jl:23` (in Julia 1.6.2), which allows us to define for example general prescription for the `dot` product of two abstract vectors as \nfunction dot(a::AbstractVector, b::AbstractVector)\n @assert length(a) == length(b)\n mapreduce(*, +, a, b)\nend\n# You can verify that the above general function can be compiled to performant code if \n# specialized for particular arguments.\n@code_native mapreduce(*,+, [1,2,3], [1,2,3])\n\n\n# ## More on the use of types in function definitions\n# ### Terminology\n# * A *function* refers to a set of \"methods\" for a different combination of type parameters (the term function can be therefore considered as refering to a mere **name**). *Methods* define different behavior for different types of arguments for a given function. For example\nmove(a::Position, b::Position) = Position(a.x + b.x, a.y + b.y)\nmove(a::Vector{<:Position}, b::Vector{<:Position}) = move.(a,b)\n# `move` refers to a function with methods `move(a::Position, b::Position)` and `move(a::Vector{<:Position}, b::Vector{<:Position})`. When different behavior on different types is defined by a programmer, as shown above, it is also called *implementation specialization*. There is another type of specialization, called *compiler specialization*, which occurs when the compiler generates different functions for you from a single method. For example for \nmove(Position(1,1), Position(2,2))\nmove(Position(1.0,1.0), Position(2.0,2.0))\n# the compiler generates two methods, one for `Position{Int64}` and the other for `Position{Float64}`. Notice that inside generated functions, the compiler needs to use different intrinsic operations, which can be viewed from \n@code_native move(Position(1,1), Position(2,2))\n# and \n@code_native move(Position(1.0,1.0), Position(2.0,2.0))\n\n# ## Intermezzo: How does the Julia compiler work?\n# Let's walk through an example. Consider the following definitions\nmove(a::Position, by::Position) = Position(a.x + by.x, a.y + by.y)\nmove(a::T, by::T) where {T<:Position} = Position(a.x + by.x, a.y + by.y)\nmove(a::Position{Float64}, by::Position{Float64}) = Position(a.x + by.x, a.y + by.y)\nmove(a::Vector{<:Position}, by::Vector{<:Position}) = move.(a, by)\nmove(a::Vector{<:Position}, by::Position) = move.(a, by)\nnothing # hide\n# and a function call \na = Position(1.0, 1.0)\nby = Position(2.0, 2.0)\nmove(a, by)\n# 1. The compiler knows that you call the function `move`.\n# 2. The compiler infers the type of the arguments. You can view the result with\n(typeof(a),typeof(by))\n# 3. The compiler identifies all `move`-methods with arguments of type `(Position{Float64}, Position{Float64})`:\nBase.method_instances(move, (typeof(a), typeof(by)))\n# (For demonstration we can store the method we want in a variable `m`)\nm = Base.method_instances(move, (typeof(a), typeof(by))) |> first\nnothing # hide\n# 4a. If the method has been specialized (compiled), then the arguments are prepared and the method is invoked. The compiled specialization can be seen from \nm.cache\n# 4b. If the method has not been specialized (compiled), the method is compiled for the given type of arguments and continues as in step 4a.\n# A compiled function is therefore a \"blob\" of **native code** living in a particular memory location. When Julia calls a function, it needs to pick the right block corresponding to a function with particular type of parameters.\n#\n# If the compiler cannot narrow the types of arguments to concrete types, it has to perform the above procedure inside the called function, which has negative effects on performance, as the type resulution and identification of the methods can be slow, especially for methods with many arguments (e.g. 30ns for a method with one argument, \n# 100 ns for method with two arguements).\n# Recall the above example \nwolfpack_a = [Wolf(\"1\", 1), Wolf(\"2\", 2), Wolf(\"3\", 3)]\n@benchmark energy(wolfpack_a)\n# and \nwolfpack_b = Any[Wolf(\"1\", 1), Wolf(\"2\", 2), Wolf(\"3\", 3)]\n@benchmark energy(wolfpack_b)\n# An interesting intermediate between fully abstract and fully concrete type happens, when the compiler knows that arguments have abstract type, which is composed of a small number of concrete types. This case called Union-Splitting, which happens when there is just a little bit of uncertainty. Julia will do something like\n# ```julia\n# argtypes = typeof(args)\n# push!(execution_stack, args)\n# if T == Tuple{Int, Bool}\n# @goto compiled_blob_1234\n# else # the only other option is Tuple{Float64, Bool}\n# @goto compiled_blob_1236\n# end\n# ``` \n# For example \nconst WolfOrSheep = Union{Wolf, Sheep}\nwolfpack_c = WolfOrSheep[Wolf(\"1\", 1), Wolf(\"2\", 2), Wolf(\"3\", 3)]\n@benchmark energy(wolfpack_c)\n# Thanks to union splitting, Julia is able to have performant operations on arrays with undefined / missing values for example \n[1, 2, 3, missing] |> typeof\n\n# ### More on matching methods and arguments\n# In the above process, the step, where Julia looks for a method instance with corresponding parameters can be very confusing. The rest of this lecture will focus on this. For those who want to have a formal background, we recommend [talk of Francesco Zappa Nardelli](https://www.youtube.com/watch?v=Y95fAipREHQ) and / or the one of [Jan Vitek](https://www.youtube.com/watch?v=LT4AP7CUMAw).\n# \n# When Julia needs to specialize a method instance, it needs to find it among multiple definitions. A single function can have many method instances, see for example `methods(+)` which lists all method instances of the `+`-function. How does Julia select the proper one?\n# 1. It finds all methods where the type of arguments match or are subtypes of restrictions on arguments in the method definition.\n# 2a. If there are multiple matches, the compiler selects the most specific definition. \n# 2b. If the compiler cannot decide, which method instance to choose, it throws an error. \nconfused_move(a::Position{Float64}, by) = Position(a.x + by.x, a.y + by.y)\nconfused_move(a, by::Position{Float64}) = Position(a.x + by.x, a.y + by.y)\nconfused_move(Position(1.0,2.0), Position(1.0,2.0))\n# 2c. If it cannot find a suitable method, it throws an error.\nmove(Position(1,2), VaguePosition(\"hello\",\"world\"))\n\n# Some examples\n# Consider following definitions\nmove(a::Position, by::Position) = Position(a.x + by.x, a.y + by.y)\nmove(a::T, by::T) where {T<:Position} = T(a.x + by.x, a.y + by.y)\nmove(a::Position{Float64}, by::Position{Float64}) = Position(a.x + by.x, a.y + by.y)\nmove(a::Vector{<:Position}, by::Vector{<:Position}) = move.(a, by)\nmove(a::Vector{T}, by::Vector{T}) where {T<:Position} = move.(a, by)\nmove(a::Vector{<:Position}, by::Position) = move.(a, by)\n# Which method will compiler select for \nmove(Position(1.0,2.0), Position(1.0,2.0))\n# The first three methods match the types of argumens, but the compiler will select the third one, since it is the most specific.\n#\n# Which method will compiler select for \nmove(Position(1,2), Position(1,2))\n# Again, the first and second method definitions match the argument, but the second is the most specific.\n#\n# Which method will the compiler select for \nmove([Position(1,2)], [Position(1,2)])\n# Again, the fourth and fifth method definitions match the argument, but the fifth is the most specific.\nmove([Position(1,2), Position(1.0,2.0)], [Position(1,2), Position(1.0,2.0)])\n\n# ### Frequent problems\n# 1. Why does the following fail?\nfoo(a::Vector{Real}) = println(\"Vector{Real}\")\nfoo([1.0,2,3])\n# Julia's type system is **invariant**, which means that `Vector{Real}` is different from `Vector{Float64}` and from `Vector{Float32}`, even though `Float64` and `Float32` are sub-types of `Real`. Therefore `typeof([1.0,2,3])` isa `Vector{Float64}` which is not subtype of `Vector{Real}.` For **covariant** languages, this would be true. For more information on variance in computer languages, [see here](https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)). If de above definition of `foo` should be applicable to all vectors which has elements of subtype of `Real` we have define it as \nfoo(a::Vector{T}) where {T<:Real} = println(\"Vector{T} where {T<:Real}\")\n# or equivalently but more tersely as \nfoo(a::Vector{<:Real}) = println(\"Vector{T} where {T<:Real}\")\n# 2. Diagonal rule says that a repeated type in a method signature has to be a concrete type. Consider for example the function below\nmove(a::T, b::T) where {T<:Position}\n# we cannot call it with `move(Position(1.0,2.0), Position(1,2))`, since in this case `Position(1.0,2.0)` is of type `Position{Float64}` while `Position(1,2)` is of type `Position{Int64}`.\n# 3. When debugging why arguments do not match a particular method definition, it is useful to use `typeof`, `isa`, and `<:` commands. For example \ntypeof(Position(1.0,2.0))\n#\ntypeof(Position(1,2))\n#\nPosition(1,2) isa Position{Float64}\n#\nPosition(1,2) isa Position{Real}\n#\nPosition(1,2) isa Position{<:Real}\n#\ntypeof(Position(1,2)) <: Position{<:Float64}\n#\ntypeof(Position(1,2)) <: Position{<:Real}\n\n\n# ### A bizzare definition which you can encounter\n# The following definition of a one-hot matrix is taken from [Flux.jl](https://github.com/FluxML/Flux.jl/blob/1a0b51938b9a3d679c6950eece214cd18108395f/src/onehot.jl#L10-L12)\nstruct OneHotArray{T<:Integer, L, N, var\"N+1\", I<:Union{T,AbstractArray{T, N}}} <: AbstractArray{Bool, var\"N+1\"}\n indices::I\nend\n# The parameters of the type carry information about the type used to encode the position of `one` in each column in `T`, the dimension of one-hot vectors in `L`, the dimension of the storage of `indices` in `N` (which is zero for `OneHotVector` and one for `OneHotMatrix`), number of dimensions of the `OneHotArray` in `var\"N+1\"` and the type of underlying storage of indicies `I`.\n\n\n", "meta": {"hexsha": "d3044e4353e379c98cc312e9d19edb830f1a3b86", "size": 27940, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/lecture_02/lecture.jl", "max_stars_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_stars_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2021-11-12T10:17:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T21:40:39.000Z", "max_issues_repo_path": "docs/src/lecture_02/lecture.jl", "max_issues_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_issues_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-10-06T09:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T15:15:03.000Z", "max_forks_repo_path": "docs/src/lecture_02/lecture.jl", "max_forks_repo_name": "JuliaTeachingCTU/Scientific-Programming-in-Julia", "max_forks_repo_head_hexsha": "7e978fc27ae547fbf95d1367ef1d1d029267e356", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-05T16:45:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:21:34.000Z", "avg_line_length": 66.3657957245, "max_line_length": 615, "alphanum_fraction": 0.7439871152, "num_tokens": 7110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.19863081737872096}} {"text": "include(\"lidar_sensors.jl\")\n\ntype MultiFeatureExtractor <: AbstractFeatureExtractor\n extract_core::Bool # [8] if true, extract lane offset, lane relative heading, speed, vehicle width, vehicle length, marker dist left+right, lane curvature\n extract_temporal::Bool # [6] if true, extract accel, jerk, turnrate G, angular rate G, turnrate F, angular rate F\n extract_well_behaved::Bool # [3] if true, extract is_colliding, is_offroad, is_reversing\n extract_neighbor_features::Bool # [28] if true, extract everything that can be missing in tim2d features (ie, speed/dist fore, etc.)\n extract_carlidar_rangerate::Bool # [nbeams] if true, extract range rate as well as range\n\n carlidar::LidarSensor # [2*nbeams] NOTE: range rate can be turned off.\n roadlidar::RoadlineLidarSensor # [nbeams × depth]\n road_lidar_culling::RoadwayLidarCulling\nend\nfunction MultiFeatureExtractor(\n extract_core::Bool,\n extract_temporal::Bool,\n extract_well_behaved::Bool,\n extract_neighbor_features::Bool,\n extract_carlidar_rangerate::Bool,\n carlidar_nbeams::Int,\n roadlidar_nbeams::Int,\n roadlidar_nlanes::Int,\n ;\n carlidar_max_range::Float64 = 100.0, # [m]\n roadlidar_max_range::Float64 = 100.0, # [m]\n )\n\n carlidar = LidarSensor(carlidar_nbeams, max_range=carlidar_max_range, angle_offset=-π)\n roadlidar = RoadlineLidarSensor(roadlidar_nbeams, max_range=roadlidar_max_range, angle_offset=-π, max_depth=roadlidar_nlanes)\n\n MultiFeatureExtractor(\n extract_core,\n extract_temporal,\n extract_well_behaved,\n extract_neighbor_features,\n extract_carlidar_rangerate,\n carlidar,\n roadlidar,\n RoadwayLidarCulling(),\n )\nend\n\nAutomotiveDrivingModels.rec_length(ext::MultiFeatureExtractor) = ext.extract_temporal ? 3 : 1\nfunction Base.length(ext::MultiFeatureExtractor)\n nbeams_carlidar = nbeams(ext.carlidar)\n nbeams_roadlidar = nbeams(ext.roadlidar)\n nlanes_roadlidar = nlanes(ext.roadlidar)\n\n 8 * ext.extract_core +\n 6 * ext.extract_temporal +\n 3 * ext.extract_well_behaved +\n 28 * ext.extract_neighbor_features +\n nbeams_carlidar * (1 + ext.extract_carlidar_rangerate) +\n nbeams_roadlidar * nlanes_roadlidar\nend\nfunction get_start_of_feature_section(ext::MultiFeatureExtractor)\n\n nbeams_carlidar = nbeams(ext.carlidar)\n nbeams_roadlidar = nbeams(ext.roadlidar)\n nlanes_roadlidar = nlanes(ext.roadlidar)\n\n i = 0\n core = temporal = well_behaved = neighbor = carlidar_range = carlidar_range_rate = roadlidar_range = -1\n\n if ext.extract_core\n core = 1\n i += 8\n end\n if ext.extract_temporal\n temporal = i\n i += 6\n end\n if ext.extract_well_behaved\n well_behaved = i\n i += 3\n end\n if ext.extract_neighbor_features\n neighbor = i\n i += 28\n end\n if nbeams_carlidar > 0\n carlidar_range = i\n i += nbeams_carlidar\n\n if ext.extract_carlidar_rangerate\n carlidar_range_rate = i\n i += nbeams_carlidar\n end\n end\n if nbeams_roadlidar > 0\n roadlidar_range = i\n i += nbeams_roadlidar * nlanes_roadlidar\n end\n\n (core, temporal, well_behaved, neighbor, carlidar_range, carlidar_range_rate, roadlidar_range, i)\nend\nfunction AutomotiveDrivingModels.pull_features!{F<:AbstractFloat}(ext::MultiFeatureExtractor,\n features::Vector{F},\n rec::SceneRecord,\n roadway::Roadway,\n vehicle_index::Int,\n pastframe::Int=0,\n )\n\n feature_index = 0\n scene = get_scene(rec, pastframe)\n veh_ego = scene[vehicle_index]\n\n d_ml = convert(Float64, get(MARKERDIST_LEFT, rec, roadway, vehicle_index, pastframe))\n d_mr = convert(Float64, get(MARKERDIST_RIGHT, rec, roadway, vehicle_index, pastframe))\n\n if ext.extract_core\n #=\n 1 - lane offset (positive to left) [m]\n 2 - lane relative heading (positive to left) [rad]\n 3 - speed [m/s]\n 4 - vehicle length [m]\n 5 - vehicle width [m]\n 6 - lane curvature [1/m]\n 7 - Marker Dist left\n 8 - Marker Dist right\n =#\n\n features[feature_index+=1] = veh_ego.state.posF.t\n features[feature_index+=1] = veh_ego.state.posF.ϕ\n features[feature_index+=1] = veh_ego.state.v\n features[feature_index+=1] = veh_ego.def.length\n features[feature_index+=1] = veh_ego.def.width\n features[feature_index+=1] = convert(Float64, get(LANECURVATURE, rec, roadway, vehicle_index, pastframe))\n features[feature_index+=1] = d_ml\n features[feature_index+=1] = d_mr\n end\n\n if ext.extract_temporal\n #=\n 1 - previous acceleration [m/s²]\n 2 - previous jerk [m/s³]\n 3 - previous turnrate G [rad/s]\n 4 - previous angular rate G [rad/s²]\n 5 - previous turnrate F [rad/s]\n 6 - previous angular rate F [rad/s²]\n =#\n\n features[feature_index+=1] = convert(Float64, get(ACC, rec, roadway, vehicle_index, pastframe))\n features[feature_index+=1] = convert(Float64, get(JERK, rec, roadway, vehicle_index, pastframe))\n features[feature_index+=1] = convert(Float64, get(TURNRATEG, rec, roadway, vehicle_index, pastframe))\n features[feature_index+=1] = convert(Float64, get(ANGULARRATEG, rec, roadway, vehicle_index, pastframe))\n features[feature_index+=1] = convert(Float64, get(TURNRATEF, rec, roadway, vehicle_index, pastframe))\n features[feature_index+=1] = convert(Float64, get(ANGULARRATEF, rec, roadway, vehicle_index, pastframe))\n end\n\n if ext.extract_well_behaved\n #=\n 1 - is colliding\n 2 - is offroad\n 3 - is reversing\n =#\n\n features[feature_index+=1] = convert(Float64, get(IS_COLLIDING, rec, roadway, vehicle_index, pastframe))\n features[feature_index+=1] = convert(Float64, d_ml < -1.0 || d_mr < -1.0)\n features[feature_index+=1] = convert(Float64, veh_ego.state.v < 0.0)\n end\n\n if ext.extract_neighbor_features\n #=\n can be missing: - first is feature, 2nd is indicator whether it is missing (0 if exists, 1 if missing)\n (1, 2) - lane offset from left lane\n (3, 4) - lane offset from right lane\n (5, 6) - speed fore middle\n (7, 8) - dist fore middle (distance along the lane from the front of the ego car to the rear of the ego car in the same lane)\n (9, 10) - speed fore left\n (11,12) - dist fore left\n (13,14) - speed fore right\n (15,16) - dist fore right\n (17,18) - speed rear middle\n (19,20) - dist fore middle\n (21,22) - speed rear left\n (23,24) - dist rear left\n (25,26) - speed rear right\n (27,28) - dist rear right\n =#\n\n vtpf = VehicleTargetPointFront()\n vtpr = VehicleTargetPointRear()\n fore_M = get_neighbor_fore_along_lane( scene, vehicle_index, roadway, vtpf, vtpr, vtpf)\n fore_L = get_neighbor_fore_along_left_lane( scene, vehicle_index, roadway, vtpf, vtpr, vtpf)\n fore_R = get_neighbor_fore_along_right_lane(scene, vehicle_index, roadway, vtpf, vtpr, vtpf)\n rear_M = get_neighbor_rear_along_lane( scene, vehicle_index, roadway, vtpr, vtpf, vtpr)\n rear_L = get_neighbor_rear_along_left_lane( scene, vehicle_index, roadway, vtpr, vtpf, vtpr)\n rear_R = get_neighbor_rear_along_right_lane(scene, vehicle_index, roadway, vtpr, vtpf, vtpr)\n\n function set_feature_missing!(features::Vector, i::Int)\n features[i] = 0.0\n features[i+1] = 1.0\n features\n end\n function set_feature!(features::Vector, i::Int, v::Float64)\n features[i] = v\n features[i+1] = 0.0\n features\n end\n function set_dual_feature!(features::Vector, i::Int, f::FeatureValue)\n if f.i == FeatureState.MISSING\n set_feature_missing!(features, i)\n else\n set_feature!(features, i, f.v)\n end\n features\n end\n function set_speed_and_distance!(features::Vector, i::Int, neigh::NeighborLongitudinalResult)\n neigh.ind != 0 ? set_feature!(features, i, scene[neigh.ind].state.v) :\n set_feature_missing!(features, i)\n neigh.ind != 0 ? set_feature!(features, i+2, neigh.Δs) :\n set_feature_missing!(features, i+2)\n features\n end\n\n set_dual_feature!(features, feature_index+=1, get(LANEOFFSETLEFT, rec, roadway, vehicle_index, pastframe))\n feature_index+=1\n set_dual_feature!(features, feature_index+=1, get(LANEOFFSETRIGHT, rec, roadway, vehicle_index, pastframe))\n feature_index+=1\n\n set_speed_and_distance!(features, feature_index+=1, fore_M); feature_index+=3\n set_speed_and_distance!(features, feature_index+=1, fore_L); feature_index+=3\n set_speed_and_distance!(features, feature_index+=1, fore_R); feature_index+=3\n set_speed_and_distance!(features, feature_index+=1, rear_M); feature_index+=3\n set_speed_and_distance!(features, feature_index+=1, rear_L); feature_index+=3\n set_speed_and_distance!(features, feature_index+=1, rear_R); feature_index+=3\n end\n\n nbeams_carlidar = nbeams(ext.carlidar)\n if nbeams_carlidar > 0\n observe!(ext.carlidar, scene, roadway, vehicle_index)\n copy!(features, feature_index+=1, ext.carlidar.ranges, 1)\n feature_index += nbeams_carlidar - 1\n if ext.extract_carlidar_rangerate\n copy!(features, feature_index+=1, ext.carlidar.range_rates, 1)\n feature_index += nbeams_carlidar - 1\n end\n end\n\n nbeams_roadlidar = nbeams(ext.roadlidar)\n if nbeams_roadlidar > 0\n if ext.road_lidar_culling.is_leaf\n observe!(ext.roadlidar, scene, roadway, vehicle_index)\n else\n observe!(ext.roadlidar, scene, roadway, vehicle_index, ext.road_lidar_culling)\n end\n copy!(features, feature_index+=1, ext.roadlidar.ranges)\n feature_index += length(ext.roadlidar.ranges) - 1\n end\n\n @assert(feature_index == length(features))\n if findfirst(v->isnan(v), features) != 0\n error(\"feature $(findfirst(v->isnan(v), features)) is nan\")\n end\n\n features\nend\n\n", "meta": {"hexsha": "a23446f9ad575a973c973ce66f8c0d658c894e17", "size": 10307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/pull_traces/multifeatureset.jl", "max_stars_repo_name": "yoshihikokuwahara/gail-driver", "max_stars_repo_head_hexsha": "fbb9d24f0dcd7edc4211b0b2fc6a6622a6942dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/pull_traces/multifeatureset.jl", "max_issues_repo_name": "yoshihikokuwahara/gail-driver", "max_issues_repo_head_hexsha": "fbb9d24f0dcd7edc4211b0b2fc6a6622a6942dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/pull_traces/multifeatureset.jl", "max_forks_repo_name": "yoshihikokuwahara/gail-driver", "max_forks_repo_head_hexsha": "fbb9d24f0dcd7edc4211b0b2fc6a6622a6942dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4904214559, "max_line_length": 158, "alphanum_fraction": 0.6589696323, "num_tokens": 2899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.1986063489461212}} {"text": "const element = [\"H\", \"He\", \"Li\", \"Be\", \"B\", \"C\", \"N\", \"O\", \"F\", \"Ne\",\n \"Na\", \"Mg\", \"Al\", \"Si\", \"P\", \"S\", \"Cl\", \"Ar\", \"K\", \"Ca\",\n \"Sc\", \"Ti\", \"V\", \"Cr\", \"Mn\", \"Fe\", \"Co\", \"Ni\", \"Cu\", \"Zn\",\n \"Ga\", \"Ge\", \"As\", \"Se\", \"Br\", \"Kr\", \"Rb\", \"Sr\", \"Y\", \"Zr\",\n \"Nb\", \"Mo\", \"Tc\", \"Ru\", \"Rh\", \"Pd\", \"Ag\", \"Cd\", \"In\", \"Sn\",\n \"Sb\", \"Te\", \"I\", \"Xe\", \"Cs\", \"Ba\", \"La\", \"Ce\", \"Pr\", \"Nd\",\n \"Pm\", \"Sm\", \"Eu\", \"Gd\", \"Tb\", \"Dy\", \"Ho\", \"Er\", \"Tm\", \"Yb\",\n \"Lu\", \"Hf\", \"Ta\", \"W\", \"Re\", \"Os\", \"Ir\", \"Pt\", \"Au\", \"Hg\",\n \"Tl\", \"Pb\", \"Bi\", \"Po\", \"At\", \"Rn\", \"Fr\", \"Ra\", \"Ac\", \"Th\",\n \"Pa\", \"U\", \"Np\", \"Pu\", \"Am\", \"Cm\", \"Bk\", \"Cf\", \"Es\", \"Fm\",\n \"Md\", \"No\", \"Lr\", \"Rf\", \"Db\", \"Sg\", \"Bh\", \"Hs\", \"Mt\", \"Ds\",\n \"Rg\", \"Cn\", \"Nh\", \"Fl\", \"Mc\", \"Lv\", \"Ts\", \"Og\"]\n\nconst reg = r\"[0-9]+\"\n\nstruct bit2b\n a::Int64\n b::Int64\n c::Int64\n d::Int64\nend\n\nstruct ifph\n i::Int64\n f::Int64\n phase::Bool\nend\n\nstruct Jpninfo\n fac::Float64\n pjump::Array{ifph,1}\n njump::Array{ifph,1}\nend\n\nstruct T1info\n f::Int64\n coef::Float64\nend\n\nstruct MiMf\n Mi::Int64\n Mf::Int64\n fac::Float64\nend\n\n\"\"\"\n main(sntf,target_nuc,num_ev,target_J;\n save_wav=false,q=1,is_block=false,is_show=false,num_history=3,lm=100,ls=20,tol=1.e-6,\n in_wf=\"\",mdimmode=false,calc_moment = false,gfactors = [1.0,0.0,5.586,-3.826],effcharge=[1.5,0.5])\n\nDigonalize the model-space Hamiltonian \n\n# Arguments: \n\n- `sntf`: path to input interaction file (.snt fmt)\n- `target_nuc`: target nucleus\n- `num_ev`: number of eigenstates to be evaluated\n- `target_J`: target total J (specified by e.g. [0]). Set to [] if you want lowest states with any J. \n Note that J should be doubled (J=0=>[0], J=1/2=>[1], J=1=>[2],...) \n\n# Optional arguments:\n- `q=1` block size for Block-Lanczos methods \n- `is_block=false` whether or not to use Block algorithm \n- `save_wav=false` whether or not to save wavefunction file \n- `is_show = true` to show elapsed time & allocations \n- `lm = 100` number of Lanczos vectors to store \n- `ls = 15` number of vectors to be used for Thick-Restart \n- `tol= 1.e-6` tolerance for convergence check in the Lanczos method \n- `in_wf=\"\"` path to initial w.f. (for preprocessing) \n- `mdimmode=false` `true` => calculate only the M-scheme dimension\n- `calc_moment=false` `true` => calculate mu&Q moments \n- `calc_entropy=false` `true` => calculate entanglement entropy\n- `gfactors=[1.0,0.0,5.586,-3.826]` angular momentum and spin g-factors \n- `effcgarge=[1.5,0.5]` effective charges \n\"\"\"\nfunction main(sntf,target_nuc,num_ev,target_J;save_wav=false,\n q=1,is_block=false,is_show=false,\n num_history=3,lm=100,ls=20,tol=1.e-6,\n in_wf=\"\",mdimmode=false,\n calc_moment = false,\n calc_entropy = false,\n gfactors = [1.0,0.0,5.586,-3.826],\n effcharge=[1.5,0.5])\n to = TimerOutput()\n Anum = parse(Int64, match(reg,target_nuc).match)\n lp,ln,cp,cn,massop,Aref,pow,p_sps,n_sps,SPEs,olabels,oTBMEs,labels,TBMEs = readsnt(sntf,Anum)\n massformula = 1\n if 16<= Anum <= 40; massformula = 2;end\n ## massformula=2: J. Blomqvist and A. Molinari, Nucl. Phys. A106, 545 (1968).\n ## we use this for the sd-shell nuclei\n hw, bpar = init_ho_by_mass(Anum,massformula)\n\n if length(target_J) > 1;\n println(\"warn! Multiple J is not supported now.\");exit()\n end\n Mtot = 0;if Anum % 2 != 0; Mtot = 1;end\n tJ = -1; eval_jj = -1.0\n if length(target_J) > 0; Mtot = minimum(target_J);tJ=target_J[1];\n eval_jj = 0.5*tJ*(tJ/2+1) ; end\n if Anum % 2 != Mtot % 2; println(\"invalid targetJ $tJ\");exit();end\n target_el = replace.(target_nuc, string(Anum)=>\"\")\n Z,N,vp,vn = getZNA(target_el,Anum,cp,cn)\n mstates_p, mstates_n,mz_p,mz_n = def_mstates(p_sps,n_sps)\n pbits,nbits,jocc_p,jocc_n,Mps,Mns,tdims = occ(p_sps,mstates_p,mz_p,vp,\n n_sps,mstates_n,mz_n,vn,Mtot)\n lblock=length(pbits)\n mdim = tdims[end]; if mdim==0;exit();end\n\n mdim_print(target_nuc,Z,N,cp,cn,vp,vn,mdim,tJ)\n if mdimmode; return nothing;end\n\n @timeit to \"prep. 1bjumps\" begin\n ## bit representation of Hamiltonian operators\n bV1,V1 = HbitT1(p_sps,n_sps,mstates_p,mstates_n,labels,TBMEs)\n bVpn,Vpn,delMs = Hbitpn(p_sps,n_sps,mstates_p,mstates_n,labels[3],TBMEs[3])\n\n ## storing two-body jumps for pp/nn 2b interaction\n ppinfo = prep_pp(mstates_p,pbits,bV1[1],V1[1])\n nninfo = prep_nn(mstates_n,nbits,bV1[2],V1[2])\n bV1 = nothing\n\n ## storing one-body jumps for pn 2b interaction\n l_pbit = length(mstates_p);l_nbit = length(mstates_n)\n bis,bfs,p_NiNfs,n_NiNfs,num_task = prep_pn(lblock,tdims,l_pbit,l_nbit,\n pbits,nbits,Mps,delMs,bVpn,Vpn)\n bVpn=nothing\n end\n ## distribute task\n block_tasks = make_distribute(num_task)\n\n @timeit to \"Jcalc.\" begin\n oPP,oNN,oPNu,oPNd = prep_J(tdims,p_sps,n_sps,mstates_p,mstates_n,\n pbits,nbits)\n Js = [ 0.5*Mtot*(0.5*Mtot+1) for i = 1:num_ev]\n Jtasks = zeros(Int64,lblock)\n for i = 1:lblock\n Jtasks[i] = length(pbits[i])*length(nbits[i])\n end\n Jidxs = make_distribute_J(Jtasks)\n end\n\n @timeit to \"Lanczos\" begin\n en =[ [1.e+4 for j=1:num_ev] for i = 1:num_history]\n Rvecs = [ zeros(Float64,mdim) for i=1:num_ev]\n Tmat = zeros(Float64,lm,lm)\n vks =[]; uks=[];itmin = 1; elit=1\n doubleLanczos = false\n if tJ !=-1; doubleLanczos = true;end\n \n if is_block #Thick-Restart double Block Lanczos: TRdBL\n ls_sub = div(ls,q)\n vks = [ zeros(Float64,q,mdim) for i=1:div(lm,q)]\n uks = [ zeros(Float64,q,mdim) for i=1:ls_sub*q]\n Beta_H = zeros(Float64,q,q)\n V = vks[1]\n if in_wf !=\"\"\n try\n read_appwav(in_wf,mdim,V,q,true)\n bl_QR!(V',Beta_H,mdim,q)\n catch\n println(\"error @preprocessing: failed to read appwav\")\n initialize_bl_wav(mdim,q,vks[1])\n bl_QR!(V',Beta_H,mdim,q)\n end\n else\n initialize_bl_wav(mdim,q,vks[1])\n bl_QR!(V',Beta_H,mdim,q)\n end\n elit = TRBL(q,vks,uks,Tmat,Beta_H,pbits,nbits,jocc_p,jocc_n,SPEs,\n ppinfo,nninfo,bis,bfs,block_tasks,\n p_NiNfs,n_NiNfs,Mps,delMs,Vpn,tdims,\n eval_jj,oPP,oNN,oPNu,oPNd,Jidxs,\n num_ev,num_history,lm,ls_sub,en,tol,to,doubleLanczos) \n else #Thick Restart (double) Lanczos: TRL\n vks = [ zeros(Float64,mdim) for i=1:lm]\n uks = [ zeros(Float64,mdim) for i=1:ls] \n initialize_wf(vks[1],\"rand\",tJ,mdim)\n elit = TRL(vks,uks,Tmat,itmin,\n pbits,nbits,jocc_p,jocc_n,SPEs,\n ppinfo,nninfo,bis,bfs,block_tasks,\n p_NiNfs,n_NiNfs,Mps,delMs,Vpn,\n eval_jj,oPP,oNN,oPNu,oPNd,Jidxs,\n tdims,num_ev,num_history,lm,ls,en,tol,to,doubleLanczos)\n end\n end\n\n @timeit to \"Rvecs\" begin\n vals,vecs = eigen(@views Tmat[1:elit*q,1:elit*q])\n @inbounds for (nth,Rvec) in enumerate(Rvecs)\n if is_block == false\n @inbounds for k=1:length(vals)\n Rvec .+= vecs[k,nth] .* vks[k]\n end\n else\n @inbounds for k=1:length(vals)\n it = div(k-1,q)\n b = k - q*it \n Rvec .+= @views vecs[k,nth] .* vks[it+1][b,:]\n end\n end\n Rvec .*= 1.0/sqrt(dot(Rvec,Rvec))\n end\n end\n vt = zeros(Float64,mdim)\n for (nth,Rv) in enumerate(Rvecs)\n vt .= 0.0\n operate_J!(Rv,vt,pbits,nbits,tdims,\n Jidxs,oPP,oNN,oPNu,oPNd)\n Js[nth] += dot(Rv,vt)\n end\n totJs = J_from_JJ1.(Js)\n ### entanglement entropy \n if calc_entropy\n entropy(Rvecs,pbits,nbits,tdims,to)\n end\n ### mu&Q-moment\n tx_mom =\"\"\n if calc_moment \n tx_mom = eval_moment(Mtot,Rvecs,totJs,p_sps,n_sps,\n mstates_p,mstates_n,tdims,\n jocc_p,jocc_n,pbits,nbits,bpar,\n gfactors,effcharge)\n end \n if save_wav\n @timeit to \"I/O\" begin\n csnt = split(split(sntf,\"/\")[end],\".\")[1]\n oupf=\"./\"*target_nuc*\"_\"*csnt*\".wav\"\n if tJ != -1;oupf=\"./\"*target_nuc*\"_\"*csnt*\"_j\"*string(tJ)*\".wav\";end\n writeRitzvecs(mdim,Mtot,en[1],totJs,Rvecs,oupf)\n end\n end \n if is_show\n show(to, allocations = true,compact = true);println(\"\")\n end\n println(\"sntf: $sntf\")\n println(\"J $totJs\")\n print(\"En. \");map(x -> @printf(\"%9.3f \",x), en[1])\n print(\"\\nEx. \");map(x -> @printf(\"%9.3f \",x),[en[1][i]-en[1][1] for i=1:num_ev])\n print(\"\\n\")\n if tx_mom != \"\"\n println(tx_mom)\n end\n return nothing\nend\n\nfunction rm_comment(lines)\n nlines = []\n for line in lines\n line = strip(line)\n if length(line)>1\n if startswith(line,\"!\")\n continue\n end\n end\n push!(nlines,line)\n end\n return nlines\nend\n\nfunction rm_nan(array)\n na = []\n for tmp in array\n if tmp != \"\";push!(na,tmp); end\n end\n return na\nend\n\n\"\"\"\n readsnt(sntf,Anum)\n\nTo read interaction file in \".snt\" format.\n- `sntf`: path to the interaction file\n- `Anum`: mass number (used for \"scaling\" of TBMEs)\n\n!!! note\n The current version supports only \"properly ordered\" interaction file in .snt format.\n \n A .snt file can be ordered to be a<=b,c<=d,a<=c for V(abcd;J) by the Python script \"ShellModel.jl/src/make_ordered_snt.py\"(, which will be replaced by Julia implementation...).\n\n\"\"\"\nfunction readsnt(sntf,Anum) \n f = open(sntf,\"r\");tlines = readlines(f);close(f)\n lines = rm_comment(tlines)\n line = lines[1]\n lp,ln,cp,cn = map(x->parse(Int,x),rm_nan(split(line,\" \")))\n p_sps = [[0,0]];deleteat!(p_sps,1)\n n_sps = [[0,0]];deleteat!(n_sps,1)\n @inbounds for i = 1:lp\n ith,n,l,j,tz = map(x->parse(Int,x),rm_nan(split(lines[1+i],\" \"))[1:5])\n push!(p_sps,[n,l,j,tz])\n end\n @inbounds for i = 1:ln\n ith, n,l,j,tz = map(x->parse(Int,x),rm_nan(split(lines[1+i+ln],\" \"))[1:5])\n push!(n_sps,[n,l,j,tz])\n end\n nsp,zero = map(x->parse(Int,x),rm_nan(split(lines[1+ln+lp+1],\" \"))[1:2])\n SPEs = [ [0.0 for i=1:lp],[0.0 for i=1:ln]]\n @inbounds for i = 1:nsp\n idx=0; j=i\n if i<=lp;idx=1;else;idx=2;j-=lp;end\n SPEs[idx][j] =parse(Float64,rm_nan(split(lines[1+ln+lp+1+i],\" \"))[3])\n end\n ntbme,massop,Aref,p = rm_nan(split(lines[1+ln+lp+1+nsp+1],\" \"))\n ntbme = parse(Int,ntbme); massop=parse(Int,massop)\n Aref = parse(Int,Aref); p = parse(Float64,p)\n labels = [ [ [0,0] ] for i=1:3]\n olabels = [ [0,0] ]\n for i=1:3; deleteat!(labels[i],1);end\n deleteat!(olabels,1)\n TBMEs=[ Float64[] for i =1:3] #pp/nn/pn\n oTBMEs= Float64[]\n @inbounds for ith = 1:ntbme\n tmp = rm_nan(split(lines[1+ln+lp+1+nsp+1+ith], \" \"))\n i = tmp[1]; j = tmp[2]; k = tmp[3]; l =tmp[4]; totJ = tmp[5]; TBME= tmp[6] \n i = parse(Int,i);j = parse(Int,j);k = parse(Int,k);l = parse(Int,l);\n nth = 0\n if i<=lp && j<=lp\n nth = 1\n elseif i>lp && j > lp\n nth = 2\n elseif i<=lp && j>lp\n nth = 3\n else\n println(\"err\");exit()\n end\n ## snt file must be \"ordered\"; a<=b & c=d & a<=c\n TBME = parse(Float64,TBME)\n if massop == 1; TBME*= (Anum/Aref)^(p);end\n if unique([i,j]) != unique([k,l])\n push!(labels[nth],[k,l,i,j,parse(Int,totJ),ith])\n push!(TBMEs[nth],TBME)\n end\n push!(labels[nth],[i,j,k,l,parse(Int,totJ),ith])\n push!(TBMEs[nth],TBME)\n\n push!(olabels,[i,j,k,l,parse(Int,totJ),ith])\n push!(oTBMEs,TBME)\n end\n return lp,ln,cp,cn,massop,Aref,p,p_sps,n_sps,SPEs,olabels,oTBMEs,labels,TBMEs\nend\n\n\"\"\"\n def_mstate(p_sps, n_sps)\n\nTo define the single particle states specified by n,l,j,mz\n\"\"\"\nfunction def_mstates(p_sps,n_sps)\n mstates_p = [[1]]; mstates_n = [[1]]; mz_p = Int64[]; mz_n = Int64[]\n deleteat!(mstates_p,1); deleteat!(mstates_n,1)\n for (pidx,tsps) in enumerate(p_sps)\n n,l,j,tz = tsps\n for mz = -j:2:j;push!(mstates_p,[n,l,j,tz,mz,pidx]);push!(mz_p,mz);end\n end\n for (nidx,tsps) in enumerate(n_sps)\n n,l,j,tz = tsps\n for mz = -j:2:j;push!(mstates_n,[n,l,j,tz,mz,nidx]);push!(mz_n,mz);end\n end\n return mstates_p, mstates_n,mz_p,mz_n\nend\n\n\"\"\"\n all_perm!(ln::Int64,num_valence::Int64,occs::Array{Array{Bool,1}})\n\nmake all possible permutation of 'bits'\n\nExample:\nIf 2 protons and 1 neutron are in the 0p-shell space,\nvalence orbits(0p1/2,0p3/2) => -1/2, 1/2, -3/2, -1/2, 1/2, 3/2\n\nconfigurations are represented like:\n\n proton: 000011, 000101, ..., 110000\n\nneutron: 000001, 000010, ..., 100000\n\"\"\"\nfunction all_perm!(ln::Int64,num_valence::Int64,\n occs::Array{Array{Bool,1}})\n for (i,tcomb) in enumerate(collect(combinations(collect(1:ln),num_valence)))\n @inbounds for nth in tcomb\n occs[i][nth] = 1\n end\n end\n return nothing\nend\n\nfunction Mcount!(ln::Int64,mzs::Array{Int64,1},\n occ::Array{Bool,1},\n Mret::Array{Int64,1})\n Mret[1] = 0\n @inbounds for i = 1:ln\n if occ[i]\n Mret[1] += mzs[i]\n end\n end\n return nothing\nend\n\nfunction possible_mz(nljtz,mstates)\n n,l,j,tz = nljtz\n mzs = Int64[]; midxs=Int64[]\n for mz = -j:2:j\n push!(mzs,mz)\n for k = 1:length(mstates)\n if @views mstates[k][1:5] == [n,l,j,tz,mz]\n push!(midxs,k)\n break\n end\n end\n end\n return j,mzs, midxs\nend\n\nfunction initialize_tvec!(tvec::Array{Bool,1})\n tvec .= false\n return nothing\nend\n\n\"\"\"\n function HbitT1(p_sps::Array{Array{Int64,1}},n_sps::Array{Array{Int64,1}},\n mstates_p::Array{Array{Int64,1},1},mstates_n::Array{Array{Int64,1},1},\n labels::Array{Array{Array{Int64,1},1},1},TBMEs::Array{Array{Float64,1}})\n\nmake bit representation of T=1 (proton-proton&neutron-neutron) interactions for each {m_z}\n\"\"\"\nfunction HbitT1(p_sps::Array{Array{Int64,1}},\n n_sps::Array{Array{Int64,1}},\n mstates_p::Array{Array{Int64,1},1},\n mstates_n::Array{Array{Int64,1},1},\n labels::Array{Array{Array{Int64,1},1},1},\n TBMEs::Array{Array{Float64,1}})\n lp = length(mstates_p)\n ln = length(mstates_n)\n bV1 = [ bit2b[] for i=1:2 ]\n V1 = [ Float64[] for i=1:2]\n mstates = [mstates_p,mstates_n]\n sps = [p_sps,n_sps]\n loffs = [ 0, length(p_sps)]\n\n for vrank =1:2 #pp:1, nn:2\n loff = loffs[vrank]\n vecs= [ [ [ false for i = 1:lp] for j=1:2],\n [ [ false for i = 1:ln] for j=1:2]]\n blist = bit2b[]\n Vs=Float64[]\n @inbounds for (i,ME) in enumerate(TBMEs[vrank])\n a,b,c,d,totJ,dummy = labels[vrank][i]\n J2 = 2*totJ\n ja,ma_s,ma_idxs = possible_mz(sps[vrank][a-loff],mstates[vrank])\n jb,mb_s,mb_idxs = possible_mz(sps[vrank][b-loff],mstates[vrank])\n jc,mc_s,mc_idxs = possible_mz(sps[vrank][c-loff],mstates[vrank])\n jd,md_s,md_idxs = possible_mz(sps[vrank][d-loff],mstates[vrank])\n @inbounds for (ic,mc) in enumerate(mc_s)\n @inbounds for (id,md) in enumerate(md_s)\n if c == d && mc >= md; continue;end\n if abs(mc + md) > J2; continue;end\n M_ani = mc + md\n initialize_tvec!(vecs[vrank][1]);vecs[vrank][1][mc_idxs[ic]] = true\n bit_c = bitarr_to_int(vecs[vrank][1])\n initialize_tvec!(vecs[vrank][1]); vecs[vrank][1][md_idxs[id]] = true\n bit_d = bitarr_to_int(vecs[vrank][1])\n @inbounds for (ia,ma) in enumerate(ma_s)\n @inbounds for (ib,mb) in enumerate(mb_s)\n if a == b && ma>=mb; continue;end\n if ma + mb != M_ani;continue;end\n initialize_tvec!(vecs[vrank][2]);vecs[vrank][2][ma_idxs[ia]] = true\n bit_a = bitarr_to_int(vecs[vrank][2])\n initialize_tvec!(vecs[vrank][2]);vecs[vrank][2][mb_idxs[ib]] = true\n bit_b = bitarr_to_int(vecs[vrank][2])\n CG1 = clebschgordan(Float64,ja//2,ma//2,jb//2,mb//2, J2//2, M_ani//2)\n CG2 = clebschgordan(Float64,jc//2,mc//2,jd//2,md//2, J2//2, M_ani//2)\n tl = bit2b(bit_a,bit_b,bit_c,bit_d)\n if ( tl in blist) == false\n push!(blist,tl)\n push!(Vs, ME * sqrt( (1.0+deltaf(a,b)) *(1.0+deltaf(c,d)) ) * CG1 * CG2)\n continue\n end\n @inbounds for kk = 1:length(blist)\n if blist[kk] == tl\n Vs[kk] += ME * sqrt( (1.0+deltaf(a,b)) *(1.0+deltaf(c,d)) ) * CG1 * CG2\n break\n end\n end\n end\n end\n end\n end\n end\n bV1[vrank] = blist\n V1[vrank] = Vs\n end\n return bV1,V1 #bVpp,Vpp,bVnn,Vnn\nend\n\n\"\"\"\n Hbitpn(p_sps::Array{Array{Int64,1}},n_sps::Array{Array{Int64,1}},\n mstates_p::Array{Array{Int64,1},1},mstates_n::Array{Array{Int64,1},1},\n labels::Array{Array{Int64,1}},TBMEs::Array{Float64,1},zeroME=false)\n\nmake bit representation of T=0 (proton-neutron) interactions for each {m_z}\n\"\"\"\nfunction Hbitpn(p_sps::Array{Array{Int64,1}},\n n_sps::Array{Array{Int64,1}},\n mstates_p::Array{Array{Int64,1},1},\n mstates_n::Array{Array{Int64,1},1},\n labels::Array{Array{Int64,1}},\n TBMEs::Array{Float64,1},\n zeroME=false)\n lp = length(mstates_p); ln = length(mstates_n)\n loff = length(p_sps)\n Mzs = Int64[]\n for j = 1:lp\n for i = 1:lp\n push!(Mzs,mstates_p[i][5]-mstates_p[j][5])\n end\n end\n unique!(Mzs);sort!(Mzs,rev=true)\n lenMz = length(Mzs)\n\n bVpn= [ [[1,1]] for i=1:lenMz ]\n for i = 1:lenMz;deleteat!(bVpn[i],1);end\n Vpn=[ Float64[ ] for i=1:lenMz]\n\n ret = [-1,-1,-1]\n vec_ani_p = [false for i = 1:lp];vec_cre_p = [false for i = 1:lp]\n vec_ani_n = [false for i = 1:ln];vec_cre_n = [false for i = 1:ln]\n\n @inbounds for (i,ME) in enumerate(TBMEs)\n a,b,c,d,totJ,dummy = labels[i]\n J2 = 2*totJ\n ja,ma_s,ma_idxs = possible_mz(p_sps[a],mstates_p)\n jc,mc_s,mc_idxs = possible_mz(p_sps[c],mstates_p)\n jb,mb_s,mb_idxs = possible_mz(n_sps[b-loff],mstates_n)\n jd,md_s,md_idxs = possible_mz(n_sps[d-loff],mstates_n)\n ja = ja//2; jb=jb//2;jc = jc//2; jd=jd//2\n for (ic,mc) in enumerate(mc_s)\n initialize_tvec!(vec_ani_p); vec_ani_p[mc_idxs[ic]] = true\n bit_c = bitarr_to_int(vec_ani_p)\n for (ia,ma) in enumerate(ma_s)\n initialize_tvec!(vec_cre_p); vec_cre_p[ma_idxs[ia]] = true\n bit_a = bitarr_to_int(vec_cre_p)\n Mp = ma - mc\n bisearch!(Mzs,Mp,ret);idx = ret[1]\n tV = Vpn[idx]; bV = bVpn[idx]\n for (id,md) in enumerate(md_s)\n if abs(mc + md) > J2; continue;end\n initialize_tvec!(vec_ani_n); vec_ani_n[md_idxs[id]] = true\n bit_d = bitarr_to_int(vec_ani_n)\n CG1 = clebschgordan(Float64,jc,mc//2,jd,md//2,J2//2,(mc+md)//2)\n tfac = ME .* CG1\n for (ib,mb) in enumerate(mb_s)\n if mb - md + Mp != 0; continue;end\n initialize_tvec!(vec_cre_n); vec_cre_n[mb_idxs[ib]] = true\n bit_b = bitarr_to_int(vec_cre_n)\n fac = tfac .* clebschgordan(Float64,ja,ma//2,jb,mb//2,J2//2,(ma+mb)//2)\n tl = [bit_a,bit_b,bit_c,bit_d]\n if (tl in bV) == false\n push!(bV,copy(tl))\n push!(tV,fac)\n continue\n end\n @inbounds for kk = 1:length(bV)\n if bV[kk] == tl\n tV[kk] += fac\n break\n end\n end\n end\n end\n end\n end\n end\n return bVpn,Vpn,Mzs\nend\n\nfunction bitarr_to_int(arr::Array{Bool,1}, val = 0)\n v = 2^(length(arr)-1)\n for i in eachindex(arr)\n val += v*arr[i]\n v >>= 1\n end\n return val\nend\nfunction bitarr_to_int!(arr::Array{Bool,1},ret)\n ret[1] = 0\n ret[2] = 2^(length(arr)-1)\n for i in eachindex(arr)\n ret[1] += ret[2]*arr[i]\n ret[2] >>= 1\n end\n return nothing\nend\n\nfunction deltaf(i::Int64,j::Int64)\n ifelse(i==j,1.0,0.0)\nend\n\n\"\"\"\n occ(p_sps::Array{Array{Int64,1}},mstates_p::Array{Array{Int64,1}},mzp::Array{Int64,1},num_vp::Int64,\n n_sps::Array{Array{Int64,1}},mstates_n::Array{Array{Int64,1}},mzn::Array{Int64,1},num_vn::Int64,Mtot::Int64)\n\nprepare bit representations of proton/neutron Slater determinants => pbits/nbits\n\njocc_p, jocc_n: corresponding occupation numbers for a \"j\" state, \nwhich is used for one-body operation and OBTDs. \n\nMps/Mns: total M for proton/neutron \"blocks\"\n\nFor 6Li in the p shell and M=0, Mps = [-3,-1,1,3] & Mns = [3,1,-1,-3] \nblocks => [ (Mp,Mn)=(-3,3),(Mp,Mn)=(-1,1),...] \n\ntdims: array of cumulative number of M-scheme dimensions for \"blocks\" \n\ntdims =[ # of possible configurations of (-3,3), \n # of possible configurations of (-1,1),...] \n\"\"\"\nfunction occ(p_sps::Array{Array{Int64,1}},\n mstates_p::Array{Array{Int64,1}},\n mzp::Array{Int64,1},num_vp::Int64,\n n_sps::Array{Array{Int64,1}},\n mstates_n::Array{Array{Int64,1}},\n mzn::Array{Int64,1},num_vn::Int64,\n Mtot::Int64)\n lp = length(mzp); ln = length(mzn)\n pDim = binomial(lp,num_vp)\n occs_p =[ [false for j=1:lp] for i = 1:pDim]\n all_perm!(lp,num_vp,occs_p)\n\n nDim = binomial(ln,num_vn)\n occs_n =[ [false for j=1:ln] for i = 1:nDim]\n all_perm!(ln,num_vn,occs_n)\n\n mdim = 0;tdims=Int64[];push!(tdims,0)\n Mret = Int64[0]; Mps = Int64[]; Mns = Int64[]\n for i=1:pDim\n Mcount!(lp,mzp,occs_p[i],Mret); push!(Mps, Mret[1])\n end\n for i=1:nDim\n Mcount!(ln,mzn,occs_n[i],Mret); push!(Mns, Mret[1])\n end\n Mps = unique(Mps); Mns = unique(Mns)\n sort!(Mps,rev=false); sort!(Mns,rev=true)\n possidxs = []\n for i = 1:length(Mps)\n for j = 1:length(Mns)\n if Mps[i] + Mns[j] == Mtot\n push!(possidxs,[i,j])\n end\n end\n end\n pbits = [ Int64[] for i=1:length(possidxs) ]\n nbits = [ Int64[] for i=1:length(possidxs) ]\n occ_p_j = [ [[0.0,0.0]] for i=1:length(possidxs) ]\n occ_n_j = [ [[0.0,0.0]] for i=1:length(possidxs) ]\n for i =1:length(possidxs)\n deleteat!(occ_p_j[i],1);deleteat!(occ_n_j[i],1)\n end\n tocc_p_j = zeros(Float64,length(p_sps))\n tocc_n_j = zeros(Float64,length(n_sps))\n for ith = 1:length(possidxs)\n ni,nj = possidxs[ith]\n Mp = Mps[ni]; Mn = Mns[nj]\n if Mp + Mn != Mtot;println(\"warn\");end\n for i = 1:pDim\n Mcount!(lp,mzp,occs_p[i],Mret)\n if Mp != Mret[1]; continue;end\n push!(pbits[ith], bitarr_to_int(occs_p[i]))\n count_jocc!(p_sps,mstates_p,occs_p[i],tocc_p_j)\n push!(occ_p_j[ith],copy(tocc_p_j))\n for j=1:nDim\n Mcount!(ln,mzn,occs_n[j],Mret)\n if Mret[1] + Mp == Mtot\n mdim += 1\n end\n end\n end\n push!(tdims,mdim)\n end\n for ith = 1:length(possidxs)\n ni,nj = possidxs[ith]\n Mp = Mps[ni]; Mn = Mns[nj]\n for j=1:nDim\n Mcount!(ln,mzn,occs_n[j],Mret)\n if Mret[1] == Mn\n push!(nbits[ith], bitarr_to_int(occs_n[j]))\n count_jocc!(n_sps,mstates_n,occs_n[j],tocc_n_j)\n push!(occ_n_j[ith],copy(tocc_n_j))\n end\n end\n end\n return pbits,nbits,occ_p_j,occ_n_j,Mps,Mns,tdims\nend\n\nfunction TF_connectable(Phi::Int64,bVs::bit2b,TF::Array{Bool,1})\n # bVs = [ bit(Ca^+), bit(Cb^+), bit(Cc), bit(Cd) ]\n if bVs.c != (bVs.c & Phi);TF[1]=false;return nothing;end\n if bVs.d != (bVs.d & Phi);TF[1]=false;return nothing;end\n APhi = (~bVs.d) & ( (~bVs.c) & Phi)\n if bVs.a != (bVs.a & (~APhi));TF[1]=false;return nothing;end\n if bVs.b != (bVs.b & (~APhi));TF[1]=false;return nothing;end\n TF[1] = true\n return nothing\nend\n\nfunction TF_connectable_1(Phi::Int64,a::Int64,c::Int64,TF::Array{Bool,1})\n # a: creation c: anihilation\n if c != c & Phi;TF[1]=false;return nothing;end\n if a != (a & (~((~c) & Phi)));TF[1]=false;return nothing;end\n TF[1] = true\n return nothing\nend\n\nfunction calc_phase!(Phi::Int64,bVs::bit2b,\n ln::Int64,ret::Array{Int64,1})\n ret[1] = 0; ret[2] = -1 # ret=[phase,nPhi]\n ## anihilation c\n ret[1] += count_ones(Phi& (~(bVs.c-1)))\n ret[2] = (~bVs.c) & Phi #|phi>:= Cc|v>\n ## anihilation d\n ret[1] += count_ones(ret[2]& (~(bVs.d-1)))\n ret[2] = (~bVs.d) & ret[2] #|phi>:=CdCc|v>\n ## creation b\n ret[1] += count_ones(ret[2]& (~(bVs.b-1)))\n ret[2] = bVs.b | ret[2] #|phi>:=C^+bCdCc|v>\n ## creation a\n ret[1] += count_ones(ret[2]& (~(bVs.a-1)))\n ret[2] = bVs.a | ret[2] #|phi>:=C^+aC^+bCdCc|v>\n ret[1] = (-1)^ret[1]\n return nothing\nend\n\nfunction calc_phase_1!(Phi::Int64,cre::Int64,ani::Int64,ret::Array{Int64,1})\n ret[1] = 1; ret[2] = -1\n ## anihilation #|phi>:=Cc|v>\n ret[1] += count_ones(Phi & (~(ani-1)))\n ret[2] = (~ani) & Phi\n ## creation #|phi>:=C^+aCc|v>\n ret[1] += count_ones(ret[2] & (~(cre-1)))\n ret[2] = cre | ret[2]\n ret[1] = (-1)^ret[1]\n return nothing\nend\n\nfunction count_jocc!(sps,mstates,occ_bit,tocc)\n tocc .= 0.0\n @simd for i = 1:length(occ_bit)\n if occ_bit[i]\n tocc[mstates[i][6]] += 1.0\n end\n end\n return nothing\nend\nfunction getZNA(target_el,Anum,cp,cn)\n Z = 0\n for i = 1:length(element)\n if element[i] == target_el;Z = i; break; end\n end\n N = Anum - Z\n vp = Z - cp; vn = N - cn\n return Z,N,vp,vn\nend\nfunction ThickRestart(vks,uks,Tmat,lm,ls)\n vals,vecs = eigen(@views Tmat[1:lm-1,1:lm-1])\n beta = Tmat[lm-1,lm]\n Tmat .= 0.0\n @inbounds for k = 1:ls\n Tmat[k,k] = vals[k]\n end\n @inbounds for (k,uk) in enumerate(uks)\n tmp = beta .* vecs[lm-1,k]\n Tmat[ls+1,k] = tmp; Tmat[k,ls+1] = tmp\n uk .= 0.0\n @inbounds for j=1:lm-1\n axpy!(vecs[j,k],vks[j],uk)\n end\n end\n @inbounds for (k,uk) in enumerate(uks)\n vks[k] .= uk .* (1.0 /sqrt(dot(uk,uk)))\n end\n vks[ls+1] .= vks[lm]\n @inbounds for k = ls+2:lm\n vks[k] .= 0.0\n end\n return nothing\nend\n\nfunction ThickRestart_J(vks,uks,Tmat,lm,ls,eval_jj,Jtol)\n vals,vecs = eigen(@views Tmat[1:lm-1,1:lm-1])\n k = argmin(abs.(vals.-eval_jj))\n beta = Tmat[lm-1,lm]\n Tmat .= 0.0\n Tmat[1,1] = vals[k]\n uk=uks[1]\n tmp = beta .* vecs[lm-1,k]\n Tmat[ls+1,k] = tmp; Tmat[k,ls+1] = tmp\n uk .= 0.0\n @inbounds for j=1:lm-1\n axpy!(vecs[j,k],vks[j],uk)\n end\n vks[1] .= uk .* (1.0/sqrt(dot(uk,uk)))\n vks[2] .= vks[lm]\n @inbounds for k = ls+2:length(vks)\n vks[k] .= 0.0\n end\n return nothing\nend\n\nfunction initialize_wf(v1,method,tJ,mdim)\n# Random.seed!(123)\n if method==\"rand\" || tJ == -1\n v1 .= randn(mdim,)\n v1 ./= sqrt(dot(v1,v1))\n elseif method == \"one\"\n v1 .= 1.0 / sqrt(mdim)\n end\n return nothing\nend\n\nfunction initialize_bl_wav(mdim,q,vks)\n Random.seed!(123)\n for i=1:q\n v = @views vks[i,:]\n v .= randn(mdim,)\n if i>1\n for k=i-1:-1:1\n tv = @views vks[k,:]\n v .-= dot(v,tv) .* tv\n end\n end\n tmp = 1.0/sqrt(dot(v,v))\n v.*= tmp\n end\n return nothing\nend\n\nfunction read_wav(inpf,mdim,n;all=false,verbose=false)\n fid =open(inpf)\n neig = read(fid,Int32)\n mtot = read(fid,Int32)\n Es = [read(fid,Float64) for i = 1:neig]\n jj = [read(fid,Int32) for i=1:neig]\n V = [ [read(fid,Float64) for i=1:mdim] for nth=1:neig]\n close(fid)\n if all\n return V,jj\n else\n return V[n],jj[n]\n end\nend\n\nfunction read_appwav(inpf,mdim,V,q,verbose=false)\n fid =open(inpf)\n neig = read(fid,Int32)\n if neig < q; println(\"#(appwav) must be >= q\");exit();end\n mtot = read(fid,Int32)\n Es = [read(fid,Float64) for i = 1:neig]\n jj = [read(fid,Int32) for i=1:neig]\n if verbose\n println(\"appwav: $inpf\")\n print_vec(\"Es(n=$neig)\",Es)\n end\n for j=1:q\n V[j,:] .= [read(fid,Float64) for i=1:mdim]\n end\n close(fid)\n return nothing\nend\n\nfunction ReORTH(it,vtarget,vks)\n @inbounds for l = it:-1:1\n v = vks[l]\n axpy!(-dot(v,vtarget),v,vtarget)\n end\n return nothing\nend\n\n\nfunction myQR!(Q,R::FA2,\n d1::Int64,d2::Int64) where{FA2<:Array{Float64,2}}\n R .= 0.0\n @inbounds for j = 1:d2\n @inbounds @simd for i = 1:d1\n R[j,j] += Q[i,j] .* Q[i,j]\n end\n R[j,j] = sqrt(R[j,j])\n @inbounds @simd for i = 1:d1\n Q[i,j] /= R[j,j]\n end\n @inbounds for k = j+1:d2\n @simd for i = 1:d1\n R[j,k] += Q[i,j] .* Q[i,k]\n end\n @simd for i = 1:d1\n Q[i,k] -= Q[i,j] .* R[j,k]\n end\n end\n end\n return nothing\nend\n\nfunction bl_QR!(Q,R::FA2,\n d1::Int64,d2::Int64) where{FA2<:Array{Float64,2}}\n R .= 0.0\n @inbounds for j = 1:d2\n q = @views Q[:,j]\n t = sqrt(dot(q,q))\n R[j,j] = t\n q .*= 1.0/t\n @inbounds for k = j+1:d2\n @simd for i = 1:d1\n R[j,k] += q[i] .* Q[i,k]\n end\n @simd for i = 1:d1\n Q[i,k] -= q[i] .* R[j,k]\n end\n end\n end\n return nothing\nend\n\nfunction bisearch!(v::Array{Int64,1}, target::Int64,\n ret::Array{Int64,1})\n hi = length(v); lo = 1\n ret[2] = 1; ret[3]=length(v)\n @inbounds while ret[2] <= ret[3]\n ret[1] = div(ret[2]+ret[3],2)\n if v[ret[1]] > target\n ret[2] = ret[1]+1\n elseif v[ret[1]] < target\n ret[3] = ret[1]-1\n else\n return nothing\n end\n end\n ret[1] = 0\n return nothing\nend\n\nfunction bisearch_ord!(v::Array{Int64,1}, target::Int64,\n ret::Array{Int64,1})\n ret[3] = length(v); ret[2] = 1\n @inbounds while ret[2] <= ret[3]\n ret[1] = div(ret[2]+ret[3],2)\n if v[ret[1]] > target\n ret[3] = ret[1]-1\n elseif v[ret[1]] < target\n ret[2] = ret[1]+1\n else\n return nothing\n end\n end\n ret[1] = 0\n return nothing\nend\n\nfunction func_j(j1::I,j2::I,m1::I,m2::I) where{I<:Int64}\n sqrt( (0.5*j1*(0.5*j1+1.0)-0.5*m1*(0.5*m1-1.0))*(0.5*j2*(0.5*j2+1.0)-0.5*m2*(0.5*m2+1.0)) )\nend\n\nfunction J_from_JJ1(JJ,tol=1.e-4)\n for J = 0:100 ## ad hoc J<=50\n hJ = 0.5*J\n if abs(hJ*(hJ+1.0)-JJ) phase,fpbit\n bisearch!(pbits[pblock_i],ret[2],ridx)#ridx=Npf\n if Npi <= ridx[1]\n coef = Vpp[nth]*ret[1]*ifelse(Npi==ridx[1],0.5,1.0)\n push!(ppinfo[pblock_i][Npi], T1info(ridx[1],coef))\n end\n end\n end\n end\n return ppinfo\nend\n\nfunction prep_nn(mstates_n::Array{Array{Int64,1},1},\n nbits::Array{Array{Int64,1}},\n bVnn::Array{bit2b,1},\n Vnn::Array{Float64,1}) where {IA<:Array{Int64,1}}\n lMn=length(nbits)\n lmstates_n = length(mstates_n)\n nninfo = [ [ T1info[ ] for j=1:length(nbits[i]) ] for i = 1:lMn]\n @inbounds @threads for nblock_i = 1:lMn\n TF=[true]; ret=[0,-1];ridx=[-1,-1,-1]\n @inbounds for (Nni,Phi) in enumerate(nbits[nblock_i])\n @inbounds for nth = 1:length(Vnn)\n if Vnn[nth] == 0.0; continue;end\n TF_connectable(Phi,bVnn[nth],TF)\n if TF[1]==false; continue;end\n calc_phase!(Phi,bVnn[nth],lmstates_n,ret)\n bisearch!(nbits[nblock_i],ret[2],ridx)\n if Nni <= ridx[1]\n coef = Vnn[nth]*ret[1]*ifelse(Nni==ridx[1],0.5,1.0)\n push!(nninfo[nblock_i][Nni],T1info(ridx[1],coef))\n end\n end\n end\n end\n return nninfo\nend\nfunction prep_pn(lblock::Int64,tdims::IA,\n l_pbit::Int64,l_nbit::Int64,\n pbits::Array{Array{Int64,1}},\n nbits::Array{Array{Int64,1}},\n Mps::IA,delMs::IA,\n bVpn::Array{Array{Array{Int64,1},1},1},\n Vpn::Array{Array{Float64,1},1}) where {IA<:Array{Int64,1}}\n #to = TimerOutput()\n maxDeltaM = maximum(delMs)\n bfs = [ Int64[ ] for i = 1:lblock]\n bis = [ Int64[ ] for i = 1:lblock]\n for i = 1:lblock\n for j = i:lblock\n if Mps[j] - Mps[i] in delMs\n push!(bfs[i],j); push!(bis[j],i)\n end\n end\n end\n\n p_NiNfs = [ [ [ ifph[] ] for j=1:length(bfs[i]) ] for i=1:lblock]\n n_NiNfs = [ [ [ ifph[] ] for j=1:length(bfs[i]) ] for i=1:lblock]\n hits = [ [0,0] for i=1:lblock]\n @threads for bi = 1:lblock\n ret = [0,0,0]\n for j = 1:length(bfs[bi])\n bf = bfs[bi][j]\n deltaM = Mps[bf] - Mps[bi]\n if (deltaM in delMs) == false;continue;end\n bisearch!(delMs,deltaM,ret) # Vidx=ret[1]\n hits[bi] += calc_1b_jumps!(bi,bf,j,lblock,tdims,\n l_pbit,l_nbit,pbits,nbits,\n bVpn[ret[1]],Vpn[ret[1]],\n p_NiNfs,n_NiNfs)\n end\n end\n return bis,bfs,p_NiNfs,n_NiNfs, hits\nend\n\nfunction print_vec(s,v;ine=false)\n s *= \" \"\n for i = 1:length(v)\n if ine\n s *= @sprintf \"%9.1e\" v[i]\n else\n s *= @sprintf \"%10.4f\" v[i]\n #s *= @sprintf \"%25.15f\" v[i]\n end\n end\n println(s)\nend\n\n\nfunction calc_1b_jumps!(bi::Int64,bf::Int64,j::Int64,\n lblock::Int64,tdims::IA,\n l_pbit::Int64,l_nbit::Int64,\n pbits::AAI,nbits::AAI,\n bVpn::AAI,Vpn::Array{Float64,1},\n p_NiNfs::Aifph,\n n_NiNfs::Aifph) where {IA<:Array{Int64,1},\n AAI<:Array{Array{Int64,1},1},\n Aifph<:Array{Array{Array{Array{ifph,1},1},1},1}}\n TF=[true]; ret=[1,-1] # [phase,possible]\n ridx=[-1,-1,-1]\n plist = [ ifph[ ] for i =1:length(Vpn) ]\n nlist = [ ifph[ ] for i =1:length(Vpn) ]\n hits = [0,0]\n @inbounds for nth = 1:length(Vpn)\n a,b,c,d = bVpn[nth]; if Vpn[nth] == 0.0; continue;end\n @inbounds for (Npi,pPhi) in enumerate(pbits[bi])# Npi:idx pPhi:bit pSD\n TF_connectable_1(pPhi,a,c,TF)\n if TF[1]==false; continue;end\n calc_phase_1!(pPhi,a,c,ret)# ret<=[phase,bit]\n bisearch!(pbits[bf],ret[2],ridx)# ridx=[Npf]\n if ridx[1] ==0 ;continue;end\n push!(plist[nth],ifph(Npi,ridx[1],ret[1]==-1))\n hits[1] += 1\n end\n @inbounds for (Nni,nPhi) in enumerate(nbits[bi]) # Nni:idx\n TF_connectable_1(nPhi,b,d,TF);if TF[1]==false; continue;end\n calc_phase_1!(nPhi,b,d,ret)\n bisearch!(nbits[bf],ret[2],ridx) # ridx=[Nnf]\n if ridx[1] == 0;continue;end\n push!(nlist[nth],ifph(Nni,ridx[1],ret[1]==-1))\n hits[2] += 1\n end\n end\n p_NiNfs[bi][j] = plist\n n_NiNfs[bi][j] = nlist\n return hits\nend\n\nfunction add_bl_T!(q::Int64,k::Int64,\n Tmat::FA2,R::FA2) where{FA2<:Array{Float64,2}}\n Tmat[q*k+1:q*k+q,q*k-q+1:q*k] .= R\n Tmat[q*k-q+1:q*k,q*k+1:q*k+q] .= R'\n return nothing\nend\n\nfunction vec_to_block(vecs,V)\n for (b,v) in enumerate(vecs) \n V[:,b] .= v\n end\n return nothing\nend\n\n\nfunction writeRitzvecs(mdim,mtot,vals,totJs,Rvecs,oupf)\n num_ev = length(vals)\n io = open(oupf,\"w\")\n write(io,Int32(num_ev))\n write(io,Int32(mtot))\n for i = 1:num_ev\n write(io,vals[i])\n end\n js= [ Int32(2*totJs[i]) for i=1:num_ev]\n for i = 1:num_ev\n write(io,Int32(js[i]))\n end\n for nth = 1:num_ev; write(io,Rvecs[nth]); end\n close(io)\nend\n\"\"\"\n entropy(Rvecs,pbits,nbits,tdims,to)\n\nTo calculate entanglement entropy (not optimized yet).\n\n```math\nS = -\\\\mathrm{Tr} \\\\rho \\\\log (\\\\rho)\n```\n\"\"\"\nfunction entropy(Rvecs,pbits,nbits,tdims,to)\n pdims = [0];for bi=1:length(pbits);push!(pdims,pdims[end]+length(pbits[bi]));end\n ndims = [0];for bi=1:length(nbits);push!(ndims,ndims[end]+length(nbits[bi]));end\n pdim = pdims[end]; ndim = ndims[end]\n rho_p = zeros(Float64,pdim,pdim)\n rho_n = zeros(Float64,ndim,ndim)\n for (n,Rvec) in enumerate(Rvecs)\n rho_p .= 0.0#; rho_n .= 0.0\n for bi = 1:length(pbits)\n idim = tdims[bi]\n nbit = nbits[bi]\n ln = length(nbit)\n pofst = pdims[bi]\n for (pid_i,pbit_i) in enumerate(pbits[bi])\n tMi = idim + (pid_i-1)*ln\n ri = pofst + pid_i\n for (pid_j,pbit_j) in enumerate(pbits[bi])\n if pid_j Npf; continue;end\n fac = ifelse(Npi==Npf,0.5,1.0) .* func_j(j1,j2,m1,m2)\n pMat[Npi,Npf] += fac\n end\n end\n end\n end\n end\n #### nn\n vec_ani = [false for i = 1:ln];vec_cre = [false for i = 1:ln]\n vec_ani_2 = [false for i = 1:ln];vec_cre_2 = [false for i = 1:ln]\n for i2 = 1:length(n_sps)\n j2 = n_sps[i2][3]\n for m2 = -j2:2:j2-2\n vec_ani_2 .= false ; vec_cre_2 .= false\n @inbounds for k = 1:ln-1\n if @views mstates_n[k][1:4] != n_sps[i2];continue;end\n if mstates_n[k][5] == m2\n vec_ani_2[k] = true; vec_cre_2[k+1] = true;break\n end\n end\n bitarr_to_int!(vec_ani_2,ret_d); bitarr_to_int!(vec_cre_2,ret_c)\n for (SDidx,Phi) in enumerate(nbits[bi])\n TF_connectable_1(Phi,ret_c[1],ret_d[1],TF)\n if TF[1]==false;continue;end\n APhi = ret_c[1] | ((~ret_d[1]) & Phi)\n @inbounds for i1 = 1:length(n_sps)\n j1 = n_sps[i1][3]\n @inbounds for m1 = -j1+2:2:j1\n vec_ani .= false; vec_cre .= false\n @inbounds for k = 2:ln\n if @views mstates_n[k][1:4] != n_sps[i1];continue;end\n if mstates_n[k][5] == m1\n vec_ani[k] = true; vec_cre[k-1]=true;break\n end\n end\n bitarr_to_int!(vec_ani,ret_b)\n bitarr_to_int!(vec_cre,ret_a)\n TF_connectable_1(APhi,ret_a[1],ret_b[1],TF)\n if TF[1]==false;continue;end\n NPhi = ret_a[1] | ((~ret_b[1]) & APhi)\n bisearch!(nbits[bi],NPhi,ridx) #ridx <=Npf\n Nni = SDidx\n Nnf = ridx[1]\n if Nni > Nnf; continue;end\n fac = ifelse(Nni==Nnf,0.5,1.0) .* func_j(j1,j2,m1,m2)\n nMat[Nni,Nnf] += fac\n end\n end\n end\n end\n end\n op_p=MiMf[]; op_n=MiMf[]\n m = size(pMat)[1]\n for j=1:m\n for i=1:j\n if pMat[i,j] != 0.0; push!(op_p,MiMf(i,j,pMat[i,j]));end\n end\n end\n m = size(nMat)[1]\n for j=1:m\n for i=1:j\n if nMat[i,j] != 0.0; push!(op_n,MiMf(i,j,nMat[i,j]));end\n end\n end\n oPP[bi] = op_p; oNN[bi] = op_n\n return nothing\nend\n\nfunction prep_J(tdims,p_sps,n_sps,\n mstates_p::Array{Array{Int64,1},1},\n mstates_n::Array{Array{Int64,1},1},\n pbits::Array{Array{Int64,1},1},\n nbits::Array{Array{Int64,1},1})\n #to = TimerOutput()\n lp=length(mstates_p); ln=length(mstates_n)\n lblock = length(nbits)\n oPP = [ MiMf[] for i =1:lblock]\n oNN = [ MiMf[] for i =1:lblock]\n #@timeit to \"nn//pp\" begin\n @inbounds @threads for bi=1:lblock\n JT1(bi,oPP,oNN,p_sps,n_sps,\n mstates_p,mstates_n,pbits,nbits,tdims)\n end\n oPNu = [ Jpninfo[] for i =1:lblock]\n oPNd = [ Jpninfo[] for i =1:lblock]\n #end\n #@timeit to \"pn\" begin\n vec_p_ani = [false for i = 1:lp]; vec_p_cre = [false for i = 1:lp]\n vec_n_ani = [false for i = 1:ln]; vec_n_cre = [false for i = 1:ln]\n ret_a = [-1,-1];ret_b = [-1,-1]\n ret_c = [-1,-1];ret_d = [-1,-1]\n birange = [1:lblock-1,2:lblock]\n for pidx = 1:length(p_sps)\n jp = p_sps[pidx][3]\n mp_range = [-jp:2:jp-2,-jp+2:2:jp]\n for nidx = 1:length(n_sps)\n jn = n_sps[nidx][3]\n mn_range = [-jn+2:2:jn,-jn:2:jn-2]\n for ud = 1:2 # up:1 down:2\n @inbounds for mp in mp_range[ud]\n @inbounds for mn in mn_range[ud]\n fac = 1.0\n if ud == 1\n fac = func_j(jn,jp,mn,mp)\n else\n fac = func_j(jp,jn,mp,mn)\n end\n if fac==0.0;continue;end\n vec_p_ani .= false; vec_p_cre .= false\n vec_n_ani .= false; vec_n_cre .= false\n\n if ud == 2 ### for pn down\n @inbounds for k = 2:lp\n if mstates_p[k][1] != p_sps[pidx][1];continue;end\n if mstates_p[k][2] != p_sps[pidx][2];continue;end\n if mstates_p[k][3] != p_sps[pidx][3];continue;end\n if mstates_p[k][4] != p_sps[pidx][4];continue;end\n if mstates_p[k][5] == mp\n vec_p_ani[k] = true; vec_p_cre[k-1] = true\n break\n end\n end\n @inbounds for k = 1:ln-1\n if mstates_n[k][1] != n_sps[nidx][1];continue;end\n if mstates_n[k][2] != n_sps[nidx][2];continue;end\n if mstates_n[k][3] != n_sps[nidx][3];continue;end\n if mstates_n[k][4] != n_sps[nidx][4];continue;end\n if mstates_n[k][5] == mn\n vec_n_ani[k] = true; vec_n_cre[k+1] = true\n break\n end\n end\n else ### for p up n down\n @inbounds for k = 1:lp-1\n if mstates_p[k][1] != p_sps[pidx][1];continue;end\n if mstates_p[k][2] != p_sps[pidx][2];continue;end\n if mstates_p[k][3] != p_sps[pidx][3];continue;end\n if mstates_p[k][4] != p_sps[pidx][4];continue;end\n if mstates_p[k][5] == mp\n vec_p_ani[k] = true;vec_p_cre[k+1] = true;break\n end\n end\n @inbounds for k = 2:ln\n if mstates_n[k][1] != n_sps[nidx][1];continue;end\n if mstates_n[k][2] != n_sps[nidx][2];continue;end\n if mstates_n[k][3] != n_sps[nidx][3];continue;end\n if mstates_n[k][4] != n_sps[nidx][4];continue;end\n if mstates_n[k][5] == mn\n vec_n_ani[k] = true;vec_n_cre[k-1] = true;break\n end\n end\n end\n bitarr_to_int!(vec_p_ani,ret_c)\n bitarr_to_int!(vec_p_cre,ret_a)\n bitarr_to_int!(vec_n_ani,ret_d)\n bitarr_to_int!(vec_n_cre,ret_b)\n\n @inbounds @threads for bi in birange[ud]\n TF=[true]; ret_p=[0,0];ret_n=[0,0]\n ridx_p=[-1,-1,-1];ridx_n=[-1,-1,-1]\n bf = bi + Int64(2*(1.5-ud))\n pjump = ifph[]; njump=ifph[]\n for (Npi,pPhi) in enumerate(pbits[bi])\n TF_connectable_1(pPhi,ret_a[1],ret_c[1],TF)\n if TF[1]==false;continue;end\n calc_phase_1!(pPhi,ret_a[1],ret_c[1],ret_p)\n bisearch!(pbits[bf],ret_p[2],ridx_p)\n phase_p = ret_p[1]\n Npf= ridx_p[1]\n push!(pjump,ifph(Npi,Npf,phase_p==-1))\n end\n for (Nni,nPhi) in enumerate(nbits[bi])\n TF_connectable_1(nPhi,ret_b[1],ret_d[1],TF)\n if TF[1]==false;continue;end\n calc_phase_1!(nPhi,ret_b[1],ret_d[1],ret_n)\n bisearch!(nbits[bf],ret_n[2],ridx_n)\n phase_n = ret_n[1]\n Nnf= ridx_n[1]\n push!(njump,ifph(Nni,Nnf,phase_n==-1))\n end\n if length(pjump)*length(njump) == 0; continue;end\n if ud == 1\n push!(oPNu[bi],Jpninfo(fac,pjump,njump))\n else\n push!(oPNd[bi],Jpninfo(fac,pjump,njump))\n end\n end\n end\n end\n end\n end\n end\n #end\n #show(to, allocations = true,compact = false)\n #println(\"\")\n return oPP,oNN,oPNu,oPNd\nend\n\nfunction operate_J!(Rvec,Jv,pbits,nbits,tdims,Jidxs,\n oPP,oNN,oPNu,oPNd,beta_J=1.0)\n #to = TimerOutput()\n lblock=length(pbits)\n #@timeit to \"pp/nn \" begin\n @inbounds @threads for bi in Jidxs\n if bi==0;continue;end\n idim = tdims[bi]\n lNn = length(nbits[bi])\n lNp = length(pbits[bi])\n opPP = oPP[bi]\n opNN = oNN[bi]\n offset = idim-lNn\n @inbounds for tmp in opPP\n Npi =tmp.Mi; Npf=tmp.Mf; fac=tmp.fac .* beta_J\n tMi = offset + Npi*lNn\n tMf = offset + Npf*lNn\n @inbounds @simd for nidx = 1:lNn\n Mi = tMi+nidx; Mf = tMf+nidx\n Jv[Mf] += fac .* Rvec[Mi]\n Jv[Mi] += fac .* Rvec[Mf]\n end\n end\n @inbounds for tmp in opNN #nn\n Nni =tmp.Mi; Nnf=tmp.Mf; fac=tmp.fac .* beta_J\n tMi = offset + Nni\n tMf = offset + Nnf\n @inbounds @simd for pidx = 1:lNp\n Mi = tMi+pidx*lNn; Mf = tMf+pidx*lNn\n Jv[Mf] += fac .* Rvec[Mi]\n Jv[Mi] += fac .* Rvec[Mf]\n end\n end\n end\n #end\n #@timeit to \"pn down\" begin\n @inbounds @threads for bi = 2:lblock\n operator = oPNd[bi]\n bf = bi-1\n l_Nn_i = length(nbits[bi])\n l_Nn_f = length(nbits[bf])\n off_i = tdims[bi] - l_Nn_i\n off_f = tdims[bf] - l_Nn_f\n @inbounds for top in operator\n pj = top.pjump\n nj = top.njump\n fac =top.fac .* beta_J\n @inbounds for tmp_p in pj\n phase_p=tmp_p.phase\n tMi = off_i + tmp_p.i * l_Nn_i\n tMf = off_f + tmp_p.f * l_Nn_f\n @inbounds for tmp_n in nj\n phase_n=tmp_n.phase\n Mi = tMi + tmp_n.i\n Mf = tMf + tmp_n.f\n Jv[Mf] += ifelse(phase_p!=phase_n,-fac,fac) .* Rvec[Mi]\n end\n end\n end\n end\n @inbounds @threads for bi = 1:lblock-1\n operator = oPNu[bi]\n bf = bi+1\n l_Nn_i = length(nbits[bi])\n l_Nn_f = length(nbits[bf])\n off_i = tdims[bi] - l_Nn_i\n off_f = tdims[bf] - l_Nn_f\n @inbounds for top in operator\n pj = top.pjump\n nj = top.njump\n fac = top.fac .* beta_J\n @inbounds for tmp_p in pj\n phase_p=tmp_p.phase\n tMi = off_i + tmp_p.i * l_Nn_i\n tMf = off_f + tmp_p.f * l_Nn_f\n @inbounds for tmp_n in nj\n Nni = tmp_n.i; Nnf = tmp_n.f; phase_n=tmp_n.phase\n Mi = tMi + tmp_n.i\n Mf = tMf + tmp_n.f\n Jv[Mf] += ifelse(phase_p!=phase_n,-fac,fac) .* Rvec[Mi]\n end\n end\n end\n end\n #end\n #show(to, allocations = true,compact = false)\n #println(\"\")\n return nothing\nend\n\n\"\"\"\n samplerun()\n\nSample scripts to calculate\n- (a) 10 lowest states of 28Si in sd shell\n- (b) 10 lowest states of 28Si with J=0\n- (c) EC estimates of 10 lowest J=0 states of 28Si\n- (d) (b) with the preprocessing\n\n!!! note\n To run ```samplerun()```, you need a copy of ShellModel.jl in your environment.\n Try e.g.,\n ```sh\n git clone https://github.com/SotaYoshida/ShellModel.jl\n ``` \n and then, execute `samplerun()` in the repository:\n ```julia \n >julia using ShellModel\n >julia samplerun()\n ``` \n or \n ```sh\n julia -t 12 sample_run.jl\n ``` \n\"\"\"\nfunction samplerun()\n ### for compilation\n println(\"For JIT compilation...\")\n @time main(\"./snts/x_mass.snt\",\"Be8\",5,[0])\n @time main(\"./snts/x_mass.snt\",\"Be8\",5,[0];is_block=true,q=3)\n println(\"Done: JIT compilation\")\n ### input\n tJ = 0 # target J\n tJs =[ tJ ] \n num_ev = 4; n_block = 4\n num_ev_target = 10\n sntf = \"./snts/usdb.snt\"; target_nuc = \"Si28\"\n ###\n \n println(\"\\n### sample (a). 10-lowest states for $target_nuc\") \n @time main(sntf,target_nuc,10,[])\n\n println(\"\\n### sample (b). 10-lowest states with J=$tJs\") \n @time main(sntf,target_nuc,10,tJs)\n\n println(\"\\n### sample (c). calc. EC estimates for $num_ev_target J=$tJs states \") \n Hs = [\"./snts/usdb.snt\"]\n tJNs = [ [tJ,num_ev_target] ]\n solveEC(Hs,target_nuc,tJNs;\n verbose=true, exact_logf = \"runlog_sigma1_valid.dat\") \n\n println(\"\\n### sample (d). (b). with the preprocessing\")\n println(\"Block Lanczos method with n_block=$n_block\")\n @time main(sntf,target_nuc,num_ev,tJs;is_block=true,q=n_block)\n println(\"\\n+ preprocessing\")\n @time main(sntf,target_nuc,num_ev,tJs;is_block=true,q=n_block,\n in_wf=\"./appwavs/\"*target_nuc*\"_usdb_j\"*string(tJ)*\".appwav\")\nend\n", "meta": {"hexsha": "3b83aa1058f6b517a9a78236105a6574b3600c6f", "size": 59321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shellmodel_main.jl", "max_stars_repo_name": "SotaYoshida/ShellModel.jl", "max_stars_repo_head_hexsha": "ad268ff6763ed33dac06476eb3436153ad645f85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-02-07T12:53:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T19:31:14.000Z", "max_issues_repo_path": "src/shellmodel_main.jl", "max_issues_repo_name": "SotaYoshida/ShellModel.jl", "max_issues_repo_head_hexsha": "ad268ff6763ed33dac06476eb3436153ad645f85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-07T06:24:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T10:53:49.000Z", "max_forks_repo_path": "src/shellmodel_main.jl", "max_forks_repo_name": "SotaYoshida/ShellModel.jl", "max_forks_repo_head_hexsha": "ad268ff6763ed33dac06476eb3436153ad645f85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8947058824, "max_line_length": 180, "alphanum_fraction": 0.4896242477, "num_tokens": 19540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.1986063415341505}} {"text": "\n# everything related to a DG semidiscretization in 1D,\n# currently limited to Lobatto-Legendre nodes\n\n# This method is called when a SemidiscretizationHyperbolic is constructed.\n# It constructs the basic `cache` used throughout the simulation to compute\n# the RHS etc.\nfunction create_cache(mesh::TreeMesh{1}, equations,\n dg::DG, RealT, uEltype)\n # Get cells for which an element needs to be created (i.e. all leaf cells)\n leaf_cell_ids = local_leaf_cells(mesh.tree)\n\n elements = init_elements(leaf_cell_ids, mesh, equations, dg.basis, RealT, uEltype)\n\n interfaces = init_interfaces(leaf_cell_ids, mesh, elements)\n\n boundaries = init_boundaries(leaf_cell_ids, mesh, elements)\n\n cache = (; elements, interfaces, boundaries)\n\n # Add specialized parts of the cache required to compute the volume integral etc.\n cache = (;cache..., create_cache(mesh, equations, dg.volume_integral, dg, uEltype)...)\n cache = (;cache..., create_cache(mesh, equations, dg.mortar, uEltype)...)\n\n return cache\nend\n\n\n# The methods below are specialized on the volume integral type\n# and called from the basic `create_cache` method at the top.\nfunction create_cache(mesh::TreeMesh{1}, equations,\n volume_integral::VolumeIntegralFluxDifferencing, dg::DG, uEltype)\n create_cache(mesh, have_nonconservative_terms(equations), equations, volume_integral, dg, uEltype)\nend\n\nfunction create_cache(mesh::TreeMesh{1}, nonconservative_terms::Val{false}, equations,\n ::VolumeIntegralFluxDifferencing, dg, uEltype)\n NamedTuple()\nend\n\n# TODO: MHD in 1D\n# function create_cache(mesh::TreeMesh{1}, nonconservative_terms::Val{true}, equations,\n# ::VolumeIntegralFluxDifferencing, dg, uEltype)\n# end\n\n\nfunction create_cache(mesh::TreeMesh{1}, equations,\n volume_integral::VolumeIntegralShockCapturingHG, dg::DG, uEltype)\n element_ids_dg = Int[]\n element_ids_dgfv = Int[]\n\n cache = create_cache(mesh, equations,\n VolumeIntegralFluxDifferencing(volume_integral.volume_flux_dg),\n dg, uEltype)\n\n A2dp1_x = Array{uEltype, 2}\n fstar1_threaded = A2dp1_x[A2dp1_x(undef, nvariables(equations), nnodes(dg)+1) for _ in 1:Threads.nthreads()]\n\n return (; cache..., element_ids_dg, element_ids_dgfv, fstar1_threaded)\nend\n\n\nfunction create_cache(mesh::TreeMesh{1}, equations,\n volume_integral::VolumeIntegralPureLGLFiniteVolume, dg::DG, uEltype)\n\n A2dp1_x = Array{uEltype, 2}\n fstar1_threaded = A2dp1_x[A2dp1_x(undef, nvariables(equations), nnodes(dg)+1) for _ in 1:Threads.nthreads()]\n\n return (; fstar1_threaded)\nend\n\n\n\n# The methods below are specialized on the mortar type\n# and called from the basic `create_cache` method at the top.\nfunction create_cache(mesh::TreeMesh{1}, equations, mortar_l2::LobattoLegendreMortarL2, uEltype)\n NamedTuple()\nend\n\n\n# TODO: Taal discuss/refactor timer, allowing users to pass a custom timer?\n\nfunction rhs!(du, u, t,\n mesh::TreeMesh{1}, equations,\n initial_condition, boundary_conditions, source_terms,\n dg::DG, cache)\n # Reset du\n @timeit_debug timer() \"reset ∂u/∂t\" du .= zero(eltype(du))\n\n # Calculate volume integral\n @timeit_debug timer() \"volume integral\" calc_volume_integral!(\n du, u, mesh,\n have_nonconservative_terms(equations), equations,\n dg.volume_integral, dg, cache)\n\n # Prolong solution to interfaces\n @timeit_debug timer() \"prolong2interfaces\" prolong2interfaces!(\n cache, u, mesh, equations, dg)\n\n # Calculate interface fluxes\n @timeit_debug timer() \"interface flux\" calc_interface_flux!(\n cache.elements.surface_flux_values, mesh,\n have_nonconservative_terms(equations), equations,\n dg, cache)\n\n # Prolong solution to boundaries\n @timeit_debug timer() \"prolong2boundaries\" prolong2boundaries!(\n cache, u, mesh, equations, dg)\n\n # Calculate boundary fluxes\n @timeit_debug timer() \"boundary flux\" calc_boundary_flux!(\n cache, t, boundary_conditions, mesh, equations, dg)\n\n # Calculate surface integrals\n @timeit_debug timer() \"surface integral\" calc_surface_integral!(\n du, mesh, equations, dg, cache)\n\n # Apply Jacobian from mapping to reference element\n @timeit_debug timer() \"Jacobian\" apply_jacobian!(\n du, mesh, equations, dg, cache)\n\n # Calculate source terms\n @timeit_debug timer() \"source terms\" calc_sources!(\n du, u, t, source_terms, equations, dg, cache)\n\n return nothing\nend\n\n\nfunction calc_volume_integral!(du, u,\n mesh::Union{TreeMesh{1}, CurvedMesh{1}},\n nonconservative_terms::Val{false}, equations,\n volume_integral::VolumeIntegralWeakForm,\n dg::DGSEM, cache)\n @unpack derivative_dhat = dg.basis\n\n @threaded for element in eachelement(dg, cache)\n for i in eachnode(dg)\n u_node = get_node_vars(u, equations, dg, i, element)\n\n flux1 = flux(u_node, 1, equations)\n for ii in eachnode(dg)\n integral_contribution = derivative_dhat[ii, i] * flux1\n add_to_node_vars!(du, integral_contribution, equations, dg, ii, element)\n end\n end\n end\n\n return nothing\nend\n\n\nfunction calc_volume_integral!(du, u,\n mesh::TreeMesh{1},\n nonconservative_terms, equations,\n volume_integral::VolumeIntegralFluxDifferencing,\n dg::DGSEM, cache)\n @threaded for element in eachelement(dg, cache)\n split_form_kernel!(du, u, nonconservative_terms, equations, volume_integral.volume_flux, dg, cache, element)\n end\nend\n\n@inline function split_form_kernel!(du::AbstractArray{<:Any,3}, u,\n nonconservative_terms::Val{false}, equations,\n volume_flux, dg::DGSEM, cache,\n element, alpha=true)\n # true * [some floating point value] == [exactly the same floating point value]\n # This can (hopefully) be optimized away due to constant propagation.\n @unpack derivative_split = dg.basis\n\n # Calculate volume integral in one element\n for i in eachnode(dg)\n u_node = get_node_vars(u, equations, dg, i, element)\n\n # x direction\n # use consistency of the volume flux to make this evaluation cheaper\n flux1 = flux(u_node, 1, equations)\n integral_contribution = alpha * derivative_split[i, i] * flux1\n add_to_node_vars!(du, integral_contribution, equations, dg, i, element)\n # use symmetry of the volume flux for the remaining terms\n for ii in (i+1):nnodes(dg)\n u_node_ii = get_node_vars(u, equations, dg, ii, element)\n flux1 = volume_flux(u_node, u_node_ii, 1, equations)\n integral_contribution = alpha * derivative_split[i, ii] * flux1\n add_to_node_vars!(du, integral_contribution, equations, dg, i, element)\n integral_contribution = alpha * derivative_split[ii, i] * flux1\n add_to_node_vars!(du, integral_contribution, equations, dg, ii, element)\n end\n end\nend\n\n\n# TODO: Taal dimension agnostic\nfunction calc_volume_integral!(du, u,\n mesh::TreeMesh{1},\n nonconservative_terms, equations,\n volume_integral::VolumeIntegralShockCapturingHG,\n dg::DGSEM, cache)\n @unpack element_ids_dg, element_ids_dgfv = cache\n @unpack volume_flux_dg, volume_flux_fv, indicator = volume_integral\n\n # Calculate blending factors α: u = u_DG * (1 - α) + u_FV * α\n alpha = @timeit_debug timer() \"blending factors\" indicator(u, equations, dg, cache)\n\n # Determine element ids for DG-only and blended DG-FV volume integral\n pure_and_blended_element_ids!(element_ids_dg, element_ids_dgfv, alpha, dg, cache)\n\n # Loop over pure DG elements\n @timeit_debug timer() \"pure DG\" @threaded for element in element_ids_dg\n split_form_kernel!(du, u, nonconservative_terms, equations, volume_flux_dg, dg, cache, element)\n end\n\n # Loop over blended DG-FV elements\n @timeit_debug timer() \"blended DG-FV\" @threaded for element in element_ids_dgfv\n alpha_element = alpha[element]\n\n # Calculate DG volume integral contribution\n split_form_kernel!(du, u, nonconservative_terms, equations, volume_flux_dg, dg, cache, element, 1 - alpha_element)\n\n # Calculate FV volume integral contribution\n fv_kernel!(du, u, equations, volume_flux_fv, dg, cache, element, alpha_element)\n end\n\n return nothing\nend\n\n# TODO: Taal dimension agnostic\nfunction calc_volume_integral!(du, u,\n mesh::TreeMesh{1},\n nonconservative_terms, equations,\n volume_integral::VolumeIntegralPureLGLFiniteVolume,\n dg::DGSEM, cache)\n @unpack volume_flux_fv = volume_integral\n\n # Calculate LGL FV volume integral\n @threaded for element in eachelement(dg, cache)\n fv_kernel!(du, u, equations, volume_flux_fv, dg, cache, element, true)\n end\n\n return nothing\nend\n\n\n\n@inline function fv_kernel!(du::AbstractArray{<:Any,3}, u::AbstractArray{<:Any,3},\n equations, volume_flux_fv, dg::DGSEM, cache, element, alpha=true)\n @unpack fstar1_threaded = cache\n @unpack inverse_weights = dg.basis\n\n # Calculate FV two-point fluxes\n fstar1 = fstar1_threaded[Threads.threadid()]\n calcflux_fv!(fstar1, u, equations, volume_flux_fv, dg, element)\n\n # Calculate FV volume integral contribution\n for i in eachnode(dg)\n for v in eachvariable(equations)\n du[v, i, element] += ( alpha *\n (inverse_weights[i] * (fstar1[v, i+1] - fstar1[v, i])) )\n\n end\n end\n\n return nothing\nend\n\n@inline function calcflux_fv!(fstar1, u::AbstractArray{<:Any,3},\n equations, volume_flux_fv, dg::DGSEM, element)\n\n fstar1[:, 1, ] .= zero(eltype(fstar1))\n fstar1[:, nnodes(dg)+1,] .= zero(eltype(fstar1))\n\n for i in 2:nnodes(dg)\n u_ll = get_node_vars(u, equations, dg, i-1, element)\n u_rr = get_node_vars(u, equations, dg, i, element)\n flux = volume_flux_fv(u_ll, u_rr, 1, equations) # orientation 1: x direction\n set_node_vars!(fstar1, flux, equations, dg, i)\n end\n\n return nothing\nend\n\n\nfunction prolong2interfaces!(cache, u,\n mesh::TreeMesh{1}, equations, dg::DG)\n @unpack interfaces = cache\n\n @threaded for interface in eachinterface(dg, cache)\n left_element = interfaces.neighbor_ids[1, interface]\n right_element = interfaces.neighbor_ids[2, interface]\n\n # interface in x-direction\n for v in eachvariable(equations)\n interfaces.u[1, v, interface] = u[v, nnodes(dg), left_element]\n interfaces.u[2, v, interface] = u[v, 1, right_element]\n end\n end\n\n return nothing\nend\n\nfunction calc_interface_flux!(surface_flux_values,\n mesh::TreeMesh{1},\n nonconservative_terms::Val{false}, equations,\n dg::DG, cache)\n @unpack surface_flux = dg\n @unpack u, neighbor_ids, orientations = cache.interfaces\n\n @threaded for interface in eachinterface(dg, cache)\n # Get neighboring elements\n left_id = neighbor_ids[1, interface]\n right_id = neighbor_ids[2, interface]\n\n # Determine interface direction with respect to elements:\n # orientation = 1: left -> 2, right -> 1\n left_direction = 2 * orientations[interface]\n right_direction = 2 * orientations[interface] - 1\n\n # Call pointwise Riemann solver\n u_ll, u_rr = get_surface_node_vars(u, equations, dg, interface)\n flux = surface_flux(u_ll, u_rr, orientations[interface], equations)\n\n # Copy flux to left and right element storage\n for v in eachvariable(equations)\n surface_flux_values[v, left_direction, left_id] = flux[v]\n surface_flux_values[v, right_direction, right_id] = flux[v]\n end\n end\nend\n\n# TODO: MHD in 1D\n# function calc_interface_flux!(surface_flux_values, mesh::TreeMesh{1},\n# nonconservative_terms::Val{true}, equations,\n# dg::DG, cache)\n# end\n\n\nfunction prolong2boundaries!(cache, u,\n mesh::TreeMesh{1}, equations, dg::DG)\n @unpack boundaries = cache\n @unpack orientations, neighbor_sides = boundaries\n\n @threaded for boundary in eachboundary(dg, cache)\n element = boundaries.neighbor_ids[boundary]\n\n # boundary in x-direction\n if neighbor_sides[boundary] == 1\n # element in -x direction of boundary\n for v in eachvariable(equations)\n boundaries.u[1, v, boundary] = u[v, nnodes(dg), element]\n end\n else # Element in +x direction of boundary\n for v in eachvariable(equations)\n boundaries.u[2, v, boundary] = u[v, 1, element]\n end\n end\n end\n\n return nothing\nend\n\n# TODO: Taal dimension agnostic\nfunction calc_boundary_flux!(cache, t, boundary_condition::BoundaryConditionPeriodic,\n mesh::TreeMesh{1}, equations, dg::DG)\n @assert isempty(eachboundary(dg, cache))\nend\n\n# TODO: Taal dimension agnostic\nfunction calc_boundary_flux!(cache, t, boundary_condition,\n mesh::TreeMesh{1}, equations, dg::DG)\n @unpack surface_flux_values = cache.elements\n @unpack n_boundaries_per_direction = cache.boundaries\n\n # Calculate indices\n lasts = accumulate(+, n_boundaries_per_direction)\n firsts = lasts - n_boundaries_per_direction .+ 1\n\n # Calc boundary fluxes in each direction\n for direction in eachindex(firsts)\n calc_boundary_flux_by_direction!(surface_flux_values, t, boundary_condition,\n equations, dg, cache,\n direction, firsts[direction], lasts[direction])\n end\nend\n\nfunction calc_boundary_flux!(cache, t, boundary_conditions::Union{NamedTuple,Tuple},\n mesh::TreeMesh{1}, equations, dg::DG)\n @unpack surface_flux_values = cache.elements\n @unpack n_boundaries_per_direction = cache.boundaries\n\n # Calculate indices\n lasts = accumulate(+, n_boundaries_per_direction)\n firsts = lasts - n_boundaries_per_direction .+ 1\n\n # Calc boundary fluxes in each direction\n calc_boundary_flux_by_direction!(surface_flux_values, t, boundary_conditions[1],\n equations, dg, cache, 1, firsts[1], lasts[1])\n calc_boundary_flux_by_direction!(surface_flux_values, t, boundary_conditions[2],\n equations, dg, cache, 2, firsts[2], lasts[2])\nend\n\nfunction calc_boundary_flux_by_direction!(surface_flux_values::AbstractArray{<:Any,3}, t,\n boundary_condition, equations, dg::DG, cache,\n direction, first_boundary, last_boundary)\n @unpack surface_flux = dg\n @unpack u, neighbor_ids, neighbor_sides, node_coordinates, orientations = cache.boundaries\n\n @threaded for boundary in first_boundary:last_boundary\n # Get neighboring element\n neighbor = neighbor_ids[boundary]\n\n # Get boundary flux\n u_ll, u_rr = get_surface_node_vars(u, equations, dg, boundary)\n if neighbor_sides[boundary] == 1 # Element is on the left, boundary on the right\n u_inner = u_ll\n else # Element is on the right, boundary on the left\n u_inner = u_rr\n end\n x = get_node_coords(node_coordinates, equations, dg, boundary)\n flux = boundary_condition(u_inner, orientations[boundary], direction, x, t, surface_flux,\n equations)\n\n # Copy flux to left and right element storage\n for v in eachvariable(equations)\n surface_flux_values[v, direction, neighbor] = flux[v]\n end\n end\n\n return nothing\nend\n\n\nfunction calc_surface_integral!(du, mesh::Union{TreeMesh{1}, CurvedMesh{1}},\n equations, dg::DGSEM, cache)\n @unpack boundary_interpolation = dg.basis\n @unpack surface_flux_values = cache.elements\n\n @threaded for element in eachelement(dg, cache)\n for v in eachvariable(equations)\n # surface at -x\n du[v, 1, element] -= surface_flux_values[v, 1, element] * boundary_interpolation[1, 1]\n # surface at +x\n du[v, nnodes(dg), element] += surface_flux_values[v, 2, element] * boundary_interpolation[nnodes(dg), 2]\n end\n end\n\n return nothing\nend\n\n\nfunction apply_jacobian!(du, mesh::Union{TreeMesh{1}, CurvedMesh{1}},\n equations, dg::DG, cache)\n\n @threaded for element in eachelement(dg, cache)\n factor = -cache.elements.inverse_jacobian[element]\n\n for i in eachnode(dg)\n for v in eachvariable(equations)\n du[v, i, element] *= factor\n end\n end\n end\n\n return nothing\nend\n\n\n# TODO: Taal dimension agnostic\nfunction calc_sources!(du, u, t, source_terms::Nothing,\n equations::AbstractEquations{1}, dg::DG, cache)\n return nothing\nend\n\nfunction calc_sources!(du, u, t, source_terms,\n equations::AbstractEquations{1}, dg::DG, cache)\n\n @threaded for element in eachelement(dg, cache)\n for i in eachnode(dg)\n u_local = get_node_vars(u, equations, dg, i, element)\n x_local = get_node_coords(cache.elements.node_coordinates, equations, dg, i, element)\n du_local = source_terms(u_local, x_local, t, equations)\n add_to_node_vars!(du, du_local, equations, dg, i, element)\n end\n end\n\n return nothing\nend\n", "meta": {"hexsha": "3aecad2bc6a3d89856e83c59b060074bae37c3e6", "size": 17437, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solvers/dg_tree/dg_1d.jl", "max_stars_repo_name": "jbreue16/Trixi.jl", "max_stars_repo_head_hexsha": "f6de21b834ceb9b9a5295cbf6b221ab297c279f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solvers/dg_tree/dg_1d.jl", "max_issues_repo_name": "jbreue16/Trixi.jl", "max_issues_repo_head_hexsha": "f6de21b834ceb9b9a5295cbf6b221ab297c279f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/dg_tree/dg_1d.jl", "max_forks_repo_name": "jbreue16/Trixi.jl", "max_forks_repo_head_hexsha": "f6de21b834ceb9b9a5295cbf6b221ab297c279f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8049281314, "max_line_length": 118, "alphanum_fraction": 0.6697826461, "num_tokens": 4379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1980516930153985}} {"text": "# Transmission & distribution coupling functions\n\n\n\n## Functions replacing PowerModels or InfrastructureModels functions\n\n\"\"\nfunction run_model(\n t_data::Dict{String,<:Any},\n d_data::Dict{String,<:Any},\n t_model_type::Type,\n d_model_type::Type{BF},\n optimizer::Union{MathOptInterface.AbstractOptimizer, MathOptInterface.OptimizerWithAttributes},\n build_method::Function;\n t_ref_extensions::Vector{<:Function} = Function[],\n d_ref_extensions::Vector{<:Function} = Function[],\n t_solution_processors::Vector{<:Function} = Function[],\n d_solution_processors::Vector{<:Function} = Function[],\n kwargs...\n ) where BF <: _PM.AbstractBFModel\n\n # Check that transmission and distribution network ids are different.\n if !isempty(intersect(Set(id for (id,nw) in t_data[\"nw\"]), Set(id for (id,nw) in d_data[\"nw\"])))\n Memento.error(_LOGGER, \"Transmission and distribution data contain networks having the same IDs.\")\n end\n\n # Instantiate models.\n start_time = time()\n t_pm, d_pm = instantiate_model(t_data, d_data, t_model_type, d_model_type, build_method; t_ref_extensions, d_ref_extensions, kwargs...)\n Memento.debug(_LOGGER, \"combined T&D model build time: $(time() - start_time)\")\n\n start_time = time()\n\n # Solve the optimization model and store the transmission result.\n t_result = _IM.optimize_model!(t_pm; optimizer, solution_processors=t_solution_processors)\n\n # Build the distribution result using the same model as above.\n d_result = _IM.build_result(d_pm, t_result[\"solve_time\"]; solution_processors=d_solution_processors)\n\n # The asymmetric code above for building results produces inaccurate debugging messages;\n # this behavior can be fixed by writing a custom optimize_model!() that takes 2 models.\n\n Memento.debug(_LOGGER, \"combined T&D model solution time: $(time() - start_time)\")\n\n # Combine the result objects.\n result = t_result # All fields are pairwise equal, except for \"solution\".\n solution = result[\"solution\"]\n for (k,v) in d_result[\"solution\"]\n if k == \"nw\"\n # Merge transmission and distribution \"nw\" fields.\n # Network ids do not clash (checked before model instantiation).\n solution[\"nw\"] = merge(solution[\"nw\"], v)\n else\n if solution[k] != v\n Memento.warning(_LOGGER, \"Transmission and distribution solutions differ on key \\\"$k\\\"; only transmission value is kept.\")\n end\n end\n end\n\n return result\nend\n\n\"\"\nfunction instantiate_model(\n t_data::Dict{String,<:Any},\n d_data::Dict{String,<:Any},\n t_model_type::Type,\n d_model_type::Type{BF},\n build_method::Function;\n t_ref_extensions::Vector{<:Function} = Function[],\n d_ref_extensions::Vector{<:Function} = Function[],\n kwargs...\n ) where BF <: _PM.AbstractBFModel\n\n # Instantiate the transmission PowerModels struct, without building the model.\n t_pm = _PM.instantiate_model(t_data, t_model_type, method->nothing; ref_extensions=t_ref_extensions, kwargs...)\n\n # Instantiate the distribution PowerModels struct, without building the model.\n # Distribution and transmission structs share the same JuMP model. The `jump_model` parameter is used by _IM.InitializeInfrastructureModel().\n d_pm = _PM.instantiate_model(d_data, d_model_type, method->nothing; ref_extensions=d_ref_extensions, jump_model=t_pm.model, kwargs...)\n\n # Build the combined model.\n build_method(t_pm, d_pm)\n\n return t_pm, d_pm\nend\n\n\n\n## Functions that manipulate data structures\n\n\"\"\"\n add_td_coupling_data!(d_data; sub_nw, qs_ratio_bound=0.48)\n\nAdd to distribution single-network data structures the data needed for T&D coupling.\n\n- Add to distribution network data structure a coupling generator connected to the reference\n bus; if it already exists, overwrite all its parameters except cost.\n- Define a bound on reactive power exchanged between transmission and distribution networks:\n it is computed as a fraction `qs_ratio_bound` of the rated power of the distribution\n network (based on the rated power of existing and candidate branches connected to the\n reference bus); default value is 0.48 as per “Network Code on Demand Connection” –\n Commission Regulation (EU) 2016/1388.\n- Add to `dim_prop(d_data, :sub_nw, sub_nw)` the following entries:\n - `d_gen`: the id of the coupling generator of distribution network;\n - `qs_ratio_bound`: the aforementioned allowable fraction of the rated power.\n\nReturn `d_gen`.\n\nThis function is intended to be the last that edits distribution single-network data\nstructures: it should be called just before `make_multinetwork`.\n\"\"\"\nfunction add_td_coupling_data!(d_data::Dict{String,Any}; sub_nw::Int, qs_ratio_bound::Float64=0.48)\n\n # Get the reference bus id\n d_ref_buses = [b for (b,bus) in d_data[\"bus\"] if bus[\"bus_type\"] == 3]\n if length(d_ref_buses) != 1\n Memento.error(_LOGGER, \"Distribution network data must have 1 ref bus, but $(length(d_ref_buses)) are present.\")\n end\n d_ref_bus = parse(Int, first(d_ref_buses))\n\n # Get a list of the ids of generators connected to the reference bus\n d_ref_gens = [g for (g,gen) in d_data[\"gen\"] if gen[\"gen_bus\"] == d_ref_bus]\n if length(d_ref_gens) > 1\n Memento.error(_LOGGER, \"Distribution network data must have 0 or 1 generators connected to ref bus, but $(length(d_ref_gens)) are present.\")\n end\n\n # Define an upper bound on the rated apparent power based on the rated power of existing and candidate branches connected to the reference bus\n d_s_rate = (\n # `Float64[...]` is to prevent `ArgumentError: reducing over an empty collection is not allowed` in case at least one of the following collections is empty.\n # TODO: when dropping support for Julia < 1.6, remove `Float64[...]` and use `init=0.0` keyword argument of `sum`.\n sum(Float64[branch[\"rate_a\"] for (b,branch) in d_data[\"branch\"] if (branch[\"f_bus\"]==d_ref_bus || branch[\"t_bus\"]==d_ref_bus) && branch[\"br_status\"]==1]) # In t_bus here, the t stands for \"to\" (not for \"transmission\" as in the rest of the function)\n + sum(Float64[branch[\"rate_a\"] for (b,branch) in d_data[\"ne_branch\"] if (branch[\"f_bus\"]==d_ref_bus || branch[\"t_bus\"]==d_ref_bus) && branch[\"br_status\"]==1]) # In t_bus here, the t stands for \"to\" (not for \"transmission\" as in the rest of the function)\n )\n\n # Add a coupling generator connected to d_ref_bus (or use existing one) to model the transmission network\n if isempty(d_ref_gens)\n d_gen_idx = length(d_data[\"gen\"]) + 1 # Assumes that gens have contiguous indices starting from 1, as should be\n d_data[\"gen\"][\"$d_gen_idx\"] = Dict{String,Any}(\n \"gen_bus\" => d_ref_bus,\n \"index\" => d_gen_idx,\n \"dispatchable\" => true,\n \"model\" => 2, # Cost model (2 => polynomial cost)\n \"ncost\" => 0, # Number of cost coefficients\n \"cost\" => Any[]\n )\n else\n d_gen_idx = parse(Int, first(d_ref_gens))\n end\n\n # Set coupling generator parameters\n d_gen = d_data[\"gen\"][\"$d_gen_idx\"]\n d_gen[\"mbase\"] = d_data[\"baseMVA\"]\n d_gen[\"pmin\"] = -d_s_rate\n d_gen[\"pmax\"] = d_s_rate\n d_gen[\"qmin\"] = -d_s_rate\n d_gen[\"qmax\"] = d_s_rate\n d_gen[\"gen_status\"] = 1\n\n # Store the T&D coupling parameters\n dim_prop(d_data, :sub_nw, sub_nw)[\"qs_ratio_bound\"] = qs_ratio_bound\n dim_prop(d_data, :sub_nw, sub_nw)[\"d_gen\"] = d_gen_idx\nend\n\n\"\"\"\n add_td_coupling_data!(t_data, d_data; t_bus, sub_nw, qs_ratio_bound=0.48)\n\nAdd to transmission and distribution single-network data structures the data needed for T&D coupling.\n\nIn addition to `add_td_coupling_data!(d_data; sub_nw, qs_ratio_bound)`, do the following:\n- Add to transmission network data structure a coupling generator connected to `t_bus`, that\n is the bus to which the distribution network is to be connected.\n- Add to `dim_prop(d_data, :sub_nw, sub_nw)` an entry `t_gen` for the id of the coupling\n generator of transmission network.\n\nReturn `t_gen`.\n\nThis function is intended to be the last that edits transmission and distribution\nsingle-network data structures: it should be called just before `make_multinetwork`.\n\"\"\"\nfunction add_td_coupling_data!(t_data::Dict{String,Any}, d_data::Dict{String,Any}; t_bus::Int, sub_nw::Int, qs_ratio_bound::Float64=0.48)\n\n d_gen_idx = add_td_coupling_data!(d_data; sub_nw, qs_ratio_bound)\n\n # Check that t_bus exists\n if !haskey(t_data[\"bus\"], \"$t_bus\")\n Memento.error(_LOGGER, \"Bus $t_bus does not exist in transmission network data.\")\n end\n\n # Add a coupling generator connected to t_bus, to model the distribution network\n t_s_rate = (d_data[\"baseMVA\"]/t_data[\"baseMVA\"]) * d_data[\"gen\"][\"$d_gen_idx\"][\"pmax\"]\n t_gen_idx = length(t_data[\"gen\"]) + 1 # Assumes that gens have contiguous indices starting from 1, as should be\n t_data[\"gen\"][\"$t_gen_idx\"] = Dict{String,Any}(\n \"gen_bus\" => t_bus,\n \"index\" => t_gen_idx,\n \"dispatchable\" => true,\n \"mbase\" => t_data[\"baseMVA\"],\n \"pmin\" => -t_s_rate,\n \"pmax\" => t_s_rate,\n \"qmin\" => -t_s_rate,\n \"qmax\" => t_s_rate,\n \"gen_status\" => 1,\n \"model\" => 2, # Cost model (2 => polynomial cost)\n \"ncost\" => 0, # Number of cost coefficients\n \"cost\" => Any[]\n )\n\n # Add generator id to T&D coupling parameters\n dim_prop(d_data, :sub_nw, sub_nw)[\"t_gen\"] = t_gen_idx\nend\n\n\n\n## Solution processors\n\n\"\"\"\n sol_td_coupling!(pm, solution)\n\nAdd T&D coupling data to solution.\n\nReport in `solution` the active and reactive power that distribution network `pm` exchanges with the\ntransmission network (positive if from transmission to distribution) in units of `baseMVA` of `pm`.\n\"\"\"\nfunction sol_td_coupling!(pm::_PM.AbstractBFModel, solution::Dict{String,Any})\n solution = _PM.get_pm_data(solution)\n if haskey(solution, \"nw\")\n nws_sol = solution[\"nw\"]\n else\n nws_sol = Dict(\"0\" => solution)\n end\n\n for (nw, nw_sol) in nws_sol\n n = parse(Int, nw)\n if !(haskey(dim_prop(pm), :sub_nw) && haskey(dim_prop(pm, n, :sub_nw), \"d_gen\"))\n Memento.error(_LOGGER, \"T&D coupling data is missing from the model of nw $nw.\")\n end\n d_gen = dim_prop(pm, n, :sub_nw, \"d_gen\")\n nw_sol[\"td_coupling\"] = Dict{String,Any}()\n nw_sol[\"td_coupling\"][\"p\"] = nw_sol[\"gen\"][\"$d_gen\"][\"pg\"]\n nw_sol[\"td_coupling\"][\"q\"] = nw_sol[\"gen\"][\"$d_gen\"][\"qg\"]\n end\nend\n\n\n\n## Functions that group constraint templates, provided for convenience\n\n\"\"\"\nConnect each distribution nw to the corresponding transmission nw and apply coupling constraints.\n\nThe coupling constraint is applied to the two generators that each distribution nw indicates.\n\"\"\"\nfunction constraint_td_coupling(t_pm::_PM.AbstractPowerModel, d_pm::_PM.AbstractBFModel)\n t_nws = nw_ids(t_pm)\n\n for s in keys(dim_prop(d_pm, :sub_nw))\n d_nws = nw_ids(d_pm; sub_nw = s)\n for i in 1:length(t_nws)\n t_nw = t_nws[i]\n d_nw = d_nws[i]\n\n constraint_td_coupling_power_balance(t_pm, d_pm, t_nw, d_nw)\n end\n end\nend\n\n\n\n## Constraint templates\n\n\"\"\"\nState the power conservation between a distribution nw and the corresponding transmission nw.\n\"\"\"\nfunction constraint_td_coupling_power_balance(t_pm::_PM.AbstractPowerModel, d_pm::_PM.AbstractBFModel, t_nw::Int, d_nw::Int)\n sub_nw = dim_prop(d_pm, d_nw, :sub_nw)\n t_gen = sub_nw[\"t_gen\"]\n d_gen = sub_nw[\"d_gen\"]\n t_mbase = _PM.ref(t_pm, t_nw, :gen, t_gen, \"mbase\")\n d_mbase = _PM.ref(d_pm, d_nw, :gen, d_gen, \"mbase\")\n\n constraint_td_coupling_power_balance_active(t_pm, d_pm, t_nw, d_nw, t_gen, d_gen, t_mbase, d_mbase)\n constraint_td_coupling_power_balance_reactive(t_pm, d_pm, t_nw, d_nw, t_gen, d_gen, t_mbase, d_mbase)\nend\n\n\"\"\"\nApply bounds on reactive power exchange at the point of common coupling (PCC) of a distribution nw.\n\"\"\"\nfunction constraint_td_coupling_power_reactive_bounds(d_pm::_PM.AbstractBFModel; nw::Int=_PM.nw_id_default)\n sub_nw = dim_prop(d_pm, nw, :sub_nw)\n d_gen = sub_nw[\"d_gen\"]\n qs_ratio_bound = sub_nw[\"qs_ratio_bound\"] # Allowable fraction of rated apparent power\n\n constraint_td_coupling_power_reactive_bounds(d_pm, nw, d_gen, qs_ratio_bound)\nend\n\n\n\n## Constraint implementations\n\n\"\"\nfunction constraint_td_coupling_power_balance_active(t_pm::_PM.AbstractPowerModel, d_pm::_PM.AbstractBFModel, t_nw::Int, d_nw::Int, t_gen::Int, d_gen::Int, t_mbase::Float64, d_mbase::Float64)\n t_p_in = _PM.var(t_pm, t_nw, :pg, t_gen)\n d_p_in = _PM.var(d_pm, d_nw, :pg, d_gen)\n JuMP.@constraint(t_pm.model, t_mbase*t_p_in + d_mbase*d_p_in == 0.0) # t_pm.model == d_pm.model\nend\n\n\"\"\nfunction constraint_td_coupling_power_balance_reactive(t_pm::_PM.AbstractPowerModel, d_pm::_PM.AbstractBFModel, t_nw::Int, d_nw::Int, t_gen::Int, d_gen::Int, t_mbase::Float64, d_mbase::Float64)\n t_q_in = _PM.var(t_pm, t_nw, :qg, t_gen)\n d_q_in = _PM.var(d_pm, d_nw, :qg, d_gen)\n JuMP.@constraint(t_pm.model, t_mbase*t_q_in + d_mbase*d_q_in == 0.0) # t_pm.model == d_pm.model\nend\n\n\"Nothing to do because the transmission network model does not support reactive power.\"\nfunction constraint_td_coupling_power_balance_reactive(t_pm::_PM.AbstractActivePowerModel, d_pm::_PM.AbstractBFModel, t_nw::Int, d_nw::Int, t_gen::Int, d_gen::Int, t_mbase::Float64, d_mbase::Float64)\nend\n\n\"\"\nfunction constraint_td_coupling_power_reactive_bounds(d_pm::_PM.AbstractBFModel, d_nw::Int, d_gen::Int, qs_ratio_bound)\n\n # Compute the rated apparent power of the distribution network, based on the rated power of\n # existing and candidate branches connected to its reference bus. This value depends on the\n # indicator variables of both existing (if applicable) and candidate branches (i.e. whether they\n # are built or not).\n if haskey(_PM.var(d_pm, d_nw), :z_branch) # Some `branch`es can be replaced by `ne_branch`es\n z_branch = _PM.var(d_pm, d_nw, :z_branch)\n s_rate = (\n sum(branch[\"rate_a\"] * get(z_branch, b, 1.0) for (b,branch) in _PM.ref(d_pm, d_nw, :frb_branch))\n + sum(branch[\"rate_a\"] * _PM.var(d_pm, d_nw, :branch_ne, b) for (b,branch) in _PM.ref(d_pm, d_nw, :frb_ne_branch))\n )\n else # No `ne_branch`es at all\n s_rate = sum(branch[\"rate_a\"] for (b,branch) in _PM.ref(d_pm, d_nw, :frb_branch))\n end\n\n q = _PM.var(d_pm, d_nw, :qg, d_gen) # Exchanged reactive power (positive if from T to D)\n\n JuMP.@constraint(d_pm.model, q <= qs_ratio_bound*s_rate)\n JuMP.@constraint(d_pm.model, q >= -qs_ratio_bound*s_rate)\nend\n", "meta": {"hexsha": "20efa8a1f5ce28ad9e45ccf70f09fb562e9a279e", "size": 14886, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core/td_coupling.jl", "max_stars_repo_name": "Electa-Git/FlexPlan.jl", "max_stars_repo_head_hexsha": "bedaa248f3abdfeb72882f3ae4015ca0e742550c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-18T20:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T16:45:02.000Z", "max_issues_repo_path": "src/core/td_coupling.jl", "max_issues_repo_name": "Electa-Git/FlexPlan.jl", "max_issues_repo_head_hexsha": "bedaa248f3abdfeb72882f3ae4015ca0e742550c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2021-11-18T16:15:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:06:13.000Z", "max_forks_repo_path": "src/core/td_coupling.jl", "max_forks_repo_name": "Electa-Git/FlexPlan.jl", "max_forks_repo_head_hexsha": "bedaa248f3abdfeb72882f3ae4015ca0e742550c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7823529412, "max_line_length": 261, "alphanum_fraction": 0.6882977294, "num_tokens": 3986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19797944224657915}} {"text": "using Interpolations: LinearInterpolation\nimport ..ContinuumAbsorption: total_continuum_absorption\n\n\"\"\"\n synthesize(atm, linelist, λ_start, λ_stop, [λ_step=0.01]; metallicity=0, abundances=Dict(), vmic=0, ... )\n\nSolve the transfer equation in the model atmosphere `atm` with the transitions in `linelist` at the \nfrom `λ_start` to `λ_stop` in steps of `λ_step` (all Å) to get the resultant astrophysical flux at \neach wavelength. An `AbstractRange` can also be probvided directly in place of `λ_start`, `λ_stop`,\nand `λ_step`.\n\nReturns a named tuple with keys:\n- `flux`: the output spectrum\n- `alpha`: the linear absorption coefficient at each wavelenth and atmospheric layer a Matrix of \n size (layers x wavelengths)\n- `number_densities`: A dictionary mapping `Species` to vectors of number densities at each \n atmospheric layer\n- `wavelengths`: The vacuum wavelenths (in Å) over which the synthesis was performed. If \n `air_wavelengths=true` this will not be the same as the input wavelenths.\n\nOptional arguments:\n- `metallicity`, i.e. [metals/H] is log_10 solar relative\n- `abundances` is a `Dict` mapping atomic symbols to ``A(X)`` format abundances, i.e. \n ``A(x) = \\\\log_{10}(n_X/n_\\\\mathrm{H}) + 12``, where ``n_X`` is the number density of ``X``.\n These override `metallicity`.\n- `vmic` (default: 0) is the microturbulent velocity, ``\\\\xi``, in km/s.\n- `air_wavelengths` (default: `false`): Whether or not the input wavelengths are air wavelenths to \n be converted to vacuum wavelengths by Korg. The conversion will not be exact, so that the \n wavelenth range can internally be represented by an evenly-spaced range. If the approximation \n error is greater than `wavelength_conversion_warn_threshold`, an error will be thrown.\n- `wavelength_conversion_warn_threshold` (default: 1e-4): see `air_wavelengths`.\n- `line_buffer` (default: 10): the farthest (in Å) any line can be from the provided wavelenth range \n before it is discarded. If the edge of your window is near a strong line, you may have to turn \n this up.\n- `cntm_step` (default 1): the distance (in Å) between point at which the continuum opacity is \n calculated.\n- `hydrogen_lines` (default: `true`): whether or not to include H lines in the synthesis.\n- `mu_grid`: the range of (surface) μ values at which to calculate the surface flux when doing \n transfer in spherical geometry (when `atm` is a `ShellAtmosphere`).\n- `line_cutoff_threshold` (default: `1e-3`): the fraction of the continuum absorption coefficient \n at which line profiles are truncated. This has major performance impacts, since line absorption\n calculations dominate more syntheses. Turn it down for more precision at the expense of runtime.\n The default value should effect final spectra below the 10^-3 level.\n- `ionization_energies`, a `Dict` mapping `Species` to their first three ionization energies, \n defaults to `Korg.ionization_energies`.\n- `partition_funcs`, a `Dict` mapping `Species` to partition functions. Defaults to data from \n Barklem & Collet 2016, `Korg.partition_funcs`.\n- `equilibrium_constants`, a `Dict` mapping `Species` representing diatomic molecules to their \n molecular equilbrium constants in partial pressure form. Defaults to data from \n Barklem and Collet 2016, `Korg.equilibrium_constants`.\n\"\"\"\nfunction synthesize(atm::ModelAtmosphere, linelist, λ_start, λ_stop, λ_step=0.01\n ; air_wavelengths=false, wavelength_conversion_warn_threshold=1e-4, kwargs...)\n wls = if air_wavelengths\n len = Int(round((λ_stop - λ_start)/λ_step))+1\n vac_start, vac_stop = air_to_vacuum.((λ_start, λ_stop))\n vac_step = (vac_stop - vac_start) / (len-1)\n wls = StepRangeLen(vac_start, vac_step, len)\n max_diff = maximum(abs.(wls .- air_to_vacuum.(λ_start:λ_step:λ_stop)))\n if max_diff > wavelength_conversion_warn_threshold\n throw(ArgumentError(\"A linear air wavelength range can't be approximated exactly with a\"\n *\"linear vacuum wavelength range. This solution differs by up to \" * \n \"$max_diff Å. Adjust wavelength_conversion_warn_threshold if you\" *\n \"want to suppress this error.\"))\n end\n wls\n else\n StepRangeLen(λ_start, λ_step, Int(round((λ_stop - λ_start)/λ_step))+1)\n end\n synthesize(atm, linelist, wls; kwargs...)\nend\nfunction synthesize(atm::ModelAtmosphere, linelist, λs::AbstractRange; metallicity::Real=0.0, \n vmic::Real=1.0, abundances=Dict(), line_buffer::Real=10.0, cntm_step::Real=1.0, \n hydrogen_lines=true, mu_grid=0:0.05:1, line_cutoff_threshold=1e-3,\n ionization_energies=ionization_energies, \n partition_funcs=partition_funcs, equilibrium_constants=equilibrium_constants)\n #work in cm\n λs = λs * 1e-8\n cntm_step *= 1e-8\n line_buffer *= 1e-8\n cntmλs = (λs[1] - line_buffer - cntm_step) : cntm_step : (λs[end] + line_buffer + cntm_step)\n\n #sort the lines if necessary and check that λs is sorted\n issorted(linelist; by=l->l.wl) || sort!(linelist, by=l->l.wl)\n if step(λs) < 0\n throw(ArgumentError(\"λs must be in increasing order.\"))\n end\n\n #discard lines far from the wavelength range being synthesized\n linelist = filter(l-> λs[1] - line_buffer*1e-8 <= l.wl <= λs[end] + line_buffer*1e-8, linelist)\n\n abundances = get_absolute_abundances(metallicity, abundances)\n MEQs = molecular_equilibrium_equations(abundances, ionization_energies, partition_funcs, \n equilibrium_constants)\n\n sorted_cntmνs = c_cgs ./ reverse(cntmλs) #frequencies at which to calculate the continuum\n\n #float-like type general to handle dual numbers\n α_type = typeof(promote(atm.layers[1].temp, length(linelist) > 0 ? linelist[1].wl : 1.0, λs[1], \n metallicity, vmic, abundances[1])[1])\n #the absorption coefficient, α, for each wavelength and atmospheric layer\n α = Matrix{α_type}(undef, length(atm.layers), length(λs))\n α_cntm = Vector(undef, length(atm.layers)) #vector of continuum-absorption interpolators\n α5 = Vector{α_type}(undef, length(atm.layers)) #each layer's absorption at reference λ (5000 Å)\n n_dicts = Vector(undef, length(atm.layers)) #vector of (species -> number density) Dicts\n for (i, layer) in enumerate(atm.layers)\n n_dicts[i] = molecular_equilibrium(MEQs, layer.temp, layer.number_density, \n layer.electron_number_density)\n\n α_cntm_vals = reverse(total_continuum_absorption(sorted_cntmνs, layer.temp,\n layer.electron_number_density,\n n_dicts[i], partition_funcs))\n α_cntm[i] = LinearInterpolation(cntmλs, α_cntm_vals)\n α[i, :] .= α_cntm[i].(λs)\n\n α5[i] = total_continuum_absorption([c_cgs/5e-5], layer.temp, layer.electron_number_density,\n n_dicts[i], partition_funcs)[1]\n\n if hydrogen_lines\n α[i, :] .+= hydrogen_line_absorption(λs, layer.temp, layer.electron_number_density, \n n_dicts[i][species\"H_I\"], \n partition_funcs[species\"H_I\"], \n hline_stark_profiles, vmic*1e5)\n end\n end\n\n #put number densities in a dict of vectors, rather than a vector of dicts.\n number_densities = Dict([spec=>[n[spec] for n in n_dicts] for spec in keys(n_dicts[1])])\n\n #add contribution of line absorption to α\n line_absorption!(α, linelist, λs, [layer.temp for layer in atm.layers], \n [layer.electron_number_density for layer in atm.layers], number_densities,\n partition_funcs, vmic*1e5; α_cntm=α_cntm, \n cutoff_threshold=line_cutoff_threshold)\n\n source_fn = blackbody.((l->l.temp).(atm.layers), λs')\n flux = radiative_transfer(atm, α, source_fn, α5, mu_grid)\n\n (flux=flux, alpha=α, number_densities=number_densities, wavelengths=λs.*1e8)\nend\n\n\"\"\"\n get_absolute_abundances(metallicity, A_X)\n\nCalculate ``n_X/n_\\\\mathrm{total}`` for each element X given some specified abundances, ``A(X)``. Use the \nmetallicity [``X``/H] to calculate those remaining from the solar values (except He).\n\"\"\"\nfunction get_absolute_abundances(metallicity, A_X::Dict) :: Vector{Number}\n if \"H\" in keys(A_X)\n throw(ArgumentError(\"A(H) set, but A(H) = 12 by definition. Adjust \\\"metallicity\\\" and \"\n * \"\\\"abundances\\\" to implicitly set the amount of H\"))\n end\n\n #populate dictionary of absolute abundaces\n abundances = map(0x01:Natoms) do elem\n if elem == 0x01 #hydrogen\n 1.0\n elseif atomic_symbols[elem] in keys(A_X)\n 10^(A_X[atomic_symbols[elem]] - 12.0)\n else\n #I'm accessing the module global solar_abundances here, but it doesn't make sense to \n #make this an optional argument because this behavior can be completely overridden by \n #specifying all abundances explicitely.\n Δ = (elem == 0x02 #= helium =#) ? 0.0 : metallicity\n 10^(solar_abundances[elem] + Δ - 12.0)\n end\n end\n #now normalize so that sum(N_x/N_total) = 1\n abundances ./= sum(abundances)\n abundances\nend\n\n\"\"\"\n blackbody(T, λ)\n\nThe value of the Planck blackbody function for temperature `T` at wavelength `λ`.\n\"\"\"\nfunction blackbody(T, λ)\n h = hplanck_cgs\n c = c_cgs\n k = kboltz_cgs\n\n 2*h*c^2/λ^5 * 1/(exp(h*c/λ/k/T) - 1)\nend\n", "meta": {"hexsha": "0b481a1ee9e98be642348314997e67a5b41dae40", "size": 9759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/synthesize.jl", "max_stars_repo_name": "ajwheeler/Korg.jl", "max_stars_repo_head_hexsha": "a51ec7ce5c7ddb25e0d582880ef05a8bb84cc2be", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-06-10T12:45:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T15:22:57.000Z", "max_issues_repo_path": "src/synthesize.jl", "max_issues_repo_name": "ajwheeler/Korg.jl", "max_issues_repo_head_hexsha": "a51ec7ce5c7ddb25e0d582880ef05a8bb84cc2be", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 60, "max_issues_repo_issues_event_min_datetime": "2021-05-01T23:04:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:20:07.000Z", "max_forks_repo_path": "src/synthesize.jl", "max_forks_repo_name": "ajwheeler/Korg.jl", "max_forks_repo_head_hexsha": "a51ec7ce5c7ddb25e0d582880ef05a8bb84cc2be", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7513513514, "max_line_length": 109, "alphanum_fraction": 0.6636950507, "num_tokens": 2575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.19788931776852267}} {"text": "function DiffEqBase.__init(\n prob::AbstractDDEProblem{uType,tupType,lType,iip},\n alg::algType,\n timeseries_init=uType[], ts_init=eltype(tupType)[], ks_init=[];\n d_discontinuities=Discontinuity{eltype(tupType)}[],\n dtmax = (prob.constant_lags === nothing || isempty(prob.constant_lags)) ?\n prob.tspan[2]-prob.tspan[1] : eltype(tupType)(7*minimum(prob.constant_lags)),\n dt=zero(eltype(tupType)), saveat=eltype(tupType)[],\n tstops = eltype(tupType)[],\n save_idxs=nothing, save_everystep=isempty(saveat),\n save_start = save_everystep || isempty(saveat) || typeof(saveat) <: Number ? true : prob.tspan[1] in saveat,\n save_end = save_everystep || isempty(saveat) || typeof(saveat) <: Number ? true : prob.tspan[2] in saveat,\n save_on = true,\n dense = save_everystep && !(typeof(alg) <: FunctionMap) && isempty(saveat),\n minimal_solution=true, discontinuity_interp_points::Int=10,\n discontinuity_abstol=eltype(tupType)(1//Int64(10)^12), discontinuity_reltol=0,\n initial_order=agrees(prob.h, prob.u0, prob.p, prob.tspan[1]) ? 1 : 0,\n initialize_integrator = true, initialize_save = true,\n callback=nothing, kwargs... ) where\n {uType,tupType,lType,iip,algType<:AbstractMethodOfStepsAlgorithm}\n\n tType = eltype(tupType)\n\n neutral = prob.neutral\n constant_lags = prob.constant_lags\n dependent_lags = prob.dependent_lags\n p = prob.p\n\n # no fixed-point iterations for constrained algorithms,\n # and thus `dtmax` should match minimal lag\n if isconstrained(alg) && constant_lags !== nothing && !isempty(constant_lags)\n dtmax = min(dtmax, constant_lags...)\n end\n\n # bootstrap the integrator using an ODE problem, but do not initialize it since\n # ODE solvers only accept functions f(du,u,p,t) or f(u,p,t) without history function\n ode_prob = ODEProblem{iip}(prob.f, prob.u0, prob.tspan, p)\n integrator = init(ode_prob, alg.alg; initialize_integrator=false,\n dt=one(tType), dtmax=dtmax, kwargs...)\n\n # check that constant lags match the given time direction\n if constant_lags !== nothing\n for lag in constant_lags\n integrator.tdir * lag > zero(tType) ||\n error(\"Constant lags and time direction do not match. Exiting.\")\n end\n end\n\n # ensure that ODE integrator satisfies tprev + dt == t\n integrator.dt = zero(integrator.dt)\n integrator.dtcache = zero(integrator.dt)\n\n # create new solution based on this integrator with an interpolation function of the\n # expected form f(du,u,p,t) or f(u,p,t) which already includes information about the\n # history function of the DDE problem, the current solution of the integrator, and\n # the extrapolation of the integrator for the future\n interp_h = HistoryFunction(prob.h, integrator.sol, integrator)\n if iip\n interp_f = (du,u,p,t) -> prob.f(du,u,interp_h,p,t)\n else\n interp_f = (u,p,t) -> prob.f(u,interp_h,p,t)\n end\n\n if typeof(alg.alg) <: OrdinaryDiffEq.OrdinaryDiffEqCompositeAlgorithm\n interp_data = OrdinaryDiffEq.CompositeInterpolationData(integrator.sol.interp,\n interp_f)\n else\n interp_data = OrdinaryDiffEq.InterpolationData(integrator.sol.interp,\n interp_f)\n end\n\n if typeof(alg.alg) <: OrdinaryDiffEq.OrdinaryDiffEqCompositeAlgorithm\n sol = DiffEqBase.build_solution(prob, integrator.sol.alg, integrator.sol.t, integrator.sol.u,\n dense=integrator.sol.dense, k=integrator.sol.k,\n interp=interp_data, alg_choice=integrator.sol.alg_choice,\n calculate_error = false)\n else\n sol = DiffEqBase.build_solution(prob, integrator.sol.alg, integrator.sol.t, integrator.sol.u,\n dense=integrator.sol.dense, k=integrator.sol.k,\n interp=interp_data, calculate_error = false)\n end\n\n # use this improved solution together with the given history function and the integrator\n # to create a problem function of the DDE with all available history information that is\n # of the form f(du,u,p,t) or f(u,p,t) such that ODE algorithms can be applied\n dde_h = HistoryFunction(prob.h, sol, integrator)\n if iip\n dde_f = ODEFunction((du,u,p,t) -> prob.f(du,u,dde_h,p,t),\n mass_matrix = prob.f.mass_matrix)\n else\n dde_f = ODEFunction((u,p,t) -> prob.f(u,dde_h,p,t),\n mass_matrix = prob.f.mass_matrix)\n end\n\n # define absolute tolerance for fixed-point iterations\n if alg.fixedpoint_abstol === nothing\n fixedpoint_abstol_internal = recursivecopy(integrator.opts.abstol)\n else\n fixedpoint_abstol_internal = real.(alg.fixedpoint_abstol)\n end\n\n # use norm of ODE integrator if no norm for fixed-point iterations is specified\n if alg.fixedpoint_norm === nothing\n fixedpoint_norm = integrator.opts.internalnorm\n end\n\n # define relative tolerance for fixed-point iterations\n if alg.fixedpoint_reltol === nothing\n fixedpoint_reltol_internal = recursivecopy(integrator.opts.reltol)\n else\n fixedpoint_reltol_internal = real.(alg.fixedpoint_reltol)\n end\n\n # create separate copies u and uprev, not pointing to integrator.u or integrator.uprev,\n # to cache uprev with correct dimensions and types\n u = recursivecopy(integrator.u)\n uprev = recursivecopy(integrator.uprev)\n\n # create container for residuals (has to be unitless)\n uEltypeNoUnits = recursive_unitless_eltype(u)\n if typeof(integrator.u) <: AbstractArray\n resid = similar(integrator.u, uEltypeNoUnits)\n else\n resid = one(uEltypeNoUnits)\n end\n\n # create uprev2 in same way as in OrdinaryDiffEq\n if integrator.uprev === integrator.uprev2\n uprev2 = uprev\n else\n uprev2 = recursivecopy(uprev)\n end\n\n # check if all indices should be returned\n if save_idxs !== nothing && collect(save_idxs) == collect(1:length(integrator.u))\n save_idxs = nothing # prevents indexing of ODE solution and saves memory\n end\n\n # new cache with updated u, uprev, uprev2, and function f\n if typeof(alg.alg) <: OrdinaryDiffEq.OrdinaryDiffEqCompositeAlgorithm\n caches = map((x,y) -> build_linked_cache(x, y, u, uprev, uprev2, dde_f,\n prob.tspan[1], dt, p),\n integrator.cache.caches, alg.alg.algs)\n dde_cache = OrdinaryDiffEq.CompositeCache(caches, alg.alg.choice_function, 1)\n else\n dde_cache = build_linked_cache(integrator.cache, alg.alg, u, uprev, uprev2, dde_f,\n prob.tspan[1], dt, p)\n end\n\n # filter provided discontinuities\n filter!(x -> x.order ≤ alg_maximum_order(alg) + 1, d_discontinuities)\n\n # retrieve time stops, time points at which solutions is saved, and discontinuities\n tstops_internal, saveat_internal, d_discontinuities_internal =\n tstop_saveat_disc_handling(tstops, saveat, d_discontinuities, integrator.tdir,\n prob.tspan, initial_order, alg_maximum_order(alg), constant_lags, tType)\n\n # create array of tracked discontinuities\n # used to find propagated discontinuities with callbacks and to keep track of all\n # passed discontinuities\n if initial_order ≤ alg_maximum_order(alg)\n tracked_discontinuities = [Discontinuity(prob.tspan[1], initial_order)]\n else\n tracked_discontinuities = Discontinuity{tType}[]\n end\n\n # create additional callback to track dependent delays\n if dependent_lags !== nothing && !isempty(dependent_lags)\n discontinuity_callback = DiscontinuityCallback(dependent_lags,\n tracked_discontinuities,\n discontinuity_interp_points,\n discontinuity_abstol,\n discontinuity_reltol,\n initialize!, nothing)\n callbacks = CallbackSet(callback, prob.callback, discontinuity_callback)\n else\n callbacks = CallbackSet(callback, prob.callback)\n end\n\n # separate options of integrator and ODE integrator since ODE integrator always saves\n # every step and every index (necessary for history function)\n opts = OrdinaryDiffEq.DEOptions(integrator.opts.maxiters,\n save_everystep,\n integrator.opts.adaptive, integrator.opts.abstol,\n integrator.opts.reltol, integrator.opts.gamma,\n integrator.opts.qmax, integrator.opts.qmin,\n integrator.opts.qsteady_max,\n integrator.opts.qsteady_min,\n integrator.opts.failfactor, integrator.opts.dtmax,\n integrator.opts.dtmin, integrator.opts.internalnorm,\n integrator.opts.internalopnorm,\n save_idxs, tstops_internal, saveat_internal,\n d_discontinuities_internal,\n tstops, saveat, d_discontinuities,\n integrator.opts.userdata, integrator.opts.progress,\n integrator.opts.progress_steps,\n integrator.opts.progress_name,\n integrator.opts.progress_message,\n integrator.opts.timeseries_errors,\n integrator.opts.dense_errors, integrator.opts.beta1,\n integrator.opts.beta2, integrator.opts.qoldinit,\n dense && integrator.opts.dense, save_on, save_start, save_end,\n callbacks, integrator.opts.isoutofdomain,\n integrator.opts.unstable_check,\n integrator.opts.verbose, integrator.opts.calck,\n integrator.opts.force_dtmin,\n integrator.opts.advance_to_tstop,\n integrator.opts.stop_at_next_tstop)\n\n # reduction of solution only possible if no dense interpolation required and only\n # selected time points saved, and all constant and no dependent lags are given\n # WARNING: can impact quality of solution if not all constant lags specified\n minimal_solution = minimal_solution && !opts.dense && !opts.save_everystep &&\n constant_lags !== nothing && !isempty(constant_lags) &&\n (dependent_lags === nothing || isempty(dependent_lags))\n\n # need copy of heap of additional time points (nodes will be deleted!) in order to\n # remove unneeded time points of ODE solution as soon as possible and keep track\n # of passed time points\n saveat_copy = minimal_solution ? deepcopy(opts.saveat) : nothing\n\n # create DDE integrator combining the new defined problem function with history\n # information, the new solution, the parameters of the ODE integrator, and\n # parameters of fixed-point iteration\n # do not initialize fsalfirst and fsallast\n tTypeNoUnits = typeof(one(tType))\n dde_int = DDEIntegrator{typeof(integrator.alg),isinplace(prob),uType,tType,typeof(p),\n typeof(integrator.eigen_est),\n typeof(fixedpoint_abstol_internal),\n typeof(fixedpoint_reltol_internal),typeof(resid),tTypeNoUnits,\n typeof(integrator.tdir),typeof(integrator.k),typeof(sol),\n typeof(dde_f),typeof(dde_cache),\n typeof(integrator),typeof(fixedpoint_norm),typeof(opts),\n typeof(saveat_copy),fsal_typeof(integrator),typeof(integrator.last_event_error)}(\n sol, u, integrator.k, integrator.t, dt, dde_f, p, uprev,\n uprev2, integrator.tprev, 1, 1, fixedpoint_abstol_internal,\n fixedpoint_reltol_internal, resid, fixedpoint_norm,\n alg.max_fixedpoint_iters, saveat_copy,\n tracked_discontinuities, integrator.alg,\n integrator.dtcache,\n integrator.dtchangeable, integrator.dtpropose,\n integrator.tdir, integrator.eigen_est,\n integrator.EEst, integrator.qold,\n integrator.q11, integrator.erracc, integrator.dtacc,\n integrator.success_iter, integrator.iter,\n integrator.saveiter, integrator.saveiter_dense,\n dde_cache, integrator.kshortsize,\n integrator.force_stepfail, integrator.just_hit_tstop,\n integrator.last_stepfail, integrator.event_last_time,\n integrator.last_event_error, integrator.accept_step,\n integrator.isout, integrator.reeval_fsal,\n integrator.u_modified, opts, integrator)\n\n # initialize DDE integrator and callbacks\n if initialize_integrator\n initialize_callbacks!(dde_int, initialize_save)\n initialize!(dde_int)\n typeof(alg.alg) <: OrdinaryDiffEq.CompositeAlgorithm &&\n copyat_or_push!(dde_int.sol.alg_choice, 1, dde_int.cache.current)\n end\n\n # take care of time step dt = 0 and dt with incorrect sign\n OrdinaryDiffEq.handle_dt!(dde_int)\n\n dde_int\nend\n\nfunction solve!(integrator::DDEIntegrator)\n # step over all stopping time points, similar to solving with ODE integrators\n @inbounds while !isempty(integrator.opts.tstops)\n while integrator.tdir * integrator.t < integrator.tdir * top(integrator.opts.tstops)\n # apply step or adapt step size\n loopheader!(integrator)\n\n # abort integration following same criteria as for ODEs:\n # maxiters exceeded, dt <= dtmin, integration unstable\n if check_error!(integrator) != :Success\n return integrator.sol\n end\n\n # calculate next step\n perform_step!(integrator)\n\n # calculate proposed next step size, handle callbacks, and update solution\n loopfooter!(integrator)\n\n if isempty(integrator.opts.tstops)\n break\n end\n end\n\n # remove hit or passed stopping time points\n handle_tstop!(integrator)\n end\n\n # clean up solution\n postamble!(integrator)\n\n # create array of time points and values that form solution\n sol_array = build_solution_array(integrator)\n\n # create interpolation data of solution\n interp = build_solution_interpolation(integrator, sol_array)\n\n # obtain DDE problem\n prob = integrator.sol.prob\n\n # calculate analytical solutions to problem if existent\n if DiffEqBase.has_analytic(prob.f)\n if integrator.opts.save_idxs === nothing\n u_analytic = [prob.f(Val{:analytic}, integrator.sol[1], integrator.p, t) for t in sol_array.t]\n else\n u_analytic = [@view(prob.f(\n Val{:analytic}, integrator.sol[1], integrator.p, t)[integrator.opts.save_idxs])\n for t in sol_array.t]\n end\n errors = Dict{Symbol,eltype(integrator.u)}()\n else\n u_analytic = nothing\n errors = nothing\n end\n\n # combine arrays of time points and values, interpolation data, and analytical solution\n # to solution\n if typeof(prob.u0) <: Tuple\n N = length((size(ArrayPartition(prob.u0))..., length(sol_array.u)))\n else\n N = length((size(prob.u0)..., length(sol_array.u)))\n end\n\n if typeof(integrator.alg) <: OrdinaryDiffEq.OrdinaryDiffEqCompositeAlgorithm\n sol = OrdinaryDiffEq.ODECompositeSolution{\n eltype(sol_array),N,typeof(sol_array.u),typeof(u_analytic),\n typeof(errors),typeof(sol_array.t),typeof(interp.ks),\n typeof(prob),typeof(integrator.sol.alg),typeof(interp)}(\n sol_array.u, u_analytic, errors, sol_array.t, interp.ks,\n prob, integrator.sol.alg, interp, interp.alg_choice,\n interp.dense, integrator.sol.tslocation, :Success)\n else\n sol = ODESolution{\n eltype(sol_array),N,typeof(sol_array.u),typeof(u_analytic),\n typeof(errors),typeof(sol_array.t),typeof(interp.ks),\n typeof(prob),typeof(integrator.sol.alg),typeof(interp)}(\n sol_array.u, u_analytic, errors, sol_array.t, interp.ks,\n prob, integrator.sol.alg, interp, interp.dense,\n integrator.sol.tslocation, :Success)\n end\n\n # calculate errors of solution\n if sol.u_analytic !== nothing\n DiffEqBase.calculate_solution_errors!(sol; fill_uanalytic=false,\n timeseries_errors=integrator.opts.timeseries_errors,\n dense_errors=integrator.opts.dense_errors)\n end\n\n return sol\nend\n\nfunction DiffEqBase.__solve(prob::DiffEqBase.AbstractDDEProblem{uType,tupType,lType,iip},\n alg::algType,\n timeseries_init=uType[], ts_init=eltype(tupType)[], ks_init=[]; kwargs...) where\n {uType,tupType,iip,algType<:AbstractMethodOfStepsAlgorithm,lType}\n\n integrator = DiffEqBase.__init(prob, alg, timeseries_init, ts_init, ks_init; kwargs...)\n solve!(integrator)\nend\n\nfunction initialize_callbacks!(dde_int::DDEIntegrator, initialize_save = true)\n u = dde_int.u\n integrator = dde_int.integrator\n # set up additional initial values of newly created DDE integrator\n # (such as fsalfirst) and its callbacks\n\n dde_int.u_modified = true\n\n u_modified = initialize!(integrator.opts.callback,dde_int.t,u,dde_int)\n\n # if the user modifies u, we need to fix previous values before initializing\n # FSAL in order for the starting derivatives to be correct\n if u_modified\n\n if iip\n recursivecopy!(dde_int.uprev,dde_int.u)\n else\n dde_int.uprev = dde_int.u\n end\n\n if OrdinaryDiffEq.alg_extrapolates(dde_int.alg)\n if iip\n recursivecopy!(dde_int.uprev2,dde_int.uprev)\n else\n dde_int.uprev2 = dde_int.uprev\n end\n end\n\n # update heap of discontinuities\n # discontinuity is assumed to be of order 0, i.e. solution x is discontinuous\n push!(dde_int.opts.d_discontinuities, Discontinuity(dde_int.t, 0))\n\n # reset this as it is now handled so the integrators should proceed as normal\n reeval_internals_due_to_modification!(dde_int,Val{false})\n\n if initialize_save &&\n (any((c)->c.save_positions[2],integrator.opts.callback.discrete_callbacks) ||\n any((c)->c.save_positions[2],integrator.opts.callback.continuous_callbacks))\n savevalues!(dde_int,true)\n end\n\n # recompute initial time step\n auto_dt_reset!(dde_int)\n end\n\n # reset this as it is now handled so the integrators should proceed as normal\n dde_int.u_modified = false\nend\n\nfunction tstop_saveat_disc_handling(tstops, saveat, d_discontinuities, tdir, tspan, initial_order, alg_maximum_order, constant_lags, tType)\n # add discontinuities propagated from initial discontinuity\n if initial_order ≤ alg_maximum_order && constant_lags !== nothing && !isempty(constant_lags)\n maxlag = abs(tspan[end] - tspan[1])\n d_discontinuities_internal = unique(\n Discontinuity{tType}[d_discontinuities;\n (Discontinuity(tspan[1] + lag, initial_order + 1)\n for lag in constant_lags if abs(lag) < maxlag)...])\n else\n d_discontinuities_internal = unique(d_discontinuities)\n end\n\n return OrdinaryDiffEq.tstop_saveat_disc_handling(tstops, saveat, d_discontinuities_internal, tdir, tspan, tType)\nend\n", "meta": {"hexsha": "d280860f5b130235fc2f949d882932d769cf29ac", "size": 20667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solve.jl", "max_stars_repo_name": "ranocha/DelayDiffEq.jl", "max_stars_repo_head_hexsha": "57e8f6a6b1a1f0745c2bdf97335130af3bd26e88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solve.jl", "max_issues_repo_name": "ranocha/DelayDiffEq.jl", "max_issues_repo_head_hexsha": "57e8f6a6b1a1f0745c2bdf97335130af3bd26e88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solve.jl", "max_forks_repo_name": "ranocha/DelayDiffEq.jl", "max_forks_repo_head_hexsha": "57e8f6a6b1a1f0745c2bdf97335130af3bd26e88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9512761021, "max_line_length": 139, "alphanum_fraction": 0.6201674167, "num_tokens": 4575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19786854901222004}} {"text": "export AmplModel, AmplException,\n reset!,\n write_sol, amplmodel_finalize, varscale, lagscale, conscale,\n obj, grad, grad!,\n cons, cons!, jth_con, jth_congrad, jth_congrad!, jth_sparse_congrad,\n jac_coord, jac, jprod, jprod!, jtprod, jtprod!,\n jth_hprod, jth_hprod!, ghjvprod, ghjvprod!,\n hess_coord, hess, hprod, hprod!\n\n# Convenience macro.\nmacro asl_call(func, args...)\n args = map(esc,args)\n quote\n ccall(($(esc(func)), libasl), $(args...))\n end\nend\n\ntype AmplException\n msg :: String\nend\n\nmacro check_ampl_model()\n esc(:(nlp.__asl == C_NULL && throw(AmplException(\"Uninitialized AMPL model\"))))\nend\n\ntype AmplModel <: AbstractNLPModel\n meta :: NLPModelMeta; # Problem metadata.\n __asl :: Ptr{Void}; # Pointer to internal ASL structure. Do not touch.\n\n counters :: Counters # Evaluation counters\n safe :: Bool # Always evaluate the objective before the Hessian.\n cvar :: Array{Int32} # x[cv(i)] is complementary to the constraints cv(i)\n\n function AmplModel(stub :: AbstractString; safe :: Bool=false)\n asl = @compat @asl_call(:asl_init, Ptr{Void}, (Ptr{UInt8},), stub);\n asl == C_NULL && error(\"Error allocating ASL structure\")\n\n minimize = @asl_call(:asl_objtype, Int32, (Ptr{Void},), asl) == 0;\n islp = @asl_call(:asl_islp, Int32, (Ptr{Void},), asl) != 0;\n\n nlo = @compat Int(@asl_call(:asl_nlo, Int32, (Ptr{Void},), asl));\n\n nvar = @compat Int(@asl_call(:asl_nvar, Int32, (Ptr{Void},), asl));\n ncon = @compat Int(@asl_call(:asl_ncon, Int32, (Ptr{Void},), asl));\n\n x0 = @compat unsafe_wrap(Array, @asl_call(:asl_x0, Ptr{Float64}, (Ptr{Void},), asl),\n (nvar,), false)\n y0 = @compat unsafe_wrap(Array, @asl_call(:asl_y0, Ptr{Float64}, (Ptr{Void},), asl),\n (ncon,), false)\n\n lvar = @compat unsafe_wrap(Array, @asl_call(:asl_lvar, Ptr{Float64}, (Ptr{Void},), asl),\n (nvar,), false)\n uvar = @compat unsafe_wrap(Array, @asl_call(:asl_uvar, Ptr{Float64}, (Ptr{Void},), asl),\n (nvar,), false)\n\n nzo = @compat Int(@asl_call(:asl_nzo, Int32, (Ptr{Void},), asl))\n nbv = @compat Int(@asl_call(:asl_nbv, Int32, (Ptr{Void},), asl))\n niv = @compat Int(@asl_call(:asl_niv, Int32, (Ptr{Void},), asl))\n nlvb = @compat Int(@asl_call(:asl_nlvb, Int32, (Ptr{Void},), asl))\n nlvo = @compat Int(@asl_call(:asl_nlvo, Int32, (Ptr{Void},), asl))\n nlvc = @compat Int(@asl_call(:asl_nlvc, Int32, (Ptr{Void},), asl))\n nlvbi = @compat Int(@asl_call(:asl_nlvbi, Int32, (Ptr{Void},), asl))\n nlvci = @compat Int(@asl_call(:asl_nlvci, Int32, (Ptr{Void},), asl))\n nlvoi = @compat Int(@asl_call(:asl_nlvoi, Int32, (Ptr{Void},), asl))\n nwv = @compat Int(@asl_call(:asl_nwv, Int32, (Ptr{Void},), asl))\n#Tangi add's\n n_cc = @compat Int(@asl_call(:asl_n_cc, Int32, (Ptr{Void},), asl))\n nlcc = @compat Int(@asl_call(:asl_nlcc, Int32, (Ptr{Void},), asl))\n ndcc = @compat Int(@asl_call(:asl_ndcc, Int32, (Ptr{Void},), asl))\n nzlb = @compat Int(@asl_call(:asl_nzlb, Int32, (Ptr{Void},), asl))\n#Fin Tangi add's\n lcon = @compat unsafe_wrap(Array, @asl_call(:asl_lcon, Ptr{Float64}, (Ptr{Void},), asl),\n (ncon,), false)\n ucon = @compat unsafe_wrap(Array, @asl_call(:asl_ucon, Ptr{Float64}, (Ptr{Void},), asl),\n (ncon,), false)\n#Tangi add's\n if n_cc>0\n #not sure what to do if nzlb!=0\n cvar = @compat unsafe_wrap(Array, @asl_call(:asl_cvar, Ptr{Int32}, (Ptr{Void},), asl),\n (ncon,), false)\n @show n_cc nlcc ndcc nzlb cvar nvar ncon\n else\n cvar=[]\n end\n#Fin Tangi add's\n nlnet = @compat Int(@asl_call(:asl_lnc, Int32, (Ptr{Void},), asl))\n nnnet = @compat Int(@asl_call(:asl_nlnc, Int32, (Ptr{Void},), asl))\n nnln = @compat(Int(@asl_call(:asl_nlc, Int32, (Ptr{Void},), asl))) - nnnet\n nlin = ncon - nnln - nnnet\n\n nln = 1 : nnln\n nnet = nnln+1 : nnln+nnnet\n lnet = nnln+nnnet+1 : nnln+nnnet+nlnet\n lin = nnln+nnnet+nlnet+1 : ncon\n\n nnzj = @compat Int(@asl_call(:asl_nnzj, Int32, (Ptr{Void},), asl))\n nnzh = @compat Int(@asl_call(:asl_nnzh, Int32, (Ptr{Void},), asl))\n\n meta = NLPModelMeta(nvar, x0=x0, lvar=lvar, uvar=uvar,\n nlo=nlo, nnzo=nzo,\n ncon=ncon, y0=y0, lcon=lcon, ucon=ucon,\n nnzj=nnzj, nnzh=nnzh,\n nbv=nbv, niv=niv,\n nlvb=nlvb, nlvo=nlvo, nlvc=nlvc,\n nlvbi=nlvbi, nlvci=nlvci, nlvoi=nlvoi, nwv=nwv,\n lin=lin, nln=nln, nnet=nnet, lnet=lnet,\n nlin=nlin, nnln=nnln, nnet=nnet, nlnet=nlnet,\n minimize=minimize, islp=islp, name=stub)\n\n nlp = new(meta, asl, Counters(), safe, cvar)\n\n finalizer(nlp, amplmodel_finalize)\n return nlp\n end\n\nend\n\n\n# Import methods we override.\nimport Base.show, Base.print\nimport NLPModels.reset!\nimport NLPModels.varscale, NLPModels.lagscale, NLPModels.conscale\nimport NLPModels.obj, NLPModels.grad, NLPModels.grad!\nimport NLPModels.cons, NLPModels.cons!, NLPModels.jth_con\nimport NLPModels.jth_congrad, NLPModels.jth_congrad!, NLPModels.jth_sparse_congrad\nimport NLPModels.jac_coord, NLPModels.jac\nimport NLPModels.jprod, NLPModels.jtprod, NLPModels.jprod!, NLPModels.jtprod!\nimport NLPModels.jth_hprod, NLPModels.jth_hprod!\nimport NLPModels.ghjvprod, NLPModels.ghjvprod!\nimport NLPModels.hess_coord, NLPModels.hess, NLPModels.hprod, NLPModels.hprod!\nimport NLPModels.NLPtoMPB\n\n# Methods associated to AmplModel instances.\n\n\"Reset evaluation counters in `nlp`.\"\nfunction reset!(nlp :: AmplModel)\n reset!(nlp.counters)\n return nlp\nend\n\n\"Write message `msg` along with primal and dual variables `x` and `y` to file.\"\nfunction write_sol(nlp :: AmplModel, msg :: String, x :: Vector{Float64}, y :: Vector{Float64})\n @check_ampl_model\n length(x) == nlp.meta.nvar || error(\"x must have length $(nlp.meta.nvar)\")\n length(y) == nlp.meta.ncon || error(\"y must have length $(nlp.meta.ncon)\")\n\n @compat @asl_call(:asl_write_sol, Void,\n (Ptr{Void}, Ptr{UInt8}, Ptr{Float64}, Ptr{Float64}),\n nlp.__asl, msg, x, y)\nend\n\nfunction amplmodel_finalize(nlp :: AmplModel)\n if nlp.__asl == C_NULL\n return\n end\n @asl_call(:asl_finalize, Void, (Ptr{Void},), nlp.__asl)\n nlp.__asl = C_NULL\nend\n\n# Displaying AmplModel instances.\n\nfunction show(io :: IO, nlp :: AmplModel)\n @check_ampl_model\n show(io, nlp.meta)\nend\n\nfunction print(io :: IO, nlp :: AmplModel)\n @check_ampl_model\n print(io, nlp.meta)\nend\n\n\n# Scaling AmplModel instances.\n\n\"Scale the vector of variables by the vector `s`.\"\nfunction varscale(nlp :: AmplModel, s :: Vector{Float64})\n @check_ampl_model\n length(s) >= nlp.meta.nvar || error(\"s must have length at least $(nlp.meta.nvar)\")\n\n err = Cint[0]\n @asl_call(:asl_varscale, Void, (Ptr{Void}, Ptr{Float64}, Ptr{Cint}), nlp.__asl, s, err)\n err[1] == 0 || throw(AmplException(\"Error while scaling variables\"))\nend\n\n\"\"\"Set the scaling factor σ in the Lagrangian:\n L(x,y) = f(x) + σ ∑ yi ci(x).\n\"\"\"\nfunction lagscale(nlp :: AmplModel, σ :: Float64)\n @check_ampl_model\n err = Cint[0]\n @asl_call(:asl_lagscale, Void, (Ptr{Void}, Float64, Ptr{Cint}), nlp.__asl, σ, err)\n err[1] == 0 || throw(AmplException(\"Error while scaling Lagrangian\"))\nend\n\n\"Scale the vector of constraints by the vector `s`.\"\nfunction conscale(nlp :: AmplModel, s :: Vector{Float64})\n @check_ampl_model\n length(s) >= nlp.meta.ncon || error(\"s must have length at least $(nlp.meta.ncon)\")\n\n err = Cint[0]\n @asl_call(:asl_conscale, Void, (Ptr{Void}, Ptr{Float64}, Ptr{Cint}), nlp.__asl, s, err)\n err[1] == 0 || throw(AmplException(\"Error while scaling constraints\"))\nend\n\n# Evaluating objective, constraints and derivatives.\n\n\"Evaluate the objective function of `nlp` at `x`.\"\nfunction obj(nlp :: AmplModel, x :: Vector{Float64})\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n\n err = Cint[0]\n f = @asl_call(:asl_obj, Float64, (Ptr{Void}, Ptr{Float64}, Ptr{Cint}), nlp.__asl, x, err)\n nlp.counters.neval_obj += 1\n err[1] == 0 || throw(AmplException(\"Error while evaluating objective\"))\n return f\nend\n\n\"Evaluate the gradient of the objective function at `x`.\"\nfunction grad(nlp :: AmplModel, x :: Vector{Float64})\n g = Array{Float64}(nlp.meta.nvar)\n return grad!(nlp, x, g)\nend\n\n\"Evaluate the gradient of the objective function at `x` in place.\"\nfunction grad!(nlp :: AmplModel, x :: Vector{Float64}, g :: Vector{Float64})\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n\n err = Cint[0]\n @asl_call(:asl_grad, Ptr{Float64},\n (Ptr{Void}, Ptr{Float64}, Ptr{Float64}, Ptr{Cint}),\n nlp.__asl, x, g, err)\n nlp.counters.neval_grad += 1\n err[1] == 0 || throw(AmplException(\"Error while evaluating objective gradient\"))\n return g\nend\n\n\"Evaluate the constraints at `x`.\"\nfunction cons(nlp :: AmplModel, x :: Vector{Float64})\n c = Array{Float64}(nlp.meta.ncon)\n return cons!(nlp, x, c)\nend\n\n\"Evaluate the constraints at `x` in place.\"\nfunction cons!(nlp :: AmplModel, x :: Vector{Float64}, c :: Vector{Float64})\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n\n err = Cint[0]\n @asl_call(:asl_cons, Void,\n (Ptr{Void}, Ptr{Float64}, Ptr{Float64}, Ptr{Cint}),\n nlp.__asl, x, c, err)\n nlp.counters.neval_cons += 1\n err[1] == 0 || throw(AmplException(\"Error while evaluating constraints\"))\n return c\nend\n\n\"Evaluate the `j`-th constraint at `x`.\"\nfunction jth_con(nlp :: AmplModel, x :: Vector{Float64}, j :: Int)\n @check_ampl_model\n (1 <= j <= nlp.meta.ncon) || error(\"expected 0 ≤ j ≤ $(nlp.meta.ncon)\")\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n\n err = Cint[0]\n cj = @asl_call(:asl_jcon, Float64,\n (Ptr{Void}, Ptr{Float64}, Int32, Ptr{Cint}),\n nlp.__asl, x, j-1, err)\n nlp.counters.neval_jcon += 1\n err[1] == 0 || throw(AmplException(\"Error while evaluating $j-th constraint\"))\n return cj\nend\n\n\"Evaluate the `j`-th constraint gradient at `x`.\"\nfunction jth_congrad(nlp :: AmplModel, x :: Vector{Float64}, j :: Int)\n g = Array{Float64}(nlp.meta.nvar)\n return jth_congrad!(nlp, x, j, g)\nend\n\n\"Evaluate the `j`-th constraint gradient at `x` in place.\"\nfunction jth_congrad!(nlp :: AmplModel, x :: Vector{Float64}, j :: Int, g :: Vector{Float64})\n @check_ampl_model\n (1 <= j <= nlp.meta.ncon) || error(\"expected 0 ≤ j ≤ $(nlp.meta.ncon)\")\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n\n err = Cint[0]\n @asl_call(:asl_jcongrad, Ptr{Float64},\n (Ptr{Void}, Ptr{Float64}, Ptr{Float64}, Int32, Ptr{Cint}),\n nlp.__asl, x, g, j-1, err)\n nlp.counters.neval_jgrad += 1\n err[1] == 0 || throw(AmplException(\"Error while evaluating $j-th constraint gradient\"))\n return g\nend\n\n\"Evaluate the `j`-th constraint sparse gradient at `x`.\"\nfunction jth_sparse_congrad(nlp :: AmplModel, x :: Vector{Float64}, j :: Int)\n @check_ampl_model\n (1 <= j <= nlp.meta.ncon) || error(\"expected 0 ≤ j ≤ $(nlp.meta.ncon)\")\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n\n nnz = @asl_call(:asl_sparse_congrad_nnz, Csize_t,\n (Ptr{Void}, Cint), nlp.__asl, j-1)\n\n err = Cint[0]\n inds = Array{Int64}(nnz)\n vals = Array{Float64}(nnz)\n @asl_call(:asl_sparse_congrad, Void,\n (Ptr{Void}, Ptr{Float64}, Int32, Ptr{Int64}, Ptr{Float64}, Ptr{Cint}),\n nlp.__asl, x, j-1, inds, vals, err)\n nlp.counters.neval_jgrad += 1\n err[1] == 0 || throw(AmplException(\"Error while evaluating $j-th sparse constraint gradient\"))\n # Use 1-based indexing.\n return sparsevec(inds+1, vals, nlp.meta.nvar)\nend\n\n\"Evaluate the constraints Jacobian at `x` in sparse coordinate format.\"\nfunction jac_coord(nlp :: AmplModel, x :: Vector{Float64})\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n\n err = Cint[0]\n rows = Array{Int64}(nlp.meta.nnzj)\n cols = Array{Int64}(nlp.meta.nnzj)\n vals = Array{Float64}(nlp.meta.nnzj)\n @asl_call(:asl_jac, Void,\n (Ptr{Void}, Ptr{Float64}, Ptr{Int64}, Ptr{Int64}, Ptr{Float64}, Ptr{Cint}),\n nlp.__asl, x, rows, cols, vals, err)\n nlp.counters.neval_jac += 1\n err[1] == 0 || throw(AmplException(\"Error while evaluating constraints Jacobian\"))\n # Use 1-based indexing.\n return (rows+1, cols+1, vals)\nend\n\n\"Evaluate the constraints Jacobian at `x` as a sparse matrix.\"\nfunction jac(nlp :: AmplModel, x :: Vector{Float64})\n @check_ampl_model\n (rows, cols, vals) = jac_coord(nlp, x)\n return sparse(rows, cols, vals, nlp.meta.ncon, nlp.meta.nvar)\nend\n\n\"\"\"\nEvaluate the Jacobian-vector product at `x`.\nWarning: Currently building the Jacobian for this.\n\"\"\"\nfunction jprod(nlp :: AmplModel, x :: Vector{Float64}, v :: Vector{Float64})\n Jv = zeros(nlp.meta.ncon)\n return jprod!(nlp, x, v, Jv)\nend\n\n\"\"\"\nEvaluate the Jacobian-vector product at `x` in place.\nWarning: Currently building the Jacobian for this.\n\"\"\"\nfunction jprod!(nlp :: AmplModel,\n x :: Vector{Float64},\n v :: Vector{Float64},\n Jv :: Vector{Float64})\n nlp.counters.neval_jac -= 1\n nlp.counters.neval_jprod += 1\n Jv[1:nlp.meta.ncon] = jac(nlp, x) * v\n return Jv\nend\n\n\"\"\"\nEvaluate the transposed-Jacobian-vector product at `x`.\nWarning: Currently building the Jacobian for this.\n\"\"\"\nfunction jtprod(nlp :: AmplModel, x :: Vector{Float64}, v :: Vector{Float64})\n Jtv = zeros(nlp.meta.nvar)\n return jtprod!(nlp, x, v, Jtv)\nend\n\n\"\"\"\nEvaluate the transposed-Jacobian-vector product at `x` in place.\nWarning: Currently building the Jacobian for this.\n\"\"\"\nfunction jtprod!(nlp :: AmplModel,\n x :: Vector{Float64},\n v :: Vector{Float64},\n Jtv :: Vector{Float64})\n nlp.counters.neval_jac -= 1\n nlp.counters.neval_jtprod += 1\n Jtv[1:nlp.meta.nvar] = jac(nlp, x)' * v\n return Jtv\nend\n\n\"Evaluate the product of the Lagrangian Hessian at `(x,y)` with the vector `v`.\"\nfunction hprod(nlp :: AmplModel,\n x :: Vector{Float64},\n v :: Vector{Float64};\n y :: Vector{Float64} = nlp.meta.y0,\n obj_weight :: Float64 = 1.0)\n hv = Array{Float64}(nlp.meta.nvar);\n return hprod!(nlp, x, v, hv, y=y, obj_weight=obj_weight)\nend\n\n\"Evaluate the product of the Lagrangian Hessian at `(x,y)` with the vector `v` in place.\"\nfunction hprod!(nlp :: AmplModel,\n x :: Vector{Float64},\n v :: Vector{Float64},\n hv :: Vector{Float64};\n y :: Vector{Float64} = nlp.meta.y0,\n obj_weight :: Float64 = 1.0)\n # Note: x is in fact not used in hprod.\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n length(y) >= nlp.meta.ncon || error(\"y must have length at least $(nlp.meta.ncon)\")\n length(v) >= nlp.meta.nvar || error(\"v must have length at least $(nlp.meta.nvar)\")\n\n if nlp.safe\n _ = obj(nlp, x) ; nlp.counters.neval_obj -= 1\n _ = cons(nlp, x) ; nlp.counters.neval_cons -= 1\n end\n @asl_call(:asl_hprod, Ptr{Float64},\n (Ptr{Void}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Float64),\n nlp.__asl, y, v, hv, obj_weight);\n nlp.counters.neval_hprod += 1\n return hv\nend\n\n\"\"\"Evaluate the product of the `j`-th constraint Hessian at `x` with the vector `v`.\nThe objective Hessian is used if `j=0`.\n\"\"\"\nfunction jth_hprod(nlp :: AmplModel,\n x :: Vector{Float64}, v :: Vector{Float64}, j :: Int)\n hv = Array{Float64}(nlp.meta.nvar)\n return jth_hprod!(nlp, x, v, j, hv)\nend\n\n\"\"\"Evaluate the product of the `j`-th constraint Hessian at `x` with the vector `v` in place.\nThe objective Hessian is used if `j=0`.\n\"\"\"\nfunction jth_hprod!(nlp :: AmplModel,\n x :: Vector{Float64}, v :: Vector{Float64},\n j :: Int, hv :: Vector{Float64})\n# Note: x is in fact not used in hprod.\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n length(v) >= nlp.meta.nvar || error(\"v must have length at least $(nlp.meta.nvar)\")\n (1 <= j <= nlp.meta.ncon) || error(\"expected 0 ≤ j ≤ $(nlp.meta.ncon)\")\n\n if nlp.safe\n if j == 0\n _ = obj(nlp, x) ; nlp.counters.neval_obj -= 1\n else\n _ = cons(nlp, x) ; nlp.counters.neval_cons -= 1\n end\n end\n @asl_call(:asl_hvcompd, Ptr{Float64},\n (Ptr{Void}, Ptr{Float64}, Ptr{Float64}, Int),\n nlp.__asl, v, hv, j-1);\n nlp.counters.neval_jhprod += 1\n return hv\nend\n\n\"\"\"Compute the vector of dot products `(g, Hj*v)`\nwhere `Hj` is the Hessian of the `j`-th constraint at `x`.\n\"\"\"\nfunction ghjvprod(nlp :: AmplModel,\n x :: Vector{Float64}, g :: Vector{Float64}, v :: Vector{Float64})\n gHv = Array{Float64}(nlp.meta.ncon);\n return ghjvprod!(nlp, x, g, v, gHv)\nend\n\n\"\"\"Compute the vector of dot products `(g, Hj*v)` in place\nwhere `Hj` is the Hessian of the `j`-th constraint at `x`.\n\"\"\"\nfunction ghjvprod!(nlp :: AmplModel,\n x :: Vector{Float64}, g :: Vector{Float64},\n v :: Vector{Float64}, gHv :: Vector{Float64})\n # Note: x is in fact not used.\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n length(g) >= nlp.meta.nvar || error(\"g must have length at least $(nlp.meta.nvar)\")\n length(v) >= nlp.meta.nvar || error(\"v must have length at least $(nlp.meta.nvar)\")\n\n if nlp.safe\n _ = cons(nlp, x) ; nlp.counters.neval_cons -= 1\n end\n @asl_call(:asl_ghjvprod, Ptr{Float64},\n (Ptr{Void}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}),\n nlp.__asl, g, v, gHv);\n nlp.counters.neval_hprod += nlp.meta.ncon\nend\n\n\"\"\"Evaluate the Lagrangian Hessian at `(x,y)` in sparse coordinate format.\nOnly the lower triangle is returned.\n\"\"\"\nfunction hess_coord(nlp :: AmplModel,\n x :: Vector{Float64};\n y :: Vector{Float64} = nlp.meta.y0,\n obj_weight :: Float64 = 1.0)\n # Note: x is in fact not used.\n @check_ampl_model\n length(x) >= nlp.meta.nvar || error(\"x must have length at least $(nlp.meta.nvar)\")\n length(y) >= nlp.meta.ncon || error(\"y must have length at least $(nlp.meta.ncon)\")\n\n if nlp.safe\n _ = obj(nlp, x) ; nlp.counters.neval_obj -= 1\n _ = cons(nlp, x) ; nlp.counters.neval_cons -= 1\n end\n\n rows = Array{Int64}(nlp.meta.nnzh)\n cols = Array{Int64}(nlp.meta.nnzh)\n vals = Array{Float64}(nlp.meta.nnzh)\n @asl_call(:asl_hess, Void,\n (Ptr{Void}, Ptr{Float64}, Float64, Ptr{Int64}, Ptr{Int64}, Ptr{Float64}),\n nlp.__asl, y, obj_weight, rows, cols, vals)\n nlp.counters.neval_hess += 1\n # Use 1-based indexing.\n # Swap rows and cols to obtain the lower triangle.\n return (cols+1, rows+1, vals)\nend\n\n\"\"\"Evaluate the Lagrangian Hessian at `(x,y)` as a sparse matrix.\nOnly the lower triangle is returned.\n\"\"\"\nfunction hess(nlp :: AmplModel,\n x :: Vector{Float64};\n y :: Vector{Float64} = nlp.meta.y0,\n obj_weight :: Float64 = 1.0)\n @check_ampl_model\n (rows, cols, vals) = hess_coord(nlp, x, y=y, obj_weight=obj_weight);\n return sparse(rows, cols, vals, nlp.meta.nvar, nlp.meta.nvar)\nend\n", "meta": {"hexsha": "4a7fafabbb77ef6110231355d3ccd77e09bea622", "size": 19811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "old/benchmark/nl_test/ampl_model.jl", "max_stars_repo_name": "tmigot/MPCCsolver.jl", "max_stars_repo_head_hexsha": "31b44f12c9b1317f2bf8356aa75b9aba770a08fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/benchmark/nl_test/ampl_model.jl", "max_issues_repo_name": "tmigot/MPCCsolver.jl", "max_issues_repo_head_hexsha": "31b44f12c9b1317f2bf8356aa75b9aba770a08fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/benchmark/nl_test/ampl_model.jl", "max_forks_repo_name": "tmigot/MPCCsolver.jl", "max_forks_repo_head_hexsha": "31b44f12c9b1317f2bf8356aa75b9aba770a08fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6634980989, "max_line_length": 96, "alphanum_fraction": 0.6222805512, "num_tokens": 6323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19758572421365608}} {"text": "# MIT License\n\n# Copyright (c) Microsoft Corporation.\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE\n\nabstract type Lattice{T<:Real} end\nabstract type InfiniteLattice{T<:Real} <: Lattice{T} end\nabstract type FiniteLattice{T<:Real,L<:InfiniteLattice{T}} <: Lattice{T} end\n\n\"\"\"returns a Tuple = (2D coordinates of emitter in the lattice,emitter)\"\"\"\nemitter(a::L, x::Int, y::Int) where {L<:InfiniteLattice} = (a.origin + x * a.e1 + y * a.e2, a.emitter)\n\nemitterpitchx(a::L) where {L<:Lattice} = norm(a.e₁)\nemitterpitchy(a::L) where {L<:Lattice} = norm(a.e₂)\n\nstruct SizedLattice{T<:Real,L<:InfiniteLattice{T}} <: FiniteLattice{T,L}\n lattice::L\n e₁emitters::Int\n e₂emitters::Int\n\n function SizedLattice(lattice::L, e₁emitters::Int, e₂emitters::Int) where {T<:Real,L<:InfiniteLattice{T}}\n @assert e₁emitters >= T(0)\n @assert e₂emitters >= T(0)\n return new{T,L}(lattice, e₁emitters, e₂emitters)\n end\nend\n\nemitterpitchx(a::SizedLattice) = emitterpitchx(norm(a.lattice.e₁))\nemitterpitchy(a::SizedLattice) = emitterpitchy(norm(a.lattice.e₂))\n\nfunction emitter(a::FiniteLattice{T,L}, x::Int, y::Int) where {T<:Real,L<:InfiniteLattice{T}}\n @assert T(0) <= x <= a.e₁emitters\n @assert T(0) <= y <= a.e₂emitters\n return emitter(a.lattice, x, y) #because L is of type InfiteLattice and not FiniteLattice this call will not cause infinite recursion.\nend\n\nstruct PrimitiveLattice{S<:AbstractSpectrum,P<:AbstractAngularPowerDistribution,T<:Real} <: InfiniteLattice{T}\n origin::SVector{2,T}\n e₁::SVector{2,T}\n e2::SVector{2,T}\n emitter::PlanarEmitter{S,P,T}\n\n PrimitiveLattice(e₁::SVector{2,T}, e₂::SVector{2,T}, emitter::PlanarEmitter{S,P,T}; origin = SVector{2,T}(T(0), T(0))) where {S<:AbstractSpectrum,P<:AbstractAngularPowerDistribution,T<:Real} = new{S,P,T}(e₁, e₂, emitter, origin)\nend\n\nhexagonalemitterlattice(pitch::T, emitter::PlanarEmitter{S,P,T}; origin = SVector{2,T}(T(0), T(0))) where {S<:AbstractSpectrum,P<:AbstractAngularPowerDistribution,T<:Real} = PrimitiveLattice{S,P,T}(origin, SVector{2,T}(emitterpitch, T(0)), SVector{2,T}(emitterpitch / T(2), emitterpitch * sqrt(T(3)) / T(2)), emitter)\n\nsquareemitterlattice(emitterpitch::T, emitter::PlanarEmitter{S,P,T}) where {S<:AbstractSpectrum,P<:AbstractAngularPowerDistribution,T<:Real} = PrimitiveLattice{S,P,T}(SVector{2,T}(emitterpitch, T(0)), SVector{2,T}(T(0), emitterpitch), emitter)\n\n#This needs work. We probably want some kind of hierarchical lattice with superemitter and subemitter functions.\nstruct RGBPixelLattice{R<:AbstractSpectrum,G<:AbstractSpectrum,B<:AbstractSpectrum,P<:AbstractAngularPowerDistribution,T<:Real} <: InfiniteLattice{T}\n red::PrimitiveLattice{R,P,T}\n green::PrimitiveLattice{G,P,T}\n blue::PrimitiveLattice{B,P,T}\n\n function RGBPixelLattice(::Type{R}, ::Type{G}, ::Type{B}, ::Type{P}, subemitterwidth::T, rgbemitterpitch::T) where {R<:AbstractSpectrum,G<:AbstractSpectrum,B<:AbstractSpectrum,P<:AbstractAngularPowerDistribution,T<:Real}\n @assert 3 * subemitterwidth <= rgbemitterpitch\n\n subemitterpitch = rgbemitterpitch / T(3.0)\n e₁ = SVector{2,T}(rgbemitterpitch, T(0))\n e2 = SVector{2,T}(T(0), rgbemitterpitch)\n\n return new{R,G,B,P,T}(PrimitiveLattice(e1, e2, PlanarEmitter{R,P,T}(subemitterwidth, rgbemitterpitch)), PrimitiveLattice(e1, e2, PlanarEmitter{G,P,T}(subemitterwidth, rgbemitterpitch), origin = SVector{2,T}(subemitterpitch, T(0.0))), PrimitiveLattice(e1, e2, PlanarEmitter{B,P,T}(subemitterwidth, rgbemitterpitch), origin = SVector{2,T}(2 * subemitterpitch, T(0.0))))\n end\nend\n", "meta": {"hexsha": "4cb098064c3a1b307afb47b8f48da12685f71ecd", "size": 4590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Optical/Lattice.jl", "max_stars_repo_name": "waldyrious/OpticSim.jl", "max_stars_repo_head_hexsha": "43bab8b3dc256e00ef781d55d5e216f64f558820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-29T19:26:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T19:26:42.000Z", "max_issues_repo_path": "src/Optical/Lattice.jl", "max_issues_repo_name": "AndiMD/OpticSim.jl", "max_issues_repo_head_hexsha": "86ae7eeadb7cdc23a0cd21235ac293b9848b29c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optical/Lattice.jl", "max_forks_repo_name": "AndiMD/OpticSim.jl", "max_forks_repo_head_hexsha": "86ae7eeadb7cdc23a0cd21235ac293b9848b29c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.3012048193, "max_line_length": 375, "alphanum_fraction": 0.731372549, "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19733960880496648}} {"text": "function update_and_get_max_abs_diff!( pssrb::PotentialSimulationSetupRB{T, S, DAT, N1, N2},\r\n depletion_handling::Val{depletion_handling_enabled}, \r\n only2d::Val{only_2d} = Val{false}(), \r\n is_weighting_potential::Val{_is_weighting_potential} = Val{false}(),\r\n use_nthreads::Int = Base.Threads.nthreads()\r\n )::T where {T, S, DAT, N1, N2, depletion_handling_enabled, only_2d, _is_weighting_potential}\r\n tmp_potential::Array{T, N2} = copy(pssrb.potential)\r\n if depletion_handling_enabled\r\n update!(pssrb, use_nthreads = use_nthreads, depletion_handling = depletion_handling, only2d = only2d, is_weighting_potential = is_weighting_potential)\r\n slopes::Array{T, N2} = tmp_potential - pssrb.potential\r\n @inbounds for i in 1:19\r\n tmp_potential[:] = pssrb.potential[:]\r\n update!(pssrb, use_nthreads = use_nthreads, depletion_handling = depletion_handling, only2d = only2d, is_weighting_potential = is_weighting_potential)\r\n slopes += tmp_potential - pssrb.potential\r\n end\r\n @inbounds slopes /= 20\r\n return maximum(abs.(slopes))\r\n else\r\n for i in 1:10\r\n update!(pssrb, use_nthreads = use_nthreads, depletion_handling = depletion_handling, only2d = only2d, is_weighting_potential = is_weighting_potential)\r\n end\r\n max_diff::T = maximum(abs.(tmp_potential - pssrb.potential))\r\n return max_diff\r\n end\r\nend\r\n\r\nfunction _update_till_convergence!( pssrb::PotentialSimulationSetupRB{T, S, 3}, \r\n convergence_limit::T, \r\n ::Type{Array};\r\n n_iterations_between_checks = 500,\r\n depletion_handling::Val{depletion_handling_enabled} = Val{false}(),\r\n only2d::Val{only_2d} = Val{false}(), \r\n is_weighting_potential::Val{_is_weighting_potential} = Val{false}(),\r\n use_nthreads::Int = Base.Threads.nthreads(), \r\n max_n_iterations::Int = -1,\r\n verbose::Bool = true\r\n )::T where {T, S, depletion_handling_enabled, only_2d, _is_weighting_potential}\r\n n_iterations::Int = 0\r\n cf::T = Inf\r\n cfs::Vector{T} = fill(cf, 10)\r\n cl::T = _is_weighting_potential ? convergence_limit : abs(convergence_limit * pssrb.bias_voltage) # to get relative change in respect to bias voltage\r\n # To disable automatically ProgressMeters in CI builds:\r\n is_logging(io) = isa(io, Base.TTY) == false || (get(ENV, \"CI\", nothing) == \"true\")\r\n if verbose prog = ProgressThresh(cl; dt = 0.1, desc = \"Convergence: \", output = stderr, enabled = !is_logging(stderr)) end\r\n while cf > cl\r\n for i in 1:n_iterations_between_checks\r\n update!(pssrb, use_nthreads = use_nthreads, depletion_handling = depletion_handling, only2d = only2d, is_weighting_potential = is_weighting_potential)\r\n end\r\n cf = update_and_get_max_abs_diff!(pssrb, depletion_handling, only2d, is_weighting_potential, use_nthreads)\r\n @inbounds cfs[1:end-1] = cfs[2:end]\r\n @inbounds cfs[end] = cf\r\n slope::T = abs(mean(diff(cfs)))\r\n if verbose ProgressMeter.update!(prog, cf) end\r\n n_iterations += n_iterations_between_checks\r\n if slope < cl\r\n # @info \"Slope is basically 0 -> Converged: $slope\"\r\n cf = slope\r\n end\r\n if max_n_iterations > 0 && n_iterations > max_n_iterations\r\n # @show n_iterations_between_checks\r\n @info \"Maximum number of iterations reached. (`n_iterations = $(n_iterations)`)\"\r\n break\r\n end\r\n end\r\n if depletion_handling_enabled\r\n tmp_point_types = pssrb.point_types .& undepleted_bit\r\n @showprogress \"Checking undepleted regions \" for i in 1:10\r\n update!(pssrb, use_nthreads = use_nthreads, depletion_handling = depletion_handling, only2d = only2d, is_weighting_potential = is_weighting_potential)\r\n @inbounds for i in eachindex(pssrb.point_types)\r\n if (pssrb.point_types[i] & undepleted_bit == 0) && (tmp_point_types[i] > 0)\r\n pssrb.point_types[i] += undepleted_bit\r\n elseif (pssrb.point_types[i] & undepleted_bit > 0) && (tmp_point_types[i] == 0)\r\n tmp_point_types[i] += undepleted_bit\r\n end\r\n end\r\n end\r\n end\r\n\r\n if verbose ProgressMeter.finish!(prog) end\r\n return cf\r\nend\r\n\r\n\r\n# \"\"\"\r\n# refine_scalar_potential(p::ScalarPotential{T}, max_diffs::NTuple{3, T}, minimum_distances::NTuple{3, T}; \r\n# only2d::Val{only_2d} = Val(size(p.data, 2)==1)) where {T, only_2d}\r\n# \r\n# Refine any scalar potential `p`. \r\n# \r\n# 1. Extent the grid to be a closed grid in all dimensions. \r\n# 2. Refine the axis of the grid based on `max_diffs` and `minimum_applied_potential`:\r\n# Insert N new ticks between to existing ticks such that the potential difference between each tick becomes\r\n# smaller than `max_diff[i]` (i -> dimension) but that the distances between the ticks stays larger than `minimum_distances[i]`.\r\n# 3. Create the new data array for the refined grid and fill it by interpolation of the the initial (coarse) grid.\r\n# \"\"\"\r\nfunction refine_scalar_potential(p::ScalarPotential{T}, max_diffs::NTuple{3, T}, minimum_distances::NTuple{3, T}; \r\n only2d::Val{only_2d} = Val(size(p.data, 2)==1)) where {T, only_2d}\r\n closed_potential = _get_closed_potential(p)\r\n new_grid = _create_refined_grid(closed_potential, T.(max_diffs), T.(minimum_distances))\r\n new_data = Array{T, 3}(undef, size(new_grid))\r\n if only_2d\r\n int = interpolate_closed_potential(closed_potential, only2d)\r\n for i3 in axes(new_data, 3)\r\n x3 = new_grid.axes[3].ticks[i3]\r\n for i1 in axes(new_data, 1)\r\n x1 = new_grid.axes[1].ticks[i1]\r\n new_data[i1, 1, i3] = int(x1, x3)\r\n end\r\n end\r\n else\r\n int = interpolate_closed_potential(closed_potential, only2d)\r\n for i3 in axes(new_data, 3)\r\n x3 = new_grid.axes[3].ticks[i3]\r\n for i2 in axes(new_data, 2)\r\n x2 = new_grid.axes[2].ticks[i2]\r\n for i1 in axes(new_data, 1)\r\n x1 = new_grid.axes[1].ticks[i1]\r\n new_data[i1, i2, i3] = int(x1, x2, x3)\r\n end\r\n end\r\n end\r\n end\r\n return _convert_to_original_potential(p, new_data, new_grid)\r\nend \r\n\r\nfunction interpolate_closed_potential(p::ScalarPotential, ::Val{true}) where {T}\r\n interpolate((p.grid.axes[1], p.grid.axes[3]), p.data[:,1,:], Gridded(Linear()))\r\nend\r\nfunction interpolate_closed_potential(p::ScalarPotential, ::Val{false}) where {T}\r\n interpolate(p.grid.axes, p.data, Gridded(Linear()))\r\nend\r\n\r\n_get_closed_ticks(ticks::Vector{T}, int::ClosedInterval{T}) where {T} = ticks\r\n_get_closed_ticks(ticks::Vector{T}, int::Interval{:closed, :open, T}) where {T} = vcat(ticks, int.right)\r\n_get_closed_ticks(ticks::Vector{T}, int::Interval{:open, :closed, T}) where {T} = vcat(int.left, ticks)\r\n\r\n_get_closed_values(values::Array{T,3}, dim::Int, int::ClosedInterval{T}) where {T} = values\r\n\r\nfunction _get_closed_values(values::Array{T,3}, dim::Int, int::Interval{:closed, :open, T})::Array{T,3} where {T} \r\n if dim == 1\r\n cat(values, values[1:1,:,:], dims=dim)\r\n elseif dim == 2\r\n cat(values, values[:,1:1,:], dims=dim)\r\n else # dim == 3\r\n cat(values, values[:,:,1:1], dims=dim)\r\n end\r\nend\r\nfunction _get_closed_values(values::Array{T,3}, dim::Int, int::Interval{:open, :closed, T})::Array{T,3} where {T} \r\n if dim == 1\r\n cat(values[end:end,:,:], values, dims=dim)\r\n elseif dim == 2\r\n cat(values[:,end:end,:], values, dims=dim)\r\n else # dim == 3\r\n cat(values[:,:,end:end], values, dims=dim)\r\n end\r\nend\r\n\r\nfunction _get_closed_axis(ax::DiscreteAxis{T, BL, BR}) where {T, BL, BR}\r\n ticks = _get_closed_ticks(ax.ticks, ax.interval)\r\n return DiscreteAxis{T, BL, BR, ClosedInterval{T}}(ClosedInterval(ax.interval.left, ax.interval.right), ticks)\r\nend\r\n\r\n# \"\"\"\r\n# _get_closed_potential(p::ScalarPotential{T,3,CS}) where {T, CS}\r\n# \r\n# Returns an closed Grid & Potential:\r\n# E.g. if one of the axis is {:closed,:open} it will turn this into {:closed,:closed}\r\n# and also extend the `data` field of the potential in the respective dimension and fill\r\n# it with the respective values.\r\n# \"\"\"\r\nfunction _get_closed_potential(p::ScalarPotential{T,3,CS}) where {T, CS}\r\n grid = p.grid\r\n closed_values = _get_closed_values(p.data, 1, grid.axes[1].interval)\r\n closed_values = _get_closed_values(closed_values, 2, grid.axes[2].interval)\r\n closed_values = _get_closed_values(closed_values, 3, grid.axes[3].interval)\r\n closed_axes = broadcast(i -> _get_closed_axis(grid.axes[i]), (1, 2, 3))\r\n AT = typeof(closed_axes)\r\n closed_grid = Grid{T, 3, CS, AT}(closed_axes)\r\n ScalarPotential(p, closed_values, closed_grid)\r\nend\r\n\r\n# \"\"\"\r\n# _convert_to_original_potential(::Type{P}, data, grid) where {P, T, CS}\r\n# \r\n# Basically the counterpart to `_get_closed_potential`.\r\n# \"\"\"\r\nfunction _convert_to_original_potential(p::ScalarPotential{T,3,CS,ATO}, data::Array{T, 3}, grid::Grid{T, 3, CS, AT}) where {T, CS, AT, ATO}\r\n ATs = get_axes_type(ATO)\r\n axs = broadcast(i -> _convert_closed_axis(ATs[i], grid.axes[i]), (1, 2, 3))\r\n new_data = _reduce_closed_values(ATs, data)\r\n new_grid = Grid{T,3,CS,ATO}(axs)\r\n ScalarPotential(p, new_data, new_grid)\r\nend\r\n\r\n_convert_closed_axis(::Type{DiscreteAxis{T, BL, BR, I}}, ax::DiscreteAxis{T, BL, BR, I}) where {T, BL, BR, I} = ax\r\n\r\nfunction _convert_closed_axis(::Type{DiscreteAxis{T, BL, BR, Interval{:closed, :open, T}}}, ax::DiscreteAxis{T, BL, BR, ClosedInterval{T}}) where {T, BL, BR}\r\n DiscreteAxis{T, BL, BR, Interval{:closed, :open, T}}(Interval{:closed, :open, T}(ax.interval.left, ax.interval.right), ax.ticks[1:end-1])\r\nend\r\nfunction _convert_closed_axis(::Type{DiscreteAxis{T, BL, BR, Interval{:open, :closed, T}}}, ax::DiscreteAxis{T, BL, BR, ClosedInterval{T}}) where {T, BL, BR}\r\n DiscreteAxis{T, BL, BR, Interval{:open, :closed, T}}(Interval{:open, :closed, T}(ax.interval.left, ax.interval.right), ax.ticks[2:end])\r\nend\r\n\r\nfunction _reduce_closed_values(axTypes::Tuple, a::Array{T, 3}) where {T} \r\n inds = broadcast(i -> _get_ind_range_of_closed_axis(size(a, i), axTypes[i]), (1, 2, 3))\r\n a[inds...]\r\nend\r\n\r\n_get_ind_range_of_closed_axis(l::Int, ::Type{DiscreteAxis{T, BL, BR, ClosedInterval{T}}}) where {T, BL, BR} = 1:l\r\n_get_ind_range_of_closed_axis(l::Int, ::Type{DiscreteAxis{T, BL, BR, Interval{:closed, :open, T}}}) where {T, BL, BR} = 1:(l-1)\r\n_get_ind_range_of_closed_axis(l::Int, ::Type{DiscreteAxis{T, BL, BR, Interval{:open, :closed, T}}}) where {T, BL, BR} = 2:l\r\n\r\n\r\nfunction _create_refined_grid(p::ScalarPotential{T,3}, max_diffs::NTuple{3, T}, minimum_distances::NTuple{3, T}) where {T}\r\n max_diffs = broadcast(md -> iszero(md) ? Inf : md, max_diffs)\r\n n_1 = floor.(Int, [maximum(abs.(p.data[i+1,:,:] .- p.data[i,:,:])) for i in 1:size(p.data, 1)-1] ./ max_diffs[1]) \r\n n_2 = floor.(Int, [maximum(abs.(p.data[:,i+1,:] .- p.data[:,i,:])) for i in 1:size(p.data, 2)-1] ./ max_diffs[2]) \r\n n_3 = floor.(Int, [maximum(abs.(p.data[:,:,i+1] .- p.data[:,:,i])) for i in 1:size(p.data, 3)-1] ./ max_diffs[3]) \r\n ns = (n_1, n_2, n_3)\r\n widths = diff.((p.grid.axes[1].ticks, p.grid.axes[2].ticks, p.grid.axes[3].ticks))\r\n sub_widths = broadcast(ia -> [widths[ia][i] / (ns[ia][i]+1) for i in eachindex(ns[ia])], (1,2,3))\r\n for ia in 1:3\r\n for i in eachindex(ns[ia])\r\n while sub_widths[ia][i] < minimum_distances[ia] && ns[ia][i] > 0\r\n ns[ia][i] -= 1\r\n sub_widths[ia][i] = widths[ia][i] / (ns[ia][i]+1)\r\n end\r\n end\r\n end\r\n for i in 1:3 # always add an even number of ticks\r\n if isodd(sum(ns[i])) \r\n i_max_width = findmax(sub_widths[i])[2]\r\n ns[i][i_max_width] += 1 \r\n sub_widths[i][i_max_width] = widths[i][i_max_width] / (ns[i][i_max_width]+1)\r\n end\r\n end\r\n new_axes = broadcast(i -> _refine_axis(p.grid.axes[i], ns[i], sub_widths[i]), (1, 2, 3))\r\n return typeof(p.grid)(new_axes)\r\nend\r\n\r\nfunction _refine_axis(ax::DiscreteAxis{T, <:Any, <:Any, ClosedInterval{T}}, ns::Vector{Int}, sub_widths::Vector{T}) where {T, I}\r\n @assert length(ns) == length(ax.ticks)-1 # for ClosedInterval axis\r\n ticks = Vector{T}(undef, length(ax.ticks) + sum(ns))\r\n i = 1 \r\n for j in eachindex(ns)\r\n ticks[i] = ax.ticks[j]\r\n for k in 1:ns[j]\r\n i += 1 \r\n ticks[i] = ax.ticks[j] + k * sub_widths[j]\r\n end\r\n i += 1 \r\n end\r\n ticks[end] = ax.ticks[end]\r\n typeof(ax)(ax.interval, ticks)\r\nend\r\n\r\n\r\n_extend_refinement_limits(rl::Real) = (rl, rl, rl )\r\n_extend_refinement_limits(rl::Tuple{<:Real,<:Real,<:Real}) = rl\r\n", "meta": {"hexsha": "222e2dda80e64ce3000fa1ca5571b5649bacc83e", "size": 13339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PotentialSimulation/ConvergenceAndRefinement.jl", "max_stars_repo_name": "hervasa2/SolidStateDetectors.jl", "max_stars_repo_head_hexsha": "c640fc84c617fb5dc360aba43550c86e959e47a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2019-07-10T06:21:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:45:57.000Z", "max_issues_repo_path": "src/PotentialSimulation/ConvergenceAndRefinement.jl", "max_issues_repo_name": "hervasa2/SolidStateDetectors.jl", "max_issues_repo_head_hexsha": "c640fc84c617fb5dc360aba43550c86e959e47a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 183, "max_issues_repo_issues_event_min_datetime": "2019-07-05T09:54:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:45:25.000Z", "max_forks_repo_path": "src/PotentialSimulation/ConvergenceAndRefinement.jl", "max_forks_repo_name": "hervasa2/SolidStateDetectors.jl", "max_forks_repo_head_hexsha": "c640fc84c617fb5dc360aba43550c86e959e47a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-08-28T11:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T10:26:24.000Z", "avg_line_length": 51.3038461538, "max_line_length": 163, "alphanum_fraction": 0.613089437, "num_tokens": 3796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.1973396049742322}} {"text": "# ----------------------------------------------------------------------------------- #\n# Copyright (c) 2016 Varnerlab\n# Robert Frederick Smith School of Chemical and Biomolecular Engineering\n# Cornell University, Ithaca NY 14850\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n# ----------------------------------------------------------------------------------- #\n#\n# ----------------------------------------------------------------------------------- #\n# Function: DataDictionary\n# Description: Holds simulation and model parameters as key => value pairs in a Julia Dict()\n# Generated on: 2016-11-02T07:00:00.307\n#\n# Input arguments:\n# time_start::Float64 => Simulation start time value (scalar)\n# time_stop::Float64 => Simulation stop time value (scalar)\n# time_step::Float64 => Simulation time step (scalar)\n#\n# Output arguments:\n# data_dictionary::Dict{AbstractString,Any} => Dictionary holding model and simulation parameters as key => value pairs\n# ----------------------------------------------------------------------------------- #\nfunction DataDictionary(time_start::Float64,time_stop::Float64,time_step_size::Float64)\n\n\t# stoichiometric_matrix and dilution_matrix -\n\tstoichiometric_matrix = readdlm(\"./Network.dat\")\n\tdilution_matrix = readdlm(\"./Dilution.dat\")\n\tdegradation_matrix = readdlm(\"./Degradation.dat\")\n\n\t# array of gene lengths -\n\t# gene_coding_length_array = [\n\t# \t15000\t;\t# 1\tgene_AP1\n\t# \t15000\t;\t# 2\tgene_AhR\n\t# \t15000\t;\t# 3\tgene_CD11b\n\t# \t15000\t;\t# 4\tgene_CD14\n\t# \t15000\t;\t# 5\tgene_CD38\n\t# \t15000\t;\t# 6\tgene_CEBPa\n\t# \t15000\t;\t# 7\tgene_E2F\n\t# \t15000\t;\t# 8\tgene_EGR1\n\t# \t15000\t;\t# 9\tgene_GFI1\n\t# \t15000\t;\t# 10\tgene_IRF1\n\t# \t15000\t;\t# 11\tgene_OCT1\n\t# \t15000\t;\t# 12\tgene_OCT4\n\t# \t15000\t;\t# 13\tgene_P21\n\t# \t15000\t;\t# 14\tgene_P47Phox\n\t# \t15000\t;\t# 15\tgene_PPARg\n\t# \t15000\t;\t# 16\tgene_PU1\n\t# \t15000\t;\t# 17\tgene_Trigger\n\t# \t15000\t;\t# 18\tgene_cRAF\n\t# ]\n\n\tgene_coding_length_array = [\n\t\t10323\t;\t# 1\tgene_AP1\n\t\t47530\t;\t# 2\tgene_AhR\n\t\t72925\t;\t# 3\tgene_CD11b\n\t\t8974\t;\t# 4\tgene_CD14\n\t\t74978\t;\t# 5\tgene_CD38\n\t\t2630\t;\t# 6\tgene_CEBPa\n\t\t17919\t;\t# 7\tgene_E2F\n\t\t10824\t;\t# 8\tgene_EGR1\n\t\t13833\t;\t# 9\tgene_GFI1\n\t\t16165\t;\t# 10\tgene_IRF1\n\t\t206516 \t;\t# 11\tgene_OCT1\n\t\t6356\t;\t# 12\tgene_OCT4\n\t\t15651\t;\t# 13\tgene_P21\n\t\t3074\t;\t# 14\tgene_P47Phox https://www.ncbi.nlm.nih.gov/nuccore/AF003533.1 #1475\t;\t# 14\tgene_P47Phox -- https://www.ncbi.nlm.nih.gov/nuccore/NM_000265.5\n\t\t153507\t;\t# 15\tgene_PPARg\n\t\t40782\t;\t# 16\tgene_PU1\n\t\t5908\t;\t# 17\tgene_Trigger\n\t\t87571; # 18\tgene_cRAF \thttps://www.ncbi.nlm.nih.gov/nuccore/NG_007467.1 #3291\t;\t# 18\tgene_cRAF --- NCBI homo sapien: https://www.ncbi.nlm.nih.gov/nuccore/NM_002880.3\n\t];\n\n\t# array of mRNA coding lengths -\n\tmRNA_coding_length_array = [\n\t\tgene_coding_length_array[1]\t;\t# 19\t1\tmRNA_gene_AP1\n\t\tgene_coding_length_array[2]\t;\t# 20\t2\tmRNA_gene_AhR\n\t\tgene_coding_length_array[3]\t;\t# 21\t3\tmRNA_gene_CD11b\n\t\tgene_coding_length_array[4]\t;\t# 22\t4\tmRNA_gene_CD14\n\t\tgene_coding_length_array[5]\t;\t# 23\t5\tmRNA_gene_CD38\n\t\tgene_coding_length_array[6]\t;\t# 24\t6\tmRNA_gene_CEBPa\n\t\tgene_coding_length_array[7]\t;\t# 25\t7\tmRNA_gene_E2F\n\t\tgene_coding_length_array[8]\t;\t# 26\t8\tmRNA_gene_EGR1\n\t\tgene_coding_length_array[9]\t;\t# 27\t9\tmRNA_gene_GFI1\n\t\tgene_coding_length_array[10]\t;\t# 28\t10\tmRNA_gene_IRF1\n\t\tgene_coding_length_array[11]\t;\t# 29\t11\tmRNA_gene_OCT1\n\t\tgene_coding_length_array[12]\t;\t# 30\t12\tmRNA_gene_OCT4\n\t\tgene_coding_length_array[13]\t;\t# 31\t13\tmRNA_gene_P21\n\t\tgene_coding_length_array[14]\t;\t# 32\t14\tmRNA_gene_P47Phox\n\t\tgene_coding_length_array[15]\t;\t# 33\t15\tmRNA_gene_PPARg\n\t\tgene_coding_length_array[16]\t;\t# 34\t16\tmRNA_gene_PU1\n\t\tgene_coding_length_array[17]\t;\t# 35\t17\tmRNA_gene_Trigger\n\t\tgene_coding_length_array[18]\t;\t# 36\t18\tmRNA_gene_cRAF\n\t]\n\n\t# array of mRNA coding lengths -\n\t# protein_coding_length_array = [\n\t# \tround((0.33)*mRNA_coding_length_array[1])\t;\t# 37\t1\tprotein_gene_AP1\n\t# \tround((0.33)*mRNA_coding_length_array[2])\t;\t# 38\t2\tprotein_gene_AhR\n\t# \tround((0.33)*mRNA_coding_length_array[3])\t;\t# 39\t3\tprotein_gene_CD11b\n\t# \tround((0.33)*mRNA_coding_length_array[4])\t;\t# 40\t4\tprotein_gene_CD14\n\t# \tround((0.33)*mRNA_coding_length_array[5])\t;\t# 41\t5\tprotein_gene_CD38\n\t# \tround((0.33)*mRNA_coding_length_array[6])\t;\t# 42\t6\tprotein_gene_CEBPa\n\t# \tround((0.33)*mRNA_coding_length_array[7])\t;\t# 43\t7\tprotein_gene_E2F\n\t# \tround((0.33)*mRNA_coding_length_array[8])\t;\t# 44\t8\tprotein_gene_EGR1\n\t# \tround((0.33)*mRNA_coding_length_array[9])\t;\t# 45\t9\tprotein_gene_GFI1\n\t# \tround((0.33)*mRNA_coding_length_array[10])\t;\t# 46\t10\tprotein_gene_IRF1\n\t# \tround((0.33)*mRNA_coding_length_array[11])\t;\t# 47\t11\tprotein_gene_OCT1\n\t# \tround((0.33)*mRNA_coding_length_array[12])\t;\t# 48\t12\tprotein_gene_OCT4\n\t# \tround((0.33)*mRNA_coding_length_array[13])\t;\t# 49\t13\tprotein_gene_P21\n\t# \tround((0.33)*mRNA_coding_length_array[14])\t;\t# 50\t14\tprotein_gene_P47Phox\n\t# \tround((0.33)*mRNA_coding_length_array[15])\t;\t# 51\t15\tprotein_gene_PPARg\n\t# \tround((0.33)*mRNA_coding_length_array[16])\t;\t# 52\t16\tprotein_gene_PU1\n\t# \tround((0.33)*mRNA_coding_length_array[17])\t;\t# 53\t17\tprotein_gene_Trigger\n\t# \tround((0.33)*mRNA_coding_length_array[18])\t;\t# 54\t18\tprotein_gene_cRAF\n\t# ]\n\n\t# array of mRNA coding lengths -\n\tprotein_coding_length_array = [\n\t\t331\t;\t# 37\t1\tprotein_gene_AP1\n\t\t848\t;\t# 38\t2\tprotein_gene_AhR\n\t\t1153\t;\t# 39\t3\tprotein_gene_CD11b\n\t\t375\t;\t# 40\t4\tprotein_gene_CD14\n\t\t300\t;\t# 41\t5\tprotein_gene_CD38\n\t\t393\t;\t# 42\t6\tprotein_gene_CEBPa\n\t\t437\t;\t# 43\t7\tprotein_gene_E2F\n\t\t543\t;\t# 44\t8\tprotein_gene_EGR1\n\t\t422\t;\t# 45\t9\tprotein_gene_GFI1\n\t\t325\t;\t# 46\t10\tprotein_gene_IRF1\n\t\t741.3333333333\t;\t# 47\t11\tprotein_gene_OCT1\n\t\t206.3333333\t;\t# 48\t12\tprotein_gene_OCT4\n\t\t198\t;\t# 49\t13\tprotein_gene_P21\n\t\t390\t;\t# 50\t14\tprotein_gene_P47Phox -- https://www.ncbi.nlm.nih.gov/protein/NP_000256.4\n\t\t250\t;\t# 51\t15\tprotein_gene_PPARg\n\t\t270.5\t;\t# 52\t16\tprotein_gene_PU1\n\t\t420.6666667\t\t;\t# 53\t17\tprotein_gene_Trigger\n\t\t648\t;\t# 54\t18\tprotein_gene_cRAF --https://www.ncbi.nlm.nih.gov/protein/NP_002871.1\n\t]\n\n\t# ------------------------------------------------------------------------------------------#\n\t# constants (from bionumbers) units\n\t# ------------------------------------------------------------------------------------------#\n\tcell_diameter = 12 # mum\n\tnumber_of_rnapII = 75000 # copies/cells\n\tnumber_of_ribosome = 1e6 # copies/cells\n\tmRNA_half_life_TF = 2 # hrs\n\tprotein_half_life = 10 # hrs\n\tdoubling_time_cell = 19.5 # hrs\n\tmax_translation_rate = 5 # aa/sec\n\tmax_transcription_rate = 6.0 # nt/sec\n\taverage_transcript_length = 15000 # nt\n\taverage_protein_length = 5000 # aa\n\tfraction_nucleus = 0.49 # dimensionless\n\tav_number = 6.02e23 # number/mol\n\tavg_gene_number = 2 # number of copies of a gene\n\t# ------------------------------------------------------------------------------------------#\n\t#\n\t# ------------------------------------------------------------------------------------------#\n\t# Calculate constants using bionumber values\n\t# ------------------------------------------------------------------------------------------#\n\t# Calculate the volume (convert to L)\n\tV = ((1-fraction_nucleus)*(1/6)*(3.14159)*(cell_diameter)^3)*(1e-15)\n\n\t# Calculate the rnapII_concentration and ribosome_concentration\n\trnapII_concentration = number_of_rnapII*(1/av_number)*(1/V)*1e9 # nM\n\tribosome_concentration = number_of_ribosome*(1/av_number)*(1/V)*1e9 # nM\n\n\t# degrdation rate constants -\n\tdegradation_constant_mRNA = -(1/mRNA_half_life_TF)*log(0.5) # hr^-1\n\tdegradation_constant_protein = -(1/protein_half_life)*log(0.5) # hr^-1\n\n\t# kcats for transcription and translation -\n\tkcat_transcription = max_transcription_rate*(3600/average_transcript_length) # hr^-1\n\tkcat_translation = max_translation_rate*(3600/average_protein_length) # hr^-1\n\n\t# Maximum specific growth rate -\n\tmaximum_specific_growth_rate = (1/doubling_time_cell)*log(2) # hr^-1\n\n\t# What is the average gene concentration -\n\tavg_gene_concentration = avg_gene_number*(1/av_number)*(1/V)*1e9 # nM\n\n\t# How fast do my cells die?\n\tdeath_rate_constant = 0.2*maximum_specific_growth_rate # hr^-1\n\n\t# Saturation constants for translation and trascription -\n\tsaturation_transcription = 4600*(1/av_number)*(1/V)*1e9 # nM\n\tsaturation_translation = 100000*(1/av_number)*(1/V)*1e9 # nM\n\t# -------------------------------------------------------------------------------------------#\n\n\t# initial condition array -\n\tinitial_condition_array = [\n\t\tavg_gene_concentration\t;\t# 1\tgene_AP1\n\t\tavg_gene_concentration\t;\t# 2\tgene_AhR\n\t\tavg_gene_concentration\t;\t# 3\tgene_CD11b\n\t\tavg_gene_concentration\t;\t# 4\tgene_CD14\n\t\tavg_gene_concentration\t;\t# 5\tgene_CD38\n\t\tavg_gene_concentration\t;\t# 6\tgene_CEBPa\n\t\tavg_gene_concentration\t;\t# 7\tgene_E2F\n\t\tavg_gene_concentration\t;\t# 8\tgene_EGR1\n\t\tavg_gene_concentration\t;\t# 9\tgene_GFI1\n\t\tavg_gene_concentration\t;\t# 10\tgene_IRF1\n\t\tavg_gene_concentration\t;\t# 11\tgene_OCT1\n\t\tavg_gene_concentration\t;\t# 12\tgene_OCT4\n\t\tavg_gene_concentration\t;\t# 13\tgene_P21\n\t\tavg_gene_concentration\t;\t# 14\tgene_P47Phox\n\t\tavg_gene_concentration\t;\t# 15\tgene_PPARg\n\t\tavg_gene_concentration\t;\t# 16\tgene_PU1\n\t\tavg_gene_concentration\t;\t# 17\tgene_Trigger\n\t\tavg_gene_concentration\t;\t# 18\tgene_cRAF\n\t\t0.0\t;\t# 19\tmRNA_gene_AP1\n\t\t0.0\t;\t# 20\tmRNA_gene_AhR\n\t\t0.0\t;\t# 21\tmRNA_gene_CD11b\n\t\t0.0\t;\t# 22\tmRNA_gene_CD14\n\t\t0.0\t;\t# 23\tmRNA_gene_CD38\n\t\t0.0\t;\t# 24\tmRNA_gene_CEBPa\n\t\t0.0\t;\t# 25\tmRNA_gene_E2F\n\t\t0.0\t;\t# 26\tmRNA_gene_EGR1\n\t\t0.0\t;\t# 27\tmRNA_gene_GFI1\n\t\t0.0\t;\t# 28\tmRNA_gene_IRF1\n\t\t0.0\t;\t# 29\tmRNA_gene_OCT1\n\t\t0.0\t;\t# 30\tmRNA_gene_OCT4\n\t\t0.0\t;\t# 31\tmRNA_gene_P21\n\t\t0.0\t;\t# 32\tmRNA_gene_P47Phox\n\t\t0.0\t;\t# 33\tmRNA_gene_PPARg\n\t\t0.0\t;\t# 34\tmRNA_gene_PU1\n\t\t0.0\t;\t# 35\tmRNA_gene_Trigger\n\t\t0.0\t;\t# 36\tmRNA_gene_cRAF\n\t\t0.0\t;\t# 37\tprotein_gene_AP1\n\t\t0.0\t;\t# 38\tprotein_gene_AhR\n\t\t0.0\t;\t# 39\tprotein_gene_CD11b\n\t\t0.0\t;\t# 40\tprotein_gene_CD14\n\t\t0.0\t;\t# 41\tprotein_gene_CD38\n\t\t0.0\t;\t# 42\tprotein_gene_CEBPa\n\t\t0.0\t;\t# 43\tprotein_gene_E2F\n\t\t0.0\t;\t# 44\tprotein_gene_EGR1\n\t\t0.0\t;\t# 45\tprotein_gene_GFI1\n\t\t0.0\t;\t# 46\tprotein_gene_IRF1\n\t\t0.0\t;\t# 47\tprotein_gene_OCT1\n\t\t0.0\t;\t# 48\tprotein_gene_OCT4\n\t\t0.0\t;\t# 49\tprotein_gene_P21\n\t\t0.0\t;\t# 50\tprotein_gene_P47Phox\n\t\t0.0\t;\t# 51\tprotein_gene_PPARg\n\t\t0.0\t;\t# 52\tprotein_gene_PU1\n\t\t0.0\t;\t# 53\tprotein_gene_Trigger\n\t\t0.0\t;\t# 54\tprotein_gene_cRAF\n\t]\n\n\tbinding_parameter_dictionary = Dict{AbstractString,Float64}()\n\tbinding_parameter_dictionary[\"n_gene_AP1_gene_AhR\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_AP1_gene_AhR\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_AP1_gene_PU1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_AP1_gene_PU1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_AP1_gene_PPARg\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_AP1_gene_PPARg\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_AhR_gene_Trigger\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_AhR_gene_Trigger\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_CD11b_gene_PU1_gene_cRAF\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_CD11b_gene_PU1_gene_cRAF\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_CEBPa_gene_Trigger\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_CEBPa_gene_Trigger\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_CEBPa_gene_PPARg\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_CEBPa_gene_PPARg\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_CEBPa_gene_CEBPa\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_CEBPa_gene_CEBPa\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_CEBPa_gene_GFI1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_CEBPa_gene_GFI1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_E2F_gene_E2F\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_E2F_gene_E2F\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_E2F_gene_PPARg\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_E2F_gene_PPARg\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_E2F_gene_CEBPa\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_E2F_gene_CEBPa\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_E2F_gene_GFI1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_E2F_gene_GFI1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_E2F_gene_cRAF\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_E2F_gene_cRAF\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_EGR1_gene_Trigger\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_EGR1_gene_Trigger\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_EGR1_gene_PU1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_EGR1_gene_PU1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_EGR1_gene_PPARg\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_EGR1_gene_PPARg\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_EGR1_gene_GFI1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_EGR1_gene_GFI1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_GFI1_gene_CEBPa\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_GFI1_gene_CEBPa\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_GFI1_gene_EGR1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_GFI1_gene_EGR1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_IRF1_gene_Trigger\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_IRF1_gene_Trigger\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_IRF1_gene_AhR\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_IRF1_gene_AhR\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_IRF1_gene_PPARg\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_IRF1_gene_PPARg\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_OCT1_gene_PPARg\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_OCT1_gene_PPARg\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_OCT4_gene_Trigger\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_OCT4_gene_Trigger\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_OCT4_gene_AhR\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_OCT4_gene_AhR\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_OCT4_gene_cRAF\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_OCT4_gene_cRAF\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_P21_gene_GFI1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_P21_gene_GFI1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_P47Phox_gene_PPARg\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_P47Phox_gene_PPARg\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PPARg_gene_Trigger\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PPARg_gene_Trigger\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PPARg_gene_CEBPa\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PPARg_gene_CEBPa\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PPARg_gene_EGR1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PPARg_gene_EGR1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PPARg_gene_PU1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PPARg_gene_PU1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PPARg_gene_AP1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PPARg_gene_AP1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PU1_gene_Trigger\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PU1_gene_Trigger\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PU1_gene_CEBPa\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PU1_gene_CEBPa\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PU1_gene_PU1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PU1_gene_PU1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PU1_gene_AP1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PU1_gene_AP1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PU1_gene_OCT1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PU1_gene_OCT1\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PU1_gene_AhR\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PU1_gene_AhR\"] = 120.0\n\tbinding_parameter_dictionary[\"n_gene_PU1_gene_GFI1\"] = 1.0\n\tbinding_parameter_dictionary[\"K_gene_PU1_gene_GFI1\"] = 120.0\n\n\t# Alias the control function parameters -\n\tcontrol_parameter_dictionary = Dict{AbstractString,Float64}()\n\tcontrol_parameter_dictionary[\"W_gene_AP1_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_AP1_gene_AhR\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_AP1_gene_PU1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_AP1_gene_PPARg\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_AhR_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_AhR_gene_Trigger\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_CD11b_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_CD11b_gene_PU1_gene_cRAF\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_CD14_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"] = 0.0\n\tcontrol_parameter_dictionary[\"W_gene_CD38_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_CEBPa_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_CEBPa_gene_Trigger\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_CEBPa_gene_PPARg\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_CEBPa_gene_CEBPa\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_CEBPa_gene_GFI1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_E2F_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_E2F_gene_E2F\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_E2F_gene_PPARg\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_E2F_gene_CEBPa\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_E2F_gene_GFI1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_E2F_gene_cRAF\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_EGR1_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_EGR1_gene_Trigger\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_EGR1_gene_PU1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_EGR1_gene_PPARg\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_EGR1_gene_GFI1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_GFI1_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_GFI1_gene_CEBPa\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_GFI1_gene_EGR1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_IRF1_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_IRF1_gene_Trigger\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_IRF1_gene_AhR\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_IRF1_gene_PPARg\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_OCT1_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_OCT1_gene_PPARg\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_OCT4_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_OCT4_gene_Trigger\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_OCT4_gene_AhR\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_OCT4_gene_cRAF\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_P21_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_P21_gene_GFI1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_P47Phox_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_P47Phox_gene_PPARg\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PPARg_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_PPARg_gene_Trigger\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PPARg_gene_CEBPa\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PPARg_gene_EGR1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PPARg_gene_PU1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PPARg_gene_AP1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PU1_RNAP\"] = 0.001\n\tcontrol_parameter_dictionary[\"W_gene_PU1_gene_Trigger\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PU1_gene_CEBPa\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PU1_gene_PU1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PU1_gene_AP1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PU1_gene_OCT1\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PU1_gene_AhR\"] = 1.0\n\tcontrol_parameter_dictionary[\"W_gene_PU1_gene_GFI1\"] = 1.0\n\n\t# These need to be zero => no background expression -\n\tcontrol_parameter_dictionary[\"W_gene_Trigger_RNAP\"] = 0.0;\n\tcontrol_parameter_dictionary[\"W_gene_cRAF_RNAP\"] = 0.0;\n\n\t# Parameter name index array -\n\tparameter_name_mapping_array = [\n\t\t\"n_gene_AP1_gene_AhR\"\t;\t# 1\n\t\t\"K_gene_AP1_gene_AhR\"\t;\t# 2\n\t\t\"n_gene_AP1_gene_PU1\"\t;\t# 3\n\t\t\"K_gene_AP1_gene_PU1\"\t;\t# 4\n\t\t\"n_gene_AP1_gene_PPARg\"\t;\t# 5\n\t\t\"K_gene_AP1_gene_PPARg\"\t;\t# 6\n\t\t\"n_gene_AhR_gene_Trigger\"\t;\t# 7\n\t\t\"K_gene_AhR_gene_Trigger\"\t;\t# 8\n\t\t\"n_gene_CD11b_gene_PU1_gene_cRAF\"\t;\t# 9\n\t\t\"K_gene_CD11b_gene_PU1_gene_cRAF\"\t;\t# 10\n\t\t\"n_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"\t;\t# 11\n\t\t\"K_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"\t;\t# 12\n\t\t\"n_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"\t;\t# 13\n\t\t\"K_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"\t;\t# 14\n\t\t\"n_gene_CEBPa_gene_Trigger\"\t;\t# 15\n\t\t\"K_gene_CEBPa_gene_Trigger\"\t;\t# 16\n\t\t\"n_gene_CEBPa_gene_PPARg\"\t;\t# 17\n\t\t\"K_gene_CEBPa_gene_PPARg\"\t;\t# 18\n\t\t\"n_gene_CEBPa_gene_CEBPa\"\t;\t# 19\n\t\t\"K_gene_CEBPa_gene_CEBPa\"\t;\t# 20\n\t\t\"n_gene_CEBPa_gene_GFI1\"\t;\t# 21\n\t\t\"K_gene_CEBPa_gene_GFI1\"\t;\t# 22\n\t\t\"n_gene_E2F_gene_E2F\"\t;\t# 23\n\t\t\"K_gene_E2F_gene_E2F\"\t;\t# 24\n\t\t\"n_gene_E2F_gene_PPARg\"\t;\t# 25\n\t\t\"K_gene_E2F_gene_PPARg\"\t;\t# 26\n\t\t\"n_gene_E2F_gene_CEBPa\"\t;\t# 27\n\t\t\"K_gene_E2F_gene_CEBPa\"\t;\t# 28\n\t\t\"n_gene_E2F_gene_GFI1\"\t;\t# 29\n\t\t\"K_gene_E2F_gene_GFI1\"\t;\t# 30\n\t\t\"n_gene_E2F_gene_cRAF\"\t;\t# 31\n\t\t\"K_gene_E2F_gene_cRAF\"\t;\t# 32\n\t\t\"n_gene_EGR1_gene_Trigger\"\t;\t# 33\n\t\t\"K_gene_EGR1_gene_Trigger\"\t;\t# 34\n\t\t\"n_gene_EGR1_gene_PU1\"\t;\t# 35\n\t\t\"K_gene_EGR1_gene_PU1\"\t;\t# 36\n\t\t\"n_gene_EGR1_gene_PPARg\"\t;\t# 37\n\t\t\"K_gene_EGR1_gene_PPARg\"\t;\t# 38\n\t\t\"n_gene_EGR1_gene_GFI1\"\t;\t# 39\n\t\t\"K_gene_EGR1_gene_GFI1\"\t;\t# 40\n\t\t\"n_gene_GFI1_gene_CEBPa\"\t;\t# 41\n\t\t\"K_gene_GFI1_gene_CEBPa\"\t;\t# 42\n\t\t\"n_gene_GFI1_gene_EGR1\"\t;\t# 43\n\t\t\"K_gene_GFI1_gene_EGR1\"\t;\t# 44\n\t\t\"n_gene_IRF1_gene_Trigger\"\t;\t# 45\n\t\t\"K_gene_IRF1_gene_Trigger\"\t;\t# 46\n\t\t\"n_gene_IRF1_gene_AhR\"\t;\t# 47\n\t\t\"K_gene_IRF1_gene_AhR\"\t;\t# 48\n\t\t\"n_gene_IRF1_gene_PPARg\"\t;\t# 49\n\t\t\"K_gene_IRF1_gene_PPARg\"\t;\t# 50\n\t\t\"n_gene_OCT1_gene_PPARg\"\t;\t# 51\n\t\t\"K_gene_OCT1_gene_PPARg\"\t;\t# 52\n\t\t\"n_gene_OCT4_gene_Trigger\"\t;\t# 53\n\t\t\"K_gene_OCT4_gene_Trigger\"\t;\t# 54\n\t\t\"n_gene_OCT4_gene_AhR\"\t;\t# 55\n\t\t\"K_gene_OCT4_gene_AhR\"\t;\t# 56\n\t\t\"n_gene_OCT4_gene_cRAF\"\t;\t# 57\n\t\t\"K_gene_OCT4_gene_cRAF\"\t;\t# 58\n\t\t\"n_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"\t;\t# 59\n\t\t\"K_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"\t;\t# 60\n\t\t\"n_gene_P21_gene_GFI1\"\t;\t# 61\n\t\t\"K_gene_P21_gene_GFI1\"\t;\t# 62\n\t\t\"n_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"\t;\t# 63\n\t\t\"K_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"\t;\t# 64\n\t\t\"n_gene_P47Phox_gene_PPARg\"\t;\t# 65\n\t\t\"K_gene_P47Phox_gene_PPARg\"\t;\t# 66\n\t\t\"n_gene_PPARg_gene_Trigger\"\t;\t# 67\n\t\t\"K_gene_PPARg_gene_Trigger\"\t;\t# 68\n\t\t\"n_gene_PPARg_gene_CEBPa\"\t;\t# 69\n\t\t\"K_gene_PPARg_gene_CEBPa\"\t;\t# 70\n\t\t\"n_gene_PPARg_gene_EGR1\"\t;\t# 71\n\t\t\"K_gene_PPARg_gene_EGR1\"\t;\t# 72\n\t\t\"n_gene_PPARg_gene_PU1\"\t;\t# 73\n\t\t\"K_gene_PPARg_gene_PU1\"\t;\t# 74\n\t\t\"n_gene_PPARg_gene_AP1\"\t;\t# 75\n\t\t\"K_gene_PPARg_gene_AP1\"\t;\t# 76\n\t\t\"n_gene_PU1_gene_Trigger\"\t;\t# 77\n\t\t\"K_gene_PU1_gene_Trigger\"\t;\t# 78\n\t\t\"n_gene_PU1_gene_CEBPa\"\t;\t# 79\n\t\t\"K_gene_PU1_gene_CEBPa\"\t;\t# 80\n\t\t\"n_gene_PU1_gene_PU1\"\t;\t# 81\n\t\t\"K_gene_PU1_gene_PU1\"\t;\t# 82\n\t\t\"n_gene_PU1_gene_AP1\"\t;\t# 83\n\t\t\"K_gene_PU1_gene_AP1\"\t;\t# 84\n\t\t\"n_gene_PU1_gene_OCT1\"\t;\t# 85\n\t\t\"K_gene_PU1_gene_OCT1\"\t;\t# 86\n\t\t\"n_gene_PU1_gene_AhR\"\t;\t# 87\n\t\t\"K_gene_PU1_gene_AhR\"\t;\t# 88\n\t\t\"n_gene_PU1_gene_GFI1\"\t;\t# 89\n\t\t\"K_gene_PU1_gene_GFI1\"\t;\t# 90\n\t\t\"W_gene_AP1_RNAP\"\t;\t# 91\n\t\t\"W_gene_AP1_gene_AhR\"\t;\t# 92\n\t\t\"W_gene_AP1_gene_PU1\"\t;\t# 93\n\t\t\"W_gene_AP1_gene_PPARg\"\t;\t# 94\n\t\t\"W_gene_AhR_RNAP\"\t;\t# 95\n\t\t\"W_gene_AhR_gene_Trigger\"\t;\t# 96\n\t\t\"W_gene_CD11b_RNAP\"\t;\t# 97\n\t\t\"W_gene_CD11b_gene_PU1_gene_cRAF\"\t;\t# 98\n\t\t\"W_gene_CD14_RNAP\"\t;\t# 99\n\t\t\"W_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"\t;\t# 100\n\t\t\"W_gene_CD38_RNAP\"\t;\t# 101\n\t\t\"W_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"\t;\t# 102\n\t\t\"W_gene_CEBPa_RNAP\"\t;\t# 103\n\t\t\"W_gene_CEBPa_gene_Trigger\"\t;\t# 104\n\t\t\"W_gene_CEBPa_gene_PPARg\"\t;\t# 105\n\t\t\"W_gene_CEBPa_gene_CEBPa\"\t;\t# 106\n\t\t\"W_gene_CEBPa_gene_GFI1\"\t;\t# 107\n\t\t\"W_gene_E2F_RNAP\"\t;\t# 108\n\t\t\"W_gene_E2F_gene_E2F\"\t;\t# 109\n\t\t\"W_gene_E2F_gene_PPARg\"\t;\t# 110\n\t\t\"W_gene_E2F_gene_CEBPa\"\t;\t# 111\n\t\t\"W_gene_E2F_gene_GFI1\"\t;\t# 112\n\t\t\"W_gene_E2F_gene_cRAF\"\t;\t# 113\n\t\t\"W_gene_EGR1_RNAP\"\t;\t# 114\n\t\t\"W_gene_EGR1_gene_Trigger\"\t;\t# 115\n\t\t\"W_gene_EGR1_gene_PU1\"\t;\t# 116\n\t\t\"W_gene_EGR1_gene_PPARg\"\t;\t# 117\n\t\t\"W_gene_EGR1_gene_GFI1\"\t;\t# 118\n\t\t\"W_gene_GFI1_RNAP\"\t;\t# 119\n\t\t\"W_gene_GFI1_gene_CEBPa\"\t;\t# 120\n\t\t\"W_gene_GFI1_gene_EGR1\"\t;\t# 121\n\t\t\"W_gene_IRF1_RNAP\"\t;\t# 122\n\t\t\"W_gene_IRF1_gene_Trigger\"\t;\t# 123\n\t\t\"W_gene_IRF1_gene_AhR\"\t;\t# 124\n\t\t\"W_gene_IRF1_gene_PPARg\"\t;\t# 125\n\t\t\"W_gene_OCT1_RNAP\"\t;\t# 126\n\t\t\"W_gene_OCT1_gene_PPARg\"\t;\t# 127\n\t\t\"W_gene_OCT4_RNAP\"\t;\t# 128\n\t\t\"W_gene_OCT4_gene_Trigger\"\t;\t# 129\n\t\t\"W_gene_OCT4_gene_AhR\"\t;\t# 130\n\t\t\"W_gene_OCT4_gene_cRAF\"\t;\t# 131\n\t\t\"W_gene_P21_RNAP\"\t;\t# 132\n\t\t\"W_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"\t;\t# 133\n\t\t\"W_gene_P21_gene_GFI1\"\t;\t# 134\n\t\t\"W_gene_P47Phox_RNAP\"\t;\t# 135\n\t\t\"W_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"\t;\t# 136\n\t\t\"W_gene_P47Phox_gene_PPARg\"\t;\t# 137\n\t\t\"W_gene_PPARg_RNAP\"\t;\t# 138\n\t\t\"W_gene_PPARg_gene_Trigger\"\t;\t# 139\n\t\t\"W_gene_PPARg_gene_CEBPa\"\t;\t# 140\n\t\t\"W_gene_PPARg_gene_EGR1\"\t;\t# 141\n\t\t\"W_gene_PPARg_gene_PU1\"\t;\t# 142\n\t\t\"W_gene_PPARg_gene_AP1\"\t;\t# 143\n\t\t\"W_gene_PU1_RNAP\"\t;\t# 144\n\t\t\"W_gene_PU1_gene_Trigger\"\t;\t# 145\n\t\t\"W_gene_PU1_gene_CEBPa\"\t;\t# 146\n\t\t\"W_gene_PU1_gene_PU1\"\t;\t# 147\n\t\t\"W_gene_PU1_gene_AP1\"\t;\t# 148\n\t\t\"W_gene_PU1_gene_OCT1\"\t;\t# 149\n\t\t\"W_gene_PU1_gene_AhR\"\t;\t# 150\n\t\t\"W_gene_PU1_gene_GFI1\"\t;\t# 151\n\t\t\"W_gene_Trigger_RNAP\"\t;\t# 152\n\t\t\"W_gene_cRAF_RNAP\"\t;\t# 153\n\t]\n\n\t# Background copy number - (added by JV)\n\tbackground_copy_number_dictionary = Dict{AbstractString,Float64}()\n\tbackground_copy_number_dictionary[\"protein_gene_AP1\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_AhR\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_CD11b\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_CD14\"] = 10.0\n\tbackground_copy_number_dictionary[\"protein_gene_CD38\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_CEBPa\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_E2F\"] = 10000.0\n\tbackground_copy_number_dictionary[\"protein_gene_OCT4\"] = 10000.0\n\tbackground_copy_number_dictionary[\"protein_gene_EGR1\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_GFI1\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_OCT1\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_P21\"] = 1000.0\n\tbackground_copy_number_dictionary[\"protein_gene_P47Phox\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_PPARg\"] = 100.0\n\tbackground_copy_number_dictionary[\"protein_gene_PU1\"] = 1000.0\n\tbackground_copy_number_dictionary[\"protein_gene_IRF1\"] = 100.0\n\n\t# =============================== DO NOT EDIT BELOW THIS LINE ============================== #\n\tdata_dictionary = Dict{AbstractString,Any}()\n\tdata_dictionary[\"initial_condition_array\"] = initial_condition_array\n\tdata_dictionary[\"average_transcript_length\"] = average_transcript_length\n\tdata_dictionary[\"average_protein_length\"] = average_protein_length\n\tdata_dictionary[\"gene_coding_length_array\"] = gene_coding_length_array\n\tdata_dictionary[\"mRNA_coding_length_array\"] = mRNA_coding_length_array\n\tdata_dictionary[\"protein_coding_length_array\"] = protein_coding_length_array\n\tdata_dictionary[\"rnapII_concentration\"] = rnapII_concentration # muM\n\tdata_dictionary[\"ribosome_concentration\"] = ribosome_concentration # muM\n\tdata_dictionary[\"degradation_constant_mRNA\"] = degradation_constant_mRNA # hr^-1\n\tdata_dictionary[\"degradation_constant_protein\"] = degradation_constant_protein # hr^-1\n\tdata_dictionary[\"kcat_transcription\"] = kcat_transcription # hr^-1\n\tdata_dictionary[\"kcat_translation\"] = kcat_translation # hr^-1\n\tdata_dictionary[\"maximum_specific_growth_rate\"] = maximum_specific_growth_rate # hr^-1\n\tdata_dictionary[\"death_rate_constant\"] = death_rate_constant\n\tdata_dictionary[\"avg_gene_concentration\"] = avg_gene_concentration\n\tdata_dictionary[\"saturation_constant_transcription\"] = saturation_transcription\n\tdata_dictionary[\"saturation_constant_translation\"] = saturation_translation\n\n\tdata_dictionary[\"stoichiometric_matrix\"] = stoichiometric_matrix\n\tdata_dictionary[\"dilution_matrix\"] = dilution_matrix\n\tdata_dictionary[\"degradation_matrix\"] = degradation_matrix\n\n\tdata_dictionary[\"binding_parameter_dictionary\"] = binding_parameter_dictionary\n\tdata_dictionary[\"control_parameter_dictionary\"] = control_parameter_dictionary\n\tdata_dictionary[\"parameter_name_mapping_array\"] = parameter_name_mapping_array\n\n\t# Added by JV -\n\tdata_dictionary[\"background_copy_number_dictionary\"] = background_copy_number_dictionary;\n\tdata_dictionary[\"cell_volume\"] = V;\n\tdata_dictionary[\"av_number\"] = av_number;\n\tdata_dictionary[\"number_of_binding\"] = 90;\n\n\t# =============================== DO NOT EDIT ABOVE THIS LINE ============================== #\n\treturn data_dictionary\nend\n", "meta": {"hexsha": "b26673a2fa3ab6568f1531d43d04f2b47a17e7c3", "size": 30561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DataDictionary.jl", "max_stars_repo_name": "varnerlab/HL60_TF_model_JuPOETs", "max_stars_repo_head_hexsha": "631944aa4cb1a4a5bb98913989c553975e9d5407", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DataDictionary.jl", "max_issues_repo_name": "varnerlab/HL60_TF_model_JuPOETs", "max_issues_repo_head_hexsha": "631944aa4cb1a4a5bb98913989c553975e9d5407", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataDictionary.jl", "max_forks_repo_name": "varnerlab/HL60_TF_model_JuPOETs", "max_forks_repo_head_hexsha": "631944aa4cb1a4a5bb98913989c553975e9d5407", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1275590551, "max_line_length": 167, "alphanum_fraction": 0.7454598999, "num_tokens": 11435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.19704264711718658}} {"text": "function simulate(pomcp::POMCPOWPlanner, h_node::POWTreeObsNode{B,A,O}, s::S, d) where {B,S,A,O}\n\n tree = h_node.tree\n h = h_node.node\n\n sol = pomcp.solver\n\n if POMDPs.isterminal(pomcp.problem, s) || d <= 0\n return (0.0,1)\n end\n\n if sol.enable_action_pw\n total_n = tree.total_n[h]\n if length(tree.tried[h]) <= sol.k_action*total_n^sol.alpha_action\n if h == 1\n a = next_action(pomcp.next_action, pomcp.problem, tree.root_belief, POWTreeObsNode(tree, h))\n else\n a = next_action(pomcp.next_action, pomcp.problem, StateBelief(tree.sr_beliefs[h]), POWTreeObsNode(tree, h))\n end\n if !sol.check_repeat_act || !haskey(tree.o_child_lookup, (h,a))\n push_anode!(tree, h, a,\n init_N(pomcp.init_N, pomcp.problem, POWTreeObsNode(tree, h), a),\n init_V(pomcp.init_V, pomcp.problem, POWTreeObsNode(tree, h), a),\n sol.check_repeat_act)\n end\n end\n else # run through all the actions\n if isempty(tree.tried[h])\n if h == 1\n action_space_iter = POMDPs.actions(pomcp.problem, tree.root_belief)\n else\n action_space_iter = POMDPs.actions(pomcp.problem, StateBelief(tree.sr_beliefs[h]))\n end\n anode = length(tree.n)\n for a in action_space_iter\n push_anode!(tree, h, a,\n init_N(pomcp.init_N, pomcp.problem, POWTreeObsNode(tree, h), a),\n init_V(pomcp.init_V, pomcp.problem, POWTreeObsNode(tree, h), a),\n false)\n end\n end\n end\n total_n = tree.total_n[h]\n\n best_node = select_best(pomcp.criterion, h_node, pomcp.solver.rng)\n a = tree.a_labels[best_node]\n\n new_node = false\n total_counts=0\n total_reward=0.0\n flag_csyes=false\n if tree.n_a_children[best_node] <= sol.k_observation*(tree.n[best_node]^sol.alpha_observation)\n\n sp, o, r = @gen(:sp, :o, :r)(pomcp.problem, s, a, sol.rng)\n\n if sol.check_repeat_obs && haskey(tree.a_child_lookup, (best_node,o))\n hao = tree.a_child_lookup[(best_node, o)]\n else\n new_node = true\n hao = length(tree.sr_beliefs) + 1\n push!(tree.sr_beliefs,\n init_node_sr_belief(pomcp.node_sr_belief_updater,\n pomcp.problem, s, a, sp, o, r))\n \"\"\"\n TODO: init_node是当o为新节点时,在创建新节点的同时把s'和w(s')加入到o中。\n 因此在这我们需要进行补偿性采样,把s'和weight加入到其他的所有o中,然后在其他o中也进行补偿性采样。\n \"\"\"\n \"\"\"\n Step 1:把s'和weight加入到其他的所有o中.\n \"\"\" \n \"\"\"\n Step 2:从任意一个其他o中,取出所有的(s',r)对中的s',计算w,加入到现在的o的belief中\n \"\"\"\n if(length(tree.generated_ltc[best_node])!=0)#如果存在其他o,执行step1.2d<85 && \n first_pair=first(tree.generated_ltc[best_node])\n first_pair_hao=first_pair.second\n if(length(tree.sr_beliefs[first_pair_hao].dist.items)<100) #step1\n for pair in tree.generated_ltc[best_node]\n o_temp=pair.first\n hao_temp=pair.second\n push_weighted!(tree.sr_beliefs[hao_temp], pomcp.node_sr_belief_updater, s, sp, r)\n end\n end\n # step2\n for i in 1:length(tree.sr_beliefs[first_pair_hao].dist.items)#step2\n if(i>100)\n break\n end\n sp_temp=tree.sr_beliefs[first_pair_hao].dist.items[i][1]\n r_temp=tree.sr_beliefs[first_pair_hao].dist.items[i][2]\n push_weighted!(tree.sr_beliefs[hao], pomcp.node_sr_belief_updater, s, sp_temp, r_temp)\n end\n end\n \n \n \n push!(tree.total_n, 0)\n push!(tree.tried, Int[])\n push!(tree.o_labels, o)\n\n if sol.check_repeat_obs\n tree.a_child_lookup[(best_node, o)] = hao\n end\n tree.n_a_children[best_node] += 1\n push!(tree.generated_ltc[best_node], o=>hao)\n end\n push!(tree.generated[best_node], o=>hao)\n \"\"\"\n Step3:\n 对其他每个o进行补偿性采样,\n \"\"\"\n # if d<90\n # if new_node\n # for j in 1:(length(tree.generated_ltc[best_node])-1)\n # pair=tree.generated_ltc[best_node][j]\n # o_temp=pair.first\n # hao_temp=pair.second\n # before_weight=tree.sr_beliefs[hao_temp].dist.cdf[end-1]\n # before_sample_times=tree.total_n[hao_temp]\n # new_added_weight=tree.sr_beliefs[hao_temp].dist.cdf[end]-before_weight\n # cs_times=div(before_sample_times*new_added_weight,before_weight)#下取整\n # if (cs_times!=0)\n # for i in 1:cs_times\n # R_temp,counts_temp=simulate_ow(pomcp, POWTreeObsNode(tree, hao_temp), sp, d-1)\n # R = r + POMDPs.discount(pomcp.problem)*R_temp\n # total_counts+=counts_temp\n # total_reward+=R*counts_temp\n # end\n # end\n # end \n # end\n # end\n else\n\n sp, r = @gen(:sp, :r)(pomcp.problem, s, a, sol.rng)\n\n end\n\n if r == Inf\n @warn(\"POMCPOW: +Inf reward. This is not recommended and may cause future errors.\")\n end\n\n if new_node\n R = r + POMDPs.discount(pomcp.problem)*estimate_value(pomcp.solved_estimate, pomcp.problem, sp, POWTreeObsNode(tree, hao), d-1)\n total_counts+=1\n total_reward+=R\n \"\"\"\n total_counts++\n total_reward+=R\n \"\"\"\n else\n pair = rand(sol.rng, tree.generated[best_node])\n o = pair.first\n hao = pair.second\n \"\"\"\n To-do: 当o不是新节点时,需要把这轮从G中得到的s',加入到当前a下的所有o分支的B(hao)中,同时根据每个分支的o计算相应的权重\n 然后在每个O分支下,对新粒子进行补偿性采样。\n \"\"\"\n \"\"\"\n Step 1:把s'和weight加入到所有o中,包括自己.\n \"\"\"\n if(length(tree.sr_beliefs[hao].dist.items)<100) #限制粒子数为1000\n for pair in tree.generated_ltc[best_node]\n o_temp=pair.first\n hao_temp=pair.second \n push_weighted!(tree.sr_beliefs[hao_temp], pomcp.node_sr_belief_updater, s, sp, r)\n end\n \"\"\"\n Step2:补偿性采样\n \"\"\"\n # for pair in tree.generated_ltc[best_node]\n # o_temp=pair.first\n # hao_temp=pair.second\n # before_weight=tree.sr_beliefs[hao_temp].dist.cdf[end-1]\n # before_sample_times=tree.total_n[hao_temp]\n # new_added_weight=tree.sr_beliefs[hao_temp].dist.cdf[end]-tree.sr_beliefs[hao_temp].dist.cdf[end-1]\n # cs_times=div(before_sample_times*new_added_weight,before_weight)#下取整\n # if (cs_times!=0)\n # for i in 1:cs_times\n # R_temp,counts_temp=simulate(pomcp, POWTreeObsNode(tree, hao_temp), sp, d-1) \n # R = r + POMDPs.discount(pomcp.problem)*R_temp\n # total_reward+=R*counts_temp\n # total_counts+=counts_temp\n # end\n # end\n # end\n else\n push_weighted!(tree.sr_beliefs[hao], pomcp.node_sr_belief_updater, s, sp, r)#默认把一个粒子加入到当前o\n end\n # push_weighted!(tree.sr_beliefs[hao], pomcp.node_sr_belief_updater, s, sp, r)#默认把一个粒子加入到当前o\n temp_lenght=length(tree.sr_beliefs[hao].dist.items)\n nums_v=length(tree.total_n[hao])\n if(d<90&&nums_v>1&&nums_v<10)#temp_lenght<10) #d<30\n before_weight=tree.sr_beliefs[hao].dist.cdf[temp_lenght-1]\n before_sample_times=tree.total_n[hao]\n new_added_weight=tree.sr_beliefs[hao].dist.cdf[temp_lenght]-before_weight\n cs_times=div(before_sample_times*new_added_weight,before_weight)#下取整\n if (cs_times!=0)\n flag_csyes=true\n if(cs_times>3)\n cs_times=2\n end\n for i in 1:cs_times\n # sp, r = rand(sol.rng, tree.sr_beliefs[hao])\n R_temp,counts_temp=simulate(pomcp, POWTreeObsNode(tree, hao), sp, d-1)\n R = r + POMDPs.discount(pomcp.problem)*R_temp\n total_counts+=counts_temp\n total_reward+=R*counts_temp\n end\n end\n end\n \n \"\"\"\n Step3:随机采样\n \n \"\"\"\n sp, r = rand(sol.rng, tree.sr_beliefs[hao])\n if(flag_csyes)\n R_temp,counts_temp=simulate(pomcp, POWTreeObsNode(tree, hao), sp, d-1)\n else\n R_temp,counts_temp=simulate(pomcp, POWTreeObsNode(tree, hao), sp, d-1)\n end\n\n R = r + POMDPs.discount(pomcp.problem)*R_temp\n total_counts+=counts_temp\n total_reward+=R*counts_temp\n # sp, r = rand(sol.rng, tree.sr_beliefs[hao])\n # R = r + POMDPs.discount(pomcp.problem)*simulate(pomcp, POWTreeObsNode(tree, hao), sp, d-1)\n end\n\n \"\"\"\n 返回Reward和次数\n \"\"\"\n tree.n[best_node] += total_counts\n tree.total_n[h] += total_counts\n if tree.v[best_node] != -Inf\n tree.v[best_node] = ((tree.n[best_node]-total_counts)*tree.v[best_node]+total_reward)/tree.n[best_node]\n end\n \n return (total_reward/total_counts,total_counts)\n\n # tree.n[best_node] += 1\n # tree.total_n[h] += 1\n # if tree.v[best_node] != -Inf\n # tree.v[best_node] += (R-tree.v[best_node])/tree.n[best_node]\n # end \n # return R\nend\n\n\nfunction simulate_ow(pomcp::POMCPOWPlanner, h_node::POWTreeObsNode{B,A,O}, s::S, d) where {B,S,A,O}\n\n tree = h_node.tree\n h = h_node.node\n\n sol = pomcp.solver\n\n if POMDPs.isterminal(pomcp.problem, s) || d <= 0\n return (0.0,1)\n end\n\n if sol.enable_action_pw\n total_n = tree.total_n[h]\n if length(tree.tried[h]) <= sol.k_action*total_n^sol.alpha_action\n if h == 1\n a = next_action(pomcp.next_action, pomcp.problem, tree.root_belief, POWTreeObsNode(tree, h))\n else\n a = next_action(pomcp.next_action, pomcp.problem, StateBelief(tree.sr_beliefs[h]), POWTreeObsNode(tree, h))\n end\n if !sol.check_repeat_act || !haskey(tree.o_child_lookup, (h,a))\n push_anode!(tree, h, a,\n init_N(pomcp.init_N, pomcp.problem, POWTreeObsNode(tree, h), a),\n init_V(pomcp.init_V, pomcp.problem, POWTreeObsNode(tree, h), a),\n sol.check_repeat_act)\n end\n end\n else # run through all the actions\n if isempty(tree.tried[h])\n if h == 1\n action_space_iter = POMDPs.actions(pomcp.problem, tree.root_belief)\n else\n action_space_iter = POMDPs.actions(pomcp.problem, StateBelief(tree.sr_beliefs[h]))\n end\n anode = length(tree.n)\n for a in action_space_iter\n push_anode!(tree, h, a,\n init_N(pomcp.init_N, pomcp.problem, POWTreeObsNode(tree, h), a),\n init_V(pomcp.init_V, pomcp.problem, POWTreeObsNode(tree, h), a),\n false)\n end\n end\n end\n total_n = tree.total_n[h]\n\n best_node = select_best(pomcp.criterion, h_node, pomcp.solver.rng)\n a = tree.a_labels[best_node]\n\n new_node = false\n total_counts=0\n total_reward=0.0\n if tree.n_a_children[best_node] <= sol.k_observation*(tree.n[best_node]^sol.alpha_observation)\n\n sp, o, r = @gen(:sp, :o, :r)(pomcp.problem, s, a, sol.rng)\n\n if sol.check_repeat_obs && haskey(tree.a_child_lookup, (best_node,o))\n hao = tree.a_child_lookup[(best_node, o)]\n else\n new_node = true\n hao = length(tree.sr_beliefs) + 1\n push!(tree.sr_beliefs,\n init_node_sr_belief(pomcp.node_sr_belief_updater,\n pomcp.problem, s, a, sp, o, r))\n \n \n push!(tree.total_n, 0)\n push!(tree.tried, Int[])\n push!(tree.o_labels, o)\n\n if sol.check_repeat_obs\n tree.a_child_lookup[(best_node, o)] = hao\n end\n tree.n_a_children[best_node] += 1\n \n end\n push!(tree.generated[best_node], o=>hao)\n \n else\n\n sp, r = @gen(:sp, :r)(pomcp.problem, s, a, sol.rng)\n\n end\n\n if r == Inf\n @warn(\"POMCPOW: +Inf reward. This is not recommended and may cause future errors.\")\n end\n\n if new_node\n R = r + POMDPs.discount(pomcp.problem)*estimate_value(pomcp.solved_estimate, pomcp.problem, sp, POWTreeObsNode(tree, hao), d-1)\n total_counts+=1\n total_reward+=R\n \"\"\"\n total_counts++\n total_reward+=R\n \"\"\"\n else\n pair = rand(sol.rng, tree.generated[best_node])\n o = pair.first\n hao = pair.second\n \n push_weighted!(tree.sr_beliefs[hao], pomcp.node_sr_belief_updater, s, sp, r)#默认把一个粒子加入到当前o\n \n \"\"\"\n Step3:随机采样\n \n \"\"\"\n sp, r = rand(sol.rng, tree.sr_beliefs[hao])\n \n R_temp,counts_temp=simulate_ow(pomcp, POWTreeObsNode(tree, hao), sp, d-1)\n \n R = r + POMDPs.discount(pomcp.problem)*R_temp\n total_counts+=counts_temp\n total_reward+=R*counts_temp\n # sp, r = rand(sol.rng, tree.sr_beliefs[hao])\n # R = r + POMDPs.discount(pomcp.problem)*simulate(pomcp, POWTreeObsNode(tree, hao), sp, d-1)\n end\n\n \"\"\"\n 返回Reward和次数\n \"\"\"\n tree.n[best_node] += total_counts\n tree.total_n[h] += total_counts\n if tree.v[best_node] != -Inf\n tree.v[best_node] = ((tree.n[best_node]-total_counts)*tree.v[best_node]+total_reward)/tree.n[best_node]\n end\n \n return (total_reward/total_counts,total_counts)\n\n # tree.n[best_node] += 1\n # tree.total_n[h] += 1\n # if tree.v[best_node] != -Inf\n # tree.v[best_node] += (R-tree.v[best_node])/tree.n[best_node]\n # end \n # return R\nend\n\n", "meta": {"hexsha": "28af0d9a46b0f00555ed123785a908413ad35c5f", "size": 14525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solver2.jl", "max_stars_repo_name": "Lttcc/CSPOMCPOW", "max_stars_repo_head_hexsha": "aee31223a4d06f19d725dc3c397bc3d0a3f9d8a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solver2.jl", "max_issues_repo_name": "Lttcc/CSPOMCPOW", "max_issues_repo_head_hexsha": "aee31223a4d06f19d725dc3c397bc3d0a3f9d8a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver2.jl", "max_forks_repo_name": "Lttcc/CSPOMCPOW", "max_forks_repo_head_hexsha": "aee31223a4d06f19d725dc3c397bc3d0a3f9d8a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6295336788, "max_line_length": 135, "alphanum_fraction": 0.5423063683, "num_tokens": 4109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.1970259149242679}} {"text": "function DiffEqBase.__solve(prob::Union{DiffEqBase.AbstractODEProblem,DiffEqBase.AbstractDAEProblem},\n alg::Union{OrdinaryDiffEqAlgorithm,DAEAlgorithm}, args...;\n kwargs...)\n integrator = DiffEqBase.__init(prob, alg, args...; kwargs...)\n solve!(integrator)\n integrator.sol\nend\n\nfunction DiffEqBase.__init(prob::Union{DiffEqBase.AbstractODEProblem,DiffEqBase.AbstractDAEProblem},\n alg::Union{OrdinaryDiffEqAlgorithm,DAEAlgorithm},\n timeseries_init = (),\n ts_init = (),\n ks_init = (),\n recompile::Type{Val{recompile_flag}} = Val{true};\n saveat = (),\n tstops = (),\n d_discontinuities = (),\n save_idxs = nothing,\n save_everystep = isempty(saveat),\n save_on = true,\n save_start = save_everystep || isempty(saveat) || saveat isa Number || prob.tspan[1] in saveat,\n save_end = nothing,\n callback = nothing,\n dense = save_everystep && !(typeof(alg) <: Union{DAEAlgorithm,FunctionMap}) && isempty(saveat),\n calck = (callback !== nothing && callback != CallbackSet()) || (dense), # and no dense output\n dt = alg isa FunctionMap && isempty(tstops) ? eltype(prob.tspan)(1) : eltype(prob.tspan)(0),\n dtmin = nothing,\n dtmax = eltype(prob.tspan)((prob.tspan[end]-prob.tspan[1])),\n force_dtmin = false,\n adaptive = isadaptive(alg),\n gamma = gamma_default(alg),\n abstol = nothing,\n reltol = nothing,\n qmin = qmin_default(alg),\n qmax = qmax_default(alg),\n qsteady_min = qsteady_min_default(alg),\n qsteady_max = qsteady_max_default(alg),\n qoldinit = isadaptive(alg) ? 1//10^4 : 0,\n fullnormalize = true,\n failfactor = 2,\n beta1 = nothing,\n beta2 = nothing,\n maxiters = adaptive ? 1000000 : typemax(Int),\n internalnorm = ODE_DEFAULT_NORM,\n internalopnorm = LinearAlgebra.opnorm,\n isoutofdomain = ODE_DEFAULT_ISOUTOFDOMAIN,\n unstable_check = ODE_DEFAULT_UNSTABLE_CHECK,\n verbose = true,\n timeseries_errors = true,\n dense_errors = false,\n advance_to_tstop = false,\n stop_at_next_tstop = false,\n initialize_save = true,\n progress = false,\n progress_steps = 1000,\n progress_name = \"ODE\",\n progress_message = ODE_DEFAULT_PROG_MESSAGE,\n userdata = nothing,\n allow_extrapolation = alg_extrapolates(alg),\n initialize_integrator = true,\n alias_u0 = false,\n alias_du0 = false,\n initializealg = DefaultInit(),\n kwargs...) where recompile_flag\n\n if prob isa DiffEqBase.AbstractDAEProblem && alg isa OrdinaryDiffEqAlgorithm\n error(\"You cannot use an ODE Algorithm with a DAEProblem\")\n end\n\n if prob isa DiffEqBase.AbstractODEProblem && alg isa DAEAlgorithm\n error(\"You cannot use an DAE Algorithm with a ODEProblem\")\n end\n\n if typeof(prob.f)<:DynamicalODEFunction && typeof(prob.f.mass_matrix)<:Tuple\n if any(mm != I for mm in prob.f.mass_matrix)\n error(\"This solver is not able to use mass matrices.\")\n end\n elseif !(typeof(prob)<:DiscreteProblem) &&\n !(typeof(prob)<:DiffEqBase.AbstractDAEProblem) &&\n !is_mass_matrix_alg(alg) &&\n prob.f.mass_matrix != I\n error(\"This solver is not able to use mass matrices.\")\n end\n\n if !isempty(saveat) && dense\n @warn(\"Dense output is incompatible with saveat. Please use the SavingCallback from the Callback Library to mix the two behaviors.\")\n end\n\n progress && @logmsg(LogLevel(-1),progress_name,_id=_id = :OrdinaryDiffEq,progress=0)\n\n tType = eltype(prob.tspan)\n tspan = prob.tspan\n tdir = sign(tspan[end]-tspan[1])\n\n t = tspan[1]\n\n if (((!(typeof(alg) <: OrdinaryDiffEqAdaptiveAlgorithm) && !(typeof(alg) <: OrdinaryDiffEqCompositeAlgorithm) && !(typeof(alg) <: DAEAlgorithm)) || !adaptive) && dt == tType(0) && isempty(tstops)) && !(typeof(alg) <: Union{FunctionMap,LinearExponential})\n error(\"Fixed timestep methods require a choice of dt or choosing the tstops\")\n end\n\n isdae = alg isa DAEAlgorithm || (!(typeof(prob)<:DiscreteProblem) &&\n prob.f.mass_matrix != I &&\n !(typeof(prob.f.mass_matrix)<:Tuple) &&\n ArrayInterface.issingular(prob.f.mass_matrix))\n if alg isa CompositeAlgorithm && alg.choice_function isa AutoSwitch\n auto = alg.choice_function\n _alg = CompositeAlgorithm(alg.algs,\n AutoSwitchCache(\n 0,0,\n auto.nonstiffalg,\n auto.stiffalg,\n auto.stiffalgfirst,\n auto.maxstiffstep,\n auto.maxnonstiffstep,\n auto.nonstifftol,\n auto.stifftol,\n auto.dtfac,\n auto.stiffalgfirst,\n auto.switch_max\n ))\n else\n _alg = alg\n end\n f = prob.f\n p = prob.p\n\n # Get the control variables\n\n if alias_u0\n u = prob.u0\n else\n u = recursivecopy(prob.u0)\n end\n\n if _alg isa DAEAlgorithm\n if alias_du0\n du = prob.du0\n else\n du = recursivecopy(prob.u0)\n end\n duprev = recursivecopy(du)\n else\n du = nothing\n duprev = nothing\n end\n\n uType = typeof(u)\n uBottomEltype = recursive_bottom_eltype(u)\n uBottomEltypeNoUnits = recursive_unitless_bottom_eltype(u)\n\n uEltypeNoUnits = recursive_unitless_eltype(u)\n tTypeNoUnits = typeof(one(tType))\n\n if typeof(_alg) <: FunctionMap\n abstol_internal = false\n elseif abstol === nothing\n if uBottomEltypeNoUnits == uBottomEltype\n abstol_internal = real(convert(uBottomEltype,oneunit(uBottomEltype)*1//10^6))\n else\n abstol_internal = real.(oneunit.(u).*1//10^6)\n end\n else\n abstol_internal = real.(abstol)\n end\n\n if typeof(_alg) <: FunctionMap\n reltol_internal = false\n elseif reltol === nothing\n if uBottomEltypeNoUnits == uBottomEltype\n reltol_internal = real(convert(uBottomEltype,oneunit(uBottomEltype)*1//10^3))\n else\n reltol_internal = real.(oneunit.(u).*1//10^3)\n end\n else\n reltol_internal = real.(reltol)\n end\n\n dtmax > zero(dtmax) && tdir < 0 && (dtmax *= tdir) # Allow positive dtmax, but auto-convert\n # dtmin is all abs => does not care about sign already.\n\n if !isdae && isinplace(prob) && typeof(u) <: AbstractArray && eltype(u) <: Number && uBottomEltypeNoUnits == uBottomEltype && tType == tTypeNoUnits # Could this be more efficient for other arrays?\n rate_prototype = recursivecopy(u)\n elseif prob isa DAEProblem\n rate_prototype = prob.du0\n else\n if (uBottomEltypeNoUnits == uBottomEltype && tType == tTypeNoUnits) || eltype(u) <: Enum\n rate_prototype = u\n else # has units!\n rate_prototype = u/oneunit(tType)\n end\n end\n rateType = typeof(rate_prototype) ## Can be different if united\n\n if isdae\n if uBottomEltype == uBottomEltypeNoUnits\n res_prototype = u\n else\n res_prototype = one(u)\n end\n resType = typeof(res_prototype)\n end\n\n tstops_internal = initialize_tstops(tType, tstops, d_discontinuities, tspan)\n saveat_internal = initialize_saveat(tType, saveat, tspan)\n d_discontinuities_internal = initialize_d_discontinuities(tType, d_discontinuities, tspan)\n\n callbacks_internal = CallbackSet(callback)\n\n max_len_cb = DiffEqBase.max_vector_callback_length(callbacks_internal)\n if max_len_cb isa VectorContinuousCallback\n uBottomEltypeReal = real(uBottomEltype)\n if isinplace(prob)\n callback_cache = DiffEqBase.CallbackCache(u,max_len_cb.len,uBottomEltypeReal,uBottomEltypeReal)\n else\n callback_cache = DiffEqBase.CallbackCache(max_len_cb.len,uBottomEltypeReal,uBottomEltypeReal)\n end\n else\n callback_cache = nothing\n end\n\n ### Algorithm-specific defaults ###\n if save_idxs === nothing\n ksEltype = Vector{rateType}\n else\n ks_prototype = rate_prototype[save_idxs]\n ksEltype = Vector{typeof(ks_prototype)}\n end\n\n # Have to convert incase passed in wrong.\n if save_idxs === nothing\n timeseries = timeseries_init === () ? uType[] : convert(Vector{uType},timeseries_init)\n else\n u_initial = u[save_idxs]\n timeseries = timeseries_init === () ? typeof(u_initial)[] :\n convert(Vector{uType},timeseries_init)\n end\n\n ts = ts_init === () ? tType[] : convert(Vector{tType},ts_init)\n ks = ks_init === () ? ksEltype[] : convert(Vector{ksEltype},ks_init)\n alg_choice = typeof(_alg) <: CompositeAlgorithm ? Int[] : ()\n\n if !adaptive && save_everystep && tspan[2]-tspan[1] != Inf\n if dt == 0\n steps = length(tstops)\n else\n dtmin === nothing && (dtmin = DiffEqBase.prob2dtmin(prob; use_end_time=true))\n abs(dt) < dtmin && throw(ArgumentError(\"Supplied dt is smaller than dtmin\"))\n steps = ceil(Int,internalnorm((tspan[2]-tspan[1])/dt,tspan[1]))\n end\n sizehint!(timeseries,steps+1)\n sizehint!(ts,steps+1)\n sizehint!(ks,steps+1)\n elseif save_everystep\n sizehint!(timeseries,50)\n sizehint!(ts,50)\n sizehint!(ks,50)\n elseif !isempty(saveat_internal)\n sizehint!(timeseries,length(saveat_internal)+1)\n sizehint!(ts,length(saveat_internal)+1)\n sizehint!(ks,length(saveat_internal)+1)\n else\n sizehint!(timeseries,2)\n sizehint!(ts,2)\n sizehint!(ks,2)\n end\n\n QT = if tTypeNoUnits <: Integer\n typeof(qmin)\n elseif prob isa DiscreteProblem\n # The QT fields are not used for DiscreteProblems\n constvalue(tTypeNoUnits)\n else\n typeof(internalnorm(u, t))\n end\n\n k = rateType[]\n\n if uses_uprev(_alg, adaptive) || calck\n uprev = recursivecopy(u)\n else\n # Some algorithms do not use `uprev` explicitly. In that case, we can save\n # some memory by aliasing `uprev = u`, e.g. for \"2N\" low storage methods.\n uprev = u\n end\n if allow_extrapolation\n uprev2 = recursivecopy(u)\n else\n uprev2 = uprev\n end\n\n if prob isa DAEProblem\n cache = alg_cache(_alg,du,u,res_prototype,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol_internal,p,calck,Val(isinplace(prob)))\n else\n cache = alg_cache(_alg,u,rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,uprev2,f,t,dt,reltol_internal,p,calck,Val(isinplace(prob)))\n end\n\n if typeof(_alg) <: OrdinaryDiffEqCompositeAlgorithm\n id = CompositeInterpolationData(f,timeseries,ts,ks,alg_choice,dense,cache)\n beta2 === nothing && ( beta2=_composite_beta2_default(_alg.algs, cache.current, QT) )\n beta1 === nothing && ( beta1=_composite_beta1_default(_alg.algs, cache.current, QT, beta2) )\n else\n id = InterpolationData(f,timeseries,ts,ks,dense,cache)\n beta2 === nothing && ( beta2=beta2_default(_alg) )\n beta1 === nothing && ( beta1=beta1_default(_alg,beta2) )\n end\n\n dtmin === nothing && (dtmin = DiffEqBase.prob2dtmin(prob; use_end_time=false))\n\n save_end_user = save_end\n save_end = save_end === nothing ? save_everystep || isempty(saveat) || saveat isa Number || prob.tspan[2] in saveat : save_end\n\n opts = DEOptions{typeof(abstol_internal),typeof(reltol_internal),QT,tType,\n typeof(internalnorm),typeof(internalopnorm),typeof(save_end_user),\n typeof(callbacks_internal),\n typeof(isoutofdomain),\n typeof(progress_message),typeof(unstable_check),typeof(tstops_internal),\n typeof(d_discontinuities_internal),typeof(userdata),typeof(save_idxs),\n typeof(maxiters),typeof(tstops),typeof(saveat),\n typeof(d_discontinuities)}(\n maxiters,save_everystep,adaptive,abstol_internal,\n reltol_internal,QT(gamma),QT(qmax),\n QT(qmin),QT(qsteady_max),\n QT(qsteady_min),QT(failfactor),tType(dtmax),\n tType(dtmin),internalnorm,internalopnorm,save_idxs,tstops_internal,saveat_internal,\n d_discontinuities_internal,\n tstops,saveat,d_discontinuities,\n userdata,progress,progress_steps,\n progress_name,progress_message,timeseries_errors,dense_errors,\n QT(beta1),QT(beta2),QT(qoldinit),dense,\n save_on,save_start,save_end,save_end_user,\n callbacks_internal,isoutofdomain,\n unstable_check,verbose,\n calck,force_dtmin,advance_to_tstop,stop_at_next_tstop)\n\n destats = DiffEqBase.DEStats(0)\n\n if typeof(_alg) <: OrdinaryDiffEqCompositeAlgorithm\n sol = DiffEqBase.build_solution(prob,_alg,ts,timeseries,\n dense=dense,k=ks,interp=id,\n alg_choice=alg_choice,\n calculate_error = false, destats=destats)\n else\n sol = DiffEqBase.build_solution(prob,_alg,ts,timeseries,\n dense=dense,k=ks,interp=id,\n calculate_error = false, destats=destats)\n end\n\n if recompile_flag == true\n FType = typeof(f)\n SolType = typeof(sol)\n cacheType = typeof(cache)\n else\n FType = Function\n if _alg isa OrdinaryDiffEqAlgorithm\n SolType = DiffEqBase.AbstractODESolution\n cacheType = OrdinaryDiffEqCache\n else\n SolType = DiffEqBase.AbstractDAESolution\n cacheType = DAECache\n end\n end\n\n # rate/state = (state/time)/state = 1/t units, internalnorm drops units\n # we don't want to differentiate through eigenvalue estimation\n eigen_est = inv(one(tType))\n tprev = t\n dtcache = tType(dt)\n dtpropose = tType(dt)\n iter = 0\n kshortsize = 0\n reeval_fsal = false\n u_modified = false\n EEst = QT(1)\n just_hit_tstop = false\n isout = false\n accept_step = false\n force_stepfail = false\n last_stepfail = false\n do_error_check = true\n event_last_time = 0\n vector_event_last_time = 1\n last_event_error = typeof(_alg) <: FunctionMap ? false : zero(uBottomEltypeNoUnits)\n dtchangeable = isdtchangeable(_alg)\n q11 = QT(1)\n success_iter = 0\n erracc = QT(1)\n dtacc = tType(1)\n reinitiailize = true\n saveiter = 0 # Starts at 0 so first save is at 1\n saveiter_dense = 0\n\n integrator = ODEIntegrator{typeof(_alg),isinplace(prob),uType,typeof(du),\n tType,typeof(p),\n typeof(eigen_est),\n QT,typeof(tdir),typeof(k),SolType,\n FType,cacheType,\n typeof(opts),fsal_typeof(_alg,rate_prototype),\n typeof(last_event_error),typeof(callback_cache),\n typeof(initializealg)}(\n sol,u,du,k,t,tType(dt),f,p,uprev,uprev2,duprev,tprev,\n _alg,dtcache,dtchangeable,\n dtpropose,tdir,eigen_est,EEst,QT(qoldinit),q11,\n erracc,dtacc,success_iter,\n iter,saveiter,saveiter_dense,cache,callback_cache,\n kshortsize,force_stepfail,last_stepfail,\n just_hit_tstop,do_error_check,\n event_last_time,vector_event_last_time,\n last_event_error,accept_step,\n isout,reeval_fsal,\n u_modified,reinitiailize,isdae,\n opts,destats,initializealg)\n if initialize_integrator\n if isdae\n DiffEqBase.initialize_dae!(integrator)\n end\n\n if save_start\n integrator.saveiter += 1 # Starts at 1 so first save is at 2\n integrator.saveiter_dense += 1\n copyat_or_push!(ts,1,t)\n if save_idxs === nothing\n copyat_or_push!(timeseries,1,integrator.u)\n copyat_or_push!(ks,1,[rate_prototype])\n else\n copyat_or_push!(timeseries,1,u_initial,Val{false})\n copyat_or_push!(ks,1,[ks_prototype])\n end\n else\n saveiter = 0 # Starts at 0 so first save is at 1\n saveiter_dense = 0\n end\n\n initialize_callbacks!(integrator, initialize_save)\n initialize!(integrator,integrator.cache)\n\n if typeof(_alg) <: OrdinaryDiffEqCompositeAlgorithm && save_start\n # Loop to get all of the extra possible saves in callback initialization\n for i in 1:integrator.saveiter\n copyat_or_push!(alg_choice,i,integrator.cache.current)\n end\n end\n end\n\n handle_dt!(integrator)\n\n integrator\nend\n\nfunction DiffEqBase.solve!(integrator::ODEIntegrator)\n @inbounds while !isempty(integrator.opts.tstops)\n while integrator.tdir * integrator.t < first(integrator.opts.tstops)\n loopheader!(integrator)\n if integrator.do_error_check && check_error!(integrator) != :Success\n return integrator.sol\n end\n perform_step!(integrator,integrator.cache)\n loopfooter!(integrator)\n if isempty(integrator.opts.tstops)\n break\n end\n end\n handle_tstop!(integrator)\n end\n postamble!(integrator)\n\n f = integrator.sol.prob.f\n\n if DiffEqBase.has_analytic(f)\n DiffEqBase.calculate_solution_errors!(integrator.sol;timeseries_errors=integrator.opts.timeseries_errors,dense_errors=integrator.opts.dense_errors)\n end\n if integrator.sol.retcode != :Default\n return integrator.sol\n end\n integrator.sol = DiffEqBase.solution_new_retcode(integrator.sol,:Success)\nend\n\n# Helpers\n\n\nfunction handle_dt!(integrator)\n if iszero(integrator.dt) && integrator.opts.adaptive\n auto_dt_reset!(integrator)\n if sign(integrator.dt)!=integrator.tdir && !iszero(integrator.dt) && !isnan(integrator.dt)\n error(\"Automatic dt setting has the wrong sign. Exiting. Please report this error.\")\n end\n if isnan(integrator.dt)\n if integrator.opts.verbose\n @warn(\"Automatic dt set the starting dt as NaN, causing instability.\")\n end\n end\n elseif integrator.opts.adaptive && integrator.dt > zero(integrator.dt) && integrator.tdir < 0\n integrator.dt *= integrator.tdir # Allow positive dt, but auto-convert\n end\nend\n\n# time stops\nfunction initialize_tstops(::Type{T}, tstops, d_discontinuities, tspan) where T\n tstops_internal = BinaryMinHeap{T}()\n\n t0, tf = tspan\n tdir = sign(tf - t0)\n tdir_t0 = tdir * t0\n tdir_tf = tdir * tf\n\n if isempty(d_discontinuities) && isempty(tstops) # TODO: Specialize more\n push!(tstops_internal, tdir_tf)\n else\n for t in tstops\n tdir_t = tdir * t\n tdir_t0 < tdir_t ≤ tdir_tf && push!(tstops_internal, tdir_t)\n end\n\n for t in d_discontinuities\n tdir_t = tdir * t\n tdir_t0 < tdir_t ≤ tdir_tf && push!(tstops_internal, tdir_t)\n end\n\n push!(tstops_internal, tdir_tf)\n end\n\n return tstops_internal\nend\n\n# saving time points\nfunction initialize_saveat(::Type{T}, saveat, tspan) where T\n saveat_internal = BinaryMinHeap{T}()\n\n t0, tf = tspan\n tdir = sign(tf - t0)\n tdir_t0 = tdir * t0\n tdir_tf = tdir * tf\n\n if typeof(saveat) <: Number\n directional_saveat = tdir * abs(saveat)\n for t in (t0 + directional_saveat):directional_saveat:tf\n push!(saveat_internal, tdir * t)\n end\n elseif !isempty(saveat)\n for t in saveat\n tdir_t = tdir * t\n tdir_t0 < tdir_t ≤ tdir_tf && push!(saveat_internal, tdir_t)\n end\n end\n\n return saveat_internal\nend\n\n# discontinuities\nfunction initialize_d_discontinuities(::Type{T}, d_discontinuities, tspan) where T\n d_discontinuities_internal = BinaryMinHeap{T}()\n sizehint!(d_discontinuities_internal, length(d_discontinuities))\n\n t0, tf = tspan\n tdir = sign(tf - t0)\n\n for t in d_discontinuities\n push!(d_discontinuities_internal, tdir * t)\n end\n\n return d_discontinuities_internal\nend\n\nfunction initialize_callbacks!(integrator, initialize_save = true)\n t = integrator.t\n u = integrator.u\n callbacks = integrator.opts.callback\n integrator.u_modified = true\n\n u_modified = initialize!(callbacks,u,t,integrator)\n\n # if the user modifies u, we need to fix previous values before initializing\n # FSAL in order for the starting derivatives to be correct\n if u_modified\n\n if isinplace(integrator.sol.prob)\n recursivecopy!(integrator.uprev,integrator.u)\n else\n integrator.uprev = integrator.u\n end\n\n if alg_extrapolates(integrator.alg)\n if isinplace(integrator.sol.prob)\n recursivecopy!(integrator.uprev2,integrator.uprev)\n else\n integrator.uprev2 = integrator.uprev\n end\n end\n\n if initialize_save &&\n (any((c)->c.save_positions[2],callbacks.discrete_callbacks) ||\n any((c)->c.save_positions[2],callbacks.continuous_callbacks))\n savevalues!(integrator,true)\n end\n end\n\n # reset this as it is now handled so the integrators should proceed as normal\n integrator.u_modified = false\nend\n", "meta": {"hexsha": "118d80495526519d7161944ca441e441db03cc5b", "size": 22104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solve.jl", "max_stars_repo_name": "colinxs/OrdinaryDiffEq.jl", "max_stars_repo_head_hexsha": "162887db581bcbf42e6520996322c62006b52549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solve.jl", "max_issues_repo_name": "colinxs/OrdinaryDiffEq.jl", "max_issues_repo_head_hexsha": "162887db581bcbf42e6520996322c62006b52549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solve.jl", "max_forks_repo_name": "colinxs/OrdinaryDiffEq.jl", "max_forks_repo_head_hexsha": "162887db581bcbf42e6520996322c62006b52549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9015025042, "max_line_length": 256, "alphanum_fraction": 0.6138707926, "num_tokens": 5504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.1966591510379009}} {"text": "# binary.jl: Elementwise broadcasting binary functions for arrays and scalars.\n# uses binary_ops from broadcast.jl.\n\nimport Base.Broadcast: broadcasted\n\n# binary_op defines the broadcast_func of a Julia function for KnetArrays.\n# The corresponding kernel is defined in libknet8.\nfunction binary_op(f, j=f, o...)\n J=Symbol(j)\n M = which(@__MODULE__, J)\n for S in (32,64)\n T = Symbol(\"Float$S\")\n\n F01 = \"$(f)_$(S)_01\" # Scalar,Array->Array\n F11 = \"$(f)_$(S)_11\" # Array,Array->Array (same size) (not broadcast)\n F12 = \"$(f)_$(S)_12\" # Array,Array->Array (one have to be vector)\n F13_x_y = \"$(f)_$(S)_13_x_y\" # e.g. (A(x,y,z,w,t...), B(1,1,1,w,1...))\n F13_y_x = \"$(f)_$(S)_13_y_x\" # different versions for efficiency\n # F14_x_y = \"$(f)_$(S)_14_x_y\" # e.g. (M(x,y,z,w,t...), N(w,1,1,1...)\n # F14_y_x = \"$(f)_$(S)_14_y_x\" # different versions for efficiency\n # F15 reserved for another kernel, eliminated later and combined with F16\n F16_3 = \"$(f)_$(S)_16_3\" # multi-dimensional bcast unrolled up to 5 dims\n F16_4 = \"$(f)_$(S)_16_4\" # multi-dimensional bcast unrolled up to 5 dims\n F16_5 = \"$(f)_$(S)_16_5\" # multi-dimensional bcast unrolled up to 5 dims\n F17 = \"$(f)_$(S)_17\" # multi-dimensional bcast with loops\n\n @eval begin\n # Scalar,Array->Array\n function broadcasted(::typeof($J),x::$T,y::KnetArray{$T})\n z = similar(y)\n @knet8($F01,(Cint,$T,Ptr{$T},Ptr{$T}),length(z),x,y,z)\n return z\n end\n # Array,Array->Array\n function broadcasted(::typeof($J),x::KnetArray{$T},y::KnetArray{$T})\n if size(x)==size(y)\n z = similar(x)\n @knet8($F11,(Cint,Ptr{$T},Ptr{$T},Ptr{$T}),length(z),x,y,z)\n return z\n else\n bs = vbroadcast_shape(x,y)\n z = similar(x,bs[1])\n _broadcasted($J,x,y,z,bs)\n end\n end\n # Helpers\n function _broadcasted(::typeof($J),x::KnetArray{$T},y::KnetArray{$T},z::KnetArray{$T,1},bs)\n if length(x) == 1\n broadcasted($J,x[1],y)\n elseif length(y) == 1\n broadcasted($J,x,y[1])\n else # length(x) == length(y) was handled above\n throw(DimensionMismatch(\"$(map(size,(x,y,z)))\"))\n end\n end\n function _broadcasted(::typeof($J),x::KnetArray{$T},y::KnetArray{$T},z::KnetArray{$T,2},bs)\n # xlast or ylast will be broadcasting dimension\n (dz,sx,nx,sy,ny,xlast,ylast,xdims,ydims,multi) = bs\n if (nx == 1\n || ny == 1\n || ((xdims == 1 && (xlast==1 || 512 < sx )) ||\n (ydims == 1 && (ylast==1 || sy < 512 )))\n || (xdims==1 && nx<704)\n || (ydims==1 && (ny<704)))\n @knet8($F12,\n (Cint,Ptr{$T},Cint,Cint,Ptr{$T},Cint,Cint,Ptr{$T}),\n length(z),x,sx,nx,y,sy,ny,z)\n elseif xdims == 1\n dim_stride = strides(y)[xlast]\n next_stride = (xlast+1) > ndims(y) ?\n 0 : strides(y)[xlast+1]\n dim_size = prod(size(y)[xlast+1:end])\n @knet8($F13_y_x,\n (Ptr{$T},Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint),\n y,x,z,dim_stride,next_stride,dim_size,\n length(y),length(x))\n elseif ydims == 1\n dim_stride = strides(x)[ylast]\n next_stride = (ylast+1) > ndims(x) ?\n 0 : strides(x)[ylast+1]\n dim_size = prod(size(x)[ylast+1:end])\n @knet8($F13_x_y,\n (Ptr{$T},Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint),\n x,y,z,dim_stride,next_stride,dim_size,\n length(x), length(y))\n else\n throw(DimensionMismatch(\"$(map(size,(x,y,z)))\"))\n end\n return z\n end\n function _broadcasted(::typeof($J),x::KnetArray{$T},y::KnetArray{$T},z::KnetArray{$T,3},bs)\n sx,sy,sz = get_strides(x,y,z)\n @knet8($F16_3,\n (Ptr{$T},Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),\n x,y,z, sx[1],sx[2],sx[3], sy[1],sy[2],sy[3], sz[1],sz[2],sz[3], length(z))\n return z\n end\n function _broadcasted(::typeof($J),x::KnetArray{$T},y::KnetArray{$T},z::KnetArray{$T,4},bs)\n sx,sy,sz = get_strides(x,y,z)\n @knet8($F16_4,\n (Ptr{$T},Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),\n x,y,z, sx[1],sx[2],sx[3],sx[4], sy[1],sy[2],sy[3],sy[4], sz[1],sz[2],sz[3],sz[4], length(z))\n return z\n end\n function _broadcasted(::typeof($J),x::KnetArray{$T},y::KnetArray{$T},z::KnetArray{$T,5},bs)\n sx,sy,sz = get_strides(x,y,z)\n @knet8($F16_5,\n (Ptr{$T},Ptr{$T},Ptr{$T},Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint,Cint),\n x,y,z, sx[1],sx[2],sx[3],sx[4],sx[5], sy[1],sy[2],sy[3],sy[4],sy[5], sz[1],sz[2],sz[3],sz[4],sz[5], length(z))\n return z\n end\n function _broadcasted(::typeof($J),x::KnetArray{$T},y::KnetArray{$T},z::KnetArray{$T},bs)\n # ndims(z) <= 5 handled above, this is for > 5\n sx,sy,sz = map(s->convert(KnetArray, s), get_strides(x,y,z))\n @knet8($F17,\n (Ptr{$T},Ptr{$T},Ptr{$T},Ptr{Cint},Ptr{Cint},Ptr{Cint},Cint,Cint),\n x,y,z, sx, sy, sz, length(z), ndims(z))\n return z\n end\n\n # Bcasted methods\n ($M).$J(x::Bcasted{<:KnetArray{$T}}, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x.value, y.value) |> Bcasted\n ($M).$J(x::KnetArray{$T}, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x, y.value) |> Bcasted\n ($M).$J(x::Bcasted{<:KnetArray{$T}}, y::KnetArray{$T}) = broadcasted($J, x.value, y) |> Bcasted\n ($M).$J(x::Bcasted{$T}, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x.value, y.value) |> Bcasted\n ($M).$J(x::$T, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x, y.value) |> Bcasted\n ($M).$J(x::Bcasted{$T}, y::KnetArray{$T}) = broadcasted($J, x.value, y) |> Bcasted\n broadcasted(::typeof($J),x::Bcasted{<:KnetArray{$T}}, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x.value, y.value) |> Bcasted\n broadcasted(::typeof($J),x::KnetArray{$T}, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x, y.value) |> Bcasted\n broadcasted(::typeof($J),x::Bcasted{<:KnetArray{$T}}, y::KnetArray{$T}) = broadcasted($J, x.value, y) |> Bcasted\n broadcasted(::typeof($J),x::Bcasted{$T}, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x.value, y.value) |> Bcasted\n broadcasted(::typeof($J),x::$T, y::Bcasted{<:KnetArray{$T}}) = broadcasted($J, x, y.value) |> Bcasted\n broadcasted(::typeof($J),x::Bcasted{$T}, y::KnetArray{$T}) = broadcasted($J, x.value, y) |> Bcasted\n end # @eval\n end # for\n @eval begin # so we do not trigger some default Base implementation \n ($M).$J(x::Bcasted, y::Bcasted) = throw(MethodError($J,(x,y)))\n ($M).$J(x, y::Bcasted) = throw(MethodError($J,(x,y)))\n ($M).$J(x::Bcasted, y) = throw(MethodError($J,(x,y)))\n broadcasted(::typeof($J),x::Bcasted, y::Bcasted) = throw(MethodError(broadcasted, ($J, x, y)))\n broadcasted(::typeof($J),x, y::Bcasted) = throw(MethodError(broadcasted, ($J, x, y)))\n broadcasted(::typeof($J),x::Bcasted, y) = throw(MethodError(broadcasted, ($J, x, y)))\n end\nend # function binary_op\n\n# vbroadcast_shape computes index/offset arguments for a broadcasting kernel call.\nfunction vbroadcast_shape(x,y)\n nz = max(ndims(x),ndims(y))\n dz = ones(Int,nz)\n xdims = ydims = xsame = ysame = xlast = ylast = 0; zlen = 1;\n sx = sy = -1;\n nx = ny = -1;\n\n for i = 1:nz\n # xdims: number of xdims != 1\n # xlast: last index != 1\n\n if size(x,i) > 1\n xdims += 1; xlast = i\n dz[i] = size(x,i)\n end\n if size(y,i) > 1\n ydims += 1; ylast = i\n if dz[i] == 1\n dz[i] = size(y,i)\n elseif dz[i] != size(y,i)\n throw(DimensionMismatch(\n \"arrays could not be broadcast to a common size\"))\n end\n end\n\n xsame += (dz[i] == size(x,i))\n ysame += (dz[i] == size(y,i))\n zlen *= dz[i]\n end\n\n multi = false\n if (xsame != nz && xdims > 1) || (ysame != nz && ydims > 1)\n multi = true\n end\n\n if xdims == 0\n sx = zlen; nx = 1\n elseif xdims == 1\n sx = prod(dz[1:xlast-1]); nx=dz[xlast]\n elseif xsame == nz\n sx = 1\n nx = zlen\n elseif !multi\n error(\"Broadcasting error\")\n end\n\n if ydims == 0\n sy = zlen\n ny = 1\n elseif ydims == 1\n sy = prod(dz[1:ylast-1])\n ny = dz[ylast]\n elseif ysame == nz\n sy = 1\n ny = zlen\n elseif !multi\n error(\"Broadcasting error\")\n end\n\n return (tuple(dz...), sx, nx, sy, ny,xlast,ylast,xdims,ydims,multi)\nend\n\nfunction get_strides(x,y,z)\n # x,y,z may have different ndims, work with the max\n n = max(ndims(x), ndims(y), ndims(z))\n stride_x = Int32[ stride(x,i) for i=1:n ]\n stride_y = Int32[ stride(y,i) for i=1:n ]\n stride_z = Int32[ stride(z,i) for i=1:n ]\n dims_x = Int32[ size(x,i) for i=1:n ]\n dims_y = Int32[ size(y,i) for i=1:n ]\n for i in 1:n\n dims_x[i] == dims_y[i] && continue\n if dims_x[i]==1\n stride_x[i]=0\n else\n stride_y[i]=0\n end\n end\n return stride_x, stride_y, stride_z\nend\n\n# Additional imports: fns in binary_ops are defined using broadcasted.\nimport Base: +, -, *, /, \\\n\n# Here we'll just define some functions that specifically do not have broadcasting.\n(+)(x::KnetArray{T},y::KnetArray{T}) where {T} = (size(x)==size(y)||throw(DimensionMismatch(\"$(map(size,(x,y)))\"));(.+)(x,y))\n(-)(x::KnetArray{T},y::KnetArray{T}) where {T} = (size(x)==size(y)||throw(DimensionMismatch(\"$(map(size,(x,y)))\"));(.-)(x,y))\n#(*){T}(x::KnetArray{T},y::KnetArray{T})=(.*)(x,y) # This is matmul\n#(/){T}(x::KnetArray{T},y::KnetArray{T})=(./)(x,y) # This is another linalg op\n\n# Broadcast max/min haven't been defined in Base:\n# max(a::Array,b::Array)=broadcast(max,a,b)\n# min(a::Array,b::Array)=broadcast(min,a,b)\n# tkelman: These two methods aren't necessary, and overwrite Base. You can get this behavior via max.(a,b), with @compat needed on 0.4.\n\n# import Base: broadcast\n\n# Scalar kernels are defined for scalar,array order only.\n# For array,scalar we can get most for free.\n@eval begin\n broadcasted(::typeof(+),a::KnetArray{T},s::Number) where {T} = (.+)(T(s),a)\n broadcasted(::typeof(+),s::Number,a::KnetArray{T}) where {T} = (.+)(T(s),a)\n broadcasted(::typeof(-),a::KnetArray{T},s::Number) where {T} = (.+)(T(-s),a)\n broadcasted(::typeof(-),s::Number,a::KnetArray{T}) where {T} = (.-)(T(s),a)\n broadcasted(::typeof(*),a::KnetArray{T},s::Number) where {T} = (.*)(T(s),a)\n broadcasted(::typeof(*),s::Number,a::KnetArray{T}) where {T} = (.*)(T(s),a)\n broadcasted(::typeof(/),a::KnetArray{T},s::Number) where {T} = (.*)(T(1/s),a)\n broadcasted(::typeof(/),s::Number,a::KnetArray{T}) where {T} = (./)(T(s),a)\n broadcasted(::typeof(max),a::KnetArray{T},s::Number) where {T} = max.(T(s),a)\n broadcasted(::typeof(max),s::Number,a::KnetArray{T}) where {T} = max.(T(s),a)\n broadcasted(::typeof(min),a::KnetArray{T},s::Number) where {T} = min.(T(s),a)\n broadcasted(::typeof(min),s::Number,a::KnetArray{T}) where {T} = min.(T(s),a)\n broadcasted(::typeof(^),s::Number,a::KnetArray{T}) where {T} = (.^)(T(s),a)\n # Pow is the one exception, we need to define a separate kernel:\n rpow(s,a)=a^s # only broadcast#rpow is defined above, we need rpow defined\n broadcasted(::typeof(^),a::KnetArray{T},s::Number) where {T} = rpow.(T(s),a)\nend\n\n@eval begin\n broadcasted(::typeof(==),a::KnetArray{T},s::Number) where {T} = (T(s).==a)\n broadcasted(::typeof(==),s::Number,a::KnetArray{T}) where {T} = (T(s).==a)\n broadcasted(::typeof(!=),a::KnetArray{T},s::Number) where {T} = (T(s).!=a)\n broadcasted(::typeof(!=),s::Number,a::KnetArray{T}) where {T} = (T(s).!=a)\n broadcasted(::typeof(>),a::KnetArray{T},s::Number) where {T} = (T(s).),s::Number,a::KnetArray{T}) where {T} = (T(s).>a)\n broadcasted(::typeof(>=),a::KnetArray{T},s::Number) where {T} = (T(s).<=a)\n broadcasted(::typeof(>=),s::Number,a::KnetArray{T}) where {T} = (T(s).>=a)\n broadcasted(::typeof(<),a::KnetArray{T},s::Number) where {T} = (T(s).>a)\n broadcasted(::typeof(<),s::Number,a::KnetArray{T}) where {T} = (T(s).=a)\n broadcasted(::typeof(<=),s::Number,a::KnetArray{T}) where {T} = (T(s).<=a)\nend\n\n# Bcasted methods\n\nfor f in Symbol.((+,-,*,/,max,min,^,==,!=,>,>=,<,<=))\n M = which(@__MODULE__, f)\n @eval begin\n broadcasted(::typeof($f),s::Bcasted{<:Number},a::Bcasted{<:KnetArray}) = broadcasted($f, s.value, a.value) |> Bcasted\n broadcasted(::typeof($f),s::Bcasted{<:Number},a::KnetArray) = broadcasted($f, s.value, a) |> Bcasted\n broadcasted(::typeof($f),s::Number,a::Bcasted{<:KnetArray}) = broadcasted($f, s, a.value) |> Bcasted\n broadcasted(::typeof($f),a::Bcasted{<:KnetArray},s::Bcasted{<:Number}) = broadcasted($f, a.value, s.value) |> Bcasted\n broadcasted(::typeof($f),a::KnetArray,s::Bcasted{<:Number}) = broadcasted($f, a, s.value) |> Bcasted\n broadcasted(::typeof($f),a::Bcasted{<:KnetArray},s::Number) = broadcasted($f, a.value, s) |> Bcasted\n ($M).$f(s::Bcasted{<:Number},a::Bcasted{<:KnetArray}) = broadcasted($f, s.value, a.value) |> Bcasted\n ($M).$f(s::Bcasted{<:Number},a::KnetArray) = broadcasted($f, s.value, a) |> Bcasted\n ($M).$f(s::Number,a::Bcasted{<:KnetArray}) = broadcasted($f, s, a.value) |> Bcasted\n ($M).$f(a::Bcasted{<:KnetArray},s::Bcasted{<:Number}) = broadcasted($f, a.value, s.value) |> Bcasted\n ($M).$f(a::KnetArray,s::Bcasted{<:Number}) = broadcasted($f, a, s.value) |> Bcasted\n ($M).$f(a::Bcasted{<:KnetArray},s::Number) = broadcasted($f, a.value, s) |> Bcasted\n end\nend\n\n# familiar aliases for broadcasting operations of array & scalar (#7226):\n# (+)(a::KnetArray{T},s::Number) where {T} = (.+)(T(s),a) -- deprecated\n# (+)(s::Number,a::KnetArray{T}) where {T} = (.+)(T(s),a) -- deprecated\n# (-)(a::KnetArray{T},s::Number) where {T} = (.+)(T(-s),a) -- deprecated\n# (-)(s::Number,a::KnetArray{T}) where {T} = (.-)(T(s),a) -- deprecated\n(*)(a::KnetArray{T},s::Number) where {T} = (.*)(T(s),a)\n(*)(s::Number,a::KnetArray{T}) where {T} = (.*)(T(s),a)\n(/)(a::KnetArray{T},s::Number) where {T} = (.*)(T(1/s),a)\n(\\)(s::Number,a::KnetArray{T}) where {T} = (.*)(T(1/s),a)\n\n#(/)(s::Number,a::KnetArray{T}) where {T} = (.*)(T(1/s),a) # TODO: non-elementwise definition in linalg\n#(^)(a::KnetArray{T},s::Number) where {T} = (.^)(a,T(s)) # non-elementwise definition in linalg\n#(^)(s::Number,a::KnetArray{T}) where {T} = (.^)(T(s),a) # non-elementwise definition in linalg\n\n# Define all overloaded Julia functions for KnetArrays:\n\nfor f in binary_ops\n if !isa(f,Tuple); f=(f,); end\n binary_op(f...)\nend\n\n# Fix #412 where KnetArray(randn(Float64,4,4,4,4)).^2 gives a 1-D result\nbroadcasted(::typeof(Base.literal_pow), ::typeof(^), k::KnetArray{T}, n::Val{N}) where {T,N} = broadcasted(^, k, N)\n", "meta": {"hexsha": "a92db0f6390fce0553d7effd9b0d7d87a79c76b0", "size": 16143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/binary.jl", "max_stars_repo_name": "petershintech/Knet.jl", "max_stars_repo_head_hexsha": "9ed953d568f2ce94265bcc9663a671ac8364d8b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-26T00:46:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-26T00:46:11.000Z", "max_issues_repo_path": "src/binary.jl", "max_issues_repo_name": "ilkerkesen/Knet.jl", "max_issues_repo_head_hexsha": "67b51a40188e13687dc912c09404d64c3c4d95da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/binary.jl", "max_forks_repo_name": "ilkerkesen/Knet.jl", "max_forks_repo_head_hexsha": "67b51a40188e13687dc912c09404d64c3c4d95da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9783281734, "max_line_length": 141, "alphanum_fraction": 0.5287121353, "num_tokens": 5440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.1966591409536998}} {"text": "import QuantumControlBase\nusing QuantumControlBase: getcontrols, getcontrolderivs, discretize_on_midpoints, evalcontrols\nusing QuantumControlBase: GradVector, TimeDependentGradGenerator\nusing QuantumPropagators: init_storage, initpropwrk\nusing ConcreteStructs\n\n# GRAPE workspace (for internal use)\n@concrete terse struct GrapeWrk\n\n # a copy of the objectives\n objectives\n\n # the adjoint objectives, containing the adjoint generators for the\n # backward propagation\n adjoint_objectives\n\n # The kwargs from the control problem\n kwargs\n\n # Tuple of the original controls (probably functions)\n controls\n\n # TODO: pulsevals0 and pulsevals1\n pulsevals :: Vector{Float64}\n\n gradient :: Vector{Float64} # gradient for guess in iterations\n\n searchdirection :: Vector{Float64} # search-direction for guess in iterations\n\n # Result object\n result\n\n #################################\n # scratch objects, per objective:\n\n # backward-propagated states\n # note: storage for fw-propagated states is in result.states\n bw_states\n\n # forward-propagated states (functional evaluation only)\n fw_states\n\n # foward-propagated grad-vectors\n fw_grad_states\n\n # gradients ∂τₖ/ϵₗ(tₙ)\n tau_grads :: Vector{Matrix{ComplexF64}}\n\n # dynamical generator (normal propagation) at a particular point in time\n G\n\n # dynamica generator for grad-propagation, time-dependent\n TDgradG\n\n # dynamical generator for grad-propagation at a particular point in time\n gradG\n\n control_derivs :: Vector{Vector{Union{Function, Nothing}}}\n\n vals_dict\n\n bw_storage # backward storage array (per objective)\n\n fw_prop_wrk # for normal forward propagation\n\n bw_prop_wrk # for normal propagation\n\n grad_prop_wrk # for gradient forward propagation\n\n use_threads :: Bool\n\nend\n\nfunction GrapeWrk(problem::QuantumControlBase.ControlProblem)\n use_threads = get(problem.kwargs, :use_threads, false)\n objectives = [obj for obj in problem.objectives]\n adjoint_objectives = [adjoint(obj) for obj in problem.objectives]\n controls = getcontrols(objectives)\n control_derivs = [\n getcontrolderivs(obj.generator, controls) for obj in objectives\n ]\n tlist = problem.tlist\n # interleave the pulse values as [ϵ₁(t̃₁), ϵ₂(t̃₁), ..., ϵ₁(t̃₂), ϵ₂(t̃₂), ...]\n # to allow access as reshape(pulsevals0, L :)[l, n] where l is the control\n # index and n is the time index\n pulsevals = convert(\n Vector{Float64},\n reshape(transpose(hcat(\n [discretize_on_midpoints(control, tlist)\n for control in controls]...\n )), :)\n )\n kwargs = Dict(problem.kwargs)\n pulse_options = problem.pulse_options\n if haskey(kwargs, :continue_from)\n @info \"Continuing previous optimization\"\n result = kwargs[:continue_from]\n if !(result isa GrapeResult)\n # account for continuing from a different optimization method\n result = convert(GrapeResult, result)\n end\n result.iter_stop = get(problem.kwargs, :iter_stop, 5000)\n result.converged = false\n result.start_local_time = now()\n result.message = \"in progress\"\n pulsevals = convert(\n Vector{Float64},\n reshape(transpose(hcat(\n [discretize_on_midpoints(control, wrk.result.tlist)\n for control in result.optimized_controls]...\n )), :)\n )\n else\n result = GrapeResult(problem)\n end\n gradient = zeros(length(pulsevals))\n searchdirection = zeros(length(pulsevals))\n bw_states = [similar(obj.initial_state) for obj in objectives]\n fw_states = [similar(obj.initial_state) for obj in objectives]\n fw_grad_states = [\n GradVector(obj.initial_state, length(controls))\n for obj in objectives\n ]\n dummy_vals = IdDict(control => 1.0 for (i, control) in enumerate(controls))\n G = [evalcontrols(obj.generator, dummy_vals) for obj in objectives]\n vals_dict = [copy(dummy_vals) for _ in objectives]\n bw_storage = [init_storage(obj.initial_state, tlist) for obj in objectives]\n fw_prop_method = [\n Val(\n QuantumControlBase.get_objective_prop_method(\n obj, :fw_prop_method, :prop_method; problem.kwargs...\n )\n )\n for obj in objectives\n ]\n bw_prop_method = [\n Val(\n QuantumControlBase.get_objective_prop_method(\n obj, :bw_prop_method, :prop_method; problem.kwargs...\n )\n )\n for obj in objectives\n ]\n grad_prop_method = [\n Val(\n QuantumControlBase.get_objective_prop_method(\n obj, :grad_prop_method, :fw_prop_method, :prop_method;\n problem.kwargs...\n )\n )\n for obj in objectives\n ]\n\n fw_prop_wrk = [\n QuantumControlBase.initobjpropwrk(obj, tlist, fw_prop_method[k];\n initial_state=obj.initial_state,\n kwargs...)\n for (k, obj) in enumerate(objectives)\n ]\n bw_prop_wrk = [\n QuantumControlBase.initobjpropwrk(obj, tlist, bw_prop_method[k];\n initial_state=obj.initial_state,\n kwargs...)\n for (k, obj) in enumerate(objectives)\n ]\n TDgradG = [TimeDependentGradGenerator(obj.generator) for obj in objectives]\n gradG = [evalcontrols(G̃_of_t, dummy_vals) for G̃_of_t ∈ TDgradG]\n grad_prop_wrk = [\n initpropwrk(Ψ̃, tlist, grad_prop_method[k], gradG[k]; kwargs...)\n for (k, Ψ̃) in enumerate(fw_grad_states)\n ]\n tau_grads :: Vector{Matrix{ComplexF64}} = [\n zeros(ComplexF64, length(controls), length(tlist)-1)\n for _ in objectives\n ]\n GrapeWrk(\n objectives,\n adjoint_objectives,\n kwargs,\n controls,\n pulsevals,\n gradient,\n searchdirection,\n result,\n bw_states,\n fw_states,\n fw_grad_states,\n tau_grads,\n G,\n TDgradG,\n gradG,\n control_derivs,\n vals_dict,\n bw_storage,\n fw_prop_wrk,\n bw_prop_wrk,\n grad_prop_wrk,\n use_threads\n )\nend\n", "meta": {"hexsha": "a1e0237bfe2dcd9086a132a6112f79d44eae319b", "size": 6281, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/workspace.jl", "max_stars_repo_name": "QuantumControl-jl/GRAPE.jl", "max_stars_repo_head_hexsha": "9628910380873f8033c361d1a91ae98d1cdbb9ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/workspace.jl", "max_issues_repo_name": "QuantumControl-jl/GRAPE.jl", "max_issues_repo_head_hexsha": "9628910380873f8033c361d1a91ae98d1cdbb9ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/workspace.jl", "max_forks_repo_name": "QuantumControl-jl/GRAPE.jl", "max_forks_repo_head_hexsha": "9628910380873f8033c361d1a91ae98d1cdbb9ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2487562189, "max_line_length": 94, "alphanum_fraction": 0.6319057475, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19664375477759474}} {"text": "# November, 2020\n# Kevin Dorma\n# module for common hydraulic calculations\n# rev 0, December 2020\n# rev 1, February 2021, added network hydraulics\n\n\n# I need to make some decisions about how to interace with these functions\n# I assume that I use dataframes to store information about sizing lines and general hydraulics\n# then I will execute a function and it will return a result, but not change the raw information\n# size lines\n # Input dataframe for describing the lines\n # Output line descriptor, pipe schedule, size criteria DP/100 and C, IDmm for each criteria and the chosen IDmm\n# pick NPS will return the next size larger for NPS.This will be the chosen size.\n# we will have utility functions for increasing or decreasing the NPS by 1. \n\n\nmodule Hydraulics2\n\nusing DataFrames\nusing CSV\nusing ExcelFiles # more convenient than CSV for user input\n\nexport calcMoodyF\nexport addPipeProperties, addFluidProperties, getReynolds, getSegmentDP\nexport getLineSize, getListLargerNPS, getLargerNPS\n# and the network hydraulic files\nexport indexLookup, doNetworkHydraulics, extractResults, combineResults\n\n# these are the reference data.\n# and this needs to be loaded correctly when we use the code in a module\ninclude(\"npsList.jl\")\ninclude(\"schedList.jl\")\ninclude(\"pipeRoughnessList.jl\")\ninclude(\"fitting3K.jl\")\ninclude(\"pipeIDlist.jl\")\n\n#schedList = CSV.File(\"schedList.csv\") |> DataFrame\n#pipeRoughness = CSV.File(\"pipeRoughness.csv\") |> DataFrame\n#fitting3K = CSV.File(\"fitting3K.csv\") |> DataFrame\n#IDmm = CSV.File(\"pipeIDlist.csv\") |> DataFrame\n## not used\n#pipeTable = CSV.read(\"pipeIDtable.csv\");\n\n\nfunction packageInfo()\n # return information about the package as a string\n return(\"Hydraulics package, Kevin Dorma. Written in Julia, rev 1 February 2021.\")\nend\n\n# need function to append piping data\n# later\n\n\nfunction calcMoodyF(Reynolds,eD)\n # Moody friction factor, this is Halaand\n # eD is e/D relative roughness\n # Reynolds is Reynolds number\n invSqrtF = -1.8 .* log10.((eD ./ 3.70) .^ 1.11 + 6.9 ./ Reynolds)\n moodyF = (1 ./ (invSqrtF .^2) )\n return (moodyF)\nend\n\nfunction checkFittingList(fittingList)\n # fittingList is our list of fittings, fittingReference is the generic data\n # go through the list of fittings (fittingList) and compare with the reference list (possibly our fitting3K global list)\n # return items that are not found\n errorList = DataFrame(message = String[], entry=Int64[], Segment=String[], fittingType=String[])\n for i = 1:(size(fittingList)[1])\n thisFitting = fittingList[i,:fittingType]\n match = fitting3K[fitting3K.fittingType .== thisFitting,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"Fitting not found in row\", i, fittingList[i,:Segment], fittingList[i,:fittingType] ))\n end\n end\n return (errorList)\nend\n\n\n\nfunction checkLineList(lines,fluidList)\n # go through our list of lines and compare with our reference lists\n # return the line items that are not found\n errorList = DataFrame(message = String[], entry=Int64[], Segment=String[], NPS=Float64[], Schedule=String[], material=String[], fluidName=String[])\n for i = 1:(size(lines)[1])\n # NPS, must check if this field exists\n\tif (indexLookup(\"NPS\",names(lines)) > 0)\n thisItem = lines[i,:NPS]\n match = npsList[npsList.NPS .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"NPS not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ));\n end;\n\tend;\n # schedule\n thisItem = lines[i,:Schedule]\n match = schedList[schedList.Schedule .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"Schedule not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ))\n end\n # roughness material\n thisItem = lines[i,:Material]\n match = pipeRoughness[pipeRoughness.Material .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"Material not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ))\n end\n # fluid\n thisItem = lines[i,:fluidName]\n match = fluidList[fluidList.fluidName .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"FluidName not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ))\n end\n end\n return (errorList)\nend\n\n\nfunction addPipeProperties(df)\n # roughness, IDmm, eD ratio\n # this appends columns to df\n # used either line sizing or hydraulic calculations\n\n df[:,:roughnessMM] .= 0.0\n df[:,:IDmm] .= 0.0\n\n for i = 1:(size(df)[1])\n df[i,:roughnessMM]=pipeRoughness[df[i,:Material] .== pipeRoughness[:,:Material],:roughnessMM][1]\n df[i,:IDmm]= IDmm[(df[i,:NPS] .== IDmm[:,:NPS]) .& (df[i,:Schedule] .== IDmm[:,:Schedule]),:Idmm][1]\n end\n\n return (0.0)\nend\n\nfunction addFluidProperties(df,fluidList)\n # extract the density, viscosity and whatever else is needed from the fluidList\n # Add this to the df\n # used either line sizing or hydraulic calculations\n\n \n\n df[:,:rho_kgm3] .= 0.0\n df[:,:mu_mPas] .= 0.0\n df[:,:roughnessMM] .= 0.0\n\n\n for i = 1:(size(df)[1])\n df[i,:rho_kgm3] = fluidList[df[i,:fluidName] .== fluidList[:,:fluidName], :rho_kgm3][1]\n df[i,:mu_mPas] = fluidList[df[i,:fluidName] .== fluidList[:,:fluidName], :mu_mPas][1]\n df[i,:roughnessMM] = pipeRoughness[df[i,:Material] .== pipeRoughness[:,:Material], :roughnessMM][1]\n end\n\n return (0.0)\nend\n\n\n\nfunction lineSizeDP(df)\n # this is for sizing lines based on pressure drop kPa per 100 m, return the ID in mm\n # very convenient form straight out of Perrys handbook\n # uses friction factor correlation from Chen\n # Do not modify the original data in df\n\n g = 9.80665\n Sf = df.kPaPer100m*1000 ./ (df.rho_kgm3*g*100)\n q = df.massFlow .* df.margin ./(df.rho_kgm3*3600)\n eps = (df.roughnessMM/1000)\n kinVisc = (df.mu_mPas/1000) ./ df.rho_kgm3\n termA = ((eps.^5)*g .* Sf ./ (q.^2)).^0.25\n termB = ((kinVisc .^ 5)./((q.^3) .* Sf * g )).^0.2\n termC = 0.125*(termA .+ termB).^0.2\n returnValue = (1000*(termC .* (q.^2) ./ (g*Sf)).^0.2)\n return (returnValue)\nend\n\nfunction lineSizeErosion(df)\n # df is the dataframe with hydraulic information\n # this is the erosion C factor method\n # C = v/sqrt(rho), with v in m/s and rho in kg/m3\n # for most service, C = 120, this is similar to C = 100 for imperial units\n # return the ID in mm\n\n g = 9.80665\n maxVeloc = df.frictionCsi ./ sqrt.(df.rho_kgm3)\n q = df.massFlow .* df.margin ./(df.rho_kgm3*3600)\n area = q ./ maxVeloc\n returnValue = (sqrt.(4*area ./ pi )*1000.0)\n return (returnValue)\nend\n\nfunction getLineSize(df,fluidList)\n # from the calculated line size for the two different methods, determine the required line size\n \n addFluidProperties(df,fluidList)\n \n theSchedule = df[:,:Schedule]\n\n theSegment = df[:,:Segment]\n\n tempDP100 = lineSizeDP(df)\n tempErosion = lineSizeErosion(df)\n tempNeeded = tempErosion[:] + tempDP100[:]\n for j in 1:size(tempDP100)[1]\n tempNeeded[j] =max(tempDP100[j], tempErosion[j])\n end\n returnValue = DataFrame(Segment = theSegment, mmDP100 = tempDP100, mmErosion = tempErosion, mmNeeded = tempNeeded, Schedule = theSchedule)\n return (returnValue)\nend\n\n# I need a function to pick the next larger line size given the pipe schedule\n\n\nfunction getLargerNPS(ourIDmm, ourSchedule)\n # from the common list of line sizes, pick the pipe size that matches the required schedule\n # and is the next larger that the required ID\n # this works for a single line size\n ourScheduleList = IDmm[IDmm[:,:Schedule] .== ourSchedule, :];\n refinedList = ourScheduleList[(ourScheduleList[:,:Idmm] .- ourIDmm) .> 0.0,:];\n theMinID = minimum(refinedList[:,:Idmm])\n ourNPS = refinedList[(refinedList[:,:Idmm] .== theMinID), :NPS]\n\n return (ourNPS)\nend\n\n\nfunction getListLargerNPS(lineSizeDF)\n # we will use the required line size and schedule and return the NPS and actual ID\n diamList = DataFrame(Segment=String[], NPS=Float64[], Schedule=String[], IDmm=Float64[])\n for i = 1:(size(lineSizeDF)[1])\n ourSchedule = lineSizeDF[i,:Schedule];\n ourIDmm = lineSizeDF[i,:mmNeeded]\n ourScheduleList = IDmm[IDmm[:,:Schedule] .== ourSchedule, :];\n refinedList = ourScheduleList[(ourScheduleList[:,:Idmm] .- ourIDmm) .> 0.0,:];\n theMinID = minimum(refinedList[:,:Idmm])\n ourNPS = refinedList[(refinedList[:,:Idmm] .== theMinID), :NPS][1]\n\n push!(diamList, (lineSizeDF[i,:Segment], ourNPS, ourSchedule, theMinID))\n end\n return (diamList)\nend\n\nfunction sizing2hydraulics(sizingDF, chosenLineSizeDF)\n # given the line sizing DF, copy the info into hydraulics dataframe\n # chosenSizeDF contains the NPS and Schedule\n # return the hydraulics DF\n # we also need a simple fittingDF, but this is done with a separate function\n hydraulicsDF = DataFrame(Segment=String[], Description=String[], LineTag=String[], PnID=String[], NPS=Float64[], Schedule=String[],\n\t\tMaterial=String[],\tfluidName=[],\tinletP_kPaa=[],\tmassFlow=Float64[])\n for i = 1:(size(sizingDF)[1])\n push!(hydraulicsDF, (sizingDF[i,:Segment], sizingDF[i,:Description],\n sizingDF[i,:LineTag], sizingDF[i,:PnID], chosenLineSizeDF[i,:NPS],\n chosenLineSizeDF[i,:Schedule], sizingDF[i,:Material], sizingDF[i,:fluidName],\n 100.0, (sizingDF[i,:massFlow]*sizingDF[i,:margin])))\n end\n return(hydraulicsDF)\nend\n\nfunction sizing2fittingList(sizingDF, chosenLineSizeDF)\n # given the line sizing DF, copy the info into the fitting list\n # chosenSizeDF contains the NPS and Schedule\n # return the pre-populsted fittign list DF\n fittingListDF = DataFrame(Segment=String[], fittingType=String[], num_length_m=Float64[], comment=String[], revision=String[])\n \n for i = 1:(size(sizingDF)[1])\n push!(fittingListDF, (sizingDF[i,:Segment], \"PIPE\", 100.0, \"from line sizing\", \"A\"))\n end\n return(fittingListDF)\nend\n\n\n\n\nfunction incrementLineSize(rowNum, lineSizeDF, increment)\n # increment the specified row number needed line size by +1 or -1\n # not the cleanest function, but it works\n \n neededDF = DataFrame(Segment=String[], mmNeeded=Float64[], Schedule=String[])\n \n i = rowNum\n push!(neededDF, (lineSizeDF[i,:Segment], lineSizeDF[i,:IDmm] + increment, lineSizeDF[i,:Schedule]))\n\n incrementedLines = getListLargerNPS(neededDF)\n\n lineSizeDF[i,:NPS] = incrementedLines[1,:NPS]\n lineSizeDF[i,:IDmm] = incrementedLines[1,:IDmm]\n\n return (3.14)\nend\n\nfunction getReynolds(df)\n # preliminary calculations for pipe hydraulics\n # return the velocity, Reynolds, friction factor, density, diameterMM, diameterInch\n\n theSegment = df.Segment\n diamMM = df.IDmm\n diamInch = diamMM / 25.4\n rho = df.rho_kgm3\n volFlow = df.massFlow ./ df.rho_kgm3\n area = 0.25 * pi * (df.IDmm / 1000.0).^2\n velocity = volFlow ./ area / 3600\n Reynolds = df.rho_kgm3 .* velocity .* (df.IDmm / 1000.0) ./ (df.mu_mPas/1000.0)\n eD = df.roughnessMM ./ df.IDmm\n moodyF = calcMoodyF(Reynolds, eD)\n returnValue = DataFrame(Segment = theSegment, velocity_ms = velocity, rho_kgm3 = rho, Re = Reynolds, frictF = moodyF, IDmm = diamMM, IDinch = diamInch)\n return (returnValue)\nend\n\n\nfunction elementDP(lines, fittingList)\n # given the hydraulic elements in df (long list of pipe and fittings)\n # and the preliminary values in prelim\n # calculate the DP in each element\n # dp = rho.f. (L/D) v2/2\n # dp = rho K v2/2\n # where I need to calculate K = K1/Re + Kinf*(1 + Kd/Dinch^0.3)\n # can I get all of the pipe segments and use K = Kp * f L/D, where Kp = 1 for pipe\n # return the value for Kp (1 for pipe, 0 for fitting) and the pressure drop in the item\n returnValue = DataFrame(Segment = String[], Kp = Float64[], fittingK=Float64[], pipeK=Float64[], elementK = Float64[], DPkpa = Float64[])\n \n # start with getting Reynolds and other important things\n prelim = getReynolds(lines)\n\n for i = 1:(size(fittingList)[1])\n theSegment = fittingList[i,:Segment]\n\n # first we get all of the K values\n valK1 = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:K1][1]\n valKinf = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kinf][1]\n valKd = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kd][1]\n valKp = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kp][1]\n\n # now we get the hydraulic properties\n ff = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:frictF][1]\n rho = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:rho_kgm3][1]\n idInch = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:IDinch][1]\n idMM = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:IDmm][1]\n veloc = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:velocity_ms][1]\n Re = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:Re][1]\n \n Kfitting = valK1/Re + valKinf*(1.0 + valKd/(idInch^0.3))\n\n # pressure drop in kPa\n thisKfitting = fittingList[i,:num_length_m] * Kfitting\n thisKpipe = valKp * ff * fittingList[i,:num_length_m] /(idMM/1000.0) \n thisK = thisKfitting + thisKpipe\n thisDP = thisK * (0.001 * rho * 0.5 * (veloc)^ 2)\n\n push!(returnValue, (theSegment, valKp, thisKfitting, thisKpipe, thisK, thisDP))\n end\n return (returnValue)\nend\n\nfunction compileDP(lines, fittingDP)\n # for each entry in lines, sum all of the fittingDP\n returnValue = DataFrame(Segment = String[], segmentK = Float64[], DPkpa = Float64[], inletP = Float64[], outletP = Float64[])\n\n for i = 1:(size(lines)[1])\n theSegment = lines[i,:Segment]\n theSumK = sum(fittingDP[fittingDP[:,:Segment] .== theSegment,:elementK])\n theSumDP = sum(fittingDP[fittingDP[:,:Segment] .== theSegment,:DPkpa])\n theInletP = lines[i,:inletP_kPaa]\n theOutletP = theInletP - theSumDP\n push!(returnValue, (theSegment, theSumK, theSumDP, theInletP, theOutletP))\n end\n return (returnValue)\nend\n\nfunction getSegmentDP(lines, fittingList, fluidList)\n # lines describes the hydraulics, fittingList has the piping details, fluidList is the fluid\n\n addFluidProperties(lines,fluidList)\n addPipeProperties(lines)\n fittingDP = elementDP(lines, fittingList)\n returnValue = compileDP(lines, fittingDP)\n return (returnValue)\nend\n\n\n# functions added for network hydraulics\n# february, 2021\n# exported\nfunction indexLookup(findMe, inThis)\n # find the index where findMe can be found inThis, which is a vector\n maxI = size(inThis)[1]\n foundIdx = 0\n for i = 1:maxI\n if (findMe == inThis[i]) \n foundIdx = i\n end\n end\n return(foundIdx)\nend\n\nfunction getConnectivity(connectivity, nodeList)\n # connectivity, lineList and nodeList are dataframe\n# maxLine = size(lineList)[1]\n\n maxLine = size(connectivity)[1]\n\n maxNode = size(nodeList)[1]\n C = zeros(Float64,maxLine,maxNode)\n \n maxConnect = size(connectivity)[1]\n \n for i = 1:maxConnect\n theSegment = connectivity[i,:Segment]\n inNode = connectivity[i,:inNode]\n outNode = connectivity[i,:outNode]\n# theRow = indexLookup(theSegment,lineList[:,:Segment])\n theRow = indexLookup(theSegment,connectivity[:,:Segment])\n inCol = indexLookup(inNode,nodeList[:,:Node])\n outCol = indexLookup(outNode,nodeList[:,:Node])\n C[theRow,inCol] = 1.0\n C[theRow,outCol] = -1.0\n end\n return(C)\nend\n\nfunction removeTrivialRows(A)\n # remove rows from matrix A that contain only one entry\n numRows = size(A)[1]\n numColumns = size(A)[2]\n indexList = zeros(Int64, numRows,1)\n numNonTrivialRows = 0\n for i = 1:numRows\n countNonZero = 0\n for j = 1:numColumns\n if (A[i,j] != 0.0)\n countNonZero = countNonZero + 1\n end\n end\n if (countNonZero >= 2)\n numNonTrivialRows += 1\n indexList[numNonTrivialRows] = i\n end\n \n end\n returnMatrix = zeros(numNonTrivialRows,numColumns)\n for i = 1:numNonTrivialRows\n for j = 1:numColumns\n returnMatrix[i,j] = A[indexList[i],j]\n end\n end\n \n return(returnMatrix)\nend\n\nfunction initializeHydraulicParameters(setRe, df)\n # set all of the Reynolds numbers in lines df\n # return the hydraulicParameters (Reynolds, friction factor, density, diameterMM, diameterInch)\n\n theSegment = df.Segment\n diamMM = df.IDmm\n rho_kgm3 = df.rho_kgm3\n diamInch = diamMM / 25.4\n\n volFlow = df.massFlow ./ df.rho_kgm3\n area = 0.25 * pi * (df.IDmm / 1000.0).^2\n velocity = volFlow ./ area / 3600\n Reynolds = setRe .* (df.rho_kgm3 ./ df.rho_kgm3)\n eD = df.roughnessMM ./ df.IDmm\n moodyF = calcMoodyF(Reynolds, eD)\n\n returnValue = DataFrame(Segment = theSegment, rho_kgm3 = rho_kgm3, Re = Reynolds, frictF = moodyF, IDmm = diamMM, IDinch = diamInch)\n return (returnValue)\nend\n\n\nfunction initializeMassFlow(df, connectivity)\n # set mass flow in df to 1000 kg/h\n # but only if the flow rate is undefined or zero\n # I want to create a df with fields Segment and massFlow\n # we have viscosity, density and IDmm in the df\n # we will use a frictional pressure gradient of 20 kPa per 100 m for initial guess on mass flow\n # and friction factor 0.02\n # but then overwrite if we have something filled in for massFlow in the df\n\n returnValue = DataFrame(Segment = String[], massFlow = Float64[])\n\n # first, set all mass flows equal to 1000 kg/h\n numRows = size(connectivity)[1]\n for i = 1:numRows\n push!(returnValue, (connectivity[i,:Segment], 1000.0) )\n end\n\n\n # now, plow thorugh the hydraulic information\n # if there is no information here, then use DP per 100m to calculate a mass flow\n # if there is information here, use this\n numHydraulicRows = size(df)[1]\n\n dp100 = 20.0\n ff = 0.02 # estimate for friction factor\n \n for i = 1:numHydraulicRows\n ii = indexLookup(df[i,:Segment],connectivity[:,:Segment])\n # calculate this just in case\n dd = df[i,:IDmm]\n rho = df[i,:rho_kgm3]\n visc = df[i,:mu_mPas]\n mm = 3600 * sqrt(20*1000*rho*(pi^2 / (8*ff))*((dd^5)/100)*(1/1000)^5)\n if (ismissing(df[i,:massFlow]) || (df[i,:massFlow] == 0.0) ) \n df[i,:massFlow] = mm\n returnValue[ii,:massFlow] = mm\n else\n returnValue[ii,:massFlow] = df[i,:massFlow]\n end\n end\n return (returnValue)\nend\n\nfunction getResistanceMatrix(hydraulicParameters, elementK, connectivity)\n # given the hydraulic parameters, a list of all segments\n # and the long list of K values for every element in the network\n # calculate the sum of the overall K for each segment\n # return a diagonal matrix with the K values on the diagonal\n # wait, the resistance K value is in terms of velocity in m/s\n # I need mass flow in kg/h\n #\n # I think I need to add the connectivity matrix to get the correct value for the variable number\n \n numRows = size(hydraulicParameters)[1]\n numColumns = size(connectivity)[1]\n\n numElements = size(elementK)[1]\n# matrixK = zeros(Float64,numRows,numRows)\n# this needs to be the number of variables in the connectivity matrix\n matrixK = zeros(Float64,numRows,numColumns)\n\n \n for i = 1:numElements\n# theRow = indexLookup(elementK[i,:Segment], hydraulicParameters[:,:Segment])\n# theRow = indexLookup(elementK[i,:Segment], hydraulicParameters[:,:Segment])\n\n theRow = indexLookup(elementK[i,:Segment], hydraulicParameters[:,:Segment])\n theColumn = indexLookup(elementK[i,:Segment], connectivity[:,:Segment])\n\n matrixK[theRow,theColumn] += elementK[i,:elementK]\n end\n # now we multiply each row element by 8 x 1000 / (rho pi^2 D^4) (1000/3600)^2 \n # where D is in mm, mass flow in kg/h and DP in kPa\n for i = 1:numRows\n multK = 8.0*1000.0 * ((1000/3600)^2) / ((pi^2) * hydraulicParameters[i,:rho_kgm3] * (hydraulicParameters[i,:IDmm]^4) )\n for j = 1:numColumns\n matrixK[i,j] *= multK\n end\n end\n return (matrixK)\nend\n\nfunction getSegLength(connectivity, fittingList)\n \n returnValue = DataFrame(Segment = String[], pipeLength=Float64[])\n \n# initialize the segLength data\n for i=1:(size(connectivity)[1])\n\tpush!(returnValue, (connectivity[i,:Segment], 0.0))\n end\n for i = 1:(size(fittingList)[1])\n valKp = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kp][1]\n\tii = indexLookup(fittingList[i,:Segment], connectivity[:,:Segment])\n\tif (valKp == 1) \n\t\treturnValue[ii,:pipeLength] += fittingList[i,:num_length_m]\n\tend\n end\n return(returnValue)\nend\n\n\n\n\nfunction getConstraintMatrix(constraintDF, constraintType, segmentDF, nodeDF)\n # given the constraint data, the type (massFlow or pressure or value), the list of segments and nodes\n # create a matrix with values of 1 in the row, or the actual value\n \n numConstraints = size(constraintDF)[1]\n numSegments = size(segmentDF)[1]\n numNodes = size(nodeDF)[1]\n \n # we need the dimensions for the return matrix\n # assume a value for now\n numCols = 2\n if (constraintType == \"flowRate\")\n numCols = numSegments\n end\n if (constraintType == \"pressure\")\n numCols = numNodes\n end\n if (constraintType == \"value\")\n numCols = 1\n end\n returnMatrix = zeros(numConstraints, numCols)\n \n # cycle through all of the constraints\n # of the constraintType matches the :variable in the constraintDF, then place a 1 in the matrix entry\n for i = 1:numConstraints\n if (constraintType == \"value\")\n returnMatrix[i] = constraintDF[i,:value]\n elseif (constraintType == \"flowRate\")\n varIndexLocal = indexLookup(constraintDF[i,:object], segmentDF[:,:Segment])\n if (varIndexLocal > 0)\n returnMatrix[i,varIndexLocal] = 1.0\n end\n elseif (constraintType == \"pressure\")\n varIndexLocal = indexLookup(constraintDF[i,:object], nodeDF[:,:Node])\n if (varIndexLocal > 0)\n returnMatrix[i,varIndexLocal] = 1.0\n end\n end\n end\n\n return(returnMatrix)\nend\n\nfunction getQuadraticMatrix(hydraulicDF, which)\n # given the estimates of mass flow rate in the hydraulic matrix, fill out the\n # linearized estimate to the quadratic mass flow^2\n # m^2 ~= 2 M m - M*M,\n # or\n # m2 - 2 M m = - M*M, where we are looking for m2 (m^2) and m, and M is the\n # previous estiamte of m\n # the value of which is either quadratic, linear, value\n\n # given the constraint data, the type (massFlow or pressure or value), the list of segments and nodes\n # create a matrix with values of 1 in the row, or the actual value\n \n numEquations = size(hydraulicDF)[1]\n numCols = numEquations\n \n if (which == \"rhs\")\n numCols = 1\n end\n\n returnMatrix = zeros(numEquations, numCols)\n \n # cycle through all of the segments\n # fill in the value for the matrix equation\n # m2 - 2 M m = - M*M, where we are looking for m2 (m^2) and m, and M is the\n # if quadratic rM[i,i] = 1.0\n # if linear rm[i,i] = -2*hydraulicDF[i,:massFlow]\n # if value rm[i] = -hydraulicDF[i,:massFlow]*hydraulicDF[i,:massFlow]\n\n for i = 1:numEquations\n if (which == \"rhs\")\n returnMatrix[i] = -hydraulicDF[i,:massFlow]*hydraulicDF[i,:massFlow]\n elseif (which == \"quadratic\")\n returnMatrix[i,i] = 1.0\n elseif (which == \"linear\")\n returnMatrix[i,i] = -2.0 * hydraulicDF[i,:massFlow]\n end\n end\n\n return(returnMatrix)\nend\n\nfunction getSegmentIMatrix(hydraulicParameters, connectivity)\n # given the Identity matrix for the segments\n # return Identity matrix\n \n numRows = size(hydraulicParameters)[1]\n numColumns = size(connectivity)[1]\n\n matrixI = zeros(Float64,numRows,numColumns)\n \n for i = 1:numRows\n findMe = hydraulicParameters[i,:Segment]\n inThis = connectivity[:,:Segment]\n j = indexLookup(findMe, inThis)\n matrixI[i,j] = 1.0\n end\n\n return (matrixI)\nend\n\nfunction getElementK(prelim, fittingList)\n # given the hydraulic elements in df (long list of pipe and fittings)\n # and the preliminary friction properties (Re, eD, ff)\n # calculate the loss coefficient K in each element\n # where I need to calculate K = K1/Re + Kinf*(1 + Kd/Dinch^0.3)\n # can I get all of the pipe segments and use K = Kp * f L/D, where Kp = 1 for pipe\n # return the value for Kp (1 for pipe, 0 for fitting) and the pressure drop in the item\n returnValue = DataFrame(Segment = String[], Kp = Float64[], fittingK=Float64[], pipeK=Float64[], elementK = Float64[], pipeLength=Float64[])\n \n\n for i = 1:(size(fittingList)[1])\n theSegment = fittingList[i,:Segment]\n\n # first we get all of the K values\n valK1 = Hydraulics2.fitting3K[Hydraulics2.fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:K1][1]\n valKinf = Hydraulics2.fitting3K[Hydraulics2.fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kinf][1]\n valKd = Hydraulics2.fitting3K[Hydraulics2.fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kd][1]\n valKp = Hydraulics2.fitting3K[Hydraulics2.fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kp][1]\n\n # now we get the hydraulic properties\n ff = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:frictF][1]\n rho = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:rho_kgm3][1]\n idInch = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:IDinch][1]\n idMM = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:IDmm][1]\n# veloc = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:velocity_ms][1]\n Re = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:Re][1]\n \n Kfitting = valK1/Re + valKinf*(1.0 + valKd/(idInch^0.3))\n\n # pressure drop in kPa\n thisKfitting = fittingList[i,:num_length_m] * Kfitting\n thisKpipe = valKp * ff * fittingList[i,:num_length_m] /(idMM/1000.0) \n\tif (valKp == 1) \n\t\tthisPipeLength = fittingList[i,:num_length_m]\n\telse\n\t\tthisPipeLength = 0.0\n\tend\n\n thisK = thisKfitting + thisKpipe\n# thisDP = thisK * (0.001 * rho * 0.5 * (veloc)^ 2)\n\n push!(returnValue, (theSegment, valKp, thisKfitting, thisKpipe, thisK, thisPipeLength))\n end\n return (returnValue)\nend\n\nfunction addToBlockMatrix(gBM, localMatrix, gR, gC, eqnType, varType, numLocalRows, numLocalColumns)\n # we will traverse the localMatrix and place the entries in the global block matrix\n # gR and gC are the table of indices that map gR[eqnType,i] to the row in global matrix\n # and gC[varType,j] to the column in the global matrix\n # eqnType and varType refer to which block\n # numLocalRows and Columns tells us how many local entries are avalable\n\n for i = 1:numLocalRows\n for j = 1:numLocalColumns\n gi = gR[eqnType,i]\n gj = gC[varType,j]\n gBM[gi,gj] = localMatrix[i,j]\n end\n end\n return(3.14)\nend\n\n\n\nfunction addToBlockRHS(gBv, localVec, gR, eqnType, numLocalRows)\n # we will traverse the localMatrix and place the entries in the global block matrix\n # gR and gC are the table of indices that map gR[eqnType,i] to the row in global matrix\n # and gC[varType,j] to the column in the global matrix\n # eqnType and varType refer to which block\n # numLocalRows and Columns tells us how many local entries are avalable\n\n for i = 1:numLocalRows\n gi = gR[eqnType,i]\n gBv[gi] = localVec[i]\n end\n return(3.14)\nend\n\n# create routines to extract results\n# extractFromBlockSolution(testSolution, globalColumn, j (which type is it),columnsInSegment[j])\nfunction extractFromBlockSoln(gBx, gR, varType, numLocalRows)\n # we will traverse the appropriate entries in the global block matrix\n # gR is the vector of indices that map gR[varType,i] to the row in global solution vector\n # varType refer to which block\n # numLocalRows tells us how many local entries are avalable\n\n localX=zeros(numLocalRows,1)\n for i = 1:numLocalRows\n gi = gR[varType,i]\n localX[i] = gBx[gi]\n end\n return(localX)\nend\n\n# create routines to extract results\n# extractFromBlockSolution(testSolution, globalColumn, j (which type is it),columnsInSegment[j])\nfunction catIt(dfHydraulic1, dfHydraulic2, dfAll)\n # dfAll has all of the rows, we need to fill in blank rows for the other dfs\n\n localX=zeros(numLocalRows,1)\n for i = 1:numLocalRows\n gi = gR[varType,i]\n localX[i] = gBx[gi]\n end\n return(localX)\nend\n\n# create routines to extract results\nfunction extractResults(gBx, lines, connectivity, nodeList, fittingList)\n # we will traverse the solutions in the block x vector\n # lines is the df with the segments defined\n # connectivity is the connectivity df\n # we will find all of the from entries in the connectivity matrix\n numLines = getSize(connectivity)\n numHydraulicLines = getSize(connectivity) \n numNodes = getSize(nodeList)\n\n columnsInSegment = getColumnsInSegment(numLines,numNodes)\n globalColumn = variableMapping(numLines, numNodes, columnsInSegment)\n\n ourDetails = (Hydraulics2.getReynolds(lines))\n\t# note that fittingList is a really long vector with every fitting\n ourElementK = getElementK(ourDetails, fittingList)\n Km = getResistanceMatrix(ourDetails, ourElementK, connectivity) # this is an actual matrix\n segLength = getSegLength(connectivity,fittingList) # dataframe for length and other stuff\n\n segList = copy(connectivity[:,:Segment])\n nList = copy(nodeList[:,:Node]) \n\n # connectivity, used for pressure continuity\n localA = getConnectivity(connectivity,nodeList)\n \n # extract all of the entries with +1 and -1\n fromA = max.(localA, 0)\n toA = -min.(localA, 0)\n\n varType = 1 # mass flow\n xMassFlow = extractFromBlockSoln(gBx, globalColumn, varType, columnsInSegment[varType])\n\n varType = 2 # mass flow^2\n xMassFlow2 = extractFromBlockSoln(gBx,globalColumn,varType,columnsInSegment[varType])\n\n\n varType = 3 # DP\n xDP = extractFromBlockSoln(gBx,globalColumn,varType,columnsInSegment[varType])\n\n varType = 4 # node pressure\n xPnode = extractFromBlockSoln(gBx,globalColumn,varType,columnsInSegment[varType])\n fromP = fromA*xPnode\n toP = toA*xPnode\n\n\n # messy, but it works\n# allResults = [segList xMassFlow xDP fromP toP Konly]\n allResults = [segList xMassFlow xDP fromP toP]\n\n\n# returnVal = DataFrame(Segment=allResults[:,1], massFlow=allResults[:,2], dp=allResults[:,3], fromP=allResults[:,4], toP=allResults[:,5], elementK=allResults[:,6])\n\n returnVal = DataFrame(Segment=allResults[:,1], massFlow=allResults[:,2], dp=allResults[:,3], fromP=allResults[:,4], toP=allResults[:,5], fromNode=connectivity[:,:inNode], toNode=connectivity[:,:outNode], segmentLength=segLength[:,:pipeLength])\n\n\n return(returnVal)\nend\n\nfunction getSize(df)\n # get the number of rows\n return(size(df)[1])\nend\n\nfunction getColumnsInSegment(numLines, numNodes)\n # define the number of variables in each of the different types of variables\n numEqnTypes = 5 # not used\n numVarTypes = 4 # m, m2, dp, p\n\n columnsInSegment = zeros(Int64,numVarTypes,1)\n columnsInSegment[1] = numLines\n columnsInSegment[2] = numLines\n columnsInSegment[3] = numLines\n columnsInSegment[4] = numNodes\n \n return(columnsInSegment)\nend\n\nfunction variableMapping(numLines, numNodes, columnsInSegment)\n # create the variable mapping as a 2 D array\n # map[row,column] = global index\n # row is the type of variable (m, m2, dp, p)\n # column contains the index for each of the available variables in the global vector\n # function to count number of equations and variables\n numEqnTypes = 5 # not used\n numVarTypes = 4 # m, m2, dp, p\n\n maxOtherIndex = numLines + numNodes\n globalColumn = zeros(Int64,numVarTypes,maxOtherIndex)\n\n index = 1\n for i = 1:size(columnsInSegment)[1]\n for j = 1:columnsInSegment[i]\n globalColumn[i,j] = index\n index += 1\n end\n end\n \n return(globalColumn)\nend\n\nfunction doNetworkHydraulics(lineHydraulics, fluidList, connectivity, dofList, nodeList, fittingList)\n # there is a lot of code here. I do not want the user typing this. It should only be function calls\n #\n # check input data\n # numLines = checkSegments(lineHydraulics)\n # numNodes = checkNodes\n # I have a DOF check in the code\n # or numLines = getSize(lineHydraulics)\n # or numNodes = getSize(nodeList)\n # variableMapping = getVariableMapping(numLines, numNodes)\n #\n # resultVector = doHydraulics(lineHydraulics, fluidList,dofList,nodeList)\n # Then we need to create a new table with the segment results\n # and we need another table with the pressures\n #\n # then do this\n # segmentResults = extractResults(\"segment\", lineHydraulics, resultVector)\n # nodeResults = extractResults(\"node\", lineHydraulics, resultVector)\n # I could supply a list of dataframe names to include in the results\n #\n\n # driver script\n addFluidProperties(lineHydraulics,fluidList)\n addPipeProperties(lineHydraulics)\n\n # and this is where we need to initialize\n # return the matrix of mass flow and m2\n # I will need to provide the connectivity df as well to get all of the fields\n massFlow = initializeMassFlow(lineHydraulics,connectivity) # if we do not have a mass flow, make one up\n\n # pass the mass flow matrix\n #and set the Reynolds number and friction factor to a reasonable value\n hydraulicParameters = initializeHydraulicParameters(40000.0, lineHydraulics)\n\n\n numLines = size(connectivity)[1]\n numResistance = size(lineHydraulics)[1]\n numNodes = size(nodeList)[1];\n #C = zeros(Float64,numLines,numNodes)\n\n segList = copy(connectivity[:,:Segment])\n# segList = copy(lineHydraulics[:,:Segment])\n nList = copy(nodeList[:,:Node]) \n\n # connectivity, used for pressure continuity\n # each row defines a segment: we have the inlet and outlet node\n # I don't think I need the lineHydraulics df\n Amatrix = getConnectivity(connectivity,nodeList)\n # I think I only need to assemble the block matrix.\n Ia = zeros(Float64,numLines,numLines)\n for i = 1:numLines\n Ia[i,i] = 1.0; \n end;\n\n\n # create the mass balance matrix\n Bprelim = Amatrix'\n Bmatrix = removeTrivialRows(Bprelim);\n\n # I need to create the constraint equations\n # use the connectivity df instead of lineHydraulics\n Cm = getConstraintMatrix(dofList, \"flowRate\", connectivity, nodeList)\n Cp = getConstraintMatrix(dofList, \"pressure\", connectivity, nodeList)\n xc = getConstraintMatrix(dofList, \"value\", connectivity, nodeList);\n \n # need to define where each matrix will go.\n # sure I could move this outside the loop, but it should not slow things down much\n # need vectors for the number of rows and columns in each segment\n # I could put most of this batch of code in a function\n # let \n # l = num lines\n # n = num nodes\n # k = resistance calcs\n # d = degrees of freedom\n\n # num unknonws = 3*l + n\n # count equations\n # num of mass balance relations = num rows in B\n # quadratic equations = l\n # resistance eqns = k\n # pressure connectivity = l\n # degree of freedom = d\n \n # the block matrix is\n # 1. 2. 3. 4. \n # m, m2, dp, p | rhs\n # 1 B, 0, 0, 0 | 0\n # 2 Qm,Qm2, 0, 0 | xq\n # 3 0,-Km,Iseg, 0 | 0\n # 4 0, 0, -I, Am | 0\n # 5 Cm, 0, 0, Cp | xc\n\n\n\n # function to count number of equations and variables\n # edit this to account fo rnumber of resistances\n numEqnTypes = 5\n numVarTypes = 4\n rowsInSegment = zeros(Int64,numEqnTypes,1)\n rowsInSegment[1] = size(Bmatrix)[1]\n rowsInSegment[2] = numLines\n rowsInSegment[3] = numResistance\n rowsInSegment[4] = numLines\n rowsInSegment[5] = size(dofList)[1]\n\n columnsInSegment = zeros(Int64,numVarTypes,1)\n columnsInSegment[1] = numLines\n columnsInSegment[2] = numLines\n columnsInSegment[3] = numLines\n columnsInSegment[4] = numNodes\n\n numEquations = sum(rowsInSegment)\n numVariables = sum(columnsInSegment)\n\n # I need this screening as a preliminary check\n (numEquations != numVariables) ? error(\"error: \", numEquations, \" equations and \", numVariables, \" variables\") : println(\"OK: \", numEquations, \" equations and variables\")\n\n # this dozen lines could go into a function\n # I could create a matrix with global indices\n # globalRow[segment][localRow]\n # globalColumn[segment][localColumn]\n maxOtherIndex = numLines + numNodes\n globalRow = zeros(Int64,numEqnTypes,maxOtherIndex)\n globalColumn = zeros(Int64,numVarTypes,maxOtherIndex)\n\n index = 1\n for i = 1:size(rowsInSegment)[1]\n for j = 1:rowsInSegment[i]\n globalRow[i,j] = index\n index += 1\n end\n end\n\n index = 1\n for i = 1:size(columnsInSegment)[1]\n for j = 1:columnsInSegment[i]\n globalColumn[i,j] = index\n index += 1\n end\n end\n\n # define the global block matrix and vector\n\n nGlobalRow = maximum(globalRow)\n nGlobalColumn = maximum(globalColumn)\n gBM = zeros(Float64,nGlobalRow,nGlobalColumn) # global block matrix\n gBv = zeros(Float64,nGlobalRow,1) # global block vector\n gBx = zeros(Float64,nGlobalRow,1) # global block solution\n\n epsM = 0.01 # mass flow kg/h\n maxIter = 15\n\n errM = 100.0\n iter = 0\n\n # and this is where we need to iterate\n\n while ((errM > epsM) && (iter < maxIter) )\n # the resistance matrix is not applied to segments that are control valves\n ourElementK = getElementK(hydraulicParameters, fittingList)\n Km = getResistanceMatrix(hydraulicParameters, ourElementK, connectivity)\n Iseg = getSegmentIMatrix(hydraulicParameters, connectivity)\n\n # we need the quadratic matrix.\n # must realize that our lineHydraulic table is not the definative source of infomration\n # for this\n # we should use the connectivity table\n # Or do we create a simple table for only mass flow and m2?\n # m2 = 2 m M - M M\n # m2 - 2 m M = -M M\n # change this from lineHydraulics to massFlow\n # why does massFlow not work?\n# Qm2 = getQuadraticMatrix(lineHydraulics, \"quadratic\")\n# Qm = getQuadraticMatrix(lineHydraulics, \"linear\")\n# xq = getQuadraticMatrix(lineHydraulics, \"rhs\");\n\n Qm2 = getQuadraticMatrix(massFlow, \"quadratic\")\n Qm = getQuadraticMatrix(massFlow, \"linear\")\n xq = getQuadraticMatrix(massFlow, \"rhs\");\n\n\n\n # the block matrix is\n # 1. 2. 3. 4. \n # m, m2, dp, p | rhs\n # 1 B, 0, 0, 0 | 0\n # 2 Qm,Qm2, 0, 0 | xq\n # 3 0,-Km,Iseg, 0 | 0\n # 4 0, 0, -I, Am | 0\n # 5 Cm, 0, 0, Cp | xc\n #\n # P1 - P2 = K.m2, where P1 is in, P2 is out\n # DP = K.m2\n # P1 - P2 = DP\n # or\n # -K.m2 + DP = 0\n # -DP + P1 - P2 = 0\n\n # once I have the answer, how do I get inlet and outlet pressure for each segment.\n # The A matrix contains the information\n # The rows in A are for each segment.\n # columns with +1 are inlet, -1 are outlet.\n # Transform the A matrix by extracting the entries with +1. Then matrix multiply.\n # then get the entries with -1 and matrix multiply.\n\n\n\n # assemble the global block matrix\n i = 1\n j = 1\n addToBlockMatrix(gBM,Bmatrix,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n\n i = 2\n j = 1\n addToBlockMatrix(gBM,Qm,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n\n i = 2\n j = 2\n addToBlockMatrix(gBM,Qm2,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n addToBlockRHS(gBv, xq, globalRow, i, rowsInSegment[i])\n\n\n i = 3\n j = 2\n addToBlockMatrix(gBM,-Km,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n\n i = 3\n j = 3\n addToBlockMatrix(gBM,Iseg,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n\n i = 4\n j = 3\n addToBlockMatrix(gBM,-Ia,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n\n i = 4\n j = 4\n addToBlockMatrix(gBM,Amatrix,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n\n i = 5\n j = 1\n addToBlockMatrix(gBM,Cm,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n\n i = 5\n j = 4\n addToBlockMatrix(gBM,Cp,globalRow,globalColumn,i,j,rowsInSegment[i],columnsInSegment[j])\n addToBlockRHS(gBv, xc, globalRow, i, rowsInSegment[i])\n\n # and solve\n testSoln = gBM \\ gBv\n\n # convergnece\n# errM = maximum(abs.(lineHydraulics[:,:massFlow] - testSoln[1:numLines]))\n\n errM = maximum(abs.(massFlow[:,:massFlow] - testSoln[1:numLines]))\n\n iter += 1\n\n\n # update the mass flow rate solutions\n massFlow[:,:massFlow] = testSoln[1:numLines]\n for i = 1:numResistance\n ii = indexLookup(lineHydraulics[i,:Segment], connectivity[:,:Segment])\n lineHydraulics[i,:massFlow] = testSoln[ii]\n end\n\n # then I need to update the hydraulic parameters\n hydraulicParameters = Hydraulics2.getReynolds(lineHydraulics)\n # and I need to update the pressures and DP estimates\n\n gBx = testSoln\n end\n return (gBx)\nend\n\n# create routines to extract results\n# extractFromBlockSolution(testSolution, globalColumn, j (which type is it),columnsInSegment[j])\nfunction combineResults(dfAllResults, dfLines)\n # dfAll has all of the rows\n # dfLines has the pressur drop hydraulic info\n # do an innerjoin to produce a single table\n\n hydraulicDetails = (Hydraulics2.getReynolds(dfLines));\n combined1=outerjoin(dfAllResults, hydraulicDetails, on = intersect(names(dfAllResults), names(hydraulicDetails)), makeunique=false,indicator=nothing,validate=(false,false));\n combined2=outerjoin(combined1, dfLines, on = intersect(names(combined1), names(dfLines)), makeunique=false,indicator=nothing,validate=(false,false));\n\n return(combined2)\nend\n\n\nend # module\n\n", "meta": {"hexsha": "1faf442892243f164ce3631721d9939bebbe8b8c", "size": 43176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Hydraulics2.jl", "max_stars_repo_name": "kevindorma/Hydraulics2.jl", "max_stars_repo_head_hexsha": "331009cc9417b560eb9442fdf8e1e85d1c5d416f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Hydraulics2.jl", "max_issues_repo_name": "kevindorma/Hydraulics2.jl", "max_issues_repo_head_hexsha": "331009cc9417b560eb9442fdf8e1e85d1c5d416f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Hydraulics2.jl", "max_forks_repo_name": "kevindorma/Hydraulics2.jl", "max_forks_repo_head_hexsha": "331009cc9417b560eb9442fdf8e1e85d1c5d416f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8395904437, "max_line_length": 247, "alphanum_fraction": 0.6597183621, "num_tokens": 12396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.1966437547775947}} {"text": "# Functions related to an individual's genome:\n# - meiosis\n# - mutation\n# - genome creation\n# - auxiliary functions\n\n\"\"\"\n meiosis(genome, maternal)\n\nCarry out meiosis on a genome (marked as maternal or not). Returns a haploid\ngamete genome. (genome => array of chromosomes)\n\"\"\"\nfunction meiosis(genome::Array{Chromosome,1}, maternal::Bool, heterozygosity::Bool)\n #NOTE This function assumes that a genome is sorted, with all paternal chromosomes\n # in the first half and all maternals in the second (or vice versa).\n gametelength = Int(length(genome)/2)\n gamete = Array{Chromosome,1}(undef, gametelength)\n i = 1\n while i <= gametelength\n rand(Bool) ? g = i : g = i+gametelength\n # We do not deepcopy parental genes for performance reasons. However, that\n # means that if these genes are to be mutated, they must be deepcopied first.\n gamete[i] = heterozygosity ? LineageChromosome(genome[g].genes, maternal, genome[g].lineage) :\n DefaultChromosome(genome[g].genes, maternal)\n i += 1\n end\n gamete\nend\n\n\"\"\"\n gettraitdict(chromosomes, traitnames)\n\nConvert a genome (an array of chromosomes) into a dict of traits and their values.\n\"\"\"\nfunction gettraitdict(chrms::Array{Chromosome, 1}, traitnames::Array{String, 1})\n #TODO can this be made more efficient? It's called really often...\n traitdict = Dict{String, Float64}()\n traits = Array{Trait,1}()\n nchrms = 0\n ngenes = 0\n for chrm in chrms\n nchrms += 1\n for gene in chrm.genes\n ngenes += 1\n append!(traits, gene.codes)\n end\n end\n for traitidx in eachindex(traitnames)\n wantedtraits = skipmissing(map(x -> x.value, filter(x -> x.nameindex == traitidx, traits)))\n traitdict[traitnames[traitidx]] = mean(wantedtraits)\n traitdict[traitnames[traitidx] * \"sd\"] = std(wantedtraits)\n end\n traitdict[\"ngenes\"] = ngenes\n traitdict[\"nlnkgunits\"] = nchrms\n traitdict\nend\n\n\"\"\"\n gettraitdictfast(chromosomes, traitnames)\n\nConvert a genome (an array of chromosomes) into a dict of traits and their values.\nThis is an optimised version that can be run if `degpleiotropy` is 0 and `linkage` is \"none\".\n\"\"\"\nfunction gettraitdictfast(chrms::Array{Chromosome, 1}, traitnames::Array{String, 1})\n # Makes use of the fact that with `degpleiotropy == 0` and `linkage == \"none\"`,\n # there is exactly one trait per chromosome (one gene per chromosome and one trait per gene),\n # and the chromosomes are arranged in trait-order.\n genomesize = length(chrms)\n traitdict = Dict{String, Float64}()\n haploidlength = Int(genomesize/2)\n values = Array{Float64,}(undef,genomesize)\n for c in eachindex(chrms)\n @inbounds values[c] = chrms[c].genes[1].codes[1].value\n end\n for traitidx in eachindex(traitnames)\n wantedtraits = (values[traitidx], values[traitidx+haploidlength])\n traitdict[traitnames[traitidx]] = mean(wantedtraits)\n traitdict[traitnames[traitidx] * \"sd\"] = std(wantedtraits)\n end\n traitdict[\"ngenes\"] = genomesize\n traitdict[\"nlnkgunits\"] = genomesize\n traitdict\nend\n\n\"\"\"\n getseqsimilarity(seqone, seqtwo)\n\nCompare two strings and return similarity.\n\"\"\"\nfunction getseqsimilarity(indgene::AbstractString, mategene::AbstractString)\n basediffs = 0\n #FIXME this should find out whether indgene or mategene is shorter and use that,\n # then count the length difference towards the base diff\n for i in eachindex(indgene)\n try\n indgene[i] != mategene[i] && (basediffs += 1) # alternatively use bioinformatics tools\n catch # e.g., in case of differently long genes\n basediffs += 1\n end\n end\n seqidentity = 1 - (basediffs / length(indgene))\nend\n\n\"\"\"\n getseqs(genome, traitname)\n\nFind and return the sequences of genes that code for the given trait.\n\"\"\"\nfunction getseqs(genome::Array{Chromosome, 1}, traitname::String)\n seqs = String[]\n traitidx = findfirst(x -> x == traitname, setting(\"traitnames\"))\n for chrm in genome\n for gene in chrm.genes\n if any(x -> x.nameindex == traitidx, gene.codes)\n setting(\"compressgenes\") ? push!(seqs, num2seq(gene.sequence)) : push!(seqs, gene.sequence)\n end\n end\n end\n seqs\nend\n\n\"\"\"\n iscompatible(mate, individual)\n\nCheck to see whether two individual organisms are reproductively compatible by\ncomparing gene sequences (which sequence depends on setting(\"speciation\")).\n\"\"\"\nfunction iscompatible(mate::Individual, ind::Individual)\n mate.lineage != ind.lineage && return false\n indgenes, mategenes = \"\", \"\"\n if setting(\"speciation\") == \"off\"\n return true # all conspecifics are compatible, no speciation can happen\n elseif setting(\"speciation\") == \"neutral\"\n # default, use a non-coding sequence for mutation-order speciation\n indgenes = join(getseqs(ind.genome, \"compat\"))\n mategenes = join(getseqs(mate.genome, \"compat\"))\n elseif setting(\"speciation\") == \"ecological\"\n # use all coding sequences for ecological speciation\n for tr in setting(\"traitsforecospec\")\n (tr == \"compat\") && continue\n indgenes *= join(getseqs(ind.genome, tr))\n mategenes *= join(getseqs(mate.genome, tr))\n end\n end\n seqidentity = getseqsimilarity(indgenes, mategenes)\n seqidentity >= ind.traits[\"seqsimilarity\"]\nend\n\n\"\"\"\n seq2num(sequence)\n\nConvert a DNA base sequence (a string) into binary and then into an integer.\nThis saves memory.\n\"\"\"\n#XXX Actually, this hardly seems to make a difference :-(\nfunction seq2num(sequence::String)\n # This function effectively uses the same technique as seq2bignum, but it skips the\n # intermediate allocations and should therefore be more efficient.\n num::Int64 = 0 # Int64 allows for max length of 21bp\n for b in eachindex(sequence)\n if sequence[end+1-b] == 'a'\n num += 2^(3*(b-1)) * 4 # b'100'\n elseif sequence[end+1-b] == 'c'\n num += 2^(3*(b-1)) * 5 # b'101'\n elseif sequence[end+1-b] == 'g'\n num += 2^(3*(b-1)) * 6 # b'110'\n elseif sequence[end+1-b] == 't'\n num += 2^(3*(b-1)) * 7 # b'111'\n end\n end\n num\nend\n\nfunction intseq(n::Int)\n #XXX doesn't seem to work either? I'm starting to think I'm optimising in the wrong place :-(\n num::Int64 = 0 # Int64 allows for max length of 21bp\n for b in 0:(n-1)\n # basically like seq2bignum(), but skips all intermediate allocations\n num += 2^(3*b) * rand(4:7)\n end\n num\nend\n\n\"\"\"\n seq2bignum(sequence)\n\nConvert a DNA base sequence (a string) into binary and then into a BigInt (for\nlarger genes). This saves memory.\n\"\"\"\nfunction seq2bignum(sequence::String)\n bases = \"acgt\"\n binary = \"\"\n for base in sequence\n binary *= string(findfirst(x -> x == base, bases) + 3, base = 2)\n end\n parse(BigInt, binary, base = 2) # BigInt allows arbitrary-length sequences\nend\n\n\"\"\"\n num2seq(n)\n\nConvert an integer into binary and then into a DNA base sequence string.\n\"\"\"\nfunction num2seq(n::Integer)\n bases = \"acgt\"\n binary = string(n, base = 2)\n sequence = \"\"\n for i in 1:3:(length(binary) - 2)\n sequence *= string(bases[parse(Int, binary[i:(i + 2)], base = 2) - 3])\n end\n sequence\nend\n\n\"\"\"\n createtraits()\n\nCreate an array of trait objects generated from the default trait values (with a\nrandom offset).\n\"\"\"\nfunction createtraits()\n #XXX this is all very ugly. (case/switch w/ v. 2.0+?)\n traitnames = setting(\"traitnames\")\n traits = Array{Trait,1}(undef,length(traitnames))\n # exponential distributions of body sizes:\n repoffset = setting(\"maxrepsize\") - setting(\"minrepsize\")\n seedoffset = setting(\"maxseedsize\") - setting(\"minseedsize\")\n tempoffset = setting(\"maxtemp\") - setting(\"mintemp\")\n precoffset = setting(\"maxprec\") - setting(\"minprec\")\n #FIXME this needs to be changed to account for allometric relationships\n repsize, seedsize = 0, 0\n while true \n repsize = exp(setting(\"minrepsize\") + repoffset * rand())\n seedsize = exp(setting(\"minseedsize\") + seedoffset * rand())\n repsize > seedsize && break\n end\n for idx in eachindex(traitnames)\n if occursin(\"dispshape\", traitnames[idx])\n traits[idx] = Trait(idx, rand() * setting(\"dispshape\"))\n elseif occursin(\"dispmean\", traitnames[idx])\n traits[idx] = Trait(idx, rand() * setting(\"dispmean\"))\n elseif occursin(\"precopt\", traitnames[idx])\n traits[idx] = Trait(idx, setting(\"minprec\") + rand() * precoffset)\n elseif occursin(\"prectol\", traitnames[idx])\n traits[idx] = Trait(idx, rand() * setting(\"maxbreadth\"))\n elseif occursin(\"repsize\", traitnames[idx])\n traits[idx] = Trait(idx, repsize)\n elseif occursin(\"seqsimilarity\", traitnames[idx]) && setting(\"fixtol\")\n traits[idx] = Trait(idx, setting(\"tolerance\"))\n elseif occursin(\"seqsimilarity\", traitnames[idx]) && !setting(\"fixtol\")\n traits[idx] = Trait(idx, rand()) # assortative mating might evolve\n elseif occursin(\"seedsize\", traitnames[idx])\n traits[idx] = Trait(idx, seedsize)\n elseif occursin(\"tempopt\", traitnames[idx])\n traits[idx] = Trait(idx, setting(\"mintemp\") + rand() * tempoffset)\n elseif occursin(\"temptol\", traitnames[idx])\n traits[idx] = Trait(idx, rand() * setting(\"maxbreadth\"))\n else\n traits[idx] = Trait(idx, rand())\n end\n end\n traits\nend\n\n\"\"\"\n creategenes(ngenes, traits)\n\nRandomly create a given number of gene objects, with their base sequence and\nassociated traits. Returns the result as an array of AbstractGenes.\n\"\"\"\nfunction creategenes(ngenes::Int, traits::Array{Trait,1})\n genes = Array{AbstractGene,1}(undef, ngenes)\n bases = ['a','c','g','t']\n compatidx = findfirst(x -> x == \"compat\", setting(\"traitnames\"))\n # initialise each gene with an arbitrary sequence\n for i in 1:ngenes\n if setting(\"compressgenes\") #default\n genes[i] = Gene(intseq(setting(\"smallgenelength\")), Trait[])\n else\n sequence = String(rand(bases, setting(\"smallgenelength\")))\n genes[i] = StringGene(sequence, Trait[])\n end\n end\n # assign traits to the genes\n if setting(\"degpleiotropy\") == 0\n # Disable polygenic inheritance and pleiotropy: make sure one gene codes for one trait.\n for tr in eachindex(traits)\n (tr == compatidx) && (genes[tr] = createcompatgene(bases, compatidx))\n genes[tr].codes = [traits[tr]]\n end\n else # allow for pleiotropy as well as polygenic inheritance\n for trait in traits\n (trait.nameindex == compatidx) && continue\n # We're actually setting polygenic inheritance here, rather than pleiotropy.\n # Pleiotropy is introduced indirectly, because a higher number of coding genes\n # increases the likelihood of picking a gene that already codes for other traits.\n ncodinggenes = rand(Geometric(1 - setting(\"degpleiotropy\"))) + 1\n codinggenes = rand(genes,ncodinggenes)\n for gene in codinggenes\n push!(gene.codes,deepcopy(trait))\n end\n end\n push!(genes, createcompatgene(bases, compatidx))\n end\n genes\nend\n\n\"\"\"\n createcompatgene(bases, compatidx)\n\nCreate the gene that is used to determine reproductive compatibility.\n\"\"\"\nfunction createcompatgene(bases::Array{Char,1}, compatidx::Int)::AbstractGene\n # Note: we only need big genes for the compatibility gene, because we need a longer base\n # sequence than offered by `smallgenelength` if we want to do phylogenetic analyses.\n setting(\"usebiggenes\") ? seql = setting(\"biggenelength\") : seql = setting(\"smallgenelength\")\n cseq = String(rand(bases, seql))\n ctrait = [Trait(compatidx, 0.5)]\n if setting(\"compressgenes\")\n if setting(\"usebiggenes\")\n return BigGene(seq2bignum(cseq), ctrait)\n else\n return Gene(seq2num(cseq), ctrait)\n end\n else\n return StringGene(cseq, ctrait)\n end\nend\n\n\"\"\"\n createchrms(nchrms, genes)\n\nRandomly distribute the passed genes into the given number of haploid chromosomes.\nReturns a diploid genome (array of chromosome objects).\n\"\"\"\nfunction createchrms(nchrms::Int,genes::Array{AbstractGene,1},lineage::String)::Array{Chromosome,1}\n chromosomes = Array{Chromosome,1}(undef,nchrms*2)\n if nchrms == 1 # linkage == \"full\"\n chromosomes[1] = @Chromosome(genes, true, lineage)\n chromosomes[2] = @Chromosome(deepcopy(genes),false, lineage)\n elseif nchrms == length(genes) # linkage == \"none\"\n for g in eachindex(genes)\n chromosomes[g] = @Chromosome([genes[g]], true, lineage)\n chromosomes[nchrms+g] = @Chromosome([deepcopy(genes[g])], false, lineage)\n end\n else # linkage == \"random\"\n chrmsplits = sort(rand(1:length(genes), nchrms-1))\n for chr in 1:nchrms\n if chr==1 # first chromosome\n cgenes = genes[1:chrmsplits[chr]]\n elseif chr==nchrms # last chromosome\n cgenes = genes[(chrmsplits[chr-1]+1):end]\n else\n cgenes = genes[(chrmsplits[chr-1]+1):chrmsplits[chr]]\n end\n chromosomes[chr] = @Chromosome(cgenes, true, lineage)\n chromosomes[nchrms+chr] = @Chromosome(deepcopy(cgenes), false, lineage)\n end\n end\n chromosomes\nend\n\n\"\"\"\n varyalleles!(genes, locivar)\n\nMutate gene traits in the passed array of genes.\n\"\"\"\nfunction varyalleles!(genes::Array{AbstractGene, 1}, locivar::Float64)\n locivar == 0 && return\n for gene in genes\n mutate!(gene.codes, locivar)\n end\nend\n\n\"\"\"\n varyalleles!(chromosomes, locivar)\n\nMutate gene traits in the passed array of chromosomes.\n\"\"\"\nfunction varyalleles!(chrms::Array{Chromosome, 1}, locivar::Float64)\n locivar == 0 && return\n for chrm in chrms\n varyalleles!(chrm.genes, locivar)\n end\nend\n\n\"\"\"\n mutate!(traits, locivar)\n\nLoop over an array of traits, mutating each value in place along a normal distribution.\n`locivar` can be used to scale the variance of the normal distribution used to draw new\ntrait values (together with `setting(phylconstr]`).\n\"\"\"\nfunction mutate!(traits::Array{Trait, 1}, locivar::Float64 = 1.0)\n setting(\"phylconstr\") * locivar == 0 && return\n for trait in traits\n traitname = setting(\"traitnames\")[trait.nameindex]\n occursin(\"seqsimilarity\", traitname) && setting(\"fixtol\") && continue\n oldvalue = trait.value\n occursin(\"tempopt\", traitname) && (oldvalue -= 273)\n while oldvalue <= 0 # make sure sd of Normal dist != 0\n oldvalue = abs(rand(Normal(0,0.01)))\n end\n newvalue = rand(Normal(oldvalue, oldvalue * setting(\"phylconstr\") * locivar))\n #FIXME there are no traits with \"prob\" in their name?!\n # Is this meant to cap compat/seqsimilarity/selfing?\n (newvalue > 1 && occursin(\"prob\", traitname)) && (newvalue=1.0)\n while newvalue <= 0\n newvalue = rand(Normal(oldvalue, oldvalue * setting(\"phylconstr\") * locivar))\n end\n occursin(\"tempopt\", traitname) && (newvalue += 273)\n trait.value = newvalue\n end\nend\n\n\"\"\"\n mutate!(individual, temp)\n\nMutate an individual's genome (sequence and traits) in place.\n\"\"\"\nfunction mutate!(ind::Individual, temp::Float64)\n muts = setting(\"mutationrate\") * exp(-act/(boltz*temp))\n nmuts = rand(Poisson(muts))\n nmuts == 0 && return\n chrmidcs = rand(eachindex(ind.genome), nmuts)\n for c in chrmidcs\n # We need to deepcopy genes here, because they are not automatically deepcopied during\n # reproduction for performance reasons\n ind.genome[c] = deepcopy(ind.genome[c])\n length(ind.genome[c].genes) == 0 && continue\n g = rand(eachindex(ind.genome[c].genes))\n gseq = ind.genome[c].genes[g].sequence\n setting(\"compressgenes\") ? charseq = collect(num2seq(gseq)) : charseq = collect(gseq)\n i = rand(eachindex(charseq))\n newbase = rand(collect(\"acgt\"),1)[1]\n while newbase == charseq[i]\n newbase = rand(collect(\"acgt\"),1)[1]\n end\n charseq[i] = newbase\n mutate!(ind.genome[c].genes[g].codes)\n if setting(\"compressgenes\")\n if length(charseq) > 21\n ind.genome[c].genes[g].sequence = seq2bignum(String(charseq))\n else\n ind.genome[c].genes[g].sequence = seq2num(String(charseq))\n end\n else\n ind.genome[c].genes[g].sequence = String(charseq)\n end\n end\n if setting(\"degpleiotropy\") == 0 && setting(\"linkage\") == \"none\"\n ind.traits = gettraitdictfast(ind.genome, setting(\"traitnames\"))\n else\n ind.traits = gettraitdict(ind.genome, setting(\"traitnames\"))\n end\nend\n\n\"\"\"\n mutate!(patch)\n\nMutate all seed individuals in a patch.\n\"\"\"\nfunction mutate!(patch::Patch)\n setting(\"mode\") == \"zosterops\" ? temp = setting(\"bodytemp\") : temp = patch.temp\n for ind in patch.seedbank\n mutate!(ind, temp)\n end\nend\n\n\"\"\"\n mutate!(world)\n\nMutate the world. (That sounds scary!)\n\"\"\"\nfunction mutate!(world::Array{Patch, 1})\n for patch in world\n (patch.isisland || !setting(\"static\")) && mutate!(patch)\n end\nend\n", "meta": {"hexsha": "a202e7d1ce05c2042a5d0aaa055fdc4814f7183f", "size": 17491, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/genetics.jl", "max_stars_repo_name": "CCTB-Ecomods/gemm", "max_stars_repo_head_hexsha": "44c2edf5408288694f5d0120509721208912a393", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-29T11:19:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T10:35:50.000Z", "max_issues_repo_path": "src/genetics.jl", "max_issues_repo_name": "CCTB-Ecomods/gemm", "max_issues_repo_head_hexsha": "44c2edf5408288694f5d0120509721208912a393", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/genetics.jl", "max_forks_repo_name": "CCTB-Ecomods/gemm", "max_forks_repo_head_hexsha": "44c2edf5408288694f5d0120509721208912a393", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.51565762, "max_line_length": 107, "alphanum_fraction": 0.6427305471, "num_tokens": 4633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1960000946234293}} {"text": "\nmodule Cqdldl\n\nusing SparseArrays\nusing LinearAlgebra\n\nusing QDLDL_jll\nconst libqdldl = QDLDL_jll.libqdldl\n\nconst QDLDL_int = Clonglong\nconst QDLDL_float = Cdouble\nconst QDLDL_bool = Cuchar\n\nexport QDLDLException, QDLDLSolver\n\nstruct QDLDLException <: Exception\n msg::String\nend\n\nBase.@kwdef mutable struct QDLDLFlags\n haselimtree::Bool = false\n isfactordone::Bool = false\n isfactorsuccess::Bool = false\nend\n\nmutable struct QDLDLBufferDims{Ti}\n n::Ti # current dimension\n n0::Ti # max dimension size\n nnzA0::Ti # max nnzA\n nnzL0::Ti # max nnzL\nend\n\nstruct QDLDLSolver{Tv <: Union{Float32, Float64}, Ti <: Integer}\n flags::QDLDLFlags\n dims::QDLDLBufferDims{Ti}\n Ap::Vector{Ti}\n Ai::Vector{Ti}\n Ax::Vector{Tv}\n work::Vector{Ti}\n Lnz::Vector{Ti}\n etree::Vector{Ti}\n Lp::Vector{Ti}\n Li::Vector{Ti}\n Lx::Vector{Tv}\n D::Vector{Tv}\n Dinv::Vector{Tv}\n bwork::Vector{QDLDL_bool}\n iwork::Vector{Ti}\n fwork::Vector{Tv}\n # L::SparseMatrixCSC{Tv,Ti}\n function QDLDLSolver{Tv}(n::Integer, nnzA::Integer, nnzL::Integer) where Tv\n n, nnzA, nnzL = promote(n, nnzA, nnzL)\n dims = QDLDLBufferDims(n, n, nnzA, nnzL)\n Ti = typeof(n)\n\n flags = QDLDLFlags()\n Ap = zeros(Ti, n + 1)\n Ai = zeros(Ti, nnzA)\n Ax = zeros(Tv, nnzA)\n work = zeros(Ti,n)\n Lnz = zeros(Ti,n)\n etree = zeros(Ti,n)\n Lp = zeros(Ti, n+1) \n Lp[end] = nnzL \n Li = zeros(Ti, nnzL) \n Lx = zeros(Tv, nnzL) \n D = zeros(Tv, n)\n Dinv = zeros(Tv, n)\n bwork = zeros(QDLDL_bool, n)\n iwork = zeros(Ti, 3n)\n fwork = zeros(Tv, n)\n new{Tv,Ti}(flags, dims, Ap, Ai, Ax, work, Lnz, etree, Lp, Li, Lx, D, Dinv, bwork, iwork, fwork)\n end\n function QDLDLSolver(A::SparseMatrixCSC{Tv}; calctree::Bool=true) where Tv <: Union{Float32, Float64}\n Ti = QDLDL_int \n flags = QDLDLFlags()\n\n # Convert to upper triangular\n if !istriu(A)\n @warn \"A not upper triangular. Creating a new upper-triangular matrix.\"\n A = triu(A)\n end\n @assert A.n == A.m \"A must be a square matrix.\"\n n = A.n\n Ap = A.colptr .- 1 # convert to 0-based indexing\n Ai = A.rowval .- 1 # convert to 0-based indexing\n Ax = A.nzval\n work = zeros(Ti,n)\n Lnz = zeros(Ti,n)\n etree = zeros(Ti,n)\n F = new{Tv,Ti}(flags, n, Ap, Ai, Ax, work, Lnz, etree)\n if calctree\n return eliminationtree!(F)\n end\n return F\n end\n function QDLDLSolver(qdldl::QDLDLSolver{Tv,Ti}) where {Tv,Ti}\n nnzL = sum(qdldl.Lnz)\n n = qdldl.n\n nnzL = sum(qdldl.Lnz)\n if nnzL == 0 || !qdldl.flags.haselimtree\n throw(QDLDLException(\n \"Cannot initialize a complete QDLDL objective without calculating the elimination tree.\"\n ))\n end\n Lp = zeros(Ti, n+1) \n Lp[end] = nnzL \n Li = zeros(Ti, nnzL) \n Lx = zeros(Tv, nnzL) \n D = zeros(Tv, n)\n Dinv = zeros(Tv, n)\n bwork = zeros(QDLDL_bool, n)\n iwork = zeros(Ti, 3n)\n fwork = zeros(Tv, n)\n # L = SparseMatrixCSC{Tv,Ti}(n, n, copy(Li), copy(Lp), copy(Lx))\n new{Tv,Ti}(qdldl.flags,\n qdldl.n, qdldl.Ap, qdldl.Ai, qdldl.Ax, qdldl.work, qdldl.Lnz, qdldl.etree,\n Lp, Li, Lx, D, Dinv, bwork, iwork, fwork\n )\n end\nend\nBase.size(F::QDLDLSolver) = (F.dims.n, F.dims.n)\nBase.size(F::QDLDLSolver, i::Integer) = i <= 2 ? F.dims.n : 1 \n\nfunction Base.resize!(F::QDLDLSolver, n::Integer)\n if n > F.dims.n0\n @warn \"New dimension $n is greater than the buffer size $(F.dims.n0).\"\n F.dims.n0 = n\n end\n resize!(F.Ap, n+1)\n resize!(F.work, n)\n resize!(F.Lnz, n)\n resize!(F.etree, n)\n resize!(F.Lp, n+1)\n resize!(F.D, n)\n resize!(F.Dinv, n)\n resize!(F.bwork, n)\n resize!(F.iwork, 3n)\n resize!(F.fwork, n)\n F.dims.n = n\n return F\nend\n\nfunction checkfullyinitialized(F::QDLDLSolver)\n if !isdefined(F, :Lp)\n throw(QDLDLException(\n \"Cannot call factor! on an object that hasn't been initialized.\\n\" * \n \"You may need to create a new QDLDL object using QDLDL(F::QDLDL).\"\n ))\n end\nend\n\nfunction eliminationtree!(F::QDLDLSolver, A::SparseMatrixCSC; check::Bool=true)\n n = size(F,1)\n if !istriu(A)\n @warn \"A not upper triangular. Creating a new upper-triangular matrix.\"\n A = triu(A)\n end\n nnzA = nnz(A)\n if nnzA > F.dims.nnzA0\n @warn \"Nonzeros buffer size not large enough for A matrix. Increasing from $(F.dims.nnzA0) to $nnzA.\"\n F.dims.nnzA0 = nnzA\n end\n resize!(F.Ai, nnzA)\n resize!(F.Ax, nnzA)\n F.Ap .= A.colptr .- 1\n F.Ai .= A.rowval .- 1\n F.Ax .= A.nzval\n eliminationtree!(F; check=check, newsolver=false) \n nnzL = sum(F.Lnz)\n if nnzL > F.dims.nnzL0\n @warn \"Nonzeros buffer size not large enough for L matrix. Increasing from $(F.dims.nnzL0) to $nnzL.\"\n F.dims.nnzL0 = nnzL\n end\n resize!(F.Li, nnzL)\n resize!(F.Lx, nnzL)\n F.Lp[end] = nnzL\n return F\nend\n\nfunction eliminationtree!(F::QDLDLSolver; check::Bool=true, newsolver::Bool=true) \n out = qdldl_etree(F.dims.n, F.Ap, F.Ai, F.work, F.Lnz, F.etree)\n if check && out == -1 \n throw(QDLDLException(\n \"Cannot calculate the elimination tree. Matrix is not upper triangular or has an empty column.\"\n ))\n elseif check && out == -2\n throw(QDLDLException(\n \"Cannot calculate the elimination tree. Number of nonzero elements in L overflowed an $QDLDL_int.\"\n ))\n end\n F.flags.haselimtree = out >= 0 \n if out >= 0\n return newsolver ? QDLDLSolver(F) : F\n else\n return F\n end\nend\n\nfunction factor!(F::QDLDLSolver; check::Bool=true)\n if !F.flags.haselimtree\n throw(QDLDLException(\"Cannot call factor! before eliminationtree!.\"))\n end\n checkfullyinitialized(F)\n \n out = qdldl_factor(\n F.dims.n, F.Ap, F.Ai, F.Ax, F.Lp, F.Li, F.Lx, F.D, F.Dinv, F.Lnz, F.etree, F.bwork, \n F.iwork, F.fwork\n )\n if check && out == -1\n throw(QDLDLException(\n \"Cannot calculate factorization. Matrix not quasidefinite.\"\n ))\n end\n F.flags.isfactorsuccess = out != -1\n F.flags.isfactordone = true\n return F\nend\n\nfunction solve!(F::QDLDLSolver{T}, b::Vector{T}) where T\n if !F.flags.isfactordone\n throw(QDLDLException(\"Cannot call solve! before factor!.\"))\n end\n if F.dims.n != size(b,1)\n throw(DimensionMismatch(\"Cannot solve system. Expected a vector of length $(F.dims.n), got $(size(b,1))\"))\n end\n checkfullyinitialized(F)\n qdldl_solve(F.dims.n, F.Lp, F.Li, F.Lx, F.Dinv, b)\n return b\nend\n\nfunction solveL!(F::QDLDLSolver{T}, b::Vector{T}) where T\n if !F.flags.isfactordone\n throw(QDLDLException(\"Cannot call solve! before factor!.\"))\n end\n if F.dims.n != size(b,1)\n throw(DimensionMismatch(\"Cannot solve system. Expected a vector of length $(F.dims.n), got $(size(b,1))\"))\n end\n checkfullyinitialized(F)\n qdldl_Lsolve(F.dims.n, F.Lp, F.Li, F.Lx, b)\n return b\nend\n\nfunction solveLt!(F::QDLDLSolver{T}, b::Vector{T}) where T\n if !F.flags.isfactordone\n throw(QDLDLException(\"Cannot call solve! before factor!.\"))\n end\n if F.dims.n != size(b,1)\n throw(DimensionMismatch(\"Cannot solve system. Expected a vector of length $(F.dims.n), got $(size(b,1))\"))\n end\n checkfullyinitialized(F)\n qdldl_Ltsolve(F.dims.n, F.Lp, F.Li, F.Lx, b)\n return b\nend\n\n\nfunction getL(F::QDLDLSolver{Tv,Ti}) where {Tv,Ti}\n return SparseMatrixCSC{Tv,Ti}(F.dims.n, F.dims.n, F.Lp .+ 1, F.Li .+ 1, F.Lx)\nend\n\n##############################\n# Factorization Interface \n##############################\nstruct QDLDLFactorization{Tv <: Union{Float32, Float64}, Ti <: Integer} <: LinearAlgebra.Factorization{Tv}\n solver::QDLDLSolver{Tv,Ti}\nend\nQDLDLFactorization(args...) = QDLDLFactorization(QDLDLSolver(args...))\ngetsolver(F::QDLDLFactorization) = getfield(F, :solver)\n\nfunction qdldl(A::SparseMatrixCSC; check::Bool=true)\n F = QDLDLSolver(A)\n F = eliminationtree!(F)\n if F.flags.haselimtree\n factor!(F, check=check)\n end\n return QDLDLFactorization(F)\nend\n\nfunction Base.getproperty(F::QDLDLFactorization, d::Symbol)\n solver = getsolver(F)\n if d == :d\n solver.D \n elseif d == :dinv\n solver.Dinv\n elseif d == :D\n Diagonal(solver.D)\n elseif d == :Dinv\n Diagonal(solver.Dinv)\n elseif d == :L\n LowerTriangular(getL(solver))\n end\nend\n\nLinearAlgebra.issuccess(F::QDLDLFactorization) = getsolver(F).flags.isfactorsuccess\n\nfunction LinearAlgebra.logabsdet(F::QDLDLFactorization{T}) where T\n return sum(log ∘ abs, F.d), prod(sign, F.d)\nend\n\nfunction LinearAlgebra.ldiv!(F::QDLDLFactorization, b)\n solver = getsolver(F)\n solver.flags.haselimtree || eliminationtree!(solver)\n solver.flags.isfactordone || factor!(solver)\n solve!(solver, b)\nend\n\n\n##############################\n# C Interface Wrapper\n##############################\nfunction qdldl_etree(n::Int, Ap::Vector{Int}, Ai::Vector{Int}, work::Vector{Int}, \n Lnz::Vector{Int}, etree::Vector{Int}\n)\n @assert length(Ap) == n+1\n nnz = Ap[end]\n @assert length(Ai) == nnz\n @assert length(work) == n\n @assert length(Lnz) == n\n @assert length(etree) == n\n ccall((:QDLDL_etree, libqdldl), QDLDL_int,\n (QDLDL_int, Ptr{QDLDL_int}, Ptr{QDLDL_int}, Ref{QDLDL_int}, Ref{QDLDL_int}, \n Ref{QDLDL_int}),\n n, Ap, Ai, work, Lnz, etree\n )\nend\n\nfunction qdldl_factor(\n n::QDLDL_int,\n Ap::Vector{QDLDL_int},\n Ai::Vector{QDLDL_int},\n Ax::Vector{QDLDL_float},\n Lp::Vector{QDLDL_int},\n Li::Vector{QDLDL_int},\n Lx::Vector{QDLDL_float},\n D::Vector{QDLDL_float},\n Dinv::Vector{QDLDL_float},\n Lnz::Vector{QDLDL_int},\n etree::Vector{QDLDL_int},\n bwork::Vector{QDLDL_bool},\n iwork::Vector{QDLDL_int},\n fwork::Vector{QDLDL_float}\n)\n @assert length(Ap) == n+1\n nnzA = Ap[end] \n @assert length(Ai) == nnzA\n @assert length(Ax) == nnzA\n @assert length(Lp) == n+1\n nnzL = Lp[end]\n @assert length(Li) == nnzL\n @assert length(Lx) == nnzL\n @assert length(D) == n\n @assert length(Dinv) == n\n @assert length(Lnz) == n\n @assert length(etree) == n\n @assert length(bwork) == n\n @assert length(iwork) == 3n\n @assert length(fwork) == n\n\n ccall((:QDLDL_factor, libqdldl), QDLDL_int,\n (\n QDLDL_int, # n\n Ptr{QDLDL_int}, # Ap\n Ptr{QDLDL_int}, # Ai\n Ptr{QDLDL_float}, # Ax\n Ref{QDLDL_int}, # Lx\n Ref{QDLDL_int}, # Li\n Ref{QDLDL_float}, # Lx\n Ref{QDLDL_float}, # D\n Ref{QDLDL_float}, # Dinv\n Ptr{QDLDL_int}, # Lnz\n Ptr{QDLDL_int}, # etree\n Ref{QDLDL_bool}, # bwork\n Ref{QDLDL_int}, # iwork\n Ref{QDLDL_float} # fwork\n ),\n n, Ap, Ai, Ax, Lp, Li, Lx, D, Dinv, Lnz, etree, bwork, iwork, fwork\n )\nend\n\nfunction qdldl_solve(\n n::QDLDL_int,\n Lp::Vector{QDLDL_int},\n Li::Vector{QDLDL_int},\n Lx::Vector{QDLDL_float},\n Dinv::Vector{QDLDL_float},\n x::Vector{QDLDL_float}\n)\n nnzL = Lp[end]\n @assert length(Li) == nnzL\n @assert length(Lx) == nnzL\n @assert length(Dinv) == n\n @assert length(x) == n\n ccall((:QDLDL_solve, libqdldl), Cvoid,\n (QDLDL_int, Ptr{QDLDL_int}, Ptr{QDLDL_int}, Ptr{QDLDL_float}, Ptr{QDLDL_float}, \n Ref{QDLDL_float}),\n n, Lp, Li, Lx, Dinv, x\n )\nend\n\n\"\"\"\n qdldl_Lsolve\n\nSolves ``(L+I)x = b``.\n\"\"\"\nfunction qdldl_Lsolve(\n n::QDLDL_int,\n Lp::Vector{QDLDL_int},\n Li::Vector{QDLDL_int},\n Lx::Vector{QDLDL_float},\n x::Vector{QDLDL_float}\n)\n nnzL = Lp[end]\n @assert length(Li) == nnzL\n @assert length(Lx) == nnzL\n @assert length(x) == n\n ccall((:QDLDL_Lsolve, libqdldl), Cvoid,\n (QDLDL_int, Ptr{QDLDL_int}, Ptr{QDLDL_int}, Ptr{QDLDL_float}, Ref{QDLDL_float}),\n n, Lp, Li, Lx, x\n )\nend\n\n\"\"\"\n qdldl_Lsolve\n\nSolves ``(L+I)^T x = b``.\n\"\"\"\nfunction qdldl_Ltsolve(\n n::QDLDL_int,\n Lp::Vector{QDLDL_int},\n Li::Vector{QDLDL_int},\n Lx::Vector{QDLDL_float},\n x::Vector{QDLDL_float}\n)\n nnzL = Lp[end]\n @assert length(Li) == nnzL\n @assert length(Lx) == nnzL\n @assert length(x) == n\n ccall((:QDLDL_Ltsolve, libqdldl), Cvoid,\n (QDLDL_int, Ptr{QDLDL_int}, Ptr{QDLDL_int}, Ptr{QDLDL_float}, Ref{QDLDL_float}),\n n, Lp, Li, Lx, x\n )\nend\n\nend", "meta": {"hexsha": "320e823ebc9fa3400614951e6b28903132a9cde7", "size": 12750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/qdldl.jl", "max_stars_repo_name": "bjack205/ALTRO.jl", "max_stars_repo_head_hexsha": "4864df2bb8ab8f629f451304cbaaa8e0017932d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qdldl.jl", "max_issues_repo_name": "bjack205/ALTRO.jl", "max_issues_repo_head_hexsha": "4864df2bb8ab8f629f451304cbaaa8e0017932d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qdldl.jl", "max_forks_repo_name": "bjack205/ALTRO.jl", "max_forks_repo_head_hexsha": "4864df2bb8ab8f629f451304cbaaa8e0017932d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7162162162, "max_line_length": 114, "alphanum_fraction": 0.5894901961, "num_tokens": 4490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}} {"text": "###\n### Particle Filtering and Particle MCMC Samplers.\n###\n\n#######################\n# Particle Transition #\n#######################\n\n\"\"\"\n ParticleTransition{T, F<:AbstractFloat}\n\nFields:\n- `θ`: The parameters for any given sample.\n- `lp`: The log pdf for the sample's parameters.\n- `le`: The log evidence retrieved from the particle.\n- `weight`: The weight of the particle the sample was retrieved from.\n\"\"\"\nstruct ParticleTransition{T, F<:AbstractFloat}\n θ::T\n lp::F\n le::F\n weight::F\nend\n\nfunction additional_parameters(::Type{<:ParticleTransition})\n return [:lp,:le, :weight]\nend\n\nDynamicPPL.getlogp(t::ParticleTransition) = t.lp\n\n####\n#### Generic Sequential Monte Carlo sampler.\n####\n\n\"\"\"\n$(TYPEDEF)\n\nSequential Monte Carlo sampler.\n\n# Fields\n\n$(TYPEDFIELDS)\n\"\"\"\nstruct SMC{space, R} <: ParticleInference\n resampler::R\nend\n\n\"\"\"\n SMC(space...)\n SMC([resampler = ResampleWithESSThreshold(), space = ()])\n SMC([resampler = resample_systematic, ]threshold[, space = ()])\n\nCreate a sequential Monte Carlo sampler of type [`SMC`](@ref) for the variables in `space`.\n\nIf the algorithm for the resampling step is not specified explicitly, systematic resampling\nis performed if the estimated effective sample size per particle drops below 0.5.\n\"\"\"\nfunction SMC(resampler = Turing.Core.ResampleWithESSThreshold(), space::Tuple = ())\n return SMC{space, typeof(resampler)}(resampler)\nend\n\n# Convenient constructors with ESS threshold\nfunction SMC(resampler, threshold::Real, space::Tuple = ())\n return SMC(Turing.Core.ResampleWithESSThreshold(resampler, threshold), space)\nend\nSMC(threshold::Real, space::Tuple = ()) = SMC(resample_systematic, threshold, space)\n\n# If only the space is defined\nSMC(space::Symbol...) = SMC(space)\nSMC(space::Tuple) = SMC(Turing.Core.ResampleWithESSThreshold(), space)\n\nmutable struct SMCState{V<:VarInfo, F<:AbstractFloat} <: AbstractSamplerState\n vi :: V\n # The logevidence after aggregating all samples together.\n average_logevidence :: F\n particles :: ParticleContainer\nend\n\nfunction SMCState(model::Model)\n vi = VarInfo(model)\n particles = ParticleContainer(Trace[])\n\n return SMCState(vi, 0.0, particles)\nend\n\nfunction Sampler(alg::SMC, model::Model, s::Selector)\n dict = Dict{Symbol, Any}()\n state = SMCState(model)\n return Sampler(alg, dict, s, state)\nend\n\nfunction AbstractMCMC.sample_init!(\n ::AbstractRNG,\n model::AbstractModel,\n spl::Sampler{<:SMC},\n N::Integer;\n kwargs...\n)\n # set the parameters to a starting value\n initialize_parameters!(spl; kwargs...)\n\n # reset the VarInfo\n vi = spl.state.vi\n reset_num_produce!(vi)\n set_retained_vns_del_by_spl!(vi, spl)\n resetlogp!(vi)\n empty!(vi)\n\n # create a new set of particles\n T = Trace{typeof(spl),typeof(vi),typeof(model)}\n particles = T[Trace(model, spl, vi) for _ in 1:N]\n\n # create a new particle container\n spl.state.particles = pc = ParticleContainer(particles)\n\n # Perform particle sweep.\n logevidence = sweep!(pc, spl.alg.resampler)\n spl.state.average_logevidence = logevidence\n\n return\nend\n\nfunction AbstractMCMC.step!(\n ::AbstractRNG,\n model::AbstractModel,\n spl::Sampler{<:SMC},\n ::Integer,\n transition;\n iteration=-1,\n kwargs...\n)\n # check that we received a real iteration number\n @assert iteration >= 1 \"step! needs to be called with an 'iteration' keyword argument.\"\n\n # grab the weight\n pc = spl.state.particles\n weight = getweight(pc, iteration)\n\n # update the master vi\n particle = pc.vals[iteration]\n params = tonamedtuple(particle.vi)\n\n # This is pretty useless since we reset the log probability continuously in the\n # particle sweep.\n lp = getlogp(particle.vi)\n\n return ParticleTransition(params, lp, spl.state.average_logevidence, weight)\nend\n\n####\n#### Particle Gibbs sampler.\n####\n\n\"\"\"\n$(TYPEDEF)\n\nParticle Gibbs sampler.\n\nNote that this method is particle-based, and arrays of variables\nmust be stored in a [`TArray`](@ref) object.\n\n# Fields\n\n$(TYPEDFIELDS)\n\"\"\"\nstruct PG{space,R} <: ParticleInference\n \"\"\"Number of particles.\"\"\"\n nparticles::Int\n \"\"\"Resampling algorithm.\"\"\"\n resampler::R\nend\n\nisgibbscomponent(::PG) = true\n\n\"\"\"\n PG(n, space...)\n PG(n, [resampler = ResampleWithESSThreshold(), space = ()])\n PG(n, [resampler = resample_systematic, ]threshold[, space = ()])\n\nCreate a Particle Gibbs sampler of type [`PG`](@ref) with `n` particles for the variables\nin `space`.\n\nIf the algorithm for the resampling step is not specified explicitly, systematic resampling\nis performed if the estimated effective sample size per particle drops below 0.5.\n\"\"\"\nfunction PG(\n nparticles::Int,\n resampler = Turing.Core.ResampleWithESSThreshold(),\n space::Tuple = (),\n)\n return PG{space, typeof(resampler)}(nparticles, resampler)\nend\n\n# Convenient constructors with ESS threshold\nfunction PG(nparticles::Int, resampler, threshold::Real, space::Tuple = ())\n return PG(nparticles, Turing.Core.ResampleWithESSThreshold(resampler, threshold), space)\nend\nfunction PG(nparticles::Int, threshold::Real, space::Tuple = ())\n return PG(nparticles, resample_systematic, threshold, space)\nend\n\n# If only the number of particles and the space is defined\nPG(nparticles::Int, space::Symbol...) = PG(nparticles, space)\nfunction PG(nparticles::Int, space::Tuple)\n return PG(nparticles, Turing.Core.ResampleWithESSThreshold(), space)\nend\n\nmutable struct PGState{V<:VarInfo, F<:AbstractFloat} <: AbstractSamplerState\n vi :: V\n # The logevidence after aggregating all samples together.\n average_logevidence :: F\nend\n\nfunction PGState(model::Model)\n vi = VarInfo(model)\n return PGState(vi, 0.0)\nend\n\nconst CSMC = PG # type alias of PG as Conditional SMC\n\n\"\"\"\n Sampler(alg::PG, model::Model, s::Selector)\n\nReturn a `Sampler` object for the PG algorithm.\n\"\"\"\nfunction Sampler(alg::PG, model::Model, s::Selector)\n info = Dict{Symbol, Any}()\n state = PGState(model)\n return Sampler(alg, info, s, state)\nend\n\nfunction AbstractMCMC.step!(\n ::AbstractRNG,\n model::AbstractModel,\n spl::Sampler{<:PG},\n ::Integer,\n transition;\n kwargs...\n)\n # obtain or create reference particle\n vi = spl.state.vi\n ref_particle = isempty(vi) ? nothing : forkr(Trace(model, spl, vi))\n\n # reset the VarInfo before new sweep\n reset_num_produce!(vi)\n set_retained_vns_del_by_spl!(vi, spl)\n resetlogp!(vi)\n\n # create a new set of particles\n num_particles = spl.alg.nparticles\n T = Trace{typeof(spl),typeof(vi),typeof(model)}\n if ref_particle === nothing\n particles = T[Trace(model, spl, vi) for _ in 1:num_particles]\n else\n particles = Vector{T}(undef, num_particles)\n @inbounds for i in 1:(num_particles - 1)\n particles[i] = Trace(model, spl, vi)\n end\n @inbounds particles[num_particles] = ref_particle\n end\n\n # create a new particle container\n pc = ParticleContainer(particles)\n\n # Perform a particle sweep.\n logevidence = sweep!(pc, spl.alg.resampler)\n\n # pick a particle to be retained.\n Ws = getweights(pc)\n indx = randcat(Ws)\n\n # extract the VarInfo from the retained particle.\n params = tonamedtuple(vi)\n spl.state.vi = pc.vals[indx].vi\n\n # This is pretty useless since we reset the log probability continuously in the\n # particle sweep.\n lp = getlogp(spl.state.vi)\n\n # update the master vi.\n return ParticleTransition(params, lp, logevidence, 1.0)\nend\n\nfunction AbstractMCMC.sample_end!(\n ::AbstractRNG,\n ::AbstractModel,\n spl::Sampler{<:ParticleInference},\n N::Integer,\n ts::Vector{<:ParticleTransition};\n resume_from = nothing,\n kwargs...\n)\n # Exponentiate the average log evidence.\n # loge = exp(mean([t.le for t in ts]))\n loge = mean(t.le for t in ts)\n\n # If we already had a chain, grab the logevidence.\n if resume_from isa MCMCChains.Chains\n # pushfirst!(samples, resume_from.info[:samples]...)\n pre_loge = resume_from.logevidence\n # Calculate new log-evidence\n pre_n = length(resume_from)\n loge = (pre_loge * pre_n + loge * N) / (pre_n + N)\n elseif resume_from !== nothing\n error(\"keyword argument `resume_from` has to be `nothing` or a `MCMCChains.Chains` object\")\n end\n\n # Store the logevidence.\n spl.state.average_logevidence = loge\nend\n\nfunction DynamicPPL.assume(\n rng,\n spl::Sampler{<:Union{PG,SMC}},\n dist::Distribution,\n vn::VarName,\n ::Any\n)\n vi = current_trace().vi\n if inspace(vn, spl)\n if ~haskey(vi, vn)\n r = rand(rng, dist)\n push!(vi, vn, r, dist, spl)\n elseif is_flagged(vi, vn, \"del\")\n unset_flag!(vi, vn, \"del\")\n r = rand(rng, dist)\n vi[vn] = vectorize(dist, r)\n setgid!(vi, spl.selector, vn)\n setorder!(vi, vn, get_num_produce(vi))\n else\n updategid!(vi, vn, spl)\n r = vi[vn]\n end\n else # vn belongs to other sampler <=> conditionning on vn\n if haskey(vi, vn)\n r = vi[vn]\n else\n r = rand(rng, dist)\n push!(vi, vn, r, dist, Selector(:invalid))\n end\n lp = logpdf_with_trans(dist, r, istrans(vi, vn))\n acclogp!(vi, lp)\n end\n return r, 0\nend\n\nfunction DynamicPPL.observe(spl::Sampler{<:Union{PG,SMC}}, dist::Distribution, value, vi)\n produce(logpdf(dist, value))\n return 0\nend\n\n####\n#### Resampling schemes for particle filters\n####\n\n# Some references\n# - http://arxiv.org/pdf/1301.4019.pdf\n# - http://people.isy.liu.se/rt/schon/Publications/HolSG2006.pdf\n# Code adapted from: http://uk.mathworks.com/matlabcentral/fileexchange/24968-resampling-methods-for-particle-filtering\n\n# Default resampling scheme\nfunction resample(w::AbstractVector{<:Real}, num_particles::Integer=length(w))\n return resample_systematic(w, num_particles)\nend\n\n# More stable, faster version of rand(Categorical)\nfunction randcat(p::AbstractVector{<:Real})\n T = eltype(p)\n r = rand(T)\n s = 1\n for j in eachindex(p)\n r -= p[j]\n if r <= zero(T)\n s = j\n break\n end\n end\n return s\nend\n\nfunction resample_multinomial(w::AbstractVector{<:Real}, num_particles::Integer)\n return rand(Distributions.sampler(Categorical(w)), num_particles)\nend\n\nfunction resample_residual(w::AbstractVector{<:Real}, num_particles::Integer)\n # Pre-allocate array for resampled particles\n indices = Vector{Int}(undef, num_particles)\n\n # deterministic assignment\n residuals = similar(w)\n i = 1\n @inbounds for j in 1:length(w)\n x = num_particles * w[j]\n floor_x = floor(Int, x)\n for k in 1:floor_x\n indices[i] = j\n i += 1\n end\n residuals[j] = x - floor_x\n end\n \n # sampling from residuals\n if i <= num_particles\n residuals ./= sum(residuals)\n rand!(Categorical(residuals), view(indices, i:num_particles))\n end\n \n return indices\nend\n\n\n\"\"\"\n resample_stratified(weights, n)\n\nReturn a vector of `n` samples `x₁`, ..., `xₙ` from the numbers 1, ..., `length(weights)`,\ngenerated by stratified resampling.\n\nIn stratified resampling `n` ordered random numbers `u₁`, ..., `uₙ` are generated, where\n``uₖ \\\\sim U[(k - 1) / n, k / n)``. Based on these numbers the samples `x₁`, ..., `xₙ`\nare selected according to the multinomial distribution defined by the normalized `weights`,\ni.e., `xᵢ = j` if and only if\n``uᵢ \\\\in [\\\\sum_{s=1}^{j-1} weights_{s}, \\\\sum_{s=1}^{j} weights_{s})``.\n\"\"\"\nfunction resample_stratified(weights::AbstractVector{<:Real}, n::Integer)\n # check input\n m = length(weights)\n m > 0 || error(\"weight vector is empty\")\n\n # pre-calculations\n @inbounds v = n * weights[1]\n\n # generate all samples\n samples = Array{Int}(undef, n)\n sample = 1\n @inbounds for i in 1:n\n # sample next `u` (scaled by `n`)\n u = oftype(v, i - 1 + rand())\n\n # as long as we have not found the next sample\n while v < u\n # increase and check the sample\n sample += 1\n sample > m &&\n error(\"sample could not be selected (are the weights normalized?)\")\n\n # update the cumulative sum of weights (scaled by `n`)\n v += n * weights[sample]\n end\n\n # save the next sample\n samples[i] = sample\n end\n\n return samples\nend\n\n\"\"\"\n resample_systematic(weights, n)\n\nReturn a vector of `n` samples `x₁`, ..., `xₙ` from the numbers 1, ..., `length(weights)`,\ngenerated by systematic resampling.\n\nIn systematic resampling a random number ``u \\\\sim U[0, 1)`` is used to generate `n` ordered\nnumbers `u₁`, ..., `uₙ` where ``uₖ = (u + k − 1) / n``. Based on these numbers the samples\n`x₁`, ..., `xₙ` are selected according to the multinomial distribution defined by the\nnormalized `weights`, i.e., `xᵢ = j` if and only if\n``uᵢ \\\\in [\\\\sum_{s=1}^{j-1} weights_{s}, \\\\sum_{s=1}^{j} weights_{s})``.\n\"\"\"\nfunction resample_systematic(weights::AbstractVector{<:Real}, n::Integer)\n # check input\n m = length(weights)\n m > 0 || error(\"weight vector is empty\")\n\n # pre-calculations\n @inbounds v = n * weights[1]\n u = oftype(v, rand())\n\n # find all samples\n samples = Array{Int}(undef, n)\n sample = 1\n @inbounds for i in 1:n\n # as long as we have not found the next sample\n while v < u\n # increase and check the sample\n sample += 1\n sample > m &&\n error(\"sample could not be selected (are the weights normalized?)\")\n\n # update the cumulative sum of weights (scaled by `n`)\n v += n * weights[sample]\n end\n\n # save the next sample\n samples[i] = sample\n\n # update `u`\n u += one(u)\n end\n\n return samples\nend\n", "meta": {"hexsha": "719dc27ce299e822c188ca1ff3095790c11ccc47", "size": 13951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/inference/AdvancedSMC.jl", "max_stars_repo_name": "konkam/Turing.jl", "max_stars_repo_head_hexsha": "1d87a1d4084299de74c2d53956895741a6e0001b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inference/AdvancedSMC.jl", "max_issues_repo_name": "konkam/Turing.jl", "max_issues_repo_head_hexsha": "1d87a1d4084299de74c2d53956895741a6e0001b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-27T03:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-27T03:35:15.000Z", "max_forks_repo_path": "src/inference/AdvancedSMC.jl", "max_forks_repo_name": "logankilpatrick/Turing.jl", "max_forks_repo_head_hexsha": "6a5a4662b447bca4d3ee3f44fcba8221f90fb975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7908366534, "max_line_length": 119, "alphanum_fraction": 0.6444699305, "num_tokens": 3774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}} {"text": "module RPO\nusing ..AGFFileReader: Glass, GlassID, AGF\nexport EKPC, H_ZLAF55_MOLD, BSM16C_MOLD, IG6, D_LAK6_MOLD, N_LAF2_MOLD, S_NPH1_MOLD, IG5, H_ZLAF53_MOLD, D_LAK70_MOLD, H_ZLAF52_MOLD, S_LAL12_MOLD, E_FDS1_MOLD, D_LAK70, IG2, L_TIM28_MOLD, SF57_MOLD, IG4, D_ZLAF52A_MOLD, H_ZLAF56_MOLD, S_LAH60_MOLD, K_CSK120_MOLD, N_SK5_MOLD, K_VC79_MOLD, N_BK7_MOLD, S_LAL18_MOLD, H_LAK54_MOLD, N_FK51_MOLD, P_SK57_MOLD, L_LAM60_MOLD, S_LAL13_MOLD, TAF3_MOLD, D_K59_MOLD, TAC4_MOLD, VC78, K_VC89_MOLD, FDS9_MOLD, N_FK5_MOLD, TAF1_MOLD, VC78_MOLD, H_ZLAF50B_MOLD, BACD14_MOLD, N_LAK22_MOLD\n\nconst EKPC = Glass(GlassID(AGF, 1728), 1, 2.1665838, 0.11325275, 0.25033244, -0.085983038, 0.015632264, -0.0010525329, 0.0, 0.0, 0.0, 0.0, 0.334, 2.325, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 2, -1.0, [(0.334, 1.0, 25.0), (0.35, 1.0, 25.0), (0.365, 1.0, 25.0), (0.37, 1.0, 25.0), (0.38, 1.0, 25.0), (0.39, 1.0, 25.0), (0.4, 1.0, 25.0), (0.42, 1.0, 25.0), (0.46, 1.0, 25.0), (0.5, 1.0, 25.0), (0.66, 1.0, 25.0), (1.06, 1.0, 25.0), (1.529, 1.0, 25.0), (2.325, 1.0, 25.0)], 1.585936, -1.0, -1.0, 0, 30.119218, 0, 0.0, 0)\nconst H_ZLAF55_MOLD = Glass(GlassID(AGF, 1729), 1, 3.25484318, -0.0128524549, 0.0333590798, -6.78562065e-5, 0.000111853849, -4.03704375e-6, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0082, -1.0, -1.0, 6.6, -1.0, 0, -1.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.01, 10.0), (0.34, 0.19, 10.0), (0.35, 0.47, 10.0), (0.36, 0.68, 10.0), (0.37, 0.8, 10.0), (0.38, 0.88, 10.0), (0.39, 0.915, 10.0), (0.4, 0.939, 10.0), (0.42, 0.963, 10.0), (0.44, 0.974, 10.0), (0.46, 0.981, 10.0), (0.48, 0.986, 10.0), (0.5, 0.989, 10.0), (0.55, 0.993, 10.0), (0.6, 0.994, 10.0), (0.65, 0.995, 10.0), (0.7, 0.995, 10.0), (0.8, 0.0, 10.0), (0.85, 0.0, 10.0), (0.9, 0.0, 10.0), (0.95, 0.0, 10.0), (1.0, 0.0, 10.0), (1.06, 0.0, 10.0), (1.2, 0.0, 10.0), (1.4, 0.0, 10.0), (1.6, 0.0, 10.0), (1.8, 0.0, 10.0), (2.0, 0.0, 10.0), (2.2, 0.0, 10.0), (2.4, 0.0, 10.0)], 1.83, -1.0, -1.0, 0, 42.726836, 0, 4.95, 0)\nconst BSM16C_MOLD = Glass(GlassID(AGF, 1730), 1, 2.56787068, -0.01138582621, 0.01387681972, 0.0005015765279, -3.592774947e-5, 1.983667247e-6, 0.0, 0.0, 0.0, 0.0, 0.299999999, 2.4, 2.256e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, -0.0014, 3.2, 3.0, 6.3, -1.0, 0, 52.2, [(0.3, 0.1, 10.0), (0.31, 0.24, 10.0), (0.32, 0.42, 10.0), (0.33, 0.6, 10.0), (0.34, 0.74, 10.0), (0.35, 0.85, 10.0), (0.36, 0.912, 10.0), (0.37, 0.948, 10.0), (0.38, 0.968, 10.0), (0.39, 0.979, 10.0), (0.4, 0.986, 10.0), (0.42, 0.992, 10.0), (0.44, 0.993, 10.0), (0.46, 0.995, 10.0), (0.48, 0.996, 10.0), (0.5, 0.997, 10.0), (0.55, 0.998, 10.0), (0.6, 0.998, 10.0), (0.65, 0.998, 10.0), (0.7, 0.998, 10.0), (0.8, 0.0, 10.0), (0.9, 0.0, 10.0), (1.0, 0.0, 10.0), (1.2, 0.0, 10.0), (1.4, 0.0, 10.0), (1.6, 0.0, 10.0), (1.8, 0.0, 10.0), (2.0, 0.0, 10.0), (2.2, 0.0, 10.0), (2.4, 0.0, 10.0)], 1.61481, -1.0, -1.0, 0, 59.71032, 0, 3.57, 5)\nconst IG6 = Glass(GlassID(AGF, 1731), 1, 7.74508077, -0.000557064219, 3.2517883, -78.7663982, 988.437047, -4179.30731, 0.0, 0.0, 0.0, 0.0, 3.0, 12.0, 3.39e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 20.7, -1.0, 0, -1.0, [], 1.0, -1.0, -1.0, 0, 0.0, 0, 4.63, 0)\nconst D_LAK6_MOLD = Glass(GlassID(AGF, 1732), 1, 2.80532992, -0.0177972005, 0.0169077957, 0.000786545091, -2.23253554e-5, -5.36623399e-8, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [], 1.689442, -1.0, -1.0, 0, 52.830176, 0, 1.0, 0)\nconst N_LAF2_MOLD = Glass(GlassID(AGF, 1733), 2, 1.79419393, 0.0102626245, 0.155056926, 0.044352647, 1.09019471, 100.731467, 0.0, 0.0, 0.0, 0.0, 0.35, 2.5, -3.64e-6, 9.2e-9, -6.0e-12, 6.43e-7, 6.11e-10, 0.22, 20.0, -0.0027, 2.2, 3.5, 8.06, 2.0, 0, 52.2, [(0.35, 0.025, 25.0), (0.365, 0.31, 25.0), (0.37, 0.43, 25.0), (0.38, 0.63, 25.0), (0.39, 0.76, 25.0), (0.4, 0.84, 25.0), (0.405, 0.865, 25.0), (0.42, 0.915, 25.0), (0.436, 0.94, 25.0), (0.46, 0.962, 25.0), (0.5, 0.983, 25.0), (0.546, 0.994, 25.0), (0.58, 0.993, 25.0), (0.62, 0.992, 25.0), (0.66, 0.993, 25.0), (0.7, 0.996, 25.0), (1.06, 0.997, 25.0), (1.53, 0.99, 25.0), (1.97, 0.93, 25.0), (2.325, 0.69, 25.0), (2.5, 0.4, 25.0)], 1.738772, 1.0, 3.0, 0, 44.536828, 0, 4.295, 2)\nconst S_NPH1_MOLD = Glass(GlassID(AGF, 1734), 2, 1.72039395, 0.0137918186, 0.35905958, 0.0669088725, 1.95245396, 136.641902, 0.0, 0.0, 0.0, 0.0, 0.3, 2.4, -2.275e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.0261, 1.0, 10.5, 8.3, -1.0, 0, 1.0, [(0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.0, 10.0), (0.34, 0.0, 10.0), (0.35, 0.0, 10.0), (0.36, 0.0, 10.0), (0.37, 0.0, 10.0), (0.38, 0.14, 10.0), (0.39, 0.53, 10.0), (0.4, 0.77, 10.0), (0.42, 0.917, 10.0), (0.44, 0.952, 10.0), (0.46, 0.967, 10.0), (0.48, 0.975, 10.0), (0.5, 0.982, 10.0), (0.55, 0.992, 10.0), (0.6, 0.994, 10.0), (0.65, 0.995, 10.0), (0.7, 0.996, 10.0), (0.8, 0.997, 10.0), (0.9, 0.997, 10.0), (1.0, 0.996, 10.0), (1.2, 0.997, 10.0), (1.4, 0.994, 10.0), (1.6, 0.992, 10.0), (1.8, 0.984, 10.0), (2.0, 0.973, 10.0), (2.2, 0.934, 10.0), (2.4, 0.88, 10.0)], 1.797892, -1.0, -1.0, 0, 22.463062, 0, 3.29, 4)\nconst IG5 = Glass(GlassID(AGF, 1735), 1, 6.92709255, -0.00120658749, -3.58858859, 103.314022, -1124.75323, 4295.46144, 0.0, 0.0, 0.0, 0.0, 3.0, 12.0, 8.2e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 14.0, -1.0, 0, -1.0, [], 1.0, -1.0, -1.0, 0, 0.0, 0, 4.66, 0)\nconst H_ZLAF53_MOLD = Glass(GlassID(AGF, 1736), 1, 3.24453775, -0.0153351622, 0.0330644118, 0.0014056192, -5.51574923e-5, 7.11912475e-6, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0039, -1.0, -1.0, 6.3, -1.0, 0, -1.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.0, 10.0), (0.34, 0.02, 10.0), (0.35, 0.17, 10.0), (0.36, 0.41, 10.0), (0.37, 0.61, 10.0), (0.38, 0.75, 10.0), (0.39, 0.84, 10.0), (0.4, 0.89, 10.0), (0.42, 0.942, 10.0), (0.44, 0.96, 10.0), (0.46, 0.972, 10.0), (0.48, 0.98, 10.0), (0.5, 0.987, 10.0), (0.55, 0.994, 10.0), (0.6, 0.995, 10.0), (0.65, 0.995, 10.0), (0.7, 0.996, 10.0), (0.8, 0.997, 10.0), (0.85, 0.998, 10.0), (0.9, 0.998, 10.0), (0.95, 0.998, 10.0), (1.0, 0.998, 10.0), (1.06, 0.998, 10.0), (1.2, 0.998, 10.0), (1.4, 0.997, 10.0), (1.6, 0.984, 10.0), (1.8, 0.976, 10.0), (2.0, 0.958, 10.0), (2.2, 0.903, 10.0), (2.4, 0.72, 10.0)], 1.8292, -1.0, -1.0, 0, 36.952953, 0, 4.55, 0)\nconst D_LAK70_MOLD = Glass(GlassID(AGF, 1737), 1, 2.6962639, 0.00638424925, 0.0324462812, -0.00344923153, 0.000451981089, -2.02364943e-5, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 2, -1.0, [], 1.665254, -1.0, -1.0, 0, 55.135587, 0, 1.0, 0)\nconst H_ZLAF52_MOLD = Glass(GlassID(AGF, 1738), 1, 3.15651187, -0.0148252255, 0.0294604452, 0.000981264712, -2.29185364e-5, 3.79523742e-6, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0055, -1.0, -1.0, 6.2, -1.0, 0, -1.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.0, 10.0), (0.34, 0.06, 10.0), (0.35, 0.28, 10.0), (0.36, 0.52, 10.0), (0.37, 0.7, 10.0), (0.38, 0.81, 10.0), (0.39, 0.88, 10.0), (0.4, 0.923, 10.0), (0.42, 0.958, 10.0), (0.44, 0.971, 10.0), (0.46, 0.98, 10.0), (0.48, 0.986, 10.0), (0.5, 0.991, 10.0), (0.55, 0.995, 10.0), (0.6, 0.995, 10.0), (0.65, 0.996, 10.0), (0.7, 0.997, 10.0), (0.8, 0.997, 10.0), (0.85, 0.998, 10.0), (0.9, 0.998, 10.0), (0.95, 0.998, 10.0), (1.0, 0.998, 10.0), (1.06, 0.998, 10.0), (1.2, 0.996, 10.0), (1.4, 0.99, 10.0), (1.6, 0.98, 10.0), (1.8, 0.956, 10.0), (2.0, 0.922, 10.0), (2.2, 0.81, 10.0), (2.4, 0.56, 10.0)], 1.801298, -1.0, -1.0, 0, 40.704676, 0, 4.47, 0)\nconst S_LAL12_MOLD = Glass(GlassID(AGF, 1739), 2, 0.609918184, 0.000533113491, 1.13827825, 0.015815259, 1.20182489, 107.73823, 0.0, 0.0, 0.0, 0.0, 0.3, 2.4, -7.683e-7, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, -0.0047, 4.2, 2.5, 7.2, -1.0, 0, 53.0, [(0.3, 0.29, 10.0), (0.31, 0.45, 10.0), (0.32, 0.61, 10.0), (0.33, 0.73, 10.0), (0.34, 0.83, 10.0), (0.35, 0.89, 10.0), (0.36, 0.938, 10.0), (0.37, 0.962, 10.0), (0.38, 0.976, 10.0), (0.39, 0.984, 10.0), (0.4, 0.988, 10.0), (0.42, 0.992, 10.0), (0.44, 0.994, 10.0), (0.46, 0.995, 10.0), (0.48, 0.997, 10.0), (0.5, 0.998, 10.0), (0.55, 0.999, 10.0), (0.6, 0.998, 10.0), (0.65, 0.998, 10.0), (0.7, 0.998, 10.0), (0.8, 0.999, 10.0), (0.9, 0.997, 10.0), (1.0, 0.996, 10.0), (1.2, 0.996, 10.0), (1.4, 0.991, 10.0), (1.6, 0.991, 10.0), (1.8, 0.981, 10.0), (2.0, 0.963, 10.0), (2.2, 0.901, 10.0), (2.4, 0.73, 10.0)], 1.673298, -1.0, -1.0, 0, 54.966722, 0, 4.01, 1)\nconst E_FDS1_MOLD = Glass(GlassID(AGF, 1740), 1, 3.46650745, -0.0202617699, 0.0533843287, 0.00629834765, -0.000572117101, 7.34747837e-5, 0.0, 0.0, 0.0, 0.0, 0.25, 1.55, -7.0623e-7, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0282, -1.0, 11.1, 6.3, 1.0, 0, 1.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.0, 10.0), (0.34, 0.0, 10.0), (0.35, 0.0, 10.0), (0.36, 0.0, 10.0), (0.37, 0.0, 10.0), (0.38, 0.01, 10.0), (0.39, 0.13, 10.0), (0.4, 0.4, 10.0), (0.42, 0.78, 10.0), (0.44, 0.88, 10.0), (0.46, 0.92, 10.0), (0.48, 0.95, 10.0), (0.5, 0.958, 10.0), (0.55, 0.977, 10.0), (0.6, 0.988, 10.0), (0.65, 0.991, 10.0), (0.7, 0.995, 10.0), (0.75, 0.0, 10.0), (0.8, 0.0, 10.0), (0.9, 0.0, 10.0), (1.0, 0.0, 10.0), (1.06, 0.0, 10.0), (1.1, 0.0, 10.0), (1.3, 0.0, 10.0), (1.55, 0.0, 10.0)], 1.912658, -1.0, 2.0, 0, 20.647419, 0, 3.94, 0)\nconst D_LAK70 = Glass(GlassID(AGF, 1741), 1, 2.70892374, 0.00639831933, 0.0325213777, -0.00345719463, 0.000453015557, -2.02829394e-5, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 2, -1.0, [], 1.669104, -1.0, -1.0, 0, 55.454671, 0, 1.0, 0)\nconst IG2 = Glass(GlassID(AGF, 1742), 1, 6.37933507, -0.00111513063, -4.78062765, 144.905769, -1731.6457, 7119.30411, 0.0, 0.0, 0.0, 0.0, 3.0, 12.0, 5.72e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 12.1, -1.0, 0, -1.0, [], 1.0, -1.0, -1.0, 0, 0.0, 0, 4.41, 0)\nconst L_TIM28_MOLD = Glass(GlassID(AGF, 1743), 2, 1.56554809, 0.0126346935, 0.176885637, 0.0603406048, 1.14661648, 116.334311, 0.0, 0.0, 0.0, 0.0, 0.35, 2.4, -1.86e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.0074, 1999.0, 3.0, 10.1, 1.0, 3, 1.0, [(0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.0, 10.0), (0.34, 0.0, 10.0), (0.35, 0.0, 10.0), (0.36, 0.16, 10.0), (0.37, 0.57, 10.0), (0.38, 0.8, 10.0), (0.39, 0.89, 10.0), (0.4, 0.929, 10.0), (0.42, 0.964, 10.0), (0.44, 0.974, 10.0), (0.46, 0.98, 10.0), (0.48, 0.984, 10.0), (0.5, 0.989, 10.0), (0.55, 0.997, 10.0), (0.6, 0.996, 10.0), (0.65, 0.0, 10.0), (0.7, 0.0, 10.0), (0.8, 0.0, 10.0), (0.9, 0.0, 10.0), (1.0, 0.0, 10.0), (1.2, 0.0, 10.0), (1.4, 0.0, 10.0), (1.6, 0.0, 10.0), (1.8, 0.0, 10.0), (2.0, 0.0, 10.0), (2.2, 0.0, 10.0), (2.4, 0.0, 10.0)], 1.68403, -1.0, -1.0, 0, 30.856565, 0, 2.88, 3)\nconst SF57_MOLD = Glass(GlassID(AGF, 1744), 1, 3.240155287, -0.009571992651, 0.04883185889, 0.003148947643, -0.0001774970599, 2.889640871e-5, 0.0, 0.0, 0.0, 0.0, 0.369999999, 2.5, 7.26e-6, 1.88e-8, -5.14e-11, 1.96e-6, 1.79e-9, 0.276, 20.0, 0.0123, 4.3, 2.5, 8.3, 2.0, 0, 52.3, [(0.37, 0.01, 25.0), (0.38, 0.198, 25.0), (0.39, 0.45, 25.0), (0.4, 0.66, 25.0), (0.405, 0.73, 25.0), (0.42, 0.86, 25.0), (0.436, 0.93, 25.0), (0.46, 0.968, 25.0), (0.5, 0.986, 25.0), (0.546, 0.994, 25.0), (0.58, 0.994, 25.0), (0.62, 0.994, 25.0), (0.66, 0.994, 25.0), (0.7, 0.996, 25.0), (1.06, 0.997, 25.0), (1.53, 0.991, 25.0), (1.97, 0.93, 25.0), (2.325, 0.79, 25.0), (2.5, 0.75, 25.0)], 1.84457, 2.3, 5.0, 0, 23.7525, 0, 5.51, 3)\nconst IG4 = Glass(GlassID(AGF, 1745), 1, 6.91189161, -0.000787956404, -4.22296071, 142.900646, -1812.32748, 7766.33028, 0.0, 0.0, 0.0, 0.0, 3.0, 12.0, 3.24e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 20.4, -1.0, 0, -1.0, [], 1.0, -1.0, -1.0, 0, 0.0, 0, 4.47, 0)\nconst D_ZLAF52A_MOLD = Glass(GlassID(AGF, 1746), 1, 3.18012111, -0.0305336243, 0.0150556955, 0.00519177551, -0.000615002878, 3.57892588e-5, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [], 1.801201, -1.0, -1.0, 0, 40.631273, 0, 1.0, 0)\nconst H_ZLAF56_MOLD = Glass(GlassID(AGF, 1747), 1, 3.13237288, -0.0132119823, 0.0339851496, 0.00184155673, -0.000107740182, 1.29364847e-5, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0007, -1.0, -1.0, 7.5, -1.0, 0, -1.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.0, 10.0), (0.34, 0.0, 10.0), (0.35, 0.01, 10.0), (0.36, 0.17, 10.0), (0.37, 0.48, 10.0), (0.38, 0.68, 10.0), (0.39, 0.79, 10.0), (0.4, 0.852, 10.0), (0.42, 0.912, 10.0), (0.44, 0.937, 10.0), (0.46, 0.951, 10.0), (0.48, 0.962, 10.0), (0.5, 0.971, 10.0), (0.55, 0.984, 10.0), (0.6, 0.987, 10.0), (0.65, 0.989, 10.0), (0.7, 0.991, 10.0), (0.8, 0.992, 10.0), (0.85, 0.997, 10.0), (0.9, 0.997, 10.0), (0.95, 0.998, 10.0), (1.0, 0.998, 10.0), (1.06, 0.998, 10.0), (1.2, 0.998, 10.0), (1.4, 0.997, 10.0), (1.6, 0.995, 10.0), (1.8, 0.989, 10.0), (2.0, 0.975, 10.0), (2.2, 0.939, 10.0), (2.4, 0.849, 10.0)], 1.799999, -1.0, -1.0, 0, 33.017644, 0, 3.69, 0)\nconst S_LAH60_MOLD = Glass(GlassID(AGF, 1748), 2, 1.08334791, 2.38405685e-11, 1.1529996, 0.0294633109, 2.47494795, 170.254264, 0.0, 0.0, 0.0, 0.0, 0.365, 2.325, -3.93e-7, 1.2e-8, -3.29e-11, 8.13e-7, 1.17e-9, 0.284, 25.0, 0.012962, 1.0, 5.0, 5.6, -1.0, 2, 4.2, [(0.24, 0.0, 10.0), (0.25, 0.0, 10.0), (0.26, 0.0, 10.0), (0.27, 0.0, 10.0), (0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.0, 10.0), (0.33, 0.0, 10.0), (0.34, 0.03, 10.0), (0.35, 0.27, 10.0), (0.36, 0.54, 10.0), (0.37, 0.72, 10.0), (0.38, 0.83, 10.0), (0.39, 0.88, 10.0), (0.4, 0.924, 10.0), (0.42, 0.957, 10.0), (0.44, 0.972, 10.0), (0.46, 0.98, 10.0), (0.48, 0.986, 10.0), (0.5, 0.99, 10.0), (0.55, 0.996, 10.0), (0.6, 0.997, 10.0), (0.65, 0.997, 10.0), (0.7, 0.998, 10.0), (0.8, 0.999, 10.0), (0.9, 0.998, 10.0), (1.0, 0.997, 10.0), (1.2, 0.996, 10.0), (1.4, 0.993, 10.0), (1.6, 0.992, 10.0), (1.8, 0.984, 10.0), (2.0, 0.964, 10.0), (2.2, 0.906, 10.0), (2.4, 0.72, 10.0)], 1.827266, 3.0, -1.0, 0, 36.787075, 0, 4.43, 1)\nconst K_CSK120_MOLD = Glass(GlassID(AGF, 1749), 1, 2.462205306, -0.007402005673, 0.01806043171, -0.001017272649, 0.0001624358258, -7.641622271e-6, 0.0, 0.0, 0.0, 0.0, 0.269999999, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0059, -1.0, -1.0, 0.0, 2.0, 0, 4.0, [(0.27, 0.0, 10.0), (0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.079, 10.0), (0.32, 0.386, 10.0), (0.33, 0.679, 10.0), (0.34, 0.843, 10.0), (0.35, 0.923, 10.0), (0.36, 0.963, 10.0), (0.37, 0.972, 10.0), (0.38, 0.99, 10.0), (0.39, 0.998, 10.0), (0.4, 0.998, 10.0), (0.42, 0.998, 10.0), (0.44, 0.998, 10.0), (0.46, 0.998, 10.0), (0.48, 0.998, 10.0), (0.5, 0.998, 10.0), (0.55, 0.998, 10.0), (0.6, 0.998, 10.0), (0.7, 0.998, 10.0), (0.8, 0.998, 10.0), (1.06, 0.998, 10.0), (1.5, 0.994, 10.0), (2.0, 0.988, 10.0)], 1.5833, -1.0, -1.0, 0, 59.191064, 0, 3.0, 0)\nconst N_SK5_MOLD = Glass(GlassID(AGF, 1750), 2, 0.982325914, 0.00533315206, 0.488744522, 0.0173212991, 0.984484296, 98.3938446, 0.0, 0.0, 0.0, 0.0, 0.3, 2.5, 3.5e-6, 1.22e-8, 6.38e-11, 2.46e-7, -3.34e-11, 0.278, 20.0, -0.0007, 1.3, 1.5, 5.5, 3.0, 0, 4.4, [(0.3, 0.02, 25.0), (0.31, 0.1, 25.0), (0.32, 0.27, 25.0), (0.334, 0.58, 25.0), (0.35, 0.82, 25.0), (0.365, 0.93, 25.0), (0.37, 0.94, 25.0), (0.38, 0.96, 25.0), (0.39, 0.971, 25.0), (0.4, 0.981, 25.0), (0.405, 0.983, 25.0), (0.42, 0.986, 25.0), (0.436, 0.987, 25.0), (0.46, 0.989, 25.0), (0.5, 0.994, 25.0), (0.546, 0.996, 25.0), (0.58, 0.995, 25.0), (0.62, 0.993, 25.0), (0.66, 0.994, 25.0), (0.7, 0.995, 25.0), (1.06, 0.997, 25.0), (1.53, 0.98, 25.0), (1.97, 0.91, 25.0), (2.325, 0.64, 25.0), (2.5, 0.38, 25.0)], 1.58393, 2.0, 1.0, 0, 60.726008, 0, 3.3, 2)\nconst K_VC79_MOLD = Glass(GlassID(AGF, 1751), 1, 2.534883491, -0.01093481644, 0.01483039411, 0.0003095841104, -9.025669048e-6, 6.707866289e-7, 0.0, 0.0, 0.0, 0.0, 0.269999999, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0076, -1.0, -1.0, 0.0, 2.0, 0, 4.0, [(0.27, 0.022, 10.0), (0.28, 0.103, 10.0), (0.29, 0.26, 10.0), (0.3, 0.378, 10.0), (0.31, 0.669, 10.0), (0.32, 0.799, 10.0), (0.33, 0.891, 10.0), (0.34, 0.939, 10.0), (0.35, 0.964, 10.0), (0.36, 0.978, 10.0), (0.37, 0.982, 10.0), (0.38, 0.985, 10.0), (0.39, 0.985, 10.0), (0.4, 0.985, 10.0), (0.42, 0.985, 10.0), (0.44, 0.988, 10.0), (0.46, 0.99, 10.0), (0.48, 0.991, 10.0), (0.5, 0.992, 10.0), (0.55, 0.994, 10.0), (0.6, 0.994, 10.0), (0.7, 0.997, 10.0), (0.8, 0.997, 10.0), (1.06, 0.998, 10.0), (1.5, 0.998, 10.0), (2.0, 0.997, 10.0)], 1.605145, -1.0, -1.0, 0, 57.304584, 0, 3.09, 0)\nconst N_BK7_MOLD = Glass(GlassID(AGF, 1752), 2, 0.780178416, 0.0133285338, 0.478659702, 0.000830413318, 1.04547946, 107.124175, 0.0, 0.0, 0.0, 0.0, 0.3, 2.5, 1.86e-6, 1.31e-8, -1.37e-11, 4.34e-7, 6.27e-10, 0.17, 20.0, -0.0009, 2.3, 1.0, 7.1, 2.0, 0, 1.0, [(0.3, 0.05, 25.0), (0.31, 0.25, 25.0), (0.32, 0.52, 25.0), (0.334, 0.78, 25.0), (0.35, 0.92, 25.0), (0.365, 0.971, 25.0), (0.37, 0.977, 25.0), (0.38, 0.983, 25.0), (0.39, 0.989, 25.0), (0.4, 0.992, 25.0), (0.405, 0.993, 25.0), (0.42, 0.993, 25.0), (0.436, 0.992, 25.0), (0.46, 0.993, 25.0), (0.5, 0.994, 25.0), (0.546, 0.996, 25.0), (0.58, 0.995, 25.0), (0.62, 0.994, 25.0), (0.66, 0.994, 25.0), (0.7, 0.996, 25.0), (1.06, 0.997, 25.0), (1.53, 0.98, 25.0), (1.97, 0.84, 25.0), (2.325, 0.56, 25.0), (2.5, 0.36, 25.0)], 1.512595, 2.0, 0.0, 0, 63.648436, 0, 2.51, 1)\nconst S_LAL18_MOLD = Glass(GlassID(AGF, 1753), 2, 0.66506272, 0.00101735308, 1.24938061, 0.0157988109, 1.31025811, 91.274655, 0.0, 0.0, 0.0, 0.0, 0.3, 2.4, 4.566e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, -0.0086, 2.0, 7.5, 5.9, -1.0, 0, 51.2, [(0.3, 0.3, 10.0), (0.31, 0.32, 10.0), (0.32, 0.55, 10.0), (0.33, 0.68, 10.0), (0.34, 0.78, 10.0), (0.35, 0.86, 10.0), (0.36, 0.912, 10.0), (0.37, 0.946, 10.0), (0.38, 0.967, 10.0), (0.39, 0.978, 10.0), (0.4, 0.984, 10.0), (0.42, 0.991, 10.0), (0.44, 0.994, 10.0), (0.46, 0.996, 10.0), (0.48, 0.997, 10.0), (0.5, 0.998, 10.0), (0.55, 0.999, 10.0), (0.6, 0.998, 10.0), (0.65, 0.999, 10.0), (0.7, 0.999, 10.0), (0.8, 0.998, 10.0), (0.9, 0.998, 10.0), (1.0, 0.997, 10.0), (1.2, 0.996, 10.0), (1.4, 0.991, 10.0), (1.6, 0.991, 10.0), (1.8, 0.982, 10.0), (2.0, 0.956, 10.0), (2.2, 0.87, 10.0), (2.4, 0.6, 10.0)], 1.723761, -1.0, -1.0, 0, 54.273851, 0, 4.18, 1)\nconst H_LAK54_MOLD = Glass(GlassID(AGF, 1754), 1, 2.9277611, -0.0147660748, 0.0206867604, 0.000708735021, -4.16441993e-5, 2.58153901e-6, 0.0, 0.0, 0.0, 0.0, 0.365, 1.692, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0098, -1.0, -1.0, 5.4, -1.0, 0, -1.0, [(0.28, 0.0, 10.0), (0.29, 0.04, 10.0), (0.3, 0.12, 10.0), (0.31, 0.24, 10.0), (0.32, 0.39, 10.0), (0.33, 0.53, 10.0), (0.34, 0.67, 10.0), (0.35, 0.78, 10.0), (0.36, 0.853, 10.0), (0.37, 0.905, 10.0), (0.38, 0.938, 10.0), (0.39, 0.957, 10.0), (0.4, 0.969, 10.0), (0.42, 0.979, 10.0), (0.44, 0.984, 10.0), (0.46, 0.987, 10.0), (0.48, 0.99, 10.0), (0.5, 0.992, 10.0), (0.55, 0.994, 10.0), (0.6, 0.994, 10.0), (0.65, 0.994, 10.0), (0.7, 0.995, 10.0), (0.8, 0.996, 10.0), (0.85, 0.997, 10.0), (0.9, 0.998, 10.0), (0.95, 0.998, 10.0), (1.0, 0.998, 10.0), (1.06, 0.998, 10.0), (1.2, 0.998, 10.0), (1.4, 0.998, 10.0), (1.6, 0.997, 10.0), (1.8, 0.985, 10.0), (2.0, 0.962, 10.0), (2.2, 0.899, 10.0), (2.4, 0.65, 10.0)], 1.728497, -1.0, -1.0, 0, 51.102214, 0, 4.01, 0)\nconst N_FK51_MOLD = Glass(GlassID(AGF, 1755), 2, 0.402845603, 0.000358331487, 0.779722736, 0.00992579562, 0.953460338, 177.526238, 0.0, 0.0, 0.0, 0.0, 0.29, 2.5, -1.83e-5, -7.89e-9, -1.63e-12, 3.74e-7, 3.46e-10, 0.15, 20.0, 0.0342, 4.3, 18.0, 13.3, 2.0, 3, 52.3, [(0.29, 0.01, 25.0), (0.3, 0.035, 25.0), (0.31, 0.12, 25.0), (0.32, 0.3, 25.0), (0.334, 0.63, 25.0), (0.35, 0.875, 25.0), (0.365, 0.963, 25.0), (0.37, 0.976, 25.0), (0.38, 0.988, 25.0), (0.39, 0.992, 25.0), (0.4, 0.993, 25.0), (0.405, 0.993, 25.0), (0.42, 0.992, 25.0), (0.436, 0.992, 25.0), (0.46, 0.993, 25.0), (0.5, 0.996, 25.0), (0.546, 0.997, 25.0), (0.58, 0.997, 25.0), (0.62, 0.996, 25.0), (0.66, 0.995, 25.0), (0.7, 0.995, 25.0), (1.06, 0.994, 25.0), (1.53, 0.98, 25.0), (1.97, 0.94, 25.0), (2.325, 0.84, 25.0), (2.5, 0.75, 25.0)], 1.484658, 2.2, 0.0, 0, 84.146056, 0, 3.66, 4)\nconst P_SK57_MOLD = Glass(GlassID(AGF, 1756), 1, 2.473063668, -0.01117810562, 0.01209876935, 0.0007748745456, -7.12908019e-5, 3.290007747e-6, 0.0, 0.0, 0.0, 0.0, 0.31, 2.5, 2.6e-6, 9.4e-9, -2.3e-11, 4.9e-7, 5.96e-10, 0.178, 20.0, -0.0024, 3.0, -1.0, 7.23, 4.0, 0, 52.3, [(0.31, 0.0, 25.0), (0.32, 0.16, 25.0), (0.334, 0.61, 25.0), (0.35, 0.87, 25.0), (0.365, 0.95, 25.0), (0.37, 0.96, 25.0), (0.38, 0.973, 25.0), (0.39, 0.98, 25.0), (0.4, 0.984, 25.0), (0.405, 0.985, 25.0), (0.42, 0.987, 25.0), (0.436, 0.989, 25.0), (0.46, 0.991, 25.0), (0.5, 0.995, 25.0), (0.546, 0.997, 25.0), (0.58, 0.997, 25.0), (0.62, 0.997, 25.0), (0.66, 0.997, 25.0), (0.7, 0.997, 25.0), (1.06, 0.997, 25.0), (1.53, 0.978, 25.0), (1.97, 0.89, 25.0), (2.325, 0.63, 25.0), (2.5, 0.4, 25.0)], 1.584061, 2.0, 3.0, 0, 58.956575, 0, 3.012, 3)\nconst L_LAM60_MOLD = Glass(GlassID(AGF, 1757), 2, 1.108755708, 0.01936029572, 0.8475056475, 0.002000002086, 1.354896422, 106.7885088, 0.0, 0.0, 0.0, 0.0, 0.309999999, 2.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, -0.0088, 2.0, 19.5, 7.4, -1.0, 0, 51.2, [(0.24, 0.0, 10.0), (0.25, 0.0, 10.0), (0.26, 0.0, 10.0), (0.27, 0.0, 10.0), (0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.09, 10.0), (0.32, 0.33, 10.0), (0.33, 0.56, 10.0), (0.34, 0.72, 10.0), (0.35, 0.83, 10.0), (0.36, 0.9, 10.0), (0.37, 0.94, 10.0), (0.38, 0.97, 10.0), (0.39, 0.977, 10.0), (0.4, 0.983, 10.0), (0.42, 0.988, 10.0), (0.44, 0.991, 10.0), (0.46, 0.993, 10.0), (0.48, 0.996, 10.0), (0.5, 0.997, 10.0), (0.55, 0.998, 10.0), (0.6, 0.998, 10.0), (0.65, 0.998, 10.0), (0.7, 0.999, 10.0), (0.8, 0.999, 10.0), (0.9, 0.999, 10.0), (1.0, 0.999, 10.0), (1.2, 0.999, 10.0), (1.4, 0.998, 10.0), (1.6, 0.997, 10.0), (1.8, 0.991, 10.0), (2.0, 0.974, 10.0), (2.2, 0.936, 10.0), (2.4, 0.75, 10.0)], 1.738585, 4.0, -1.0, 0, 48.990757, 0, 4.2, 4)\nconst S_LAL13_MOLD = Glass(GlassID(AGF, 1758), 2, 1.15067264, 0.0167483199, 0.646991168, 0.000278647233, 1.32830643, 102.511518, 0.0, 0.0, 0.0, 0.0, 0.3, 2.4, 7.171e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, -0.0081, 3.0, 3.0, 5.7, -1.0, 0, 52.0, [(0.3, 0.03, 10.0), (0.31, 0.08, 10.0), (0.32, 0.19, 10.0), (0.33, 0.34, 10.0), (0.34, 0.52, 10.0), (0.35, 0.68, 10.0), (0.36, 0.8, 10.0), (0.37, 0.88, 10.0), (0.38, 0.932, 10.0), (0.39, 0.958, 10.0), (0.4, 0.972, 10.0), (0.42, 0.986, 10.0), (0.44, 0.99, 10.0), (0.46, 0.993, 10.0), (0.48, 0.995, 10.0), (0.5, 0.996, 10.0), (0.55, 0.997, 10.0), (0.6, 0.995, 10.0), (0.65, 0.995, 10.0), (0.7, 0.996, 10.0), (0.8, 0.997, 10.0), (0.9, 0.996, 10.0), (1.0, 0.995, 10.0), (1.2, 0.995, 10.0), (1.4, 0.99, 10.0), (1.6, 0.99, 10.0), (1.8, 0.981, 10.0), (2.0, 0.958, 10.0), (2.2, 0.88, 10.0), (2.4, 0.66, 10.0)], 1.688895, -1.0, -1.0, 0, 52.855414, 0, 3.6, 1)\nconst TAF3_MOLD = Glass(GlassID(AGF, 1759), 1, 3.15871089, -0.0140753606, 0.0287918139, 3.34879169e-5, 8.0245017e-5, -2.88900113e-6, 0.0, 0.0, 0.0, 0.0, 0.25, 1.55, 3.8238e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0067, -1.0, 16.3, 6.3, 1.0, 0, 3.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.01, 10.0), (0.31, 0.05, 10.0), (0.32, 0.12, 10.0), (0.33, 0.25, 10.0), (0.34, 0.41, 10.0), (0.35, 0.51, 10.0), (0.36, 0.71, 10.0), (0.37, 0.82, 10.0), (0.38, 0.89, 10.0), (0.39, 0.93, 10.0), (0.4, 0.953, 10.0), (0.42, 0.97, 10.0), (0.44, 0.979, 10.0), (0.46, 0.987, 10.0), (0.48, 0.996, 10.0), (0.5, 0.996, 10.0), (0.55, 0.999, 10.0), (0.6, 0.999, 10.0), (0.65, 0.999, 10.0), (0.7, 0.999, 10.0), (0.75, 0.999, 10.0), (0.8, 0.999, 10.0), (0.9, 0.999, 10.0), (1.0, 0.998, 10.0), (1.06, 0.999, 10.0), (1.1, 0.998, 10.0), (1.3, 0.996, 10.0), (1.55, 0.997, 10.0)], 1.7998, -1.0, 2.0, 0, 46.24814, 0, 4.65, 0)\nconst D_K59_MOLD = Glass(GlassID(AGF, 1760), 1, 2.26619651, -0.0100434033, 0.00963297006, 0.000714825442, -0.000102309298, 6.58788276e-6, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 7.5, -1.0, 0, -1.0, [], 1.514796, -1.0, -1.0, 0, 63.09874, 0, 2.41, 0)\nconst TAC4_MOLD = Glass(GlassID(AGF, 1761), 1, 2.9254352, -0.0132275531, 0.0234911825, -0.000163595621, 9.21331502e-5, -4.84866833e-6, 0.0, 0.0, 0.0, 0.0, 0.25, 1.55, 9.2955e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0064, -1.0, 8.1, 5.2, 1.0, 1, 4.0, [(0.28, 0.0, 10.0), (0.29, 0.01, 10.0), (0.3, 0.05, 10.0), (0.31, 0.13, 10.0), (0.32, 0.26, 10.0), (0.33, 0.41, 10.0), (0.34, 0.57, 10.0), (0.35, 0.71, 10.0), (0.36, 0.82, 10.0), (0.37, 0.891, 10.0), (0.38, 0.934, 10.0), (0.39, 0.959, 10.0), (0.4, 0.972, 10.0), (0.42, 0.985, 10.0), (0.44, 0.988, 10.0), (0.46, 0.994, 10.0), (0.48, 0.997, 10.0), (0.5, 0.999, 10.0), (0.55, 0.999, 10.0), (0.6, 0.999, 10.0), (0.65, 0.999, 10.0), (0.7, 0.999, 10.0), (0.75, 0.999, 10.0), (0.8, 0.999, 10.0), (0.9, 0.999, 10.0), (1.0, 0.999, 10.0), (1.06, 0.999, 10.0), (1.1, 0.999, 10.0), (1.3, 0.999, 10.0), (1.55, 0.991, 10.0)], 1.728999, -1.0, 3.0, 0, 50.70639, 0, 4.06, 0)\nconst VC78 = Glass(GlassID(AGF, 1762), 1, 2.735136, -0.01182207, 0.01827911, 0.0001798584, 1.677301e-5, -5.307061e-7, 0.0, 0.0, 0.0, 0.0, 0.27, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0088, -1.0, -1.0, 0.0, 2.0, 2, 4.0, [(0.27, 0.032, 10.0), (0.28, 0.111, 10.0), (0.29, 0.232, 10.0), (0.3, 0.279, 10.0), (0.31, 0.552, 10.0), (0.32, 0.71, 10.0), (0.33, 0.826, 10.0), (0.34, 0.898, 10.0), (0.35, 0.943, 10.0), (0.36, 0.967, 10.0), (0.37, 0.982, 10.0), (0.38, 0.985, 10.0), (0.39, 0.988, 10.0), (0.4, 0.99, 10.0), (0.42, 0.99, 10.0), (0.44, 0.991, 10.0), (0.46, 0.994, 10.0), (0.48, 0.995, 10.0), (0.5, 0.995, 10.0), (0.55, 0.995, 10.0), (0.6, 0.997, 10.0), (0.7, 0.998, 10.0), (0.8, 0.998, 10.0), (1.06, 0.998, 10.0), (1.5, 0.998, 10.0), (2.0, 0.995, 10.0)], 1.669096, -1.0, -1.0, 0, 55.418322, 0, 3.44, 0)\nconst K_VC89_MOLD = Glass(GlassID(AGF, 1763), 1, 3.156483328, -0.008569421184, 0.03656210778, -0.0008804961946, 0.0002065655345, -7.019901337e-6, 0.0, 0.0, 0.0, 0.0, 0.269999999, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [], 1.804597, -1.0, -1.0, 0, 40.712764, 0, 1.0, 0)\nconst FDS9_MOLD = Glass(GlassID(AGF, 1764), 1, 3.25298133, -0.01489599, 0.0413434, 0.00540956, -0.000490511259, 4.51034874e-5, 0.0, 0.0, 0.0, 0.0, 0.46, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 2, -1.0, [(0.334, 1.0, 25.0), (0.35, 1.0, 25.0), (0.365, 1.0, 25.0), (0.37, 1.0, 25.0), (0.38, 1.0, 25.0), (0.39, 1.0, 25.0), (0.4, 1.0, 25.0), (0.42, 1.0, 25.0), (0.46, 1.0, 25.0), (0.5, 1.0, 25.0), (0.66, 1.0, 25.0), (1.06, 1.0, 25.0), (1.529, 1.0, 25.0), (2.325, 1.0, 25.0)], 1.845058, -1.0, -1.0, 0, 23.781322, 0, 1.0, 0)\nconst N_FK5_MOLD = Glass(GlassID(AGF, 1765), 2, 0.339383535, 0.0150237221, 0.839911284, 0.00482102014, 0.909090481, 97.8824387, 0.0, 0.0, 0.0, 0.0, 0.3, 2.5, -7.24e-6, 1.58e-8, -9.51e-12, 3.51e-7, 4.61e-10, 0.156, 20.0, 0.0036, 2.3, 2.0, 9.2, 2.0, 0, 4.0, [(0.27, 0.0, 25.0), (0.28, 0.11, 25.0), (0.29, 0.4, 25.0), (0.3, 0.7, 25.0), (0.31, 0.86, 25.0), (0.32, 0.93, 25.0), (0.334, 0.972, 25.0), (0.35, 0.987, 25.0), (0.365, 0.992, 25.0), (0.37, 0.992, 25.0), (0.38, 0.99, 25.0), (0.39, 0.994, 25.0), (0.4, 0.994, 25.0), (0.405, 0.994, 25.0), (0.42, 0.993, 25.0), (0.436, 0.993, 25.0), (0.46, 0.993, 25.0), (0.5, 0.993, 25.0), (0.546, 0.994, 25.0), (0.58, 0.994, 25.0), (0.62, 0.993, 25.0), (0.66, 0.994, 25.0), (0.7, 0.996, 25.0), (1.06, 0.998, 25.0), (1.53, 0.965, 25.0), (1.97, 0.93, 25.0), (2.325, 0.63, 25.0), (2.5, 0.38, 25.0)], 1.48439, 2.0, 1.0, 0, 69.958041, 0, 2.45, 1)\nconst TAF1_MOLD = Glass(GlassID(AGF, 1766), 1, 3.05438324, -0.0154525436, 0.0235532812, 0.0006611972, -2.8277377e-5, 2.20316121e-6, 0.0, 0.0, 0.0, 0.0, 0.25, 1.55, 5.4401e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0086, -1.0, 11.6, 5.9, 1.0, 0, 3.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.07, 10.0), (0.32, 0.22, 10.0), (0.33, 0.4, 10.0), (0.34, 0.56, 10.0), (0.35, 0.7, 10.0), (0.36, 0.81, 10.0), (0.37, 0.88, 10.0), (0.38, 0.92, 10.0), (0.39, 0.95, 10.0), (0.4, 0.968, 10.0), (0.42, 0.982, 10.0), (0.44, 0.99, 10.0), (0.46, 0.996, 10.0), (0.48, 0.997, 10.0), (0.5, 0.999, 10.0), (0.55, 0.999, 10.0), (0.6, 0.999, 10.0), (0.65, 0.999, 10.0), (0.7, 0.999, 10.0), (0.75, 0.998, 10.0), (0.8, 0.996, 10.0), (0.9, 0.999, 10.0), (1.0, 0.999, 10.0), (1.06, 0.999, 10.0), (1.1, 0.998, 10.0), (1.3, 0.999, 10.0), (1.55, 0.992, 10.0)], 1.767, -1.0, 2.0, 0, 49.270913, 0, 4.28, 0)\nconst VC78_MOLD = Glass(GlassID(AGF, 1767), 1, 2.72315491, -0.011795786, 0.0182393739, 0.000179456538, 1.67443241e-5, -5.29694392e-7, 0.0, 0.0, 0.0, 0.0, 0.2, 1.135, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0088, -1.0, -1.0, 0.0, 2.0, 2, 4.0, [(0.27, 0.032, 10.0), (0.28, 0.111, 10.0), (0.29, 0.232, 10.0), (0.3, 0.279, 10.0), (0.31, 0.552, 10.0), (0.32, 0.71, 10.0), (0.33, 0.826, 10.0), (0.34, 0.898, 10.0), (0.35, 0.943, 10.0), (0.36, 0.967, 10.0), (0.37, 0.982, 10.0), (0.38, 0.985, 10.0), (0.39, 0.988, 10.0), (0.4, 0.99, 10.0), (0.42, 0.99, 10.0), (0.44, 0.991, 10.0), (0.46, 0.994, 10.0), (0.48, 0.995, 10.0), (0.5, 0.995, 10.0), (0.55, 0.995, 10.0), (0.6, 0.997, 10.0), (0.7, 0.998, 10.0), (0.8, 0.998, 10.0), (1.06, 0.998, 10.0), (1.5, 0.998, 10.0), (2.0, 0.995, 10.0), (0.6, 0.999, 10.0), (0.65, 0.999, 10.0), (0.7, 0.999, 10.0), (0.75, 0.999, 10.0), (0.8, 0.999, 10.0), (0.9, 0.999, 10.0), (1.0, 0.999, 10.0), (1.06, 0.998, 10.0), (1.1, 0.998, 10.0), (1.3, 0.998, 10.0), (1.55, 0.993, 10.0)], 1.66547, -1.0, -1.0, 0, 55.117971, 0, 3.44, 0)\nconst H_ZLAF50B_MOLD = Glass(GlassID(AGF, 1768), 1, 3.15783794, -0.0153043586, 0.0266112335, 0.000705929142, -1.54365564e-5, 1.94771335e-6, 0.0, 0.0, 0.0, 0.0, 0.365, 1.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, -0.0093, -1.0, -1.0, 6.3, -1.0, 0, -1.0, [(0.28, 0.0, 10.0), (0.29, 0.0, 10.0), (0.3, 0.0, 10.0), (0.31, 0.0, 10.0), (0.32, 0.04, 10.0), (0.33, 0.14, 10.0), (0.34, 0.29, 10.0), (0.35, 0.46, 10.0), (0.36, 0.61, 10.0), (0.37, 0.74, 10.0), (0.38, 0.831, 10.0), (0.39, 0.888, 10.0), (0.4, 0.923, 10.0), (0.42, 0.956, 10.0), (0.44, 0.969, 10.0), (0.46, 0.976, 10.0), (0.48, 0.982, 10.0), (0.5, 0.986, 10.0), (0.55, 0.99, 10.0), (0.6, 0.992, 10.0), (0.65, 0.992, 10.0), (0.7, 0.994, 10.0), (0.8, 0.995, 10.0), (0.85, 0.997, 10.0), (0.9, 0.998, 10.0), (0.95, 0.998, 10.0), (1.0, 0.998, 10.0), (1.06, 0.998, 10.0), (1.2, 0.998, 10.0), (1.4, 0.998, 10.0), (1.6, 0.998, 10.0), (1.8, 0.997, 10.0), (2.0, 0.974, 10.0), (2.2, 0.926, 10.0), (2.4, 0.7, 10.0)], 1.7987, -1.0, -1.0, 0, 46.268881, 0, 4.72, 0)\nconst BACD14_MOLD = Glass(GlassID(AGF, 1769), 1, 2.51890371, -0.0118689364, 0.0122214182, 0.000789633586, -7.71764413e-5, 3.98293393e-6, 0.0, 0.0, 0.0, 0.0, 0.25, 1.55, 1.2212e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.002, -1.0, 2.7, 6.0, 3.0, 0, 4.0, [(0.28, 0.0, 10.0), (0.29, 0.01, 10.0), (0.3, 0.05, 10.0), (0.31, 0.17, 10.0), (0.32, 0.35, 10.0), (0.33, 0.56, 10.0), (0.34, 0.74, 10.0), (0.35, 0.85, 10.0), (0.36, 0.915, 10.0), (0.37, 0.952, 10.0), (0.38, 0.973, 10.0), (0.39, 0.985, 10.0), (0.4, 0.989, 10.0), (0.42, 0.992, 10.0), (0.44, 0.993, 10.0), (0.46, 0.994, 10.0), (0.48, 0.996, 10.0), (0.5, 0.999, 10.0), (0.55, 0.999, 10.0), (0.6, 0.999, 10.0), (0.65, 0.999, 10.0), (0.7, 0.999, 10.0), (0.75, 0.999, 10.0), (0.8, 0.999, 10.0), (0.9, 0.999, 10.0), (1.0, 0.999, 10.0), (1.06, 0.998, 10.0), (1.1, 0.998, 10.0), (1.3, 0.998, 10.0), (1.55, 0.993, 10.0)], 1.598511, -1.0, 5.0, 0, 60.231575, 0, 3.43, 0)\nconst N_LAK22_MOLD = Glass(GlassID(AGF, 1770), 2, 0.629412843, 0.00132678736, 1.03372876, 0.0158399692, 1.0775735, 104.339117, 0.0, 0.0, 0.0, 0.0, 0.31, 2.5, 1.36e-6, 1.49e-8, -1.29e-11, 3.41e-7, 2.09e-10, 0.262, 20.0, -0.0031, 2.3, 3.5, 6.6, 2.0, 0, 51.2, [(0.31, 0.02, 25.0), (0.32, 0.1, 25.0), (0.334, 0.35, 25.0), (0.35, 0.655, 25.0), (0.365, 0.84, 25.0), (0.37, 0.873, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.964, 25.0), (0.405, 0.968, 25.0), (0.42, 0.973, 25.0), (0.436, 0.975, 25.0), (0.46, 0.98, 25.0), (0.5, 0.988, 25.0), (0.546, 0.993, 25.0), (0.58, 0.993, 25.0), (0.62, 0.991, 25.0), (0.66, 0.992, 25.0), (0.7, 0.994, 25.0), (1.06, 0.994, 25.0), (1.53, 0.978, 25.0), (1.97, 0.9, 25.0), (2.325, 0.62, 25.0), (2.5, 0.37, 25.0)], 1.646725, 1.0, 2.0, 0, 55.510774, 0, 3.768, 3)\nend # module\n", "meta": {"hexsha": "25e6c52ff07b30a1ed7e9f3eec9933acb1b0e928", "size": 32278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/data/jl/RPO.jl", "max_stars_repo_name": "rambunctiousapple/GlassCat", "max_stars_repo_head_hexsha": "5e10affbed57311088f78f461e8f83f6f5874c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/data/jl/RPO.jl", "max_issues_repo_name": "rambunctiousapple/GlassCat", "max_issues_repo_head_hexsha": "5e10affbed57311088f78f461e8f83f6f5874c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-12T17:20:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-12T17:20:35.000Z", "max_forks_repo_path": "src/data/jl/RPO.jl", "max_forks_repo_name": "rambunctiousapple/GlassCat", "max_forks_repo_head_hexsha": "5e10affbed57311088f78f461e8f83f6f5874c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-29T23:16:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T23:16:46.000Z", "avg_line_length": 658.7346938776, "max_line_length": 1048, "alphanum_fraction": 0.5115248776, "num_tokens": 23476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.19577374901865274}} {"text": "module t\n\nusing BioSequences\n\nstruct Unsafe end\n\nconst N_AA = length(alphabet(AminoAcid))\n\nstruct CodonSet <: AbstractSet{RNACodon}\n x::UInt64\n\n CodonSet(x::UInt64, ::Unsafe) = new(x)\nend\nCodonSet() = CodonSet(UInt64(0), Unsafe())\nCodonSet(itr) = foldl(push, itr, init=CodonSet())\n\nfunction Base.iterate(x::CodonSet, s::UInt64=x.x)\n iszero(s) ? nothing : (reinterpret(RNACodon, trailing_zeros(s)), s & (s-1))\nend\n\nfunction push(s::CodonSet, x::RNACodon)\n CodonSet(s.x | (UInt64(1) << (reinterpret(UInt64, x) & 63)), Unsafe())\nend\n\nBase.length(x::CodonSet) = count_ones(x.x)\nBase.in(c::RNACodon, s::CodonSet) = isodd(s.x >>> (reinterpret(UInt64, c) & 63))\ndelete(s::CodonSet, x::RNACodon) = setdiff(s, CodonSet((x,)))\nBase.issubset(a::CodonSet, b::CodonSet) = isempty(setdiff(a, b))\nBase.filter(f, s::CodonSet) = CodonSet(Iterators.filter(f, s))\nBase.setdiff(a::CodonSet, b::Vararg{CodonSet}) = CodonSet(a.x & ~(union(b...).x), Unsafe())\n\nfor (name, f) in [(:union, |), (:intersect, &), (:symdiff, ⊻)]\n @eval function Base.$(name)(a::CodonSet, b::Vararg{CodonSet}) \n CodonSet(mapreduce(i -> i.x, $f, b, init=a.x), Unsafe())\n end\nend\n\nstruct ReverseGeneticCode <: AbstractDict{AminoAcid, CodonSet}\n name::String\n sets::NTuple{N_AA-1, CodonSet}\nend\n\nfunction ReverseGeneticCode(x::BioSequences.GeneticCode)\n ind(aa::AminoAcid) = reinterpret(UInt8, aa) + 1\n\n sets = fill(CodonSet(), N_AA-1)\n for i in Int64(0):Int64(63)\n aa = x.tbl[i + 1]\n sets[ind(aa)] = push(sets[ind(aa)], reinterpret(RNACodon, i))\n end\n\n # Ambiguous amino acids\n for (n, (a, b)) in [(AA_B, (AA_D, AA_N)), (AA_J, (AA_I, AA_L)), (AA_Z, (AA_E, AA_Q))]\n sets[ind(n)] = sets[ind(a)] ∪ sets[ind(b)]\n end\n\n # AA_X codes for all amino acids\n sets[ind(AA_X)] = CodonSet(typemax(UInt64), Unsafe())\n\n # Pyrrolysine and selenocysteine are never part of the \"forward\" genetic\n # code, but can be unambiguously resolved in the reverse genetic code.\n sets[ind(AA_U)] = CodonSet((mer\"UGA\"r,))\n sets[ind(AA_O)] = CodonSet((mer\"UAG\"r,))\n\n ReverseGeneticCode(x.name, Tuple(sets))\nend\n\nfor symbol in names(BioSequences, all=true)\n Base.isdeprecated(BioSequences, symbol) && continue\n isdefined(BioSequences, symbol) || continue\n thing = getproperty(BioSequences, symbol)\n thing isa BioSequences.GeneticCode || continue\n @eval const $(Symbol(:rev_, symbol)) = ReverseGeneticCode($thing)\nend\n\nfunction Base.getindex(s::ReverseGeneticCode, a::AminoAcid)\n if reinterpret(UInt8, a) > (N_AA - 2) # cannot translate gap\n error(\"Cannot reverse translate element: \", a)\n end\n @inbounds s.sets[reinterpret(UInt8, a) + 1]\nend\n\nfunction reverse_translate!(\n v::Vector{CodonSet},\n seq::AminoAcidSeq,\n code=rev_standard_genetic_code\n)\n resize!(v, length(seq))\n @inbounds for i in eachindex(v)\n v[i] = code[seq[i]]\n end\n v\nend\n\nfunction reverse_translate(seq::AminoAcidSeq, code=rev_standard_genetic_code)\n reverse_translate!(Vector{CodonSet}(undef, length(seq)), seq, code)\nend\n\nend # module\n", "meta": {"hexsha": "47d4aa8a9012def3843c05e753a916cf2e94f212", "size": 3081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "revtrans.jl", "max_stars_repo_name": "jakobnissen/play", "max_stars_repo_head_hexsha": "fe8c930757d6dbf451b3250ca0794e2fe66155aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "revtrans.jl", "max_issues_repo_name": "jakobnissen/play", "max_issues_repo_head_hexsha": "fe8c930757d6dbf451b3250ca0794e2fe66155aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "revtrans.jl", "max_forks_repo_name": "jakobnissen/play", "max_forks_repo_head_hexsha": "fe8c930757d6dbf451b3250ca0794e2fe66155aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.81, "max_line_length": 91, "alphanum_fraction": 0.6653683869, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1957686634201141}} {"text": "# This file is a part of Julia, but is derived from\n# https://github.com/google/double-conversion which has the following license\n#\n# Copyright 2006-2014, the V8 project authors. All rights reserved.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nstruct Float\n s::UInt64\n e::Int32\n de::Int32\nend\n\nFloat() = Float(0,0,0)\nFloat(x,y) = Float(x,y,Int32(0))\nFloat(d::AbstractFloat) = Float(_significand(d), _exponent(d))\n\n# Consts\nconst Float10MSBits = 0xFFC0000000000000 # used normalize(Float)\nconst FloatSignMask = 0x8000000000000000 # used in normalize(Float)\nconst FloatSignificandSize = Int32(64)\n\nfunction normalize(v::Float)\n f = v.s\n e::Int32 = v.e\n while (f & Float10MSBits) == 0\n f <<= 10\n e -= 10\n end\n while (f & FloatSignMask) == 0\n f <<= 1\n e -= 1\n end\n return Float(f,e)\nend\nfunction normalize(v::Float64)\n s = _significand(v); e = _exponent(v)\n while (s & HiddenBit(Float64)) == 0\n s <<= UInt64(1)\n e -= Int32(1)\n end\n s <<= UInt64(FloatSignificandSize - SignificandSize(Float64))\n e -= Int32( FloatSignificandSize - SignificandSize(Float64))\n return Float(s, e)\nend\n\n# Float128\n#DenormalExponent(::Type{Float128}) = Int32(-ExponentBias(Float128) + 1)\n#ExponentMask(::Type{Float128}) = 0x7fff0000000000000000000000000000\n#PhysicalSignificandSize(::Type{Float128}) = Int32(112)\n#SignificandSize(::Type{Float128}) = Int32(113)\n#ExponentBias(::Type{Float128}) = Int32(0x00003fff + PhysicalSignificandSize(Float128))\n#SignificandMask(::Type{Float128}) = 0x0000ffffffffffffffffffffffffffff\n#HiddenBit(::Type{Float128}) = 0x00010000000000000000000000000000\n#uint_t(d::Float128) = reinterpret(UInt128,d)\n# Float64\nDenormalExponent(::Type{Float64}) = Int32(-ExponentBias(Float64) + 1)\nExponentMask(::Type{Float64}) = 0x7FF0000000000000\nPhysicalSignificandSize(::Type{Float64}) = Int32(52)\nSignificandSize(::Type{Float64}) = Int32(53)\nExponentBias(::Type{Float64}) = Int32(0x3FF + PhysicalSignificandSize(Float64))\nSignificandMask(::Type{Float64}) = 0x000FFFFFFFFFFFFF\nHiddenBit(::Type{Float64}) = 0x0010000000000000\nuint_t(d::Float64) = reinterpret(UInt64,d)\n# Float32\nDenormalExponent(::Type{Float32}) = Int32(-ExponentBias(Float32) + 1)\nExponentMask(::Type{Float32}) = 0x7F800000\nPhysicalSignificandSize(::Type{Float32}) = Int32(23)\nSignificandSize(::Type{Float32}) = Int32(24)\nExponentBias(::Type{Float32}) = Int32(0x7F + PhysicalSignificandSize(Float32))\nSignificandMask(::Type{Float32}) = 0x007FFFFF\nHiddenBit(::Type{Float32}) = 0x00800000\nuint_t(d::Float32) = reinterpret(UInt32,d)\n# Float16\nDenormalExponent(::Type{Float16}) = Int32(-ExponentBias(Float16) + 1)\nExponentMask(::Type{Float16}) = 0x7c00\nPhysicalSignificandSize(::Type{Float16}) = Int32(10)\nSignificandSize(::Type{Float16}) = Int32(11)\nExponentBias(::Type{Float16}) = Int32(0x000f + PhysicalSignificandSize(Float16))\nSignificandMask(::Type{Float16}) = 0x03ff\nHiddenBit(::Type{Float16}) = 0x0400\nuint_t(d::Float16) = reinterpret(UInt16,d)\n\nfunction _exponent(d::T) where T<:AbstractFloat\n isdenormal(d) && return DenormalExponent(T)\n biased_e::Int32 = Int32((uint_t(d) & ExponentMask(T)) >> PhysicalSignificandSize(T))\n return Int32(biased_e - ExponentBias(T))\nend\nfunction _significand(d::T) where T<:AbstractFloat\n s = uint_t(d) & SignificandMask(T)\n return !isdenormal(d) ? s + HiddenBit(T) : s\nend\nisdenormal{T<:AbstractFloat}(d::T) = (uint_t(d) & ExponentMask(T)) == 0\n\nfunction normalizedbound(f::AbstractFloat)\n v = Float(_significand(f),_exponent(f))\n m_plus = normalize(Float((v.s << 1) + 1, v.e - 1))\n if lowerboundaryiscloser(f)\n m_minus = Float((v.s << 2) - 1, v.e - 2)\n else\n m_minus = Float((v.s << 1) - 1, v.e - 1)\n end\n return Float(m_minus.s << (m_minus.e - m_plus.e), m_plus.e), m_plus\nend\nfunction lowerboundaryiscloser(f::T) where T<:AbstractFloat\n physical_significand_is_zero = (uint_t(f) & SignificandMask(T)) == 0\n return physical_significand_is_zero && (_exponent(f) != DenormalExponent(T))\nend\n\n(-)(a::Float,b::Float) = Float(a.s - b.s,a.e,a.de)\n\nconst FloatM32 = 0xFFFFFFFF\n\nfunction (*)(this::Float,other::Float)\n a::UInt64 = this.s >> 32\n b::UInt64 = this.s & FloatM32\n c::UInt64 = other.s >> 32\n d::UInt64 = other.s & FloatM32\n ac::UInt64 = a * c\n bc::UInt64 = b * c\n ad::UInt64 = a * d\n bd::UInt64 = b * d\n tmp::UInt64 = (bd >> 32) + (ad & FloatM32) + (bc & FloatM32)\n # By adding 1U << 31 to tmp we round the final result.\n # Halfway cases will be round up.\n tmp += UInt64(1) << 31\n result_f::UInt64 = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32)\n return Float(result_f,this.e + other.e + 64,this.de)\nend\n\nconst CachedPowers = Float[\n Float(0xfa8fd5a0081c0288, -1220, -348),\n Float(0xbaaee17fa23ebf76, -1193, -340),\n Float(0x8b16fb203055ac76, -1166, -332),\n Float(0xcf42894a5dce35ea, -1140, -324),\n Float(0x9a6bb0aa55653b2d, -1113, -316),\n Float(0xe61acf033d1a45df, -1087, -308),\n Float(0xab70fe17c79ac6ca, -1060, -300),\n Float(0xff77b1fcbebcdc4f, -1034, -292),\n Float(0xbe5691ef416bd60c, -1007, -284),\n Float(0x8dd01fad907ffc3c, -980, -276),\n Float(0xd3515c2831559a83, -954, -268),\n Float(0x9d71ac8fada6c9b5, -927, -260),\n Float(0xea9c227723ee8bcb, -901, -252),\n Float(0xaecc49914078536d, -874, -244),\n Float(0x823c12795db6ce57, -847, -236),\n Float(0xc21094364dfb5637, -821, -228),\n Float(0x9096ea6f3848984f, -794, -220),\n Float(0xd77485cb25823ac7, -768, -212),\n Float(0xa086cfcd97bf97f4, -741, -204),\n Float(0xef340a98172aace5, -715, -196),\n Float(0xb23867fb2a35b28e, -688, -188),\n Float(0x84c8d4dfd2c63f3b, -661, -180),\n Float(0xc5dd44271ad3cdba, -635, -172),\n Float(0x936b9fcebb25c996, -608, -164),\n Float(0xdbac6c247d62a584, -582, -156),\n Float(0xa3ab66580d5fdaf6, -555, -148),\n Float(0xf3e2f893dec3f126, -529, -140),\n Float(0xb5b5ada8aaff80b8, -502, -132),\n Float(0x87625f056c7c4a8b, -475, -124),\n Float(0xc9bcff6034c13053, -449, -116),\n Float(0x964e858c91ba2655, -422, -108),\n Float(0xdff9772470297ebd, -396, -100),\n Float(0xa6dfbd9fb8e5b88f, -369, -92),\n Float(0xf8a95fcf88747d94, -343, -84),\n Float(0xb94470938fa89bcf, -316, -76),\n Float(0x8a08f0f8bf0f156b, -289, -68),\n Float(0xcdb02555653131b6, -263, -60),\n Float(0x993fe2c6d07b7fac, -236, -52),\n Float(0xe45c10c42a2b3b06, -210, -44),\n Float(0xaa242499697392d3, -183, -36),\n Float(0xfd87b5f28300ca0e, -157, -28),\n Float(0xbce5086492111aeb, -130, -20),\n Float(0x8cbccc096f5088cc, -103, -12),\n Float(0xd1b71758e219652c, -77, -4),\n Float(0x9c40000000000000, -50, 4),\n Float(0xe8d4a51000000000, -24, 12),\n Float(0xad78ebc5ac620000, 3, 20),\n Float(0x813f3978f8940984, 30, 28),\n Float(0xc097ce7bc90715b3, 56, 36),\n Float(0x8f7e32ce7bea5c70, 83, 44),\n Float(0xd5d238a4abe98068, 109, 52),\n Float(0x9f4f2726179a2245, 136, 60),\n Float(0xed63a231d4c4fb27, 162, 68),\n Float(0xb0de65388cc8ada8, 189, 76),\n Float(0x83c7088e1aab65db, 216, 84),\n Float(0xc45d1df942711d9a, 242, 92),\n Float(0x924d692ca61be758, 269, 100),\n Float(0xda01ee641a708dea, 295, 108),\n Float(0xa26da3999aef774a, 322, 116),\n Float(0xf209787bb47d6b85, 348, 124),\n Float(0xb454e4a179dd1877, 375, 132),\n Float(0x865b86925b9bc5c2, 402, 140),\n Float(0xc83553c5c8965d3d, 428, 148),\n Float(0x952ab45cfa97a0b3, 455, 156),\n Float(0xde469fbd99a05fe3, 481, 164),\n Float(0xa59bc234db398c25, 508, 172),\n Float(0xf6c69a72a3989f5c, 534, 180),\n Float(0xb7dcbf5354e9bece, 561, 188),\n Float(0x88fcf317f22241e2, 588, 196),\n Float(0xcc20ce9bd35c78a5, 614, 204),\n Float(0x98165af37b2153df, 641, 212),\n Float(0xe2a0b5dc971f303a, 667, 220),\n Float(0xa8d9d1535ce3b396, 694, 228),\n Float(0xfb9b7cd9a4a7443c, 720, 236),\n Float(0xbb764c4ca7a44410, 747, 244),\n Float(0x8bab8eefb6409c1a, 774, 252),\n Float(0xd01fef10a657842c, 800, 260),\n Float(0x9b10a4e5e9913129, 827, 268),\n Float(0xe7109bfba19c0c9d, 853, 276),\n Float(0xac2820d9623bf429, 880, 284),\n Float(0x80444b5e7aa7cf85, 907, 292),\n Float(0xbf21e44003acdd2d, 933, 300),\n Float(0x8e679c2f5e44ff8f, 960, 308),\n Float(0xd433179d9c8cb841, 986, 316),\n Float(0x9e19db92b4e31ba9, 1013, 324),\n Float(0xeb96bf6ebadf77d9, 1039, 332),\n Float(0xaf87023b9bf0ee6b, 1066, 340)]\n\nconst CachedPowersLength = length(CachedPowers)\nconst CachedPowersOffset = 348 # -1 * the first decimal_exponent.\nconst D_1_LOG2_10 = 0.30102999566398114 # 1 / lg(10)\n# Difference between the decimal exponents in the table above.\nconst DecimalExponentDistance = 8\nconst MinDecimalExponent = -348\nconst MaxDecimalExponent = 340\n\nfunction binexp_cache(min_exponent,max_exponent)\n k = ceil(Integer,(min_exponent+63)*D_1_LOG2_10)\n index = div(CachedPowersOffset+k-1,DecimalExponentDistance) + 1\n cp = CachedPowers[index+1]\n return cp\nend\n", "meta": {"hexsha": "2adec178d2fd6570483d5217f7aca2da53295d4e", "size": 10186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "base/grisu/float.jl", "max_stars_repo_name": "odow/julia", "max_stars_repo_head_hexsha": "d394a934a5d66a933b47996e5b8b4cd572b16dc8", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "base/grisu/float.jl", "max_issues_repo_name": "odow/julia", "max_issues_repo_head_hexsha": "d394a934a5d66a933b47996e5b8b4cd572b16dc8", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/grisu/float.jl", "max_forks_repo_name": "odow/julia", "max_forks_repo_head_hexsha": "d394a934a5d66a933b47996e5b8b4cd572b16dc8", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6342412451, "max_line_length": 87, "alphanum_fraction": 0.7165717652, "num_tokens": 3880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19569420631072648}} {"text": "\n\n#=\nmodule Gaugefields_2D_mpi_module\n using LinearAlgebra\n import ..AbstractGaugefields_module:AbstractGaugefields,Shifted_Gaugefields,shift_U,\n Adjoint_Gaugefields,set_wing_U!,Abstractfields,construct_staple!,clear_U!,\n calculate_Plaquette\n import Base\n import ..Gaugefields_4D_module:Gaugefields_4D\n \n using MPI\n =#\n\n #const comm = MPI.COMM_WORLD\n\n \"\"\"\n `Gaugefields_2D_nowing_mpi{NC} <: Gaugefields_2D{NC}`\n\n MPI version of SU(N) Gauge fields in four dimensional lattice. \n \"\"\"\n struct Gaugefields_2D_nowing_mpi{NC} <: Gaugefields_2D{NC}\n U::Array{ComplexF64,4}\n NX::Int64\n #NY::Int64\n #NZ::Int64\n NT::Int64\n NDW::Int64\n NV::Int64\n NC::Int64\n PEs::NTuple{2,Int64}\n PN::NTuple{2,Int64}\n mpiinit::Bool\n myrank::Int64\n nprocs::Int64\n myrank_xt::NTuple{2,Int64}\n mpi::Bool\n verbose_print::Verbose_print\n Ushifted::Array{ComplexF64,4}\n tempmatrix::Array{ComplexF64,3}\n positions::Vector{Int64}\n send_ranks::Dict{Int64,Data_sent{NC}}\n win::MPI.Win\n win_i::MPI.Win\n win_1i::MPI.Win\n countvec::Vector{Int64}\n otherranks::Vector{Int64}\n win_other::MPI.Win\n your_ranks::Matrix{Int64}\n \n\n function Gaugefields_2D_nowing_mpi(NC::T,NX::T,NT::T,PEs;mpiinit=true,\n verbose_level = 2) where T<: Integer\n NV = NX*NT\n NDW = 0\n @assert NX % PEs[1] == 0 \"NX % PEs[1] should be 0. Now NX = $NX and PEs = $PEs\"\n #@assert NY % PEs[2] == 0 \"NY % PEs[2] should be 0. Now NY = $NY and PEs = $PEs\"\n #@assert NZ % PEs[3] == 0 \"NZ % PEs[3] should be 0. Now NZ = $NZ and PEs = $PEs\"\n @assert NT % PEs[2] == 0 \"NT % PEs[2] should be 0. Now NT = $NT and PEs = $PEs\"\n\n PN = (NX ÷ PEs[1],\n #NY ÷ PEs[2],\n #NZ ÷ PEs[3],\n NT ÷ PEs[2],\n )\n\n if mpiinit == false\n MPI.Init()\n mpiinit = true\n end\n\n comm = MPI.COMM_WORLD\n\n nprocs = MPI.Comm_size(comm)\n @assert prod(PEs) == nprocs \"num. of MPI process should be prod(PEs). Now nprocs = $nprocs and PEs = $PEs\"\n myrank = MPI.Comm_rank(comm)\n\n verbose_print = Verbose_print(verbose_level,myid = myrank)\n\n myrank_xt = get_myrank_xt(myrank,PEs)\n\n #println(\"Hello world, I am $(MPI.Comm_rank(comm)) of $(MPI.Comm_size(comm))\")\n\n U = zeros(ComplexF64,NC,NC,PN[1],PN[2])\n Ushifted = zero(U)\n #U = Array{Array{ComplexF64,6}}(undef,4)\n #for μ=1:4\n # U[μ] = zeros(ComplexF64,NC,NC,NX+2NDW,NY+2NDW,NZ+2NDW,NT+2NDW)\n #end\n tempmatrix = zeros(ComplexF64,NC,NC,prod(PN))\n positions = zeros(Int64,prod(PN)) \n send_ranks = Dict{Int64,Data_sent{NC}}()\n mpi = true\n win = MPI.Win_create(tempmatrix,comm)\n win_i = MPI.Win_create(positions,comm)\n countvec = zeros(Int64,1)\n win_1i = MPI.Win_create(countvec,comm)\n\n otherranks = zeros(Int64,nprocs)\n otherranks .= 0\n win_other = MPI.Win_create(otherranks,comm)\n your_ranks = zeros(Int64,nprocs,nprocs)\n\n\n return new{NC}(U,NX,NT,NDW,NV,NC,Tuple(PEs),PN,mpiinit,myrank,nprocs,myrank_xt,mpi,verbose_print,\n Ushifted,tempmatrix,positions,send_ranks,\n win,win_i,win_1i,countvec,otherranks,win_other,your_ranks)\n end\n end\n\n function get_myrank_xt(myrank,PEs)\n #myrank = (myrank_t)*PEs[1] + myrank_x\n myrank_x = myrank % PEs[1] \n myrank_t = (myrank - myrank_x) ÷ PEs[1]\n return myrank_x,myrank_t\n end\n\n function get_myrank(U::T) where T <: Gaugefields_2D_nowing_mpi\n return U.myrank\n end\n\n function get_myrank(U::Array{T,1}) where T <: Gaugefields_2D_nowing_mpi\n return U[1].myrank\n end\n\n function get_nprocs(U::T) where T <: Gaugefields_2D_nowing_mpi\n return U.nprocs\n end\n\n function get_nprocs(U::Array{T,1}) where T <: Gaugefields_2D_nowing_mpi\n return U[1].nprocs\n end\n\n\n function barrier(x::T) where T <: Gaugefields_2D_nowing_mpi\n #println(\"ba\")\n MPI.Barrier(comm)\n end\n\n function Base.setindex!(x::Gaugefields_2D_nowing_mpi,v,i1,i2,i3,i6) \n error(\"Each element can not be accessed by global index in $(typeof(x)). Use setvalue! function\")\n #x.U[i1,i2,i3 + x.NDW,i4 + x.NDW,i5 + x.NDW,i6 + x.NDW] = v\n end\n\n function Base.getindex(x::Gaugefields_2D_nowing_mpi,i1,i2,i3,i6) \n error(\"Each element can not be accessed by global index in $(typeof(x)) Use getvalue function\")\n #return x.U[i1,i2,i3 .+ x.NDW,i4 .+ x.NDW,i5 .+ x.NDW,i6 .+ x.NDW]\n end\n\n function Base.setindex!(x::Adjoint_Gaugefields{T},v,i1,i2,i3,i6) where T <: Gaugefields_2D_nowing_mpi #U'\n error(\"type $(typeof(U)) has no setindex method. This type is read only.\")\n #x.U[i1,i2,i3 + x.NDW,i4 + x.NDW,i5 + x.NDW,i6 + x.NDW] = v\n end\n\n function Base.getindex(x::Adjoint_Gaugefields{T},i1,i2,i3,i6) where T <: Gaugefields_2D_nowing_mpi #U'\n error(\"Each element can not be accessed by global index in $(typeof(x)) Use getvalue function\")\n #return x.U[i1,i2,i3 .+ x.NDW,i4 .+ x.NDW,i5 .+ x.NDW,i6 .+ x.NDW]\n end\n\n\n @inline function getvalue(x::Gaugefields_2D_nowing_mpi,i1,i2,i3, i6)\n @inbounds return x.U[i1,i2,i3,i6 ]\n end\n\n @inline function setvalue!(x::Gaugefields_2D_nowing_mpi,v,i1,i2,i3, i6)\n @inbounds x.U[i1,i2,i3,i6 ] = v\n end\n\n @inline function getvalue(U::Adjoint_Gaugefields{T},i1,i2,i3,i6) where T <: Abstractfields #U'\n @inbounds return conj(getvalue(U.parent,i2,i1,i3,i6))\n end\n\n\n\n\n\n\n function identityGaugefields_2D_nowing_mpi(NC,NX, NT,PEs;mpiinit = true,verbose_level = 2,randomnumber=\"Random\")\n U = Gaugefields_2D_nowing_mpi(NC,NX, NT,PEs,mpiinit = mpiinit,verbose_level = verbose_level)\n v = 1\n\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n @simd for ic=1:NC\n setvalue!(U,v,ic,ic,ix, it)\n end\n end\n #end\n #end\n end\n #println(\"setwing\")\n set_wing_U!(U)\n\n return U\n end\n\n function randomGaugefields_2D_nowing_mpi(NC,NX, NT,PEs;mpiinit = true,verbose_level= 2,randomnumber=\"Random\")\n U = Gaugefields_2D_nowing_mpi(NC,NX, NT,PEs,mpiinit = mpiinit,verbose_level = verbose_level)\n v = 1\n\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n for jc=1:NC\n @simd for ic=1:NC\n v = rand()-0.5 + im*(rand()-0.5)\n setvalue!(U,v,ic,jc,ix, it)\n end\n end\n end\n #end\n #end\n end\n #println(\"setwing\")\n normalize_U!(U)\n set_wing_U!(U)\n\n return U\n end\n\n function clear_U!(U::Gaugefields_2D_nowing_mpi{NC}) where NC\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n for jc=1:NC\n @simd for ic=1:NC\n v = 0\n @inbounds setvalue!(U,v,ic,jc,ix, it)\n #@inbounds Uμ[k1,k2,ix, it] = 0\n end\n end\n end\n #end\n #end\n end\n set_wing_U!(U)\n end\n\n function clear_U!(U::Gaugefields_2D_nowing_mpi{NC},iseven::Bool) where NC\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n evenodd = ifelse( (ix+ it) % 2 ==0, true,false)\n if evenodd == iseven \n for k2=1:NC \n for k1=1:NC\n v = 0\n @inbounds setvalue!(U,v,k1,k2,ix, it)\n end\n end\n end\n end\n #end\n #end\n end\n set_wing_U!(U)\n end\n\n function clear_U!(U::Gaugefields_2D_nowing_mpi{NC},filternumber::N,filterindex::N) where {NC,N <: Integer}\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n filter = ((ix+ it)) % filternumber\n #evenodd = ifelse( (ix+ it) % filternumber ==0, true,false)\n if filter == filterindex \n for k2=1:NC \n for k1=1:NC\n v = 0\n @inbounds setvalue!(U,v,k1,k2,ix, it)\n end\n end\n end\n end\n #end\n #end\n end\n set_wing_U!(U)\n end\n\n function add_U!(c::Gaugefields_2D_nowing_mpi{NC},a::T1) where {NC,T1 <: Abstractfields}\n for it=1:c.PN[2]\n #for iz=1:c.PN[3]\n #for iy=1:c.PN[2]\n for ix=1:c.PN[1]\n\n for k2=1:NC \n @simd for k1=1:NC\n av = getvalue(a,k1,k2,ix, it)\n cv = getvalue(c,k1,k2,ix, it)\n v = cv + av\n setvalue!(c,v,k1,k2,ix, it)\n #c[k1,k2,ix, it] += a[k1,k2,ix, it]\n end\n end\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function add_U!(c::Gaugefields_2D_nowing_mpi{NC},a::T1,iseven::Bool) where {NC,T1 <: Abstractfields}\n @inbounds for it=1:c.PN[2]\n #for iz=1:c.PN[3]\n #for iy=1:c.PN[2]\n for ix=1:c.PN[1]\n evenodd = ifelse( (ix+ it) % 2 ==0, true,false)\n if evenodd == iseven\n for k2=1:NC \n @simd for k1=1:NC\n av = getvalue(a,k1,k2,ix, it)\n cv = getvalue(c,k1,k2,ix, it)\n v = cv + av\n setvalue!(c,v,k1,k2,ix, it)\n #c[k1,k2,ix, it] += a[k1,k2,ix, it]\n end\n end\n end\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function add_U!(c::Gaugefields_2D_nowing_mpi{NC},α::N,a::T1) where {NC,T1 <: Abstractfields, N<:Number}\n #@inbounds for i=1:length(c.U)\n # c.U[i] += α*a.U[i]\n #end\n #return \n\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n @inbounds for it=1:c.PN[2]\n #for iz=1:c.PN[3]\n #for iy=1:c.PN[2]\n for ix=1:c.PN[1]\n for k2=1:NC \n @simd for k1=1:NC\n v = getvalue(c,k1,k2,ix, it) + α*getvalue(a,k1,k2,ix, it)\n setvalue!(c,v,k1,k2,ix, it)\n #c[k1,k2,ix, it] += α*a[k1,k2,ix, it]\n end\n end\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function substitute_U!(a::Array{T1,1},b::Array{T2,1}) where {T1 <: Gaugefields_2D_nowing_mpi,T2 <: Gaugefields_2D_nowing_mpi}\n for μ=1:2\n substitute_U!(a[μ],b[μ])\n end\n end\n\n function substitute_U!(a::Array{T1,1},b::Array{T2,1},iseven::Bool) where {T1 <: Gaugefields_2D_nowing_mpi,T2 <: Gaugefields_2D_nowing_mpi}\n for μ=1:2\n substitute_U!(a[μ],b[μ],iseven)\n end\n end\n\n\n function substitute_U!(U::Gaugefields_2D_nowing_mpi{NC},b::T2) where {NC, T2 <: Abstractfields}\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n for k2=1:NC \n for k1=1:NC\n v = getvalue(b,k1,k2,ix, it)\n #v = b[k1,k2,ix, it]\n @inbounds setvalue!(U,v,k1,k2,ix, it)\n end\n end\n end\n #end\n #end\n end\n set_wing_U!(U)\n\n end\n\n\n function substitute_U!(U::Gaugefields_2D_nowing_mpi{NC},b::T2,iseven::Bool) where {NC, T2 <: Abstractfields}\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n evenodd = ifelse( (ix+ it) % 2 ==0, true,false)\n if evenodd == iseven\n for k2=1:NC \n for k1=1:NC\n v = getvalue(b,k1,k2,ix, it)\n #v = b[k1,k2,ix, it]\n @inbounds setvalue!(U,v,k1,k2,ix, it)\n end\n end\n end\n end\n #end\n #end\n end\n set_wing_U!(U)\n\n end\n\n\n function map_U!(U::Gaugefields_2D_nowing_mpi{NC},f!::Function,V::Gaugefields_2D_nowing_mpi{NC},iseven::Bool) where {NC} \n\n A = zeros(ComplexF64,NC,NC)\n B = zeros(ComplexF64,NC,NC)\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n evenodd = ifelse( (ix+ it) % 2 ==0, true,false)\n if evenodd == iseven \n for k2=1:NC \n for k1=1:NC\n \n A[k1,k2] = getvalue(V,k1,k2,ix, it)\n B[k1,k2] = getvalue(U,k1,k2,ix, it)\n end\n end\n f!(B,A)\n for k2=1:NC \n for k1=1:NC\n v = B[k1,k2]\n setvalue!(U,v,k1,k2,ix, it)\n #U[k1,k2,ix, it] = B[k1,k2]\n end\n end\n end\n end\n #end\n #end\n end\n set_wing_U!(U)\n end\n\n function map_U_sequential!(U::Gaugefields_2D_nowing_mpi{NC},f!::Function,Uin) where {NC} \n error(\"The function map_U_sequential! can not be used with MPI\")\n end\n\n\n\n struct Shifted_Gaugefields_2D_mpi_nowing{NC} <: Shifted_Gaugefields{NC,2} \n parent::Gaugefields_2D_nowing_mpi{NC}\n #parent::T\n shift::NTuple{2,Int8}\n NX::Int64\n #NY::Int64\n #NZ::Int64\n NT::Int64\n NDW::Int64\n\n #function Shifted_Gaugefields(U::T,shift,Dim) where {T <: AbstractGaugefields}\n function Shifted_Gaugefields_2D_mpi_nowing(U::Gaugefields_2D_nowing_mpi{NC},shift) where NC\n #shifted_U!(U,shift)\n shifted_U_improved!(U,shift)\n \n return new{NC}(U,shift,U.NX,U.NT,U.NDW)\n end\n end\n\n function shifted_U_improved_zeroshift!(U::Gaugefields_2D_nowing_mpi{NC}) where NC\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n for jc=1:NC\n for ic=1:NC\n v = getvalue(U,ic,jc,ix, it)\n U.Ushifted[ic,jc,ix, it] =v\n end\n end\n \n end\n #end\n #end\n end \n end\n\n function update_sent_data!(send_ranks,N,ix, it,ix_shifted,it_shifted,\n PEs,myrank_xt,xP,tP,U::Gaugefields_2D_nowing_mpi{NC}) where NC\n tempmatrix_mini = view(U.tempmatrix,1:NC,1:NC,1) \n\n \n px = myrank_xt[1] + xP\n while px >= PEs[1]\n px += -PEs[1]\n end\n while px < 0\n px += PEs[1]\n end\n\n\n pt = myrank_xt[2] + tP\n while pt >= PEs[2]\n pt += -PEs[2]\n end\n while pt < 0\n pt += PEs[2]\n end\n\n myrank_xt_send = (px,pt)\n \n myrank_send = get_myrank_2d(myrank_xt_send,PEs)\n #println(\"send \",myrank_send)\n\n\n\n for jc=1:NC\n @simd for ic=1:NC\n #v = getvalue(U,ic,jc,ix_shifted_back,iy_shifted_back,iz_shifted_back,it_shifted_back)\n #v = getvalue(U,ic,jc,ix_shifted, it_shifted)\n v = getvalue(U,ic,jc,ix, it)\n tempmatrix_mini[ic,jc] = v\n end\n end\n #disp = ((((it-1)*U.PN[3] + iz-1)*U.PN[2] + iy-1)*U.PN[1] + ix-1)*NC*NC\n #disp = ((((it_shifted-1)*U.PN[3] + iz_shifted-1)*U.PN[2] + iy_shifted-1)*U.PN[1] + ix_shifted-1)*NC*NC\n #println(myrank_send)\n disp = (it_shifted-1)*U.PN[1] + ix_shifted\n\n\n if haskey(send_ranks,myrank_send)\n else\n send_ranks[myrank_send] = Data_sent(N,NC)\n end\n send_ranks[myrank_send].count += 1\n send_ranks[myrank_send].data[:,:,send_ranks[myrank_send].count] .= tempmatrix_mini\n send_ranks[myrank_send].positions[send_ranks[myrank_send].count] = disp\n\n end\n\n \n\n function shifted_U_improved_xshift!(U::Gaugefields_2D_nowing_mpi{NC},shift) where NC\n tP = 0\n\n PEs = U.PEs\n PN = U.PN\n myrank = U.myrank\n myrank_xt = U.myrank_xt\n myrank_xt_send = U.myrank_xt\n #tempmatrix = zeros(ComplexF64,NC,NC)#view(U.tempmatrix,1:NC,1:NC,1) #zeros(ComplexF64,NC,NC)\n #tempmatrix_mini = view(U.tempmatrix,1:NC,1:NC,1) \n\n lat_size = size(U.Ushifted)\n send_ranks = U.send_ranks\n empty!(send_ranks)\n # Dict{Int64,Data_sent}()\n N = prod(U.PN)\n\n for it=1:U.PN[2]\n it_shifted = it\n #for iz=1:U.PN[3]\n #iz_shifted = iz\n #for iy=1:U.PN[2]\n #iy_shifted = iy\n for ix=1:U.PN[1]\n ix_shifted = ix - shift[1]\n ix_global = myrank_xt[1]*U.PN[1] + ix\n ix_shifted_global = ix_global - shift[1]\n #if myrank_xt[1] == 0\n while ix_shifted_global < 1\n ix_shifted += U.NX\n ix_shifted_global += U.NX\n end\n #ix_shifted += ifelse(ix_shifted < 1,U.NX,0)\n #end\n #if myrank_xt[1] == PEs[1]-1\n while ix_shifted_global > U.NX\n ix_shifted += -U.NX\n ix_shifted_global += -U.NX\n end\n\n if ix_shifted <= 0\n xP = div(ix_shifted,U.PN[1])-1\n else\n xP = div(ix_shifted-1,U.PN[1])\n end\n\n \n while ix_shifted < 1\n ix_shifted += U.PN[1]\n end\n while ix_shifted > U.PN[1]\n ix_shifted += -U.PN[1]\n end\n \n\n if xP == 0\n for jc=1:NC\n @simd for ic=1:NC\n #v = getvalue(U,ic,jc,ix_shifted, it_shifted)\n #U.Ushifted[ic,jc,ix, it] = v\n v = getvalue(U,ic,jc,ix, it)\n U.Ushifted[ic,jc,ix_shifted,it_shifted] = v\n \n end\n end\n else\n update_sent_data!(send_ranks,N,ix, it,\n ix_shifted,it_shifted,PEs,myrank_xt,xP,tP,U)\n \n end\n end\n #end\n #end\n end \n\n mpi_updates_U!(U,send_ranks)\n\n end\n\n\n function shifted_U_improved_tshift!(U::Gaugefields_2D_nowing_mpi{NC},shift) where NC\n xP = 0\n\n PEs = U.PEs\n PN = U.PN\n myrank = U.myrank\n myrank_xt = U.myrank_xt\n myrank_xt_send = U.myrank_xt\n #tempmatrix = zeros(ComplexF64,NC,NC)#view(U.tempmatrix,1:NC,1:NC,1) #zeros(ComplexF64,NC,NC)\n #tempmatrix_mini = view(U.tempmatrix,1:NC,1:NC,1) \n\n lat_size = size(U.Ushifted)\n send_ranks = U.send_ranks\n empty!(send_ranks)\n # Dict{Int64,Data_sent}()\n N = prod(U.PN)\n\n for it=1:U.PN[2]\n it_shifted = it - shift[2]\n it_global = myrank_xt[2]*U.PN[2] + it\n it_shifted_global = it_global - shift[2]\n #if myrank_xt[2] == 0\n while it_shifted_global < 1\n it_shifted += U.NT\n it_shifted_global += U.NT\n end\n #it_shifted += ifelse(it_shifted < 1,U.NT,0)\n #end \n #if myrank_xt[2] == PEs[2]-1\n while it_shifted_global > U.NT\n it_shifted += -U.NT\n it_shifted_global += -U.NT\n end\n\n if it_shifted <= 0\n tP = div(it_shifted,U.PN[2]) -1\n else\n tP = div(it_shifted-1,U.PN[2])\n end\n #if tP < 0 \n # println(\"it_shifted $it_shifted tP = $tP\")\n #end\n\n\n #it_shifted += ifelse(it_shifted < 1,U.PN[2],0)\n while it_shifted < 1\n it_shifted += U.PN[2]\n end\n while it_shifted > U.PN[2]\n it_shifted += -U.PN[2]\n end\n\n #for iz=1:U.PN[3]\n #iz_shifted = iz \n \n #for iy=1:U.PN[2]\n #iy_shifted = iy\n\n for ix=1:U.PN[1]\n ix_shifted = ix \n \n if tP == 0\n @inbounds for jc=1:NC\n @simd for ic=1:NC\n #v = getvalue(U,ic,jc,ix_shifted, it_shifted)\n #U.Ushifted[ic,jc,ix, it] = v\n v = getvalue(U,ic,jc,ix, it)\n U.Ushifted[ic,jc,ix_shifted,it_shifted] = v\n \n end\n end\n else\n update_sent_data!(send_ranks,N,ix, it,\n ix_shifted, it_shifted,PEs,myrank_xt,xP,tP,U)\n \n end\n end\n #end\n #end\n end \n \n mpi_updates_U!(U,send_ranks)\n \n\n end\n\n\n function mpi_updates_U_1data!(U::Gaugefields_2D_nowing_mpi{NC},send_ranks) where NC\n if length(send_ranks) != 0\n #=\n for rank=0:get_nprocs(U)\n if rank == get_myrank(U)\n println(\"myrank = \",myrank)\n for (key,value) in send_ranks\n println(key,\"\\t\",value.count)\n end\n end\n barrier(U)\n end\n =#\n tempmatrix = U.tempmatrix #zeros(ComplexF64,NC,NC,N)\n #tempmatrix = zeros(ComplexF64,NC,NC,N)\n positions = U.positions\n\n win = U.win\n #@time win = MPI.Win_create(tempmatrix,comm)\n #println(typeof(win))\n #Isend Irecv\n MPI.Win_fence(0, win)\n\n for (myrank_send,value) in send_ranks\n count = value.count\n MPI.Put(value.data[:,:,1:count], myrank_send,win)\n end\n\n MPI.Win_fence(0, win)\n #MPI.free(win)\n\n win_i = U.win_i#MPI.Win_create(positions,comm)\n MPI.Win_fence(0, win_i)\n\n for (myrank_send,value) in send_ranks\n count = value.count\n MPI.Put(value.positions[1:count], myrank_send,win_i)\n end\n\n MPI.Win_fence(0, win_i)\n #MPI.free(win_i)\n\n countvec = U.countvec#zeros(Int64,1)\n win_c = U.win_1i\n #win_c = MPI.Win_create(countvec,comm)\n MPI.Win_fence(0, win_c)\n\n for (myrank_send,value) in send_ranks\n count = value.count\n MPI.Put(Int64[count], myrank_send,win_c)\n end\n\n MPI.Win_fence(0, win_c)\n #MPI.free(win_c)\n\n count = countvec[1]\n\n \n\n #=\n for rank=0:get_nprocs(U)\n if rank == get_myrank(U)\n println(\"myrank = \",myrank)\n for position in positions[1:count]\n println(position)\n end\n end\n barrier(U)\n end\n =#\n\n for i = 1:count\n position = positions[i]\n for jc = 1:NC\n for ic= 1:NC\n ii = ((position-1)*NC + jc-1)*NC + ic\n U.Ushifted[ii] = tempmatrix[ic,jc,i]\n end\n end\n #println(position)\n end\n\n #error(\"in shiftdU\")\n end\n end\n\n\n const printdata =false\n\n function get_myrank_2d(myrank_xyzt,PEs)\n @inbounds return myrank_xyzt[2]*PEs[1] + myrank_xyzt[1]\n end\n\n function mpi_updates_U_moredata!(U::Gaugefields_2D_nowing_mpi{NC},send_ranks) where NC\n\n otherranks = U.otherranks\n win_other = U.win_other\n\n MPI.Win_fence(0, win_other)\n myrank = get_myrank(U)\n nprocs = get_nprocs(U)\n for (myrank_send,value) in send_ranks\n count = value.count\n MPI.Put(Int64[count], myrank_send,myrank,win_other)\n end\n MPI.Win_fence(0, win_other)\n\n\n tempmatrix = U.tempmatrix #zeros(ComplexF64,NC,NC,N)\n #tempmatrix = zeros(ComplexF64,NC,NC,N)\n positions = U.positions\n\n win = U.win\n #@time win = MPI.Win_create(tempmatrix,comm)\n #println(typeof(win))\n #Isend Irecv\n \n win_i = U.win_i#MPI.Win_create(positions,comm)\n \n win_c = U.win_1i\n #win_c = MPI.Win_create(countvec,comm)\n \n\n countvec = U.countvec#zeros(Int64,1)\n\n your_ranks = U.your_ranks #zeros(Int64,nprocs,nprocs)\n your_ranks .= -1\n\n MPI.Win_fence(0, win_other)\n icount = 0\n for (myrank_send,value) in send_ranks\n icount += 1\n MPI.Get(view(your_ranks,1:nprocs,icount), myrank_send,win_other)\n end\n MPI.Win_fence(0, win_other)\n\n\n \n\n MPI.Win_fence(0, win)\n MPI.Win_fence(0, win_i)\n MPI.Win_fence(0, win_c)\n\n icount = 0\n for (myrank_send,value) in send_ranks\n count = value.count\n icount += 1\n disp = 0\n for irank=1:myrank\n if your_ranks[irank,icount] != -1\n disp += your_ranks[irank,icount]\n end\n end\n \n\n MPI.Put(value.positions[1:count], myrank_send,disp,win_i)\n MPI.Put(value.data[:,:,1:count], myrank_send,disp*NC*NC,win)\n end\n \n\n MPI.Win_fence(0, win)\n MPI.Win_fence(0, win_i)\n MPI.Win_fence(0, win_c)\n\n your_ranks .= -1\n\n totaldatanum = sum(otherranks)\n\n\n for i = 1:totaldatanum\n position = positions[i]\n for jc = 1:NC\n for ic= 1:NC\n ii = ((position-1)*NC + jc-1)*NC + ic\n U.Ushifted[ii] = tempmatrix[ic,jc,i]\n end\n end\n #println(position)\n end\n\n otherranks .= 0\n\n end\n\n function mpi_updates_U!(U::Gaugefields_2D_nowing_mpi{NC},send_ranks) where NC\n if length(send_ranks) != 0\n\n val = MPI.Allreduce(length(send_ranks), +,comm) ÷ get_nprocs(U)\n\n #=\n for rank=0:get_nprocs(U)\n if rank == get_myrank(U)\n println(\"length = \",val,\"\\t\")\n println(\"myrank = \",rank,\" length = $(length(send_ranks))\")\n end\n barrier(U)\n end\n =#\n\n mpi_updates_U_moredata!(U,send_ranks)\n return\n\n if val == 1\n mpi_updates_U_1data!(U,send_ranks)\n else\n mpi_updates_U_moredata!(U,send_ranks)\n end\n return\n\n\n #error(\"in shiftdU\")\n end\n end\n\n\n \n\n function shifted_U_improved!(U::Gaugefields_2D_nowing_mpi{NC},shift) where NC\n if shift == (0,0)\n shifted_U_improved_zeroshift!(U)\n return\n\n \n elseif shift[1] != 0 && shift[2] == 0 \n shifted_U_improved_xshift!(U,shift)\n return\n elseif shift[1] == 0 && shift[2] != 0 \n shifted_U_improved_tshift!(U,shift)\n return \n end\n \n \n\n PEs = U.PEs\n PN = U.PN\n myrank = U.myrank\n myrank_xt = U.myrank_xt\n myrank_xt_send = U.myrank_xt\n #tempmatrix = zeros(ComplexF64,NC,NC)#view(U.tempmatrix,1:NC,1:NC,1) #zeros(ComplexF64,NC,NC)\n tempmatrix_mini = view(U.tempmatrix,1:NC,1:NC,1) \n\n lat_size = size(U.Ushifted)\n send_ranks = U.send_ranks\n empty!(send_ranks)\n # Dict{Int64,Data_sent}()\n N = prod(U.PN)\n\n\n #win = MPI.Win_create(U.Ushifted,comm)\n #Isend Irecv\n\n #MPI.Win_fence(0, win)\n\n\n for it=1:U.PN[2]\n it_shifted = it - shift[2]\n it_global = myrank_xt[2]*U.PN[2] + it\n it_shifted_global = it_global - shift[2]\n #if myrank_xt[2] == 0\n while it_shifted_global < 1\n it_shifted += U.NT\n it_shifted_global += U.NT\n end\n #it_shifted += ifelse(it_shifted < 1,U.NT,0)\n #end \n #if myrank_xt[2] == PEs[2]-1\n while it_shifted_global > U.NT\n it_shifted += -U.NT\n it_shifted_global += -U.NT\n end\n #it_shifted += ifelse(it_shifted > U.PN[2],-U.NT,0)\n #end\n if it_shifted <= 0\n tP = div(it_shifted,U.PN[2]) -1\n else\n tP = div(it_shifted-1,U.PN[2])\n end\n #if tP < 0 \n # println(\"it_shifted $it_shifted tP = $tP myrank_xt $myrank_xt it = $it shift = $shift it_shifted_global $it_shifted_global\")\n #end\n\n\n #it_shifted += ifelse(it_shifted < 1,U.PN[2],0)\n while it_shifted < 1\n it_shifted += U.PN[2]\n end\n while it_shifted > U.PN[2]\n it_shifted += -U.PN[2]\n end\n #it_shifted += ifelse(it_shifted > U.PN[2],-U.PN[2],0)\n\n \n #for iz=1:U.PN[3]\n\n\n\n #iy_shifted += ifelse(iy_shifted < 1,U.PN[2],0)\n #iy_shifted += ifelse(iy_shifted > U.PN[2],-U.PN[2],0)\n \n for ix=1:U.PN[1]\n ix_shifted = ix - shift[1]\n ix_global = myrank_xt[1]*U.PN[1] + ix\n ix_shifted_global = ix_global - shift[1]\n #if myrank_xt[1] == 0\n while ix_shifted_global < 1\n ix_shifted += U.NX\n ix_shifted_global += U.NX\n end\n #ix_shifted += ifelse(ix_shifted < 1,U.NX,0)\n #end\n #if myrank_xt[1] == PEs[1]-1\n while ix_shifted_global > U.NX\n ix_shifted += -U.NX\n ix_shifted_global += -U.NX\n end\n #ix_shifted += ifelse(ix_shifted > U.PN[1],-U.NX,0)\n #end\n\n\n if ix_shifted <= 0\n xP = div(ix_shifted,U.PN[1])-1\n else\n xP = div(ix_shifted-1,U.PN[1])\n end\n\n \n while ix_shifted < 1\n ix_shifted += U.PN[1]\n end\n while ix_shifted > U.PN[1]\n ix_shifted += -U.PN[1]\n end\n #ix_shifted += ifelse(ix_shifted < 1,U.PN[1],0)\n #ix_shifted += ifelse(ix_shifted > U.PN[1],-U.PN[1],0)\n #xP = div(ix_shifted-1,U.PN[1])\n #println((tP,zP,yP,xP),\"\\t $shift\")\n if tP == 0 && xP == 0\n for jc=1:NC\n @simd for ic=1:NC\n #v = getvalue(U,ic,jc,ix_shifted, it_shifted)\n #U.Ushifted[ic,jc,ix, it] = v\n v = getvalue(U,ic,jc,ix, it)\n U.Ushifted[ic,jc,ix_shifted, it_shifted] = v\n \n end\n end\n else\n update_sent_data!(send_ranks,N,ix, it,\n ix_shifted, it_shifted,PEs,myrank_xt,xP,tP,U)\n end\n end\n #end\n #end\n end\n\n\n\n #println(\"length = \",length(send_ranks))\n \n\n #barrier(U)\n if length(send_ranks) != 0\n mpi_updates_U!(U,send_ranks)\n #=\n if length(send_ranks) == 1\n mpi_updates_U_1data!(U,send_ranks)\n else\n mpi_updates_U_moredata!(U,send_ranks)\n end\n =#\n end\n \n \n \n \n\n\n end\n\n \n\n function shifted_U!(U::Gaugefields_2D_nowing_mpi{NC},shift) where NC\n PEs = U.PEs\n PN = U.PN\n myrank = U.myrank\n myrank_xt = U.myrank_xt\n myrank_xt_send = U.myrank_xt\n tempmatrix = zeros(ComplexF64,NC,NC)\n\n win = MPI.Win_create(U.Ushifted,comm)\n #Isend Irecv\n\n MPI.Win_fence(0, win)\n\n\n for it=1:U.PN[2]\n it_shifted = it - shift[2]\n if myrank_xt[2] == 0\n while it_shifted < 1\n it_shifted += U.NT\n end\n #it_shifted += ifelse(it_shifted < 1,U.NT,0)\n end\n if myrank_xt[2] == PEs[2]-1\n while it_shifted > U.PN[2]\n it_shifted += -U.NT\n end\n #it_shifted += ifelse(it_shifted > U.PN[2],-U.NT,0)\n end\n if it_shifted <= 0\n tP = div(it_shifted,U.PN[2]) -1\n else\n tP = div(it_shifted-1,U.PN[2])\n end\n\n\n #it_shifted += ifelse(it_shifted < 1,U.PN[2],0)\n while it_shifted < 1\n it_shifted += U.PN[2]\n end\n while it_shifted > U.PN[2]\n it_shifted += -U.PN[2]\n end\n #it_shifted += ifelse(it_shifted > U.PN[2],-U.PN[2],0)\n\n \n #for iz=1:U.PN[3]\n iz_shifted = iz - shift[3]\n if myrank_xt[3] == 0\n while iz_shifted < 1\n iz_shifted += U.NZ\n end\n #iz_shifted += ifelse(iz_shifted < 1,U.NZ,0)\n end\n if myrank_xt[3] == PEs[3]-1\n while iz_shifted > U.PN[3]\n iz_shifted += -U.NZ\n end\n\n #iz_shifted += ifelse(iz_shifted > U.PN[3],-U.NZ,0)\n end\n\n if iz_shifted <= 0\n zP = div(iz_shifted,U.PN[3])-1\n else\n zP = div(iz_shifted-1,U.PN[3])\n end\n\n \n\n while iz_shifted < 1\n iz_shifted += U.PN[3]\n end\n while iz_shifted > U.PN[3]\n iz_shifted += -U.PN[3]\n end\n #iz_shifted += ifelse(iz_shifted < 1,U.PN[3],0)\n #iz_shifted += ifelse(iz_shifted > U.PN[3],-U.PN[3],0)\n \n #for iy=1:U.PN[2]\n iy_shifted = iy - shift[2]\n if myrank_xt[2] == 0\n while iy_shifted < 1\n iy_shifted += U.NY\n end\n\n #iy_shifted += ifelse(iy_shifted < 1,U.NY,0)\n end\n if myrank_xt[2] == PEs[2]-1\n while iy_shifted > U.PN[2]\n iy_shifted += -U.NY\n end\n #iy_shifted += ifelse(iy_shifted > U.PN[2],-U.NY,0)\n end\n\n if iy_shifted <= 0\n yP = div(iy_shifted,U.PN[2])-1\n else\n yP = div(iy_shifted-1,U.PN[2])\n end\n\n \n while iy_shifted < 1\n iy_shifted += U.PN[2]\n end\n while iy_shifted > U.PN[2]\n iy_shifted += -U.PN[2]\n end\n #iy_shifted += ifelse(iy_shifted < 1,U.PN[2],0)\n #iy_shifted += ifelse(iy_shifted > U.PN[2],-U.PN[2],0)\n \n for ix=1:U.PN[1]\n ix_shifted = ix - shift[1]\n if myrank_xt[1] == 0\n while ix_shifted < 1\n ix_shifted += U.NX\n end\n #ix_shifted += ifelse(ix_shifted < 1,U.NX,0)\n end\n if myrank_xt[1] == PEs[1]-1\n while ix_shifted > U.PN[1]\n ix_shifted += -U.NX\n end\n #ix_shifted += ifelse(ix_shifted > U.PN[1],-U.NX,0)\n end\n\n\n if ix_shifted <= 0\n xP = div(ix_shifted,U.PN[1])-1\n else\n xP = div(ix_shifted-1,U.PN[1])\n end\n\n \n while ix_shifted < 1\n ix_shifted += U.PN[1]\n end\n while ix_shifted > U.PN[1]\n ix_shifted += -U.PN[1]\n end\n #ix_shifted += ifelse(ix_shifted < 1,U.PN[1],0)\n #ix_shifted += ifelse(ix_shifted > U.PN[1],-U.PN[1],0)\n #xP = div(ix_shifted-1,U.PN[1])\n #println((tP,zP,yP,xP),\"\\t $shift\")\n if tP == 0 && zP == 0 && yP == 0 && xP == 0\n for jc=1:NC\n @simd for ic=1:NC\n #v = getvalue(U,ic,jc,ix_shifted, it_shifted)\n #U.Ushifted[ic,jc,ix, it] = v\n v = getvalue(U,ic,jc,ix, it)\n U.Ushifted[ic,jc,ix_shifted, it_shifted] = v\n \n end\n end\n else\n\n px = myrank_xt[1] + xP\n px += ifelse(px >= PEs[1],-PEs[1],0) \n px += ifelse(px < 0,+PEs[1],0) \n py = myrank_xt[2] + yP\n py += ifelse(py >= PEs[2],-PEs[2],0) \n py += ifelse(py < 0,+PEs[2],0) \n pz = myrank_xt[3] + zP\n pz += ifelse(pz >= PEs[3],-PEs[3],0) \n pz += ifelse(pz < 0,+PEs[3],0) \n pt = myrank_xt[2] + tP\n pt += ifelse(pt >= PEs[2],-PEs[2],0) \n pt += ifelse(pt < 0,+PEs[2],0) \n\n myrank_xt_send = (px,py,pz,pt)\n #println(myrank_xt_send)\n myrank_send = get_myrank_2d(myrank_xt_send,PEs)\n #println(myrank_send,\"\\t\",myrank)\n\n\n\n #it_shifted_back = (it_shifted-1) % U.PN[2] + 1\n #iz_shifted_back = (iz_shifted-1) % U.PN[3] +1\n #iy_shifted_back = (iy_shifted-1) % U.PN[2] + 1\n #ix_shifted_back = (ix_shifted-1) % U.PN[1] + 1\n\n for jc=1:NC\n @simd for ic=1:NC\n #v = getvalue(U,ic,jc,ix_shifted_back,iy_shifted_back,iz_shifted_back,it_shifted_back)\n #v = getvalue(U,ic,jc,ix_shifted, it_shifted)\n v = getvalue(U,ic,jc,ix, it)\n tempmatrix[ic,jc] = v\n end\n end\n #disp = ((((it-1)*U.PN[3] + iz-1)*U.PN[2] + iy-1)*U.PN[1] + ix-1)*NC*NC\n disp = ((((it_shifted-1)*U.PN[3] + iz_shifted-1)*U.PN[2] + iy_shifted-1)*U.PN[1] + ix_shifted-1)*NC*NC\n #println(myrank_send)\n MPI.Put(tempmatrix, myrank_send,disp,win)\n #println(\"t \",tempmatrix)\n #if myrank == myrank_send\n # println(U.Ushifted[:,:,ix, it] )\n #end\n\n #=\n for rank=0:(get_nprocs(U)-1)\n #println(get_nprocs(U))\n if get_myrank(U) == rank\n println(\"site $((ix, it))\")\n println(\"shift $shift\")\n println(\"shifted site $((ix_shifted_back,iy_shifted_back,iz_shifted_back,it_shifted_back))\")\n println(\"xPs,$((xP,yP,zP,tP))\")\n println(\"myrank = $myrank send $myrank_send\")\n println(\"pxs \",(px,py,pz,pt))\n println((1,1,ix_shifted_back,iy_shifted_back,iz_shifted_back,it_shifted_back))\n end\n barrier(U)\n end\n =#\n\n end\n end\n #end\n #end\n end\n\n MPI.Win_fence(0, win)\n\n MPI.free(win)\n\n \n\n end\n\n\n\n @inline function getvalue(U::Shifted_Gaugefields_2D_mpi_nowing{NC},i1,i2,i3, i6) where NC\n @inbounds return U.parent.Ushifted[i1,i2,i3,i6 ]\n end\n\n @inline function setvalue!(U::Shifted_Gaugefields_2D_mpi_nowing{NC},v,i1,i2,i3,i6) where NC\n error(\"type $(typeof(U)) has no setindex method. This type is read only.\")\n end\n\n\n function shift_U(U::Gaugefields_2D_nowing_mpi{NC},ν::T) where {T <: Integer,NC}\n if ν == 1\n shift = (1,0)\n elseif ν == 2\n shift = (0,1)\n elseif ν == -1\n shift = (-1,0)\n elseif ν == -2\n shift = (0,-1)\n end\n\n return Shifted_Gaugefields_2D_mpi_nowing(U,shift)\n end\n\n function shift_U(U::TU,shift::NTuple{Dim,T}) where {Dim,T <: Integer,TU <: Gaugefields_2D_nowing_mpi}\n return Shifted_Gaugefields_2D_mpi_nowing(U,shift)\n end \n\n\n\n function normalize_U!(U::Gaugefields_2D_nowing_mpi{NC}) where NC\n\n A = zeros(ComplexF64,NC,NC)\n\n for it=1:U.PN[2]\n #for iz=1:U.PN[3]\n #for iy=1:U.PN[2]\n for ix=1:U.PN[1]\n for jc=1:NC\n @simd for ic=1:NC\n A[ic,jc] = getvalue(U,ic,jc,ix, it)\n end\n end\n gramschmidt!(A)\n\n for jc=1:NC\n @simd for ic=1:NC\n v = A[ic,jc]\n setvalue!(U,v,ic,jc,ix, it)\n end\n end\n end\n #end\n #end\n end\n set_wing_U!(U)\n\n end\n\n\n function Base.similar(U::T) where T <: Gaugefields_2D_nowing_mpi \n Uout = Gaugefields_2D_nowing_mpi(U.NC,U.NX,U.NT,U.PEs,mpiinit=U.mpiinit,verbose_level = U.verbose_print.level)\n #identityGaugefields_4D_nowing(U.NC,U.NX,U.NY,U.NZ,U.NT,U.NDW)\n return Uout\n end\n\n\n function Base.similar(U::Array{T,1}) where T <: Gaugefields_2D_nowing_mpi\n Uout = Array{T,1}(undef,2)\n for μ=1:2\n Uout[μ] = similar(U[μ]) \n end\n return Uout\n end\n\n function LinearAlgebra.tr(a::Gaugefields_2D_nowing_mpi{NC}) where NC\n NX=a.NX\n #NY=a.NY\n #NZ=a.NZ\n NT=a.NT\n PN =a.PN\n\n s = 0\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n @simd for k=1:NC\n s += getvalue(a,k,k,ix, it)\n #println(a[k,k,ix, it])\n end\n end\n #end\n #end\n end\n\n s = MPI.Allreduce(s,MPI.SUM,comm)\n\n #println(3*NT*NZ*NY*NX*NC)\n return s\n end\n\n function calculate_Polyakov_loop(U::Array{T,1},temp1::AbstractGaugefields{NC,Dim},temp2::AbstractGaugefields{NC,Dim}) where {NC,Dim,T <: Gaugefields_2D_nowing_mpi}\n Uold = temp1\n Unew = temp2\n shift = zeros(Int64,Dim)\n \n μ = Dim\n _,_,NN... = size(U[1]) #NC,NC,NX, NT 4D case\n lastaxis = NN[end]\n #println(lastaxis)\n\n substitute_U!(Uold,U[μ])\n for i=2:lastaxis\n shift[μ] = i-1\n U1 = shift_U(U[μ],Tuple(shift))\n mul_skiplastindex!(Unew,Uold,U1)\n #println(getvalue(U1,1,1,1,1,1,1))\n Uold,Unew = Unew,Uold\n #println(getvalue(Uold,1,1,1,1,1,1))\n end\n\n set_wing_U!(Uold)\n #println(prod(NN[1:Dim-1]))\n #println(Uold)\n poly = 0\n #if get_myrank(U) == 0\n poly = partial_tr(Uold,μ)/prod(NN[1:Dim-1])\n #end\n poly /= U[1].PEs[μ]\n #poly = MPI.bcast(poly,0,comm)\n \n return poly\n\n end\n\n\n function partial_tr(a::Gaugefields_2D_nowing_mpi{NC},μ) where NC\n #error(\"Polyakov loop is not supported with MPI yet.\")\n PN =a.PN\n\n if μ == 1\n s = 0\n ix = 1\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n #for ix=1:NX\n @simd for k=1:NC\n s += getvalue(a,k,k,ix, it)\n #println(a[k,k,ix, it])\n end\n \n #end\n #end\n #end\n end\n elseif μ == 2\n s = 0\n iy =1\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:NY\n for ix=1:PN[1]\n @simd for k=1:NC\n s += getvalue(a,k,k,ix, it)\n #println(a[k,k,ix, it])\n end\n end\n #end\n #end\n end\n elseif μ == 3\n s = 0\n iz = 1\n for it=1:PN[2]\n #for iz=1:NZ\n #for iy=1:PN[2]\n for ix=1:PN[1]\n @simd for k=1:NC\n s += getvalue(a,k,k,ix, it)\n #println(a[k,k,ix, it])\n end\n end\n #end\n #end\n end\n else \n s = 0\n it = 1\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n @simd for k=1:NC\n s += getvalue(a,k,k,ix, it)\n # println(s)\n end\n end\n #end\n #end\n \n end\n\n s = MPI.Allreduce(s,MPI.SUM,comm)\n \n\n\n #println(3*NT*NZ*NY*NX*NC)\n return s\n end\n\n \n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{NC},a::T1,b::T2) where {NC,T1 <: Abstractfields,T2 <: Abstractfields}\n @assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n for k2=1:NC \n for k1=1:NC\n v = 0\n setvalue!(c,v,k1,k2,ix, it)\n #c[k1,k2,ix, it] = 0\n\n @simd for k3=1:NC\n vc = getvalue(c,k1,k2,ix, it) + getvalue(a,k1,k3,ix, it)*getvalue(b,k3,k2,ix, it)\n setvalue!(c,vc,k1,k2,ix, it)\n #c[k1,k2,ix, it] += a[k1,k3,ix, it]*b[k3,k2,ix, it]\n end\n end\n end\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{NC},a::T1,b::T2,iseven::Bool) where {NC,T1 <: Abstractfields,T2 <: Abstractfields}\n @assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n evenodd = ifelse( (ix+ it) % 2 ==0, true,false)\n if evenodd == iseven\n\n for k2=1:NC \n for k1=1:NC\n v = 0\n setvalue!(c,v,k1,k2,ix, it)\n #c[k1,k2,ix, it] = 0\n\n @simd for k3=1:NC\n vc = getvalue(c,k1,k2,ix, it) + getvalue(a,k1,k3,ix, it)*getvalue(b,k3,k2,ix, it)\n setvalue!(c,vc,k1,k2,ix, it)\n #c[k1,k2,ix, it] += a[k1,k3,ix, it]*b[k3,k2,ix, it]\n end\n end\n end\n end\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function mul_skiplastindex!(c::Gaugefields_2D_nowing_mpi{NC},a::T1,b::T2) where {NC,T1 <: Abstractfields,T2 <: Abstractfields}\n #@assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n #for it=1:NT\n it = 1\n PN = c.PN\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n for k2=1:NC \n for k1=1:NC\n v = 0\n #setvalue!(c,v,k1,k2,ix, it)\n #c[k1,k2,ix, it] = 0\n\n @simd for k3=1:NC\n av = getvalue(a,k1,k3,ix, it)\n bv = getvalue(b,k3,k2,ix, it)\n #cv = getvalue(c,k1,k2,ix, it)\n\n v += av*bv\n \n #c[k1,k2,ix, it] += a[k1,k3,ix, it]*b[k3,k2,ix, it]\n end\n setvalue!(c,v,k1,k2,ix, it)\n end\n end\n #end\n #end\n end\n #end\n set_wing_U!(c)\n end\n \n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{3},a::T1,b::T2) where {NC,T1 <: Abstractfields,T2 <: Abstractfields}\n #@assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n \n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n @inbounds for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n a11 = getvalue(a,1,1,ix, it)\n a21 = getvalue(a,2,1,ix, it)\n a31 = getvalue(a,3,1,ix, it)\n a12 = getvalue(a,1,2,ix, it)\n a22 = getvalue(a,2,2,ix, it)\n a32 = getvalue(a,3,2,ix, it)\n a13 = getvalue(a,1,3,ix, it)\n a23 = getvalue(a,2,3,ix, it)\n a33 = getvalue(a,3,3,ix, it)\n b11 = getvalue(b,1,1,ix, it)\n b21 = getvalue(b,2,1,ix, it)\n b31 = getvalue(b,3,1,ix, it)\n b12 = getvalue(b,1,2,ix, it)\n b22 = getvalue(b,2,2,ix, it)\n b32 = getvalue(b,3,2,ix, it)\n b13 = getvalue(b,1,3,ix, it)\n b23 = getvalue(b,2,3,ix, it)\n b33 = getvalue(b,3,3,ix, it)\n\n\n v = (a11*b11+a12*b21+a13*b31)\n setvalue!(c,v,1,1,ix, it) \n v = (a21*b11+a22*b21+a23*b31)\n setvalue!(c,v,2,1,ix, it) \n v = (a31*b11+a32*b21+a33*b31)\n setvalue!(c,v,3,1,ix, it) \n v = (a11*b12+a12*b22+a13*b32)\n setvalue!(c,v,1,2,ix, it) \n v = (a21*b12+a22*b22+a23*b32)\n setvalue!(c,v,2,2,ix, it) \n v = (a31*b12+a32*b22+a33*b32)\n setvalue!(c,v,3,2,ix, it) \n v = (a11*b13+a12*b23+a13*b33)\n setvalue!(c,v,1,3,ix, it) \n v = (a21*b13+a22*b23+a23*b33)\n setvalue!(c,v,2,3,ix, it) \n v = (a31*b13+a32*b23+a33*b33)\n setvalue!(c,v,3,3,ix, it) \n end\n #end\n #end\n end\n \n #set_wing_U!(c)\n end\n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{3},a::T1,b::T2,iseven::Bool) where {NC,T1 <: Abstractfields,T2 <: Abstractfields}\n #@assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n evenodd = ifelse( (ix+ it) % 2 ==0, true,false)\n if evenodd == iseven\n\n a11 = getvalue(a,1,1,ix, it)\n a21 = getvalue(a,2,1,ix, it)\n a31 = getvalue(a,3,1,ix, it)\n a12 = getvalue(a,1,2,ix, it)\n a22 = getvalue(a,2,2,ix, it)\n a32 = getvalue(a,3,2,ix, it)\n a13 = getvalue(a,1,3,ix, it)\n a23 = getvalue(a,2,3,ix, it)\n a33 = getvalue(a,3,3,ix, it)\n b11 = getvalue(b,1,1,ix, it)\n b21 = getvalue(b,2,1,ix, it)\n b31 = getvalue(b,3,1,ix, it)\n b12 = getvalue(b,1,2,ix, it)\n b22 = getvalue(b,2,2,ix, it)\n b32 = getvalue(b,3,2,ix, it)\n b13 = getvalue(b,1,3,ix, it)\n b23 = getvalue(b,2,3,ix, it)\n b33 = getvalue(b,3,3,ix, it)\n\n\n v = (a11*b11+a12*b21+a13*b31)\n setvalue!(c,v,1,1,ix, it) \n v = (a21*b11+a22*b21+a23*b31)\n setvalue!(c,v,2,1,ix, it) \n v = (a31*b11+a32*b21+a33*b31)\n setvalue!(c,v,3,1,ix, it) \n v = (a11*b12+a12*b22+a13*b32)\n setvalue!(c,v,1,2,ix, it) \n v = (a21*b12+a22*b22+a23*b32)\n setvalue!(c,v,2,2,ix, it) \n v = (a31*b12+a32*b22+a33*b32)\n setvalue!(c,v,3,2,ix, it) \n v = (a11*b13+a12*b23+a13*b33)\n setvalue!(c,v,1,3,ix, it) \n v = (a21*b13+a22*b23+a23*b33)\n setvalue!(c,v,2,3,ix, it) \n v = (a31*b13+a32*b23+a33*b33)\n setvalue!(c,v,3,3,ix, it) \n end\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{2},a::T1,b::T2) where {NC,T1 <: Abstractfields,T2 <: Abstractfields}\n #@assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n a11 = getvalue(a,1,1,ix, it)\n a21 = getvalue(a,2,1,ix, it)\n \n a12 = getvalue(a,1,2,ix, it)\n a22 = getvalue(a,2,2,ix, it)\n\n\n b11 = getvalue(b,1,1,ix, it)\n b21 = getvalue(b,2,1,ix, it)\n\n b12 = getvalue(b,1,2,ix, it)\n b22 = getvalue(b,2,2,ix, it)\n\n\n\n v = a11*b11+a12*b21\n setvalue!(c,v,1,1,ix, it) \n v = a21*b11+a22*b21\n setvalue!(c,v,2,1,ix, it) \n\n v = a11*b12+a12*b22\n setvalue!(c,v,1,2,ix, it) \n v = a21*b12+a22*b22\n setvalue!(c,v,2,2,ix, it) \n #v = a31*b12+a32*b22\n\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{2},a::T1,b::T2,iseven::Bool) where {NC,T1 <: Abstractfields,T2 <: Abstractfields}\n #@assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n evenodd = ifelse( (ix+ it) % 2 ==0, true,false)\n if evenodd == iseven\n\n\n a11 = getvalue(a,1,1,ix, it)\n a21 = getvalue(a,2,1,ix, it)\n \n a12 = getvalue(a,1,2,ix, it)\n a22 = getvalue(a,2,2,ix, it)\n\n\n b11 = getvalue(b,1,1,ix, it)\n b21 = getvalue(b,2,1,ix, it)\n\n b12 = getvalue(b,1,2,ix, it)\n b22 = getvalue(b,2,2,ix, it)\n\n\n\n v = a11*b11+a12*b21\n setvalue!(c,v,1,1,ix, it) \n v = a21*b11+a22*b21\n setvalue!(c,v,2,1,ix, it) \n\n v = a11*b12+a12*b22\n setvalue!(c,v,1,2,ix, it) \n v = a21*b12+a22*b22\n setvalue!(c,v,2,2,ix, it) \n v = a31*b12+a32*b22\n end\n\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{NC},a::T1,b::T2,α::Ta,β::Tb) where {NC,T1 <: Abstractfields,T2 <: Abstractfields,Ta <: Number, Tb <: Number}\n @assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n for ix=1:PN[1]\n for k2=1:NC \n for k1=1:NC\n v = β*getvalue(c,k1,k2,ix, it)\n setvalue!(c,v,k1,k2,ix, it)\n #c[k1,k2,ix, it] = β*c[k1,k2,ix, it] \n @simd for k3=1:NC\n vc = getvalue(c,k1,k2,ix, it) + α*getvalue(a,k1,k3,ix, it)*getvalue(b,k3,k2,ix, it)\n setvalue!(c,vc,k1,k2,ix, it)\n #c[k1,k2,ix, it] += α*a[k1,k3,ix, it]*b[k3,k2,ix, it] \n end\n end\n end\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{2},a::T1,b::T2,α::Ta,β::Tb) where {NC,T1 <: Abstractfields,T2 <: Abstractfields,Ta <: Number, Tb <: Number}\n #@assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n if β == zero(β)\n if α == one(α)\n mul!(c,a,b)\n return\n end\n end\n\n\n @inbounds for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n @simd for ix=1:PN[1]\n a11 = getvalue(a,1,1,ix, it)\n a21 = getvalue(a,2,1,ix, it)\n a12 = getvalue(a,1,2,ix, it)\n a22 = getvalue(a,2,2,ix, it)\n\n b11 = getvalue(b,1,1,ix, it)\n b21 = getvalue(b,2,1,ix, it)\n b12 = getvalue(b,1,2,ix, it)\n b22 = getvalue(b,2,2,ix, it)\n\n\n v = (a11*b11+a12*b21)*α + β*getvalue(c,1,1,ix, it)\n setvalue!(c,v,1,1,ix, it) \n v = (a21*b11+a22*b21)*α + β*getvalue(c,2,1,ix, it)\n setvalue!(c,v,2,1,ix, it) \n v = (a11*b12+a12*b22)*α + β*getvalue(c,1,2,ix, it)\n setvalue!(c,v,1,2,ix, it) \n v = (a21*b12+a22*b22)*α + β*getvalue(c,2,2,ix, it)\n setvalue!(c,v,2,2,ix, it) \n\n\n end\n #end\n #end\n end\n #set_wing_U!(c)\n end\n\n function LinearAlgebra.mul!(c::Gaugefields_2D_nowing_mpi{3},a::T1,b::T2,α::Ta,β::Tb) where {NC,T1 <: Abstractfields,T2 <: Abstractfields,Ta <: Number, Tb <: Number}\n #@assert NC != 2 && NC != 3 \"This function is for NC != 2,3\"\n NT = c.NT\n #NZ = c.NZ\n #NY = c.NY\n NX = c.NX\n PN = c.PN\n if β == zero(β)\n if α == one(α)\n mul!(c,a,b)\n return\n end\n end\n\n\n @inbounds for it=1:PN[2]\n #for iz=1:PN[3]\n #for iy=1:PN[2]\n @simd for ix=1:PN[1]\n a11 = getvalue(a,1,1,ix, it)\n a21 = getvalue(a,2,1,ix, it)\n a31 = getvalue(a,3,1,ix, it)\n a12 = getvalue(a,1,2,ix, it)\n a22 = getvalue(a,2,2,ix, it)\n a32 = getvalue(a,3,2,ix, it)\n a13 = getvalue(a,1,3,ix, it)\n a23 = getvalue(a,2,3,ix, it)\n a33 = getvalue(a,3,3,ix, it)\n b11 = getvalue(b,1,1,ix, it)\n b21 = getvalue(b,2,1,ix, it)\n b31 = getvalue(b,3,1,ix, it)\n b12 = getvalue(b,1,2,ix, it)\n b22 = getvalue(b,2,2,ix, it)\n b32 = getvalue(b,3,2,ix, it)\n b13 = getvalue(b,1,3,ix, it)\n b23 = getvalue(b,2,3,ix, it)\n b33 = getvalue(b,3,3,ix, it)\n\n v = (a11*b11+a12*b21+a13*b31)*α + β*getvalue(c,1,1,ix, it)\n setvalue!(c,v,1,1,ix, it) \n v = (a21*b11+a22*b21+a23*b31)*α + β*getvalue(c,2,1,ix, it)\n setvalue!(c,v,2,1,ix, it) \n v = (a31*b11+a32*b21+a33*b31)*α + β*getvalue(c,3,1,ix, it)\n setvalue!(c,v,3,1,ix, it) \n v = (a11*b12+a12*b22+a13*b32)*α + β*getvalue(c,1,2,ix, it)\n setvalue!(c,v,1,2,ix, it) \n v = (a21*b12+a22*b22+a23*b32)*α + β*getvalue(c,2,2,ix, it)\n setvalue!(c,v,2,2,ix, it) \n v = (a31*b12+a32*b22+a33*b32)*α + β*getvalue(c,3,2,ix, it)\n setvalue!(c,v,3,2,ix, it) \n v = (a11*b13+a12*b23+a13*b33)*α + β*getvalue(c,1,3,ix, it)\n setvalue!(c,v,1,3,ix, it) \n v = (a21*b13+a22*b23+a23*b33)*α + β*getvalue(c,2,3,ix, it)\n setvalue!(c,v,2,3,ix, it) \n v = (a31*b13+a32*b23+a33*b33)*α + β*getvalue(c,3,3,ix, it)\n setvalue!(c,v,3,3,ix, it) \n\n\n end\n #end\n #end\n end\n end\n\n function set_wing_U!(u::Array{Gaugefields_2D_nowing_mpi{NC},1}) where NC\n return \n for μ=1:2\n set_wing_U!(u[μ]) \n end\n end\n\n function set_wing_U!(u::Gaugefields_2D_nowing_mpi{NC}) where NC\n return \n end\n\n\n \n\n#end", "meta": {"hexsha": "fba8557f7c86f6726b0f3ea8fd6f61ca5df28b79", "size": 69062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/2D/gaugefields_2D_mpi_nowing.jl", "max_stars_repo_name": "akio-tomiya/Gaugefields.jl", "max_stars_repo_head_hexsha": "dd2180dfe54eba7826ddd45a13ab2f5a007857d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-24T14:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T14:21:45.000Z", "max_issues_repo_path": "src/2D/gaugefields_2D_mpi_nowing.jl", "max_issues_repo_name": "akio-tomiya/Gaugefields.jl", "max_issues_repo_head_hexsha": "dd2180dfe54eba7826ddd45a13ab2f5a007857d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2022-01-18T01:51:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T01:14:03.000Z", "max_forks_repo_path": "src/2D/gaugefields_2D_mpi_nowing.jl", "max_forks_repo_name": "akio-tomiya/Gaugefields.jl", "max_forks_repo_head_hexsha": "dd2180dfe54eba7826ddd45a13ab2f5a007857d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3934262948, "max_line_length": 169, "alphanum_fraction": 0.3954852162, "num_tokens": 19322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19507638209139164}} {"text": "\n\nfunction trace_back(geometry::Geometry{T,S,A,E}, shaders::Vector{Function}, ray::Ray{T}, nBands::S, maxNumberOfCycles::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon for rendering\n count_while_loop = 0\n continue_iterating::Bool = true\n radiance::Vector{T} = ones(nBands) .* GREAT_NUM\n mtl::Int = 0\n hit::Bool = false\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfCycles\n continue_iterating = false\n continue\n end\n hit_, In, eidx, nrml, rmin = intersect(geometry, ray)\n if hit_ === true\n\t hit = true\n\t mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n\t if scatter === false\n\t\tcontinue_iterating = false\n\t end\n else\n\t radiance .*= 0.0\n continue_iterating = false\n end\n end\n return hit, radiance\nend\n\nfunction trace_back(geometry::Geometry{T,S,A,E}, geometry_bvh::Bvh{T,S,A,E}, shaders::Vector{Function}, ray::Ray{T}, nBands::S, maxNumberOfCycles::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon for rendering\n count_while_loop = 0\n continue_iterating::Bool = true\n radiance::Vector{T} = ones(nBands) .* GREAT_NUM\n mtl::Int = 0\n hit::Bool = false\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfCycles\n continue_iterating = false\n continue\n end\n hit_, In, eidx, nrml, rmin = intersect(geometry, geometry_bvh, ray)\n if hit_ === true\n\t hit = true\n\t mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n\t if scatter === false\n\t\tcontinue_iterating = false\n\t end\n else\n\t radiance .*= 0.0\n continue_iterating = false\n end\n end\n return hit, radiance\nend\n\nfunction trace_back(geometry::Geometry{T,S,A,E}, shaders::Vector{Function}, skymap::B, ray::Ray{T}, nBands::S, maxNumberOfCycles::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, B<:AbstractArray{T,2}, E<:AbstractArray{S,1}}\n # traces ray/photon for rendering\n count_while_loop = 0\n continue_iterating::Bool = true\n radiance::Vector{T} = ones(nBands) .* GREAT_NUM\n mtl::Int = 0\n hit::Bool = false\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfCycles\n continue_iterating = false\n continue\n end\n hit_, In, eidx, nrml, rmin = intersect(mesh, ray)\n if hit_mesh === true\n\t hit = true\n\t mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n\t if scatter === false\n\t\tcontinue_iterating = false\n\t end\n else\n\t radiance .*= sample_skymap(skymap, ray.dx, ray.dy, ray.dz)\n continue_iterating = false\n end\n end\n return hit, radiance\nend\n\nfunction trace_back(geometry::Geometry{T,S,A,E}, geometry_bvh::Bvh{T,S,A,E}, shaders::Vector{Function}, skymap::B, ray::Ray{T}, nBands::S, maxNumberOfCycles::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, B<:AbstractArray{T,2}, E<:AbstractArray{S,1}}\n # traces ray/photon for rendering\n count_while_loop = 0\n continue_iterating::Bool = true\n radiance::Vector{T} = ones(nBands) .* GREAT_NUM\n mtl::Int = 0\n hit::Bool = false\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfCycles\n continue_iterating = false\n continue\n end\n hit_, In, eidx, nrml, rmin = intersect(geometry, geometry_bvh, ray)\n if hit_ === true\n\t hit = true\n\t mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n\t if scatter === false\n\t\tcontinue_iterating = false\n\t end\n else\n\t radiance .*= sample_skymap(skymap, ray.dx, ray.dy, ray.dz)\n continue_iterating = false\n end\n end\n return hit, radiance\nend\n\nfunction trace_back(assets::AbstractArray{Asset{T,S},1}, geometries::AbstractArray{Geometry{T,S,A,E},1}, palettes::AbstractArray{Vector{Function},1}, geometry_bvhs::AbstractArray{Bvh{T,S,A,E},1}, scene_bvh::Bvh{T,S,A,E}, ray::Ray{T}, skymap::B, nBands::S, maxNumberOfCycles::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, B<:AbstractArray{T,2}, E<:AbstractArray{S,1}}\n # traces ray/photon for rendering\n count_while_loop::S = 0\n continue_iterating::Bool = true\n radiance::Vector{T} = ones(nBands)\n hit::Bool = false\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfCycles\n continue_iterating = false\n continue\n end\n hit_scene, I_scene, tray, nrml, range_scene, aidx, oidx, eidx = intersect_scene(assets, geometries, geometry_bvhs, scene_bvh, ray)\n if hit_scene === true\n\t hit = true\n mtl = geometries[oidx].mtl[eidx]\n pidx = assets[aidx].pidx\n shader = palettes[pidx][mtl]\n scatter, ray, r = shader(I_scene.x, I_scene.y, I_scene.z, -tray.dx, -tray.dy, -tray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n\t if scatter === false\n\t\tcontinue_iterating = false\n\t end\n else\n\t radiance = radiance .* sample_skymap(skymap, ray.dx, ray.dy, ray.dz)\n continue_iterating = false\n end\n end\n return radiance\nend\n\n\n\n# following traces in forward direction with cyclic Walls. \n# These functions record the \"faterecs\" and don't use skymaps.\n# These function can be used to compute e.g. fAPAR or surface BDRF/BRF/BHR etc.\n# but some are relatively slow because of the instantiation of small arrays...\n\nfunction record(geometry::Geometry{T,S,A,E}, shaders::Vector{Function}, walls::Walls{T}, ray::Ray{T}, maxNumberOfBounces::Int) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon until it is absorbed or bounces through the reference plane\n #\n # TERMINAL CODES:\n #\n # -1 the maximum number of cycles was reached\n # 1 photon escapes through the reference plane\n # 2 photon escapes through the bottom plane\n # 3 photon cyclicly re-enters the scene (through walls)'\n # 4 photon is absorbed\n # 5 photon is scattered\n #\n path::AbstractArray{T, 2} = zeros(Float64, maxNumberOfBounces+1, 3)\n path[1,:] = [ray.x, ray.y, ray.z]\n codes::AbstractArray{Int, 1} = zeros(Int, maxNumberOfBounces+1) # code[1] === 0\n index::Int = 1\n count_while_loop::Int = 0\n continue_iterating::Bool = true\n mtl::Int = -1\n while continue_iterating\n count_while_loop += 1\n index += 1\n if count_while_loop >= maxNumberOfBounces\n path[index, :] = [ray.x, ray.y, ray.z]\n codes[index] = -1\n continue_iterating = false\n continue\n end\n I_wall, side, r_wall = intersect_walls(walls, ray)\n hit_, In, eidx, nrml, rmin = intersect(geometry, ray)\n wall = r_wall <= rmin\n if wall === true\n if side === 't'\n # photon escapes through reference plane\n continue_iterating = false\n codes[index] = 1\n path[index, :] = [I_wall.x, I_wall.y, I_wall.z]\n elseif (side === 'b')\n # photon is absorbed by a black surface underneath the scene\n continue_iterating = false\n codes[index] = 2\n path[index, :] = [I_wall.x, I_wall.y, I_wall.z]\n else # thus the condition: ' !(side ==='t') && !(side === 'b') ' is true\n # photon cyclicly re-enters from the opposite wall\n ray = cycle_ray(walls, ray)\n count_while_loop -= 1 # don't count these events toward the number of cycles\n index -= 1\n end\n else # implies hit_ is true, because the ray either hits the scene or a wall\n hit = true\n mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n if scatter === false\n continue_iterating = false\n codes[index] = 4\n path[index, :] = [I_scene.x, I_scene.y, I_scene.z]\n else\n codes[index] = 5\n path[index, :] = [I_scene.x, I_scene.y, I_scene.z]\n end\n\tend\n end\n return path, codes\nend\n\nfunction record(geometry::Geometry{T,S,A,E}, geometry_bvh::Bvh{T,S,A,E}, shaders::Vector{Function}, walls::Walls{T}, ray::Ray{T}, maxNumberOfBounces::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon until it is absorbed or bounces through the reference plane\n #\n # TERMINAL CODES:\n #\n # -1 the maximum number of cycles was reached\n # 1 photon escapes through the reference plane\n # 2 photon escapes through the bottom plane\n # 3 photon cyclicly re-enters the scene (through walls)'\n # 4 photon is absorbed\n # 5 photon is scattered\n #\n path::AbstractArray{T, 2} = zeros(Float64, maxNumberOfBounces+1, 3)\n path[1,:] = [ray.x, ray.y, ray.z]\n codes::AbstractArray{Int, 1} = zeros(Int, maxNumberOfBounces+1) # code[1] === 0\n index::Int = 1\n count_while_loop::Int = 0\n continue_iterating::Bool = true\n mtl::Int = -1\n while continue_iterating\n count_while_loop += 1\n index += 1\n if count_while_loop >= maxNumberOfBounces\n path[index, :] = [ray.x, ray.y, ray.z]\n codes[index] = -1\n continue_iterating = false\n continue\n end\n I_wall, side, r_wall = intersect_walls(walls, ray)\n hit_, In, eidx, nrml, rmin = intersect(geometry, geometry_bvh, ray)\n wall = r_wall <= rmin\n if wall === true\n if side === 't'\n # photon escapes through reference plane\n continue_iterating = false\n codes[index] = 1\n path[index, :] = [I_wall.x, I_wall.y, I_wall.z]\n elseif (side === 'b')\n # photon is absorbed by a black surface underneath the scene\n continue_iterating = false\n codes[index] = 2\n path[index, :] = [I_wall.x, I_wall.y, I_wall.z]\n else # thus the condition: ' !(side ==='t') && !(side === 'b') ' is true\n # photon cyclicly re-enters from the opposite wall\n ray = cycle_ray(walls, ray)\n count_while_loop -= 1 # don't count these events toward the number of cycles\n index -= 1\n end\n else # implies hit_ is true, because the ray either hits the scene or a wall\n hit = true\n mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n if scatter === false\n continue_iterating = false\n codes[index] = 4\n path[index, :] = [I_scene.x, I_scene.y, I_scene.z]\n else\n codes[index] = 5\n path[index, :] = [I_scene.x, I_scene.y, I_scene.z]\n end\n\tend\n end\n return path, codes\nend\n\nfunction record(assets::AbstractArray{Asset{T,S},1}, geometries::AbstractArray{Geometry{T,S,A,E},1}, palettes::AbstractArray{Vector{Function},1}, geometry_bvhs::AbstractArray{Bvh{T,S,A,E},1}, scene_bvh::Bvh{T,S,A,E}, walls::Walls{T}, ray::Ray{T}, maxNumberOfBounces::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon until it is absorbed or bounces through the reference plane\n #\n # TERMINAL CODES:\n #\n # -1 the maximum number of cycles was reached\n # 1 photon escapes through the reference plane\n # 2 photon escapes through the bottom plane\n # 3 photon cyclicly re-enters the scene (through walls)'\n # 4 photon is absorbed\n # 5 photon is scattered\n #\n path::AbstractArray{T, 2} = zeros(Float64, maxNumberOfBounces+1, 3)\n path[1,:] = [ray.x, ray.y, ray.z]\n codes::AbstractArray{Int, 1} = zeros(Int, maxNumberOfBounces+1) # code[1] === 0\n index::Int = 1\n count_while_loop::Int = 0\n continue_iterating::Bool = true\n mtl::Int = -1\n while continue_iterating\n count_while_loop += 1\n\tindex += 1\n if count_while_loop >= maxNumberOfBounces\n path[index, :] = [ray.x, ray.y, ray.z]\n codes[index] = -1\n continue_iterating = false\n continue\n end\n I_wall, side, r_wall = intersect_walls(walls, ray)\n hit_scene, I_scene, tray, nrml, range_scene, aidx, oidx, eidx = intersect_scene(assets, geometries, geometry_bvhs, scene_bvh, ray)\n wall = r_wall <= range_scene\n if wall === true\n if side === 't'\n # photon escapes through reference plane\n continue_iterating = false\n codes[index] = 1\n path[index, :] = [I_wall.x, I_wall.y, I_wall.z]\n elseif (side === 'b')\n # photon is absorbed by a black surface underneath the scene\n continue_iterating = false\n codes[index] = 2\n path[index, :] = [I_wall.x, I_wall.y, I_wall.z]\n else # thus the condition: ' !(side ==='t') && !(side === 'b') ' is true\n # photon cyclicly re-enters from the opposite wall\n ray = cycle_ray(walls, ray)\n count_while_loop -= 1 # don't count these events toward the number of cycles\n index -= 1\n end\n else # wall is false, hence ray must have hit the (objects in the) scene\n hit = true\n @assert(hit_scene)\n\t geometry = geometries[oidx]\n mtl = geometry.mtl[eidx]\n pidx = assets[aidx].pidx\n shader = palettes[pidx][mtl]\n scatter, ray, r = shader(I_scene.x, I_scene.y, I_scene.z, -tray.dx, -tray.dy, -tray.dz, nrml.x, nrml.y, nrml.z)\n if scatter === false\n continue_iterating = false\n codes[index] = 4\n path[index, :] = [I_scene.x, I_scene.y, I_scene.z]\n else\n codes[index] = 5\n path[index, :] = [I_scene.x, I_scene.y, I_scene.z]\n end\n\tend\n end\n return path, codes\nend\n\nfunction trace_forward(geometry::Geometry{T,S,A,E}, shaders::Vector{Function}, walls::Walls{T}, ray::Ray{T}, maxNumberOfBounces::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon until it is absorbed or bounces through the reference plane\n count_while_loop::Int = 0\n continue_iterating::Bool = true\n mtl::Int = -1\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfBounces\n continue_iterating = false\n continue\n end\n I_wall, side, r_wall = intersect_walls(walls, ray)\n hit_, In, eidx, nrml, rmin = intersect(geometry, ray)\n wall = r_wall <= rmin\n if wall === true\n if side === 't'\n # photon escapes through reference plane\n continue_iterating = false\n elseif (side === 'b')\n # photon is absorbed by a black surface underneath the scene\n continue_iterating = false\n else # thus the condition: ' !(side ==='t') && !(side === 'b') ' is true\n # photon cyclicly re-enters from the opposite wall\n ray = cycle_ray(walls, ray)\n count_while_loop -= 1 # don't count these events toward the number of cycles\n end\n else # implies hit_ is true, because the ray either hits the scene or a wall\n hit = true\n mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n if scatter === false\n continue_iterating = false\n end\n\tend\n end\n return ray\nend\n\nfunction trace_forward(geometry::Geometry{T,S,A,E}, geometry_bvh::Bvh{T,S,A,E}, shaders::Vector{Function}, walls::Walls{T}, ray::Ray{T}, maxNumberOfBounces::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon until it is absorbed or bounces through the reference plane\n count_while_loop::Int = 0\n continue_iterating::Bool = true\n mtl::Int = -1\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfBounces\n continue_iterating = false\n continue\n end\n I_wall, side, r_wall = intersect_walls(walls, ray)\n hit_, In, eidx, nrml, rmin = intersect(geometry, geometry_bvh, ray)\n wall = r_wall <= rmin\n if wall === true\n if side === 't'\n # photon escapes through reference plane\n continue_iterating = false\n elseif (side === 'b')\n # photon is absorbed by a black surface underneath the scene\n continue_iterating = false\n else # thus the condition: ' !(side ==='t') && !(side === 'b') ' is true\n # photon cyclicly re-enters from the opposite wall\n ray = cycle_ray(walls, ray)\n count_while_loop -= 1 # don't count these events toward the number of cycles\n end\n else # implies hit_ is true, because the ray either hits the scene or a wall\n hit = true\n mtl = geometry.mtl[eidx]\n scatter, ray, r = shaders[mtl](In.x, In.y, In.z, -ray.dx, -ray.dy, -ray.dz, nrml.x, nrml.y, nrml.z)\n radiance .*= r\n if scatter === false\n continue_iterating = false\n end\n\tend\n end\n return ray\nend\n\nfunction trace_forward(assets::AbstractArray{Asset{T,S},1}, geometries::AbstractArray{Geometry{T,S,A,E},1}, palettes::AbstractArray{Vector{Function},1}, geometry_bvhs::AbstractArray{Bvh{T,S,A,E},1}, scene_bvh::Bvh{T,S,A,E}, walls::Walls{T}, ray::Ray{T}, maxNumberOfBounces::S) where {T<:AbstractFloat, S<:Integer, A<:AbstractArray{T,1}, E<:AbstractArray{S,1}}\n # traces ray/photon until it is absorbed or bounces through the reference plane\n count_while_loop::Int = 0\n continue_iterating::Bool = true\n mtl::Int = -1\n while continue_iterating\n count_while_loop += 1\n if count_while_loop >= maxNumberOfBounces\n push!(codes, -1)\n push!(path, Line(ray.x, ray.y, ray.z, ray.x, ray.y, ray.z)) # add a zero-length line, basically indicating that we stop tracing here...\n continue_iterating = false\n continue\n end\n I_wall, side, r_wall = intersect_walls(walls, ray)\n hit_scene, I_scene, tray, nrml, range_scene, aidx, oidx, eidx = intersect_scene(assets, geometries, geometry_bvhs, scene_bvh, ray)\n wall = r_wall <= range_scene\n if wall === true\n if side === 't'\n # photon escapes through reference plane\n continue_iterating = false\n elseif (side === 'b')\n # photon is absorbed by a black surface underneath the scene\n continue_iterating = false\n else # thus the condition: ' !(side ==='t') && !(side === 'b') ' is true\n # photon cyclicly re-enters from the opposite wall\n ray = cycle_ray(walls, ray)\n count_while_loop -= 1 # don't count these events toward the number of cycles\n end\n else # wall is false, hence ray must have hit the (objects in the) scene\n hit = true\n\t geometry = geometries[oidx]\n mtl = geometry.mtl[eidx]\n pidx = assets[aidx].pidx\n shader = palettes[pidx][mtl]\n scatter, ray, r = shader(I_scene.x, I_scene.y, I_scene.z, -tray.dx, -tray.dy, -tray.dz, nrml.x, nrml.y, nrml.z)\n if scatter === false\n continue_iterating = false\n end\n\tend\n end\n return ray\nend\n", "meta": {"hexsha": "3a2cffc87a455cbf005dcf624a587584ac4aea58", "size": 20668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trace.jl", "max_stars_repo_name": "martinvanleeuwen/RenderJay", "max_stars_repo_head_hexsha": "45d0db721550d677448abddef0c6660d41922d6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-28T23:47:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T23:47:24.000Z", "max_issues_repo_path": "src/trace.jl", "max_issues_repo_name": "martinvanleeuwen/RenderJay", "max_issues_repo_head_hexsha": "45d0db721550d677448abddef0c6660d41922d6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/trace.jl", "max_forks_repo_name": "martinvanleeuwen/RenderJay", "max_forks_repo_head_hexsha": "45d0db721550d677448abddef0c6660d41922d6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8796680498, "max_line_length": 383, "alphanum_fraction": 0.5876717631, "num_tokens": 5697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19466748782771073}} {"text": "\nstruct LoopMulFunc{P,TC,TA,TB,Α,Β,Md,Kd,Nd} <: Function end\nfunction (::LoopMulFunc{P,TC,TA,TB,Α,Β,Md,Kd,Nd})(p::Ptr{UInt}) where {P,TC,TA,TB,Α,Β,Md,Kd,Nd}\n offset, C = load(p, TC, 2*sizeof(UInt))\n offset, A = load(p, TA, offset)\n offset, B = load(p, TB, offset)\n offset, α = load(p, Α, offset)\n offset, β = load(p, Β, offset)\n offset, M = load(p, Md, offset)\n offset, K = load(p, Kd, offset)\n offset, N = load(p, Nd, offset)\n _call_loopmul!(C, A, B, α, β, M, K, N, Val{P}())\n _atomic_store!(p, SPIN)\n nothing\nend\n@inline _call_loopmul!(C, A, B, α, β, M, K, N, ::Val{false}) = loopmul!(C, A, B, α, β, M, K, N)\n@inline function _call_loopmul!(C::StridedPointer{T}, A, B, α, β, M, K, N, ::Val{true}) where {T}\n if M*K < first_cache_size(Val(T)) * R₂Default()\n packaloopmul!(C, A, B, α, β, M, K, N)\n return\n else\n matmul_st_only_pack_A!(C, A, B, α, β, M, K, N, W₁Default(), W₂Default(), R₁Default(), R₂Default())\n return\n end\nend\ncall_loopmul!(C, A, B, α, β, M, K, N, ::Val{P}) where {P} = _call_loopmul!(C, A, B, α, β, M, K, N, Val{P}())\n\nstruct SyncMulFunc{TC,TA,TB,Α,Β,Md,Kd,Nd,BCP,ID,TT,W₁,W₂,R₁,R₂} <: Function end\nfunction (::SyncMulFunc{TC,TA,TB,Α,Β,Md,Kd,Nd,BCP,ID,TT,W₁,W₂,R₁,R₂})(p::Ptr{UInt}) where {TC,TA,TB,Α,Β,Md,Kd,Nd,BCP,ID,TT,W₁,W₂,R₁,R₂}\n offset, C = load(p, TC, 2*sizeof(UInt))\n offset, A = load(p, TA, offset)\n offset, B = load(p, TB, offset)\n offset, α = load(p, Α, offset)\n offset, β = load(p, Β, offset)\n offset, M = load(p, Md, offset)\n offset, K = load(p, Kd, offset)\n offset, N = load(p, Nd, offset)\n offset, atomicp = load(p, Ptr{UInt32}, offset)\n offset, bcachep = load(p, BCP, offset)\n offset, id = load(p, ID, offset)\n offset, total_ids = load(p, TT, offset)\n sync_mul!(C, A, B, α, β, M, K, N, atomicp, bcachep, id, total_ids, StaticFloat64{W₁}(), StaticFloat64{W₂}(), StaticFloat64{R₁}(), StaticFloat64{R₂}())\n _atomic_store!(p, SPIN)\n nothing\nend\n\n@generated function cfuncpointer(::T) where {T}\n precompile(T(), (Ptr{UInt},))\n quote\n $(Expr(:meta,:inline))\n @cfunction($(T()), Cvoid, (Ptr{UInt},))\n end\nend\n\n@inline function setup_matmul!(p::Ptr{UInt}, C::TC, A::TA, B::TB, α::Α, β::Β, M::Md, K::Kd, N::Nd, ::Val{P}) where {P,TC,TA,TB,Α,Β,Md,Kd,Nd}\n offset = store!(p, cfuncpointer(LoopMulFunc{P,TC,TA,TB,Α,Β,Md,Kd,Nd}()), sizeof(UInt))\n offset = store!(p, C, offset)\n offset = store!(p, A, offset)\n offset = store!(p, B, offset)\n offset = store!(p, α, offset)\n offset = store!(p, β, offset)\n offset = store!(p, M, offset)\n offset = store!(p, K, offset)\n offset = store!(p, N, offset)\n nothing\nend\n\n@inline function launch_thread_mul!(C, A, B, α, β, M, K, N, tid::UInt32, ::Val{P}) where {P}\n launch(setup_matmul!, tid, C, A, B, α, β, M, K, N, Val{P}())\nend\n\nstruct SyncMulLauncher{W₁, W₂, R₁, R₂} end\n@inline function (::SyncMulLauncher{W₁, W₂, R₁, R₂})(\n p::Ptr{UInt}, C::TC, A::TA, B::TB, α::Α, β::Β, M::Md, K::Kd, N::Nd,\n ap::Ptr{UInt32},bcp::BCP,id::ID,tt::TT\n) where {TC,TA,TB,Α,Β,Md,Kd,Nd,BCP,ID,TT,W₁,W₂,R₁,R₂}\n fptr = cfuncpointer(SyncMulFunc{TC,TA,TB,Α,Β,Md,Kd,Nd,BCP,ID,TT,W₁,W₂,R₁,R₂}())\n offset = store!(p, fptr, sizeof(UInt))\n offset = store!(p, C, offset)\n offset = store!(p, A, offset)\n offset = store!(p, B, offset)\n offset = store!(p, α, offset)\n offset = store!(p, β, offset)\n offset = store!(p, M, offset)\n offset = store!(p, K, offset)\n offset = store!(p, N, offset)\n offset = store!(p, ap, offset)\n offset = store!(p, bcp, offset)\n offset = store!(p, id, offset)\n offset = store!(p, tt, offset)\n nothing\nend\n@inline function launch_thread_mul!(\n C, A, B, α, β, M, K, N, ap, bcp, tid, id, tt,\n ::StaticFloat64{W₁},::StaticFloat64{W₂},::StaticFloat64{R₁},::StaticFloat64{R₂}\n) where {W₁,W₂,R₁,R₂}\n launch(SyncMulLauncher{W₁, W₂, R₁, R₂}(), tid, C, A, B, α, β, M, K, N, ap, bcp, id, tt)\nend\n\n\n", "meta": {"hexsha": "26c0f89e242a7426d88f049bb211c7609ae2da8b", "size": 3827, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/funcptrs.jl", "max_stars_repo_name": "IanButterworth/Octavian.jl", "max_stars_repo_head_hexsha": "db713f3310030041bfa55576a15fcbeb55585884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/funcptrs.jl", "max_issues_repo_name": "IanButterworth/Octavian.jl", "max_issues_repo_head_hexsha": "db713f3310030041bfa55576a15fcbeb55585884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-12-26T21:59:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-26T22:27:59.000Z", "max_forks_repo_path": "src/funcptrs.jl", "max_forks_repo_name": "DilumAluthge/Augustus.jl", "max_forks_repo_head_hexsha": "ad7f0997f916437d06c2b44824a9ff82a24e9af2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8910891089, "max_line_length": 152, "alphanum_fraction": 0.6096158871, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.19465170062065518}} {"text": "# Utilities for taking gradients through simulations\n\nexport\n extract_parameters,\n inject_gradients\n\n\"\"\"\n extract_parameters(system, force_field)\n\nForm a `Dict` of all parameters in a `System`, allowing gradients\nto be tracked.\n\"\"\"\nfunction extract_parameters(sys, ff)\n params_dic = Dict()\n\n for at_data in sys.atoms_data\n key_prefix = \"atom_$(at_data.atom_type)_\"\n if !haskey(params_dic, key_prefix * \"mass\")\n at = ff.atom_types[at_data.atom_type]\n params_dic[key_prefix * \"mass\"] = at.mass\n params_dic[key_prefix * \"σ\" ] = at.σ\n params_dic[key_prefix * \"ϵ\" ] = at.ϵ\n end\n end\n\n for inter in values(sys.pairwise_inters)\n if inter isa LennardJones\n key_prefix = \"inter_LJ_\"\n params_dic[key_prefix * \"weight_14\"] = inter.weight_14\n params_dic[key_prefix * \"weight_solute_solvent\"] = inter.weight_solute_solvent\n elseif inter isa Coulomb\n key_prefix = \"inter_CO_\"\n params_dic[key_prefix * \"weight_14\"] = inter.weight_14\n params_dic[key_prefix * \"coulomb_const\"] = inter.coulomb_const\n elseif inter isa CoulombReactionField\n key_prefix = \"inter_CRF_\"\n params_dic[key_prefix * \"dist_cutoff\"] = inter.dist_cutoff\n params_dic[key_prefix * \"solvent_dielectric\"] = inter.solvent_dielectric\n params_dic[key_prefix * \"weight_14\"] = inter.weight_14\n params_dic[key_prefix * \"coulomb_const\"] = inter.coulomb_const\n end\n end\n\n for inter in values(sys.specific_inter_lists)\n if Molly.interaction_type(inter) <: HarmonicBond\n for bond_type in inter.types\n key_prefix = \"inter_HB_$(bond_type)_\"\n if !haskey(params_dic, key_prefix * \"b0\")\n bond = ff.bond_types[atom_types_to_tuple(bond_type)]\n params_dic[key_prefix * \"b0\"] = bond.b0\n params_dic[key_prefix * \"kb\"] = bond.kb\n end\n end\n elseif Molly.interaction_type(inter) <: HarmonicAngle\n for angle_type in inter.types\n key_prefix = \"inter_HA_$(angle_type)_\"\n if !haskey(params_dic, key_prefix * \"th0\")\n angle = ff.angle_types[atom_types_to_tuple(angle_type)]\n params_dic[key_prefix * \"th0\"] = angle.th0\n params_dic[key_prefix * \"cth\"] = angle.cth\n end\n end\n elseif Molly.interaction_type(inter) <: PeriodicTorsion\n for (torsion_type, torsion_inter) in zip(inter.types, Array(inter.inters))\n if torsion_inter.proper\n key_prefix = \"inter_PT_$(torsion_type)_\"\n else\n key_prefix = \"inter_IT_$(torsion_type)_\"\n end\n if !haskey(params_dic, key_prefix * \"phase_1\")\n torsion = ff.torsion_types[atom_types_to_tuple(torsion_type)]\n for i in 1:length(torsion.phases)\n params_dic[key_prefix * \"phase_$i\"] = torsion.phases[i]\n params_dic[key_prefix * \"k_$i\" ] = torsion.ks[i]\n end\n end\n end\n end\n end\n\n return params_dic\nend\n\n\"\"\"\n inject_gradients(sys, params_dic)\n\nAdd parameters from a dictionary to a `System`.\nAllows gradients for individual parameters to be tracked.\nReturns atoms, pairwise interactions and specific interaction lists.\n\"\"\"\nfunction inject_gradients(sys, params_dic, gpu::Bool=isa(sys.coords, CuArray))\n if gpu\n atoms_grad = cu(inject_atom.(Array(sys.atoms), sys.atoms_data, (params_dic,)))\n else\n atoms_grad = inject_atom.(sys.atoms, sys.atoms_data, (params_dic,))\n end\n pis_grad = inject_interaction.(sys.pairwise_inters, (params_dic,))\n sis_grad = inject_interaction_list.(sys.specific_inter_lists, (params_dic,), gpu)\n return atoms_grad, pis_grad, sis_grad\nend\n\n# get function errors with AD\ndict_get(dic, key, default) = haskey(dic, key) ? dic[key] : default\n\nfunction inject_atom(at, at_data, params_dic)\n key_prefix = \"atom_$(at_data.atom_type)_\"\n Atom(\n at.index,\n at.charge, # Residue-specific\n dict_get(params_dic, key_prefix * \"mass\" , at.mass ),\n dict_get(params_dic, key_prefix * \"σ\" , at.σ ),\n dict_get(params_dic, key_prefix * \"ϵ\" , at.ϵ ),\n at.solute,\n )\nend\n\nfunction inject_interaction_list(inter::InteractionList2Atoms, params_dic, gpu)\n if gpu\n inters_grad = cu(inject_interaction.(Array(inter.inters), inter.types, (params_dic,)))\n else\n inters_grad = inject_interaction.(inter.inters, inter.types, (params_dic,))\n end\n InteractionList2Atoms(inter.is, inter.js, inter.types, inters_grad)\nend\n\nfunction inject_interaction_list(inter::InteractionList3Atoms, params_dic, gpu)\n if gpu\n inters_grad = cu(inject_interaction.(Array(inter.inters), inter.types, (params_dic,)))\n else\n inters_grad = inject_interaction.(inter.inters, inter.types, (params_dic,))\n end\n InteractionList3Atoms(inter.is, inter.js, inter.ks, inter.types, inters_grad)\nend\n\nfunction inject_interaction_list(inter::InteractionList4Atoms, params_dic, gpu)\n if gpu\n inters_grad = cu(inject_interaction.(Array(inter.inters), inter.types, (params_dic,)))\n else\n inters_grad = inject_interaction.(inter.inters, inter.types, (params_dic,))\n end\n InteractionList4Atoms(inter.is, inter.js, inter.ks, inter.ls,\n inter.types, inters_grad)\nend\n\nfunction inject_interaction(inter::LennardJones{S, C, W, WS, F, E}, params_dic) where {S, C, W, WS, F, E}\n key_prefix = \"inter_LJ_\"\n LennardJones{S, C, W, WS, F, E}(\n inter.cutoff,\n inter.nl_only,\n inter.lorentz_mixing,\n dict_get(params_dic, key_prefix * \"weight_14\", inter.weight_14),\n dict_get(params_dic, key_prefix * \"weight_solute_solvent\", inter.weight_solute_solvent),\n inter.force_units,\n inter.energy_units,\n )\nend\n\nfunction inject_interaction(inter::Coulomb, params_dic)\n key_prefix = \"inter_CO_\"\n Coulomb(\n inter.cutoff,\n inter.nl_only,\n dict_get(params_dic, key_prefix * \"weight_14\", inter.weight_14),\n dict_get(params_dic, key_prefix * \"coulomb_const\", inter.coulomb_const),\n inter.force_units,\n inter.energy_units,\n )\nend\n\nfunction inject_interaction(inter::CoulombReactionField, params_dic)\n key_prefix = \"inter_CRF_\"\n CoulombReactionField(\n dict_get(params_dic, key_prefix * \"dist_cutoff\", inter.dist_cutoff),\n dict_get(params_dic, key_prefix * \"solvent_dielectric\", inter.solvent_dielectric),\n inter.nl_only,\n dict_get(params_dic, key_prefix * \"weight_14\", inter.weight_14),\n dict_get(params_dic, key_prefix * \"coulomb_const\", inter.coulomb_const),\n inter.force_units,\n inter.energy_units,\n )\nend\n\nfunction inject_interaction(inter::HarmonicBond, inter_type, params_dic)\n key_prefix = \"inter_HB_$(inter_type)_\"\n HarmonicBond(\n dict_get(params_dic, key_prefix * \"b0\", inter.b0),\n dict_get(params_dic, key_prefix * \"kb\", inter.kb),\n )\nend\n\nfunction inject_interaction(inter::HarmonicAngle, inter_type, params_dic)\n key_prefix = \"inter_HA_$(inter_type)_\"\n HarmonicAngle(\n dict_get(params_dic, key_prefix * \"th0\", inter.th0),\n dict_get(params_dic, key_prefix * \"cth\", inter.cth),\n )\nend\n\nfunction inject_interaction(inter::PeriodicTorsion{N, T, E}, inter_type, params_dic) where {N, T, E}\n if inter.proper\n key_prefix = \"inter_PT_$(inter_type)_\"\n else\n key_prefix = \"inter_IT_$(inter_type)_\"\n end\n PeriodicTorsion{N, T, E}(\n inter.periodicities,\n ntuple(i -> dict_get(params_dic, key_prefix * \"phase_$i\", inter.phases[i]), N),\n ntuple(i -> dict_get(params_dic, key_prefix * \"k_$i\" , inter.ks[i] ), N),\n inter.proper,\n )\nend\n", "meta": {"hexsha": "8c8db5fe0fc3c6789fae0b2d07c06b423e5c6de2", "size": 8053, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gradients.jl", "max_stars_repo_name": "jrdegreeff/Molly.jl", "max_stars_repo_head_hexsha": "9d2b44a9a87423575f1ef33bfddb88662324c206", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gradients.jl", "max_issues_repo_name": "jrdegreeff/Molly.jl", "max_issues_repo_head_hexsha": "9d2b44a9a87423575f1ef33bfddb88662324c206", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradients.jl", "max_forks_repo_name": "jrdegreeff/Molly.jl", "max_forks_repo_head_hexsha": "9d2b44a9a87423575f1ef33bfddb88662324c206", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9858490566, "max_line_length": 105, "alphanum_fraction": 0.6444803179, "num_tokens": 1994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19423646169227823}} {"text": "##############################################################\n\n\"\"\"\n function fasta2matrix(filename::AbstractString; max_gap_fraction = 1)\n\n Reads an aligned fasta file and returns a matrix with amino acids converted\n to numbers following the convention A --> 1, C --> 2, ... '-' --> 21.\n\n \"filename\": full path of the fasta file. \n \"max_gap_fraction\": to be removed. \n\n\"\"\"\n\nfunction fasta2matrix(filename::AbstractString; max_gap_fraction = 1)\n f = FastaReader(filename)\n\n max_gap_fraction = Float64(max_gap_fraction)\n\n # pass 1\n\n seqs = Int[]\n inds = Int[]\n fseqlen = 0\n\n for (name, seq) in f\n ngaps = 0\n if f.num_parsed == 1\n ls = length(seq)\n resize!(inds, ls)\n for i = 1:ls\n c = seq[i]\n if c != '.' && c == uppercase(c)\n fseqlen += 1\n inds[fseqlen] = i\n c == '-' && (ngaps += 1)\n end\n end\n else\n ls = length(seq)\n ls == length(inds) || error(\"inputs are not aligned\")\n tstfseqlen = 0\n for i = 1:ls\n c = seq[i]\n if c != '.' && c == uppercase(c)\n tstfseqlen += 1\n inds[tstfseqlen] == i || error(\"inconsistent inputs\")\n c == '-' && (ngaps += 1)\n end\n end\n tstfseqlen == fseqlen || error(\"inconsistent inputs\")\n end\n ngaps / fseqlen <= max_gap_fraction && push!(seqs, f.num_parsed)\n end\n\n length(seqs) > 0 || error(\"Out of $(f.num_parsed) sequences, none passed the filter (max_gap_fraction=$max_gap_fraction)\")\n\n # pass 2\n Z = Array{Int16}(undef, fseqlen, length(seqs))\n seqid = 1\n for (name, seq) in f\n seqs[end] < f.num_parsed && break\n seqs[seqid] == f.num_parsed || continue\n for i = 1:fseqlen\n c = seq[inds[i]]\n Z[i, seqid] = letter2num(c)\n end\n seqid += 1\n end\n @assert seqid == length(seqs) + 1\n\n close(f)\n\n return Z'\nend\n\n\n##############################################################\n\"\"\"\n letter2num(c::Union{Char,UInt8})\n\n Takes as input a char (representing an amino acid)\n and returns its conventional number representation.\n In this case with the convention \"1 2 .. 21\" <==> \"A C .. -\"\n\"\"\"\n\nlet alphabet = [ 1, 21, 2, 3, 4, 5, 6, 7, 8, 21, 9, 10, 11, 12, 21, 13, 14, 15, 16, 17, 21, 18, 19, 21, 20]\n # A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y\n global letter2num\n function letter2num(c::Union{Char,UInt8})\n i = UInt8(c) - 0x40\n 1 <= i <= 25 && return alphabet[i]\n return 21\n end\nend\n\n\n##############################################################\n\"\"\"\n num2letter(i::Integer)\n\n Takes as input an integer (representing an amino acid)\n and returns its conventional character representation.\n In this case with the convention \"1 2 .. 21\" <==> \"A C .. -\"\n\"\"\"\n\n\nlet alphabet = [\"A\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"K\", \"L\", \"M\", \"N\", \"P\", \"Q\", \"R\",\n\"S\", \"T\", \"V\", \"W\", \"Y\"]\n global num2letter\n function num2letter(i :: Integer)\n 1 <= i <= 20 && return alphabet[i]\n return \"-\"\n end\nend\n\n\n##############################################################\n\"\"\"\n vec2string(v)\n\n Takes as input a vector of integers (representing an amino acids)\n and returns a list of characters, the corresponding amino acids. \n In this case with the convention \"1 2 .. 21\" <==> \"A C .. -\"\n\"\"\"\n\n\nfunction vec2string(v)\n s = \"\"\n for i in v\n s = s*num2letter(i)\n end\n return s\nend\n\n\n\n##############################################################\n\"\"\"\n Takes as input a string (representing amino acids)\n and returns a vector of numbers, the corresponding number representation. \n In this case with the convention \"1 2 .. 21\" <==> \"A C .. -\"\n\"\"\"\n\n\nfunction string2vec(s)\n v = Vector{Int8}(undef, length(s))\n for (i, l) in enumerate(s)\n v[i] = letter2num(l)\n end\n return v\nend\n\n", "meta": {"hexsha": "58745e494542b7e0c7c17d43229fbb5e8158ad6b", "size": 4137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/read_write_MSA.jl", "max_stars_repo_name": "sabrinacotogno/KitMSA", "max_stars_repo_head_hexsha": "d54c0f20d51ff9d9bbb41f80f072f328b211a17e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/read_write_MSA.jl", "max_issues_repo_name": "sabrinacotogno/KitMSA", "max_issues_repo_head_hexsha": "d54c0f20d51ff9d9bbb41f80f072f328b211a17e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/read_write_MSA.jl", "max_forks_repo_name": "sabrinacotogno/KitMSA", "max_forks_repo_head_hexsha": "d54c0f20d51ff9d9bbb41f80f072f328b211a17e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0392156863, "max_line_length": 126, "alphanum_fraction": 0.4815083394, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19422425689540748}} {"text": "# ----------------------------------------------------------------------------------- #\n# Copyright (c) 2016 Varnerlab\n# Robert Frederick Smith School of Chemical and Biomolecular Engineering\n# Cornell University, Ithaca NY 14850\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n# ----------------------------------------------------------------------------------- #\n#\n# ----------------------------------------------------------------------------------- #\n# Function: Control\n# Description: Calculate the transcriptional control array at time t\n# Generated on: 2016-11-02T07:00:01.342\n#\n# Input arguments:\n# t::Float64 => Current time value (scalar) \n# x::Array{Float64,1} => State array (number_of_species x 1) \n# data_dictionary::Dict{AbstractString,Any} => Dictionary holding model parameters \n#\n# Output arguments:\n# control_array::Array{Float64,1} => Transcriptional control array (number_of_genes x 1) at time t \n# ----------------------------------------------------------------------------------- #\nfunction Control(t::Float64,x::Array{Float64,1},data_dictionary::Dict{AbstractString,Any})\n\n\t# initialize the control - \n\tcontrol_array = zeros(18)\n\n\t# Alias the species - \n\tgene_AP1 = x[1]\n\tgene_AhR = x[2]\n\tgene_CD11b = x[3]\n\tgene_CD14 = x[4]\n\tgene_CD38 = x[5]\n\tgene_CEBPa = x[6]\n\tgene_E2F = x[7]\n\tgene_EGR1 = x[8]\n\tgene_GFI1 = x[9]\n\tgene_IRF1 = x[10]\n\tgene_OCT1 = x[11]\n\tgene_OCT4 = x[12]\n\tgene_P21 = x[13]\n\tgene_P47Phox = x[14]\n\tgene_PPARg = x[15]\n\tgene_PU1 = x[16]\n\tgene_Trigger = x[17]\n\tgene_cRAF = x[18]\n\tmRNA_gene_AP1 = x[19]\n\tmRNA_gene_AhR = x[20]\n\tmRNA_gene_CD11b = x[21]\n\tmRNA_gene_CD14 = x[22]\n\tmRNA_gene_CD38 = x[23]\n\tmRNA_gene_CEBPa = x[24]\n\tmRNA_gene_E2F = x[25]\n\tmRNA_gene_EGR1 = x[26]\n\tmRNA_gene_GFI1 = x[27]\n\tmRNA_gene_IRF1 = x[28]\n\tmRNA_gene_OCT1 = x[29]\n\tmRNA_gene_OCT4 = x[30]\n\tmRNA_gene_P21 = x[31]\n\tmRNA_gene_P47Phox = x[32]\n\tmRNA_gene_PPARg = x[33]\n\tmRNA_gene_PU1 = x[34]\n\tmRNA_gene_Trigger = x[35]\n\tmRNA_gene_cRAF = x[36]\n\tprotein_gene_AP1 = x[37]\n\tprotein_gene_AhR = x[38]\n\tprotein_gene_CD11b = x[39]\n\tprotein_gene_CD14 = x[40]\n\tprotein_gene_CD38 = x[41]\n\tprotein_gene_CEBPa = x[42]\n\tprotein_gene_E2F = x[43]\n\tprotein_gene_EGR1 = x[44]\n\tprotein_gene_GFI1 = x[45]\n\tprotein_gene_IRF1 = x[46]\n\tprotein_gene_OCT1 = x[47]\n\tprotein_gene_OCT4 = x[48]\n\tprotein_gene_P21 = x[49]\n\tprotein_gene_P47Phox = x[50]\n\tprotein_gene_PPARg = x[51]\n\tprotein_gene_PU1 = x[52]\n\tprotein_gene_Trigger = x[53]\n\tprotein_gene_cRAF = x[54]\n\n\t# Alias the binding parameters - \n\tbinding_parameter_dictionary = data_dictionary[\"binding_parameter_dictionary\"]\n\tn_gene_AP1_gene_AhR = binding_parameter_dictionary[\"n_gene_AP1_gene_AhR\"]\n\tK_gene_AP1_gene_AhR = binding_parameter_dictionary[\"K_gene_AP1_gene_AhR\"]\n\tn_gene_AP1_gene_PU1 = binding_parameter_dictionary[\"n_gene_AP1_gene_PU1\"]\n\tK_gene_AP1_gene_PU1 = binding_parameter_dictionary[\"K_gene_AP1_gene_PU1\"]\n\tn_gene_AP1_gene_PPARg = binding_parameter_dictionary[\"n_gene_AP1_gene_PPARg\"]\n\tK_gene_AP1_gene_PPARg = binding_parameter_dictionary[\"K_gene_AP1_gene_PPARg\"]\n\tn_gene_AhR_gene_Trigger = binding_parameter_dictionary[\"n_gene_AhR_gene_Trigger\"]\n\tK_gene_AhR_gene_Trigger = binding_parameter_dictionary[\"K_gene_AhR_gene_Trigger\"]\n\tn_gene_CD11b_gene_PU1_gene_cRAF = binding_parameter_dictionary[\"n_gene_CD11b_gene_PU1_gene_cRAF\"]\n\tK_gene_CD11b_gene_PU1_gene_cRAF = binding_parameter_dictionary[\"K_gene_CD11b_gene_PU1_gene_cRAF\"]\n\tn_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF = binding_parameter_dictionary[\"n_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"]\n\tK_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF = binding_parameter_dictionary[\"K_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"]\n\tn_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF = binding_parameter_dictionary[\"n_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"]\n\tK_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF = binding_parameter_dictionary[\"K_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"]\n\tn_gene_CEBPa_gene_Trigger = binding_parameter_dictionary[\"n_gene_CEBPa_gene_Trigger\"]\n\tK_gene_CEBPa_gene_Trigger = binding_parameter_dictionary[\"K_gene_CEBPa_gene_Trigger\"]\n\tn_gene_CEBPa_gene_PPARg = binding_parameter_dictionary[\"n_gene_CEBPa_gene_PPARg\"]\n\tK_gene_CEBPa_gene_PPARg = binding_parameter_dictionary[\"K_gene_CEBPa_gene_PPARg\"]\n\tn_gene_CEBPa_gene_CEBPa = binding_parameter_dictionary[\"n_gene_CEBPa_gene_CEBPa\"]\n\tK_gene_CEBPa_gene_CEBPa = binding_parameter_dictionary[\"K_gene_CEBPa_gene_CEBPa\"]\n\tn_gene_CEBPa_gene_GFI1 = binding_parameter_dictionary[\"n_gene_CEBPa_gene_GFI1\"]\n\tK_gene_CEBPa_gene_GFI1 = binding_parameter_dictionary[\"K_gene_CEBPa_gene_GFI1\"]\n\tn_gene_E2F_gene_E2F = binding_parameter_dictionary[\"n_gene_E2F_gene_E2F\"]\n\tK_gene_E2F_gene_E2F = binding_parameter_dictionary[\"K_gene_E2F_gene_E2F\"]\n\tn_gene_E2F_gene_PPARg = binding_parameter_dictionary[\"n_gene_E2F_gene_PPARg\"]\n\tK_gene_E2F_gene_PPARg = binding_parameter_dictionary[\"K_gene_E2F_gene_PPARg\"]\n\tn_gene_E2F_gene_CEBPa = binding_parameter_dictionary[\"n_gene_E2F_gene_CEBPa\"]\n\tK_gene_E2F_gene_CEBPa = binding_parameter_dictionary[\"K_gene_E2F_gene_CEBPa\"]\n\tn_gene_E2F_gene_GFI1 = binding_parameter_dictionary[\"n_gene_E2F_gene_GFI1\"]\n\tK_gene_E2F_gene_GFI1 = binding_parameter_dictionary[\"K_gene_E2F_gene_GFI1\"]\n\tn_gene_E2F_gene_cRAF = binding_parameter_dictionary[\"n_gene_E2F_gene_cRAF\"]\n\tK_gene_E2F_gene_cRAF = binding_parameter_dictionary[\"K_gene_E2F_gene_cRAF\"]\n\tn_gene_EGR1_gene_Trigger = binding_parameter_dictionary[\"n_gene_EGR1_gene_Trigger\"]\n\tK_gene_EGR1_gene_Trigger = binding_parameter_dictionary[\"K_gene_EGR1_gene_Trigger\"]\n\tn_gene_EGR1_gene_PU1 = binding_parameter_dictionary[\"n_gene_EGR1_gene_PU1\"]\n\tK_gene_EGR1_gene_PU1 = binding_parameter_dictionary[\"K_gene_EGR1_gene_PU1\"]\n\tn_gene_EGR1_gene_PPARg = binding_parameter_dictionary[\"n_gene_EGR1_gene_PPARg\"]\n\tK_gene_EGR1_gene_PPARg = binding_parameter_dictionary[\"K_gene_EGR1_gene_PPARg\"]\n\tn_gene_EGR1_gene_GFI1 = binding_parameter_dictionary[\"n_gene_EGR1_gene_GFI1\"]\n\tK_gene_EGR1_gene_GFI1 = binding_parameter_dictionary[\"K_gene_EGR1_gene_GFI1\"]\n\tn_gene_GFI1_gene_CEBPa = binding_parameter_dictionary[\"n_gene_GFI1_gene_CEBPa\"]\n\tK_gene_GFI1_gene_CEBPa = binding_parameter_dictionary[\"K_gene_GFI1_gene_CEBPa\"]\n\tn_gene_GFI1_gene_EGR1 = binding_parameter_dictionary[\"n_gene_GFI1_gene_EGR1\"]\n\tK_gene_GFI1_gene_EGR1 = binding_parameter_dictionary[\"K_gene_GFI1_gene_EGR1\"]\n\tn_gene_IRF1_gene_Trigger = binding_parameter_dictionary[\"n_gene_IRF1_gene_Trigger\"]\n\tK_gene_IRF1_gene_Trigger = binding_parameter_dictionary[\"K_gene_IRF1_gene_Trigger\"]\n\tn_gene_IRF1_gene_AhR = binding_parameter_dictionary[\"n_gene_IRF1_gene_AhR\"]\n\tK_gene_IRF1_gene_AhR = binding_parameter_dictionary[\"K_gene_IRF1_gene_AhR\"]\n\tn_gene_IRF1_gene_PPARg = binding_parameter_dictionary[\"n_gene_IRF1_gene_PPARg\"]\n\tK_gene_IRF1_gene_PPARg = binding_parameter_dictionary[\"K_gene_IRF1_gene_PPARg\"]\n\tn_gene_OCT1_gene_PPARg = binding_parameter_dictionary[\"n_gene_OCT1_gene_PPARg\"]\n\tK_gene_OCT1_gene_PPARg = binding_parameter_dictionary[\"K_gene_OCT1_gene_PPARg\"]\n\tn_gene_OCT4_gene_Trigger = binding_parameter_dictionary[\"n_gene_OCT4_gene_Trigger\"]\n\tK_gene_OCT4_gene_Trigger = binding_parameter_dictionary[\"K_gene_OCT4_gene_Trigger\"]\n\tn_gene_OCT4_gene_AhR = binding_parameter_dictionary[\"n_gene_OCT4_gene_AhR\"]\n\tK_gene_OCT4_gene_AhR = binding_parameter_dictionary[\"K_gene_OCT4_gene_AhR\"]\n\tn_gene_OCT4_gene_cRAF = binding_parameter_dictionary[\"n_gene_OCT4_gene_cRAF\"]\n\tK_gene_OCT4_gene_cRAF = binding_parameter_dictionary[\"K_gene_OCT4_gene_cRAF\"]\n\tn_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF = binding_parameter_dictionary[\"n_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"]\n\tK_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF = binding_parameter_dictionary[\"K_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"]\n\tn_gene_P21_gene_GFI1 = binding_parameter_dictionary[\"n_gene_P21_gene_GFI1\"]\n\tK_gene_P21_gene_GFI1 = binding_parameter_dictionary[\"K_gene_P21_gene_GFI1\"]\n\tn_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF = binding_parameter_dictionary[\"n_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"]\n\tK_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF = binding_parameter_dictionary[\"K_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"]\n\tn_gene_P47Phox_gene_PPARg = binding_parameter_dictionary[\"n_gene_P47Phox_gene_PPARg\"]\n\tK_gene_P47Phox_gene_PPARg = binding_parameter_dictionary[\"K_gene_P47Phox_gene_PPARg\"]\n\tn_gene_PPARg_gene_Trigger = binding_parameter_dictionary[\"n_gene_PPARg_gene_Trigger\"]\n\tK_gene_PPARg_gene_Trigger = binding_parameter_dictionary[\"K_gene_PPARg_gene_Trigger\"]\n\tn_gene_PPARg_gene_CEBPa = binding_parameter_dictionary[\"n_gene_PPARg_gene_CEBPa\"]\n\tK_gene_PPARg_gene_CEBPa = binding_parameter_dictionary[\"K_gene_PPARg_gene_CEBPa\"]\n\tn_gene_PPARg_gene_EGR1 = binding_parameter_dictionary[\"n_gene_PPARg_gene_EGR1\"]\n\tK_gene_PPARg_gene_EGR1 = binding_parameter_dictionary[\"K_gene_PPARg_gene_EGR1\"]\n\tn_gene_PPARg_gene_PU1 = binding_parameter_dictionary[\"n_gene_PPARg_gene_PU1\"]\n\tK_gene_PPARg_gene_PU1 = binding_parameter_dictionary[\"K_gene_PPARg_gene_PU1\"]\n\tn_gene_PPARg_gene_AP1 = binding_parameter_dictionary[\"n_gene_PPARg_gene_AP1\"]\n\tK_gene_PPARg_gene_AP1 = binding_parameter_dictionary[\"K_gene_PPARg_gene_AP1\"]\n\tn_gene_PU1_gene_Trigger = binding_parameter_dictionary[\"n_gene_PU1_gene_Trigger\"]\n\tK_gene_PU1_gene_Trigger = binding_parameter_dictionary[\"K_gene_PU1_gene_Trigger\"]\n\tn_gene_PU1_gene_CEBPa = binding_parameter_dictionary[\"n_gene_PU1_gene_CEBPa\"]\n\tK_gene_PU1_gene_CEBPa = binding_parameter_dictionary[\"K_gene_PU1_gene_CEBPa\"]\n\tn_gene_PU1_gene_PU1 = binding_parameter_dictionary[\"n_gene_PU1_gene_PU1\"]\n\tK_gene_PU1_gene_PU1 = binding_parameter_dictionary[\"K_gene_PU1_gene_PU1\"]\n\tn_gene_PU1_gene_AP1 = binding_parameter_dictionary[\"n_gene_PU1_gene_AP1\"]\n\tK_gene_PU1_gene_AP1 = binding_parameter_dictionary[\"K_gene_PU1_gene_AP1\"]\n\tn_gene_PU1_gene_OCT1 = binding_parameter_dictionary[\"n_gene_PU1_gene_OCT1\"]\n\tK_gene_PU1_gene_OCT1 = binding_parameter_dictionary[\"K_gene_PU1_gene_OCT1\"]\n\tn_gene_PU1_gene_AhR = binding_parameter_dictionary[\"n_gene_PU1_gene_AhR\"]\n\tK_gene_PU1_gene_AhR = binding_parameter_dictionary[\"K_gene_PU1_gene_AhR\"]\n\tn_gene_PU1_gene_GFI1 = binding_parameter_dictionary[\"n_gene_PU1_gene_GFI1\"]\n\tK_gene_PU1_gene_GFI1 = binding_parameter_dictionary[\"K_gene_PU1_gene_GFI1\"]\n\n\t# Alias the control function parameters - \n\tcontrol_parameter_dictionary = data_dictionary[\"control_parameter_dictionary\"]\n\tW_gene_AP1_RNAP = control_parameter_dictionary[\"W_gene_AP1_RNAP\"]\n\tW_gene_AP1_gene_AhR = control_parameter_dictionary[\"W_gene_AP1_gene_AhR\"]\n\tW_gene_AP1_gene_PU1 = control_parameter_dictionary[\"W_gene_AP1_gene_PU1\"]\n\tW_gene_AP1_gene_PPARg = control_parameter_dictionary[\"W_gene_AP1_gene_PPARg\"]\n\tW_gene_AhR_RNAP = control_parameter_dictionary[\"W_gene_AhR_RNAP\"]\n\tW_gene_AhR_gene_Trigger = control_parameter_dictionary[\"W_gene_AhR_gene_Trigger\"]\n\tW_gene_CD11b_RNAP = control_parameter_dictionary[\"W_gene_CD11b_RNAP\"]\n\tW_gene_CD11b_gene_PU1_gene_cRAF = control_parameter_dictionary[\"W_gene_CD11b_gene_PU1_gene_cRAF\"]\n\tW_gene_CD14_RNAP = control_parameter_dictionary[\"W_gene_CD14_RNAP\"]\n\tW_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF = control_parameter_dictionary[\"W_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\"]\n\tW_gene_CD38_RNAP = control_parameter_dictionary[\"W_gene_CD38_RNAP\"]\n\tW_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF = control_parameter_dictionary[\"W_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\"]\n\tW_gene_CEBPa_RNAP = control_parameter_dictionary[\"W_gene_CEBPa_RNAP\"]\n\tW_gene_CEBPa_gene_Trigger = control_parameter_dictionary[\"W_gene_CEBPa_gene_Trigger\"]\n\tW_gene_CEBPa_gene_PPARg = control_parameter_dictionary[\"W_gene_CEBPa_gene_PPARg\"]\n\tW_gene_CEBPa_gene_CEBPa = control_parameter_dictionary[\"W_gene_CEBPa_gene_CEBPa\"]\n\tW_gene_CEBPa_gene_GFI1 = control_parameter_dictionary[\"W_gene_CEBPa_gene_GFI1\"]\n\tW_gene_E2F_RNAP = control_parameter_dictionary[\"W_gene_E2F_RNAP\"]\n\tW_gene_E2F_gene_E2F = control_parameter_dictionary[\"W_gene_E2F_gene_E2F\"]\n\tW_gene_E2F_gene_PPARg = control_parameter_dictionary[\"W_gene_E2F_gene_PPARg\"]\n\tW_gene_E2F_gene_CEBPa = control_parameter_dictionary[\"W_gene_E2F_gene_CEBPa\"]\n\tW_gene_E2F_gene_GFI1 = control_parameter_dictionary[\"W_gene_E2F_gene_GFI1\"]\n\tW_gene_E2F_gene_cRAF = control_parameter_dictionary[\"W_gene_E2F_gene_cRAF\"]\n\tW_gene_EGR1_RNAP = control_parameter_dictionary[\"W_gene_EGR1_RNAP\"]\n\tW_gene_EGR1_gene_Trigger = control_parameter_dictionary[\"W_gene_EGR1_gene_Trigger\"]\n\tW_gene_EGR1_gene_PU1 = control_parameter_dictionary[\"W_gene_EGR1_gene_PU1\"]\n\tW_gene_EGR1_gene_PPARg = control_parameter_dictionary[\"W_gene_EGR1_gene_PPARg\"]\n\tW_gene_EGR1_gene_GFI1 = control_parameter_dictionary[\"W_gene_EGR1_gene_GFI1\"]\n\tW_gene_GFI1_RNAP = control_parameter_dictionary[\"W_gene_GFI1_RNAP\"]\n\tW_gene_GFI1_gene_CEBPa = control_parameter_dictionary[\"W_gene_GFI1_gene_CEBPa\"]\n\tW_gene_GFI1_gene_EGR1 = control_parameter_dictionary[\"W_gene_GFI1_gene_EGR1\"]\n\tW_gene_IRF1_RNAP = control_parameter_dictionary[\"W_gene_IRF1_RNAP\"]\n\tW_gene_IRF1_gene_Trigger = control_parameter_dictionary[\"W_gene_IRF1_gene_Trigger\"]\n\tW_gene_IRF1_gene_AhR = control_parameter_dictionary[\"W_gene_IRF1_gene_AhR\"]\n\tW_gene_IRF1_gene_PPARg = control_parameter_dictionary[\"W_gene_IRF1_gene_PPARg\"]\n\tW_gene_OCT1_RNAP = control_parameter_dictionary[\"W_gene_OCT1_RNAP\"]\n\tW_gene_OCT1_gene_PPARg = control_parameter_dictionary[\"W_gene_OCT1_gene_PPARg\"]\n\tW_gene_OCT4_RNAP = control_parameter_dictionary[\"W_gene_OCT4_RNAP\"]\n\tW_gene_OCT4_gene_Trigger = control_parameter_dictionary[\"W_gene_OCT4_gene_Trigger\"]\n\tW_gene_OCT4_gene_AhR = control_parameter_dictionary[\"W_gene_OCT4_gene_AhR\"]\n\tW_gene_OCT4_gene_cRAF = control_parameter_dictionary[\"W_gene_OCT4_gene_cRAF\"]\n\tW_gene_P21_RNAP = control_parameter_dictionary[\"W_gene_P21_RNAP\"]\n\tW_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF = control_parameter_dictionary[\"W_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\"]\n\tW_gene_P21_gene_GFI1 = control_parameter_dictionary[\"W_gene_P21_gene_GFI1\"]\n\tW_gene_P47Phox_RNAP = control_parameter_dictionary[\"W_gene_P47Phox_RNAP\"]\n\tW_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF = control_parameter_dictionary[\"W_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF\"]\n\tW_gene_P47Phox_gene_PPARg = control_parameter_dictionary[\"W_gene_P47Phox_gene_PPARg\"]\n\tW_gene_PPARg_RNAP = control_parameter_dictionary[\"W_gene_PPARg_RNAP\"]\n\tW_gene_PPARg_gene_Trigger = control_parameter_dictionary[\"W_gene_PPARg_gene_Trigger\"]\n\tW_gene_PPARg_gene_CEBPa = control_parameter_dictionary[\"W_gene_PPARg_gene_CEBPa\"]\n\tW_gene_PPARg_gene_EGR1 = control_parameter_dictionary[\"W_gene_PPARg_gene_EGR1\"]\n\tW_gene_PPARg_gene_PU1 = control_parameter_dictionary[\"W_gene_PPARg_gene_PU1\"]\n\tW_gene_PPARg_gene_AP1 = control_parameter_dictionary[\"W_gene_PPARg_gene_AP1\"]\n\tW_gene_PU1_RNAP = control_parameter_dictionary[\"W_gene_PU1_RNAP\"]\n\tW_gene_PU1_gene_Trigger = control_parameter_dictionary[\"W_gene_PU1_gene_Trigger\"]\n\tW_gene_PU1_gene_CEBPa = control_parameter_dictionary[\"W_gene_PU1_gene_CEBPa\"]\n\tW_gene_PU1_gene_PU1 = control_parameter_dictionary[\"W_gene_PU1_gene_PU1\"]\n\tW_gene_PU1_gene_AP1 = control_parameter_dictionary[\"W_gene_PU1_gene_AP1\"]\n\tW_gene_PU1_gene_OCT1 = control_parameter_dictionary[\"W_gene_PU1_gene_OCT1\"]\n\tW_gene_PU1_gene_AhR = control_parameter_dictionary[\"W_gene_PU1_gene_AhR\"]\n\tW_gene_PU1_gene_GFI1 = control_parameter_dictionary[\"W_gene_PU1_gene_GFI1\"]\n\tW_gene_Trigger_RNAP = control_parameter_dictionary[\"W_gene_Trigger_RNAP\"]\n\tW_gene_cRAF_RNAP = control_parameter_dictionary[\"W_gene_cRAF_RNAP\"]\n\n\t# Transfer function target:gene_AP1 actor:gene_AhR\n\tactor_set_gene_AP1_gene_AhR = [\n\t\tprotein_gene_AhR\n\t]\n\tactor = prod(actor_set_gene_AP1_gene_AhR)\n\tb_gene_AP1_gene_AhR = (actor^(n_gene_AP1_gene_AhR))/(K_gene_AP1_gene_AhR^(n_gene_AP1_gene_AhR)+actor^(n_gene_AP1_gene_AhR))\n\n\t# Transfer function target:gene_AP1 actor:gene_PU1\n\tactor_set_gene_AP1_gene_PU1 = [\n\t\tprotein_gene_PU1\n\t]\n\tactor = prod(actor_set_gene_AP1_gene_PU1)\n\tb_gene_AP1_gene_PU1 = (actor^(n_gene_AP1_gene_PU1))/(K_gene_AP1_gene_PU1^(n_gene_AP1_gene_PU1)+actor^(n_gene_AP1_gene_PU1))\n\n\t# Transfer function target:gene_AP1 actor:gene_PPARg\n\tactor_set_gene_AP1_gene_PPARg = [\n\t\tprotein_gene_PPARg\n\t]\n\tactor = prod(actor_set_gene_AP1_gene_PPARg)\n\tb_gene_AP1_gene_PPARg = (actor^(n_gene_AP1_gene_PPARg))/(K_gene_AP1_gene_PPARg^(n_gene_AP1_gene_PPARg)+actor^(n_gene_AP1_gene_PPARg))\n\n\t# Control function for gene_AP1 - \n\tcontrol_array[1] = (W_gene_AP1_RNAP+W_gene_AP1_gene_AhR*b_gene_AP1_gene_AhR+W_gene_AP1_gene_PU1*b_gene_AP1_gene_PU1)/(1+W_gene_AP1_RNAP+W_gene_AP1_gene_AhR*b_gene_AP1_gene_AhR+W_gene_AP1_gene_PU1*b_gene_AP1_gene_PU1+W_gene_AP1_gene_PPARg*b_gene_AP1_gene_PPARg)\n\n\t# Transfer function target:gene_AhR actor:gene_Trigger\n\tactor_set_gene_AhR_gene_Trigger = [\n\t\tprotein_gene_Trigger\n\t]\n\tactor = prod(actor_set_gene_AhR_gene_Trigger)\n\tb_gene_AhR_gene_Trigger = (actor^(n_gene_AhR_gene_Trigger))/(K_gene_AhR_gene_Trigger^(n_gene_AhR_gene_Trigger)+actor^(n_gene_AhR_gene_Trigger))\n\n\t# Control function for gene_AhR - \n\tcontrol_array[2] = (W_gene_AhR_RNAP+W_gene_AhR_gene_Trigger*b_gene_AhR_gene_Trigger)/(1+W_gene_AhR_RNAP+W_gene_AhR_gene_Trigger*b_gene_AhR_gene_Trigger)\n\n\t# Transfer function target:gene_CD11b actor:gene_PU1_gene_cRAF\n\tactor_set_gene_CD11b_gene_PU1_gene_cRAF = [\n\t\tprotein_gene_PU1\n\t\tprotein_gene_cRAF\n\t]\n\tactor = prod(actor_set_gene_CD11b_gene_PU1_gene_cRAF)\n\tb_gene_CD11b_gene_PU1_gene_cRAF = (actor^(n_gene_CD11b_gene_PU1_gene_cRAF))/(K_gene_CD11b_gene_PU1_gene_cRAF^(n_gene_CD11b_gene_PU1_gene_cRAF)+actor^(n_gene_CD11b_gene_PU1_gene_cRAF))\n\n\t# Control function for gene_CD11b - \n\tcontrol_array[3] = (W_gene_CD11b_RNAP+W_gene_CD11b_gene_PU1_gene_cRAF*b_gene_CD11b_gene_PU1_gene_cRAF)/(1+W_gene_CD11b_RNAP+W_gene_CD11b_gene_PU1_gene_cRAF*b_gene_CD11b_gene_PU1_gene_cRAF)\n\n\t# Transfer function target:gene_CD14 actor:gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF\n\tactor_set_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF = [\n\t\tprotein_gene_PPARg\n\t\tprotein_gene_CEBPa\n\t\tprotein_gene_EGR1\n\t\tprotein_gene_cRAF\n\t]\n\tactor = prod(actor_set_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF)\n\tb_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF = (actor^(n_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF))/(K_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF^(n_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF)+actor^(n_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF))\n\n\t# Control function for gene_CD14 - \n\tcontrol_array[4] = (W_gene_CD14_RNAP+W_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF*b_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF)/(1+W_gene_CD14_RNAP+W_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF*b_gene_CD14_gene_PPARg_gene_CEBPa_gene_EGR1_gene_cRAF)\n\n\t# Transfer function target:gene_CD38 actor:gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF\n\tactor_set_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF = [\n\t\tprotein_gene_IRF1\n\t\tprotein_gene_PPARg\n\t\tprotein_gene_Trigger\n\t\tprotein_gene_cRAF\n\t]\n\tactor = prod(actor_set_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF)\n\tb_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF = (actor^(n_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF))/(K_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF^(n_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF)+actor^(n_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF))\n\n\t# Control function for gene_CD38 - \n\tcontrol_array[5] = (W_gene_CD38_RNAP+W_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF*b_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF)/(1+W_gene_CD38_RNAP+W_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF*b_gene_CD38_gene_IRF1_gene_PPARg_gene_Trigger_gene_cRAF)\n\n\t# Transfer function target:gene_CEBPa actor:gene_Trigger\n\tactor_set_gene_CEBPa_gene_Trigger = [\n\t\tprotein_gene_Trigger\n\t]\n\tactor = prod(actor_set_gene_CEBPa_gene_Trigger)\n\tb_gene_CEBPa_gene_Trigger = (actor^(n_gene_CEBPa_gene_Trigger))/(K_gene_CEBPa_gene_Trigger^(n_gene_CEBPa_gene_Trigger)+actor^(n_gene_CEBPa_gene_Trigger))\n\n\t# Transfer function target:gene_CEBPa actor:gene_PPARg\n\tactor_set_gene_CEBPa_gene_PPARg = [\n\t\tprotein_gene_PPARg\n\t]\n\tactor = prod(actor_set_gene_CEBPa_gene_PPARg)\n\tb_gene_CEBPa_gene_PPARg = (actor^(n_gene_CEBPa_gene_PPARg))/(K_gene_CEBPa_gene_PPARg^(n_gene_CEBPa_gene_PPARg)+actor^(n_gene_CEBPa_gene_PPARg))\n\n\t# Transfer function target:gene_CEBPa actor:gene_CEBPa\n\tactor_set_gene_CEBPa_gene_CEBPa = [\n\t\tprotein_gene_CEBPa\n\t]\n\tactor = prod(actor_set_gene_CEBPa_gene_CEBPa)\n\tb_gene_CEBPa_gene_CEBPa = (actor^(n_gene_CEBPa_gene_CEBPa))/(K_gene_CEBPa_gene_CEBPa^(n_gene_CEBPa_gene_CEBPa)+actor^(n_gene_CEBPa_gene_CEBPa))\n\n\t# Transfer function target:gene_CEBPa actor:gene_GFI1\n\tactor_set_gene_CEBPa_gene_GFI1 = [\n\t\tprotein_gene_GFI1\n\t]\n\tactor = prod(actor_set_gene_CEBPa_gene_GFI1)\n\tb_gene_CEBPa_gene_GFI1 = (actor^(n_gene_CEBPa_gene_GFI1))/(K_gene_CEBPa_gene_GFI1^(n_gene_CEBPa_gene_GFI1)+actor^(n_gene_CEBPa_gene_GFI1))\n\n\t# Control function for gene_CEBPa - \n\tcontrol_array[6] = (W_gene_CEBPa_RNAP+W_gene_CEBPa_gene_Trigger*b_gene_CEBPa_gene_Trigger+W_gene_CEBPa_gene_PPARg*b_gene_CEBPa_gene_PPARg+W_gene_CEBPa_gene_CEBPa*b_gene_CEBPa_gene_CEBPa)/(1+W_gene_CEBPa_RNAP+W_gene_CEBPa_gene_Trigger*b_gene_CEBPa_gene_Trigger+W_gene_CEBPa_gene_PPARg*b_gene_CEBPa_gene_PPARg+W_gene_CEBPa_gene_CEBPa*b_gene_CEBPa_gene_CEBPa+W_gene_CEBPa_gene_GFI1*b_gene_CEBPa_gene_GFI1)\n\n\t# Transfer function target:gene_E2F actor:gene_E2F\n\tactor_set_gene_E2F_gene_E2F = [\n\t\tprotein_gene_E2F\n\t]\n\tactor = prod(actor_set_gene_E2F_gene_E2F)\n\tb_gene_E2F_gene_E2F = (actor^(n_gene_E2F_gene_E2F))/(K_gene_E2F_gene_E2F^(n_gene_E2F_gene_E2F)+actor^(n_gene_E2F_gene_E2F))\n\n\t# Transfer function target:gene_E2F actor:gene_PPARg\n\tactor_set_gene_E2F_gene_PPARg = [\n\t\tprotein_gene_PPARg\n\t]\n\tactor = prod(actor_set_gene_E2F_gene_PPARg)\n\tb_gene_E2F_gene_PPARg = (actor^(n_gene_E2F_gene_PPARg))/(K_gene_E2F_gene_PPARg^(n_gene_E2F_gene_PPARg)+actor^(n_gene_E2F_gene_PPARg))\n\n\t# Transfer function target:gene_E2F actor:gene_CEBPa\n\tactor_set_gene_E2F_gene_CEBPa = [\n\t\tprotein_gene_CEBPa\n\t]\n\tactor = prod(actor_set_gene_E2F_gene_CEBPa)\n\tb_gene_E2F_gene_CEBPa = (actor^(n_gene_E2F_gene_CEBPa))/(K_gene_E2F_gene_CEBPa^(n_gene_E2F_gene_CEBPa)+actor^(n_gene_E2F_gene_CEBPa))\n\n\t# Transfer function target:gene_E2F actor:gene_GFI1\n\tactor_set_gene_E2F_gene_GFI1 = [\n\t\tprotein_gene_GFI1\n\t]\n\tactor = prod(actor_set_gene_E2F_gene_GFI1)\n\tb_gene_E2F_gene_GFI1 = (actor^(n_gene_E2F_gene_GFI1))/(K_gene_E2F_gene_GFI1^(n_gene_E2F_gene_GFI1)+actor^(n_gene_E2F_gene_GFI1))\n\n\t# Transfer function target:gene_E2F actor:gene_cRAF\n\tactor_set_gene_E2F_gene_cRAF = [\n\t\tprotein_gene_cRAF\n\t]\n\tactor = prod(actor_set_gene_E2F_gene_cRAF)\n\tb_gene_E2F_gene_cRAF = (actor^(n_gene_E2F_gene_cRAF))/(K_gene_E2F_gene_cRAF^(n_gene_E2F_gene_cRAF)+actor^(n_gene_E2F_gene_cRAF))\n\n\t# Control function for gene_E2F - \n\tcontrol_array[7] = (W_gene_E2F_RNAP+W_gene_E2F_gene_E2F*b_gene_E2F_gene_E2F)/(1+W_gene_E2F_RNAP+W_gene_E2F_gene_E2F*b_gene_E2F_gene_E2F+W_gene_E2F_gene_PPARg*b_gene_E2F_gene_PPARg+W_gene_E2F_gene_CEBPa*b_gene_E2F_gene_CEBPa+W_gene_E2F_gene_GFI1*b_gene_E2F_gene_GFI1+W_gene_E2F_gene_cRAF*b_gene_E2F_gene_cRAF)\n\n\t# Transfer function target:gene_EGR1 actor:gene_Trigger\n\tactor_set_gene_EGR1_gene_Trigger = [\n\t\tprotein_gene_Trigger\n\t]\n\tactor = prod(actor_set_gene_EGR1_gene_Trigger)\n\tb_gene_EGR1_gene_Trigger = (actor^(n_gene_EGR1_gene_Trigger))/(K_gene_EGR1_gene_Trigger^(n_gene_EGR1_gene_Trigger)+actor^(n_gene_EGR1_gene_Trigger))\n\n\t# Transfer function target:gene_EGR1 actor:gene_PU1\n\tactor_set_gene_EGR1_gene_PU1 = [\n\t\tprotein_gene_PU1\n\t]\n\tactor = prod(actor_set_gene_EGR1_gene_PU1)\n\tb_gene_EGR1_gene_PU1 = (actor^(n_gene_EGR1_gene_PU1))/(K_gene_EGR1_gene_PU1^(n_gene_EGR1_gene_PU1)+actor^(n_gene_EGR1_gene_PU1))\n\n\t# Transfer function target:gene_EGR1 actor:gene_PPARg\n\tactor_set_gene_EGR1_gene_PPARg = [\n\t\tprotein_gene_PPARg\n\t]\n\tactor = prod(actor_set_gene_EGR1_gene_PPARg)\n\tb_gene_EGR1_gene_PPARg = (actor^(n_gene_EGR1_gene_PPARg))/(K_gene_EGR1_gene_PPARg^(n_gene_EGR1_gene_PPARg)+actor^(n_gene_EGR1_gene_PPARg))\n\n\t# Transfer function target:gene_EGR1 actor:gene_GFI1\n\tactor_set_gene_EGR1_gene_GFI1 = [\n\t\tprotein_gene_GFI1\n\t]\n\tactor = prod(actor_set_gene_EGR1_gene_GFI1)\n\tb_gene_EGR1_gene_GFI1 = (actor^(n_gene_EGR1_gene_GFI1))/(K_gene_EGR1_gene_GFI1^(n_gene_EGR1_gene_GFI1)+actor^(n_gene_EGR1_gene_GFI1))\n\n\t# Control function for gene_EGR1 - \n\tcontrol_array[8] = (W_gene_EGR1_RNAP+W_gene_EGR1_gene_Trigger*b_gene_EGR1_gene_Trigger+W_gene_EGR1_gene_PU1*b_gene_EGR1_gene_PU1)/(1+W_gene_EGR1_RNAP+W_gene_EGR1_gene_Trigger*b_gene_EGR1_gene_Trigger+W_gene_EGR1_gene_PU1*b_gene_EGR1_gene_PU1+W_gene_EGR1_gene_PPARg*b_gene_EGR1_gene_PPARg+W_gene_EGR1_gene_GFI1*b_gene_EGR1_gene_GFI1)\n\n\t# Transfer function target:gene_GFI1 actor:gene_CEBPa\n\tactor_set_gene_GFI1_gene_CEBPa = [\n\t\tprotein_gene_CEBPa\n\t]\n\tactor = prod(actor_set_gene_GFI1_gene_CEBPa)\n\tb_gene_GFI1_gene_CEBPa = (actor^(n_gene_GFI1_gene_CEBPa))/(K_gene_GFI1_gene_CEBPa^(n_gene_GFI1_gene_CEBPa)+actor^(n_gene_GFI1_gene_CEBPa))\n\n\t# Transfer function target:gene_GFI1 actor:gene_EGR1\n\tactor_set_gene_GFI1_gene_EGR1 = [\n\t\tprotein_gene_EGR1\n\t]\n\tactor = prod(actor_set_gene_GFI1_gene_EGR1)\n\tb_gene_GFI1_gene_EGR1 = (actor^(n_gene_GFI1_gene_EGR1))/(K_gene_GFI1_gene_EGR1^(n_gene_GFI1_gene_EGR1)+actor^(n_gene_GFI1_gene_EGR1))\n\n\t# Control function for gene_GFI1 - \n\tcontrol_array[9] = (W_gene_GFI1_RNAP+W_gene_GFI1_gene_CEBPa*b_gene_GFI1_gene_CEBPa)/(1+W_gene_GFI1_RNAP+W_gene_GFI1_gene_CEBPa*b_gene_GFI1_gene_CEBPa+W_gene_GFI1_gene_EGR1*b_gene_GFI1_gene_EGR1)\n\n\t# Transfer function target:gene_IRF1 actor:gene_Trigger\n\tactor_set_gene_IRF1_gene_Trigger = [\n\t\tprotein_gene_Trigger\n\t]\n\tactor = prod(actor_set_gene_IRF1_gene_Trigger)\n\tb_gene_IRF1_gene_Trigger = (actor^(n_gene_IRF1_gene_Trigger))/(K_gene_IRF1_gene_Trigger^(n_gene_IRF1_gene_Trigger)+actor^(n_gene_IRF1_gene_Trigger))\n\n\t# Transfer function target:gene_IRF1 actor:gene_AhR\n\tactor_set_gene_IRF1_gene_AhR = [\n\t\tprotein_gene_AhR\n\t]\n\tactor = prod(actor_set_gene_IRF1_gene_AhR)\n\tb_gene_IRF1_gene_AhR = (actor^(n_gene_IRF1_gene_AhR))/(K_gene_IRF1_gene_AhR^(n_gene_IRF1_gene_AhR)+actor^(n_gene_IRF1_gene_AhR))\n\n\t# Transfer function target:gene_IRF1 actor:gene_PPARg\n\tactor_set_gene_IRF1_gene_PPARg = [\n\t\tprotein_gene_PPARg\n\t]\n\tactor = prod(actor_set_gene_IRF1_gene_PPARg)\n\tb_gene_IRF1_gene_PPARg = (actor^(n_gene_IRF1_gene_PPARg))/(K_gene_IRF1_gene_PPARg^(n_gene_IRF1_gene_PPARg)+actor^(n_gene_IRF1_gene_PPARg))\n\n\t# Control function for gene_IRF1 - \n\tcontrol_array[10] = (W_gene_IRF1_RNAP+W_gene_IRF1_gene_Trigger*b_gene_IRF1_gene_Trigger+W_gene_IRF1_gene_AhR*b_gene_IRF1_gene_AhR+W_gene_IRF1_gene_PPARg*b_gene_IRF1_gene_PPARg)/(1+W_gene_IRF1_RNAP+W_gene_IRF1_gene_Trigger*b_gene_IRF1_gene_Trigger+W_gene_IRF1_gene_AhR*b_gene_IRF1_gene_AhR+W_gene_IRF1_gene_PPARg*b_gene_IRF1_gene_PPARg)\n\n\t# Transfer function target:gene_OCT1 actor:gene_PPARg\n\tactor_set_gene_OCT1_gene_PPARg = [\n\t\tprotein_gene_PPARg\n\t]\n\tactor = prod(actor_set_gene_OCT1_gene_PPARg)\n\tb_gene_OCT1_gene_PPARg = (actor^(n_gene_OCT1_gene_PPARg))/(K_gene_OCT1_gene_PPARg^(n_gene_OCT1_gene_PPARg)+actor^(n_gene_OCT1_gene_PPARg))\n\n\t# Control function for gene_OCT1 - \n\tcontrol_array[11] = (W_gene_OCT1_RNAP+W_gene_OCT1_gene_PPARg*b_gene_OCT1_gene_PPARg)/(1+W_gene_OCT1_RNAP+W_gene_OCT1_gene_PPARg*b_gene_OCT1_gene_PPARg)\n\n\t# Transfer function target:gene_OCT4 actor:gene_Trigger\n\tactor_set_gene_OCT4_gene_Trigger = [\n\t\tprotein_gene_Trigger\n\t]\n\tactor = prod(actor_set_gene_OCT4_gene_Trigger)\n\tb_gene_OCT4_gene_Trigger = (actor^(n_gene_OCT4_gene_Trigger))/(K_gene_OCT4_gene_Trigger^(n_gene_OCT4_gene_Trigger)+actor^(n_gene_OCT4_gene_Trigger))\n\n\t# Transfer function target:gene_OCT4 actor:gene_AhR\n\tactor_set_gene_OCT4_gene_AhR = [\n\t\tprotein_gene_AhR\n\t]\n\tactor = prod(actor_set_gene_OCT4_gene_AhR)\n\tb_gene_OCT4_gene_AhR = (actor^(n_gene_OCT4_gene_AhR))/(K_gene_OCT4_gene_AhR^(n_gene_OCT4_gene_AhR)+actor^(n_gene_OCT4_gene_AhR))\n\n\t# Transfer function target:gene_OCT4 actor:gene_cRAF\n\tactor_set_gene_OCT4_gene_cRAF = [\n\t\tprotein_gene_cRAF\n\t]\n\tactor = prod(actor_set_gene_OCT4_gene_cRAF)\n\tb_gene_OCT4_gene_cRAF = (actor^(n_gene_OCT4_gene_cRAF))/(K_gene_OCT4_gene_cRAF^(n_gene_OCT4_gene_cRAF)+actor^(n_gene_OCT4_gene_cRAF))\n\n\t# Control function for gene_OCT4 - \n\tcontrol_array[12] = (W_gene_OCT4_RNAP)/(1+W_gene_OCT4_RNAP+W_gene_OCT4_gene_Trigger*b_gene_OCT4_gene_Trigger+W_gene_OCT4_gene_AhR*b_gene_OCT4_gene_AhR+W_gene_OCT4_gene_cRAF*b_gene_OCT4_gene_cRAF)\n\n\t# Transfer function target:gene_P21 actor:gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF\n\tactor_set_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF = [\n\t\tprotein_gene_Trigger\n\t\tprotein_gene_AP1\n\t\tprotein_gene_PPARg\n\t\tprotein_gene_PU1\n\t\tprotein_gene_IRF1\n\t\tprotein_gene_CEBPa\n\t\tprotein_gene_cRAF\n\t]\n\tactor = prod(actor_set_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF)\n\tb_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF = (actor^(n_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF))/(K_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF^(n_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF)+actor^(n_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF))\n\n\t# Transfer function target:gene_P21 actor:gene_GFI1\n\tactor_set_gene_P21_gene_GFI1 = [\n\t\tprotein_gene_GFI1\n\t]\n\tactor = prod(actor_set_gene_P21_gene_GFI1)\n\tb_gene_P21_gene_GFI1 = (actor^(n_gene_P21_gene_GFI1))/(K_gene_P21_gene_GFI1^(n_gene_P21_gene_GFI1)+actor^(n_gene_P21_gene_GFI1))\n\n\t# Control function for gene_P21 - \n\tcontrol_array[13] = (W_gene_P21_RNAP+W_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF*b_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF)/(1+W_gene_P21_RNAP+W_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF*b_gene_P21_gene_Trigger_gene_AP1_gene_PPARg_gene_PU1_gene_IRF1_gene_CEBPa_gene_cRAF+W_gene_P21_gene_GFI1*b_gene_P21_gene_GFI1)\n\n\t# Transfer function target:gene_P47Phox actor:gene_PU1_gene_CEBPa_gene_cRAF\n\tactor_set_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF = [\n\t\tprotein_gene_PU1\n\t\tprotein_gene_CEBPa\n\t\tprotein_gene_cRAF\n\t]\n\tactor = prod(actor_set_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF)\n\tb_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF = (actor^(n_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF))/(K_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF^(n_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF)+actor^(n_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF))\n\n\t# Transfer function target:gene_P47Phox actor:gene_PPARg\n\tactor_set_gene_P47Phox_gene_PPARg = [\n\t\tprotein_gene_PPARg\n\t]\n\tactor = prod(actor_set_gene_P47Phox_gene_PPARg)\n\tb_gene_P47Phox_gene_PPARg = (actor^(n_gene_P47Phox_gene_PPARg))/(K_gene_P47Phox_gene_PPARg^(n_gene_P47Phox_gene_PPARg)+actor^(n_gene_P47Phox_gene_PPARg))\n\n\t# Control function for gene_P47Phox - \n\tcontrol_array[14] = (W_gene_P47Phox_RNAP+W_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF*b_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF)/(1+W_gene_P47Phox_RNAP+W_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF*b_gene_P47Phox_gene_PU1_gene_CEBPa_gene_cRAF+W_gene_P47Phox_gene_PPARg*b_gene_P47Phox_gene_PPARg)\n\n\t# Transfer function target:gene_PPARg actor:gene_Trigger\n\tactor_set_gene_PPARg_gene_Trigger = [\n\t\tprotein_gene_Trigger\n\t]\n\tactor = prod(actor_set_gene_PPARg_gene_Trigger)\n\tb_gene_PPARg_gene_Trigger = (actor^(n_gene_PPARg_gene_Trigger))/(K_gene_PPARg_gene_Trigger^(n_gene_PPARg_gene_Trigger)+actor^(n_gene_PPARg_gene_Trigger))\n\n\t# Transfer function target:gene_PPARg actor:gene_CEBPa\n\tactor_set_gene_PPARg_gene_CEBPa = [\n\t\tprotein_gene_CEBPa\n\t]\n\tactor = prod(actor_set_gene_PPARg_gene_CEBPa)\n\tb_gene_PPARg_gene_CEBPa = (actor^(n_gene_PPARg_gene_CEBPa))/(K_gene_PPARg_gene_CEBPa^(n_gene_PPARg_gene_CEBPa)+actor^(n_gene_PPARg_gene_CEBPa))\n\n\t# Transfer function target:gene_PPARg actor:gene_EGR1\n\tactor_set_gene_PPARg_gene_EGR1 = [\n\t\tprotein_gene_EGR1\n\t]\n\tactor = prod(actor_set_gene_PPARg_gene_EGR1)\n\tb_gene_PPARg_gene_EGR1 = (actor^(n_gene_PPARg_gene_EGR1))/(K_gene_PPARg_gene_EGR1^(n_gene_PPARg_gene_EGR1)+actor^(n_gene_PPARg_gene_EGR1))\n\n\t# Transfer function target:gene_PPARg actor:gene_PU1\n\tactor_set_gene_PPARg_gene_PU1 = [\n\t\tprotein_gene_PU1\n\t]\n\tactor = prod(actor_set_gene_PPARg_gene_PU1)\n\tb_gene_PPARg_gene_PU1 = (actor^(n_gene_PPARg_gene_PU1))/(K_gene_PPARg_gene_PU1^(n_gene_PPARg_gene_PU1)+actor^(n_gene_PPARg_gene_PU1))\n\n\t# Transfer function target:gene_PPARg actor:gene_AP1\n\tactor_set_gene_PPARg_gene_AP1 = [\n\t\tprotein_gene_AP1\n\t]\n\tactor = prod(actor_set_gene_PPARg_gene_AP1)\n\tb_gene_PPARg_gene_AP1 = (actor^(n_gene_PPARg_gene_AP1))/(K_gene_PPARg_gene_AP1^(n_gene_PPARg_gene_AP1)+actor^(n_gene_PPARg_gene_AP1))\n\n\t# Control function for gene_PPARg - \n\tcontrol_array[15] = (W_gene_PPARg_RNAP+W_gene_PPARg_gene_Trigger*b_gene_PPARg_gene_Trigger+W_gene_PPARg_gene_CEBPa*b_gene_PPARg_gene_CEBPa+W_gene_PPARg_gene_EGR1*b_gene_PPARg_gene_EGR1)/(1+W_gene_PPARg_RNAP+W_gene_PPARg_gene_Trigger*b_gene_PPARg_gene_Trigger+W_gene_PPARg_gene_CEBPa*b_gene_PPARg_gene_CEBPa+W_gene_PPARg_gene_EGR1*b_gene_PPARg_gene_EGR1+W_gene_PPARg_gene_PU1*b_gene_PPARg_gene_PU1+W_gene_PPARg_gene_AP1*b_gene_PPARg_gene_AP1)\n\n\t# Transfer function target:gene_PU1 actor:gene_Trigger\n\tactor_set_gene_PU1_gene_Trigger = [\n\t\tprotein_gene_Trigger\n\t]\n\tactor = prod(actor_set_gene_PU1_gene_Trigger)\n\tb_gene_PU1_gene_Trigger = (actor^(n_gene_PU1_gene_Trigger))/(K_gene_PU1_gene_Trigger^(n_gene_PU1_gene_Trigger)+actor^(n_gene_PU1_gene_Trigger))\n\n\t# Transfer function target:gene_PU1 actor:gene_CEBPa\n\tactor_set_gene_PU1_gene_CEBPa = [\n\t\tprotein_gene_CEBPa\n\t]\n\tactor = prod(actor_set_gene_PU1_gene_CEBPa)\n\tb_gene_PU1_gene_CEBPa = (actor^(n_gene_PU1_gene_CEBPa))/(K_gene_PU1_gene_CEBPa^(n_gene_PU1_gene_CEBPa)+actor^(n_gene_PU1_gene_CEBPa))\n\n\t# Transfer function target:gene_PU1 actor:gene_PU1\n\tactor_set_gene_PU1_gene_PU1 = [\n\t\tprotein_gene_PU1\n\t]\n\tactor = prod(actor_set_gene_PU1_gene_PU1)\n\tb_gene_PU1_gene_PU1 = (actor^(n_gene_PU1_gene_PU1))/(K_gene_PU1_gene_PU1^(n_gene_PU1_gene_PU1)+actor^(n_gene_PU1_gene_PU1))\n\n\t# Transfer function target:gene_PU1 actor:gene_AP1\n\tactor_set_gene_PU1_gene_AP1 = [\n\t\tprotein_gene_AP1\n\t]\n\tactor = prod(actor_set_gene_PU1_gene_AP1)\n\tb_gene_PU1_gene_AP1 = (actor^(n_gene_PU1_gene_AP1))/(K_gene_PU1_gene_AP1^(n_gene_PU1_gene_AP1)+actor^(n_gene_PU1_gene_AP1))\n\n\t# Transfer function target:gene_PU1 actor:gene_OCT1\n\tactor_set_gene_PU1_gene_OCT1 = [\n\t\tprotein_gene_OCT1\n\t]\n\tactor = prod(actor_set_gene_PU1_gene_OCT1)\n\tb_gene_PU1_gene_OCT1 = (actor^(n_gene_PU1_gene_OCT1))/(K_gene_PU1_gene_OCT1^(n_gene_PU1_gene_OCT1)+actor^(n_gene_PU1_gene_OCT1))\n\n\t# Transfer function target:gene_PU1 actor:gene_AhR\n\tactor_set_gene_PU1_gene_AhR = [\n\t\tprotein_gene_AhR\n\t]\n\tactor = prod(actor_set_gene_PU1_gene_AhR)\n\tb_gene_PU1_gene_AhR = (actor^(n_gene_PU1_gene_AhR))/(K_gene_PU1_gene_AhR^(n_gene_PU1_gene_AhR)+actor^(n_gene_PU1_gene_AhR))\n\n\t# Transfer function target:gene_PU1 actor:gene_GFI1\n\tactor_set_gene_PU1_gene_GFI1 = [\n\t\tprotein_gene_GFI1\n\t]\n\tactor = prod(actor_set_gene_PU1_gene_GFI1)\n\tb_gene_PU1_gene_GFI1 = (actor^(n_gene_PU1_gene_GFI1))/(K_gene_PU1_gene_GFI1^(n_gene_PU1_gene_GFI1)+actor^(n_gene_PU1_gene_GFI1))\n\n\t# Control function for gene_PU1 - \n\tcontrol_array[16] = (W_gene_PU1_RNAP+W_gene_PU1_gene_Trigger*b_gene_PU1_gene_Trigger+W_gene_PU1_gene_CEBPa*b_gene_PU1_gene_CEBPa+W_gene_PU1_gene_PU1*b_gene_PU1_gene_PU1+W_gene_PU1_gene_AP1*b_gene_PU1_gene_AP1+W_gene_PU1_gene_OCT1*b_gene_PU1_gene_OCT1)/(1+W_gene_PU1_RNAP+W_gene_PU1_gene_Trigger*b_gene_PU1_gene_Trigger+W_gene_PU1_gene_CEBPa*b_gene_PU1_gene_CEBPa+W_gene_PU1_gene_PU1*b_gene_PU1_gene_PU1+W_gene_PU1_gene_AP1*b_gene_PU1_gene_AP1+W_gene_PU1_gene_OCT1*b_gene_PU1_gene_OCT1+W_gene_PU1_gene_AhR*b_gene_PU1_gene_AhR+W_gene_PU1_gene_GFI1*b_gene_PU1_gene_GFI1)\n\n\t# Control function for gene_Trigger - \n\tcontrol_array[17] = (W_gene_Trigger_RNAP)/(1+W_gene_Trigger_RNAP)\n\n\t# Control function for gene_cRAF - \n\tcontrol_array[18] = (W_gene_cRAF_RNAP)/(1+W_gene_cRAF_RNAP)\n\n\t# return - \n\treturn control_array\nend\n", "meta": {"hexsha": "e4cf27034fcf366714ae2ad46965e442521db0bc", "size": 37316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Control.jl", "max_stars_repo_name": "varnerlab/HL60_TF_model_JuPOETs", "max_stars_repo_head_hexsha": "631944aa4cb1a4a5bb98913989c553975e9d5407", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Control.jl", "max_issues_repo_name": "varnerlab/HL60_TF_model_JuPOETs", "max_issues_repo_head_hexsha": "631944aa4cb1a4a5bb98913989c553975e9d5407", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Control.jl", "max_forks_repo_name": "varnerlab/HL60_TF_model_JuPOETs", "max_forks_repo_head_hexsha": "631944aa4cb1a4a5bb98913989c553975e9d5407", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.8542635659, "max_line_length": 568, "alphanum_fraction": 0.8551291671, "num_tokens": 12389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19395960471703505}} {"text": "# MIT License\n#\n# Copyright (c) 2018 Martin Biel\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n StochasticProgram\n\nAn instance of a stochastic optimization problem.\n\"\"\"\nstruct StochasticProgram{N, S <: NTuple{N, Stage}, ST <: AbstractStochasticStructure{N}}\n stages::S\n decisions::Decisions{N}\n structure::ST\n generator::Dict{Symbol, Function}\n problemcache::Dict{Symbol, JuMP.Model}\n solutioncache::Dict{Symbol, SolutionCache}\n optimizer::StochasticProgramOptimizer\n\n function StochasticProgram(stages::NTuple{N, Stage},\n scenario_types::ScenarioTypes{M},\n instantiation::StochasticInstantiation,\n optimizer_constructor) where {N, M}\n N >= 2 || error(\"Stochastic program needs at least two stages.\")\n M == N - 1 || error(\"Inconsistent number of stages $N and number of scenario types $M\")\n S = typeof(stages)\n decisions = Decisions(Val(N))\n optimizer = StochasticProgramOptimizer(optimizer_constructor)\n structure = StochasticStructure(decisions, scenario_types, default_structure(instantiation, optimizer.optimizer))\n ST = typeof(structure)\n return new{N, S, ST}(stages,\n decisions,\n structure,\n Dict{Symbol, Function}(),\n Dict{Symbol, JuMP.Model}(),\n Dict{Symbol, SolutionCache}(),\n optimizer)\n end\n\n function StochasticProgram(stages::NTuple{N, Stage},\n scenarios::NTuple{M, Vector{<:AbstractScenario}},\n instantiation::StochasticInstantiation,\n optimizer_constructor) where {N, M}\n N >= 2 || error(\"Stochastic program needs at least two stages.\")\n M == N - 1 || error(\"Inconsistent number of stages $N and number of scenario types $M\")\n S = typeof(stages)\n decisions = Decisions(Val(N))\n optimizer = StochasticProgramOptimizer(optimizer_constructor)\n structure = StochasticStructure(decisions, scenarios, default_structure(instantiation, optimizer.optimizer))\n ST = typeof(structure)\n return new{N, S, ST}(stages,\n decisions,\n structure,\n Dict{Symbol, Function}(),\n Dict{Symbol, JuMP.Model}(),\n Dict{Symbol, SolutionCache}(),\n optimizer)\n end\nend\nTwoStageStochasticProgram{S <: Tuple{Stage, Stage}, ST <: AbstractStochasticStructure{2}} = StochasticProgram{2, S, ST}\n\n# Constructors #\n# ========================== #\n# Two-stage\n# ========================== #\n\"\"\"\n StochasticProgram(first_stage_params::Any,\n second_stage_params::Any,\n instantiation::StochasticInstantiation,\n optimizer_constructor=nothing) where T <: AbstractFloat\n\nCreate a new two-stage stochastic program with stage data given by `first_stage_params` and `second_stage_params`. After construction, scenarios of type `Scenario` can be added through `add_scenario!`. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.\n\"\"\"\nfunction StochasticProgram(first_stage_params::Any,\n second_stage_params::Any,\n instantiation::StochasticInstantiation,\n optimizer_constructor = nothing)\n stages = (Stage(first_stage_params), Stage(second_stage_params))\n return StochasticProgram(stages, (Scenario,), instantiation, optimizer_constructor)\nend\n\"\"\"\n StochasticProgram(first_stage_params::Any,\n second_stage_params::Any,\n ::Type{Scenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor=nothing) where Scenario <: AbstractScenario\n\nCreate a new two-stage stochastic program with stage data given by `first_stage_params` and `second_stage_params`. After construction, scenarios of type `S` can be added through `add_scenario!`. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.\n\"\"\"\nfunction StochasticProgram(first_stage_params::Any,\n second_stage_params::Any,\n ::Type{Scenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor = nothing) where Scenario <: AbstractScenario\n stages = (Stage(first_stage_params), Stage(second_stage_params))\n return StochasticProgram(stages, (Scenario,), instantiation, optimizer_constructor)\nend\n\"\"\"\n StochasticProgram(::Type{Scenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor=nothing) where Scenario <: AbstractScenario\n\nCreate a new two-stage stochastic program with scenarios of type `Scenario` and no stage data. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program.\n\"\"\"\nfunction StochasticProgram(::Type{Scenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor = nothing) where Scenario <: AbstractScenario\n stages = (Stage(nothing), Stage(nothing))\n return StochasticProgram(stages, (Scenario,), instantiation, optimizer_constructor; procs = procs)\nend\n\"\"\"\n StochasticProgram(first_stage_params::Any,\n second_stage_params::Any,\n scenarios::Vector{<:AbstractScenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor = nothing)\n\nCreate a new two-stage stochastic program with a given collection of `scenarios`. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.\n\"\"\"\nfunction StochasticProgram(first_stage_params::Any,\n second_stage_params::Any,\n scenarios::Vector{<:AbstractScenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor = nothing)\n stages = (Stage(first_stage_params), Stage(second_stage_params))\n return StochasticProgram(stages, (scenarios,), instantiation, optimizer_constructor)\nend\n\"\"\"\n StochasticProgram(scenarios::Vector{<:AbstractScenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor = nothing)\n\nCreate a new two-stage stochastic program with a given collection of `scenarios` and no stage data. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.\n\"\"\"\nfunction StochasticProgram(scenarios::Vector{<:AbstractScenario},\n instantiation::StochasticInstantiation,\n optimizer_constructor = nothing)\n stages = (Stage(nothing), Stage(nothing))\n return StochasticProgram(stages, (scenarios,), instantiation, optimizer_constructor)\nend\n\nfunction Base.copy(src::StochasticProgram{N}; instantiation = UnspecifiedInstantiation(), optimizer = nothing) where N\n stages = ntuple(Val(N)) do i\n Stage(stage_parameters(src, i))\n end\n scenario_types = ntuple(Val(N-1)) do i\n scenario_type(src, i+1)\n end\n dest = StochasticProgram(stages, scenario_types, instantiation, optimizer)\n merge!(dest.generator, src.generator)\n return dest\nend\n\n# Printing #\n# ========================== #\nfunction Base.show(io::IO, stochasticprogram::StochasticProgram{N}) where N\n plural(n) = (n == 1 ? \"\" : \"s\")\n stage(sp, s) = begin\n stage_key = Symbol(:stage_,s)\n ndecisions = num_decisions(sp, s)\n nscenarios = num_scenarios(sp, s)\n if s == 1\n if N == 2\n return \" * $(ndecisions) decision variable$(plural(ndecisions))\"\n else\n return \" * Stage $s:\\n * $(ndecisions) decision variable$(plural(ndecisions))\"\n end\n elseif s == 2 && N == 2\n stype = typename(scenario_type(stochasticprogram))\n return \" * $(ndecisions) recourse variables\\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype\"\n else\n stype = typename(scenario_type(stochasticprogram, s))\n if distributed(stochasticprogram, s)\n if s == N\n return \" * Distributed stage $s:\\n * $(ndecisions) recourse variables\\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype\"\n else\n return \" * Distributed stage $s:\\n * $(ndecisions) decision variable$(plural(ndecisions))\\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype\"\n end\n else\n if s == N\n return \" * Stage $s:\\n * $(ndecisions) recourse variables\\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype\"\n else\n return \" * Stage $s:\\n * $(ndecisions) decision variable$(plural(ndecisions))\\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype\"\n end\n end\n end\n end\n if deferred(stochasticprogram)\n n = num_scenarios(stochasticprogram)\n if n == 0\n return print(io, \"Deferred stochastic program\")\n else\n return print(io, \"Deferred stochastic program with $n scenario$(plural(n))\")\n end\n end\n if N == 2 && distributed(stochasticprogram)\n println(io, \"Distributed stochastic program with:\")\n else\n println(io, \"Stochastic program with:\")\n end\n print(io, stage(stochasticprogram, 1))\n for s = 2:N\n println(io,\"\")\n print(io, stage(stochasticprogram, s))\n end\n println(io,\"\")\n print(io, \"Structure: \")\n print(io, structure_name(stochasticprogram))\n println(io,\"\")\n print(io, \"Solver name: \")\n print(io, optimizer_name(stochasticprogram))\nend\nfunction Base.print(io::IO, stochasticprogram::StochasticProgram)\n if !deferred(stochasticprogram)\n # Delegate printing according to stochastic structure\n print(io, structure(stochasticprogram))\n print(io, \"Solver name: \")\n print(io, optimizer_name(stochasticprogram))\n else\n # Just give summary if the stochastic program has not been initialized yet\n show(io, stochasticprogram)\n end\nend\n# ========================== #\n\n# MOI #\n# ========================== #\nfunction MOI.get(stochasticprogram::StochasticProgram, attr::Union{MOI.TerminationStatus, MOI.PrimalStatus, MOI.DualStatus})\n # Check if there is a cached solution\n cache = solutioncache(stochasticprogram)\n if haskey(cache, :solution)\n # Returned cached solution if possible\n try\n return MOI.get(cache[:solution], attr)\n catch\n end\n end\n if haskey(cache, :node_solution_1)\n # Value was possibly only cached in first-stage solution\n try\n return MOI.get(cache[:node_solution_1], attr)\n catch\n end\n end\n return MOI.get(optimizer(stochasticprogram), attr)\nend\nfunction MOI.get(stochasticprogram::StochasticProgram, attr::MOI.AbstractModelAttribute)\n if MOI.is_set_by_optimize(attr)\n # Check if there is a cached solution\n cache = solutioncache(stochasticprogram)\n if haskey(cache, :solution)\n # Returned cached solution if possible\n try\n return MOI.get(cache[:solution], attr)\n catch\n end\n end\n if haskey(cache, :node_solution_1)\n # Value was possibly only cached in first-stage solution\n try\n return MOI.get(cache[:node_solution_1], attr)\n catch\n end\n end\n check_provided_optimizer(stochasticprogram.optimizer)\n if MOI.get(stochasticprogram, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED\n throw(OptimizeNotCalled())\n end\n return MOI.get(optimizer(stochasticprogram), attr)\n else\n if is_structure_independent(attr)\n # Get attribute from first stage of proxy if structure independent\n return MOI.get(proxy(stochasticprogram, 1), attr)\n else\n # Handle in structure otherwise\n return MOI.get(structure(stochasticprogram), attr)\n end\n end\nend\nfunction MOI.get(stochasticprogram::StochasticProgram, attr::ScenarioDependentModelAttribute)\n if MOI.is_set_by_optimize(attr)\n # Check if there is a cached solution\n cache = solutioncache(stochasticprogram)\n key = Symbol(:node_solution_, attr.stage, :_, attr.scenario_index)\n if haskey(cache, key)\n try\n return MOI.get(cache[key], attr.attr)\n catch\n end\n end\n check_provided_optimizer(stochasticprogram.optimizer)\n # Return statuses without checks\n if typeof(attr.attr) <: Union{MOI.TerminationStatus, MOI.PrimalStatus, MOI.DualStatus}\n try\n # Try to get scenario-dependent value directly\n return MOI.get(optimizer(stochasticprogram), attr)\n catch\n # Fallback to resolving scenario-dependence in structure if\n # not supported natively by optimizer\n return MOI.get(structure(stochasticprogram), attr)\n end\n end\n if MOI.get(stochasticprogram, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED\n throw(OptimizeNotCalled())\n end\n try\n # Try to get scenario-dependent value directly\n return MOI.get(optimizer(stochasticprogram), attr)\n catch\n # Fallback to resolving scenario-dependence in structure if\n # not supported natively by optimizer\n MOI.get(structure(stochasticprogram), attr)\n end\n else\n if is_structure_independent(attr)\n # Get attribute from first stage of proxy if structure independent\n return MOI.get(proxy(stochasticprogram, 1), attr)\n else\n # Handle in structure otherwise\n return MOI.get(structure(stochasticprogram), attr)\n end\n end\nend\nfunction MOI.get(stochasticprogram::StochasticProgram, attr::MOI.AbstractOptimizerAttribute)\n MOI.get(optimizer(stochasticprogram), attr)\nend\n\nfunction MOI.set(sp::StochasticProgram, attr::MOI.AbstractOptimizerAttribute, value)\n MOI.set(optimizer(sp), attr, value)\n return nothing\nend\nfunction MOI.set(sp::StochasticProgram, attr::MOI.AbstractModelAttribute, value)\n if is_structure_independent(attr)\n MOI.set(proxy(sp, attr.stage), attr, value)\n end\n MOI.set(structure(sp), attr, value)\n return nothing\nend\nfunction MOI.set(sp::StochasticProgram, attr::ScenarioDependentModelAttribute, value)\n if is_structure_independent(attr)\n MOI.set(proxy(sp, attr.stage), attr, value)\n end\n MOI.set(structure(sp), attr, value)\n return nothing\nend\n\nfunction MOI.set(sp::StochasticProgram, attr::MOI.Silent, flag)\n # Ensure that Silent is always passed\n MOI.set(structure(sp), attr, flag)\n # Pass to optimizer anyway\n MOI.set(optimizer(sp), attr, flag)\n return nothing\nend\n\nfunction JuMP.check_belongs_to_model(con_ref::ConstraintRef{<:StochasticProgram}, stochasticprogram::StochasticProgram)\n if owner_model(con_ref) !== model\n throw(ConstraintNotOwned(con_ref))\n end\nend\n\nBase.broadcastable(sp::StochasticProgram) = Ref(sp)\n", "meta": {"hexsha": "8a6a05d6b5d80ba0b411ad0acdee5eebb74ff577", "size": 17501, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types/stochasticprogram.jl", "max_stars_repo_name": "martinbiel/StochasticPrograms.jl", "max_stars_repo_head_hexsha": "eb142c4cd530022c10a3384fb3a0bfd83fc5714f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49, "max_stars_repo_stars_event_min_datetime": "2018-06-29T09:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:20:57.000Z", "max_issues_repo_path": "src/types/stochasticprogram.jl", "max_issues_repo_name": "juantztz/StochasticPrograms.jl", "max_issues_repo_head_hexsha": "eb142c4cd530022c10a3384fb3a0bfd83fc5714f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2018-09-06T08:34:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T15:55:41.000Z", "max_forks_repo_path": "src/types/stochasticprogram.jl", "max_forks_repo_name": "juantztz/StochasticPrograms.jl", "max_forks_repo_head_hexsha": "eb142c4cd530022c10a3384fb3a0bfd83fc5714f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-06-12T10:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T23:22:21.000Z", "avg_line_length": 46.1767810026, "max_line_length": 488, "alphanum_fraction": 0.6469344609, "num_tokens": 3616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19378350417746945}} {"text": "export simulate!\nexport propagate_init!\n\n#---------------constructor first time step-------------------------------------\nfunction propagate_init!(s::Simulation) #check seems okay #everything good.\n compute_eigen_H!(s)\n H_derivatives!(s)\n generate_therm_surf!(s)\n\n #set initial wavefunction\n @views s.ψ .= convert(Array{ComplexF64, 2}, s.Γ[:, s.surfp])\n\n # KE = sum(0.5 ./m_spread .* s.v.^2)\n # PE = s.hp[1] + sum(s.Γ[s.surfp])\n\n #calculate initial forces\n update_forces!(s)\n #fix position of the last layer of atoms\n s.F[399:530, :] .= 0.0\n s.v[399:530, :] .= 0.0\n\n #convert to Forces\n s.F .= -s.F\n if logopt == 1\n storage_init!(s)\n end\nend\n\n\n#stores data from initialization into first columns of storage arrays\n@inline function storage_init!(s::Simulation)\n get_temperature!(s, 1)\n s.storage_K[1] = 0.5 * sum(s.v.^2 .* m_spread)\n s.storage_P[1] = s.hp[1] + sum(s.λ[s.surfp])\n rtemp = norm(s.Δ_no)\n @views s.storage_e[1, 1] = 0.5 * (mass_arr[1] + mass_arr[2]) *\n sum(((mass_arr[1].*s.v[1, :] + mass_arr[2].*s.v[2, :])/(mass_arr[1] + mass_arr[2])).^2)\n @views T_vib = 0.50 * μ * sum(((s.v[1, :] .- s.v[2, :]).*s.Δ_no/rtemp).^2)\n U_vib = F_n *(1.0 - exp(-δ_n * (rtemp - r_0_NO)))^2\n E_vib = U_vib + T_vib\n s.storage_e[2, 1] = E_vib\n @views T_tot = 0.5 * mass_arr[1] * sum(s.v[1, :].^2) + 0.5*mass_arr[2]*sum(s.v[2, :].^2)\n @views s.storage_e[3, 1] = T_tot - T_vib - s.storage_e[1, 1]\n s.storage_e[4, 1] = sum(s.λ[s.surfp]) - sum(s.λ[s.surfpinit]) #das hier macht keinen Sinn\n @views s.storage_xno[1:3, 1] = s.x[1, :]\n @views s.storage_xno[4:6, 1] = s.x[2, :]\n @views s.storage_vno[1:3, 1] = s.v[1, :]\n @views s.storage_vno[4:6, 1] = s.v[2, :]#check seems okay\nend\n\n@inline function compute_eigen_H!(s::Simulation)\n s.H .= Symmetric(h0 .+ vm .* s.hp[3] ./ sqrt_de)\n s.H[1, 1] = s.H[1, 1] + s.hp[2] - s.hp[1]\n s.λ .= eigvals(s.H)\n s.Γ .= eigvecs(s.H)#check seems okay\n\nend\n\n\n@inbounds @inline function H_derivatives!(s::Simulation) #seems ok, fixed error\n for i in 1:Ms+1\n s.dhdea[:, i] .= view(s.Γ, 1, :) .* s.Γ[1, i]\n end\n temp = vm * s.Γ #needs preallocation\n mul!(s.dhdv, transpose(s.Γ), temp)\n s.dhdv .= s.dhdv ./ sqrt_de\nend\n\n\n@inline @inbounds function generate_therm_surf!(s::Simulation) #check seems okay\n #generate thermalized populations for electronic states\n for j in 1:Ne\n s.surfp[j] = j\n end\n\n for j in 1:Ne\n s.occnum[s.surfp[j]] = 1\n end\n\n k = 1\n for j in 1:Ms+1\n if s.occnum[j] == 0\n s.surfh[k] = j\n k = k + 1\n end\n end\n\n for t in 1:Ne\n for k in 1:Ne*(Ms + 1 - Ne)\n hoprand = rand(Float64, 3)\n #hoprand = collect([0.2, 0.4, 0.6])\n jp = Int(floor(hoprand[1]*Ne)) + 1\n jh = Int(floor(hoprand[2] * (Ms + 1 - Ne))) + 1\n rtemp = exp(-(s.λ[s.surfh[jh]] - s.dhp_neutral[s.surfp[jp]])) / (kb * tsurf)\n if hoprand[3] < rtemp\n m = s.surfh[jh]\n s.surfh[jh] = s.surfp[jp]\n s.surfp[jp] = m\n end\n end\n end\n\n s.surfpinit .= deepcopy(s.surfp)\nend\n\n\n\n@inline @inbounds function update_forces!(s::Simulation) #check seems okay\n for j in 1:Ne\n s.F .= s.F .+ (s.dhdea[s.surfp[j], s.surfp[j]] .* (s.dhp_ion .- s.dhp_neutral) .+\n s.dhdv[s.surfp[j], s.surfp[j]] .* s.dhp_coup)\n\n # @views s.F .= s.F .+ s.dhdv[s.surfp[j], s.surfp[j]] .* s.dhp_coup\n end\n s.F .= s.F .+ s.dhp_neutral\nend\n\n#---------------------simulation main time loop for n=2:tsteps-----------------\nfunction simulate!(s::Simulation)\n for n in 2:tsteps\n do_we_stop = v_z_condition_check(s)\n if do_we_stop == -1\n break\n end\n # Record minimial distance of z approach and orientational angle\n @views min_z_no = minimum(s.x[1:2, 3])\n if min_z_no <= s.trajzmin[1]\n s.trajzmin .= min_z_no\n s.trajtheta .= acos(s.Δ_no[3]/norm(s.Δ_no))\n end\n t_prog = round(n/tsteps * 100.0; digits=3)\n str_t_prog = string(t_prog)*\"%\"\n traj_prog = round(min_z_no/Å; digits=3)\n str_trajzmin_prog = string(traj_prog)\n println(str_t_prog*\", \"*str_trajzmin_prog)\n # get state corresponding to current surface\n @inbounds for j in 1:Ne\n s.ϕ[:, j] = view(s.Γ, :, s.surfp[j])\n end\n\n #Calculate nonadiabatic coupling matrix DM between adiabatic orbitals\n get_dm!(s::Simulation)\n # Get occupied (particle), unoccupied (hole) states corresponding to current surface specified by surfp\n # surfp is Ne x 1 array of particle states\n # surfh is (Ms+1-Ne) x 1 array of hole states\n get_occupied_unoccpied_states!(s)\n # Get b_{kl} where k is current many-electron adiabatic state and l is possible new\n # \tmany-electron adiabatic state\n # k corresponds to occupation of states specified by surfp\n # l corresponds to occupation of states specified by a one electron-hole-pair excitation out of surfp\n get_blk2_pbmaxest!(s)\n # Calculate upper bound of maximum hopping probability, Pbmaxest\n\n #beginn hopping\n #Generate random number for surface hopping\n hoprand = rand()\n #! Only attempt hop if hoprand < Pbmaxest to avoid expensive calculation\n #! of real hopping elements blk\n if hoprand < s.Pbmaxest[1]\n hopping!(s, hoprand, n)\n end\n # Propagate electronic Hamiltonian\n uu = MVector{Ms+1, ComplexF64}(zeros(ComplexF64, Ms+1))\n uuu = zeros(ComplexF64, Ms+1, Ne)\n propagate_hamiltonian!(s, uu, uuu)\n #storage\n if logopt == 1\n storage_sim1!(s, n)\n end\n #propagate nuclear motion\n propagate_nuclear!(s)\n #get adiabatic eigenvalues, eigenvectors\n get_eigen_sim!(s)\n # Get dH / d Ep matrices where Ep is parameter in Newns-Anderson Hamiltonian\n # (i.e. Ep = V or Ep = E_a = (EI-EN) )\n get_dhdea_dhdv_loop!(s)\n\n # Calculate forces\n s.F .= 0\n update_forces!(s)\n s.F[399:530, :] .= 0\n s.v[399:530, :] .= 0\n s.F .= -s.F\n\n s.v .= s.vtemp .+ 0.5 ./m_spread .* s.F * dt\n if logopt == 1\n @views s.storage_xno[1:3, 1] = s.x[1, :]\n @views s.storage_xno[4:6, 1] = s.x[2, :]\n @views s.storage_vno[1:3, 1] = s.v[1, :]\n @views s.storage_vno[4:6, 1] = s.v[2, :]#check seems okay\n end\n s.nf .= s.nf .+ one(Int64)\n end\n s.storage_e[5, :] = sum(s.storage_e[1:4, :], dims=1) .- sum(s.storage_e[1:4, 1])\n\nend\n#-------------------------------------------------------------------------------\n\n#check if the projectile has reached simulation boundaries\nfunction v_z_condition_check(s::Simulation) #should be ok\n @views v_cond = (s.v[1, 3]*m_N + s.v[2, 3]*m_O)/(m_N + m_O)\n @views z_cond = (s.x[1, 3] + s.x[2, 3])/2.0\n if z_cond > z_end && v_cond > 0.0\n println(\"Boundary reached:End Simulation\")\n return -1\n end\n return 1\nend\n\n\n@inbounds @inline function get_dm!(s::Simulation) #should be ok\n # Calculate nonadiabatic coupling elements DM between adiabatic orbitals s.dm\n # phipsi = is overlap between \"current\" adiabatic state |phi_k> and electronic state |psi>\n temp_1 = transpose(s.ϕ) * s.ψ #preallocation\n s.phipsi[1] = det(temp_1)\n # Calculate akk as defined in Tully JCP 1990\n s.akk[1] = abs(s.phipsi[1])^2 #corrected error\n\n # Calculate nonadiabatic coupling elements DM between adiabatic orbitals\n\n temp_2 = s.dhp_ion .- s.dhp_neutral #preallocation\n temp_2 .= temp_2 .* s.v\n temp_2_sum = sum(temp_2)\n s.dm .= temp_2_sum .* s.dhdea\n\n temp_3 = s.dhp_coup .* s.v\n temp_3_sum = sum(temp_3)\n s.dm .= s.dm .+ temp_3_sum .* s.dhdv\n\n temp_rep1 = repeat(s.λ, 1, Ms+1)\n temp_rep2 = temp_rep1' .- temp_rep1\n s.dm .= s.dm ./ temp_rep2\n for j in 1:Ms+1\n s.dm[j,j] = zero(eltype(s.dm))\n end #should be ok\nend\n\n\n@inline @inbounds function get_occupied_unoccpied_states!(s::Simulation) #should be ok\n s.occnum .= 0\n for j in 1:Ne\n s.occnum[s.surfp[j]] = 1\n end\n k = 1\n for j in 1:Ms+1\n if s.occnum[j] == 0\n s.surfh[k] = j\n k = k+1\n end\n end #should be ok\nend\n\n@inline @inbounds function get_blk2_pbmaxest!(s::Simulation) #should be ok\n rtemp = abs(s.phipsi[1] * s.phipsi[1])\n if rtemp > one(eltype(rtemp))\n rtemp = 1.0\n end\n for jp in 1:Ne\n for jh in 1:Ms+1-Ne\n s.blk2[jp, jh] = 2.0 * abs(s.phipsi[1] * s.dm[s.surfp[jp], s.surfh[jh]])\n end\n end\n\n s.Pbmaxest[1] = sqrt(sum(s.blk2.^2)) * sqrt(1.0 - rtemp)/s.akk[1] * dt * Float64(thop) #should be ok\nend\n\n\n#---------------------start hopping! hoprand < pbmaxest -----------------------\nfunction hopping!(s::Simulation, hoprand::Float64, n::Int64)\n hopping!_pbmaxest!(s, hoprand, n)\nend\n\nfunction hopping!_pbmaxest!(s::Simulation, hoprand::Float64, n::Int64)\n get_blk_akl!(s)\n get_pb!(s)\n\n s.storage_phop[n] = s.Pb[Ne*(Ms+1-Ne)]\n #attempt hop conditioned on random number\n if hoprand < s.Pb[Ne*(Ms+1-Ne)]\n print(\"Hopping! \")\n hopping!_pbmaxest!_attempt!(s, hoprand, n)\n end\nend\n\n@inline function get_blk_akl!(s::Simulation) #seems ok\n ctemp1 = Matrix{ComplexF64}(undef, Ne, Ne)\n for jp in 1:Ne\n for jh in 1:Ms+1-Ne\n s.surfpnew .= s.surfp\n s.surfpnew[jp] = s.surfh[jh]\n for j in 1:Ne\n @views s.ϕ[:, j] = s.Γ[:, s.surfpnew[j]]\n end\n #Ctemp = is overlap between \"new\" adiabatic state\n #|phi_l> and electronic state |psi>\n mul!(ctemp1, transpose(s.ϕ) , s.ψ)\n ctemp = det(ctemp1)\n s.akl[1] = s.phipsi[1] * conj(ctemp)\n @views s.blk[jp, jh] = 2.0 * real(s.akl[1] * s.dm[s.surfp[jp], s.surfh[jh]])\n end\n end\nend\n\n@inline function get_pb!(s::Simulation) #seems ok\n rtemp = 0.0\n for jh in 1:Ms+1-Ne\n for jp in 1:Ne\n s.Pb[(jh-1) * Ne + jp] = rtemp\n @views temp = s.blk[jp,jh]\n if temp <= 0.0\n temp = 0.0\n end\n s.Pb[(jh-1) * Ne + jp] = s.Pb[(jh-1)*Ne + jp] + temp\n rtemp = s.Pb[(jh - 1) * Ne + jp]\n end\n end\n s.Pb .= s.Pb ./ s.akk[1] * dt * Float64(thop)\nend\n#-----------------start hopping! hoprand < pbmaxest && hoprand < Pbmax ---------\nfunction hopping!_pbmaxest!_attempt!(s::Simulation, hoprand::Float64, n::Int64)\n hopstate = which_state(s, hoprand) #ok\n jh= which_orbital_jh(hopstate) #ok\n jp= which_orbital_jp(hopstate) #ok\n rhop = which_direction(s, jp, jh) #needs durther testing, not sure about rescaling\n e_el_old, e_el_new, k_rhop, k_temp = check_energy1(s, jp, jh, rhop)\n bool_e = check_energy2(e_el_old, e_el_new, k_rhop, k_temp)\n s.attnum .= s.attnum .+ one(Int64)\n\n if bool_e == true\n update_vel_populations!(s, jp, jh, rhop, k_temp, k_rhop, e_el_old, e_el_new, n) #needs more storage\n end\nend\n\n@inline function which_state(s::Simulation, hoprand::Float64)::Int64 #ok\n hopstate = one(Int64)\n while s.Pb[hopstate] <= hoprand\n hopstate = hopstate + one(Int64)\n end\n return hopstate\nend\n\n@inline function which_orbital_jh(hopstate::Int64)::Int64 #ok\n jh = Int(floor((hopstate - 1) / Ne)) + one(Int64)\n return jh\nend\n@inline function which_orbital_jp(hopstate::Int64)::Int64 #ok\n jp = ((hopstate - one(Int64)) % Ne) + one(Int64)\n return jp\nend\n\n@inline function which_direction(s::Simulation, jp::Int64, jh::Int64)::float_array #needs checking\n @views temp = s.dhdea[s.surfp[jp], s.surfh[jh]] .* (s.dhp_ion .- s.dhp_neutral)\n @views temp .= temp .+ s.dhdv[s.surfp[jp], s.surfh[jh]] .* s.dhp_coup\n temp2 = sqrt(sum(temp.^2)/sum(s.v .^2))\n temp .= temp ./ temp2\n temp3 = sum(temp .* s.v)\n temp .= temp .* copysign(1.0, temp3)\n return temp\nend\n\n\n@inline function check_energy1(s::Simulation, jp::Int64, jh::Int64, rhop::float_array) # seems ok\n s.surfpnew .= s.surfp\n s.surfpnew[jp] = s.surfh[jh]\n e_el_old = sum(s.λ[s.surfp])\n e_el_new = sum(s.λ[s.surfpnew])\n k_rhop = 0.5 * sum(1.0 ./ m_spread .* rhop .^2)\n k_temp = sum(s.v .* rhop)\n\n return e_el_old, e_el_new, k_rhop, k_temp\nend\n\n\n@inline function check_energy2(e_el_old::Float64, e_el_new::Float64, k_rhop::Float64, k_temp::Float64)::Bool\n bool_e = k_temp^2 - 4.0*k_rhop * (e_el_new - e_el_old) > 0.0\n return bool_e\nend\n\n@inline function update_vel_populations!(s::Simulation, jp::Int64, jh::Int64, rhop::float_array,\n k_temp::Float64, k_rhop::Float64, e_el_old::Float64, e_el_new::Float64, n::Int64)\n rtemp = s.vscale[1]\n s.vscale[1] = (k_temp - sqrt(k_temp^2 - 4.0 * k_rhop * (e_el_new - e_el_old)))/2.0/k_rhop\n @views k_no = 0.50 * sum(view(m_spread, 1:2, :).* view(s.v, 1:2, :).^2)\n @views k_au = 0.50 * sum(view(m_spread, 3:N+2, :) .* view(s.v, 3:N+2, :).^2)\n s.v .= s.v .- s.vscale[1] .* (1.0 ./m_spread .* rhop)\n s.storage_deltaKNO[s.exnum[1]+1] = k_no - 0.5*sum(view(m_spread, 1:2, :) .* view(s.v, 1:2, :) .^2)\n s.storage_deltaKAu[s.exnum[1]+1] = k_au - 0.5*sum(view(m_spread, 3:N+2, :) .* view(s.v, 3:N+2, :) .^2)\n s.storage_state[2*s.exnum[1] + 1] = s.surfp[jp]\n s.storage_state[2*s.exnum[1] + 2] = s.surfh[jh]\n s.surfp .= s.surfpnew\n s.storage_hoptimes[s.exnum[1]+1] = n\n s.exnum .= s.exnum .+ one(Int64)\n #endif\nend\n#-----------------END hopping! hoprand < pbmaxest && hoprand < Pbmax ---------\n\n\n\n@inline function propagate_hamiltonian!(s::Simulation, uu::MVector{Ms+1, ComplexF64},\n uuu::Matrix{ComplexF64}) # seems ok\n s.ψ .= transpose(s.Γ) * s.ψ\n\n uu .= exp.(-1im * s.λ * dt/hbar)\n uuu .= repeat(uu, 1, Ne)\n s.ψ .= uuu .* s.ψ\n s.ψ .= s.Γ * s.ψ\nend\n\n#storage_op_e\n@inline function storage_sim1!(s::Simulation, n::Int64) #seems ok\n get_temperature!(s, n)\n s.storage_K[n] = 0.5 * sum(s.v .^2 .* m_spread)\n s.storage_P[n] = s.hp[1] + sum(s.λ[s.surfp])\n @views s.storage_aop[n] = sum(abs.(s.ψ[1, :]).^2) #rhoa\n store_temp = sum(abs.(transpose(s.Γ) * s.ψ).^2, dims=2)\n s.storage_op[:, n] .= store_temp[:, 1] #psip\n\n rtemp = norm(s.Δ_no)\n s.storage_e[1, n] = 0.5 * (mass_arr[1] + mass_arr[2]) *\n sum(((mass_arr[1].*s.v[1, :] + mass_arr[2].*s.v[2, :])/(mass_arr[1] + mass_arr[2])).^2)\n @views T_vib = 0.50 * μ * sum(((s.v[1, :] .- s.v[2, :]).*s.Δ_no/rtemp).^2)\n U_vib = F_n *(1.0 - exp(-δ_n * (rtemp - r_0_NO)))^2\n E_vib = U_vib + T_vib\n s.storage_e[2, n] = E_vib\n @views T_tot = 0.5 * mass_arr[1] * sum(s.v[1, :].^2) + 0.5*mass_arr[2]*sum(s.v[2, :].^2)\n s.storage_e[3, n] = T_tot - T_vib - s.storage_e[1, n]\n s.storage_e[4, n] = sum(s.λ[s.surfp]) - sum(s.λ[s.surfpinit])\n\nend\n@inline function propagate_nuclear!(s::Simulation)\n s.vdot .= 1.0./m_spread .* s.F\n s.x .= s.x .+ s.v * dt .+ 0.50*s.vdot * dt^2\n s.Δ_no .= s.x[1, :] - s.x[2, :]\n s.vtemp .= s.v .+ 0.50*s.vdot*dt #ARRAY ALLOCATION !!!! solve later\nend\n\n@inline function get_eigen_sim!(s::Simulation)\n s.hp .= get_E_all(s) #update energy surface\n get_F_all(s) #update partial derivatives dhp_i\n s.H .= h0 .+ vm .* s.hp[3] ./sqrt_de\n s.H[1, 1] = s.H[1, 1] + s.hp[2] - s.hp[1]\n Γ_hold = deepcopy(s.Γ) #ARRAY ALLOCATION !!!! solve later\n s.λ .= eigvals(s.H)\n s.Γ .= eigvecs(s.H)\n temp = zeros(Float64, Ms+1)\n @inbounds for j in 1:Ms+1\n @views temp .= abs.(transpose(Γ_hold) * s.Γ[:, j])\n Γmaxloc = argmax(temp)\n temp2 = dot(Γ_hold[:, Γmaxloc], s.Γ[:, j])\n s.Γ[:, j] = s.Γ[:, j]/copysign(1.0, temp2)\n end\nend\n\nfunction get_dhdea_dhdv_loop!(s::Simulation)\n s.blk .= 0.0\n @inbounds for j in 1:Ms+1\n s.dhdea[:, j] = s.Γ[1, :] .* s.Γ[1, j]\n end\n temp = (vm * s.Γ) #ARRAY ALLOCATION !!!! solve later\n mul!(s.dhdv, transpose(s.Γ), temp)\n s.dhdv .= s.dhdv ./sqrt_de\nend\n\nfunction get_temperature!(s::Simulation, n::Int)\n speed = [norm(s.v[i, :]) for i in 3:398]\n s.storage_temp[n] = 2*m_au*sum(speed.^2)/(3*(N*0.75-3)*kb)\nend\n", "meta": {"hexsha": "b70d47c5ad8b84cb1945518975b60261738532f8", "size": 16248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/propagation.jl", "max_stars_repo_name": "numbpapaya/My_iesh", "max_stars_repo_head_hexsha": "eca13f818f8bc1157cca9c80934f10f092cae96c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/propagation.jl", "max_issues_repo_name": "numbpapaya/My_iesh", "max_issues_repo_head_hexsha": "eca13f818f8bc1157cca9c80934f10f092cae96c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-05T00:12:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T00:12:58.000Z", "max_forks_repo_path": "src/propagation.jl", "max_forks_repo_name": "numbpapaya/My_iesh", "max_forks_repo_head_hexsha": "eca13f818f8bc1157cca9c80934f10f092cae96c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7179487179, "max_line_length": 111, "alphanum_fraction": 0.5708394879, "num_tokens": 5971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.19368390975908614}} {"text": "using .NumericalFluxes: CentralHyperDiffusiveFlux, CentralDivPenalty\n\nstruct DGModel{BL, G, NFND, NFD, GNF, AS, DS, HDS, D, DD, MD}\n balancelaw::BL\n grid::G\n numfluxnondiff::NFND\n numfluxdiff::NFD\n gradnumflux::GNF\n auxstate::AS\n diffstate::DS\n hyperdiffstate::HDS\n direction::D\n diffusion_direction::DD\n modeldata::MD\nend\nfunction DGModel(\n balancelaw,\n grid,\n numfluxnondiff,\n numfluxdiff,\n gradnumflux;\n auxstate = create_auxstate(balancelaw, grid),\n diffstate = create_diffstate(balancelaw, grid),\n hyperdiffstate = create_hyperdiffstate(balancelaw, grid),\n direction = EveryDirection(),\n diffusion_direction = direction,\n modeldata = nothing,\n)\n DGModel(\n balancelaw,\n grid,\n numfluxnondiff,\n numfluxdiff,\n gradnumflux,\n auxstate,\n diffstate,\n hyperdiffstate,\n direction,\n diffusion_direction,\n modeldata,\n )\nend\n\nfunction (dg::DGModel)(dQdt, Q, ::Nothing, t; increment = false)\n\n bl = dg.balancelaw\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n Nfp = Nq * Nqk\n nrealelem = length(topology.realelems)\n\n Qvisc = dg.diffstate\n Qhypervisc_grad, Qhypervisc_div = dg.hyperdiffstate\n auxstate = dg.auxstate\n\n FT = eltype(Q)\n nviscstate = num_diffusive(bl, FT)\n nhyperviscstate = num_hyperdiffusive(bl, FT)\n\n Np = dofs_per_element(grid)\n\n workgroups_volume = (Nq, Nq, Nqk)\n ndrange_volume = (nrealelem * Nq, Nq, Nqk)\n workgroups_surface = Nfp\n ndrange_surface = Nfp * nrealelem\n\n communicate =\n !(isstacked(topology) && typeof(dg.direction) <: VerticalDirection)\n\n aux_comm = update_aux!(dg, bl, Q, t)\n @assert typeof(aux_comm) == Bool\n\n if nhyperviscstate > 0\n hypervisc_indexmap = create_hypervisc_indexmap(bl)\n else\n hypervisc_indexmap = nothing\n end\n\n ########################\n # Gradient Computation #\n ########################\n if communicate\n MPIStateArrays.start_ghost_exchange!(Q)\n if aux_comm\n MPIStateArrays.start_ghost_exchange!(auxstate)\n end\n end\n\n if nviscstate > 0 || nhyperviscstate > 0\n\n event = Event(device)\n event = volumeviscterms!(device, workgroups_volume)(\n bl,\n Val(dim),\n Val(N),\n dg.diffusion_direction,\n Q.data,\n Qvisc.data,\n Qhypervisc_grad.data,\n auxstate.data,\n grid.vgeo,\n t,\n grid.D,\n hypervisc_indexmap,\n topology.realelems,\n ndrange = ndrange_volume,\n dependencies = (event,),\n )\n wait(device, event)\n\n if communicate\n MPIStateArrays.finish_ghost_recv!(Q)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n end\n\n event = Event(device)\n event = faceviscterms!(device, workgroups_surface)(\n bl,\n Val(dim),\n Val(N),\n dg.diffusion_direction,\n dg.gradnumflux,\n Q.data,\n Qvisc.data,\n Qhypervisc_grad.data,\n auxstate.data,\n grid.vgeo,\n grid.sgeo,\n t,\n grid.vmap⁻,\n grid.vmap⁺,\n grid.elemtobndy,\n hypervisc_indexmap,\n topology.realelems;\n ndrange = ndrange_surface,\n dependencies = (event,),\n )\n wait(device, event)\n\n if communicate\n nviscstate > 0 && MPIStateArrays.start_ghost_exchange!(Qvisc)\n nhyperviscstate > 0 &&\n MPIStateArrays.start_ghost_exchange!(Qhypervisc_grad)\n end\n\n if nviscstate > 0\n aux_comm = update_aux_diffusive!(dg, bl, Q, t)\n @assert typeof(aux_comm) == Bool\n end\n\n if aux_comm\n MPIStateArrays.start_ghost_exchange!(auxstate)\n end\n end\n\n if nhyperviscstate > 0\n #########################\n # Laplacian Computation #\n #########################\n\n event = Event(device)\n event = volumedivgrad!(device, workgroups_volume)(\n bl,\n Val(dim),\n Val(N),\n dg.diffusion_direction,\n Qhypervisc_grad.data,\n Qhypervisc_div.data,\n grid.vgeo,\n grid.D,\n topology.realelems;\n ndrange = ndrange_volume,\n dependencies = (event,),\n )\n wait(device, event)\n\n communicate && MPIStateArrays.finish_ghost_recv!(Qhypervisc_grad)\n\n event = Event(device)\n event = facedivgrad!(device, workgroups_surface)(\n bl,\n Val(dim),\n Val(N),\n dg.diffusion_direction,\n CentralDivPenalty(),\n Qhypervisc_grad.data,\n Qhypervisc_div.data,\n grid.vgeo,\n grid.sgeo,\n grid.vmap⁻,\n grid.vmap⁺,\n grid.elemtobndy,\n topology.realelems;\n ndrange = ndrange_surface,\n dependencies = (event,),\n )\n wait(device, event)\n\n communicate && MPIStateArrays.start_ghost_exchange!(Qhypervisc_div)\n\n ####################################\n # Hyperdiffusive terms computation #\n ####################################\n\n event = Event(device)\n event = volumehyperviscterms!(device, workgroups_volume)(\n bl,\n Val(dim),\n Val(N),\n dg.diffusion_direction,\n Qhypervisc_grad.data,\n Qhypervisc_div.data,\n Q.data,\n auxstate.data,\n grid.vgeo,\n grid.ω,\n grid.D,\n topology.realelems,\n t;\n ndrange = ndrange_volume,\n dependencies = (event,),\n )\n wait(device, event)\n\n communicate && MPIStateArrays.finish_ghost_recv!(Qhypervisc_div)\n\n event = Event(device)\n event = facehyperviscterms!(device, workgroups_surface)(\n bl,\n Val(dim),\n Val(N),\n dg.diffusion_direction,\n CentralHyperDiffusiveFlux(),\n Qhypervisc_grad.data,\n Qhypervisc_div.data,\n Q.data,\n auxstate.data,\n grid.vgeo,\n grid.sgeo,\n grid.vmap⁻,\n grid.vmap⁺,\n grid.elemtobndy,\n topology.realelems,\n t;\n ndrange = ndrange_surface,\n dependencies = (event,),\n )\n wait(device, event)\n\n communicate && MPIStateArrays.start_ghost_exchange!(Qhypervisc_grad)\n end\n\n\n ###################\n # RHS Computation #\n ###################\n event = Event(device)\n event = volumerhs!(device, workgroups_volume)(\n bl,\n Val(dim),\n Val(N),\n dg.direction,\n dQdt.data,\n Q.data,\n Qvisc.data,\n Qhypervisc_grad.data,\n auxstate.data,\n grid.vgeo,\n t,\n grid.ω,\n grid.D,\n topology.realelems,\n increment;\n ndrange = ndrange_volume,\n dependencies = (event,),\n )\n wait(device, event)\n\n if communicate\n if nviscstate > 0 || nhyperviscstate > 0\n if nviscstate > 0\n MPIStateArrays.finish_ghost_recv!(Qvisc)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n end\n nhyperviscstate > 0 &&\n MPIStateArrays.finish_ghost_recv!(Qhypervisc_grad)\n else\n MPIStateArrays.finish_ghost_recv!(Q)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n end\n end\n\n event = Event(device)\n event = facerhs!(device, workgroups_surface)(\n bl,\n Val(dim),\n Val(N),\n dg.direction,\n dg.numfluxnondiff,\n dg.numfluxdiff,\n dQdt.data,\n Q.data,\n Qvisc.data,\n Qhypervisc_grad.data,\n auxstate.data,\n grid.vgeo,\n grid.sgeo,\n t,\n grid.vmap⁻,\n grid.vmap⁺,\n grid.elemtobndy,\n topology.realelems;\n ndrange = ndrange_surface,\n dependencies = (event,),\n )\n wait(device, event)\n\n # Just to be safe, we wait on the sends we started.\n if communicate\n MPIStateArrays.finish_ghost_send!(Qhypervisc_div)\n MPIStateArrays.finish_ghost_send!(Qvisc)\n MPIStateArrays.finish_ghost_send!(Qhypervisc_grad)\n MPIStateArrays.finish_ghost_send!(Q)\n end\nend\n\nfunction init_ode_state(\n dg::DGModel,\n args...;\n init_on_cpu = false,\n commtag = 888,\n)\n device = arraytype(dg.grid) <: Array ? CPU() : CUDA()\n\n bl = dg.balancelaw\n grid = dg.grid\n\n state = create_state(bl, grid, commtag)\n\n topology = grid.topology\n Np = dofs_per_element(grid)\n\n auxstate = dg.auxstate\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n nrealelem = length(topology.realelems)\n\n if !init_on_cpu\n event = Event(device)\n event = initstate!(device, Np)(\n bl,\n Val(dim),\n Val(N),\n state.data,\n auxstate.data,\n grid.vgeo,\n topology.realelems,\n args...;\n ndrange = Np * nrealelem,\n dependencies = (event,),\n )\n wait(device, event)\n else\n h_state = similar(state, Array)\n h_auxstate = similar(auxstate, Array)\n h_auxstate .= auxstate\n event = initstate!(CPU(), Np)(\n bl,\n Val(dim),\n Val(N),\n h_state.data,\n h_auxstate.data,\n Array(grid.vgeo),\n topology.realelems,\n args...;\n ndrange = Np * nrealelem,\n )\n wait(event) # XXX: This could be `wait(device, event)` once KA supports that.\n state .= h_state\n end\n\n MPIStateArrays.start_ghost_exchange!(state)\n MPIStateArrays.finish_ghost_exchange!(state)\n\n return state\nend\n\n# fallback\nfunction update_aux!(dg::DGModel, bl::BalanceLaw, Q::MPIStateArray, t::Real)\n return false\nend\n\nfunction update_aux_diffusive!(\n dg::DGModel,\n bl::BalanceLaw,\n Q::MPIStateArray,\n t::Real,\n)\n return false\nend\n\nfunction indefinite_stack_integral!(\n dg::DGModel,\n m::BalanceLaw,\n Q::MPIStateArray,\n auxstate::MPIStateArray,\n t::Real,\n)\n\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n FT = eltype(Q)\n\n # do integrals\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n event = Event(device)\n event = knl_indefinite_stack_integral!(device, (Nq, Nqk))(\n m,\n Val(dim),\n Val(N),\n Val(nvertelem),\n Q.data,\n auxstate.data,\n grid.vgeo,\n grid.Imat,\n 1:nhorzelem;\n ndrange = (nhorzelem * Nq, Nqk),\n dependencies = (event,),\n )\n wait(device, event)\nend\n\nfunction reverse_indefinite_stack_integral!(\n dg::DGModel,\n m::BalanceLaw,\n Q::MPIStateArray,\n auxstate::MPIStateArray,\n t::Real,\n)\n\n device = typeof(auxstate.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n FT = eltype(auxstate)\n\n # do integrals\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n event = Event(device)\n event = knl_reverse_indefinite_stack_integral!(device, (Nq, Nqk))(\n m,\n Val(dim),\n Val(N),\n Val(nvertelem),\n Q.data,\n auxstate.data,\n 1:nhorzelem;\n ndrange = (nhorzelem * Nq, Nqk),\n dependencies = (event,),\n )\n wait(device, event)\nend\n\nfunction nodal_update_aux!(\n f!,\n dg::DGModel,\n m::BalanceLaw,\n Q::MPIStateArray,\n t::Real;\n diffusive = false,\n)\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n nrealelem = length(topology.realelems)\n\n Np = dofs_per_element(grid)\n\n nodal_update_aux! = knl_nodal_update_aux!(device, Np)\n ### update aux variables\n event = Event(device)\n if diffusive\n event = nodal_update_aux!(\n m,\n Val(dim),\n Val(N),\n f!,\n Q.data,\n dg.auxstate.data,\n dg.diffstate.data,\n t,\n topology.realelems;\n ndrange = Np * nrealelem,\n dependencies = (event,),\n )\n else\n event = nodal_update_aux!(\n m,\n Val(dim),\n Val(N),\n f!,\n Q.data,\n dg.auxstate.data,\n t,\n topology.realelems;\n ndrange = Np * nrealelem,\n dependencies = (event,),\n )\n end\n wait(device, event)\nend\n\n\"\"\"\n courant(local_courant::Function, dg::DGModel, m::BalanceLaw,\n Q::MPIStateArray, direction=EveryDirection())\nReturns the maximum of the evaluation of the function `local_courant`\npointwise throughout the domain. The function `local_courant` is given an\napproximation of the local node distance `Δx`. The `direction` controls which\nreference directions are considered when computing the minimum node distance\n`Δx`.\nAn example `local_courant` function is\n function local_courant(m::AtmosModel, state::Vars, aux::Vars,\n diffusive::Vars, Δx)\n return Δt * cmax / Δx\n end\nwhere `Δt` is the time step size and `cmax` is the maximum flow speed in the\nmodel.\n\"\"\"\nfunction courant(\n local_courant::Function,\n dg::DGModel,\n m::BalanceLaw,\n Q::MPIStateArray,\n Δt,\n simtime,\n direction = EveryDirection(),\n)\n grid = dg.grid\n topology = grid.topology\n nrealelem = length(topology.realelems)\n\n if nrealelem > 0\n N = polynomialorder(grid)\n dim = dimensionality(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n device = grid.vgeo isa Array ? CPU() : CUDA()\n pointwise_courant = similar(grid.vgeo, Nq^dim, nrealelem)\n event = Event(device)\n event = Grids.knl_min_neighbor_distance!(device, (Nq, Nq, Nqk))(\n Val(N),\n Val(dim),\n direction,\n pointwise_courant,\n grid.vgeo,\n topology.realelems;\n ndrange = (nrealelem * Nq, Nq, Nqk),\n dependencies = (event,),\n )\n event = knl_local_courant!(device, Nq * Nq * Nqk)(\n m,\n Val(dim),\n Val(N),\n pointwise_courant,\n local_courant,\n Q.data,\n dg.auxstate.data,\n dg.diffstate.data,\n topology.realelems,\n Δt,\n simtime,\n direction;\n ndrange = nrealelem * Nq * Nq * Nqk,\n dependencies = (event,),\n )\n wait(device, event)\n rank_courant_max = maximum(pointwise_courant)\n else\n rank_courant_max = typemin(eltype(Q))\n end\n\n MPI.Allreduce(rank_courant_max, max, topology.mpicomm)\nend\n\nfunction copy_stack_field_down!(\n dg::DGModel,\n m::BalanceLaw,\n auxstate::MPIStateArray,\n fldin,\n fldout,\n)\n\n device = typeof(auxstate.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n # do integrals\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n event = Event(device)\n event = knl_copy_stack_field_down!(device, (Nq, Nqk))(\n Val(dim),\n Val(N),\n Val(nvertelem),\n auxstate.data,\n 1:nhorzelem,\n Val(fldin),\n Val(fldout);\n ndrange = (nhorzelem * Nq, Nqk),\n dependencies = (event,),\n )\n wait(device, event)\nend\n\nfunction MPIStateArrays.MPIStateArray(dg::DGModel, commtag = 888)\n bl = dg.balancelaw\n grid = dg.grid\n\n state = create_state(bl, grid, commtag)\n\n return state\nend\n\nfunction create_hypervisc_indexmap(bl::BalanceLaw)\n # helper function\n _getvars(v, ::Type) = v\n function _getvars(v::Vars, ::Type{T}) where {T <: NamedTuple}\n fields = getproperty.(Ref(v), fieldnames(T))\n collect(Iterators.Flatten(_getvars.(fields, fieldtypes(T))))\n end\n\n gradvars = vars_gradient(bl, Int)\n gradlapvars = vars_gradient_laplacian(bl, Int)\n indices = Vars{gradvars}(1:varsize(gradvars))\n SVector{varsize(gradlapvars)}(_getvars(indices, gradlapvars))\nend\n", "meta": {"hexsha": "ad7ba577f329293cbf0733000238e95754ce5e34", "size": 17137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DGmethods/DGmodel.jl", "max_stars_repo_name": "trontrytel/CLIMA", "max_stars_repo_head_hexsha": "9677227cbc53f6da77acb9939c8269d0cc2283d1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DGmethods/DGmodel.jl", "max_issues_repo_name": "trontrytel/CLIMA", "max_issues_repo_head_hexsha": "9677227cbc53f6da77acb9939c8269d0cc2283d1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DGmethods/DGmodel.jl", "max_forks_repo_name": "trontrytel/CLIMA", "max_forks_repo_head_hexsha": "9677227cbc53f6da77acb9939c8269d0cc2283d1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0907759883, "max_line_length": 85, "alphanum_fraction": 0.5521386474, "num_tokens": 4386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.19331342654222544}} {"text": "#using Ipopt: optimize!\nusing Base: Int64\nusing XLSX: length\n#=using Pkg\nPkg.add(\"Tables\")\nPkg.add(\"DataFrames\")\nPkg.add(\"XLSX\")\nPkg.add(\"ExcelReaders\")\nPkg.add(\"JuMP\")\nPkg.add(\"Ipopt\")\n=#\nusing XLSX, ExcelReaders, DataFrames, Tables, JuMP, Ipopt;\nIOSource = XLSX.readdata(\"IO.xlsx\", \"io-table-5!A1:DV130\");\n\n#filepath cross system compatability code\nif Sys.KERNEL === :NT || kern === :Windows\n pathmark = \"\\\\\"\nelse\n pathmark = \"/\"\nend\n\n#indexing vectors for initial data import groups\nintermediaryTotalsCol = findall(x -> occursin(\"T4\", x), string.(IOSource[3,:]));\nintermediaryTotalsRow = findall(x -> occursin(\"T1\", x), string.(IOSource[:,1]));\nfinalTotalsCol = findall(x -> occursin(\"T6\", x), string.(IOSource[3,:]));\nfinalTotalsRow = findall(x -> occursin(\"Australian Production\", x), string.(IOSource[:,2]));\nfinalDemandCol = findall(x -> occursin('Q', x), string.(IOSource[3,:]));\nfactorRow = findall(x -> occursin('P', x), string.(IOSource[:,1]));\nIOSourceCol = vcat(intermediaryTotalsCol, finalDemandCol, finalTotalsCol);\nIOSourceRow = vcat(intermediaryTotalsRow, factorRow, finalTotalsRow);\n#initialising IO\nIO = zeros(length(IOSourceRow), length(IOSourceCol));\n#import numerical data into IO\nIO[1:length(IOSourceRow), 1:length(IOSourceCol)] = IOSource[IOSourceRow, IOSourceCol];\n#creating vectors of titles for IO\nIOCodeRow = IOSource[IOSourceRow, 1];\nIOCodeCol = IOSource[3, IOSourceCol];\nIONameRow = IOSource[IOSourceRow, 2];\nIONameCol = IOSource[2, IOSourceCol];\n\n#code to sum public and private entities into one collumn\ninvestment = findall(x -> occursin(\"Capital Formation\", x), IONameCol);\nIO[:, investment[1]]=sum(eachcol(IO[:, investment[1:2]]));\nIO = IO[:,Not(investment[2])];\n#alter title vectors accordingly (include Q in total investment collumn in IOcode)\nIOCodeCol[investment[1]] = \"Q3+Q4\";\nIOCodeCol = IOCodeCol[Not(investment[2])];\nIONameCol[investment[1]] = \"Private and Public Gross Fixed Capital Formation\";\nIONameCol = IONameCol[Not(investment[2])];\n#creating a dictionary for the index of each collumn and row in IO by IOCode\nIOColDict = Dict(IOCodeCol .=> [1:1:8;]);\nIORowDict = Dict(IOCodeRow .=> [1:1:8;]);\nIOCapForm = findall(x -> occursin(\"Capital Formation\", x), IONameCol);\nIOChangeInv = findall(x -> occursin(\"Changes in Inventories\", x), IONameCol);\n\n#importing relevant ASNA data for table 5\nASNAHouseCap = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204039_Household_Capital_Account.xls\", \"Data1!A1:T71\");\nASNANonFinCap = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204018_NonFin_Corp_Capital_Account.xls\", \"Data1!A1:T71\");\nASNAFinCap = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204026_Fin_Corp_Capital_Account.xls\", \"Data1!A1:S71\");\nASNAGovCap = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204032_GenGov_Capital_Account.xls\", \"Data1!A1:AV71\");\nASNAYearRow = findall(x -> occursin(\"2019\", x), string.(ASNAHouseCap[:,1]));\n\n#table 5\n#creating table 5a - allocation of investment expenditure (broken into subsections for dict referencing purposes)\n#subsection a is fixed capital expenditure\ntable5aNameCol = [\"Households\", \"Non-Financial Corporations\", \"Financial Corporations\", \"General Government\", \"Total\"];\ntable5aNameRow = [\"Domestic Commodities\", \"Imported Commodities, complementary\", \"Imported Commodities, competing\", \n\"Taxes less subsidies on products\", \"Other taxes less subsidies on investment\", \"Total indirect taxes\", \n\"Total fixed capital expenditure\"];\ntable5aRowDict = Dict(table5aNameRow .=> [1:1:length(table5aNameRow);]);\ntable5aColDict = Dict(table5aNameCol .=> [1:1:length(table5aNameCol);]);\ntable5a = zeros(length(table5aNameRow), length(table5aNameCol));\n\n#filling in totals collumn from corresponding IO data\ntable5a[table5aRowDict[\"Domestic Commodities\"], table5aColDict[\"Total\"]] = sum(IO[IORowDict[\"T1\"],IOCapForm]);\ntable5a[table5aRowDict[\"Imported Commodities, complementary\"], table5aColDict[\"Total\"]] = sum(IO[IORowDict[\"P5\"],IOCapForm]);\ntable5a[table5aRowDict[\"Imported Commodities, competing\"], table5aColDict[\"Total\"]] = sum(IO[IORowDict[\"P6\"],IOCapForm]);\ntable5a[table5aRowDict[\"Taxes less subsidies on products\"], table5aColDict[\"Total\"]] = sum(IO[IORowDict[\"P3\"],IOCapForm]);\ntable5a[table5aRowDict[\"Other taxes less subsidies on investment\"], table5aColDict[\"Total\"]] = sum(IO[IORowDict[\"P4\"],IOCapForm]);\ntable5aTaxes = findall(x -> occursin(\"taxes\", lowercase(x)), table5aNameRow);\ntable5aTaxes = table5aTaxes[Not(3)];\ntable5a[table5aRowDict[\"Total indirect taxes\"], table5aColDict[\"Total\"]] = sum(table5a[table5aTaxes,table5aColDict[\"Total\"]]);\ntable5a[table5aRowDict[\"Total fixed capital expenditure\"], table5aColDict[\"Total\"]] = sum(table5a[Not(table5aRowDict[\"Total indirect taxes\"]),table5aColDict[\"Total\"]]);\n\n#creating index variables for the measurements that we want\nASNAHouseCapTotCapForm = findall(x -> occursin(\"Gross fixed capital formation ;\", x), string.(ASNAHouseCap[1,:]));\nASNANonFinCapTotCapForm = findall(x -> occursin(\"Gross fixed capital formation ;\", x), string.(ASNANonFinCap[1,:]));\nASNAFinCapTotCapForm = findall(x -> occursin(\"Gross fixed capital formation ;\", x), string.(ASNAFinCap[1,:]));\nASNAGenGovCapTotCapForm = findall(x -> occursin(\"General government ; Gross fixed capital formation ;\", x), string.(ASNAGovCap[1,:]));\n\n#filling in totals row from ASNA Data\ntable5a[table5aRowDict[\"Total fixed capital expenditure\"], table5aColDict[\"Households\"]] = first(ASNAHouseCap[ASNAYearRow, ASNAHouseCapTotCapForm]);\ntable5a[table5aRowDict[\"Total fixed capital expenditure\"], table5aColDict[\"Non-Financial Corporations\"]] = first(ASNANonFinCap[ASNAYearRow, ASNANonFinCapTotCapForm]);\ntable5a[table5aRowDict[\"Total fixed capital expenditure\"], table5aColDict[\"Financial Corporations\"]] = first(ASNAFinCap[ASNAYearRow, ASNAFinCapTotCapForm]);\ntable5a[table5aRowDict[\"Total fixed capital expenditure\"], table5aColDict[\"General Government\"]] = first(ASNAGovCap[ASNAYearRow, ASNAGenGovCapTotCapForm]);\n\n#filling in non-total values\nfor ring in [1:1:length(table5aColDict)-1;];\n table5a[table5aRowDict[\"Domestic Commodities\"],ring] = table5a[table5aRowDict[\"Total fixed capital expenditure\"],ring]*IO[IORowDict[\"T1\"],IOCapForm[1]] / IO[IORowDict[missing],IOCapForm[1]];\n table5a[table5aRowDict[\"Imported Commodities, complementary\"],ring] = table5a[table5aRowDict[\"Total fixed capital expenditure\"],ring]*IO[IORowDict[\"P5\"],IOCapForm[1]] / IO[IORowDict[missing],IOCapForm[1]];\n table5a[table5aRowDict[\"Imported Commodities, competing\"],ring] = table5a[table5aRowDict[\"Total fixed capital expenditure\"],ring]*IO[IORowDict[\"P6\"],IOCapForm[1]] / IO[IORowDict[missing],IOCapForm[1]];\n table5a[table5aRowDict[\"Taxes less subsidies on products\"],ring] = table5a[table5aRowDict[\"Total fixed capital expenditure\"],ring]*IO[IORowDict[\"P3\"],IOCapForm[1]] / IO[IORowDict[missing],IOCapForm[1]];\n table5a[table5aRowDict[\"Other taxes less subsidies on investment\"],ring] = table5a[table5aRowDict[\"Total fixed capital expenditure\"],ring]*IO[IORowDict[\"P4\"],IOCapForm[1]] / IO[IORowDict[missing],IOCapForm[1]];\n table5a[table5aRowDict[\"Total indirect taxes\"], ring] = sum(table5a[table5aTaxes, ring]);\nend\n\n#creating table 5b - allocation of investment expenditure (broken into subsections for dict referencing purposes)\n#subsection b is fixed capital expenditure\ntable5bNameCol = [\"Households\", \"Non-Financial Corporations\", \"Financial Corporations\", \"General Government\", \"Total\"];\ntable5bNameRow = [\"Domestic Commodities\", \"Imported Commodities, complementary\", \"Imported Commodities, competing\", \n\"Taxes less subsidies on products\", \"Total change in inventories\"];\ntable5bRowDict = Dict(table5bNameRow .=> [1:1:length(table5bNameRow);]);\ntable5bColDict = Dict(table5bNameCol .=> [1:1:length(table5bNameCol);]);\ntable5b = zeros(length(table5bNameRow), length(table5bNameCol));\n\n#filling in totals collumn from corresponding IO data\ntable5b[table5bRowDict[\"Domestic Commodities\"], table5bColDict[\"Total\"]] = sum(IO[IORowDict[\"T1\"],IOChangeInv]);\ntable5b[table5bRowDict[\"Imported Commodities, complementary\"], table5bColDict[\"Total\"]] = sum(IO[IORowDict[\"P5\"],IOChangeInv]);\ntable5b[table5bRowDict[\"Imported Commodities, competing\"], table5bColDict[\"Total\"]] = sum(IO[IORowDict[\"P6\"],IOChangeInv]);\ntable5b[table5bRowDict[\"Taxes less subsidies on products\"], table5bColDict[\"Total\"]] = sum(IO[IORowDict[\"P3\"],IOChangeInv]);\ntable5b[table5bRowDict[\"Total change in inventories\"], table5bColDict[\"Total\"]] = sum(table5b[:,table5bColDict[\"Total\"]]);\n\n#creating index variables for the measurements that we want\nASNAHouseCapChangeInv = findall(x -> occursin(\"Changes in inventories ;\", x), string.(ASNAHouseCap[1,:]));\nASNANonFinCapChangeInv = findall(x -> occursin(\"Changes in inventories ;\", x), string.(ASNANonFinCap[1,:]));\nASNAFinCapChangeInv = findall(x -> occursin(\"Changes in inventories ;\", x), string.(ASNAFinCap[1,:]));\nASNAGenGovCapChangeInv = findall(x -> occursin(\"General government ; Changes in inventories ;\", x), string.(ASNAGovCap[1,:]));\n\n#filling in totals row from ASNA Data\ntable5b[table5bRowDict[\"Total change in inventories\"], table5bColDict[\"Households\"]] = first(ASNAHouseCap[ASNAYearRow, ASNAHouseCapChangeInv]);\ntable5b[table5bRowDict[\"Total change in inventories\"], table5bColDict[\"Non-Financial Corporations\"]] = first(ASNANonFinCap[ASNAYearRow, ASNANonFinCapChangeInv]);\ntable5b[table5bRowDict[\"Total change in inventories\"], table5bColDict[\"Financial Corporations\"]] = first(ASNAFinCap[ASNAYearRow, ASNAFinCapChangeInv]);\ntable5b[table5bRowDict[\"Total change in inventories\"], table5bColDict[\"General Government\"]] = first(ASNAGovCap[ASNAYearRow, ASNAGenGovCapChangeInv]);\n\n#calculate non-total values with lagrangian optimisation\ntable5bScalingFact = abs(minimum(table5b)) * 2;\nmod5b = Model(Ipopt.Optimizer);\n@variable(mod5b, x[1:(length(table5bNameRow)-1), 1:(length(table5bNameCol)-1)]);\n@NLobjective(mod5b, Min, sum((x[i,j] - table5bScalingFact) ^ 2 for i in 1:(length(table5bNameRow)-1), j in 1:(length(table5bNameCol)-1)));\nfor i in 1:(length(table5bNameRow)-1);\n @constraint(mod5b, sum(x[:,i]) == table5b[table5bRowDict[\"Total change in inventories\"],i]+table5bScalingFact);\nend;\nfor i in 1:(length(table5bNameCol)-1);\n @constraint(mod5b, sum(x[i,:]) == table5b[i,table5bColDict[\"Total\"]]+table5bScalingFact);\nend;\noptimize!(mod5b);\n\n#plug back into table 5b\ntable5b[1:(length(table5bNameRow)-1),1:(length(table5bNameCol)-1)]=value.(x).-table5bScalingFact/4;\n\n\n#creating table 5c - allocation of investment expenditure (broken into subsections for dict referencing purposes)\n#subsection c is totals\ntable5cNameCol = [\"Households\", \"Non-Financial Corporations\", \"Financial Corporations\", \"General Government\", \"Total\"];\ntable5cNameRow = [\"Domestic Commodities\", \"Imported Commodities\", \"Taxes less subsidies on products\", \"Other taxes less subsidies on investment\", \"Total investment expenditure\"];\ntable5cRowDict = Dict(table5cNameRow .=> [1:1:length(table5cNameRow);]);\ntable5cColDict = Dict(table5cNameCol .=> [1:1:length(table5cNameCol);]);\ntable5c = zeros(length(table5cNameRow), length(table5cNameCol));\n\n#do totals calcuations to get all values in 5c\ntable5c[table5cRowDict[\"Domestic Commodities\"],:] = (table5a[table5aRowDict[\"Domestic Commodities\"],:] +\ntable5b[table5bRowDict[\"Domestic Commodities\"],:]);\ntable5c[table5cRowDict[\"Imported Commodities\"],:] = sum(eachrow(table5a[[table5aRowDict[\"Imported Commodities, competing\"],table5aRowDict[\"Imported Commodities, complementary\"]],:] +\ntable5b[[table5bRowDict[\"Imported Commodities, competing\"],table5bRowDict[\"Imported Commodities, complementary\"]],:]));\ntable5c[table5cRowDict[\"Taxes less subsidies on products\"],:] = table5a[table5aRowDict[\"Taxes less subsidies on products\"],:];\ntable5c[table5cRowDict[\"Other taxes less subsidies on investment\"],:] = (table5a[table5aRowDict[\"Other taxes less subsidies on investment\"],:] +\ntable5b[table5bRowDict[\"Taxes less subsidies on products\"],:]);\ntable5c[table5cRowDict[\"Total investment expenditure\"],:] = (table5a[table5aRowDict[\"Total fixed capital expenditure\"],:] +\ntable5b[table5bRowDict[\"Total change in inventories\"],:]);\n\n#table 6\n#importing relevant ASNA data\nASNAHouseInc = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204036_Household_Income_Account.xls\", \"Data1!A1:AN71\");\nASNANonFinInc = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204017_NonFin_Corp_Income_Account.xls\", \"Data1!A1:AE71\");\nASNAFinInc = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204025_Fin_Corp_Income_Account.xls\", \"Data1!A1:AD71\");\nASNAGovInc = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204030_GenGov_Income_Account.xls\", \"Data1!A1:DA71\");\nASNAExtInc = ExcelReaders.readxl(\"ASNAData\"*pathmark*\"5204043_External_Accounts.xls\", \"Data1!A1:AI71\");\n#initialising table\ntable6Name = [\"Households\", \"Non-Financial Corporations\", \"Financial Corporations\", \"General Government\", \"External\", \"Total\"];\ntable6Dict = Dict(table6Name .=> [1:1:length(table6Name);]);\ntable6 = zeros(length(table6Name),length(table6Name));\n#allocating total collumn and row data\ntable6[table6Dict[\"Total\"],table6Dict[\"Households\"]] = (first(ASNAHouseInc[ASNAYearRow,findall(x -> occursin(\"receivable - Interest\", x), string.(ASNAHouseInc[1,:]))])\n+first(ASNAHouseInc[ASNAYearRow,findall(x -> occursin(\"receivable - Imputed interest\", x), string.(ASNAHouseInc[1,:]))]));\ntable6[table6Dict[\"Total\"],table6Dict[\"Non-Financial Corporations\"]] = (first(ASNANonFinInc[ASNAYearRow,findall(x -> occursin(\"receivable - Interest\", x), string.(ASNANonFinInc[1,:]))])\n+first(ASNANonFinInc[ASNAYearRow,findall(x -> occursin(\"Property income attributed to insurance policyholders\", x), string.(ASNANonFinInc[1,:]))]));\ntable6[table6Dict[\"Total\"],table6Dict[\"Financial Corporations\"]] = first(ASNAFinInc[ASNAYearRow,findall(x -> occursin(\"receivable - Interest\", x), string.(ASNAFinInc[1,:]))]);\ntable6[table6Dict[\"Total\"],table6Dict[\"General Government\"]] = first(ASNAGovInc[ASNAYearRow,findall(x -> occursin(\"General government ; Property income receivable - Interest ;\", x), string.(ASNAGovInc[1,:]))]);\ntable6[table6Dict[\"Total\"],table6Dict[\"External\"]] = first(ASNAExtInc[ASNAYearRow,findall(x -> occursin(\"receivable - Interest\", x), string.(ASNAExtInc[1,:]))]);\n\ntable6[table6Dict[\"Households\"],table6Dict[\"Total\"]] = sum(ASNAHouseInc[ASNAYearRow,findall(x -> occursin(\"Property income payable - Interest\", x), string.(ASNAHouseInc[1,:]))]);\ntable6[table6Dict[\"Non-Financial Corporations\"],table6Dict[\"Total\"]] = first(ASNANonFinInc[ASNAYearRow,findall(x -> occursin(\"Property income payable - Interest\", x), string.(ASNANonFinInc[1,:]))]);\ntable6[table6Dict[\"Financial Corporations\"],table6Dict[\"Total\"]] = (first(ASNAFinInc[ASNAYearRow,findall(x -> occursin(\"Property income payable - Interest\", x), string.(ASNAFinInc[1,:]))])\n+first(ASNAFinInc[ASNAYearRow,findall(x -> occursin(\"payable - Property income attributed to insurance policy holders\", x), string.(ASNAFinInc[1,:]))]));\ntable6[table6Dict[\"General Government\"],table6Dict[\"Total\"]] = first(ASNAGovInc[ASNAYearRow,findall(x -> occursin(\"General government ; Property income payable - Total interest ;\", x), string.(ASNAGovInc[1,:]))]);\ntable6[table6Dict[\"External\"],table6Dict[\"Total\"]] = first(ASNAExtInc[ASNAYearRow,findall(x -> occursin(\"Property income payable - Interest\", x), string.(ASNAExtInc[1,:]))]);\n\nif 0.98*sum(table6[:,length(table6Name)])=0);\n@NLobjective(mod6, Min, sum((x[i,j]) ^ 2 for i in 1:(length(table6Name)-1), j in 1:(length(table6Name)-1)));\nfor i in 1:(length(table6Name)-1);\n @constraint(mod6, sum(x[:,i]) == table6[table6Dict[\"Total\"],i]-sum(table6[1:(length(table6Name)-1),i]));\nend;\nfor i in 1:(length(table6Name)-1);\n @constraint(mod6, sum(x[i,:]) == table6[i,table6Dict[\"Total\"]]-sum(table6[i,1:(length(table6Name)-1)]));\nend;\nfor i in 1:(length(table6Name)-1);\n @constraint(mod6, x[i,table6Dict[\"General Government\"]] == 0);\nend;\n@constraint(mod6, x[table6Dict[\"Households\"],table6Dict[\"Households\"]] == 0);\n@constraint(mod6, x[table6Dict[\"External\"],table6Dict[\"Households\"]] == 0);\n@constraint(mod6, x[table6Dict[\"Households\"],table6Dict[\"External\"]] == 0);\n@constraint(mod6, x[table6Dict[\"External\"],table6Dict[\"External\"]] == 0);\noptimize!(mod6);\n\ntable6[1:(length(table6Name)-1), 1:(length(table6Name)-1)] = table6[1:(length(table6Name)-1), 1:(length(table6Name)-1)] + value.(x);\n=#\n\n#solve for missing values with scaling\ntable6Step3 = zeros(length(table6Name),length(table6Name));\ntable6Step3Row = [table6Dict[\"Non-Financial Corporations\"],table6Dict[\"Financial Corporations\"],table6Dict[\"General Government\"]];\ntable6Step3Col = [table6Dict[\"Households\"],table6Dict[\"External\"]];\nfor i in table6Step3Col;\n for ring in table6Step3Row;\n table6Step3[ring,i] = (table6[table6Dict[\"Total\"],i]-sum(table6[1:(length(table6Name)-1),i]))*(\n table6[ring,table6Dict[\"Total\"]]-sum(table6[ring,1:(length(table6Name)-1)]))/sum(table6[\n table6Step3Row,table6Dict[\"Total\"]]-sum(eachcol(table6[table6Step3Row,1:(length(table6Name)-1)])));\n end\nend\ntable6 = table6+table6Step3;\n\ntable6Step4 = zeros(length(table6Name),length(table6Name));\ntable6Step4Row = [1:1:(length(table6Name)-1);];\ntable6Step4Col = [table6Dict[\"Non-Financial Corporations\"],table6Dict[\"Financial Corporations\"]];\nfor i in table6Step4Col;\n for ring in table6Step4Row;\n table6Step4[ring,i] = (table6[table6Dict[\"Total\"],i]-sum(table6[1:(length(table6Name)-1),i]))*(\n table6[ring,table6Dict[\"Total\"]]-sum(table6[ring,1:(length(table6Name)-1)]))/sum(table6[\n table6Step4Row,table6Dict[\"Total\"]]-sum(eachcol(table6[table6Step4Row,1:(length(table6Name)-1)])));\n end\nend\ntable6 = table6+table6Step4;\n\n#=convert dataframe to dictionary\nfunction increment!( d::Dict{S, T}, k::S, i::T) where {T<:Real, S<:Any}\n if haskey(d, k)\n d[k] += i\n else\n d[k] = i\n end\nend\nincrement!(d::Dict{S, T}, k::S ) where {T<:Real, S<:Any} = increment!( d, k, one(T))\n\nfunction df2dict( df::DataFrame, key_col::Symbol, val_col::Symbol=:null)\n keytype = typeof(df[1,key_col])\n if val_col == :null\n valtype = Int\n else\n valtype = typeof(df[1,val_col])\n end\n D = Dict{keytype, valtype}()\n for i=1:size(df,1)\n if !ismissing(df[i,key_col])\n if val_col == :null\n increment!( D, df[i,key_col] )\n elseif valtype <: Real\n increment!( D, df[i,key_col], df[i,val_col] )\n else\n if haskey(D, df[i,key_col])\n @warn(\"non-unique entry: $(df[i,key_col])\")\n else\n D[df[i,key_col]] = df[i,val_col]\n end\n end\n end\n end\n return D\nend\ndf[!, \"IOCode\"]=IOcode\ninsertcols!(df, 2, :name => vector)\nD = df2dict(df, :IOCode, :x3)\n=#", "meta": {"hexsha": "c43446e710ab08f85093d2582ded2692cd3a610e", "size": 19031, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "import-io-standard.jl", "max_stars_repo_name": "jaberdeen1/SAM", "max_stars_repo_head_hexsha": "8ccb905cb5076198fea0954247ddd01fbd393d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-02T08:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T08:22:22.000Z", "max_issues_repo_path": "import-io-standard.jl", "max_issues_repo_name": "jaberdeen1/SAM", "max_issues_repo_head_hexsha": "8ccb905cb5076198fea0954247ddd01fbd393d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "import-io-standard.jl", "max_forks_repo_name": "jaberdeen1/SAM", "max_forks_repo_head_hexsha": "8ccb905cb5076198fea0954247ddd01fbd393d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-05T05:42:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T05:42:58.000Z", "avg_line_length": 66.0798611111, "max_line_length": 214, "alphanum_fraction": 0.7374809521, "num_tokens": 5797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.19281264421804584}} {"text": "# TODO: Need to finish\n# Need to test\nfunction fit_fs_imcmc_pt!(cfs::ConstantsFS,\n dfs::DataFS;\n nmcmc::Int, nburn::Int, \n # Args for PT:\n tempers::Vector{Float64},\n inits=nothing,\n save_all_states=false,\n randpair=0.0,\n # End of PT Args.\n # Args are for iMCMC:\n batchprop::Float64=0.1,\n batchsizes=nothing,\n prior_thin::Int=2,\n imcmc_burn_prop=0.6,\n swap_freq::Float64=1.0,\n # End of iMCMC args.\n tfs::Union{Nothing, Vector{TunersFS}}=nothing,\n monitors=[monitor1, monitor2],\n fix::Vector{Symbol}=Symbol[],\n thins::Vector{Int}=[2, nsamps_to_thin(10, nmcmc)],\n ndden_samps::Int=200,\n printFreq::Int=0, \n checkpoint=0,\n computeDIC::Bool=true, computeLPML::Bool=true,\n computedden::Bool=true,\n sb_ibp::Bool=false,\n use_repulsive::Bool=true,\n Z_marg_lamgam::Float64=1.0,\n Z_marg_lamgam_decay_rate::Float64=100.0,\n Z_marg_lamgam_min::Float64=0.05,\n verbose::Int=1,\n time_updates=false,\n seed::Int=-1)\n\n printMsg(iter::Int, msg::String) = if printFreq > 0 && iter % printFreq == 0\n print(msg)\n end\n \n # How frequently to thin dden\n thin_dden = nsamps_to_thin(ndden_samps, nmcmc)\n\n # Number of temperatures\n num_tempers = length(tempers)\n\n @assert mod(num_tempers, 2) == 0\n if tfs != nothing\n @assert num_tempers == length(tfs)\n end\n\n # Assert swap frequency is in unit interval\n @assert 0 < swap_freq <= 1.0\n\n # Cache for swap counts\n swapcounts = zeros(Int, num_tempers, num_tempers)\n\n # Cache for pair counts\n paircounts = zeros(Int, num_tempers, num_tempers)\n\n # Set random seed if needed\n if seed >= 0\n Random.seed!(seed)\n end\n\n if verbose >= 1\n fixed_vars_str = join(fix, \", \")\n if fixed_vars_str == \"\"\n fixed_vars_str = \"nothing\"\n end\n println(\"fixing: $fixed_vars_str\")\n println(\"Use stick-breaking IBP: $(sb_ibp)\")\n println(\"Z_marg_lamgam: $(Z_marg_lamgam)\")\n println(\"Z_marg_lamgam_decay_rate: $(Z_marg_lamgam_decay_rate)\")\n println(\"Z_marg_lamgam_min: $(Z_marg_lamgam_min)\")\n println(\"use_repulsive: $(use_repulsive)\")\n println(\"batchprop: $(batchprop)\")\n println(\"batchsizes: $(batchsizes)\")\n flush(stdout)\n end\n\n @assert printFreq >= -1\n if printFreq == 0\n numPrints = 10\n printFreq = Int(ceil((nburn + nmcmc) / numPrints))\n end\n\n # Instantiate (but not initialize) CPO stream\n if computeLPML\n cpoStream = MCMC.CPOstream{Float64}()\n end\n\n # DIC\n if computeDIC\n dicStream = initDicStream(dfs.data)\n loglikeDIC(param::DICparam) = computeLoglikeDIC(dfs.data, param)\n\n convertStateToDicParam(s::State)::DICparam = let\n _convertStateToDicParam(s, cfs.constants, dfs.data)\n end\n end\n\n # Cache for data density\n dden = Matrix{Vector{Float64}}[]\n\n # Update function\n function update!(states, args, iter::Int)\n # Whether or not to marginalize over lambda and gamma.\n # We want to do this more often at the beginning, and less at the end.\n zmarg = ((Z_marg_lamgam - Z_marg_lamgam_min) * \n exp(-iter/Z_marg_lamgam_decay_rate) + \n Z_marg_lamgam_min) > rand()\n\n s_arg_vec = pmap(states, args) do s, arg\n tu = (arg[:c].constants.temper == 1) && time_updates\n \n # For reproducibility.\n if seed > - 1\n temper_idx = findfirst(tau -> tau == arg[:c].constants.temper, tempers)\n Random.seed!(iter + temper_idx + seed)\n end\n\n # Update state using trained prior\n imcmc_all_params = let\n iter < imcmc_burn_prop * nburn\n end\n\n update_via_trained_prior!(s, dfs, arg[:c], arg[:t],\n batchprop, prior_thin,\n batchsizes=batchsizes,\n fix=fix, use_repulsive=use_repulsive,\n Z_marg_lamgam=zmarg, sb_ibp=sb_ibp,\n time_updates=time_updates, temper=1.0,\n minibatch_update_all_params=imcmc_all_params,\n verbose=verbose-2)\n (s, arg)\n end\n\n states = [sa[1] for sa in s_arg_vec]\n args = [sa[2] for sa in s_arg_vec]\n\n # Swap Chains\n if verbose > 0\n println()\n end\n\n llf(s, tuner) = compute_marg_loglike(s, cfs.constants, dfs.data, tuner)\n\n if swap_freq > rand()\n swapchains!(states, llf, tempers,\n paircounts=paircounts, swapcounts=swapcounts,\n randpair=randpair, verbose=verbose)\n end\n if iter == nburn\n println(\"swapcounts / paircounts:\")\n println(swapcounts ./ (paircounts .+ 1e-6))\n println(\"Resetting swapcounts, paircounts ...\")\n swapcounts .= 0.0\n paircounts .= 0.0\n end\n\n # Pull out inner componenets for convenience\n s = states[1]\n c = args[1][:c]\n d = dfs\n ll = args[1][:ll]\n\n # # Append loglike\n append!(ll, compute_marg_loglike(s.theta, c.constants, d.data, 1.0))\n\n if computedden && iter > nburn && (iter - nburn) % thin_dden == 0\n # NOTE: `datadensity(s, c, d)` returns an (I x J) matrix of vectors of\n # length g.\n append!(dden, [datadensity(s.theta, c.constants, d.data)])\n end\n\n if computeLPML && iter > nburn\n # Inverse likelihood for each data point\n like = [[compute_like(i, n, s.theta, c.constants, d.data)\n for n in 1:d.data.N[i]] for i in 1:d.data.I]\n\n # Update (or initialize) CPO\n MCMC.updateCPO(cpoStream, vcat(like...))\n\n # Add to printMsg\n printMsg(iter, \" -- LPML: $(MCMC.computeLPML(cpoStream))\")\n end\n\n if computeDIC && iter > nburn\n # Update DIC\n MCMC.updateDIC(dicStream, s.theta, updateParams,\n loglikeDIC, convertStateToDicParam)\n\n # Add to printMsg\n printMsg(iter, \" -- DIC: $(MCMC.computeDIC(dicStream, loglikeDIC,\n paramMeanCompute))\")\n\n DICg = MCMC.DIC_gelman(ll[(nburn+1):end])\n printMsg(iter, \" -- DIC_gelman: $(DICg)\")\n end\n\n printMsg(iter, \"\\n\")\n flush(stdout)\n\n return states, args\n end\n\n # Create vectors of states\n states = if inits == nothing\n println(\"Using random inits!\")\n [let\n s = genInitialState(cfs.constants, dfs.data)\n s.eps .= 0.0\n StateFS{Float64}(s, dfs)\n end for _ in tempers]\n else\n @assert length(inits) == num_tempers\n for _init in inits\n _init.theta.eps .= 0.0\n end\n inits\n end\n\n # Create Args\n args = [let\n ll = Float64[] # FIXME\n c = deepcopy(cfs)\n c.constants.temper = tempers[i]\n t = if tfs == nothing\n TunersFS(Tuners(dfs.data.y, cfs.constants.K),\n states[1].theta, dfs.X)\n else\n tfs[i]\n end\n Dict(:ll => ll, :c => c, :t => t)\n end\n for i in 1:num_tempers]\n\n\n println(\"Running Gibbs sampler ...\")\n samples, states, args = let\n MCMC.gibbs_pt(states, args, update!, monitors=monitors,\n thins=thins, nmcmc=nmcmc, nburn=nburn,\n printFreq=printFreq, \n save_all_states=save_all_states,\n printlnAfterMsg=false)\n end\n\n out = Dict(:samples => samples,\n :lastState => states[1],\n :inits => inits,\n :c => cfs,\n :d => dfs,\n :lls => [arg[:ll] for arg in args],\n :save_all_states => save_all_states,\n :tempers => tempers,\n :swap_freq => swap_freq,\n :randpair => randpair,\n :paircounts => paircounts,\n :swapcounts => swapcounts)\n\n if computeDIC || computeLPML\n LPML = computeLPML ? MCMC.computeLPML(cpoStream) : NaN\n Dmean, pD = computeDIC ? MCMC.computeDIC(dicStream, loglikeDIC,\n paramMeanCompute,\n return_Dmean_pD=true) : (NaN, NaN)\n\n ll1 = args[1][:ll]\n DICg = MCMC.DIC_gelman(ll1[(nburn+1):end])\n\n metrics = Dict(:LPML => LPML,\n :DIC => Dmean + pD,\n :Dmean => Dmean,\n :pD => pD,\n :DICg => DICg)\n println()\n println(\"metrics:\")\n for (k, v) in metrics\n out[k] = v\n println(\"$k => $v\")\n end\n flush(stdout)\n end\n\n if computedden\n out[:dden] = dden\n end\n\n out[:nburn] = nburn\n out[:nmcmc] = nmcmc\n out[:batchprop] = batchprop\n out[:batchsizes] = batchsizes\n out[:prior_thin] = prior_thin\n\n # Return all states if requested\n if save_all_states\n out[:all_last_states] = deepcopy(states)\n end\n\n return out\nend\n", "meta": {"hexsha": "404e7715dd8e3171af5b918681e8f4a0e17f439b", "size": 9297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Model/FeatureSelect/fit_feature_select_imcmc_pt.jl", "max_stars_repo_name": "luiarthur/CytofRepFAM.jl", "max_stars_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Model/FeatureSelect/fit_feature_select_imcmc_pt.jl", "max_issues_repo_name": "luiarthur/CytofRepFAM.jl", "max_issues_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-05T01:26:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T04:13:03.000Z", "max_forks_repo_path": "src/Model/FeatureSelect/fit_feature_select_imcmc_pt.jl", "max_forks_repo_name": "luiarthur/CytofRepFAM.jl", "max_forks_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7847682119, "max_line_length": 79, "alphanum_fraction": 0.5372700871, "num_tokens": 2494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.1926815811419229}} {"text": "function applycnsics!(system::CVSystem,old=Dict(\"a\"=>0),restart=\"no\")\n if restart == \"no\"\n system.cns.H[1] = 1/system.heart.activation.th[1]*minTos;\n system.cns.Emaxlv[1] = system.heart.lv.Emax[1];\n system.cns.Emaxrv[1] = system.heart.rv.Emax[1];\n\n system.cns.R2L[1] = system.branches.term[13].R[2];\n system.cns.R3L[1] = system.branches.term[13].R[3];\n system.cns.R2U[1] = system.branches.term[54].R[2];\n system.cns.R3U[1] = system.branches.term[54].R[3];\n system.cns.C4L[1] = system.branches.term[13].C[4];\n system.cns.C5L[1] = system.branches.term[13].C[5];\n system.cns.C4U[1] = system.branches.term[54].C[4];\n system.cns.C5U[1] = system.branches.term[54].C[5];\n system.cns.V4L[1] = system.branches.term[13].V0[4];\n system.cns.V5L[1] = system.branches.term[13].V0[5];\n system.cns.V4U[1] = system.branches.term[54].V0[4];\n system.cns.V5U[1] = system.branches.term[54].V0[5];\n\n system.cns.gammalv = 0.8*system.cns.Emaxlv[1];\n system.cns.alphalv = 1.6*system.cns.Emaxlv[1] - system.cns.gammalv;\n system.cns.gammarv = 0.8*system.cns.Emaxrv[1];\n system.cns.alpharv = 1.6*system.cns.Emaxrv[1] - system.cns.gammarv;\n system.cns.gammaR2L = 0.6*system.cns.R2L[1];\n system.cns.alphaR2L = 2.2*system.cns.R2L[1] - system.cns.gammaR2L;\n system.cns.gammaR3L = 0.6*system.cns.R3L[1];\n system.cns.alphaR3L = 2.2*system.cns.R3L[1] - system.cns.gammaR3L;\n system.cns.gammaR2U = 0.6*system.cns.R2U[1];\n system.cns.alphaR2U = 2.2*system.cns.R2U[1] - system.cns.gammaR2U;\n system.cns.gammaR3U = 0.6*system.cns.R3U[1];\n system.cns.alphaR3U = 2.2*system.cns.R3U[1] - system.cns.gammaR3U;\n system.cns.gammaC4L = 1.1*system.cns.C4L[1];\n system.cns.alphaC4L = -0.7*system.cns.C4L[1] + system.cns.gammaC4L;\n system.cns.gammaC5L = 1.1*system.cns.C5L[1];\n system.cns.alphaC5L = -0.7*system.cns.C5L[1] + system.cns.gammaC5L;\n system.cns.gammaC4U = 1.1*system.cns.C4U[1];\n system.cns.alphaC4U = -0.7*system.cns.C4U[1] + system.cns.gammaC4U;\n system.cns.gammaC5U = 1.1*system.cns.C5U[1];\n system.cns.alphaC5U = -0.7*system.cns.C5U[1] + system.cns.gammaC5U;\n system.cns.gammaV4L = 1.05*system.cns.V4L[1];\n system.cns.alphaV4L = -0.85*system.cns.V4L[1] + system.cns.gammaV4L;\n system.cns.gammaV5L = 1.05*system.cns.V5L[1];\n system.cns.alphaV5L = -0.85*system.cns.V5L[1] + system.cns.gammaV5L;\n system.cns.gammaV4U = 1.05*system.cns.V4U[1];\n system.cns.alphaV4U = -0.85*system.cns.V4U[1] + system.cns.gammaV4U;\n system.cns.gammaV5U = 1.05*system.cns.V5U[1];\n system.cns.alphaV5U = -0.85*system.cns.V5U[1] + system.cns.gammaV5U;\n\n system.cns.ns = [0.25];\n system.cns.np = [0.25];\n elseif restart == \"yes\"\n system.cns.H[1] = old[\"H\"][end];\n system.cns.Emaxlv[1] = old[\"Emaxlv\"][end];\n system.cns.Emaxrv[1] = old[\"Emaxrv\"][end];\n\n system.cns.R2L[1] = old[\"R2L\"][end];\n system.cns.R3L[1] = old[\"R3L\"][end];\n system.cns.R2U[1] = old[\"R2U\"][end];\n system.cns.R3U[1] = old[\"R3U\"][end];\n system.cns.C4L[1] = old[\"C4L\"][end];\n system.cns.C5L[1] = old[\"C5L\"][end];\n system.cns.C4U[1] = old[\"C4U\"][end];\n system.cns.C5U[1] = old[\"C5U\"][end];\n system.cns.V4L[1] = old[\"V4L\"][end];\n system.cns.V5L[1] = old[\"V5L\"][end];\n system.cns.V4U[1] = old[\"V4U\"][end];\n system.cns.V5U[1] = old[\"V5U\"][end];\n\n system.cns.gammalv = old[\"gammalv\"];\n system.cns.alphalv = old[\"alphalv\"];\n system.cns.gammarv = old[\"gammarv\"];\n system.cns.alpharv = old[\"alpharv\"];\n system.cns.gammaR2L = old[\"gammaR2L\"];\n system.cns.alphaR2L = old[\"alphaR2L\"];\n system.cns.gammaR3L = old[\"gammaR3L\"];\n system.cns.alphaR3L = old[\"alphaR3L\"];\n system.cns.gammaR2U = old[\"gammaR2U\"];\n system.cns.alphaR2U = old[\"alphaR2U\"];\n system.cns.gammaR3U = old[\"gammaR3U\"];\n system.cns.alphaR3U = old[\"alphaR3U\"];\n system.cns.gammaC4L = old[\"gammaC4L\"];\n system.cns.alphaC4L = old[\"alphaC4L\"];\n system.cns.gammaC5L = old[\"gammaC5L\"];\n system.cns.alphaC5L = old[\"alphaC5L\"];\n system.cns.gammaC4U = old[\"gammaC4U\"];\n system.cns.alphaC4U = old[\"alphaC4U\"];\n system.cns.gammaC5U = old[\"gammaC5U\"];\n system.cns.alphaC5U = old[\"alphaC5U\"];\n system.cns.gammaV4L = old[\"gammaV4L\"];\n system.cns.alphaV4L = old[\"alphaV4L\"];\n system.cns.gammaV5L = old[\"gammaV5L\"];\n system.cns.alphaV5L = old[\"alphaV5L\"];\n system.cns.gammaV4U = old[\"gammaV4U\"];\n system.cns.alphaV4U = old[\"alphaV4U\"];\n system.cns.gammaV5U = old[\"gammaV5U\"];\n system.cns.alphaV5U = old[\"alphaV5U\"];\n\n system.cns.ns = [old[\"ns\"][end]];\n system.cns.np = [old[\"np\"][end]];\n end\n system.cns.alphaH = 2.1563;\n system.cns.betaH = 0.5313;\n system.cns.gammaH = 0.8438;\nend\n", "meta": {"hexsha": "8a92062542657cb5ae1b2ca1912d75c7aa6fa432", "size": 5077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/applycnsics.jl", "max_stars_repo_name": "dcanuto/CardioModeling", "max_stars_repo_head_hexsha": "39d308cc784e3a1ed0f52e96fe0463ac2539372b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/applycnsics.jl", "max_issues_repo_name": "dcanuto/CardioModeling", "max_issues_repo_head_hexsha": "39d308cc784e3a1ed0f52e96fe0463ac2539372b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/applycnsics.jl", "max_forks_repo_name": "dcanuto/CardioModeling", "max_forks_repo_head_hexsha": "39d308cc784e3a1ed0f52e96fe0463ac2539372b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-19T22:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T22:11:58.000Z", "avg_line_length": 48.3523809524, "max_line_length": 76, "alphanum_fraction": 0.5918849714, "num_tokens": 1969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.1924809289863305}} {"text": "\n\"\"\"\n flux_first_order!(\n bl::BalanceLaw,\n flux::Grad,\n state::Vars,\n aux::Vars,\n t::Real\n )\n\nComputes (and assembles) flux terms `F¹(Y)` in:\n\n```\n∂Y\n-- + ∇ • F¹(Y) + ∇ • F²(Y,G) = S(Y, G), G = ∇Y\n∂t\n```\n\nComputes and assembles non-diffusive\nfluxes in the model equations.\n\nFor this fallback to work, several methods must be defined:\n - [`prognostic_vars`](@ref)\n - [`eq_tends`](@ref)\n - [`get_prog_state`](@ref)\noptionally,\n - [`precompute`](@ref)\nand individual [`flux`](@ref) kernels that\nare defined for each type that `eq_tends` returns.\n\"\"\"\n@inline function flux_first_order!(\n bl::BalanceLaw,\n flux,\n state,\n aux,\n t,\n direction,\n)\n\n tend = Flux{FirstOrder}()\n _args = (; state, aux, t, direction)\n args = merge(_args, (precomputed = precompute(bl, _args, tend),))\n\n map(prognostic_vars(bl)) do prog\n var, name = get_prog_state(flux, prog)\n val = Σfluxes(prog, eq_tends(prog, bl, tend), bl, args)\n setproperty!(var, name, val)\n end\n nothing\nend\n\n\"\"\"\n flux_second_order!(\n bl::BalanceLaw,\n flux::Grad,\n state::Vars,\n diffusive::Vars,\n hyperdiffusive::Vars,\n aux::Vars,\n t::Real\n )\n\nComputes (and assembles) flux terms `F²(Y, G)` in:\n\n```\n∂Y\n-- + ∇ • F¹(Y) + ∇ • F²(Y,G) = S(Y, G), G = ∇Y\n∂t\n```\n\nDiffusive fluxes in BalanceLaw. Viscosity, diffusivity are calculated\nin the turbulence subcomponent and accessed within the diffusive flux\nfunction. Contributions from subcomponents are then assembled (pointwise).\n\nFor this fallback to work, several methods must be defined:\n - [`prognostic_vars`](@ref)\n - [`eq_tends`](@ref)\n - [`get_prog_state`](@ref)\noptionally,\n - [`precompute`](@ref)\nand individual [`flux`](@ref) kernels that\nare defined for each type that `eq_tends` returns.\n\"\"\"\n@inline function flux_second_order!(\n bl::BalanceLaw,\n flux,\n state,\n diffusive,\n hyperdiffusive,\n aux,\n t,\n)\n tend = Flux{SecondOrder}()\n _args = (; state, aux, t, diffusive, hyperdiffusive)\n args = merge(_args, (precomputed = precompute(bl, _args, tend),))\n\n map(prognostic_vars(bl)) do prog\n var, name = get_prog_state(flux, prog)\n val = Σfluxes(prog, eq_tends(prog, bl, tend), bl, args)\n setproperty!(var, name, val)\n end\n nothing\nend\n\n\"\"\"\n source!(\n bl::BalanceLaw,\n source::Vars,\n state::Vars,\n diffusive::Vars,\n aux::Vars,\n t::Real,\n direction::Direction,\n )\n\nComputes (and assembles) source terms `S(Y)` in:\n\n```\n∂Y\n-- + ∇ • F¹(Y) + ∇ • F²(Y,G) = S(Y, G), G = ∇Y\n∂t\n```\n\nFor this fallback to work, several methods must be defined:\n - [`prognostic_vars`](@ref)\n - [`eq_tends`](@ref)\n - [`get_prog_state`](@ref)\noptionally,\n - [`precompute`](@ref)\nand individual [`source`](@ref) kernels that\nare defined for each type that `eq_tends` returns.\n\"\"\"\nfunction source!(bl::BalanceLaw, source, state, diffusive, aux, t, direction)\n tend = Source()\n _args = (; state, aux, t, direction, diffusive)\n args = merge(_args, (precomputed = precompute(bl, _args, tend),))\n\n map(prognostic_vars(bl)) do prog\n var, name = get_prog_state(source, prog)\n val = Σsources(prog, eq_tends(prog, bl, tend), bl, args)\n setproperty!(var, name, val)\n end\n nothing\nend\n", "meta": {"hexsha": "cc02eae8b6ccde3740b49273b8a2a2462f5aac0b", "size": 3358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BalanceLaws/kernels.jl", "max_stars_repo_name": "ErikQQY/ClimateMachine.jl", "max_stars_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 256, "max_stars_repo_stars_event_min_datetime": "2020-05-06T08:03:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:01:20.000Z", "max_issues_repo_path": "src/BalanceLaws/kernels.jl", "max_issues_repo_name": "ErikQQY/ClimateMachine.jl", "max_issues_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1174, "max_issues_repo_issues_event_min_datetime": "2020-05-06T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T17:51:13.000Z", "max_forks_repo_path": "src/BalanceLaws/kernels.jl", "max_forks_repo_name": "ErikQQY/ClimateMachine.jl", "max_forks_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2020-05-08T02:28:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T22:44:56.000Z", "avg_line_length": 23.1586206897, "max_line_length": 77, "alphanum_fraction": 0.6078022633, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1923399908898706}} {"text": "# Conversions\n# -----------\n\n# convert(C, c) might be called as convert(RGB, c) or convert(RGB{Float32}, c)\n# This is handled in ColorTypes, which calls functions\n# _convert(::Type{Cdest}, ::Type{Odest}, ::Type{Osrc}, c)\n# _convert(::Type{Cdest}, ::Type{Odest}, ::Type{Osrc}, c, alpha)\n# Here are the argument types:\n# - Cdest may be any concrete Color{T,N} type. For parametric Color types\n# it _always_ has the desired element type (e.g., Float32), so it's\n# safe to dispatch on Cdest{T}.\n# - Odest and Osrc are Color subtypes, i.e., things like RGB\n# or HSV. They have no element type.\n# - c is the Colorant object you wish to convert.\n# - alpha, if present, is a user-supplied alpha value (to be used in\n# place of any default alpha or alpha present in c).\n#\n# The motivation for this arrangement is that Julia doesn't (yet) support\n# \"triangular dispatch\", e.g.,\n# convert{T,C}(::Type{C{T}}, c)\n# The various arguments of _convert therefore \"peel off\" element types\n# (or guarantee them) so that comparisons may be made via\n# dispatch. The alternative design is\n# for C in parametric_colors\n# @eval convert{T}(::Type{$C{T}}, c) = ...\n# @eval convert( ::Type{$C}, c) = convert($C{eltype(c)}, c)\n# ...\n# end\n# but this requires a fair amount of codegen (especially for all\n# the various alpha variants) and can break if not all C support\n# the same eltypes.\n#\n# Note that ColorTypes handles the cases where Odest == Osrc, or they\n# are both subtypes of AbstractRGB. Therefore, here we only have to\n# deal with conversions between different spaces.\n\n\nfunction ColorTypes._convert{Cdest<:TransparentColor,Odest,Osrc}(::Type{Cdest}, ::Type{Odest}, ::Type{Osrc}, p, alpha)\n # Convert the base color\n c = cnvt(color_type(Cdest), color(p))\n # Append the alpha\n ColorTypes._convert(Cdest, Odest, Odest, c, alpha)\nend\nfunction ColorTypes._convert{Cdest<:TransparentColor,Odest,Osrc}(::Type{Cdest}, ::Type{Odest}, ::Type{Osrc}, p)\n c = cnvt(color_type(Cdest), color(p))\n ColorTypes._convert(Cdest, Odest, Odest, c, alpha(p))\nend\n\nColorTypes._convert{Cdest<:Color,Odest,Osrc}(::Type{Cdest}, ::Type{Odest}, ::Type{Osrc}, c) = cnvt(Cdest, c)\n\n\n# Fallback to catch undefined operations\ncnvt{C<:Color}(::Type{C}, c::TransparentColor) = cnvt(C, color(c))\ncnvt{C}(::Type{C}, c) = convert(C, c)\n\n# Conversions from grayscale\n# --------------------------\ncnvt{C<:Color3}(::Type{C}, g::AbstractGray) = cnvt(C, convert(RGB{eltype(C)}, g))\n\n\nmacro mul3x3(T, M, c1, c2, c3)\n esc(quote\n @inbounds ret = $T($M[1,1]*$c1 + $M[1,2]*$c2 + $M[1,3]*$c3,\n $M[2,1]*$c1 + $M[2,2]*$c2 + $M[2,3]*$c3,\n $M[3,1]*$c1 + $M[3,2]*$c2 + $M[3,3]*$c3)\n ret\n end)\nend\n\n# Everything to RGB\n# -----------------\n\ncorrect_gamut{CV<:AbstractRGB}(c::CV) = CV(clamp01(red(c)), clamp01(green(c)), clamp01(blue(c)))\nclamp01{T<:Fractional}(v::T) = ifelse(v < zero(T), zero(T), ifelse(v > one(T), one(T), v))\n\nfunction srgb_compand(v)\n v <= 0.0031308 ? 12.92v : 1.055v^(1/2.4) - 0.055\nend\n\ncnvt{CV<:AbstractRGB}(::Type{CV}, c::AbstractRGB) = CV(red(c), green(c), blue(c))\n\nfunction cnvt{CV<:AbstractRGB}(::Type{CV}, c::HSV)\n h = c.h / 60\n i = floor(Int, h)\n f = h - i\n if i & 1 == 0\n f = 1 - f\n end\n m = c.v * (1 - c.s)\n n = c.v * (1 - c.s * f)\n if i == 6 || i == 0; CV(c.v, n, m)\n elseif i == 1; CV(n, c.v, m)\n elseif i == 2; CV(m, c.v, n)\n elseif i == 3; CV(m, n, c.v)\n elseif i == 4; CV(n, m, c.v)\n else; CV(c.v, m, n)\n end\nend\n\nfunction qtrans(u, v, hue)\n if hue > 360; hue -= 360\n elseif hue < 0; hue += 360\n end\n\n if hue < 60; u + (v - u) * hue / 60\n elseif hue < 180; v\n elseif hue < 240; u + (v - u) * (240 - hue) / 60\n else; u\n end\nend\n\nfunction cnvt{CV<:AbstractRGB}(::Type{CV}, c::HSL)\n v = c.l <= 0.5 ? c.l * (1 + c.s) : c.l + c.s - (c.l * c.s)\n u = 2 * c.l - v\n\n if c.s == 0; CV(c.l, c.l, c.l)\n else; CV(qtrans(u, v, c.h + 120),\n qtrans(u, v, c.h),\n qtrans(u, v, c.h - 120))\n end\nend\n\nfunction cnvt{CV<:AbstractRGB}(::Type{CV}, c::HSI)\n h, s, i = c.h, c.s, c.i\n while(h > 360) h -= 360 end\n while(h < 0) h += 360 end\n is = i*s\n if h < 120\n cosr = cosd(h) / cosd(60-h)\n CV(i+is*cosr, i+is*(1-cosr), i-is)\n elseif h < 240\n cosr = cosd(h-120) / cosd(180-h)\n CV(i-is, i+is*cosr, i+is*(1-cosr))\n else\n cosr = cosd(h-240) / cosd(300-h)\n CV(i+is*(1-cosr), i-is, i+is*cosr)\n end\nend\n\nfunction cnvt{CV<:AbstractRGB}(::Type{CV}, c::XYZ)\n r = 3.2404542*c.x - 1.5371385*c.y - 0.4985314*c.z\n g = -0.9692660*c.x + 1.8760108*c.y + 0.0415560*c.z\n b = 0.0556434*c.x - 0.2040259*c.y + 1.0572252*c.z\n CV(clamp01(srgb_compand(r)),\n clamp01(srgb_compand(g)),\n clamp01(srgb_compand(b)))\nend\n\nfunction cnvt{CV<:AbstractRGB}(::Type{CV}, c::YIQ)\n cc = correct_gamut(c)\n CV(clamp01(cc.y+0.9563*cc.i+0.6210*cc.q),\n clamp01(cc.y-0.2721*cc.i-0.6474*cc.q),\n clamp01(cc.y-1.1070*cc.i+1.7046*cc.q))\nend\n\nfunction cnvt{CV<:AbstractRGB}(::Type{CV}, c::YCbCr)\n cc = correct_gamut(c)\n ny = cc.y - 16\n ncb = cc.cb - 128\n ncr = cc.cr - 128\n CV(clamp01(0.004567ny - 1.39135e-7ncb + 0.0062586ncr),\n clamp01(0.004567ny - 0.00153646ncb - 0.0031884ncr),\n clamp01(0.004567ny + 0.00791058ncb - 2.79201e-7ncr))\nend\n\ncnvt{CV<:AbstractRGB}(::Type{CV}, c::LCHab) = cnvt(CV, convert(Lab{eltype(c)}, c))\ncnvt{CV<:AbstractRGB}(::Type{CV}, c::LCHuv) = cnvt(CV, convert(Luv{eltype(c)}, c))\ncnvt{CV<:AbstractRGB}(::Type{CV}, c::Color3) = cnvt(CV, convert(XYZ{eltype(c)}, c))\n\ncnvt{CV<:AbstractRGB{UFixed8}}(::Type{CV}, c::RGB24) = CV(UFixed8(c.color&0x00ff0000>>>16,0), UFixed8(c.color&0x0000ff00>>>8,0), UFixed8(c.color&0x000000ff,0))\ncnvt{CV<:AbstractRGB}(::Type{CV}, c::RGB24) = CV((c.color&0x00ff0000>>>16)/255, ((c.color&0x0000ff00)>>>8)/255, (c.color&0x000000ff)/255)\n\nfunction cnvt{CV<:AbstractRGB}(::Type{CV}, c::AbstractGray)\n g = convert(eltype(CV), gray(c))\n CV(g, g, g)\nend\n\n\n# Everything to HSV\n# -----------------\n\nfunction cnvt{T}(::Type{HSV{T}}, c::AbstractRGB)\n c_min = Float64(min(red(c), green(c), blue(c)))\n c_max = Float64(max(red(c), green(c), blue(c)))\n if c_min == c_max\n return HSV{T}(zero(T), zero(T), c_max)\n end\n\n if c_min == red(c)\n f = Float64(green(c)) - Float64(blue(c))\n i = 3\n elseif c_min == green(c)\n f = Float64(blue(c)) - Float64(red(c))\n i = 5\n else\n f = Float64(red(c)) - Float64(green(c))\n i = 1\n end\n\n HSV{T}(60 * (i - f / (c_max - c_min)),\n (c_max - c_min) / c_max,\n c_max)\nend\n\n\ncnvt{T}(::Type{HSV{T}}, c::Color3) = cnvt(HSV{T}, convert(RGB{T}, c))\n\n\n# Everything to HSL\n# -----------------\n\nfunction cnvt{T}(::Type{HSL{T}}, c::AbstractRGB)\n r, g, b = T(red(c)), T(green(c)), T(blue(c))\n c_min = min(r, g, b)\n c_max = max(r, g, b)\n l = (c_max + c_min) / 2\n\n if c_max == c_min\n return HSL(zero(T), zero(T), l)\n end\n\n if l < 0.5; s = (c_max - c_min) / (c_max + c_min)\n else; s = (c_max - c_min) / (convert(T, 2) - c_max - c_min)\n end\n\n if c_max == red(c)\n h = (g - b) / (c_max - c_min)\n elseif c_max == green(c)\n h = convert(T, 2) + (b - r) / (c_max - c_min)\n else\n h = convert(T, 4) + (r - g) / (c_max - c_min)\n end\n\n h *= 60\n if h < 0\n h += 360\n elseif h > 360\n h -= 360\n end\n\n HSL{T}(h,s,l)\nend\n\n\ncnvt{T}(::Type{HSL{T}}, c::Color3) = cnvt(HSL{T}, convert(RGB{T}, c))\n\n\n# Everything to HSI\n# -----------------\n\nfunction cnvt{T}(::Type{HSI{T}}, c::AbstractRGB)\n rgb = correct_gamut(c)\n r, g, b = red(rgb), green(rgb), blue(rgb)\n isum = r+g+b\n i = isum/3\n m = min(r, g, b)\n s = i > 0 ? 1-m/i : 1-one(i)/one(i) # the latter is a type-stable 0\n val = (r-(g+b)/2)/sqrt(r^2+g^2+b^2-r*g-r*b-g*b)\n val = clamp(val, -one(val), one(val))\n h = acosd(val)\n if b > g\n h = 360-h\n end\n HSI{T}(h, s, i)\nend\n\ncnvt{T}(::Type{HSI{T}}, c::Color3) = cnvt(HSI{T}, convert(RGB{T}, c))\n\n# Everything to XYZ\n# -----------------\n\nfunction invert_rgb_compand(v)\n v <= 0.04045 ? v/12.92 : ((v+0.055) /1.055)^2.4\nend\n\nfunction cnvt{T}(::Type{XYZ{T}}, c::AbstractRGB)\n r, g, b = invert_rgb_compand(red(c)), invert_rgb_compand(green(c)), invert_rgb_compand(blue(c))\n XYZ{T}(0.4124564*r + 0.3575761*g + 0.1804375*b,\n 0.2126729*r + 0.7151522*g + 0.0721750*b,\n 0.0193339*r + 0.1191920*g + 0.9503041*b)\nend\n\n\ncnvt{T}(::Type{XYZ{T}}, c::HSV) = cnvt(XYZ{T}, convert(RGB{T}, c))\ncnvt{T}(::Type{XYZ{T}}, c::HSL) = cnvt(XYZ{T}, convert(RGB{T}, c))\ncnvt{T}(::Type{XYZ{T}}, c::HSI) = cnvt(XYZ{T}, convert(RGB{T}, c))\n\n\nfunction cnvt{T}(::Type{XYZ{T}}, c::xyY)\n X = c.Y*c.x/c.y\n Z = c.Y*(1-c.x-c.y)/c.y\n XYZ{T}(X, c.Y, Z)\nend\n\n\nconst xyz_epsilon = 216 / 24389\nconst xyz_kappa = 24389 / 27\n\nconvert(::Type{XYZ}, c, wp::XYZ) = convert(XYZ{eltype(wp)}, c, wp)\nconvert{T}(::Type{XYZ{T}}, c, wp::XYZ) = cnvt(XYZ{T}, c, wp)\nfunction cnvt{T}(::Type{XYZ{T}}, c::Lab, wp::XYZ)\n fy = (c.l + 16) / 116\n fx = c.a / 500 + fy\n fz = fy - c.b / 200\n\n fx3 = fx^3\n fz3 = fz^3\n\n x = fx3 > xyz_epsilon ? fx3 : (116fx - 16) / xyz_kappa\n y = c.l > xyz_kappa * xyz_epsilon ? ((c. l+ 16) / 116)^3 : c.l / xyz_kappa\n z = fz3 > xyz_epsilon ? fz3 : (116fz - 16) / xyz_kappa\n\n XYZ{T}(x*wp.x, y*wp.y, z*wp.z)\nend\n\n\ncnvt{T}(::Type{XYZ{T}}, c::Lab) = convert(XYZ{T}, c, WP_DEFAULT)\ncnvt{T}(::Type{XYZ{T}}, c::LCHab) = cnvt(XYZ{T}, convert(Lab{T}, c))\ncnvt{T}(::Type{XYZ{T}}, c::DIN99) = cnvt(XYZ{T}, convert(Lab{T}, c))\ncnvt{T}(::Type{XYZ{T}}, c::DIN99o) = cnvt(XYZ{T}, convert(Lab{T}, c))\n\ncnvt{T<:UFixed}(::Type{XYZ{T}}, c::LCHab) = cnvt(XYZ{T}, convert(Lab{eltype(c)}, c))\ncnvt{T<:UFixed}(::Type{XYZ{T}}, c::DIN99) = cnvt(XYZ{T}, convert(Lab{eltype(c)}, c))\ncnvt{T<:UFixed}(::Type{XYZ{T}}, c::DIN99o) = cnvt(XYZ{T}, convert(Lab{eltype(c)}, c))\n\n\nfunction xyz_to_uv(c::XYZ)\n d = c.x + 15c.y + 3c.z\n d==0 && return (d, d)\n u = 4c.x / d\n v = 9c.y / d\n return (u, v)\nend\n\n\nfunction cnvt{T}(::Type{XYZ{T}}, c::Luv, wp::XYZ = WP_DEFAULT)\n (u_wp, v_wp) = xyz_to_uv(wp)\n\n a = (52 * (c.l==0 ? zero(T) : c.l / (c.u + 13 * c.l * u_wp)) - 1) / 3\n y = c.l > xyz_kappa * xyz_epsilon ? wp.y * ((c.l + 16) / 116)^3 : wp.y * c.l / xyz_kappa\n b = -5y\n d = y * (39 * (c.l==0 ? zero(T) : c.l / (c.v + 13 * c.l * v_wp)) - 5)\n x = d==b ? zero(T) : (d - b) / (a + 1/3)\n z = a * x + b + zero(T)\n\n XYZ{T}(x, y, z)\nend\n\ncnvt{T}(::Type{XYZ{T}}, c::LCHuv) = cnvt(XYZ{T}, convert(Luv{T}, c))\n\n\nfunction cnvt{T}(::Type{XYZ{T}}, c::DIN99d)\n\n # Go back to C-h space\n # FIXME: Clean this up (why is there no atan2d?)\n h = rad2deg(atan2(c.b,c.a)) + 50\n while h > 360; h -= 360; end\n while h < 0; h += 360; end\n\n C = sqrt(c.a^2 + c.b^2)\n\n # Intermediate terms\n G = (exp(C/22.5)-1)/0.06\n f = G*sind(h - 50)\n ee = G*cosd(h - 50)\n\n l = (exp(c.l/325.22)-1)/0.0036\n # a = ee*cosd(50) - f/1.14*sind(50)\n a = ee*0.6427876096865393 - f/1.14*0.766044443118978\n # b = ee*sind(50) - f/1.14*cosd(50)\n b = ee*0.766044443118978 - f/1.14*0.6427876096865393\n\n adj = convert(XYZ, Lab(l, a, b))\n\n XYZ{T}((adj.x + 0.12*adj.z)/1.12, adj.y, adj.z)\n\nend\n\n\nfunction cnvt{T}(::Type{XYZ{T}}, c::LMS)\n @mul3x3 XYZ{T} CAT02_INV c.l c.m c.s\nend\n\n\ncnvt{T}(::Type{XYZ{T}}, c::YIQ) = cnvt(XYZ{T}, convert(RGB{T}, c))\ncnvt{T}(::Type{XYZ{T}}, c::YCbCr) = cnvt(XYZ{T}, convert(RGB{T}, c))\n\ncnvt{T}(::Type{XYZ{T}}, c::RGB24) = cnvt(XYZ{T}, convert(RGB{T}, c))\n\n# Everything to xyY\n# -----------------\n\nfunction cnvt{T}(::Type{xyY{T}}, c::XYZ)\n\n x = c.x/(c.x + c.y + c.z)\n y = c.y/(c.x + c.y + c.z)\n\n xyY{T}(x, y, convert(typeof(x), c.y))\n\nend\n\ncnvt{T}(::Type{xyY{T}}, c::Color3) = cnvt(xyY{T}, convert(XYZ{T}, c))\n\n\n\n# Everything to Lab\n# -----------------\n\ncnvt{T}(::Type{Lab{T}}, c::AbstractRGB) = convert(Lab{T}, convert(XYZ{T}, c))\ncnvt{T}(::Type{Lab{T}}, c::HSV) = cnvt(Lab{T}, convert(RGB{T}, c))\ncnvt{T}(::Type{Lab{T}}, c::HSL) = cnvt(Lab{T}, convert(RGB{T}, c))\n\nconvert{T}(::Type{Lab{T}}, c, wp::XYZ) = cnvt(Lab{T}, c, wp)\nconvert(::Type{Lab}, c, wp::XYZ) = cnvt(Lab{eltype(wp)}, c, wp)\n\nfunction fxyz2lab(v)\n v > xyz_epsilon ? cbrt(v) : (xyz_kappa * v + 16) / 116\nend\nfunction cnvt{T}(::Type{Lab{T}}, c::XYZ, wp::XYZ)\n fx, fy, fz = fxyz2lab(c.x / wp.x), fxyz2lab(c.y / wp.y), fxyz2lab(c.z / wp.z)\n Lab{T}(116fy - 16, 500(fx - fy), 200(fy - fz))\nend\n\n\ncnvt{T}(::Type{Lab{T}}, c::XYZ{T}) = cnvt(Lab{T}, c, WP_DEFAULT)\n\n\nfunction cnvt{T}(::Type{Lab{T}}, c::LCHab)\n hr = deg2rad(c.h)\n Lab{T}(c.l, c.c * cos(hr), c.c * sin(hr))\nend\n\n\nfunction cnvt{T}(::Type{Lab{T}}, c::DIN99)\n\n # We assume the adjustment parameters are always 1; the standard recommends\n # that they not be changed from these values.\n kch = 1\n ke = 1\n\n # Calculate Chroma (C99) in the DIN99 space\n cc = sqrt(c.a^2 + c.b^2)\n\n # NOTE: This is calculated in degrees, against the standard, to save\n # computation steps later.\n if (c.a > 0 && c.b >= 0)\n h = atand(c.b/c.a)\n elseif (c.a == 0 && c.b > 0)\n h = 90\n elseif (c.a < 0)\n h = 180+atand(c.b/c.a)\n elseif (c.a == 0 && c.b < 0)\n h = 270\n elseif (c.a > 0 && c.b <= 0)\n h = 360 + atand(c.b/c.a)\n else\n h = 0\n end\n\n # Temporary variable for chroma\n g = (e^(0.045*cc*kch*ke)-1)/0.045\n\n # Temporary redness\n ee = g*cosd(h)\n\n # Temporary yellowness\n f = g*sind(h)\n\n # CIELAB a*b*\n # ciea = ee*cosd(16) - (f/0.7)*sind(16)\n ciea = ee*0.9612616959383189 - (f/0.7)*0.27563735581699916\n # cieb = ee*sind(16) + (f/0.7)*cosd(16)\n cieb = ee*0.27563735581699916 + (f/0.7)*0.9612616959383189\n\n # CIELAB L*\n ciel = (e^(c.l*ke/105.51)-1)/0.0158\n\n Lab{T}(ciel, ciea, cieb)\nend\n\n\nfunction cnvt{T}(::Type{Lab{T}}, c::DIN99o)\n\n # We assume the adjustment parameters are always 1; the standard recommends\n # that they not be changed from these values.\n kch = 1\n ke = 1\n\n # Calculate Chroma (C99) in the DIN99o space\n co = sqrt(c.a^2 + c.b^2)\n\n # hue angle h99o\n h = atan2(c.b, c.a)\n\n # revert rotation by 26°\n ho= rad2deg(h)-26\n\n # revert logarithmic chroma compression\n g = (e^(co*kch*ke/23.0)-1)/0.075\n\n # Temporary redness\n eo = g*cosd(ho)\n\n # Temporary yellowness\n fo = g*sind(ho)\n\n # CIELAB a*b* (revert b* axis compression)\n # ciea = eo*cosd(26) - (fo/0.83)*sind(26)\n ciea = eo*0.898794046299167 - (fo/0.83)*0.4383711467890774\n # cieb = eo*sind(26) + (fo/0.83)*cosd(26)\n cieb = eo*0.4383711467890774 + (fo/0.83)*0.898794046299167\n\n # CIELAB L* (revert logarithmic lightness compression)\n ciel = (e^(c.l*ke/303.67)-1)/0.0039\n\n Lab{T}(ciel, ciea, cieb)\nend\n\n\ncnvt{T}(::Type{Lab{T}}, c::Color3) = cnvt(Lab{T}, convert(XYZ{T}, c))\n\n\n# Everything to Luv\n# -----------------\n\ncnvt{T}(::Type{Luv{T}}, c::AbstractRGB) = cnvt(Luv{T}, convert(XYZ{T}, c))\ncnvt{T}(::Type{Luv{T}}, c::HSV) = cnvt(Luv{T}, convert(RGB{T}, c))\ncnvt{T}(::Type{Luv{T}}, c::HSL) = cnvt(Luv{T}, convert(RGB{T}, c))\n\nconvert{T}(::Type{Luv{T}}, c, wp::XYZ) = cnvt(Luv{T}, c, wp)\nconvert(::Type{Luv}, c, wp::XYZ) = cnvt(Luv{eltype(wp)}, c, wp)\n\nfunction cnvt{T}(::Type{Luv{T}}, c::XYZ, wp::XYZ = WP_DEFAULT)\n (u_wp, v_wp) = xyz_to_uv(wp)\n (u_, v_) = xyz_to_uv(c)\n\n y = c.y / wp.y\n\n l = y > xyz_epsilon ? 116 * cbrt(y) - 16 : xyz_kappa * y\n u = 13 * l * (u_ - u_wp) + zero(T)\n v = 13 * l * (v_ - v_wp) + zero(T)\n\n Luv{T}(l, u, v)\nend\n\n\nfunction cnvt{T}(::Type{Luv{T}}, c::LCHuv)\n hr = deg2rad(c.h)\n Luv{T}(c.l, c.c * cos(hr), c.c * sin(hr))\nend\n\n\ncnvt{T}(::Type{Luv{T}}, c::Color3) = cnvt(Luv{T}, convert(XYZ{T}, c))\n\n\n# Everything to LCHuv\n# -------------------\n\nfunction cnvt{T}(::Type{LCHuv{T}}, c::Luv)\n h = rad2deg(atan2(c.v, c.u))\n while h > 360; h -= 360; end\n while h < 0; h += 360; end\n LCHuv{T}(c.l, sqrt(c.u^2 + c.v^2), h)\nend\n\n\ncnvt{T}(::Type{LCHuv{T}}, c::Color3) = cnvt(LCHuv{T}, convert(Luv{T}, c))\n\n\n# Everything to LCHab\n# -------------------\n\nfunction cnvt{T}(::Type{LCHab{T}}, c::Lab)\n h = rad2deg(atan2(c.b, c.a))\n while h > 360; h -= 360; end\n while h < 0; h += 360; end\n LCHab{T}(c.l, sqrt(c.a^2 + c.b^2), h)\nend\n\n\ncnvt{T}(::Type{LCHab{T}}, c::Color3) = cnvt(LCHab{T}, convert(Lab{T}, c))\n\n\n# Everything to DIN99\n# -------------------\n\nfunction cnvt{T}(::Type{DIN99{T}}, c::Lab)\n\n # We assume the adjustment parameters are always 1; the standard recommends\n # that they not be changed from these values.\n kch = 1\n ke = 1\n\n # Calculate DIN99 L\n l99 = (1/ke)*105.51*log(1+0.0158*c.l)\n\n # Temporary value for redness and yellowness\n # ee = c.a*cosd(16) + c.b*sind(16)\n ee = c.a*0.9612616959383189 + c.b*0.27563735581699916\n # f = -0.7*c.a*sind(16) + 0.7*c.b*cosd(16)\n f = -0.7*c.a*0.27563735581699916 + 0.7*c.b*0.9612616959383189\n\n # Temporary value for chroma\n g = sqrt(ee^2 + f^2)\n\n # Hue angle\n # Calculated in degrees, against the specification.\n if (ee > 0 && f >= 0)\n h = atand(f/ee)\n elseif (ee == 0 && f > 0)\n h = 90\n elseif (ee < 0)\n h = 180+atand(f/ee)\n elseif (ee == 0 && f < 0)\n h = 270\n elseif (ee > 0 && f <= 0)\n h = 360 + atand(f/ee)\n else\n h = 0\n end\n\n # DIN99 chroma\n cc = log(1+0.045*g)/(0.045*kch*ke)\n\n # DIN99 chromaticities\n a99, b99 = cc*cosd(h), cc*sind(h)\n\n DIN99{T}(l99, a99, b99)\n\nend\n\n\ncnvt{T}(::Type{DIN99{T}}, c::Color3) = cnvt(DIN99{T}, convert(Lab{T}, c))\n\n\n# Everything to DIN99d\n# --------------------\n\nfunction cnvt{T}(::Type{DIN99d{T}}, c::XYZ{T})\n\n # Apply tristimulus-space correction term\n adj_c = XYZ(1.12*c.x - 0.12*c.z, c.y, c.z)\n\n # Apply L*a*b*-space correction\n lab = convert(Lab, adj_c)\n adj_L = 325.22*log(1+0.0036*lab.l)\n\n # Calculate intermediate parameters\n # ee = lab.a*cosd(50) + lab.b*sind(50)\n ee = lab.a*0.6427876096865393 + lab.b*0.766044443118978\n # f = 1.14*(lab.b*cosd(50) - lab.a*sind(50))\n f = 1.14*(lab.b*0.6427876096865393 - lab.a*0.766044443118978)\n G = sqrt(ee^2+f^2)\n\n # Calculate hue/chroma\n C = 22.5*log(1+0.06*G)\n # FIXME: Clean this up (why is there no atan2d?)\n h = rad2deg(atan2(f,ee)) + 50\n while h > 360; h -= 360; end\n while h < 0; h += 360; end\n\n DIN99d{T}(adj_L, C*cosd(h), C*sind(h))\n\nend\n\n\ncnvt{T}(::Type{DIN99d{T}}, c::Color3) = cnvt(DIN99d{T}, convert(XYZ{T}, c))\n\n\n# Everything to DIN99o\n# -------------------\n\nfunction cnvt{T}(::Type{DIN99o{T}}, c::Lab)\n\n # We assume the adjustment parameters are always 1; the standard recommends\n # that they not be changed from these values.\n kch = 1\n ke = 1\n\n # Calculate DIN99o L (logarithmic compression)\n l99 = 303.67/ke*log(1+0.0039*c.l)\n\n # Temporary value for redness and yellowness\n # including rotation by 26°\n # eo = c.a*cosd(26) + c.b*sind(26)\n eo = c.a*0.898794046299167 + c.b*0.4383711467890774\n # compression along the yellowness (blue-yellow) axis\n # fo = 0.83 * (c.b*cosd(26) - c.a*sind(26))\n fo = 0.83 * (c.b*0.898794046299167 - c.a*0.4383711467890774)\n\n # Temporary value for chroma\n go = sqrt(eo^2 + fo^2)\n ho = atan2(fo,eo)\n # rotation of the color space by 26°\n h = rad2deg(ho) + 26\n\n # DIN99o chroma (logarithmic compression)\n cc = 23.0*log(1+0.075*go)/(kch*ke)\n\n # DIN99o chromaticities\n a99, b99 = cc*cosd(h), cc*sind(h)\n\n DIN99o{T}(l99, a99, b99)\n\nend\n\n\ncnvt{T}(::Type{DIN99o{T}}, c::Color3) = cnvt(DIN99o{T}, convert(Lab{T}, c))\n\n\n# Everything to LMS\n# -----------------\n\n# Chromatic adaptation from CIECAM97s\nconst CAT97s = [ 0.8562 0.3372 -0.1934\n -0.8360 1.8327 0.0033\n 0.0357 -0.0469 1.0112 ]\n\nconst CAT97s_INV = inv(CAT97s)\n\n# Chromatic adaptation from CIECAM02\nconst CAT02 = [ 0.7328 0.4296 -0.1624\n -0.7036 1.6975 0.0061\n 0.0030 0.0136 0.9834 ]\n\nconst CAT02_INV = inv(CAT02)\n\n\nfunction cnvt{T}(::Type{LMS{T}}, c::XYZ)\n @mul3x3 LMS{T} CAT02 c.x c.y c.z\nend\n\n\ncnvt{T}(::Type{LMS{T}}, c::Color3) = cnvt(LMS{T}, convert(XYZ{T}, c))\n\n# Everything to YIQ\n# -----------------\n\ncorrect_gamut{T}(c::YIQ{T}) = YIQ{T}(clamp(c.y, zero(T), one(T)),\n clamp(c.i, convert(T,-0.5957), convert(T,0.5957)),\n clamp(c.q, convert(T,-0.5226), convert(T,0.5226)))\n\nfunction cnvt{T}(::Type{YIQ{T}}, c::AbstractRGB)\n rgb = correct_gamut(c)\n YIQ{T}(0.299*red(rgb)+0.587*green(rgb)+0.114*blue(rgb),\n 0.595716*red(rgb)-0.274453*green(rgb)-0.321263*blue(rgb),\n 0.211456*red(rgb)-0.522591*green(rgb)+0.311135*blue(rgb))\nend\n\ncnvt{T}(::Type{YIQ{T}}, c::Color3) = cnvt(YIQ{T}, convert(RGB{T}, c))\n\n\n# Everything to YCbCr\n# -------------------\n\ncorrect_gamut{T}(c::YCbCr{T}) = YCbCr{T}(clamp(c.y, convert(T,16), convert(T,235)),\n clamp(c.cb, convert(T,16), convert(T,240)),\n clamp(c.cr, convert(T,16), convert(T,240)))\n\nfunction cnvt{T}(::Type{YCbCr{T}}, c::AbstractRGB)\n rgb = correct_gamut(c)\n YCbCr{T}(16+65.481*red(rgb)+128.553*green(rgb)+24.966*blue(rgb),\n 128-37.797*red(rgb)-74.203*green(rgb)+112*blue(rgb),\n 128+112*red(rgb)-93.786*green(rgb)-18.214*blue(rgb))\nend\n\ncnvt{T}(::Type{YCbCr{T}}, c::Color3) = cnvt(YCbCr{T}, convert(RGB{T}, c))\n\n# Everything to RGB24\n# -------------------\n\nconvert(::Type{RGB24}, c::RGB24) = c\nconvert(::Type{RGB24}, c::AbstractRGB{UFixed8}) = RGB24(red(c), green(c), blue(c))\nconvert(::Type{RGB24}, c::AbstractRGB) = RGB24((round(UInt8, 255*red(c))%UInt32)<<16 +\n (round(UInt8, 255*green(c))%UInt32)<<8 +\n round(UInt8, 255*blue(c))%UInt32)\n\nconvert(::Type{RGB24}, c::Color) = convert(RGB24, convert(RGB{UFixed8}, c))\n\n\n# To ARGB32\n# ----------------\n\nconvert(::Type{ARGB32}, c::ARGB32) = c\nconvert{CV<:AbstractRGB{UFixed8}}(::Type{ARGB32}, c::TransparentColor{CV}) =\n ARGB32(red(c), green(c), blue(c), alpha(c))\nconvert(::Type{ARGB32}, c::TransparentColor) =\n ARGB32(convert(RGB24, c).color | (round(UInt8, 255*alpha(c))%UInt32)<<24)\nconvert(::Type{ARGB32}, c::Color) = ARGB32(convert(RGB24, c).color | 0xff000000)\nconvert(::Type{ARGB32}, c::Color, alpha) = ARGB32(convert(RGB24, c).color | round(UInt32, 255*alpha)<<24)\n\n# To Gray\n# -------\n\n# Rec 601 luma conversion\nif VERSION < v\"0.4.0-dev+1827\"\n const unsafe_trunc = itrunc\nelse\n const unsafe_trunc = Base.unsafe_trunc\nend\n\nconvert{T<:UFixed}(::Type{Gray{T}}, x::AbstractRGB{T}) = (TU = FixedPointNumbers.rawtype(T); Gray{T}(T(round(TU, min(typemax(TU), 0.299f0*reinterpret(x.r) + 0.587f0*reinterpret(x.g) + 0.114f0*reinterpret(x.b))), 0)))\nconvert{T}(::Type{Gray{T}}, x::AbstractRGB) = convert(Gray{T}, 0.299f0*x.r + 0.587f0*x.g + 0.114f0*x.b)\n", "meta": {"hexsha": "51cde1db12b998c83ad7b3dfb7862834fee60921", "size": 23150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conversions.jl", "max_stars_repo_name": "JuliaPackageMirrors/Colors.jl", "max_stars_repo_head_hexsha": "9f69a2a734855116336838a6a73b53afddf4c36f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/conversions.jl", "max_issues_repo_name": "JuliaPackageMirrors/Colors.jl", "max_issues_repo_head_hexsha": "9f69a2a734855116336838a6a73b53afddf4c36f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conversions.jl", "max_forks_repo_name": "JuliaPackageMirrors/Colors.jl", "max_forks_repo_head_hexsha": "9f69a2a734855116336838a6a73b53afddf4c36f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7935323383, "max_line_length": 216, "alphanum_fraction": 0.5543412527, "num_tokens": 8973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19233998538149175}} {"text": "\nfunction shufflevector_instrs(W, T, I, two_operands)\n typ = LLVM_TYPES[T]\n vtyp1 = \"<$W x $typ>\"\n M = length(I)\n vtyp3 = \"<$M x i32>\"\n vtypr = \"<$M x $typ>\"\n mask = '<' * join(map(x->string(\"i32 \", x), I), \", \") * '>'\n v2 = two_operands ? \"%1\" : \"undef\"\n M, \"\"\"\n %res = shufflevector $vtyp1 %0, $vtyp1 $v2, $vtyp3 $mask\n ret $vtypr %res\n \"\"\"\nend\n@generated function shufflevector(v1::Vec{W,T}, v2::Vec{W,T}, ::Val{I}) where {W,T,I}\n M, instrs = shufflevector_instrs(W, T, I, true)\n quote\n $(Expr(:meta, :inline))\n Vec(llvmcall($instrs, _Vec{$M,$T}, Tuple{_Vec{$W,$T}, _Vec{$W,$T}}, data(v1), data(v2)))\n end\nend\n@generated function shufflevector(v1::Vec{W,T}, ::Val{I}) where {W,T,I}\n M, instrs = shufflevector_instrs(W, T, I, false)\n quote\n $(Expr(:meta, :inline))\n Vec(llvmcall($instrs, _Vec{$M,$T}, Tuple{_Vec{$W,$T}}, data(v1)))\n end\nend\n@generated function vresize(::Union{StaticInt{W},Val{W}}, v::Vec{L,T}) where {W,L,T}\n typ = LLVM_TYPES[T]\n mask = '<' * join(map(x->string(\"i32 \", x ≥ L ? L : x), 0:W-1), \", \") * '>'\n instrs = \"\"\"\n %res = shufflevector <$L x $typ> %0, <$L x $typ> undef, <$W x i32> $mask\n ret <$W x $typ> %res\n \"\"\"\n quote\n $(Expr(:meta, :inline))\n Vec(llvmcall($instrs, _Vec{$W,$T}, Tuple{_Vec{$L,$T}}, data(v)))\n end\nend\n@generated function vresize(::Union{StaticInt{W},Val{W}}, v::T) where {W,T<:NativeTypes}\n typ = LLVM_TYPES[T]\n vtyp = vtype(W, typ)\n instrs = \"\"\"\n %ie = insertelement $vtyp undef, $typ %0, i32 0\n ret $vtyp %ie\n \"\"\"\n quote\n $(Expr(:meta, :inline))\n Vec(llvmcall($instrs, _Vec{$W,$T}, Tuple{$T}, v))\n end\nend\n\n@generated function shufflevector(i::MM{W,X}, ::Val{I}) where {W,X,I}\n allincr = true\n L = length(I)\n for l ∈ 2:L\n allincr &= (I[l] == I[l-1] + 1)\n end\n allincr || return Expr(:block, Expr(:meta,:inline), :(shufflevector(Vec(i), Val{$I}())))\n Expr(:block, Expr(:meta,:inline), :(MM{$L,$X}( extractelement(i, $(first(I))) )))\nend\n\n", "meta": {"hexsha": "cdf090df93b15f96defb6f04fa773e637124ff4a", "size": 2090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/llvm_intrin/vector_ops.jl", "max_stars_repo_name": "brenhinkeller/VectorizationBase.jl", "max_stars_repo_head_hexsha": "26b295a88476845dd4d461e83d6296323766bc45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/llvm_intrin/vector_ops.jl", "max_issues_repo_name": "brenhinkeller/VectorizationBase.jl", "max_issues_repo_head_hexsha": "26b295a88476845dd4d461e83d6296323766bc45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/llvm_intrin/vector_ops.jl", "max_forks_repo_name": "brenhinkeller/VectorizationBase.jl", "max_forks_repo_head_hexsha": "26b295a88476845dd4d461e83d6296323766bc45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.65625, "max_line_length": 96, "alphanum_fraction": 0.5339712919, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19229518937991608}} {"text": "using MathProgBase\nexport CplexSolver\n\nmutable struct CplexMathProgModel <: AbstractLinearQuadraticModel\n inner::Model\n lazycb\n cutcb\n heuristiccb\n branchcb\n incumbentcb\n infocb\n solvetime::Float64\n mipstart_effortlevel::Cint\n heuristic_buffer::Vector{Float64}\nend\n\nfunction CplexMathProgModel(;mipstart_effortlevel::Cint = CPX_MIPSTART_AUTO, options...)\n env = Env()\n # set_param!(env, \"CPX_PARAM_MIPCBREDLP\", 0) # access variables in original problem, not presolved\n # set_param!(env, \"CPX_PARAM_PRELINEAR\", 0) # MAY NOT BE NECESSARY, only performs linear presolving so can recover original variables\n set_param!(env, \"CPX_PARAM_SCRIND\", 1) # output logs to stdout by default\n for (name,value) in options\n set_param!(env, string(name), value)\n end\n\n m = CplexMathProgModel(Model(env), nothing, nothing, nothing, nothing, nothing, nothing, NaN, mipstart_effortlevel, [])\n return m\nend\n\nmutable struct CplexSolver <: AbstractMathProgSolver\n options\nend\nCplexSolver(;kwargs...) = CplexSolver(kwargs)\nMathProgBase.LinearQuadraticModel(s::CplexSolver) = CplexMathProgModel(;s.options...)\n\nMathProgBase.ConicModel(s::CplexSolver) = LPQPtoConicBridge(LinearQuadraticModel(s))\nMathProgBase.supportedcones(::CplexSolver) = [:Free,:Zero,:NonNeg,:NonPos,:SOC]\n\nfunction MathProgBase.setparameters!(s::CplexSolver; mpboptions...)\n opts = collect(Any,s.options)\n for (optname, optval) in mpboptions\n if optname == :TimeLimit\n push!(opts, (:CPX_PARAM_TILIM, optval))\n elseif optname == :Silent\n if optval == true\n push!(opts, (:CPX_PARAM_SCRIND, 0))\n end\n else\n error(\"Unrecognized parameter $optname\")\n end\n end\n s.options = opts\n return\nend\n\nfunction MathProgBase.setparameters!(s::CplexMathProgModel; mpboptions...)\n for (optname, optval) in mpboptions\n if optname == :TimeLimit\n setparam!(m.inner, \"CPX_PARAM_TILIM\", optval)\n elseif optname == :Silent\n if optval == true\n setparam!(m.inner,\"CPX_PARAM_SCRIND\",0)\n end\n else\n error(\"Unrecognized parameter $optname\")\n end\n end\nend\n\nfunction MathProgBase.loadproblem!(m::CplexMathProgModel, filename::String)\n read_model(m.inner, filename)\nend\n\nfunction MathProgBase.loadproblem!(m::CplexMathProgModel, A, collb, colub, obj, rowlb, rowub, sense)\n # throw away old model but keep env\n m.inner = Model(m.inner.env)\n add_vars!(m.inner, float(obj), float(collb), float(colub))\n\n neginf = typemin(eltype(rowlb))\n posinf = typemax(eltype(rowub))\n\n rangeconstrs = any((rowlb .!= rowub) .& (rowlb .> neginf) .& (rowub .< posinf))\n if rangeconstrs\n warn(\"Julia Cplex interface doesn't properly support range (two-sided) constraints.\")\n add_rangeconstrs!(m.inner, float(A), float(rowlb), float(rowub))\n else\n b = Vector{Float64}(undef, length(rowlb))\n senses = Vector{Cchar}(undef, length(rowlb))\n for i in 1:length(rowlb)\n if rowlb[i] == rowub[i]\n senses[i] = 'E'\n b[i] = rowlb[i]\n elseif rowlb[i] > neginf\n senses[i] = 'G'\n b[i] = rowlb[i]\n else\n @assert rowub[i] < posinf\n senses[i] = 'L'\n b[i] = rowub[i]\n end\n end\n add_constrs!(m.inner, float(A), senses, b)\n end\n\n set_sense!(m.inner, sense)\nend\n\nMathProgBase.writeproblem(m::CplexMathProgModel, filename::String) = write_model(m.inner, filename)\n\nMathProgBase.getvarLB(m::CplexMathProgModel) = get_varLB(m.inner)\nMathProgBase.setvarLB!(m::CplexMathProgModel, l) = set_varLB!(m.inner, l)\nMathProgBase.getvarUB(m::CplexMathProgModel) = get_varUB(m.inner)\nMathProgBase.setvarUB!(m::CplexMathProgModel, u) = set_varUB!(m.inner, u)\n\n# CPXchgcoef\nMathProgBase.getconstrLB(m::CplexMathProgModel) = get_constrLB(m.inner)\nMathProgBase.setconstrLB!(m::CplexMathProgModel, lb) = set_constrLB!(m.inner, lb)\nMathProgBase.getconstrUB(m::CplexMathProgModel) = get_constrUB(m.inner)\nMathProgBase.setconstrUB!(m::CplexMathProgModel, ub) = set_constrUB!(m.inner, ub)\n\nMathProgBase.getobj(m::CplexMathProgModel) = get_obj(m.inner)\nMathProgBase.setobj!(m::CplexMathProgModel, c) = set_obj!(m.inner, c)\n\nMathProgBase.addvar!(m::CplexMathProgModel, l, u, coeff) = add_var!(m.inner, [], [], l, u, coeff)\nMathProgBase.addvar!(m::CplexMathProgModel, constridx, constrcoef, l, u, coeff) = add_var!(m.inner, constridx, constrcoef, l, u, coeff)\n\nfunction MathProgBase.addconstr!(m::CplexMathProgModel, varidx, coef, lb, ub)\n neginf = typemin(eltype(lb))\n posinf = typemax(eltype(ub))\n\n rangeconstrs = any((lb .!= ub) & (lb .> neginf) & (ub .< posinf))\n if rangeconstrs\n warn(\"Julia Cplex interface doesn't properly support range (two-sided) constraints.\")\n add_rangeconstrs!(m.inner, [0], varidx, float(coef), float(lb), float(ub))\n else\n if lb == ub\n rel = 'E'\n rhs = lb\n elseif lb > neginf\n rel = 'G'\n rhs = lb\n else\n @assert ub < posinf\n rel = 'L'\n rhs = ub\n end\n add_constrs!(m.inner, ivec([1]), ivec(varidx), fvec(coef), convert(Vector{Cchar},[rel]), fvec(vec(collect(rhs))))\n end\nend\n\nMathProgBase.getconstrmatrix(m::CplexMathProgModel) = get_constr_matrix(m.inner)\n\nMathProgBase.setsense!(m::CplexMathProgModel, sense) = set_sense!(m.inner, sense)\n\nMathProgBase.getsense(m::CplexMathProgModel) = get_sense(m.inner)\n\nMathProgBase.numvar(m::CplexMathProgModel) = num_var(m.inner)\nMathProgBase.numconstr(m::CplexMathProgModel) = num_constr(m.inner) + num_qconstr(m.inner)\nMathProgBase.numlinconstr(m::CplexMathProgModel) = num_constr(m.inner)\nMathProgBase.numquadconstr(m::CplexMathProgModel) = num_qconstr(m.inner)\n\n# MathProgBase.optimize!(m::CplexMathProgModel) = optimize!(m.inner)\n\nfunction MathProgBase.optimize!(m::CplexMathProgModel)\n # set callbacks if present\n if m.lazycb != nothing\n setmathproglazycallback!(m)\n end\n if m.cutcb != nothing\n setmathprogcutcallback!(m)\n end\n if m.heuristiccb != nothing\n setmathprogheuristiccallback!(m)\n end\n if m.branchcb != nothing\n setmathprogbranchcallback!(m)\n end\n if m.incumbentcb != nothing\n setmathprogincumbentcallback!(m)\n end\n if m.infocb != nothing\n setmathproginfocallback!(m)\n end\n start = time()\n optimize!(m.inner)\n m.solvetime = time() - start\nend\n\nfunction MathProgBase.status(m::CplexMathProgModel)\n ret = get_status(m.inner)\n return (if ret in [:CPX_STAT_OPTIMAL, :CPXMIP_OPTIMAL, :CPXMIP_OPTIMAL_TOL]\n :Optimal\n elseif ret in [:CPX_STAT_UNBOUNDED, :CPXMIP_UNBOUNDED]\n :Unbounded\n elseif ret in [:CPX_STAT_INFEASIBLE, :CPXMIP_INFEASIBLE]\n :Infeasible\n elseif ret in [:CPX_STAT_INForUNBD, :CPXMIP_INForUNBD]\n Base.warn_once(\"CPLEX reported infeasible or unbounded. Set CPX_PARAM_REDUCE=1 to check\n infeasibility or CPX_PARAM_REDUCE=2 to check unboundedness.\")\n :InfeasibleOrUnbounded\n elseif occursin(\"TIME_LIM\", string(ret)) || occursin(\"MIP_ABORT\", string(ret))\n :UserLimit\n else\n ret\n end)\nend\n\nMathProgBase.getobjval(m::CplexMathProgModel) = get_objval(m.inner)\nMathProgBase.getobjbound(m::CplexMathProgModel) = get_best_bound(m.inner)\nMathProgBase.getsolution(m::CplexMathProgModel) = get_solution(m.inner)\nMathProgBase.getconstrsolution(m::CplexMathProgModel) = get_constr_solution(m.inner)\nMathProgBase.getreducedcosts(m::CplexMathProgModel) = get_reduced_costs(m.inner)\nMathProgBase.getconstrduals(m::CplexMathProgModel) = get_constr_duals(m.inner)\nMathProgBase.getrawsolver(m::CplexMathProgModel) = m.inner\nMathProgBase.getnodecount(m::CplexMathProgModel) = get_node_count(m.inner)\n\nconst var_type_map = Dict(\n 'C' => :Cont,\n 'B' => :Bin,\n 'I' => :Int,\n 'S' => :SemiCont,\n 'N' => :SemiInt\n)\n\nconst rev_var_type_map = Dict(\n :Cont => 'C',\n :Bin => 'B',\n :Int => 'I',\n :SemiCont => 'S',\n :SemiInt => 'N'\n)\n\nfunction MathProgBase.setvartype!(m::CplexMathProgModel, v::Vector{Symbol})\n target_int = all(x->isequal(x,:Cont), v)\n prob_type = get_prob_type(m.inner)\n if target_int\n if m.inner.has_sos # if it has sos we need to keep has_int==true and the MI(prob_type) version.\n set_vartype!(m.inner, map(x->rev_var_type_map[x], v))\n else\n m.inner.has_int = false\n if !(prob_type in [:LP,:QP,:QCP])\n toggleproblemtype!(m)\n end\n end\n else\n if prob_type in [:LP,:QP,:QCP]\n toggleproblemtype!(m)\n end\n set_vartype!(m.inner, map(x->rev_var_type_map[x], v))\n end\n return nothing\nend\n\nconst prob_type_toggle_map = Dict(\n :LP => :MILP,\n :MILP => :LP,\n :QP => :MIQP,\n :MIQP => :QP,\n :QCP => :MIQCP,\n :MIQCP => :QCP\n)\n\nfunction toggleproblemtype!(m::CplexMathProgModel)\n prob_type = get_prob_type(m.inner)\n set_prob_type!(m.inner, prob_type_toggle_map[prob_type])\nend\n\nfunction MathProgBase.getvartype(m::CplexMathProgModel)\n if m.inner.has_int\n return map(x->var_type_map[x], get_vartype(m.inner))\n else\n return fill(:Cont, num_var(m.inner))\n end\nend\n\nfunction MathProgBase.getsolvetime(m::CplexMathProgModel)\n return m.solvetime\nend\n\nMathProgBase.getinfeasibilityray(m::CplexMathProgModel) = get_infeasibility_ray(m.inner)\nMathProgBase.getunboundedray(m::CplexMathProgModel) = get_unbounded_ray(m.inner)\n\nMathProgBase.getbasis(m::CplexMathProgModel) = get_basis(m.inner)\n\nfunction MathProgBase.setwarmstart!(m::CplexMathProgModel, v)\n # This means that warm starts are ignored if you haven't called setvartype! first\n if m.inner.has_int\n set_warm_start!(m.inner, v, m.mipstart_effortlevel)\n end\nend\n\nMathProgBase.addsos1!(m::CplexMathProgModel, idx, weight) = add_sos!(m.inner, :SOS1, idx, weight)\nMathProgBase.addsos2!(m::CplexMathProgModel, idx, weight) = add_sos!(m.inner, :SOS2, idx, weight)\n\n######\n# QCQP\n######\nMathProgBase.addquadconstr!(m::CplexMathProgModel, linearidx, linearval, quadrowidx, quadcolidx, quadval, sense, rhs) =\n add_qconstr!(m.inner,linearidx,linearval,quadrowidx,quadcolidx,quadval,sense,rhs)\nMathProgBase.setquadobj!(m::CplexMathProgModel,rowidx,colidx,quadval) = add_qpterms!(m.inner,rowidx,colidx,quadval)\n\n######\n# Data\n######\nfunction getdettime(m::CplexMathProgModel)\n tim = Vector{Cdouble}(undef, 1)\n stat = @cpx_ccall(getdettime, Cint, (Ptr{Cvoid},Ptr{Cdouble}), m.inner.env.ptr, tim)\n if stat != 0\n error(CplexError(m.inner.env, stat).msg)\n end\n return tim[1]\nend\n\nMathProgBase.getobjgap(m::CplexMathProgModel) = get_rel_gap(m.inner)\n\n###########\n# Callbacks\n###########\nexport cbaddboundbranchup!,\n cbaddboundbranchdown!,\n setmathprogbranchcallback!,\n cbgetnodelb,\n cbgetnodeub,\n cbgetnodeobjval,\n cbgetnodesleft,\n cbgetmipiterations,\n cbgetfeasibility,\n cbgetgap,\n cbgetstarttime,\n cbgetdetstarttime,\n cbgettimestamp,\n cbgetdettimestamp,\n cbgetintfeas\n\nabstract type CplexCallbackData <: MathProgCallbackData end\n\n# set to nothing to clear callback\nMathProgBase.setlazycallback!(m::CplexMathProgModel,f) = (m.lazycb = f)\nMathProgBase.setcutcallback!(m::CplexMathProgModel,f) = (m.cutcb = f)\nMathProgBase.setheuristiccallback!(m::CplexMathProgModel,f) = (m.heuristiccb = f)\nsetbranchcallback!(m::CplexMathProgModel,f) = (m.branchcb = f)\nsetincumbentcallback!(m::CplexMathProgModel,f) = (m.incumbentcb = f)\nMathProgBase.setinfocallback!(m::CplexMathProgModel,f) = (m.infocb = f)\n\nfunction MathProgBase.cbgetmipsolution(d::CplexCallbackData)\n @assert d.state == :MIPSol || d.state == :MIPIncumbent\n n = num_var(d.cbdata.model)\n sol = Vector{Cdouble}(undef, n)\n stat = @cpx_ccall(getcallbacknodex, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cdouble},Cint,Cint),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, sol, 0, n-1)\n if stat != 0\n error(CplexError(d.cbdata.model.env, stat).msg)\n end\n return sol\nend\n\nfunction MathProgBase.cbgetmipsolution(d::CplexCallbackData, sol::Vector{Cdouble})\n @assert d.state == :MIPSol\n stat = @cpx_ccall(getcallbacknodex, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cdouble},Cint,Cint),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, sol, 0, length(sol)-1)\n if stat != 0\n error(CplexError(d.cbdata.model.env, stat).msg)\n end\n return nothing\nend\n\nfunction MathProgBase.cbgetlpsolution(d::CplexCallbackData)\n @assert d.state == :MIPNode || d.state == :MIPBranch\n n = num_var(d.cbdata.model)\n sol = Vector{Cdouble}(undef, n)\n stat = @cpx_ccall(getcallbacknodex, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cdouble},Cint,Cint),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, sol, 0, n-1)\n if stat != 0\n error(CplexError(d.cbdata.model.env, stat).msg)\n end\n return sol\nend\n\nfunction MathProgBase.cbgetlpsolution(d::CplexCallbackData, sol::Vector{Cdouble})\n @assert d.state == :MIPNode || d.state == :MIPIncumbent || d.state == :MIPBranch\n stat = @cpx_ccall(getcallbacknodex, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cdouble},Cint,Cint),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, sol, 0, length(sol)-1)\n if stat != 0\n error(CplexError(d.cbdata.model.env, stat).msg)\n end\n return nothing\nend\n\nfor (func,param,typ) in ((:cbgetexplorednodes,CPX_CALLBACK_INFO_NODE_COUNT_LONG,:Int64),\n (:cbgetobj,CPX_CALLBACK_INFO_BEST_INTEGER,:Cdouble),\n (:cbgetbestbound,CPX_CALLBACK_INFO_BEST_REMAINING,:Cdouble))\n\n @eval begin\n function (MathProgBase.$func)(d::CplexCallbackData)\n val = Vector{$(typ)}(undef, 1)\n ret = @cpx_ccall(getcallbackinfo, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Cint,Ptr{Cvoid}),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, $(convert(Cint,param)), val)\n if ret != 0\n error(CplexError(d.cbdata.model.env, stat).msg)\n end\n return val[1]\n end\n end\nend\n\nfor (func,param,typ) in ((:cbgetnodesleft,CPX_CALLBACK_INFO_NODES_LEFT_LONG,:Int64),\n (:cbgetmipiterations,CPX_CALLBACK_INFO_MIP_ITERATIONS_LONG,:Int64),\n (:cbgetgap,CPX_CALLBACK_INFO_MIP_REL_GAP,:Cdouble),\n (:cbgetfeasibility,CPX_CALLBACK_INFO_MIP_FEAS,:Cint),\n (:cbgetstarttime,CPX_CALLBACK_INFO_STARTTIME,:Cdouble),\n (:cbgetdetstarttime,CPX_CALLBACK_INFO_STARTDETTIME,:Cdouble),\n (:cbgettimestamp,CPX_CALLBACK_INFO_ENDTIME,:Cdouble),\n (:cbgetdettimestamp,CPX_CALLBACK_INFO_ENDDETTIME,:Cdouble))\n\n @eval begin\n function ($func)(d::CplexCallbackData)\n val = Vector{$(typ)}(undef, 1)\n ret = @cpx_ccall(getcallbackinfo, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Cint,Ptr{Cvoid}),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, $(convert(Cint,param)), val)\n if ret != 0\n error(CplexError(d.cbdata.model.env, stat).msg)\n end\n return val[1]\n end\n end\nend\n\n# returns :MIPNode :MIPSol :Intermediate\nMathProgBase.cbgetstate(d::CplexCallbackData) = d.state\n\n#const sensemap = Dict('=' => 'E', '<' => 'L', '>' => 'G')\nfunction MathProgBase.cbaddcut!(d::CplexCallbackData,varidx,varcoef,sense,rhs)\n @assert d.state == :MIPNode\n cbcut(d.cbdata, d.where, convert(Vector{Cint}, varidx), float(varcoef), sensemap[sense], float(rhs))\n unsafe_store!(d.userinteraction_p, convert(Cint,CPX_CALLBACK_ABORT_CUT_LOOP), 1)\nend\n\nfunction MathProgBase.cbaddcutlocal!(d::CplexCallbackData,varidx,varcoef,sense,rhs)\n @assert d.state == :MIPNode\n cbcutlocal(d.cbdata, d.where, convert(Vector{Cint}, varidx), float(varcoef), sensemap[sense], float(rhs))\n unsafe_store!(d.userinteraction_p, convert(Cint,CPX_CALLBACK_ABORT_CUT_LOOP), 1)\nend\n\n\nfunction MathProgBase.cbaddlazy!(d::CplexCallbackData,varidx,varcoef,sense,rhs)\n @assert d.state == :MIPNode || d.state == :MIPSol\n cblazy(d.cbdata, d.where, convert(Vector{Cint}, varidx), float(varcoef), sensemap[sense], float(rhs))\nend\n\nfunction MathProgBase.cbaddlazylocal!(d::CplexCallbackData,varidx,varcoef,sense,rhs)\n @assert d.state == :MIPNode || d.state == :MIPSol\n cblazylocal(d.cbdata, d.where, convert(Vector{Cint}, varidx), float(varcoef), sensemap[sense], float(rhs))\nend\n\n\nfunction MathProgBase.cbaddsolution!(d::CplexCallbackData)\n val = unsafe_wrap(Array, d.userinteraction_p, 1)\n if val[1] == CPX_CALLBACK_SET\n error(\"CPLEX only allows one heuristic solution for each call to the callback\")\n end\n unsafe_store!(d.userinteraction_p, convert(Cint,CPX_CALLBACK_SET), 1)\nend\n\nfunction MathProgBase.cbsetsolutionvalue!(d::CplexCallbackData,varidx,value)\n @assert 1 <= varidx <= num_var(d.cbdata.model)\n d.heur_x[varidx] = value\n d.user_solution = true\n nothing\nend\n\nfunction cbaddboundbranchup!(d::CplexCallbackData,idx,bd,nodeest)\n seqnum = cbbranch(d.cbdata, d.where,convert(Cint,idx-1),convert(Cchar,'L'),bd,nodeest)\n unsafe_store!(d.userinteraction_p, convert(Cint,CPX_CALLBACK_SET), 1)\n seqnum\nend\n\nfunction cbaddboundbranchdown!(d::CplexCallbackData,idx,bd,nodeest)\n seqnum = cbbranch(d.cbdata, d.where,convert(Cint,idx-1),convert(Cchar,'U'),bd,nodeest)\n unsafe_store!(d.userinteraction_p, convert(Cint,CPX_CALLBACK_SET), 1)\n seqnum\nend\n\nfunction cbaddconstrbranch!(d::CplexCallbackData, indices, coeffs, rhs, sense, nodeest)\n seqnum = cbbranchconstr(d.cbdata,\n d.where,\n Cint[idx-1 for idx in indices],\n Cdouble[c for c in coeffs],\n convert(Cdouble, rhs),\n convert(Cchar, sense),\n nodeest)\n unsafe_store!(d.userinteraction_p, convert(Cint,CPX_CALLBACK_SET), 1)\n seqnum\nend\n\nfunction cbprocessincumbent!(d::CplexCallbackData,accept::Bool)\n if accept\n unsafe_store!(d.isfeas_p, convert(Cint, 1), 1)\n else\n unsafe_store!(d.isfeas_p, convert(Cint, 0), 1)\n end\n nothing\nend\n\nmutable struct CplexLazyCallbackData <: CplexCallbackData\n cbdata::CallbackData\n state::Symbol\n where::Cint\n userinteraction_p::Ptr{Cint}\nend\n\nmutable struct CplexCutCallbackData <: CplexCallbackData\n cbdata::CallbackData\n state::Symbol\n where::Cint\n userinteraction_p::Ptr{Cint}\nend\n\nterminate(model::CplexMathProgModel) = terminate(model.inner)\n\n# breaking abstraction, define our low-level callback to eliminate\n# a level of indirection\nfunction mastercallback(env::Ptr{Cvoid}, cbdata::Ptr{Cvoid}, wherefrom::Cint, userdata::Ptr{Cvoid}, userinteraction_p::Ptr{Cint})\n model = MathProgBase.unsafe_pointer_to_objref(userdata)::CplexMathProgModel\n cpxrawcb = CallbackData(cbdata, model.inner)\n if wherefrom == CPX_CALLBACK_MIP_CUT_FEAS || wherefrom == CPX_CALLBACK_MIP_CUT_UNBD\n state = :MIPSol\n # elseif wherefrom == CPX_CALLBACK_MIP_CUT_LOOP || wherefrom == CPX_CALLBACK_MIP_CUT_LAST\n elseif wherefrom == CPX_CALLBACK_MIP_CUT_LAST\n state = :MIPNode\n else\n state = :Intermediate\n end\n\n if model.infocb != nothing\n cpxcb = CplexInfoCallbackData(cpxrawcb, state, wherefrom)\n stat = model.infocb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n if model.lazycb != nothing && state == :MIPSol\n cpxcb = CplexLazyCallbackData(cpxrawcb, state, wherefrom, userinteraction_p)\n stat = model.lazycb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n if model.cutcb != nothing && state == :MIPNode\n cpxcb = CplexCutCallbackData(cpxrawcb, state, wherefrom, userinteraction_p)\n stat = model.cutcb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n return convert(Cint, 0)\nend\n\nmutable struct CplexHeuristicCallbackData <: CplexCallbackData\n cbdata::CallbackData\n state::Symbol\n where::Cint\n sol::Vector{Float64}\n heur_x::Vector{Float64}\n isfeas_p::Ptr{Cint}\n userinteraction_p::Ptr{Cint}\n user_solution::Bool # true if user has set any solution values\nend\n\nfunction MathProgBase.cbgetlpsolution(d::CplexHeuristicCallbackData)\n return copy(d.sol)\nend\n\nfunction MathProgBase.cbgetlpsolution(d::CplexHeuristicCallbackData, sol::Vector{Cdouble})\n copyto!(sol,d.sol)\nend\n\nfunction masterheuristiccallback(env::Ptr{Cvoid},\n cbdata::Ptr{Cvoid},\n wherefrom::Cint,\n userdata::Ptr{Cvoid},\n objval_p::Ptr{Cdouble},\n xx::Ptr{Cdouble},\n isfeas_p::Ptr{Cint},\n userinteraction_p::Ptr{Cint})\n model = MathProgBase.unsafe_pointer_to_objref(userdata)::CplexMathProgModel\n cpxrawcb = CallbackData(cbdata, model.inner)\n if wherefrom == CPX_CALLBACK_MIP_HEURISTIC\n state = :MIPNode\n else\n state = :Intermediate\n end\n\n if model.infocb != nothing\n cpxcb = CplexInfoCallbackData(cpxrawcb, state, wherefrom)\n stat = model.infocb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n if model.heuristiccb != nothing && state == :MIPNode\n sol = unsafe_wrap(Array, xx, numvar(model))\n cpxcb = CplexHeuristicCallbackData(cpxrawcb, state, wherefrom, sol, model.heuristic_buffer, isfeas_p, userinteraction_p, false)\n stat = model.heuristiccb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n if cpxcb.user_solution # we filled in some solution values\n unsafe_store!(objval_p, dot(get_obj(model.inner), cpxcb.heur_x), 1)\n for i in 1:numvar(model)\n unsafe_store!(xx, cpxcb.heur_x[i], i)\n end\n if any(x->isnan(x), cpxcb.heur_x) # we have a partial solution\n unsafe_store!(isfeas_p, convert(Cint,CPX_ON), 1)\n else\n unsafe_store!(isfeas_p, convert(Cint,CPX_OFF), 1)\n end\n fill!(model.heuristic_buffer, NaN)\n end\n end\n return convert(Cint, 0)\nend\n\nfunction setmathproglazycallback!(model::CplexMathProgModel)\n set_param!(model.inner.env, \"CPX_PARAM_MIPCBREDLP\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_PRELINEAR\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_REDUCE\", CPX_PREREDUCE_PRIMALONLY)\n cpxcallback = @cfunction(mastercallback, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Cint, Ptr{Cvoid}, Ptr{Cint}))\n stat = @cpx_ccall(setlazyconstraintcallbackfunc, Cint, (\n Ptr{Cvoid},\n Ptr{Cvoid},\n Any,\n ),\n model.inner.env.ptr, cpxcallback, model)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n nothing\nend\n\nfunction setmathprogcutcallback!(model::CplexMathProgModel)\n set_param!(model.inner.env, \"CPX_PARAM_MIPCBREDLP\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_PRELINEAR\", 0)\n cpxcallback = @cfunction(mastercallback, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Cint, Ptr{Cvoid}, Ptr{Cint}))\n stat = @cpx_ccall(setusercutcallbackfunc, Cint, (\n Ptr{Cvoid},\n Ptr{Cvoid},\n Any,\n ),\n model.inner.env.ptr, cpxcallback, model)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n nothing\nend\n\nfunction setmathprogheuristiccallback!(model::CplexMathProgModel)\n set_param!(model.inner.env, \"CPX_PARAM_MIPCBREDLP\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_PRELINEAR\", 0)\n cpxcallback = @cfunction(masterheuristiccallback, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Cint, Ptr{Cvoid}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}))\n stat = @cpx_ccall(setheuristiccallbackfunc, Cint, (\n Ptr{Cvoid},\n Ptr{Cvoid},\n Any,\n ),\n model.inner.env.ptr, cpxcallback, model)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n model.heuristic_buffer = fill(NaN, numvar(model))\n nothing\nend\n\nstruct BranchingChoice\n indices::Vector{Cint}\n bounds::Vector{Cdouble}\n lu::Vector{Cchar}\nend\nexport BranchingChoice\n\nstruct CplexBranchCallbackData <: CplexCallbackData\n cbdata::CallbackData\n state::Symbol\n where::Cint\n userinteraction_p::Ptr{Cint}\n nodes::Vector{BranchingChoice}\nend\n\nfunction masterbranchcallback(env::Ptr{Cvoid},\n cbdata::Ptr{Cvoid},\n wherefrom::Cint,\n userdata::Ptr{Cvoid},\n typ::Cint,\n sos::Cint,\n nodecnt::Cint,\n bdcnt::Cint,\n nodebeg::Ptr{Cint},\n indices::Ptr{Cint},\n lu::Ptr{Cchar},\n bd::Ptr{Cdouble},\n nodeest::Ptr{Cdouble},\n userinteraction_p::Ptr{Cint})\n model = unsafe_pointer_to_objref(userdata)::CplexMathProgModel\n cpxrawcb = CallbackData(cbdata, model.inner)\n if wherefrom == CPX_CALLBACK_MIP_BRANCH\n @assert 0 <= nodecnt <= 2\n state = :MIPBranch\n else\n state = :Intermediate\n end\n\n if model.infocb != nothing\n cpxcb = CplexInfoCallbackData(cpxrawcb, state, wherefrom)\n stat = model.infocb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n if model.branchcb != nothing && state == :MIPBranch\n numbranchingvars = unsafe_wrap(Array, nodebeg, convert(Cint,nodecnt))::Vector{Cint} .+ 1\n idxs = unsafe_wrap(Array, indices, sum(numbranchingvars))::Vector{Cint}\n vals = unsafe_wrap(Array, bd, sum(numbranchingvars))::Vector{Cdouble}\n dirs = unsafe_wrap(Array, lu, sum(numbranchingvars))::Vector{Cchar}\n nodes = Vector{BranchingChoice}(undef, nodecnt)\n if nodecnt >= 1\n subidx = 1 : (numbranchingvars[1])\n nodes[1] = BranchingChoice(idxs[subidx], vals[subidx], dirs[subidx])\n end\n if nodecnt == 2\n subidx = (numbranchingvars[1]+1) : (numbranchingvars[2])\n nodes[2] = BranchingChoice(idxs[subidx], vals[subidx], dirs[subidx])\n end\n cpxcb = CplexBranchCallbackData(cpxrawcb, state, wherefrom, userinteraction_p, nodes)\n stat = model.branchcb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n return convert(Cint, 0)\nend\n\nfunction setmathprogbranchcallback!(model::CplexMathProgModel)\n set_param!(model.inner.env, \"CPX_PARAM_MIPCBREDLP\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_PRELINEAR\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_REDUCE\", CPX_PREREDUCE_PRIMALONLY)\n cpxcallback = @cfunction(masterbranchcallback, Cint, (Ptr{Cvoid},\n Ptr{Cvoid},\n Cint,\n Ptr{Cvoid},\n Cint,\n Cint,\n Cint,\n Cint,\n Ptr{Cint},\n Ptr{Cint},\n Ptr{Cchar},\n Ptr{Cdouble},\n Ptr{Cdouble},\n Ptr{Cint}))\n stat = @cpx_ccall(setbranchcallbackfunc, Cint, (\n Ptr{Cvoid},\n Ptr{Cvoid},\n Any,\n ),\n model.inner.env.ptr, cpxcallback, model)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n nothing\nend\n\nmutable struct CplexIncumbentCallbackData <: CplexCallbackData\n cbdata::CallbackData\n state::Symbol\n where::Cint\n sol::Vector{Float64}\n isfeas_p::Ptr{Cint}\n userinteraction_p::Ptr{Cint}\n nodes::Vector{BranchingChoice}\nend\n\nfunction masterincumbentcallback(env::Ptr{Cvoid},\n cbdata::Ptr{Cvoid},\n wherefrom::Cint,\n userdata::Ptr{Cvoid},\n objval::Cdouble,\n xx::Ptr{Cdouble},\n isfeas_p::Ptr{Cint},\n useraction_p::Ptr{Cint})\n model = unsafe_pointer_to_objref(userdata)::CplexMathProgModel\n cpxrawcb = CallbackData(cbdata, model.inner)\n if wherefrom == CPX_CALLBACK_MIP_INCUMBENT_NODESOLN ||\n wherefrom == CPX_CALLBACK_MIP_INCUMBENT_HEURSOLN ||\n wherefrom == CPX_CALLBACK_MIP_INCUMBENT_USERSOLN\n state = :MIPIncumbent\n else\n state = :Intermediate\n end\n\n if model.infocb != nothing\n cpxcb = CplexInfoCallbackData(cpxrawcb, state, wherefrom)\n stat = model.infocb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n if model.incumbentcb != nothing && state == :MIPIncumbent\n sol = unsafe_wrap(Array, xx, numvar(model))\n cpxcb = CplexIncumbentCallbackData(cpxrawcb, state, wherefrom, sol, isfeas_p, useraction_p, BranchingChoice[])\n stat = model.incumbentcb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n return convert(Cint, 0)\nend\n\nfunction setmathprogincumbentcallback!(model::CplexMathProgModel)\n set_param!(model.inner.env, \"CPX_PARAM_MIPCBREDLP\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_PRELINEAR\", 0)\n set_param!(model.inner.env, \"CPX_PARAM_REDUCE\", CPX_PREREDUCE_PRIMALONLY)\n cpxcallback = @cfunction(masterincumbentcallback, Cint, (Ptr{Cvoid},\n Ptr{Cvoid},\n Cint,\n Ptr{Cvoid},\n Cdouble,\n Ptr{Cdouble},\n Ptr{Cint},\n Ptr{Cint}))\n stat = @cpx_ccall(setincumbentcallbackfunc, Cint, (\n Ptr{Cvoid},\n Ptr{Cvoid},\n Any,\n ),\n model.inner.env.ptr, cpxcallback, model)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n nothing\nend\n\nmutable struct CplexInfoCallbackData <: CplexCallbackData\n cbdata::CallbackData\n state::Symbol\n where::Cint\nend\n\nfunction masterinfocallback(env::Ptr{Cvoid},\n cbdata::Ptr{Cvoid},\n wherefrom::Cint,\n userdata::Ptr{Cvoid})\n model = unsafe_pointer_to_objref(userdata)::CplexMathProgModel\n if model.infocb != nothing\n state = :Intermediate\n cpxrawcb = CallbackData(cbdata, model.inner)\n cpxcb = CplexInfoCallbackData(cpxrawcb, state, wherefrom)\n stat = model.infocb(cpxcb)\n if stat == :Exit\n terminate(model.inner)\n end\n end\n return convert(Cint, 0)\nend\n\nfunction setmathproginfocallback!(model::CplexMathProgModel)\n cpxcallback = @cfunction(masterinfocallback, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Cint, Ptr{Cvoid}))\n stat = @cpx_ccall(setinfocallbackfunc, Cint, (\n Ptr{Cvoid},\n Ptr{Cvoid},\n Any,\n ),\n model.inner.env.ptr, cpxcallback, model)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n nothing\nend\n\nfunction cbgetnodelb(d::CplexCallbackData)\n n = num_var(d.cbdata.model)\n lb = Vector{Cdouble}(undef, n)\n stat = @cpx_ccall(getcallbacknodelb, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cdouble},Cint,Cint),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, lb, 0, n-1)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n return lb\nend\n\nfunction cbgetnodeub(d::CplexCallbackData)\n n = num_var(d.cbdata.model)\n ub = Vector{Cdouble}(undef, n)\n stat = @cpx_ccall(getcallbacknodeub, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cdouble},Cint,Cint),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, ub, 0, n-1)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n return ub\nend\n\nfunction cbgetnodeobjval(d::CplexCallbackData)\n val = Vector{Cdouble}(undef, 1)\n stat = @cpx_ccall(getcallbacknodeobjval, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cdouble}),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, val)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n return val[1]\nend\n\nfunction cbgetintfeas(d::CplexCallbackData)\n n = num_var(d.cbdata.model)\n feas = Vector{Cint}(undef, n)\n stat = @cpx_ccall(getcallbacknodeintfeas, Cint, (Ptr{Cvoid},Ptr{Cvoid},Cint,Ptr{Cint},Cint,Cint),\n d.cbdata.model.env.ptr, d.cbdata.cbdata, d.where, feas, 0, n-1)\n if stat != 0\n throw(CplexError(model.env, stat))\n end\n return convert(Vector{Int64},feas)\nend\n", "meta": {"hexsha": "24c42a86f026c54cdb51839f36edd37f05a45ef2", "size": 33953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CplexSolverInterface.jl", "max_stars_repo_name": "matbesancon/CPLEX.jl", "max_stars_repo_head_hexsha": "6c0099cbec464a50899fbcfd54895acf57a0efa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CplexSolverInterface.jl", "max_issues_repo_name": "matbesancon/CPLEX.jl", "max_issues_repo_head_hexsha": "6c0099cbec464a50899fbcfd54895acf57a0efa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-09-12T13:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-12T13:51:49.000Z", "max_forks_repo_path": "src/CplexSolverInterface.jl", "max_forks_repo_name": "matbesancon/CPLEX.jl", "max_forks_repo_head_hexsha": "6c0099cbec464a50899fbcfd54895acf57a0efa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9054347826, "max_line_length": 153, "alphanum_fraction": 0.6220068919, "num_tokens": 9435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.19119741574172444}} {"text": "using Parameters\nusing LinearAlgebra\nusing StaticArrays\nusing Dierckx\nusing Calculus\n\nabstract type AbstractDomain end\nexport AbstractDomain\n\nabstract type AbstractConstantKDomain <: AbstractDomain end\nexport AbstractConstantKDomain\n\nabstract type AbstractVariableKDomain <: AbstractDomain end\nexport AbstractVariableKDomain\n\n@with_kw struct ConstantTPDomain{N<:AbstractPhase,S<:Integer,W<:Real, W2<:Real, I<:Integer, Q<:AbstractArray} <: AbstractConstantKDomain\n phase::N\n interfaces::Array{AbstractInterface,1} = Array{AbstractInterface,1}()\n indexes::Q #assumed to be in ascending order\n constantspeciesinds::Array{S,1}\n T::W\n P::W\n kfs::Array{W,1}\n krevs::Array{W,1}\n efficiencyinds::Array{I,1}\n Gs::Array{W,1}\n rxnarray::Array{UInt16,2}\n mu::W = 0.0\n diffusivity::Array{W,1} = Array{Float64,1}()\n jacobian::Array{W,2} = Array{Float64,2}(undef,(0,0))\n sensitivity::Bool = false\n jacuptodate::MArray{Tuple{1},Bool,1,1}=MVector(false)\n t::MArray{Tuple{1},W2,1,1}=MVector(0.0)\nend\nfunction ConstantTPDomain(;phase::E2,interfaces::Array{Q,1}=Array{EmptyInterface,1}(),initialconds::Dict{X,X2},constantspecies::Array{X3,1}=Array{String,1}(),\n sparse::Bool=false,sensitivity::Bool=false) where {E<:Real,E2<:AbstractPhase,Q<:AbstractInterface,W<:Real,X,X2,X3}\n #set conditions and initialconditions\n T = 0.0\n P = 0.0\n if sensitivity\n y0 = zeros(length(phase.species)*(1+length(phase.species)+length(phase.reactions)))\n else\n y0 = zeros(length(phase.species))\n end\n spnames = [x.name for x in phase.species]\n for (key,val) in initialconds\n if key == \"T\"\n T = val\n elseif key == \"P\"\n P = val\n else\n ind = findfirst(isequal(key),spnames)\n @assert typeof(ind)<: Integer \"$key not found in species list: $spnames\"\n y0[ind] = val\n end\n end\n\n\n @assert T != 0.0\n @assert P != 0.0\n ns = y0\n N = sum(ns)\n\n if length(constantspecies) > 0\n spcnames = getfield.(phase.species,:name)\n constspcinds = [findfirst(isequal(k),spcnames) for k in constantspecies]\n else\n constspcinds = Array{Int64,1}()\n end\n efficiencyinds = [rxn.index for rxn in phase.reactions if typeof(rxn.kinetics)<:AbstractFalloffRate && length(rxn.kinetics.efficiencies) > 0]\n Gs = calcgibbs(phase,T)\n if :solvent in fieldnames(typeof(phase)) && typeof(phase.solvent) != EmptySolvent\n mu = phase.solvent.mu(T)\n else\n mu = 0.0\n end\n if phase.diffusionlimited\n diffs = getfield.(phase.species,:diffusion)(T=T,mu=mu,P=P)\n else\n diffs = Array{typeof(T),1}()\n end\n C = P/(R*T)\n V = N*R*T/P\n kfs,krevs = getkfkrevs(phase=phase,T=T,P=P,C=C,N=N,ns=ns,Gs=Gs,diffs=diffs,V=V)\n if sparse\n jacobian=spzeros(typeof(T),length(phase.species),length(phase.species))\n else\n jacobian=zeros(typeof(T),length(phase.species),length(phase.species))\n end\n rxnarray = getreactionindices(phase)\n return ConstantTPDomain(phase,interfaces,SVector(phase.species[1].index,phase.species[end].index),constspcinds,\n T,P,kfs,krevs,efficiencyinds,Gs,rxnarray,mu,diffs,jacobian,sensitivity,MVector(false),MVector(0.0)), y0\nend\nexport ConstantTPDomain\n\n@with_kw struct ConstantVDomain{N<:AbstractPhase,S<:Integer,W<:Real,W2<:Real,Q<:AbstractArray} <: AbstractVariableKDomain\n phase::N\n interfaces::Array{AbstractInterface,1} = Array{AbstractInterface,1}()\n indexes::Q #assumed to be in ascending order\n constantspeciesinds::Array{S,1}\n V::W\n rxnarray::Array{UInt16,2}\n jacobian::Array{W,2}\n sensitivity::Bool = false\n jacuptodate::MArray{Tuple{1},Bool,1,1}=MVector(false)\n t::MArray{Tuple{1},W2,1,1}=MVector(0.0)\nend\nfunction ConstantVDomain(;phase::Z,interfaces::Array{Q,1}=Array{EmptyInterface,1}(),initialconds::Dict{X,E},constantspecies::Array{X2,1}=Array{String,1}(),\n sparse::Bool=false,sensitivity::Bool=false) where {E,X,X2,Z<:IdealGas,Q<:AbstractInterface}\n\n #set conditions and initialconditions\n T = 0.0\n P = 0.0\n V = 0.0\n ns = zeros(length(phase.species))\n spnames = [x.name for x in phase.species]\n for (key,val) in initialconds\n if key == \"T\"\n T = val\n elseif key == \"P\"\n P = val\n elseif key == \"V\"\n V = val\n else\n ind = findfirst(isequal(key),spnames)\n @assert typeof(ind)<: Integer \"$key not found in species list: $spnames\"\n ns[ind] = val\n end\n end\n @assert V != 0.0 || (T != 0.0 && P != 0.0)\n N = sum(ns)\n if V == 0.0\n V = N*R*T/P\n elseif T == 0.0\n T = P*V/(R*N)\n elseif P == 0.0\n P = N*R*T/V\n else\n throw(error(\"ConstantVDomain overspecified with T,P and V\"))\n end\n if sensitivity\n y0 = vcat(ns,T,zeros((length(ns)+1)*(length(ns)+length(phase.reactions))))\n else\n y0 = vcat(ns,T)\n end\n if length(constantspecies) > 0\n spcnames = getfield.(phase.species,:name)\n constspcinds = [findfirst(isequal(k),spcnames) for k in constantspecies]\n else\n constspcinds = Array{Int64,1}()\n end\n if sparse\n jacobian=zeros(typeof(T),length(phase.species)+1,length(phase.species)+1)\n else\n jacobian=zeros(typeof(T),length(phase.species)+1,length(phase.species)+1)\n end\n rxnarray = getreactionindices(phase)\n return ConstantVDomain(phase,interfaces,SVector(phase.species[1].index,phase.species[end].index,phase.species[end].index+1),constspcinds,\n V,rxnarray,jacobian,sensitivity,MVector(false),MVector(0.0)), y0\nend\nexport ConstantVDomain\n\n@with_kw struct ParametrizedTPDomain{N<:AbstractPhase,S<:Integer,W<:Real,W2<:Real,Q<:AbstractArray} <: AbstractVariableKDomain\n phase::N\n interfaces::Array{AbstractInterface,1} = Array{AbstractInterface,1}()\n indexes::Q #assumed to be in ascending order\n constantspeciesinds::Array{S,1}\n T::Function\n P::Function\n rxnarray::Array{UInt16,2}\n jacobian::Array{W,2}\n sensitivity::Bool = false\n jacuptodate::MArray{Tuple{1},Bool,1,1}=MVector(false)\n t::MArray{Tuple{1},W2,1,1}=MVector(0.0)\nend\nfunction ParametrizedTPDomain(;phase::Z,interfaces::Array{Q,1}=Array{EmptyInterface,1}(),initialconds::Dict{X,Any},constantspecies::Array{X2,1}=Array{String,1}(),\n sparse::Bool=false,sensitivity::Bool=false) where {X,X2,Z<:IdealGas,Q<:AbstractInterface}\n\n #set conditions and initialconditions\n T = 0.0\n P = 0.0\n V = 0.0\n ts = 0.0\n ns = zeros(length(phase.species))\n spnames = [x.name for x in phase.species]\n for (key,val) in initialconds\n if key == \"T\"\n T = val\n elseif key == \"P\"\n P = val\n elseif key == \"V\"\n V = val\n elseif key == \"ts\"\n ts = val\n else\n ind = findfirst(isequal(key),spnames)\n @assert typeof(ind) <: Integer \"$key not found in species list: $spnames\"\n ns[ind] = val\n end\n end\n @assert V != 0.0 || (T != 0.0 && P != 0.0)\n if isa(T,AbstractArray)\n q = Spline1D(ts,T;k=3,s=1e-11)\n Tfcn(x::Float64) = q(x)\n elseif isa(T,Function)\n Tfcn = T\n else\n throw(error(\"ParametrizedTPDomain must take \\\"T\\\" as a function or if an array of times for \\\"ts\\\" is supplied as an array of volumes\"))\n end\n if isa(P,AbstractArray)\n v = Spline1D(ts,P;k=3,s=1e-11)\n Pfcn(x::Float64) = v(x)\n elseif isa(P,Function)\n Pfcn = P\n else\n throw(error(\"ParametrizedTPDomain must take \\\"P\\\" as a function or if an array of times for \\\"ts\\\" is supplied as an array of volumes\"))\n end\n\n N = sum(ns)\n V = N*R*Tfcn(0.0)/Pfcn(0.0)\n\n if sensitivity\n y0 = zeros(length(phase.species)*(length(phase.species)+1+length(phase.reactions)))\n else\n y0 = zeros(length(phase.species))\n end\n\n y0[phase.species[1].index:phase.species[end].index] = ns\n\n if length(constantspecies) > 0\n spcnames = getfield.(phase.species,:name)\n constspcinds = [findfirst(isequal(k),spcnames) for k in constantspecies]\n else\n constspcinds = Array{Int64,1}()\n end\n if sparse\n jacobian=zeros(typeof(V),length(phase.species)+1,length(phase.species)+1)\n else\n jacobian=zeros(typeof(V),length(phase.species)+1,length(phase.species)+1)\n end\n rxnarray = getreactionindices(phase)\n return ParametrizedTPDomain(phase,interfaces,SVector(phase.species[1].index,phase.species[end].index),constspcinds,\n Tfcn,Pfcn,rxnarray,jacobian,sensitivity,MVector(false),MVector(0.0)), y0\nend\nexport ParametrizedTPDomain\n\n@with_kw struct ParametrizedVDomain{N<:AbstractPhase,S<:Integer,W<:Real,W2<:Real,Q<:AbstractArray} <: AbstractVariableKDomain\n phase::N\n interfaces::Array{AbstractInterface,1} = Array{AbstractInterface,1}()\n indexes::Q #assumed to be in ascending order\n constantspeciesinds::Array{S,1}\n V::Function\n rxnarray::Array{UInt16,2}\n jacobian::Array{W,2}\n sensitivity::Bool = false\n jacuptodate::MArray{Tuple{1},Bool,1,1}=MVector(false)\n t::MArray{Tuple{1},W2,1,1}=MVector(0.0)\nend\nfunction ParametrizedVDomain(;phase::Z,interfaces::Array{Q,1}=Array{EmptyInterface,1}(),initialconds::Dict{X,Any},constantspecies::Array{X2,1}=Array{String,1}(),\n sparse::Bool=false,sensitivity::Bool=false) where {X,X2,E<:Real,Z<:IdealGas,Q<:AbstractInterface}\n\n #set conditions and initialconditions\n T = 0.0\n P = 0.0\n V = 0.0\n ts = Array{Float64,1}()\n ns = zeros(length(phase.species))\n spnames = [x.name for x in phase.species]\n @assert \"V\" in keys(initialconds)\n for (key,val) in initialconds\n if key == \"T\"\n T = val\n elseif key == \"P\"\n P = val\n elseif key == \"V\"\n V = val\n elseif key == \"ts\"\n ts = val\n else\n ind = findfirst(isequal(key),spnames)\n @assert typeof(ind)<: Integer \"$key not found in species list: $spnames\"\n ns[ind] = val\n end\n end\n @assert isa(V,Function) || isa(V,AbstractArray)\n if isa(V,AbstractArray)\n q = Spline1D(ts,V;k=3,s=1e-11)\n Vfcn = f(x::Float64) = q(x)\n elseif isa(V,Function)\n Vfcn = V\n else\n throw(error(\"ParametrizedVDomain must take \\\"V\\\" as a function or if an array of times for \\\"ts\\\" is supplied as an array of volumes\"))\n end\n N = sum(ns)\n if T == 0.0\n T = P*Vfcn(0.0)/(R*N)\n elseif P == 0.0\n P = N*R*T/Vfcn(0.0)\n else\n ns *= (P*Vfcn(0.0)/(R*T))/sum(ns) #automatically scale down moles if pressure specified\n end\n if sensitivity\n y0 = vcat(ns,T,zeros((length(ns)+1)*(length(ns)+length(phase.reactions))))\n else\n y0 = vcat(ns,T)\n end\n if length(constantspecies) > 0\n spcnames = getfield.(phase.species,:name)\n constspcinds = [findfirst(isequal(k),spcnames) for k in constantspecies]\n else\n constspcinds = Array{Int64,1}()\n end\n if sparse\n jacobian=zeros(typeof(T),length(phase.species)+1,length(phase.species)+1)\n else\n jacobian=zeros(typeof(T),length(phase.species)+1,length(phase.species)+1)\n end\n rxnarray = getreactionindices(phase)\n return ParametrizedVDomain(phase,interfaces,SVector(phase.species[1].index,phase.species[end].index,phase.species[end].index+1),constspcinds,\n Vfcn,rxnarray,jacobian,sensitivity,MVector(false),MVector(0.0)), y0\nend\nexport ParametrizedVDomain\n@with_kw struct ConstantTVDomain{N<:AbstractPhase,S<:Integer,W<:Real, W2<:Real, I<:Integer, Q<:AbstractArray} <: AbstractConstantKDomain\n phase::N\n interfaces::Array{AbstractInterface,1} = Array{AbstractInterface,1}()\n indexes::Q #assumed to be in ascending order\n constantspeciesinds::Array{S,1}\n T::W\n V::W\n kfs::Array{W,1}\n krevs::Array{W,1}\n efficiencyinds::Array{I,1}\n Gs::Array{W,1}\n rxnarray::Array{UInt16,2}\n mu::W = 0.0\n diffusivity::Array{W,1} = Array{Float64,1}()\n jacobian::Array{W,2} = Array{Float64,2}(undef,(0,0))\n sensitivity::Bool = false\n jacuptodate::MArray{Tuple{1},Bool,1,1}=MVector(false)\n t::MArray{Tuple{1},W2,1,1}=MVector(0.0)\nend\nfunction ConstantTVDomain(;phase::Z,interfaces::Array{Q,1}=Array{EmptyInterface,1}(),initialconds::Dict{X,E},constantspecies::Array{X2,1}=Array{String,1}(),\n sparse=false,sensitivity=false) where {E,X,X2, Z<:AbstractPhase,Q<:AbstractInterface,W<:Real}\n #set conditions and initialconditions\n T = 0.0\n V = 0.0\n P = 1.0e9\n if sensitivity\n y0 = zeros(length(phase.species)*(length(phase.species)+1+length(phase.reactions)))\n else\n y0 = zeros(length(phase.species))\n end\n spnames = [x.name for x in phase.species]\n for (key,val) in initialconds\n if key == \"T\"\n T = val\n elseif key == \"P\"\n P = val\n elseif key == \"V\"\n V = val\n else\n ind = findfirst(isequal(key),spnames)\n @assert typeof(ind)<: Integer \"$key not found in species list: $spnames\"\n y0[ind] = val\n end\n end\n @assert T != 0.0\n @assert V != 0.0\n ns = y0\n N = sum(ns)\n\n if length(constantspecies) > 0\n spcnames = getfield.(phase.species,:name)\n constspcinds = [findfirst(isequal(k),spcnames) for k in constantspecies]\n else\n constspcinds = Array{Int64,1}()\n end\n efficiencyinds = [rxn.index for rxn in phase.reactions if typeof(rxn.kinetics)<:AbstractFalloffRate && length(rxn.kinetics.efficiencies) > 0]\n Gs = calcgibbs(phase,T)\n if :solvent in fieldnames(typeof(phase)) && typeof(phase.solvent) != EmptySolvent\n mu = phase.solvent.mu(T)\n else\n mu = 0.0\n end\n if phase.diffusionlimited\n diffs = [x(T=T,mu=mu,P=P) for x in getfield.(phase.species,:diffusion)]\n else\n diffs = Array{Float64,1}()\n end\n P = 1.0e9 #essentiallly assuming this is a liquid\n C = N/V\n kfs,krevs = getkfkrevs(phase=phase,T=T,P=P,C=C,N=N,ns=ns,Gs=Gs,diffs=diffs,V=V)\n if sparse\n jacobian=zeros(typeof(T),length(phase.species),length(phase.species))\n else\n jacobian=zeros(typeof(T),length(phase.species),length(phase.species))\n end\n rxnarray = getreactionindices(phase)\n return ConstantTVDomain(phase,interfaces,SVector(phase.species[1].index,phase.species[end].index),constspcinds,\n T,V,kfs,krevs,efficiencyinds,Gs,rxnarray,mu,diffs,jacobian,sensitivity,MVector(false),MVector(0.0)), y0\nend\nexport ConstantTVDomain\n\n@with_kw struct ParametrizedTConstantVDomain{N<:AbstractPhase,S<:Integer,W<:Real,W2<:Real,Q<:AbstractArray} <: AbstractVariableKDomain\n phase::N\n interfaces::Array{AbstractInterface,1} = Array{AbstractInterface,1}()\n indexes::Q #assumed to be in ascending order\n constantspeciesinds::Array{S,1}\n T::Function\n V::W\n rxnarray::Array{UInt16,2}\n jacobian::Array{W,2}\n sensitivity::Bool = false\n jacuptodate::MArray{Tuple{1},Bool,1,1}=MVector(false)\n t::MArray{Tuple{1},W2,1,1}=MVector(0.0)\nend\nfunction ParametrizedTConstantVDomain(;phase::IdealDiluteSolution,interfaces::Array{Q,1}=Array{EmptyInterface,1}(),initialconds::Dict{X,X3},constantspecies::Array{X2,1}=Array{String,1}(),\n sparse::Bool=false,sensitivity::Bool=false) where {X,X2,X3,Q<:AbstractInterface}\n #set conditions and initialconditions\n T = 0.0\n P = 0.0\n V = 0.0\n ts = Array{Float64,1}()\n ns = zeros(length(phase.species))\n spnames = [x.name for x in phase.species]\n @assert \"V\" in keys(initialconds)\n for (key,val) in initialconds\n if key == \"T\"\n T = val\n elseif key == \"P\"\n P = val\n elseif key == \"V\"\n V = val\n elseif key == \"ts\"\n ts = val\n else\n ind = findfirst(isequal(key),spnames)\n @assert typeof(ind)<: Integer \"$key not found in species list: $spnames\"\n ns[ind] = val\n end\n end\n if isa(T,AbstractArray)\n q = Spline1D(ts,T;k=3,s=1e-11)\n Tfcn = f(x::Float64) = q(x)\n elseif isa(T,Function)\n Tfcn = T\n else\n throw(error(\"ParametrizedTConstantVDomain must take \\\"T\\\" as a function or if an array of times for \\\"ts\\\" is supplied as an array of volumes\"))\n end\n N = sum(ns)\n if P == 0.0\n P = 1e8\n else\n throw(error(\"ParametrizedTConstantVDomain cannot specify P\"))\n end\n if sensitivity\n y0 = zeros(length(phase.species)*(length(phase.species)+1+length(phase.reactions)))\n else\n y0 = zeros(length(phase.species))\n end\n y0[phase.species[1].index:phase.species[end].index] = ns\n if length(constantspecies) > 0\n spcnames = getfield.(phase.species,:name)\n constspcinds = [findfirst(isequal(k),spcnames) for k in constantspecies]\n else\n constspcinds = Array{Int64,1}()\n end\n if sparse\n jacobian=zeros(typeof(V),length(phase.species)+1,length(phase.species)+1)\n else\n jacobian=zeros(typeof(V),length(phase.species)+1,length(phase.species)+1)\n end\n rxnarray = getreactionindices(phase)\n return ParametrizedTConstantVDomain(phase,interfaces,SVector(phase.species[1].index,phase.species[end].index),constspcinds,\n Tfcn,V,rxnarray,jacobian,sensitivity,MVector(false),MVector(0.0)), y0\nend\nexport ParametrizedTConstantVDomain\n\n@inline function calcthermo(d::ConstantTPDomain{W,Y},y::J,t::Q) where {W<:IdealGas,Y<:Integer,J<:AbstractArray{Float64,1},Q<:Float64}\n if t != d.t[1]\n d.t[1] = t\n d.jacuptodate[1] = false\n end\n ns = y[d.indexes[1]:d.indexes[2]]\n N = sum(ns)\n V = N*d.T*R/d.P\n cs = ns./V\n C = N/V\n for ind in d.efficiencyinds #efficiency related rates may have changed\n d.kfs[ind],d.krevs[ind] = getkfkrev(d.phase.reactions[ind],d.phase,d.T,d.P,C,N,ns,d.Gs,d.diffusivity,V)\n end\n return ns,cs,d.T,d.P,V,C,N,d.mu,d.kfs,d.krevs,[],[],[],[],0.0\nend\n\n@inline function calcthermo(d::ConstantTPDomain{W,Y},y::J,t::Q) where {W<:IdealGas,Y<:Integer,J<:AbstractArray,Q<:Real}\n if t != d.t[1]\n if isa(t,Float64)\n d.t[1] = t\n end\n d.jacuptodate[1] = false\n end\n ns = y[d.indexes[1]:d.indexes[2]]\n N = sum(ns)\n V = N*d.T*R/d.P\n cs = ns./V\n C = N/V\n kfs = convert(typeof(y),copy(d.kfs))\n krevs = convert(typeof(y),copy(d.krevs))\n for ind in d.efficiencyinds #efficiency related rates may have changed\n kfs[ind],krevs[ind] = getkfkrev(d.phase.reactions[ind],d.phase,d.T,d.P,C,N,ns,d.Gs,d.diffusivity,V)\n end\n return ns,cs,d.T,d.P,V,C,N,d.mu,kfs,krevs,[],[],[],[],0.0\nend\n\n@inline function calcthermo(d::ConstantVDomain{W,Y},y::J,t::Q) where {W<:IdealGas,Y<:Integer,J<:AbstractArray,Q<:Real}\n if t != d.t[1]\n d.t[1] = t\n d.jacuptodate[1] = false\n end\n ns = y[d.indexes[1]:d.indexes[2]]\n T = y[d.indexes[3]]\n N = sum(ns)\n cs = ns./d.V\n C = N/d.V\n P = C*R*T\n Gs = zeros(length(d.phase.species))\n Us = zeros(length(d.phase.species))\n Cvave = 0.0\n @simd for i = 1:length(d.phase.species)\n @inbounds cpdivR,hdivRT,sdivR = calcHSCpdless(d.phase.species[i].thermo,T)\n @fastmath @inbounds Gs[i] = (hdivRT-sdivR)*R*T\n @fastmath @inbounds Us[i] = (hdivRT-1.0)*R*T\n @fastmath @inbounds Cvave += cpdivR*ns[i]\n end\n @fastmath Cvave *= R/N\n @fastmath Cvave -= R\n if d.phase.diffusionlimited\n diffs = getfield.(d.phase.species,:diffusion)(T=T,mu=mu,P=P)\n else\n diffs = Array{Float64,1}()\n end\n kfs,krevs = getkfkrevs(phase=d.phase,T=T,P=P,C=C,N=N,ns=ns,Gs=Gs,diffs=diffs,V=d.V)\n return ns,cs,T,P,d.V,C,N,0.0,kfs,krevs,[],Us,Gs,diffs,Cvave\nend\n\n@inline function calcthermo(d::ParametrizedVDomain{W,Y},y::J,t::Q) where {W<:IdealGas,Y<:Integer,J<:AbstractArray,Q<:Real}\n if t != d.t[1]\n d.t[1] = t\n d.jacuptodate[1] = false\n end\n V = d.V(t)\n ns = y[d.indexes[1]:d.indexes[2]]\n T = y[d.indexes[3]]\n N = sum(ns)\n cs = ns./V\n C = N/V\n P = C*R*T\n Gs = zeros(length(d.phase.species))\n Us = zeros(length(d.phase.species))\n Cvave = 0.0\n @simd for i = 1:length(d.phase.species)\n @inbounds cpdivR,hdivRT,sdivR = calcHSCpdless(d.phase.species[i].thermo,T)\n @fastmath @inbounds Gs[i] = (hdivRT-sdivR)*R*T\n @fastmath @inbounds Us[i] = (hdivRT-1.0)*R*T\n @fastmath @inbounds Cvave += cpdivR*ns[i]\n end\n @fastmath Cvave *= R/N\n @fastmath Cvave -= R\n if d.phase.diffusionlimited\n diffs = getfield.(d.phase.species,:diffusion)(T=T,mu=mu,P=P)\n else\n diffs = Array{Float64,1}()\n end\n kfs,krevs = getkfkrevs(phase=d.phase,T=T,P=P,C=C,N=N,ns=ns,Gs=Gs,diffs=diffs,V=V)\n return ns,cs,T,P,V,C,N,0.0,kfs,krevs,[],Us,Gs,diffs,Cvave\nend\n\n@inline function calcthermo(d::ParametrizedTConstantVDomain{W,Y},y::J,t::Q) where {W<:IdealDiluteSolution,Y<:Integer,J<:AbstractArray,Q<:Real}\n if t != d.t[1]\n d.t[1] = t\n d.jacuptodate[1] = false\n end\n V = d.V\n T = d.T(t)\n ns = y[d.indexes[1]:d.indexes[2]]\n N = sum(ns)\n cs = ns./V\n C = N/V\n P = C*R*T\n Gs = zeros(length(d.phase.species))\n mu = d.phase.solvent.mu(T)\n for i = 1:length(d.phase.species)\n @inbounds cpdivR,hdivRT,sdivR = calcHSCpdless(d.phase.species[i].thermo,T)\n @fastmath @inbounds Gs[i] = (hdivRT-sdivR)*R*T\n end\n if d.phase.diffusionlimited\n diffs = [x(T=T,mu=mu,P=P) for x in getfield.(d.phase.species,:diffusion)]\n else\n diffs = Array{Float64,1}()\n end\n kfs,krevs = getkfkrevs(phase=d.phase,T=T,P=P,C=C,N=N,ns=ns,Gs=Gs,diffs=diffs,V=V)\n return ns,cs,T,P,V,C,N,0.0,kfs,krevs,[],[],Gs,diffs,0.0\nend\n\n@inline function calcthermo(d::ParametrizedTPDomain{W,Y},y::J,t::Q) where {W<:IdealGas,Y<:Integer,J<:AbstractArray,Q<:Real}\n if t != d.t[1]\n d.t[1] = t\n d.jacuptodate[1] = false\n end\n T = d.T(t)\n @assert T < 10000.0\n P = d.P(t)\n ns = y[d.indexes[1]:d.indexes[2]]\n N = sum(ns)\n V = N*T*R/P\n cs = ns./V\n C = N/V\n P = C*R*T\n Gs = zeros(length(d.phase.species))\n Us = zeros(length(d.phase.species))\n Cvave = 0.0\n @simd for i = 1:length(d.phase.species)\n @inbounds cpdivR,hdivRT,sdivR = calcHSCpdless(d.phase.species[i].thermo,T)\n @fastmath @inbounds Gs[i] = (hdivRT-sdivR)*R*T\n end\n @fastmath Cvave *= R/N\n @fastmath Cvave -= R\n if d.phase.diffusionlimited\n diffs = getfield.(d.phase.species,:diffusion)(T=T,mu=mu,P=P)\n else\n diffs = Array{Float64,1}()\n end\n kfs,krevs = getkfkrevs(phase=d.phase,T=T,P=P,C=C,N=N,ns=ns,Gs=Gs,diffs=diffs,V=V)\n return ns,cs,T,P,V,C,N,0.0,kfs,krevs,[],[],Gs,diffs,0.0\nend\n\n@inline function calcthermo(d::ConstantTVDomain{W,Y},y::J,t::Q) where {W<:IdealDiluteSolution,Y<:Integer,J<:AbstractArray,Q<:Real}\n if t != d.t[1]\n d.t[1] = t\n d.jacuptodate[1] = false\n end\n ns = y[d.indexes[1]:d.indexes[2]]\n N = sum(ns)\n cs = ns./d.V\n C = N/d.V\n P = 1.0e9\n return ns,cs,d.T,P,d.V,C,N,d.mu,d.kfs,d.krevs,[],[],[],[],0.0\nend\nexport calcthermo\n\n@inline function calcdomainderivatives!(d::Q,dydt::Array{Z7,1};t::Z10,T::Z4,P::Z9,Us::Array{Z,1},V::Z2,C::Z3,ns::Array{Z5,1},N::Z6,Cvave::Z8) where {Q<:AbstractDomain,Z10,Z9,Z8<:Real,Z7<:Real,W<:IdealGas,Y<:Integer,Z6,Z,Z2,Z3,Z4,Z5<:Real}\n for ind in d.constantspeciesinds #make dydt zero for constant species\n @inbounds dydt[ind] = 0.0\n end\nend\n\n@inline function calcdomainderivatives!(d::ConstantVDomain{W,Y},dydt::Array{K,1};t::Z10,T::Z4,P::Z9,Us::Array{Z,1},V::Z2,C::Z3,ns::Array{Z5,1},N::Z6,Cvave::Z7) where {Z10,Z9,W<:IdealGas,Z7<:Real,K<:Real,Y<:Integer,Z6,Z,Z2,Z3,Z4,Z5<:Real}\n @views @fastmath @inbounds dydt[d.indexes[3]] = -dot(Us,dydt[d.indexes[1]:d.indexes[2]])/(N*Cvave) #divide by V to cancel ωV to ω\n for ind in d.constantspeciesinds #make dydt zero for constant species\n @inbounds dydt[ind] = 0.0\n end\nend\n\n@inline function calcdomainderivatives!(d::ParametrizedVDomain{W,Y},dydt::Array{K,1};t::Z10,T::Z4,P::Z9,Us::Array{Z,1},V::Z2,C::Z3,ns::Array{Z5,1},N::Z6,Cvave::Z7) where {Z10,Z9,W<:IdealGas,Z7<:Real,K<:Real,Y<:Integer,Z6,Z,Z2,Z3,Z4,Z5<:Real}\n @views @fastmath @inbounds dydt[d.indexes[3]] = (-dot(Us,dydt[d.indexes[1]:d.indexes[2]])-P*Calculus.derivative(d.V,t))/(N*Cvave) #divide by V to cancel ωV to ω\n\n for ind in d.constantspeciesinds #make dydt zero for constant species\n @inbounds dydt[ind] = 0.0\n end\nend\nexport calcdomainderivatives!\n\nfunction getreactionindices(ig::Q) where {Q<:AbstractPhase}\n arr = zeros(UInt16,(6,length(ig.reactions)))\n for (i,rxn) in enumerate(ig.reactions)\n arr[1:length(rxn.reactantinds),i] = rxn.reactantinds\n arr[4:length(rxn.productinds)+3,i] = rxn.productinds\n end\n return arr\nend\nexport getreactionindices\n", "meta": {"hexsha": "284a6de59c71ecf985f34048e749fb3a8f83b45f", "size": 24851, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Domain.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/ReactionMechanismSimulator.jl-c2d78dd2-25c4-5b79-bebc-be6c69dd440f", "max_stars_repo_head_hexsha": "5adc6c1f7e969164cdda182fed497e6ca7c1dc03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-23T21:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-23T21:00:45.000Z", "max_issues_repo_path": "src/Domain.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/ReactionMechanismSimulator.jl-c2d78dd2-25c4-5b79-bebc-be6c69dd440f", "max_issues_repo_head_hexsha": "5adc6c1f7e969164cdda182fed497e6ca7c1dc03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/ReactionMechanismSimulator.jl-c2d78dd2-25c4-5b79-bebc-be6c69dd440f", "max_forks_repo_head_hexsha": "5adc6c1f7e969164cdda182fed497e6ca7c1dc03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4384164223, "max_line_length": 241, "alphanum_fraction": 0.6305178866, "num_tokens": 8182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.19093870143665204}} {"text": "export SimulationBuilder, set!, build\n\nmutable struct SimulationBuilder{N}\n unit_system::UnitSystem\n kernel::Kernel{N}\n eos::EquationOfState\n mass_distribution::InitialMassDistribution{N}\n velocity_distribution::InitialVelocityDistribution{N}\n energy_distribution::InitialEnergyDistribution{N}\n mass_component_type::Tuple{Type,Any}\n energy_component_type::Tuple{Type,Any}\n diffusion_component_type::Tuple{Type,Any}\n boundary_component_type::Tuple{Type,Any}\n stepper_type::Tuple{Type,Any}\n\n function SimulationBuilder(\n mass_distribution::InitialMassDistribution{N},\n energy_distribution::InitialEnergyDistribution{N};\n unit_system::UnitSystem = SI,\n kernel::Kernel{N} = TabulatedKernel(CubicSplineKernel{N}()),\n eos::EquationOfState = AdiabaticIdealGasEOS(1.4, NORMALIZED),\n velocity_distribution::InitialVelocityDistribution{N} = StaticVelocityDistribution{\n N,\n }(),\n ) where {N}\n new{N}(\n unit_system,\n kernel,\n eos,\n mass_distribution,\n velocity_distribution,\n energy_distribution,\n (AdaptiveMass, []),\n (StandardEnergy, []),\n (StandardDiffusion, []),\n (NoBoundaries{N}, []),\n (EulerStepper, []),\n )\n end\nend\n\nfunction Base.show(io::IO, builder::SimulationBuilder{N}) where {N}\n print(\n io,\n \"\"\"\n SimulationBuilder{\n $(N)D\n $(typeof(builder.mass_distribution))\n $(typeof(builder.velocity_distribution))\n $(typeof(builder.energy_distribution))\n $(typeof(builder.eos))\n $(typeof(builder.kernel))\n $(builder.mass_component_type[1])\n $(builder.energy_component_type[1])\n $(builder.diffusion_component_type[1])\n $(builder.boundary_component_type[1])\n $(builder.stepper_type[1])\n }\"\"\",\n )\nend\n\n(Base.:+)(builder::SimulationBuilder, property) = set!(builder, property)\n(Base.:+)(\n builder::SimulationBuilder,\n (property, kwargs)::Tuple{<:Any,NamedTuple},\n) = set!(builder, property, kwargs...)\n\nfunction set!(builder::SimulationBuilder{N}, unit_system::UnitSystem) where {N}\n builder.unit_system = unit_system\n builder\nend\n\nfunction set!(builder::SimulationBuilder{N}, kernel::Kernel{N}) where {N}\n builder.kernel = kernel\n builder\nend\n\nfunction set!(builder::SimulationBuilder{N}, eos::EquationOfState) where {N}\n builder.eos = eos\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n mass_distribution::InitialMassDistribution{N},\n) where {N}\n builder.mass_distribution = mass_distribution\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n velocity_distribution::InitialVelocityDistribution{N},\n) where {N}\n builder.velocity_distribution = velocity_distribution\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n energy_distribution::InitialEnergyDistribution{N},\n) where {N}\n builder.energy_distribution = energy_distribution\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n mass_component_type::Type{<:MassComponent};\n kwargs...,\n) where {N}\n builder.mass_component_type = (mass_component_type, kwargs)\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n energy_component_type::Type{<:EnergyComponent};\n kwargs...,\n) where {N}\n builder.energy_component_type = (energy_component_type, kwargs)\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n diffusion_component_type::Type{<:DiffusionComponent};\n kwargs...,\n) where {N}\n builder.diffusion_component_type = (diffusion_component_type, kwargs)\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n boundary_component_type::Type{<:BoundaryComponent{N}};\n kwargs...,\n) where {N}\n builder.boundary_component_type = (boundary_component_type, kwargs)\n builder\nend\n\nfunction set!(\n builder::SimulationBuilder{N},\n stepper_type::Type{<:Stepper{N}};\n kwargs...,\n) where {N}\n builder.stepper_type = (stepper_type, kwargs)\n builder\nend\n\nfunction build(builder::SimulationBuilder{N}) where {N}\n mass_component, positions = builder.mass_component_type[1](\n builder.kernel,\n builder.mass_distribution;\n builder.mass_component_type[2]...,\n )\n mass_densities = get_mass_densities(mass_component)\n energy_component = builder.energy_component_type[1](\n positions,\n mass_densities,\n builder.energy_distribution,\n builder.eos;\n builder.energy_component_type[2]...,\n )\n diffusion_component =\n builder.diffusion_component_type[1](builder.diffusion_component_type[2]...)\n velocities =\n Velocities(positions, mass_densities, builder.velocity_distribution)\n boundary_component =\n builder.boundary_component_type[1](builder.boundary_component_type[2]...)\n stepper = builder.stepper_type[1](\n positions,\n velocities,\n mass_component,\n energy_component,\n diffusion_component,\n boundary_component,\n builder.eos;\n builder.stepper_type[2]...,\n )\n stepper\nend\n", "meta": {"hexsha": "91f3df6fea0bbe4d0581e2643bb657b08462d7ee", "size": 5245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulation.jl", "max_stars_repo_name": "lars-frogner/Whirl", "max_stars_repo_head_hexsha": "34b096a16fceea6ee6a947e6568d226d58b4ce70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation.jl", "max_issues_repo_name": "lars-frogner/Whirl", "max_issues_repo_head_hexsha": "34b096a16fceea6ee6a947e6568d226d58b4ce70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation.jl", "max_forks_repo_name": "lars-frogner/Whirl", "max_forks_repo_head_hexsha": "34b096a16fceea6ee6a947e6568d226d58b4ce70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5054347826, "max_line_length": 91, "alphanum_fraction": 0.6722592946, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19089760236349335}} {"text": "# MIT License\n#\n# Copyright (c) 2018 Martin Biel\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n DeterministicEquivalent\n\nDeterministic equivalent memory structure. Stochastic program is stored as one large optimization problem. Supported by any standard `AbstractOptimizer`.\n\n\"\"\"\nstruct DeterministicEquivalent{N, M, S <: NTuple{M, Scenarios}} <: AbstractStochasticStructure{N}\n decisions::Decisions{N}\n scenarios::S\n model::JuMP.Model\n proxy::NTuple{N,JuMP.Model}\n\n function DeterministicEquivalent(decisions::Decisions{N}, scenarios::NTuple{M, Scenarios}) where {N, M}\n M == N - 1 || error(\"Inconsistent number of stages $N and number of scenario types $M\")\n proxy = ntuple(Val{N}()) do _\n Model()\n end\n S = typeof(scenarios)\n return new{N,M,S}(decisions, scenarios, Model(), proxy)\n end\nend\n\nfunction StochasticStructure(decisions::Decisions{N}, scenario_types::ScenarioTypes{M}, ::Deterministic) where {N, M}\n scenarios = ntuple(Val(M)) do i\n Vector{scenario_types[i]}()\n end\n return DeterministicEquivalent(decisions, scenarios)\nend\n\nfunction StochasticStructure(decisions::Decisions{N}, scenarios::NTuple{M, Vector{<:AbstractScenario}}, ::Deterministic) where {N, M}\n return DeterministicEquivalent(decisions, scenarios)\nend\n\n# Base overloads #\n# ========================== #\nfunction Base.print(io::IO, structure::DeterministicEquivalent)\n print(io, \"Deterministic equivalent problem\\n\")\n print(io, structure.model)\nend\n# ========================== #\n\n# MOI #\n# ========================== #\nfunction MOI.get(structure::DeterministicEquivalent, attr::MOI.AbstractModelAttribute)\n return MOI.get(backend(structure.model), attr)\nend\nfunction MOI.get(structure::DeterministicEquivalent, attr::MOI.AbstractVariableAttribute, index::MOI.VariableIndex)\n return MOI.get(backend(structure.model), attr, index)\nend\nfunction MOI.get(structure::DeterministicEquivalent, attr::MOI.AbstractConstraintAttribute, ci::CI)\n return MOI.get(backend(structure.model), attr, ci)\nend\nfunction MOI.get(structure::DeterministicEquivalent, attr::MOI.AbstractConstraintAttribute, ci::CI{F,S}) where {F <: SingleDecision, S}\n con_ref = ConstraintRef(structure.model, ci)\n return MOI.get(structure.model, attr, con_ref)\nend\nfunction MOI.get(structure::DeterministicEquivalent{N}, attr::ScenarioDependentModelAttribute) where N\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n if attr.attr isa MOI.ObjectiveFunction\n return get_stage_objective(structure.decisions, attr.stage, attr.scenario_index)[2]\n elseif attr.attr isa MOI.ObjectiveFunctionType\n return typeof(get_stage_objective(structure.decisions, attr.stage, attr.scenario_index)[2])\n elseif attr.attr isa MOI.ObjectiveSense\n return get_stage_objective(structure.decisions, attr.stage, attr.scenario_index)[1]\n elseif attr.attr isa MOI.ObjectiveValue || attr.attr isa MOI.DualObjectiveValue\n return MOIU.eval_variables(get_stage_objective(structure.decisions, attr.stage, attr.scenario_index)[2]) do idx\n return MOI.get(backend(structure.model), MOI.VariablePrimal(), idx)\n end\n else\n # Most attributes are shared with the deterministic equivalent\n return MOI.get(backend(structure.model), attr.attr)\n end\nend\nfunction MOI.get(structure::DeterministicEquivalent, attr::ScenarioDependentVariableAttribute, index::MOI.VariableIndex)\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, index, attr.scenario_index)\n return MOI.get(backend(structure.model), attr.attr, mapped_vi)\nend\nfunction MOI.get(structure::DeterministicEquivalent, attr::ScenarioDependentConstraintAttribute, ci::CI)\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_ci = mapped_index(structure, ci, attr.scenario_index)\n return MOI.get(backend(structure.model), attr.attr, mapped_ci)\nend\nfunction MOI.get(structure::DeterministicEquivalent, attr::ScenarioDependentConstraintAttribute, ci::CI{F,S}) where {F <: SingleDecision, S}\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, MOI.VariableIndex(ci.value), attr.scenario_index)\n mapped_ci = CI{F,S}(mapped_vi.value)\n con_ref = ConstraintRef(structure.model, mapped_ci)\n return MOI.get(structure.model, attr.attr, con_ref)\nend\nfunction MOI.get(structure::DeterministicEquivalent, attr::ScenarioDependentConstraintAttribute, ci::CI{F,S}) where {F <: MOI.SingleVariable, S}\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, MOI.VariableIndex(ci.value), attr.scenario_index)\n mapped_ci = CI{F,S}(mapped_vi.value)\n return MOI.get(backend(structure.model), attr.attr, mapped_ci)\nend\n\nfunction MOI.set(structure::DeterministicEquivalent, attr::MOI.Silent, flag)\n MOI.set(backend(structure.model), attr, flag)\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent{N}, attr::MOI.AbstractModelAttribute, value) where N\n if attr isa MOI.ObjectiveFunction\n # Get full objective+sense\n dep_obj = copy(value)\n obj_sense = objective_sense(structure.model)\n # Update first-stage objective\n set_stage_objective!(structure.decisions, 1, 1, obj_sense, value)\n # Update main objective\n for (i, sub_objective) in enumerate(structure.decisions.stage_objectives[2])\n (sense, func) = sub_objective\n if obj_sense == sense\n dep_obj += probability(structure, 2, i) * func\n else\n dep_obj -= probability(structure, 2, i) * func\n end\n end\n MOI.set(backend(structure.model), attr, dep_obj)\n elseif attr isa MOI.ObjectiveSense\n # Get full objective+sense\n prev_sense, dep_obj = get_stage_objective(structure.decisions, 1, 1)\n # Update first-stage objective\n set_stage_objective!(structure.decisions, 1, 1, value, dep_obj)\n # Update main objective (if necessary)\n if value != prev_sense\n for (i, sub_objective) in enumerate(structure.decisions.stage_objectives[2])\n (sense, func) = sub_objective\n if value == sense\n dep_obj += probability(structure, 2, i) * func\n else\n dep_obj -= probability(structure, 2, i) * func\n end\n end\n MOI.set(backend(structure.model), MOI.ObjectiveFunction{typeof(dep_obj)}(), dep_obj)\n end\n MOI.set(backend(structure.model), MOI.ObjectiveSense(), value)\n else\n # Most attributes are shared with the deterministic equivalent\n MOI.set(backend(structure.model), attr, value)\n end\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent, attr::MOI.AbstractVariableAttribute,\n index::MOI.VariableIndex, value)\n MOI.set(backend(structure.model), attr, index, value)\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent, attr::MOI.AbstractConstraintAttribute,\n ci::MOI.ConstraintIndex, value)\n con_ref = ConstraintRef(structure.model, mapped_ci)\n MOI.set(structure.model, attr.attr, con_ref, value)\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent{N}, attr::ScenarioDependentModelAttribute, value) where N\n if attr.attr isa MOI.ObjectiveFunction\n # Get full objective+sense\n obj_sense = objective_sense(structure.model)\n dep_obj = objective_function(structure.model)\n # Update subobjective\n (sub_sense, prev_func) = get_stage_objective(structure.model, attr.stage, attr.scenario_index, Val{N}())\n set_stage_objective!(structure.decisions, attr.stage, attr.scenario_index, sub_sense, value)\n sub_obj = jump_function(structure.model, value)\n # Update main objective\n if obj_sense == sub_sense\n dep_obj += probability(structure, attr.stage, attr.scenario_index) * (sub_obj - prev_func)\n else\n dep_obj -= probability(structure, attr.stage, attr.scenario_index) * (sub_obj - prev_func)\n end\n set_objective_function(structure.model, dep_obj)\n elseif attr.attr isa MOI.ObjectiveSense\n # Get current\n (prev_sense, func) = get_stage_objective(structure.model, attr.stage, attr.scenario_index, Val{N}())\n if value == prev_sense\n # Nothing to do\n return nothing\n end\n # Get full objective+sense\n obj_sense = objective_sense(structure.model)\n dep_obj = objective_function(structure.model)\n # Update subobjective sense\n set_stage_objective!(structure.decisions, attr.stage, attr.scenario_index, value, moi_function(func))\n # Update main objective\n if value == obj_sense\n dep_obj += 2 * probability(structure, attr.stage, attr.scenario_index) * func\n else\n dep_obj -= 2 * probability(structure, attr.stage, attr.scenario_index) * func\n end\n set_objective_function(structure.model, dep_obj)\n else\n # Most attributes are shared with the deterministic equivalent\n MOI.set(backend(structure.model), attr.attr, value)\n end\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent, attr::ScenarioDependentVariableAttribute,\n index::MOI.VariableIndex, value)\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, index, attr.scenario_index)\n MOI.set(backend(structure.model), attr.attr, mapped_vi, value)\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent, attr::ScenarioDependentConstraintAttribute,\n ci::CI, value)\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_ci = mapped_index(structure, ci, attr.scenario_index)\n MOI.set(backend(structure.model), attr.attr, mapped_ci, value)\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent, attr::ScenarioDependentConstraintAttribute,\n ci::CI{F,S}, value) where {F <: SingleDecision, S}\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, MOI.VariableIndex(ci.value), attr.scenario_index)\n mapped_ci = CI{F,S}(mapped_vi.value)\n con_ref = ConstraintRef(structure.model, mapped_ci)\n MOI.set(structure.model, attr.attr, con_ref, value)\n return nothing\nend\nfunction MOI.set(structure::DeterministicEquivalent, attr::ScenarioDependentConstraintAttribute,\n ci::CI{F,S}, value) where {F <: MOI.SingleVariable, S}\n n = num_scenarios(structure, attr.stage)\n 1 <= attr.scenario_index <= n || error(\"Scenario index $attr.scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, MOI.VariableIndex(ci.value), attr.scenario_index)\n mapped_ci = CI{F,S}(mapped_vi.value)\n MOI.set(backend(structure.model), attr.attr, mapped_ci, value)\n return nothing\nend\n\nfunction MOI.is_valid(structure::DeterministicEquivalent, index::MOI.VariableIndex, stage::Integer)\n stage == 1 || error(\"No scenario index specified.\")\n return MOI.is_valid(backend(structure.model), index)\nend\nfunction MOI.is_valid(structure::DeterministicEquivalent, index::MOI.VariableIndex, stage::Integer, scenario_index::Integer)\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, index, scenario_index)\n return MOI.is_valid(backend(structure.model), mapped_vi)\nend\nfunction MOI.is_valid(structure::DeterministicEquivalent, ci::MOI.ConstraintIndex{F,S}, stage::Integer) where {F, S}\n stage == 1 || error(\"No scenario index specified.\")\n return MOI.is_valid(backend(structure.model), ci)\nend\nfunction MOI.is_valid(structure::DeterministicEquivalent, ci::MOI.ConstraintIndex{F,S}, stage::Integer, scenario_index::Integer) where {F, S}\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_ci = mapped_index(structure, ci, scenario_index)\n return MOI.is_valid(backend(structure.model), mapped_ci)\nend\nfunction MOI.delete(structure::DeterministicEquivalent, indices::Vector{MOI.VariableIndex}, stage::Integer)\n stage == 1 || error(\"No scenario index specified.\")\n JuMP.delete(structure.model, DecisionRef.(structure.model, indices))\n return nothing\nend\nfunction MOI.delete(structure::DeterministicEquivalent{N}, indices::Vector{MOI.VariableIndex}, stage::Integer, scenario_index::Integer) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_indices = map(indices) do index\n return mapped_index(structure, index, scenario_index)\n end\n JuMP.delete(structure.model, DecisionRef.(structure.model, mapped_indices))\n return nothing\nend\nfunction MOI.delete(structure::DeterministicEquivalent, ci::MOI.ConstraintIndex, stage::Integer)\n stage == 1 || error(\"No scenario index specified.\")\n MOI.delete(backend(structure.model), ci)\n return nothing\nend\nfunction MOI.delete(structure::DeterministicEquivalent, cis::Vector{<:MOI.ConstraintIndex}, stage::Integer)\n stage == 1 || error(\"No scenario index specified.\")\n MOI.delete(backend(structure.model), cis)\n return nothing\nend\nfunction MOI.delete(structure::DeterministicEquivalent{N}, ci::MOI.ConstraintIndex, stage::Integer, scenario_index::Integer) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_ci = mapped_index(structure, ci, scenario_index)\n MOI.delete(backend(structure.model), mapped_ci)\n return nothing\nend\nfunction MOI.delete(structure::DeterministicEquivalent{N}, cis::Vector{<:MOI.ConstraintIndex}, stage::Integer, scenario_index::Integer) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_cis = map(cis) do ci\n return mapped_index(structure, ci, scenario_index)\n end\n MOI.delete(backend(structure.model), mapped_cis)\n return nothing\nend\n\n# JuMP #\n# ========================== #\nfunction decision_dispatch(decision_function::Function,\n structure::DeterministicEquivalent{N},\n index::MOI.VariableIndex,\n stage::Integer,\n args...) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage == 1 || error(\"No scenario index specified.\")\n dref = DecisionRef(structure.model, index)\n return decision_function(dref, args...)\nend\nfunction scenario_decision_dispatch(decision_function::Function,\n structure::DeterministicEquivalent{N},\n index::MOI.VariableIndex,\n stage::Integer,\n scenario_index::Integer,\n args...) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, index, scenario_index)\n dref = DecisionRef(structure.model, mapped_vi)\n return decision_function(dref, args...)\nend\nfunction decision_dispatch!(decision_function!::Function,\n structure::DeterministicEquivalent{N},\n index::MOI.VariableIndex,\n stage::Integer,\n args...) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage == 1 || error(\"No scenario index specified.\")\n dref = DecisionRef(structure.model, index)\n decision_function!(dref, args...)\n return nothing\nend\nfunction scenario_decision_dispatch!(decision_function!::Function,\n structure::DeterministicEquivalent{N},\n index::MOI.VariableIndex,\n stage::Integer,\n scenario_index::Integer,\n args...) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, index, scenario_index)\n dref = DecisionRef(structure.model, mapped_vi)\n decision_function!(dref, args...)\n return nothing\nend\n\nfunction JuMP.fix(structure::DeterministicEquivalent{N}, index::MOI.VariableIndex, stage::Integer, val::Number) where N\n dref = DecisionRef(structure.model, index)\n fix(dref, val)\n return nothing\nend\nfunction JuMP.fix(structure::DeterministicEquivalent{N}, index::MOI.VariableIndex, stage::Integer, scenario_index::Integer, val::Number) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n # Fix mapped decision\n mapped_vi = mapped_index(structure, index, scenario_index)\n dref = DecisionRef(structure.model, mapped_vi)\n fix(dref, val)\n return nothing\nend\nfunction JuMP.unfix(structure::DeterministicEquivalent{N}, index::MOI.VariableIndex, stage::Integer) where N\n dref = DecisionRef(structure.model, index)\n unfix(dref)\n return nothing\nend\nfunction JuMP.unfix(structure::DeterministicEquivalent{N}, index::MOI.VariableIndex, stage::Integer, scenario_index::Integer) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n # Unfix mapped decision\n mapped_vi = mapped_index(structure, index, scenario_index)\n dref = DecisionRef(structure.model, mapped_vi)\n unfix(dref)\n return nothing\nend\n\nfunction JuMP.set_objective_sense(structure::DeterministicEquivalent, stage::Integer, sense::MOI.OptimizationSense)\n if stage == 1\n # Changing the first-stage sense modifies the whole objective as usual\n MOI.set(structure, MOI.ObjectiveSense(), sense)\n else\n # Every sub-objective in the given stage should be changed\n for scenario_index in 1:num_scenarios(structure, stage)\n attr = ScenarioDependentModelAttribute(stage, scenario_index, MOI.ObjectiveSense())\n MOI.set(structure, attr, sense)\n end\n end\n return nothing\nend\n\nfunction JuMP.objective_function_type(structure::DeterministicEquivalent)\n return jump_function_type(structure.model,\n MOI.get(structure, MOI.ObjectiveFunctionType()))\nend\nfunction JuMP.objective_function_type(structure::DeterministicEquivalent{N}, stage::Integer, scenario_index::Integer) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n attr = ScenarioDependentModelAttribute(stage, scenario_index, MOI.ObjectiveFunctionType())\n return jump_function_type(structure.model,\n MOI.get(structure, attr))\nend\n\nfunction JuMP.objective_function(structure::DeterministicEquivalent, FunType::Type{<:AbstractJuMPScalar})\n MOIFunType = moi_function_type(FunType)\n func = MOI.get(structure,\n MOI.ObjectiveFunction{MOIFunType}())::MOIFunType\n return JuMP.jump_function(structure, 1, func)\nend\nfunction JuMP.objective_function(structure::DeterministicEquivalent{N}, stage::Integer, FunType::Type{<:AbstractJuMPScalar}) where N\n if stage == 1\n (sense, obj::FunType) = get_stage_objective(structure.model, 1, Val{N}())\n return obj\n else\n return objective_function(structure.proxy, FunType)\n end\nend\nfunction JuMP.objective_function(structure::DeterministicEquivalent{N},\n stage::Integer,\n scenario_index::Integer,\n FunType::Type{<:AbstractJuMPScalar}) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n MOIFunType = moi_function_type(FunType)\n attr = ScenarioDependentModelAttribute(stage, scenario_index, MOI.ObjectiveFunction{MOIFunType}())\n func = MOI.get(structure, attr)::MOIFunType\n return JuMP.jump_function(structure, stage, scenario_index, func)\nend\n\nfunction JuMP._moi_optimizer_index(structure::DeterministicEquivalent, index::VI)\n return decision_index(backend(structure.model), index)\nend\nfunction JuMP._moi_optimizer_index(structure::DeterministicEquivalent, index::VI, scenario_index::Integer)\n mapped_vi = mapped_index(structure, index, scenario_index)\n return decision_index(backend(structure.model), mapped_vi)\nend\nfunction JuMP._moi_optimizer_index(structure::DeterministicEquivalent, ci::CI)\n return decision_index(backend(structure.model), ci)\nend\nfunction JuMP._moi_optimizer_index(structure::DeterministicEquivalent, ci::CI{F,S}) where {F <: SingleDecision, S}\n inner = mapped_constraint(structure.decisions, ci)\n inner.value == 0 && error(\"Constraint $ci not properly mapped.\")\n return decision_index(backend(structure.model), inner)\nend\nfunction JuMP._moi_optimizer_index(structure::DeterministicEquivalent, ci::CI, scenario_index::Integer)\n mapped_ci = mapped_index(structure, ci, scenario_index)\n return decision_index(backend(structure.model), mapped_ci)\nend\nfunction JuMP._moi_optimizer_index(structure::DeterministicEquivalent, ci::CI{F,S}, scenario_index::Integer) where {F <: SingleDecision, S}\n mapped_vi = mapped_index(structure, MOI.VariableIndex(ci.value), scenario_index)\n mapped_ci = CI{F,S}(mapped_vi.value)\n inner = mapped_constraint(structure.decisions, mapped_ci)\n inner.value == 0 && error(\"Constraint $mapped_ci not properly mapped.\")\n return decision_index(backend(structure.model), inner)\nend\n\nfunction JuMP.set_objective_coefficient(structure::DeterministicEquivalent{N}, index::VI, var_stage::Integer, stage::Integer, coeff::Real) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n var_stage <= stage || error(\"Can only modify coefficient in current stage of decision or subsequent stages from where decision is taken.\")\n if var_stage == 1 && stage == 1\n # Use temporary model to apply modification\n obj = get_stage_objective(structure.model, 1, Val{N}())[2]\n moi_obj = moi_function(obj)\n m = Model()\n MOI.set(backend(m), MOI.ObjectiveFunction{typeof(moi_obj)}(), moi_obj)\n dref = DecisionRef(m, index)\n set_objective_coefficient(m, dref, coeff)\n obj = objective_function(m)\n F = moi_function_type(typeof(obj))\n # Modify full objective\n MOI.set(structure, MOI.ObjectiveFunction{F}(), moi_function(obj))\n elseif (var_stage == 1 && stage > 1) || var_stage > 1\n for scenario_index in 1:num_scenarios(structure, stage)\n # Use temporary model to apply modification\n obj = get_stage_objective(structure.model, stage, scenario_index, Val{N}())[2]\n moi_obj = moi_function(obj)\n m = Model()\n MOI.set(backend(m), MOI.ObjectiveFunction{typeof(moi_obj)}(), moi_obj)\n dref = DecisionRef(m, index)\n set_objective_coefficient(m, dref, coeff)\n obj = objective_function(m)\n attr = ScenarioDependentModelAttribute(stage, scenario_index, MOI.ObjectiveFunction{typeof(obj)}())\n MOI.set(structure, attr, obj)\n end\n end\n return nothing\nend\nfunction JuMP.set_objective_coefficient(structure::DeterministicEquivalent{N}, index::VI, var_stage::Integer, stage::Integer, scenario_index::Integer, coeff::Real) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n if var_stage == 1\n # Use temporary model to apply modification\n obj = get_stage_objective(structure.model, stage, scenario_index, Val{N}())[2]\n moi_obj = moi_function(obj)\n m = Model()\n MOI.set(backend(m), MOI.ObjectiveFunction{typeof(moi_obj)}(), moi_obj)\n dref = DecisionRef(m, index)\n set_objective_coefficient(m, dref, coeff)\n obj = objective_function(m)\n F = moi_function_type(typeof(obj))\n attr = ScenarioDependentModelAttribute(stage, scenario_index, MOI.ObjectiveFunction{F}())\n MOI.set(structure, attr, moi_function(obj))\n else\n # Use temporary model to apply modification\n sense, obj = get_stage_objective(structure.model, stage, scenario_index, Val{N}())\n moi_obj = moi_function(obj)\n m = Model()\n MOI.set(backend(m), MOI.ObjectiveFunction{typeof(moi_obj)}(), moi_obj)\n mapped_vi = mapped_index(structure, index, scenario_index)\n dref = DecisionRef(m, mapped_vi)\n set_objective_coefficient(m, dref, coeff)\n obj = objective_function(m)\n set_stage_objective!(structure.decisions, stage, scenario_index, sense, moi_function(obj))\n # Set coefficient of mapped second-stage variable\n dref = DecisionRef(structure.model, mapped_vi)\n set_objective_coefficient(structure.model, dref, probability(structure, stage, scenario_index) * coeff)\n end\n return nothing\nend\n\nfunction JuMP.set_normalized_coefficient(structure::DeterministicEquivalent,\n ci::CI{F,S},\n index::VI,\n value) where {T, F <: Union{AffineDecisionFunction{T}, QuadraticDecisionFunction{T}}, S}\n MOI.modify(backend(structure.model), ci,\n DecisionCoefficientChange(index, convert(T, value)))\n return nothing\nend\nfunction JuMP.set_normalized_coefficient(structure::DeterministicEquivalent{N},\n ci::CI{F,S},\n index::VI,\n var_stage::Integer,\n stage::Integer,\n scenario_index::Integer,\n value) where {N, T, F <: Union{AffineDecisionFunction{T}, QuadraticDecisionFunction{T}}, S}\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_vi = if var_stage == 1\n mapped_vi = index\n else\n mapped_vi = mapped_index(structure, index, scenario_index)\n end\n mapped_ci = mapped_index(structure, ci, scenario_index)\n MOI.modify(backend(structure.model), mapped_ci,\n DecisionCoefficientChange(mapped_vi, convert(T, value)))\n return nothing\nend\n\nfunction JuMP.normalized_coefficient(structure::DeterministicEquivalent{N},\n ci::CI{F,S},\n index::VI,\n var_stage::Integer,\n stage::Integer,\n scenario_index::Integer) where {N, T, F <: Union{AffineDecisionFunction{T}, QuadraticDecisionFunction{T}}, S}\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_ci = mapped_index(structure, ci, scenario_index)\n f = MOI.get(structure, MOI.ConstraintFunction(), mapped_ci)::F\n dref = if var_stage == 1\n dref = DecisionRef(structure.model, index)\n else\n mapped_vi = mapped_index(structure, index, scenario_index)\n dref = DecisionRef(structure.model, mapped_vi)\n end\n return JuMP._affine_coefficient(jump_function(structure.model, f), dref)\nend\n\nfunction JuMP.set_normalized_rhs(structure::DeterministicEquivalent,\n ci::CI{F,S},\n value) where {T,\n F <: Union{AffineDecisionFunction{T}, QuadraticDecisionFunction{T}},\n S <: MOIU.ScalarLinearSet{T}}\n MOI.set(backend(structure.model), MOI.ConstraintSet(), ci,\n S(convert(T, value)))\n return nothing\nend\nfunction JuMP.set_normalized_rhs(structure::DeterministicEquivalent{N},\n ci::CI{F,S},\n stage::Integer,\n scenario_index::Integer,\n value) where {N,\n T,\n F <: Union{AffineDecisionFunction{T}, QuadraticDecisionFunction{T}},\n S <: MOIU.ScalarLinearSet{T}}\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_ci = mapped_index(structure, ci, scenario_index)\n MOI.set(backend(structure.model), MOI.ConstraintSet(), mapped_ci,\n S(convert(T, value)))\n return nothing\nend\n\nfunction DecisionRef(structure::DeterministicEquivalent, index::VI)\n return DecisionRef(structure.model, index)\nend\nfunction DecisionRef(structure::DeterministicEquivalent, index::VI, stage::Integer, scenario_index::Integer)\n mapped_vi = mapped_index(structure, index, scenario_index)\n return DecisionRef(structure.model, mapped_vi)\nend\nfunction DecisionRef(structure::DeterministicEquivalent{N}, index::VI, at_stage::Integer, stage::Integer, scenario_index::Integer) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n at_stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, at_stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n return DecisionRef(structure.model, index)\nend\n\nfunction JuMP.jump_function(structure::DeterministicEquivalent{N},\n stage::Integer,\n f::MOI.AbstractFunction) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n if stage == 1\n return JuMP.jump_function(structure.model, f)\n else\n return JuMP.jump_function(structure.proxy[stage], f)\n end\nend\nfunction JuMP.jump_function(structure::DeterministicEquivalent{N},\n stage::Integer,\n scenario_index::Integer,\n f::MOI.AbstractFunction) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n return JuMP.jump_function(structure.model, f)\nend\n\nfunction JuMP.relax_integrality(structure::DeterministicEquivalent)\n unrelax = relax_decision_integrality(structure.model)\n return unrelax\nend\n\n# Getters #\n# ========================== #\nfunction structure_name(structure::DeterministicEquivalent)\n return \"Deterministic equivalent\"\nend\nfunction scenario_types(structure::DeterministicEquivalent{N}) where N\n return ntuple(Val{N-1}()) do i\n eltype(structure.scenarios[i])\n end\nend\nfunction proxy(structure::DeterministicEquivalent{N}, stage::Integer) where N\n 1 <= stage <= N || error(\"Stage $stage not in range 1 to $N.\")\n return structure.proxy[stage]\nend\nfunction decision(structure::DeterministicEquivalent{N}, index::MOI.VariableIndex, stage::Integer) where N\n stage == 1 || error(\"No scenario index specified.\")\n return decision(structure.decisions, stage, index)\nend\nfunction decision(structure::DeterministicEquivalent{N}, index::MOI.VariableIndex, stage::Integer, scenario_index::Integer) where N\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n mapped_vi = mapped_index(structure, index, scenario_index)\n return decision(structure.decisions, stage, mapped_vi)\nend\nfunction scenario(structure::DeterministicEquivalent{N}, stage::Integer, scenario_index::Integer) where N\n return structure.scenarios[stage-1][scenario_index]\nend\nfunction scenarios(structure::DeterministicEquivalent{N}, stage::Integer) where N\n return structure.scenarios[stage-1]\nend\nfunction subproblem(structure::DeterministicEquivalent, stage::Integer, scenario_index::Integer)\n error(\"The determinstic equivalent is not decomposed into subproblems.\")\nend\nfunction subproblems(structure::DeterministicEquivalent, stage::Integer)\n error(\"The determinstic equivalent is not decomposed into subproblems.\")\nend\nfunction num_subproblems(structure::DeterministicEquivalent, stage::Integer)\n return 0\nend\nfunction deferred(structure::DeterministicEquivalent)\n return num_variables(structure.model) == 0\nend\n# ========================== #\n\n# Setters\n# ========================== #\nfunction update_known_decisions!(structure::DeterministicEquivalent)\n update_known_decisions!(structure.model)\n return nothing\nend\nfunction update_known_decisions!(structure::DeterministicEquivalent, stage::Integer, scenario_index::Integer)\n stage > 1 || error(\"There are no scenarios in the first stage.\")\n n = num_scenarios(structure, stage)\n 1 <= scenario_index <= n || error(\"Scenario index $scenario_index not in range 1 to $n.\")\n update_known_decisions!(structure.model)\n return nothing\nend\n\nfunction add_scenario!(structure::DeterministicEquivalent, stage::Integer, scenario::AbstractScenario)\n push!(scenarios(structure, stage), scenario)\n return nothing\nend\nfunction add_worker_scenario!(structure::DeterministicEquivalent, stage::Integer, scenario::AbstractScenario, w::Integer)\n add_scenario!(structure, scenario, stage)\n return nothing\nend\nfunction add_scenario!(scenariogenerator::Function, structure::DeterministicEquivalent, stage::Integer)\n add_scenario!(structure, stage, scenariogenerator())\n return nothing\nend\nfunction add_worker_scenario!(scenariogenerator::Function, structure::DeterministicEquivalent, stage::Integer, w::Integer)\n add_scenario!(scenariogenerator, structure, stage)\n return nothing\nend\nfunction add_scenarios!(structure::DeterministicEquivalent, stage::Integer, _scenarios::Vector{<:AbstractScenario})\n append!(scenarios(structure, stage), _scenarios)\n return nothing\nend\nfunction add_worker_scenarios!(structure::DeterministicEquivalent, stage::Integer, scenarios::Vector{<:AbstractScenario}, w::Integer)\n add_scenarios!(structure, scenarios, stasge)\n return nothing\nend\nfunction add_scenarios!(scenariogenerator::Function, structure::DeterministicEquivalent, stage::Integer, n::Integer)\n for i = 1:n\n add_scenario!(structure, stage) do\n return scenariogenerator()\n end\n end\n return nothing\nend\nfunction add_worker_scenarios!(scenariogenerator::Function, structure::DeterministicEquivalent, stage::Integer, n::Integer, w::Integer)\n add_scenarios!(scenariogenerator, structure, n, stage)\n return nothing\nend\nfunction sample!(structure::DeterministicEquivalent, stage::Integer, sampler::AbstractSampler, n::Integer)\n sample!(scenarios(structure, stage), sampler, n)\n return nothing\nend\n# ========================== #\n\n# Indices\n# ========================== #\nfunction mapped_index(structure::DeterministicEquivalent{2}, index::MOI.VariableIndex, scenario_index::Integer)\n # The initial number of first-stage decisions is always given by\n num_first_stage_decisions = MOI.get(structure.proxy[1], MOI.NumberOfConstraints{MOI.SingleVariable,SingleDecisionSet{Float64}}())\n # Calculate offset from first-stage auxilliary variables (first-stage decisions are included in second-stage proxy, so deduct them)\n first_stage_offset = MOI.get(structure.proxy[1], MOI.NumberOfVariables()) - num_first_stage_decisions\n # Calculate offset from extra counts of first-stage decisions from second-stage proxy\n first_stage_decision_offset = -(scenario_index - 1) * num_first_stage_decisions\n # Calculate offset from second-stage variables\n scenario_offset = (scenario_index - 1) * MOI.get(structure.proxy[2], MOI.NumberOfVariables())\n return MOI.VariableIndex(index.value + first_stage_offset + first_stage_decision_offset + scenario_offset)\nend\nfunction mapped_index(structure::DeterministicEquivalent{2}, ci::CI{F,S}, scenario_index::Integer) where {F,S}\n first_stage_offset = MOI.get(structure.proxy[1], MOI.NumberOfConstraints{F,S}())\n scenario_offset = (scenario_index - 1) * MOI.get(structure.proxy[2], MOI.NumberOfConstraints{F,S}())\n return CI{F,S}(ci.value + first_stage_offset + scenario_offset)\nend\n", "meta": {"hexsha": "51eb9a1f09d522ad099e8638b641b96e921384fa", "size": 40313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types/deterministic_equivalent/deterministicequivalent.jl", "max_stars_repo_name": "martinbiel/StochasticPrograms.jl", "max_stars_repo_head_hexsha": "eb142c4cd530022c10a3384fb3a0bfd83fc5714f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49, "max_stars_repo_stars_event_min_datetime": "2018-06-29T09:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:20:57.000Z", "max_issues_repo_path": "src/types/deterministic_equivalent/deterministicequivalent.jl", "max_issues_repo_name": "juantztz/StochasticPrograms.jl", "max_issues_repo_head_hexsha": "eb142c4cd530022c10a3384fb3a0bfd83fc5714f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2018-09-06T08:34:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T15:55:41.000Z", "max_forks_repo_path": "src/types/deterministic_equivalent/deterministicequivalent.jl", "max_forks_repo_name": "juantztz/StochasticPrograms.jl", "max_forks_repo_head_hexsha": "eb142c4cd530022c10a3384fb3a0bfd83fc5714f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-06-12T10:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T23:22:21.000Z", "avg_line_length": 50.7081761006, "max_line_length": 171, "alphanum_fraction": 0.6861310247, "num_tokens": 9450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.19089759871879305}} {"text": "using FillArrays\n\n\"\"\"\n ADI.SDIAlgorithm <: ADI.ADIAlgorithm\n\nSpectral differential imaging (SDI) algorithms. These work on 4-D SDI tensors. To use these algorithms, simply treat them like functions (or call [`process`](@ref))\n\n```julia\n(::SDIAlgorithm)(data::AbstractArray{T,4}, angles, scales; [ref] kwargs...)\n```\n\nThe data is expected to be laid out in `(nλ, nf, ny, nx)` format, so you may need to `permutedims` before processing the data. The `scales` correspond to the relative wavelength scales for each spectrum, and can be retrieved with `HCIToolbox.scale_list`.\n\n# Algorithms\n\nThe current SDI implementations are\n* [`SingleSDI`](@ref)\n* [`DoubleSDI`](@ref)\n* [`SliceSDI`](@ref)\n\"\"\"\nabstract type SDIAlgorithm <: ADIAlgorithm end\n\n\"\"\"\n SingleSDI(alg)\n\nA wrapper algorithm for spectral differential imaging (SDI) data reduced in a single pass. This means that each channel will be scaled and then concatenated together, so an SDI tensor `(nλ, nf, y, x)` becomes a stack `(nλ * nf, y, x)` which is processed by the underlying `alg` like ADI data.\n\n!!! tip\n `SingleSDI` is the default SDI mode. This means instead of writing\n ```julia\n SingleSDI(PCA(15))(data, angles, scales)\n ```\n you can just write\n ```julia\n PCA(15)(data, angles, scales)\n ```\n\"\"\"\nstruct SingleSDI{ALG<:ADIAlgorithm} <: SDIAlgorithm\n alg::ALG\nend\n\nprocess(alg, spcube::AbstractArray{T,4}, angles, scales; kwargs...) where {T} =\n process(SingleSDI(alg), spcube, angles, scales; kwargs...)\n\nfunction process(sdi::SingleSDI, spcube::AbstractArray{T,4}, angles, scales; method=:deweight, kwargs...) where T\n nλ, n, ny, nx = size(spcube)\n frame_size = (ny, nx)\n big_cube = scale_and_stack(spcube, scales)\n angs = repeat(angles, inner=nλ)\n # do single-pass reconstruction\n if :ref in keys(kwargs)\n big_cube_ref = scale_and_stack(kwargs[:ref], scales)\n big_resid_cube = subtract(sdi.alg, big_cube; angles=angs, kwargs..., ref=big_cube_ref)\n else\n big_resid_cube = subtract(sdi.alg, big_cube; angles=angs, kwargs...)\n end\n\n # bin across spectral dim\n resid_cube = invscale_and_collapse(big_resid_cube, scales, frame_size)\n # derotate and combine\n return collapse!(resid_cube, angles; method=method, kwargs...)\nend\n\n\"\"\"\n DoubleSDI(alg)\n DoubleSDI(alg_spec, alg_temp)\n\nA wrapper algorithm for spectral differential imaging (SDI) data reduced in two passes. The first pass uses `alg_spec` to reduce each spectral cube slice in the SDI tensor. Then, the spectral residual frames will be reduced using `alg_temp`, which will include the derotation and final combination.\n\nThe difference between [`DoubleSDI`](@ref) and [`SliceSDI`](@ref) is that `DoubleSDI` does its first pass in the spectral slice, effectively collapsing the slice before performing ADI on the residual cube. `SliceSDI` does its first pass in the temporal slice, collapsing it first before performing ADI on the residual cube.\n\n# Examples\n\n```julia\njulia> data, angles, scales = # load data...\n\n# Median subtraction for each spectral slice,\n# GreeDS{PCA} subtraction on spectral residual cube\njulia> res = DoubleSDI(Classic(), GreeDS(15))(data, angles, scales)\n```\n\"\"\"\nstruct DoubleSDI{ALG<:ADIAlgorithm, ALG2<:ADIAlgorithm} <: SDIAlgorithm\n alg_spec::ALG\n alg_temp::ALG2\nend\n\nDoubleSDI(alg) = DoubleSDI(alg, alg)\n\nfunction process(sdi::DoubleSDI, spcube::AbstractArray{T,4}, angles, scales; method=:deweight, kwargs...) where T\n nλ, n, ny, nx = size(spcube)\n frame_size = (ny, nx)\n spec_resids = similar(spcube, n, ny, nx)\n # do first pass in spectral domain\n Threads.@threads for n in axes(spcube, 2)\n cube = @view spcube[:, n, :, :]\n scaled_cube = scale(cube, scales)\n angs = Zeros(nλ)\n if :ref in keys(kwargs)\n cube_ref = view(kwargs[:ref], :, n, :, :)\n scaled_cube_ref = scale(cube_ref, scales)\n R = subtract(sdi.alg_spec, scaled_cube; angles=angs, kwargs..., ref=scaled_cube_ref)\n else\n R = subtract(sdi.alg_spec, scaled_cube; angles=angs, kwargs...)\n end\n spec_resid = invscale(R, scales, frame_size)\n spec_resids[n, :, :] .= collapse(spec_resid)\n end\n # do second pass in temporal domain\n return sdi.alg_temp(spec_resids, angles; method=method, angles=angles, kwargs...)\nend\n\n\"\"\"\n SliceSDI(alg)\n SliceSDI(alg_spec, alg_temp)\n\nA wrapper algorithm for spectral differential imaging (SDI) data reduced in two passes. The first pass uses `alg_temp` to reduce each temporal cube slice in the SDI tensor. These residuals will be rescaled and stacked into a new cube. Then, the temporal residual frames will be reduced using `alg_spec`, which will include the derotation and final combination.\n\nThe difference between [`SliceSDI`](@ref) and [`DoubleSDI`](@ref) is that `DoubleSDI` does its first pass in the spectral slice, effectively collapsing the slice before performing ADI on the residual cube. `SliceSDI` does its first pass in the temporal slice, collapsing it first before performing ADI on the residual cube.\n\n# Examples\n\n```julia\njulia> data, angles, scales = # load data...\n\n# Median subtraction for each spectral slice,\n# GreeDS{PCA} subtraction on spectral residual cube\njulia> res = SliceSDI(Classic(), GreeDS(15))(data, angles, scales)\n```\n\"\"\"\nstruct SliceSDI{ALG<:ADIAlgorithm, ALG2<:ADIAlgorithm} <: SDIAlgorithm\n alg_spec::ALG\n alg_temp::ALG2\nend\n\nSliceSDI(alg) = SliceSDI(alg, alg)\n\nfunction process(sdi::SliceSDI, spcube::AbstractArray{T,4}, angles, scales; kwargs...) where T\n nλ, n, ny, nx = size(spcube)\n frame_size = (ny, nx)\n temp_resids = similar(spcube, nλ, ny, nx)\n # do first pass in temporal domain\n Threads.@threads for n in axes(spcube, 1)\n cube = @view spcube[n, :, :, :]\n if :ref in keys(kwargs)\n cube_ref = @view kwargs[:ref][n, :, :, :]\n temp_resids[n, :, :] .= sdi.alg_temp(cube, angles; kwargs..., ref=cube_ref)\n else\n temp_resids[n, :, :] .= sdi.alg_temp(cube, angles; kwargs...)\n end\n end\n # do second pass in temporal domain\n scaled_resid_cube = scale(temp_resids, scales)\n angs = Zeros(nλ)\n resid = sdi.alg_spec(scaled_resid_cube, angs; angles=angs, kwargs...)\n return invscale(resid, maximum(scales))\nend\n", "meta": {"hexsha": "52806d0a9b5233787377bbb25dba89e7d07131c8", "size": 6318, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sdi.jl", "max_stars_repo_name": "JuliaHCI/ADI.jl", "max_stars_repo_head_hexsha": "87e434f48ca5954ddeebb63f6f63ec12518449fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-27T07:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T14:13:42.000Z", "max_issues_repo_path": "src/sdi.jl", "max_issues_repo_name": "JuliaHCI/ADI.jl", "max_issues_repo_head_hexsha": "87e434f48ca5954ddeebb63f6f63ec12518449fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2020-09-21T22:44:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T08:26:43.000Z", "max_forks_repo_path": "src/sdi.jl", "max_forks_repo_name": "JuliaHCI/ADI.jl", "max_forks_repo_head_hexsha": "87e434f48ca5954ddeebb63f6f63ec12518449fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-03-27T09:38:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T08:11:03.000Z", "avg_line_length": 40.2420382166, "max_line_length": 360, "alphanum_fraction": 0.6934156379, "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.1907147264866852}} {"text": "export iauApco13\n\"\"\"\nFor a terrestrial observer, prepare star-independent astrometry\nparameters for transformations between ICRS and observed\ncoordinates. The caller supplies UTC, site coordinates, ambient air\nconditions and observing wavelength, and SOFA models are used to\nobtain the Earth ephemeris, CIP/CIO and refraction constants.\n\nThe parameters produced by this function are required in the\nparallax, light deflection, aberration, and bias-precession-nutation\nparts of the ICRS/CIRS transformations.\n\nThis function is part of the International Astronomical Union's\nSOFA (Standards of Fundamental Astronomy) software collection.\n\nStatus: support function.\n\nGiven:\n utc1 double UTC as a 2-part...\n utc2 double ...quasi Julian Date (Notes 1,2)\n dut1 double UT1-UTC (seconds, Note 3)\n elong double longitude (radians, east +ve, Note 4)\n phi double latitude (geodetic, radians, Note 4)\n hm double height above ellipsoid (m, geodetic, Notes 4,6)\n xp,yp double polar motion coordinates (radians, Note 5)\n phpa double pressure at the observer (hPa = mB, Note 6)\n tc double ambient temperature at the observer (deg C)\n rh double relative humidity at the observer (range 0-1)\n wl double wavelength (micrometers, Note 7)\n\nReturned:\n astrom iauASTROM* star-independent astrometry parameters:\n pmt double PM time interval (SSB, Julian years)\n eb double[3] SSB to observer (vector, au)\n eh double[3] Sun to observer (unit vector)\n em double distance from Sun to observer (au)\n v double[3] barycentric observer velocity (vector, c)\n bm1 double sqrt(1-|v|^2): reciprocal of Lorenz factor\n bpn double[3][3] bias-precession-nutation matrix\n along double longitude + s' (radians)\n xpl double polar motion xp wrt local meridian (radians)\n ypl double polar motion yp wrt local meridian (radians)\n sphi double sine of geodetic latitude\n cphi double cosine of geodetic latitude\n diurab double magnitude of diurnal aberration vector\n eral double \"local\" Earth rotation angle (radians)\n refa double refraction constant A (radians)\n refb double refraction constant B (radians)\n eo double* equation of the origins (ERA-GST)\n\nReturned (function value):\n int status: +1 = dubious year (Note 2)\n 0 = OK\n -1 = unacceptable date\n\nNotes:\n\n 1. utc1+utc2 is quasi Julian Date (see Note 2), apportioned in any\n convenient way between the two arguments, for example where utc1\n is the Julian Day Number and utc2 is the fraction of a day.\n\n However, JD cannot unambiguously represent UTC during a leap\n second unless special measures are taken. The convention in the\n present function is that the JD day represents UTC days whether\n the length is 86399, 86400 or 86401 SI seconds.\n\n Applications should use the function iauDtf2d to convert from\n calendar date and time of day into 2-part quasi Julian Date, as\n it implements the leap-second-ambiguity convention just\n described.\n\n 2. The warning status \"dubious year\" flags UTCs that predate the\n introduction of the time scale or that are too far in the\n future to be trusted. See iauDat for further details.\n\n 3. UT1-UTC is tabulated in IERS bulletins. It increases by exactly\n one second at the end of each positive UTC leap second,\n introduced in order to keep UT1-UTC within +/- 0.9s. n.b. This\n practice is under review, and in the future UT1-UTC may grow\n essentially without limit.\n\n 4. The geographical coordinates are with respect to the WGS84\n reference ellipsoid. TAKE CARE WITH THE LONGITUDE SIGN: the\n longitude required by the present function is east-positive\n (i.e. right-handed), in accordance with geographical convention.\n\n 5. The polar motion xp,yp can be obtained from IERS bulletins. The\n values are the coordinates (in radians) of the Celestial\n Intermediate Pole with respect to the International Terrestrial\n Reference System (see IERS Conventions 2003), measured along the\n meridians 0 and 90 deg west respectively. For many\n applications, xp and yp can be set to zero.\n\n Internally, the polar motion is stored in a form rotated onto\n the local meridian.\n\n 6. If hm, the height above the ellipsoid of the observing station\n in meters, is not known but phpa, the pressure in hPa (=mB), is\n available, an adequate estimate of hm can be obtained from the\n expression\n\n hm = -29.3 * tsl * log ( phpa / 1013.25 );\n\n where tsl is the approximate sea-level air temperature in K\n (See Astrophysical Quantities, C.W.Allen, 3rd edition, section\n 52). Similarly, if the pressure phpa is not known, it can be\n estimated from the height of the observing station, hm, as\n follows:\n\n phpa = 1013.25 * exp ( -hm / ( 29.3 * tsl ) );\n\n Note, however, that the refraction is nearly proportional to\n the pressure and that an accurate phpa value is important for\n precise work.\n\n 7. The argument wl specifies the observing wavelength in\n micrometers. The transition from optical to radio is assumed to\n occur at 100 micrometers (about 3000 GHz).\n\n 8. It is advisable to take great care with units, as even unlikely\n values of the input parameters are accepted and processed in\n accordance with the models used.\n\n 9. In cases where the caller wishes to supply his own Earth\n ephemeris, Earth rotation information and refraction constants,\n the function iauApco can be used instead of the present function.\n\n 10. This is one of several functions that inserts into the astrom\n structure star-independent parameters needed for the chain of\n astrometric transformations ICRS <-> GCRS <-> CIRS <-> observed.\n\n The various functions support different classes of observer and\n portions of the transformation chain:\n\n functions observer transformation\n\n iauApcg iauApcg13 geocentric ICRS <-> GCRS\n iauApci iauApci13 terrestrial ICRS <-> CIRS\n iauApco iauApco13 terrestrial ICRS <-> observed\n iauApcs iauApcs13 space ICRS <-> GCRS\n iauAper iauAper13 terrestrial update Earth rotation\n iauApio iauApio13 terrestrial CIRS <-> observed\n\n Those with names ending in \"13\" use contemporary SOFA models to\n compute the various ephemerides. The others accept ephemerides\n supplied by the caller.\n\n The transformation from ICRS to GCRS covers space motion,\n parallax, light deflection, and aberration. From GCRS to CIRS\n comprises frame bias and precession-nutation. From CIRS to\n observed takes account of Earth rotation, polar motion, diurnal\n aberration and parallax (unless subsumed into the ICRS <-> GCRS\n transformation), and atmospheric refraction.\n\n 11. The context structure astrom produced by this function is used\n by iauAtioq, iauAtoiq, iauAtciq* and iauAticq*.\n\nCalled:\n iauUtctai UTC to TAI\n iauTaitt TAI to TT\n iauUtcut1 UTC to UT1\n iauEpv00 Earth position and velocity\n iauPnm06a classical NPB matrix, IAU 2006/2000A\n iauBpn2xy extract CIP X,Y coordinates from NPB matrix\n iauS06 the CIO locator s, given X,Y, IAU 2006\n iauEra00 Earth rotation angle, IAU 2000\n iauSp00 the TIO locator s', IERS 2000\n iauRefco refraction constants for given ambient conditions\n iauApco astrometry parameters, ICRS-observed\n iauEors equation of the origins, given NPB matrix and s\n\nThis revision: 2013 December 5\n\nSOFA release 2018-01-30\n\nCopyright (C) 2018 IAU SOFA Board. See notes at end.\n\"\"\"\nfunction iauApco13(utc1::Real, utc2::Real, dut1::Real,\n elong::Real, phi::Real, hm::Real,\n xp::Real, yp::Real,\n phpa::Real, tc::Real, rh::Real, wl::Real)\n # Allocate return value\n ref_astrom = Ref{iauASTROM}(iauASTROM())\n ref_eo = Ref{Float64}(0.0)\n\n\n status = ccall((:iauApco13, libsofa_c), Cint, \n (Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble,\n Ref{iauASTROM}, Ref{Cdouble}), \n convert(Float64, utc1), convert(Float64, utc2),\n convert(Float64, dut1), convert(Float64, elong),\n convert(Float64, phi), convert(Float64, hm),\n convert(Float64, xp), convert(Float64, yp),\n convert(Float64, phpa), convert(Float64, tc),\n convert(Float64, rh), convert(Float64, wl),\n ref_astrom, ref_eo)\n\n return status, ref_astrom[], ref_eo[]\nend", "meta": {"hexsha": "b6c6fcd20d9d09a2a0996e5b12b483c0f980c9cb", "size": 8793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/apco13.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_stars_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-12-11T05:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T03:10:26.000Z", "max_issues_repo_path": "src/apco13.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_issues_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-02T00:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T06:42:23.000Z", "max_forks_repo_path": "src/apco13.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_forks_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:41:12.000Z", "avg_line_length": 43.7462686567, "max_line_length": 71, "alphanum_fraction": 0.6935061981, "num_tokens": 2353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.19066668023330938}} {"text": "\n\"\"\"\n`module JAC.PairAnnihilation1Photon` ... a submodel of JAC that contains all methods for computing positron-bound-electron pair annihilation \n (PEPA) with single-photon emission cross sections and rates; e^+ + |i(N)> --> |f(N-1)> + photon;\n it is using JAC, JAC.ManyElectron, JAC.Radial.\n\"\"\"\nmodule PairAnnihilation1Photon \n\n using JAC, JAC.ManyElectron, JAC.Radial\n global JAC_counter = 0\n\n\n \"\"\"\n `struct PairAnnihilation1Photon.Settings` ... defines a type for the details and parameters in computing positron-bound-electron pair \n annihilation (PEPA) with single-photon emission cross sections and rates; e^+ + |i(N)> --> |f(N-1)> + photon.\n\n + multipoles ::Array{EmMultipole} ... Specifies the multipoles of the radiation field that are to be included.\n + gauges ::Array{UseGauge} ... Specifies the gauges to be included into the computations.\n + positronEnergies ::Array{Float64,1} ... List of positron energies.\n + printBeforeComputation ::Bool ... True, if all energies and lines are printed before their evaluation.\n + selectLines ::Bool ... True, if lines are selected individually for the computations.\n + selectedLines ::Array{Tuple{Int64,Int64},1} ... List of lines, given by tupels (inital-level, final-level).\n \"\"\"\n struct Settings \n multipoles ::Array{EmMultipole}\n gauges ::Array{UseGauge}\n positronEnergies ::Array{Float64,1} \n printBeforeComputation ::Bool\n selectLines ::Bool\n selectedLines ::Array{Tuple{Int64,Int64},1} \n end \n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.Settings()` ... constructor for the default values of pair-annihilation photon line computations\n \"\"\"\n function Settings()\n Settings(EmMultipole[], UseGauge[], Float64[], false, false, Tuple{Int64,Int64}[])\n end\n\n\n # `Base.show(io::IO, settings::PairAnnihilation1Photon.Settings)` \n #\t\t... prepares a proper printout of the variable settings::PairAnnihilation1Photon.Settings.\n function Base.show(io::IO, settings::PairAnnihilation1Photon.Settings) \n println(io, \"multipoles: $(settings.multipoles) \")\n println(io, \"gauges: $(settings.gauges) \")\n println(io, \"positronEnergies: $(settings.positronEnergies) \")\n println(io, \"printBeforeComputation: $(settings.printBeforeComputation) \")\n println(io, \"selectLines: $(settings.selectLines) \")\n println(io, \"selectedLines: $(settings.selectedLines) \")\n end\n\n\n \"\"\"\n `struct PairAnnihilation1Photon.Channel` ... defines a type for a positron-bound-electron pair annihilation (PEPA) with single-photon \n emission channel that specifies all quantum numbers, phases and amplitudes.\n\n + multipole ::EmMultipole ... Multipole of the photon absorption.\n + gauge ::EmGauge ... Gauge for dealing with the (coupled) radiation field.\n + kappa ::Int64 ... partial-wave of the incoming free positron\n + symmetry ::LevelSymmetry ... total angular momentum and parity of the scattering state\n + phase ::Float64 ... phase of the partial wave\n + amplitude ::Complex{Float64} ... PairAnnihilation1PhotonChannel amplitude associated with the given channel.\n \"\"\"\n struct Channel\n multipole ::EmMultipole\n gauge ::EmGauge\n kappa ::Int64\n symmetry ::LevelSymmetry\n phase ::Float64\n amplitude ::Complex{Float64}\n end\n\n\n \"\"\"\n `struct PairAnnihilation1Photon.Line` ... defines a type for a positron-bound-electron pair-annihilation (photon) line that may \n include the definition of channels.\n\n + initialLevel ::Level ... initial-(state) level\n + finalLevel ::Level ... final-(state) level\n + positronEnergy ::Float64 ... Energy of the (incoming free) positron.\n + photonEnergy ::Float64 ... Energy of the emitted photon.\n + crossSection ::EmProperty ... Cross section for this pair-annihilation (photon) line.\n + hasChannels ::Bool ... Determines whether the individual (sub-) channels are defined in terms of their \n free-positron energy, kappa, multipole, etc., or not.\n + channels ::Array{PairAnnihilation1Photon.Channel,1} ... List of PairAnnihilation1Photon.Channels of this line.\n \"\"\"\n struct Line\n initialLevel ::Level\n finalLevel ::Level\n positronEnergy ::Float64\n photonEnergy ::Float64\n crossSection ::EmProperty\n hasChannels ::Bool\n channels ::Array{PairAnnihilation1Photon.Channel,1}\n end\n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.Line()` ... 'empty' constructor for a pair-annihilation (photon) line between a specified initial and \n final level.\n \"\"\"\n function Line()\n Line(Level(), Level(), 0., 0., EmProperty(0., 0.), false, PairAnnihilation1Photon[] )\n end\n\n\n # `Base.show(io::IO, line::PairAnnihilation1Photon.Line)` ... prepares a proper printout of the variable line::PairAnnihilation1Photon.Line.\n function Base.show(io::IO, line::PairAnnihilation1Photon.Line) \n println(io, \"initialLevel: $(line.initialLevel) \")\n println(io, \"finalLevel: $(line.finalLevel) \")\n println(io, \"positronEnergy: $(line.positronEnergy) \")\n println(io, \"photonEnergy: $(line.photonEnergy) \")\n println(io, \"crossSection: $(line.crossSection) \")\n println(io, \"hasChannels: $(line.hasChannels) \")\n println(io, \"channels: $(line.channels) \")\n end\n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.computeAmplitudesProperties(line::PairAnnihilation1Photon.Line, grid::Radial.Grid, \n settings::PairAnnihilation1Photon.Settings)` ... to compute all amplitudes and \n properties of the given line; a line::PairAnnihilation1Photon.Line is returned for which the amplitudes and properties are now evaluated.\n \"\"\"\n function computeAmplitudesProperties(line::PairAnnihilation1Photon.Line, grid::Radial.Grid, settings::PairAnnihilation1Photon.Settings)\n global JAC_counter\n newChannels = PairAnnihilation1Photon.Channel[]\n for channel in line.channels\n # Generate a continuum orbital\n JAC_counter = JAC_counter + 1\n if JAC_counter < 20 println(\"PairAnnihilation1Photon.computeAmplitudes..-aa: warning ... no cont. orbital is generated.\") end\n phase = 0.\n # Define a proper continuum basis from the initialLevel.basis and the continuum orbital\n JAC_counter = JAC_counter + 1\n if JAC_counter < 20 println(\"PairAnnihilation1Photon.computeAmplitudes..-ab: warning ... no coninuum basis is yet generated.\") end\n # Compute the transition matrix for the continuum and the initial-state basis\n JAC_counter = JAC_counter + 1\n if JAC_counter < 20 println(\"PairAnnihilation1Photon.computeAmplitudes..-ac: warning ... no transition matrix is computed.\") end\n # matrix = JAC.PhotoIonization.computeMatrix(channel.multipole, channel.gauge, line.omega, line.finalLevel.basis, \n # line.initialLevel.basis, grid, settings)\n # amplitude = line.finalLevel.mc * matrix * line.initialLevel.mc \n amplitude = 1.0 \n push!( newChannels, PairAnnihilation1Photon.Channel( channel.multipole, channel.gauge, channel.kappa, channel.symmetry, \n phase, amplitude) )\n end\n # Calculate the photonrate and angular beta if requested\n JAC_counter = JAC_counter + 1\n if JAC_counter < 20 println(\"PairAnnihilation1Photon.computeAmplitudesProperties-ba: warning ... cs set to -1.\") end\n crossSection = EmProperty(-1., -1.)\n line = PairAnnihilation1Photon.Line( line.initialLevel, line.finalLevel, line.positronEnergy, line.photonEnergy, \n crossSection, true, newChannels)\n return( line )\n end\n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, grid::Radial.Grid, \n settings::PairAnnihilation1Photon.Settings; output::Bool=true)` ... to compute the \n pair-annihilation single-photon emission amplitudes and all properties as requested by the given settings. A list of \n lines::Array{PairAnnihilation1Photon.Lines} is returned.\n \"\"\"\n function computeLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, grid::Radial.Grid, settings::PairAnnihilation1Photon.Settings; \n output::Bool=true)\n lines = JAC.PairAnnihilation1Photon.determineLines(finalMultiplet, initialMultiplet, settings)\n # Display all selected lines before the computations start\n if settings.printBeforeComputation JAC.PairAnnihilation1Photon.displayLines(lines) end\n # Calculate all amplitudes and requested properties\n newLines = PairAnnihilation1Photon.Line[]\n for line in lines\n newLine = JAC.PairAnnihilation1Photon.computeAmplitudesProperties(line, grid, settings) \n push!( newLines, newLine)\n end\n # Print all results to screen\n JAC.PairAnnihilation1Photon.displayResults(lines)\n #\n if output return( lines )\n else return( nothing )\n end\n end\n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.determineChannels(finalLevel::Level, initialLevel::Level, settings::PairAnnihilation1Photon.Settings)` \n ... to determine a list of pair-annihilation single-photon emission Channel for a transitions from the initial to final level and by \n taking into account the particular settings of for this computation; an Array{PairAnnihilation1Photon.Channel,1} is returned.\n \"\"\"\n function determineChannels(finalLevel::Level, initialLevel::Level, settings::PairAnnihilation1Photon.Settings)\n channels = PairAnnihilation1Photon.Channel[]; \n symi = LevelSymmetry(initialLevel.J, initialLevel.parity); symf = LevelSymmetry(finalLevel.J, finalLevel.parity) \n for mp in settings.multipoles\n for gauge in settings.gauges\n symList = JAC.AngularMomentum.allowedMultipoleSymmetries(symi, mp)\n ##x println(\"mp = $mp symi = $symi symList = $symList\")\n for symt in symList\n kappaList = JAC.AngularMomentum.allowedKappaSymmetries(symt, symf)\n for kappa in kappaList\n # Include further restrictions if appropriate\n if string(mp)[1] == 'E' && gauge == Basics.UseCoulomb \n push!(channels, PairAnnihilation1Photon.Channel(mp, JAC.Coulomb, kappa, symt, 0., Complex(0.)) )\n elseif string(mp)[1] == 'E' && gauge == Basics.UseBabushkin \n push!(channels, PairAnnihilation1Photon.Channel(mp, JAC.Babushkin, kappa, symt, 0., Complex(0.)) ) \n elseif string(mp)[1] == 'M' \n push!(channels, PairAnnihilation1Photon.Channel(mp, JAC.Magnetic, kappa, symt, 0., Complex(0.)) ) \n end \n end\n end\n end\n end\n return( channels ) \n end\n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, \n settings::PairAnnihilation1Photon.Settings)` ... to determine a list of \n PairAnnihilation1Photon.Line's for transitions between levels from the initial- and final-state multiplets, and by taking into account \n the particular selections and settings for this computation; an Array{PairAnnihilation1Photon.Line,1} is returned. Apart from the \n level specification, all physical properties are set to zero during the initialization process.\n \"\"\"\n function determineLines(finalMultiplet::Multiplet, initialMultiplet::Multiplet, settings::PairAnnihilation1Photon.Settings)\n if settings.selectLines selectLines = true; selectedLines = Basics.determine(\"selected lines\", settings.selectedLines)\n else selectLines = false\n end\n \n lines = PairAnnihilation1Photon.Line[]\n for i = 1:length(initialMultiplet.levels)\n for f = 1:length(finalMultiplet.levels)\n if selectLines && !(haskey(selectedLines, (i,f)) ) continue end\n for ep in settings.positronEnergies\n omega = ep - (finalMultiplet.levels[f].energy - initialMultiplet.levels[i].energy) + 2* Defaults.getDefaults(\"mc^2\")\n if omega < 0 continue end \n\n channels = JAC.PairAnnihilation1Photon.determineChannels(finalMultiplet.levels[f], initialMultiplet.levels[i], settings) \n push!( lines, PairAnnihilation1Photon.Line(initialMultiplet.levels[i], finalMultiplet.levels[f], ep, omega, \n EmProperty(0., 0.), true, channels) )\n end\n end\n end\n return( lines )\n end\n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.displayLines(lines::Array{PairAnnihilation1Photon.Line,1})` ... to display a list of lines and channels that \n have been selected due to the prior settings. A neat table of all selected transitions and energies is printed but nothing is returned \n otherwise.\n \"\"\"\n function displayLines(lines::Array{PairAnnihilation1Photon.Line,1})\n println(\" \")\n println(\" Selected pair-annihilation single-photon emission lines:\")\n println(\" \")\n println(\" \", JAC.TableStrings.hLine(175))\n sa = \" \"; sb = \" \"\n sa = sa * JAC.TableStrings.center(18, \"i-level-f\"; na=2); sb = sb * JAC.TableStrings.hBlank(20)\n sa = sa * JAC.TableStrings.center(18, \"i--J^P--f\"; na=4); sb = sb * JAC.TableStrings.hBlank(22)\n sa = sa * JAC.TableStrings.center(38, \"Energies \" * JAC.TableStrings.inUnits(\"energy\"); na=4); \n sb = sb * JAC.TableStrings.center(38, \" i--f positron omega\"; na=4)\n sa = sa * JAC.TableStrings.flushleft(57, \"List of multipoles, gauges, kappas and total symmetries\"; na=4) \n sb = sb * JAC.TableStrings.flushleft(57, \"partial (multipole, gauge, total J^P) \"; na=4)\n println(sa); println(sb); println(\" \", JAC.TableStrings.hLine(175)) \n # \n for line in lines\n sa = \" \"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * JAC.TableStrings.center(18, JAC.TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * JAC.TableStrings.center(18, JAC.TableStrings.symmetries_if(isym, fsym); na=4)\n energy = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", energy)) * \" \"\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", line.positronEnergy)) * \" \"\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", line.photonEnergy)) * \" \"\n kappaMultipoleSymmetryList = Tuple{Int64,EmMultipole,EmGauge,LevelSymmetry}[]\n for i in 1:length(line.channels)\n push!( kappaMultipoleSymmetryList, (line.channels[i].kappa, line.channels[i].multipole, line.channels[i].gauge, \n line.channels[i].symmetry) )\n end\n wa = JAC.TableStrings.kappaMultipoleSymmetryTupels(85, kappaMultipoleSymmetryList)\n sb = sa * wa[1]; println( sb ) \n for i = 2:length(wa)\n sb = JAC.TableStrings.hBlank( length(sa) ) * wa[i]; println( sb )\n end\n end\n println(\" \", JAC.TableStrings.hLine(175))\n #\n return( nothing )\n end\n\n\n \"\"\"\n `JAC.PairAnnihilation1Photon.displayResults(lines::Array{PairAnnihilation1Photon.Line,1})` ... to list all results, energies, cross sections, \n etc. of the selected lines. A neat table is printed but nothing is returned otherwise.\n \"\"\"\n function displayResults(lines::Array{PairAnnihilation1Photon.Line,1})\n println(\" \")\n println(\" Pair-annihilation single-photon emission cross sections:\")\n println(\" \")\n println(\" \", JAC.TableStrings.hLine(128))\n sa = \" \"; sb = \" \"\n sa = sa * JAC.TableStrings.center(18, \"i-level-f\"; na=2); sb = sb * JAC.TableStrings.hBlank(20)\n sa = sa * JAC.TableStrings.center(18, \"i--J^P--f\"; na=4); sb = sb * JAC.TableStrings.hBlank(22)\n sa = sa * JAC.TableStrings.center(38, \"Energies \" * JAC.TableStrings.inUnits(\"energy\"); na=4); \n sb = sb * JAC.TableStrings.center(38, \" i--f positron omega\"; na=4)\n sa = sa * JAC.TableStrings.center(10, \"Multipoles\"; na=1); sb = sb * JAC.TableStrings.hBlank(13)\n sa = sa * JAC.TableStrings.center(30, \"Cou -- Cross section -- Bab\"; na=3) \n sb = sb * JAC.TableStrings.center(30, JAC.TableStrings.inUnits(\"cross section\") * \" \" * \n JAC.TableStrings.inUnits(\"cross section\"); na=3)\n println(sa); println(sb); println(\" \", JAC.TableStrings.hLine(128)) \n # \n for line in lines\n sa = \" \"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * JAC.TableStrings.center(18, JAC.TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * JAC.TableStrings.center(18, JAC.TableStrings.symmetries_if(isym, fsym); na=4)\n energy = line.initialLevel.energy - line.finalLevel.energy\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", energy)) * \" \"\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", line.positronEnergy)) * \" \"\n sa = sa * @sprintf(\"%.5e\", Defaults.convertUnits(\"energy: from atomic\", line.photonEnergy)) * \" \"\n multipoles = EmMultipole[]\n for ch in line.channels\n multipoles = push!( multipoles, ch.multipole)\n end\n multipoles = unique(multipoles); mpString = JAC.TableStrings.multipoleList(multipoles) * \" \"\n sa = sa * JAC.TableStrings.flushleft(11, mpString[1:10]; na=2)\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"cross section: from atomic\", line.crossSection.Coulomb)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"cross section: from atomic\", line.crossSection.Babushkin)) * \" \"\n println(sa)\n end\n println(\" \", JAC.TableStrings.hLine(128))\n #\n return( nothing )\n end\n\nend # module\n", "meta": {"hexsha": "6bf47f544a9575c7c9a42651fc3e40078099f6d7", "size": 20405, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-PairAnnihilation1Photon.jl", "max_stars_repo_name": "SanjiangYang/JAC.jl", "max_stars_repo_head_hexsha": "f5612dd0912d95da0a22efa1224381606f0012d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-15T11:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T11:27:51.000Z", "max_issues_repo_path": "src/module-PairAnnihilation1Photon.jl", "max_issues_repo_name": "Zstar95/JAC.jl", "max_issues_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-PairAnnihilation1Photon.jl", "max_forks_repo_name": "Zstar95/JAC.jl", "max_forks_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-30T13:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T13:09:52.000Z", "avg_line_length": 61.2762762763, "max_line_length": 147, "alphanum_fraction": 0.5951972556, "num_tokens": 4738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.19018713091644487}} {"text": "\"\"\"\n definesignal(signal_type::SignalType, f_s, t_length; prn=1,\n f_if=0., f_d=0., fd_rate=0., Tsys=535.,\n CN0=45., phi=0., nADC=4, include_carrier=true,\n include_adc=true, include_thermal_noise=true,\n code_start_idx=1., include_databits_I=true,\n include_databits_Q=true, include_phase_noise=true,\n phase_noise_scaler=1/10, name=\"custom\",\n skip_noise_generation=false, allocate_noise_vectors=true,\n receiver_h_parms=h_parms_tcxo[1])\n\n\nDefine properties of locally generated generic signal\nbased off its type, PRN, etc.\n\n\nRequired Arguments:\n\n- `signal_type::SignalType`: user defined signal type\n * see `definecodetype` and `definesignaltype`\n- `f_s`: signal sampling frequency in Hz\n- `t_length`: signal length in seconds\n\n\nOptional Arguments:\n\n- `prn`: satellite PRN number `(default = 1)`\n- `f_if`: IF frequency in Hz `(default = 0Hz)`\n- `f_d`: signal Doppler frequency in Hz `(default = 0Hz)`\n- `fd_rate`: signal Doppler rate in Hz/s `(default = 0Hz/s)`\n- `Tsys`: receiver noise temperature in Kelvin `(default = 535K)`\n- `CN0`: signal carrier-to-noise ratio (C/N₀) `(default = 45dB⋅Hz)`\n- `phi`: initial carrier phase in rad `(default = 0rad)`\n- `nADC`: receiver bit depth `(default = 8 bits)`\n- `include_carrier`: flag for modulating codes onto carrier `(default = true)`\n- `include_adc`: flag for performing ADC quantization on signal `(default = true)`\n- `include_thermal_noise`: flag for including thermal noise in signal generation\n `(default = true)`\n- `code_start_idx`: starting index in `ReplicaSignal.data` where all codes\n start `(default = 1)`\n- `include_databits_I`: flag for including I channel databits in simulated signal\n `(default = true)`\n- `include_databits_Q`: flag for including Q channel databits in simulated signal\n `(default = true)`\n- `include_phase_noise`: flag for including phase noise `(default = true)`\n- `phase_noise_scaler`: standard deviation of phase noise in rad\n `(default = 1/10rad)`\n- `name`: name of signal `(default = custom)`\n- `skip_noise_generation`: flag for skipping thermal and phase noise generation\n `(default = false)`\n- `allocate_noise_vectors`: flag for allocating memory for thermal and phase\n noise vectors `(default = true)`\n * if set to `true`, thermal and phase noise vectors have the same length as\n `ReplicaSignal.data` vector\n * if set to `false`, thermal and phase noise vectors have length set to 0\n and the `include_thermal_noise` and `include_phase_noise` flags are set\n to `false`\n- `receiver_h_parms`: vector of oscillator h parameters for use in simulating \n oscillator phase noise\n * format is `[h₋₂, h₋₁, h₀, h₁, h₂]`\n- `start_t`: the start time of the signal in seconds `(default = 0 seconds)`\n\n\nReturns:\n\n- `ReplicaSignal` struct\n\"\"\"\nfunction definesignal(signal_type::SignalType, f_s, t_length; prn=1,\n f_if=0., f_d=0., fd_rate=0., Tsys=535.,\n CN0=45., phi=0., nADC=8, include_carrier=true,\n include_adc=true, include_thermal_noise=true,\n code_start_idx=1., include_databits_I=true,\n include_databits_Q=true, include_phase_noise=true,\n phase_noise_scaler=1/10, name=\"custom\",\n skip_noise_generation=false, allocate_noise_vectors=true,\n receiver_h_parms=h_parms_tcxo[4], start_t=0)\n # Obtain sample number based off the sampling frequency and duration of\n # signal\n sample_num = floor(Int, f_s*t_length)\n # Calculate code chipping rates with Doppler applied for all codes on\n # each channel and their initial code phases\n sig_freq = signal_type.sig_freq\n I_codes = signal_type.I_codes\n Q_codes = signal_type.Q_codes\n # Get adjusted code chipping rates and chipping rate rates for I channel\n # codes\n if signal_type.include_I\n f_code_d_I = Array{Float64}(undef, I_codes.code_num)\n f_code_dd_I = Array{Float64}(undef, I_codes.code_num)\n init_code_phases_I = Array{Float64}(undef, I_codes.code_num)\n for i in 1:signal_type.I_codes.code_num\n # I channel\n f_code = I_codes.chipping_rates[i]\n code_length = I_codes.code_lengths[i]\n f_code_d, f_code_dd = calc_doppler_code_rate(f_code, sig_freq,\n f_d, fd_rate)\n f_code_d_I[i] = f_code_d\n f_code_dd_I[i] = f_code_dd\n init_code_phases_I[i] = calcinitcodephase(code_length, f_code_d,\n f_code_dd, f_s, code_start_idx)\n end\n if I_codes.databits\n if ~include_databits_I\n I_codes.include_codes[end] = false\n else\n I_codes.include_codes[end] = true\n end\n end\n else\n # Set these vectors to zero length if there are no I channel codes\n f_code_d_I = Array{Float64}(undef, 0)\n f_code_dd_I = Array{Float64}(undef, 0)\n init_code_phases_I = Array{Float64}(undef, 0)\n end\n # Get adjusted code chipping rates and chipping rate rates for Q channel\n # codes\n if signal_type.include_Q\n f_code_d_Q = Array{Float64}(undef, Q_codes.code_num)\n f_code_dd_Q = Array{Float64}(undef, Q_codes.code_num)\n init_code_phases_Q = Array{Float64}(undef, Q_codes.code_num)\n for i in 1:signal_type.Q_codes.code_num\n # Q channel\n f_code = Q_codes.chipping_rates[i]\n code_length = Q_codes.code_lengths[i]\n f_code_d, f_code_dd = calc_doppler_code_rate(f_code, sig_freq,\n f_d, fd_rate)\n f_code_d_Q[i] = f_code_d\n f_code_dd_Q[i] = f_code_dd\n init_code_phases_Q[i] = calcinitcodephase(code_length, f_code_d,\n f_code_dd, f_s,\n code_start_idx)\n end\n if Q_codes.databits\n if ~include_databits_Q\n Q_codes.include_codes[end] = false\n else\n Q_codes.include_codes[end] = true\n end\n end\n else\n # Set these vectors to zero length if there are no Q channel codes\n f_code_d_Q = Array{Float64}(undef, 0)\n f_code_dd_Q = Array{Float64}(undef, 0)\n init_code_phases_Q = Array{Float64}(undef, 0)\n end\n # Allocate space for signal. No simulated data is stored in yet. After\n # define the signal, user can use `generatesignal!(signal)` to generate\n # the I/Q samples which will be stored in `ReplicaSignal.data`.\n data = Array{Complex{Float64}}(undef, sample_num)\n isreplica = false\n noexp = false\n # Generate thermal noise and phase noise\n if allocate_noise_vectors\n if skip_noise_generation\n # Space for thermal and phase noise vectors are allocated. User can\n # use `definesignal!(signal; new_thermal_noise=true, new_phase_noise=true)`\n # to generate the noise in the vectors.\n thermal_noise = Array{Complex{Float64}}(undef, sample_num)\n phase_noise = Array{Float64}(undef, sample_num)\n else\n # Generate thermal and phase noise. Thermal noise is unscaled\n # but is scaled in `generatesignal!` when the signal is generated.\n # Phase noise is scaled based off the value of `phase_noise_scaler`.\n thermal_noise = randn(Complex{Float64}, sample_num)\n phase_noise = generate_phase_noise(t_length, f_s, \n signal_type.sig_freq, \n receiver_h_parms)\n end\n else\n # Create 0 sized thermal and phase noise vectors and set the\n # `include_thermal_noise` and `include_phase_noise` flags to `false`.\n thermal_noise = Array{Complex{Float64}}(undef, 0)\n phase_noise = Array{Float64}(undef, 0)\n include_thermal_noise = false\n include_phase_noise = false\n end\n return ReplicaSignal(name, prn, f_s, t_length, f_if, f_d, fd_rate, Tsys,\n CN0, phi, nADC, code_start_idx, init_code_phases_I,\n init_code_phases_Q, data, include_carrier,\n include_adc, include_thermal_noise, include_databits_I,\n include_databits_Q, include_phase_noise, f_code_d_I,\n f_code_dd_I, f_code_d_Q, f_code_dd_Q, sample_num,\n isreplica, noexp, thermal_noise, phase_noise,\n signal_type, receiver_h_parms, start_t)\nend\n\n\n\"\"\"\n definesignal!(signal::ReplicaSignal;\n prn=signal.prn, f_if=signal.f_if, f_d=signal.f_d,\n fd_rate=signal.fd_rate, Tsys=signal.Tsys,\n CN0=signal.CN0, phi=signal.phi, nADC=signal.nADC,\n include_carrier=signal.include_carrier,\n include_adc=signal.include_adc,\n include_thermal_noise=signal.include_thermal_noise,\n code_start_idx=signal.code_start_idx,\n include_databits_I=signal.include_databits_I,\n include_databits_Q=signal.include_databits_Q,\n include_phase_noise=signal.include_phase_noise,\n phase_noise_scaler=1/10, name=signal.name,\n new_thermal_noise=false, new_phase_noise=false,\n isreplica=signal.isreplica, noexp=signal.noexp,\n new_databits=false)\n\n\nRedefine properties of locally generated generic signal\nbased off its type, PRN, etc.\n\n\nRequired Arguments:\n\n- `signal::ReplicaSignal`: the signal already defined by the user using\n `definesignal`\n\n\nOptional Arguments with Defaults Equal to `signal` Field Values:\n\n- `prn`: satellite PRN number\n- `f_if`: IF frequency in Hz\n- `f_d`: signal Doppler frequency in Hz\n- `fd_rate`: signal Doppler rate in Hz/s\n- `Tsys`: receiver noise temperature in Kelvin\n- `CN0`: signal carrier-to-noise ratio (C/N₀)\n- `phi`: initial carrier phase in rad\n- `nADC`: receiver bit depth\n- `include_carrier`: flag for modulating codes onto carrier\n- `include_adc`: flag for performing ADC quantization on signal\n- `include_thermal_noise`: flag for including thermal noise in signal generation\n- `code_start_idx`: starting index in `ReplicaSignal.data` where all codes\n start\n- `include_databits_I`: flag for including I channel databits in simulated signal\n- `include_databits_Q`: flag for including Q channel databits in simulated signal\n- `include_phase_noise`: flag for including phase noise\n- `name`: name of signal\n- `isreplica`: `[DEPRICATED]` flag to identify whether signal is being for processing\n * replica signals being used for processing simulated or real signals\n should not include any noise source\n * this is usually set to `true` when being used by processing functions\n such as `courseacquisition!`, `fineacquisition`, and `trackprn`, only if\n this signal structure is being used as the replica signal, and is NOT\n the signal being processed\n * if `true`, a `ReplicaSignal` struct will not have noise added onto it\n and will not undergo ADC quantization\n * signal generation will be done using the second method of `generatesignal!`,\n `generatesignal!(signal::ReplicaSignal, isreplica::Bool)`\n- `noexp`: used only if second method of `generatesignal!`, discussed\n above, is used\n * does not modulate codes onto carrier\n\n\nOther Optional Arguments:\n\n- `phase_noise_init_phase`: initial phase for phase noise `(default = 0 rad)`\n- `new_thermal_noise`: flag to generate new phase noise for signal\n `(default = false)`\n- `new_phase_noise`: flag to generate new phase noise for signal\n `(default = false)`\n- `new_databits`: flag to generate new databits for signal `(default = false)`\n- `start_t`: the start time of the signal in seconds `(default = 0 seconds)`\n\n\nModifies and Returns:\n\n- `signal::ReplicaSignal`\n\"\"\"\nfunction definesignal!(signal::ReplicaSignal;\n prn=signal.prn, f_if=signal.f_if, f_d=signal.f_d,\n fd_rate=signal.fd_rate, Tsys=signal.Tsys,\n CN0=signal.CN0, phi=signal.phi, nADC=signal.nADC,\n include_carrier=signal.include_carrier,\n include_adc=signal.include_adc,\n include_thermal_noise=signal.include_thermal_noise,\n code_start_idx=signal.code_start_idx,\n include_databits_I=signal.include_databits_I,\n include_databits_Q=signal.include_databits_Q,\n include_phase_noise=signal.include_phase_noise,\n phase_noise_init_phase=0, name=signal.name,\n new_thermal_noise=false, new_phase_noise=false,\n isreplica=signal.isreplica, noexp=signal.noexp,\n receiver_h_parms=signal.receiver_h_parms,\n new_databits=false, start_t=signal.start_t)\n # Calculate code chipping rates with Doppler applied for all codes on\n # each channel and their initial code phases\n f_s = signal.f_s\n signal_type = signal.signal_type\n sample_num = signal.sample_num\n sig_freq = signal_type.sig_freq\n I_codes = signal_type.I_codes\n Q_codes = signal_type.Q_codes\n # Get adjusted code chipping rates and chipping rate rates for I channel\n # codes\n if signal_type.include_I\n for i in 1:signal_type.I_codes.code_num\n # I channel\n f_code = I_codes.chipping_rates[i]\n code_length = I_codes.code_lengths[i]\n f_code_d, f_code_dd = calc_doppler_code_rate(f_code, sig_freq,\n f_d, fd_rate)\n signal.f_code_d_I[i] = f_code_d\n signal.f_code_dd_I[i] = f_code_dd\n signal.init_code_phases_I[i] = calcinitcodephase(code_length,\n f_code_d,\n f_code_dd, f_s,\n code_start_idx)\n end\n if I_codes.databits\n if ~include_databits_I\n signal.signal_type.I_codes.include_codes[end] = false\n else\n signal.signal_type.I_codes.include_codes[end] = true\n end\n # Generate new databits for I channel if `new_databits` flag is\n # `true`\n if new_databits\n prn_keys = collect(keys(I_codes.codes[1]))\n\n if I_codes.similar_databits\n # If one array of databits was used for all PRNs, then the\n # databit arrays for all PRNs are references to the same\n # one. Therefore, changing one, will change them all.\n rand!(signal.signal_type.I_codes.codes[end][prn_keys[1]], 0:1)\n else\n # If a dictionary of databits was given instead, then each\n # databit array is different. They are then separately\n # regenerated.\n for key in prn_keys\n rand!(signal.signal_type.I_codes.codes[end][key], 0:1)\n end\n end\n end\n end\n end\n # Get adjusted code chipping rates and chipping rate rates for Q channel\n # codes\n if signal_type.include_Q\n for i in 1:signal_type.Q_codes.code_num\n # Q channel\n f_code = Q_codes.chipping_rates[i]\n code_length = Q_codes.code_lengths[i]\n f_code_d, f_code_dd = calc_doppler_code_rate(f_code, sig_freq,\n f_d, fd_rate)\n signal.f_code_d_Q[i] = f_code_d\n signal.f_code_dd_Q[i] = f_code_dd\n signal.init_code_phases_Q[i] = calcinitcodephase(code_length,\n f_code_d,\n f_code_dd, f_s,\n code_start_idx)\n end\n # Generate new databits for Q channel if `new_databits` flag is\n # `true`\n if Q_codes.databits\n if ~include_databits_Q\n signal.signal_type.Q_codes.include_codes[end] = false\n else\n signal.signal_type.Q_codes.include_codes[end] = true\n end\n if new_databits\n prn_keys = collect(keys(Q_codes.codes[1]))\n if Q_codes.similar_databits\n # If one array of databits was used for all PRNs, then the\n # databit arrays for all PRNs are references to the same\n # one. Therefore, changing one, will change them all.\n rand!(signal.signal_type.Q_codes.codes[end][prn_keys[1]], 0:1)\n else\n for key in prn_keys\n # If a dictionary of databits was given instead, then each\n # databit array is different. They are then separately\n # regenerated.\n rand!(signal.signal_type.Q_codes.codes[end][key], 0:1)\n end\n end\n end\n end\n end\n # Generate new thermal noise and phase noise vectors if `new_thermal_noise`\n # and/or `new_phase_noise` flags are set to `true`\n if new_thermal_noise\n randn!(signal.thermal_noise)\n end\n if new_phase_noise\n generate_phase_noise!(signal.phase_noise, signal.t_length, \n signal.signal_type.sig_freq, \n receiver_h_parms; \n phi_init=phase_noise_init_phase)\n end\n signal.name = name\n signal.prn = prn\n signal.f_if = f_if\n signal.f_d = f_d\n signal.fd_rate = fd_rate\n signal.Tsys = Tsys\n signal.CN0 = CN0\n signal.phi = phi\n signal.nADC = nADC\n signal.code_start_idx = code_start_idx\n signal.include_carrier = include_carrier\n signal.include_adc = include_adc\n signal.include_thermal_noise = include_thermal_noise\n signal.include_databits_I = include_databits_I\n signal.include_databits_Q = include_databits_Q\n signal.include_phase_noise = include_phase_noise\n signal.isreplica = isreplica\n signal.noexp = noexp\n signal.start_t = start_t\n return signal\nend\n\n\n\"\"\"\n definereplica(signal_type::SignalType, f_s, t_length; prn=1,\n f_if=0., f_d=0., fd_rate=0., phi=0., \n include_carrier=true, code_start_idx=1., \n include_databits_I=true, include_databits_Q=true, \n name=\"custom\",)\n\n\nDefine properties of locally generated generic replica signal\nbased off its type, PRN, etc.\n\nThis is used for processing `GNSSSignal` structs. It does not\ncontain noise souces in it. Do not use for GNSS signal simulation.\nUse definesignal and definesignal! methods for simulating GNSS\nsignals with noise.\n\n\nRequired Arguments:\n\n- `signal_type::SignalType`: user defined signal type\n * see `definecodetype` and `definesignaltype`\n- `f_s`: signal sampling frequency in Hz\n- `t_length`: signal length in seconds\n\n\nOptional Arguments:\n\n- `prn`: satellite PRN number `(default = 1)`\n- `f_if`: IF frequency in Hz `(default = 0Hz)`\n- `f_d`: signal Doppler frequency in Hz `(default = 0Hz)`\n- `fd_rate`: signal Doppler rate in Hz/s `(default = 0Hz/s)`\n- `phi`: initial carrier phase in rad `(default = 0rad)`\n- `include_carrier`: flag for modulating codes onto carrier `(default = true)`\n- `code_start_idx`: starting index in `ReplicaSignal.data` where all codes\n start `(default = 1)`\n- `include_databits_I`: flag for including I channel databits in simulated signal\n `(default = true)`\n- `include_databits_Q`: flag for including Q channel databits in simulated signal\n `(default = true)`\n- `name`: name of signal `(default = custom)`\n- `start_t`: the start time of the signal in seconds `(default = 0 seconds)`\n\n\nReturns:\n\n- `ReplicaSignal` struct\n\"\"\"\nfunction definereplica(signal_type::SignalType, f_s, t_length; prn=1,\n f_if=0., f_d=0., fd_rate=0., phi=0., \n include_carrier=true, code_start_idx=1., \n include_databits_I=true, include_databits_Q=true, \n name=\"custom\", start_t=0)\n return definesignal(signal_type, f_s, t_length; prn=prn,\n f_if=f_if, f_d=f_d, fd_rate=fd_rate, phi=phi, \n include_carrier=include_carrier, include_adc=false, \n include_thermal_noise=false, \n code_start_idx=code_start_idx, \n include_databits_I=include_databits_I,\n include_databits_Q=include_databits_Q, \n include_phase_noise=false, name=name, \n skip_noise_generation=true, \n allocate_noise_vectors=false,\n start_t=start_t)\nend\n\n\n\"\"\"\n definereplica!(signal::ReplicaSignal;\n prn=signal.prn, f_if=signal.f_if, f_d=signal.f_d,\n fd_rate=signal.fd_rate, phi=signal.phi, \n include_carrier=signal.include_carrier,\n code_start_idx=signal.code_start_idx,\n include_databits_I=signal.include_databits_I,\n include_databits_Q=signal.include_databits_Q,\n name=signal.name)\n\n\nRedefine properties of locally generated generic replica signal\nbased off its type, PRN, etc.\n\nThis is used for processing `GNSSSignal` structs. It does not\ncontain noise souces in it. Do not use for GNSS signal simulation.\nUse definesignal and definesignal! methods for simulating GNSS\nsignals with noise.\n\n\nRequired Arguments:\n\n- `signal::ReplicaSignal`: the signal already defined by the user using\n `definesignal`\n\n\nOptional Arguments with Defaults Equal to `signal` Field Values:\n\n- `prn`: satellite PRN number\n- `f_if`: IF frequency in Hz\n- `f_d`: signal Doppler frequency in Hz\n- `fd_rate`: signal Doppler rate in Hz/s\n- `phi`: initial carrier phase in rad\n- `include_carrier`: flag for modulating codes onto carrier\n- `code_start_idx`: starting index in `ReplicaSignal.data` where all codes\n start\n- `include_databits_I`: flag for including I channel databits in simulated signal\n- `include_databits_Q`: flag for including Q channel databits in simulated signal\n- `name`: name of signal\n- `start_t`: the start time of the signal in seconds `(default = 0 seconds)`\n\n\nModifies and Returns:\n\n- `signal::ReplicaSignal`\n\"\"\"\nfunction definereplica!(signal::ReplicaSignal;\n prn=signal.prn, f_if=signal.f_if, f_d=signal.f_d,\n fd_rate=signal.fd_rate, phi=signal.phi, \n include_carrier=signal.include_carrier,\n code_start_idx=signal.code_start_idx,\n include_databits_I=signal.include_databits_I,\n include_databits_Q=signal.include_databits_Q,\n name=signal.name, start_t=signal.start_t)\nreturn definesignal!(signal;\n prn=prn, f_if=f_if, f_d=f_d,\n fd_rate=fd_rate, phi=phi,\n include_carrier=include_carrier,\n include_adc=false, include_thermal_noise=false,\n code_start_idx=code_start_idx,\n include_databits_I=include_databits_I,\n include_databits_Q=include_databits_Q,\n include_phase_noise=false, name=name,\n new_thermal_noise=false, new_phase_noise=false,\n new_databits=false,\n start_t=signal.start_t)\nend\n\n\n\"\"\"\n check_length(a, N)\n\n\nCheck that an array, `a`, has length `N` or 1.\nIf it has length 1, return `a`, if its length\nis `N`, return `fill(a, N)`.\n\n\nRequired Arguments:\n\n- `a`: array whose length to check\n- `N`: the length to compare with `length(a)`\n\n\nReturns:\n\n- array that is either the same as `a` or `fill(a, N)`\n\"\"\"\nfunction check_length(a, N)\n @assert (length(a) == N) || (length(a) == 1)\n if length(a) > 1\n @assert length(a) == N\n return a\n else\n return fill(a, N)\n end\nend\n\n\n\n\"\"\"\n definesignal(prn::Vector, signal_type::SignalType, f_s, t_length;\n f_if=0., f_d=0., fd_rate=0., Tsys=535.,\n CN0=45., phi=0., nADC=4, include_carrier=true,\n include_adc=true, include_thermal_noise=true,\n code_start_idx=1., include_databits_I=true,\n include_databits_Q=true, include_phase_noise=true,\n phase_noise_scaler=1/10, name=\"custom\",\n receiver_h_parms=h_parms_tcxo[1], start_t=0)\n\"\"\"\nfunction definesignal(prn::Vector{Int}, signal_type, f_s, t_length;\n f_if=0., f_d=0., fd_rate=0., Tsys=535.,\n CN0=45., phi=0., nADC=4, include_carrier=true,\n include_adc=true, include_thermal_noise=true,\n code_start_idx=1., include_databits_I=true,\n include_databits_Q=true, include_phase_noise=true,\n phase_noise_scaler=1/10, name=\"custom\",\n receiver_h_parms=h_parms_tcxo[1], start_t=0)\n # Check that parameters are either length of 1 or N. If they are length 1,\n # then they are globally asigned to all signals defined.\n N = length(prn)\n f_d = check_length(f_d, N)\n fd_rate = check_length(fd_rate, N)\n CN0 = check_length(CN0, N)\n phi = check_length(phi, N)\n code_start_idx = check_length(code_start_idx, N)\n include_databits_I = check_length(include_databits_I, N)\n include_databits_Q = check_length(include_databits_Q, N)\n # Check that `signal_type` is either an array of signal types or singular\n if isa(signal_type, Array{eltype(signal_type)})\n @assert length(signal_type) == N \n elseif isa(signal_type, SignalType)\n signal_type = fill(signal_type, N)\n else\n error(\"Invalid `signal_type` specified.\")\n end\n # Define vector of `length(prn)` `ReplicaSignal` structs with 0 `t_length`\n replica_signals = Array{ReplicaSignal}(undef, N)\n B_Is = []\n B_Qs = []\n\n for i in 1:N\n push!(B_Is, signal_type[i].B_I)\n push!(B_Qs, signal_type[i].B_Q)\n replica_signals[i] = definesignal(signal_type[i], f_s, 0.; prn=prn[i],\n f_if=f_if, f_d=f_d[i], \n fd_rate=fd_rate[i], Tsys=Tsys[i],\n CN0=CN0[i], phi=phi[i], nADC=nADC,\n code_start_idx=code_start_idx[i],\n include_databits_I=include_databits_I[i],\n include_databits_Q=include_databits_Q[i],\n include_thermal_noise=false,\n include_phase_noise=false,\n include_carrier=include_carrier,\n include_adc=false, \n skip_noise_generation=true,\n allocate_noise_vectors=false) \n end\n B_I = maximuma(xor.(1, ismissing.(B_Is)))\n B_Q = maximuma(xor.(1, ismissing.(B_Qs)))\n B = max(B_I, B_Q)\n sample_num = floor(Int, f_s*t_length)\n data = Array{Complex{Float64}}(undef, sample_num)\n if include_thermal_noise\n thermal_noise = randn(Complex{Float64}, sample_num)\n else\n thermal_noise = Array{Complex{Float64}}(undef, sample_num)\n end\n if include_phase_noise\n phase_noise = generate_phase_noise(t_length, f_s, \n signal_type[1].sig_freq, \n receiver_h_parms)\n else\n phase_noise = Array{Float64}(undef, sample_num)\n end\n return ReplicaSignals(name, replica_signals, data, t_length, f_s, f_if, \n B, Tsys, sample_num, nADC, include_carrier, \n include_adc, include_thermal_noise, \n include_phase_noise, thermal_noise, phaser_noise,\n receiver_h_parms, start_t)\nend\n\n\n\"\"\"\n definesignal!(signal::ReplicaSignals, prn::Vector{Int}, signal_type;\n f_if=signal.f_if, f_d=0., fd_rate=0., Tsys=535.,\n CN0=45., phi=0., nADC=4, \n include_carrier=signal.include_carrier,\n include_adc=signal.include_adc, \n include_thermal_noise=signal.include_thermal_noise,\n code_start_idx=1., include_databits_I=true,\n include_databits_Q=true, \n include_phase_noise=signal.include_phase_noise,\n name=\"custom\", new_thermal_noise=false,\n new_phase_noise=false,\n receiver_h_parms=signal.receiver_h_parms,\n start_t=signal.start_t)\n\"\"\"\nfunction definesignal!(signal::ReplicaSignals, prn::Vector{Int}, signal_type;\n f_if=signal.f_if, f_d=0., fd_rate=0., Tsys=535.,\n CN0=45., phi=0., nADC=4, \n include_carrier=signal.include_carrier,\n include_adc=signal.include_adc, \n include_thermal_noise=signal.include_thermal_noise,\n code_start_idx=1., include_databits_I=true,\n include_databits_Q=true, \n include_phase_noise=signal.include_phase_noise,\n name=\"custom\", new_thermal_noise=false,\n new_phase_noise=false,\n receiver_h_parms=signal.receiver_h_parms,\n start_t=signal.start_t)\n # Check that parameters are either length of 1 or N. If they are length 1,\n # then they are globally asigned to all signals defined.\n f_s = signal.f_s\n t_length = signal.t_length\n include_carrier = signal.include_carrier\n N = length(prn)\n f_d = check_length(f_d, N)\n fd_rate = check_length(fd_rate, N)\n CN0 = check_length(CN0, N)\n phi = check_length(phi, N)\n code_start_idx = check_length(code_start_idx, N)\n include_databits_I = check_length(include_databits_I, N)\n include_databits_Q = check_length(include_databits_Q, N)\n signal.include_thermal_noise = include_thermal_noise\n signal.include_phase_noise = include_phase_noise\n signal.Tsys = Tsys \n signal.start_t = start_t\n # Check that `signal_type` is either an array of signal types or singular\n if isa(signal_type, Array{eltype(signal_type)})\n @assert length(signal_type) == N \n elseif isa(signal_type, SignalType)\n signal_type = fill(signal_type, N)\n else\n error(\"Invalid `signal_type` specified.\")\n end\n # Define vector of `length(prn)` `ReplicaSignal` structs with 0 `t_length`\n signal.replica_signals = Array{ReplicaSignal}(undef, N)\n B_Is = []\n B_Qs = []\n for i in 1:N\n push!(B_Is, signal_type[i].B_I)\n push!(B_Qs, signal_type[i].B_Q)\n signal.replica_signals[i] = definesignal(signal_type[i], f_s, 0.; \n prn=prn[i],\n f_if=f_if, f_d=f_d[i], \n fd_rate=fd_rate[i], Tsys=Tsys[i],\n CN0=CN0[i], phi=phi[i], nADC=nADC,\n code_start_idx=code_start_idx[i],\n include_databits_I=include_databits_I[i],\n include_databits_Q=include_databits_Q[i],\n include_thermal_noise=false,\n include_phase_noise=false,\n include_carrier=include_carrier,\n include_adc=false, \n skip_noise_generation=true,\n allocate_noise_vectors=false) \n end\n B_I = maximuma(xor.(1, ismissing.(B_Is)))\n B_Q = maximuma(xor.(1, ismissing.(B_Qs)))\n B = max(B_I, B_Q)\n signal.B = B\n if new_thermal_noise\n randn!(signal.thermal_noise)\n end\n if new_phase_noise\n generate_phase_noise!(signal.phase_noise, t_length, \n signal.replica_signals[1].signal_type.sig_freq, \n receiver_h_parms)\n end\n return signal\nend\n", "meta": {"hexsha": "c8f1b04e81fd331be9dc60b818c887718c27ae68", "size": 33460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/definesignal.jl", "max_stars_repo_name": "cu-sense-lab/GNSSTools.jl", "max_stars_repo_head_hexsha": "6077629b969b7ab8434c6060a317cea818d9c7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-20T20:22:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T20:22:43.000Z", "max_issues_repo_path": "src/definesignal.jl", "max_issues_repo_name": "cu-sense-lab/GNSSTools.jl", "max_issues_repo_head_hexsha": "6077629b969b7ab8434c6060a317cea818d9c7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/definesignal.jl", "max_forks_repo_name": "cu-sense-lab/GNSSTools.jl", "max_forks_repo_head_hexsha": "6077629b969b7ab8434c6060a317cea818d9c7d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-20T20:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T20:22:46.000Z", "avg_line_length": 44.7925033467, "max_line_length": 90, "alphanum_fraction": 0.5962343096, "num_tokens": 7605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18949865699205484}} {"text": "\n # Functions and methods for cascade computation\n\n \"\"\"\n `Cascade.computeDecayYieldOutcome(outcome::DecayYield.Outcome, linesR::Array{PhotoEmission.Line,1}, \n linesA::Array{AutoIonization.Line,1}, settings::DecayYield.Settings)` \n ... to compute the flourescence and Auger yields for a single decay yield outcome as specified by the corresponding\n level; an outcome::DecayYield.Outcome is returned in which all physical parameters are now specified for the given\n decay-yield.\n \"\"\"\n function computeDecayYieldOutcome(outcome::DecayYield.Outcome, linesR::Array{PhotoEmission.Line,1}, \n linesA::Array{AutoIonization.Line,1}, settings::DecayYield.Settings)\n # Identify the level key of the given level also in the lists of radiative and Auger lines\n level = outcome.level; levelKey = LevelKey( LevelSymmetry(level.J, level.parity), level.index, level.energy, 0.)\n similarKey = LevelKey(); rateR = 0.; rateA = 0.; NoPhotonLines = 0; NoAugerLines = 0\n for line in linesR\n compareKey = LevelKey( LevelSymmetry(line.initialLevel.J, line.initialLevel.parity), line.initialLevel.index, line.initialLevel.energy, 0.)\n if Basics.isSimilar(levelKey, compareKey, 1.0e-3) println(\"** compareKey = $compareKey\"); similarKey = deepcopy(compareKey) end\n end\n if similarKey == LevelKey() error(\"No similar level found !\") end\n \n for line in linesR\n if similarKey == LevelKey( LevelSymmetry(line.initialLevel.J, line.initialLevel.parity), line.initialLevel.index, line.initialLevel.energy, 0.)\n rateR = rateR + line.photonRate; NoPhotonLines = NoPhotonLines + 1 \n end\n end\n for line in linesA\n if similarKey == LevelKey( LevelSymmetry(line.initialLevel.J, line.initialLevel.parity), line.initialLevel.index, line.initialLevel.energy, 0.)\n rateA = rateA + line.totalRate; NoAugerLines = NoAugerLines + 1 \n end\n end\n \n omegaR = rateR / (rateR + rateA); omegaA = rateA / (rateR + rateA)\n newOutcome = DecayYield.Outcome(level, NoPhotonLines, NoAugerLines, rateR, rateA, omegaR, omegaA)\n return( newOutcome )\n end\n\n\n \"\"\"\n `Cascade.computeTotalAugerRate(level::Cascade.Level)` \n ... computes the total Auger rate of level as given by its daugther levels; a rate::Float64 is returned.\n \"\"\"\n function computeTotalAugerRate(level::Cascade.Level)\n rate = 0.\n for daugther in level.daugthers\n if daugther.process != Basics.Auger(); continue end\n aLine = daugther.lineSet.linesA[daugther.index]\n rate = rate + aLine.totalRate\n end\n return( rate )\n end\n\n\n \"\"\"\n `Cascade.computeTotalPhotonRate(level::Cascade.Level)` \n ... computes the total photon (radiative) rate of level as given by its daugther levels; a rate::EmProperty is returned.\n \"\"\"\n function computeTotalPhotonRate(level::Cascade.Level)\n rate = Basics.EmProperty(0.)\n for daugther in level.daugthers\n if daugther.process != Basics.Radiative(); continue end\n rLine = daugther.lineSet.linesR[daugther.index]\n rate = rate + rLine.photonRate\n end\n \n return( rate )\n end\n\n\n\n \"\"\"\n `Cascade.displayBlocks(stream::IO, blockList::Array{Cascade.Block,1}; sa::String=\"\")` \n ... group & display the blocks of the cascade with same No. of electrons; this blocks are displayed with the\n minimum and maximum energy of each multiplet. The optional sa::String can be used to display some details\n about the given blocks. nothing is returned.\n \"\"\"\n function displayBlocks(stream::IO, blockList::Array{Cascade.Block,1}; sa::String=\"\")\n #\n nx = 150\n println(stream, \"\\n* Configuration 'blocks' (multiplets): \" * sa * \"\\n\")\n println(stream, \" \", TableStrings.hLine(nx))\n println(stream, \" No. Configurations \" *\n \" No. CSF \",\n \" Range of total energies \" * TableStrings.inUnits(\"energy\") ) \n println(stream, \" \", TableStrings.hLine(nx))\n i = 0\n for block in blockList\n i = i + 1; \n sa = \" \" * TableStrings.flushright( 6, string(i); na=2)\n sb = \" \"; for conf in blockList[i].confs sb = sb * string(conf) * \", \" end\n en = Float64[]; for level in block.multiplet.levels push!(en, level.energy) end\n minEn = minimum(en); minEn = Defaults.convertUnits(\"energy: from atomic\", minEn)\n maxEn = maximum(en); maxEn = Defaults.convertUnits(\"energy: from atomic\", maxEn)\n sa = sa * TableStrings.flushleft(87, sb[1:end-2]; na=2) \n sb = \" \" * string( length(block.multiplet.levels) )\n sa = sa * sb[end-9:end] * \" \"\n sa = sa * TableStrings.flushleft(30, string( round(minEn)) * \" ... \" * string( round(maxEn)); na=2)\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(nx))\n\n return( nothing )\n end\n \n\n \"\"\"\n `Cascade.displayLevels(stream::IO, multiplets::Array{Multiplet,1}; sa::String=\"\")` \n ... display on stream the initial configurations as well as the calculated levels for all initial multiplets.\n \"\"\"\n function displayLevels(stream::IO, multiplets::Array{Multiplet,1}; sa::String=\"\")\n nx = 44\n println(stream, \" \")\n println(stream, \"* Configurations and levels for all given \" * sa * \"multiplets of the cascade, relative to the lowest:\")\n for multiplet in multiplets\n println(stream, \" \")\n confList = Basics.extractNonrelativisticConfigurations(multiplet.levels[1].basis)\n for conf in confList\n println(stream, \" $conf\")\n end\n println(stream, \" \", TableStrings.hLine(nx))\n println(stream, \" Level J Parity Energy \" * TableStrings.inUnits(\"energy\") ) \n println(stream, \" \", TableStrings.hLine(nx))\n for i = 1:length(multiplet.levels)\n lev = multiplet.levels[i]\n en = lev.energy - multiplet.levels[1].energy; en_requested = Defaults.convertUnits(\"energy: from atomic\", en)\n sc = \" \" * TableStrings.level(i) * \" \" * string(LevelSymmetry(lev.J, lev.parity)) * \" \"\n @printf(stream, \"%s %.15e %s\", sc, en_requested, \"\\n\")\n end\n println(stream, \" \", TableStrings.hLine(nx))\n end\n return( nothing )\n end\n \n\n \"\"\"\n `Cascade.displaySteps(stream::IO, steps::Array{Cascade.Step,1}; sa::String=\"\")` \n ... displays all predefined steps in a neat table and supports to delete individual steps from the list.\n sa::String can be used to display details about the given steps\n \"\"\"\n function displaySteps(stream::IO, steps::Array{Cascade.Step,1}; sa::String=\"\")\n nx = 170\n println(stream, \" \")\n println(stream, \"* Steps that are defined for the current \" * sa * \"cascade due to the given approach:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"\n sa = sa * TableStrings.center( 9, \"Step-No\"; na=2)\n sa = sa * TableStrings.flushleft(11, \"Process\"; na=1)\n sa = sa * TableStrings.flushleft(55, \"Initial: No CSF, configuration(s)\"; na=4)\n sa = sa * TableStrings.flushleft(55, \"Final: No CSF, configuration(s)\"; na=4)\n sa = sa * TableStrings.flushleft(40, \"Energies from ... to in \" * TableStrings.inUnits(\"energy\"); na=4)\n println(stream, sa)\n println(stream, \" \", TableStrings.hLine(nx))\n #\n for i = 1:length(steps)\n sa = \" \" * TableStrings.flushright( 7, string(i); na=5)\n sa = sa * TableStrings.flushleft( 11, string(steps[i].process); na=1)\n sb = \"\"; for conf in steps[i].initialConfigs sb = sb * string(conf) * \", \" end\n sa = sa * TableStrings.flushright( 5, string( length(steps[i].initialMultiplet.levels[1].basis.csfs) )*\", \"; na=0) \n sa = sa * TableStrings.flushleft( 50, sb[1:end-2]; na=4)\n sb = \"\"; for conf in steps[i].finalConfigs sb = sb * string(conf) * \", \" end\n sa = sa * TableStrings.flushright( 5, string( length(steps[i].finalMultiplet.levels[1].basis.csfs) )*\", \"; na=0) \n sa = sa * TableStrings.flushleft( 50, sb[1:end-2]; na=4)\n minEn = 1000.; maxEn = -1000.;\n for p = 1:length(steps[i].initialMultiplet.levels), q = 1:length(steps[i].finalMultiplet.levels)\n minEn = min(minEn, steps[i].initialMultiplet.levels[p].energy - steps[i].finalMultiplet.levels[q].energy)\n maxEn = max(maxEn, steps[i].initialMultiplet.levels[p].energy - steps[i].finalMultiplet.levels[q].energy)\n end\n minEn = Defaults.convertUnits(\"energy: from atomic\", minEn); maxEn = Defaults.convertUnits(\"energy: from atomic\", maxEn)\n sa = sa * string( round(minEn)) * \" ... \" * string( round(maxEn))\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(nx))\n end\n \n \n \"\"\"\n `Cascade.generateBlocks(comp::Cascade.Computation, confs::Array{Configuration,1}, initalOrbitals::Dict{Subshell, Orbital}; \n sa::String=\"\", printout::Bool=true)` \n ... generate all block::Cascade.Block's, that need to be computed for this cascade, and compute also the corresponding multiplets.\n The different cascade approches enables one to realized follow different strategies how these block are selected and computed. \n A blockList::Array{Cascade.Block,1} is returned.\n \"\"\"\n function generateBlocks(comp::Cascade.Computation, confs::Array{Configuration,1}, initalOrbitals::Dict{Subshell, Orbital}; \n sa::String=\"\", printout::Bool=true)\n blockList = Cascade.Block[]\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n #\n if comp.approach == AverageSCA()\n if printout\n println(\"\\n* Generate blocks \" * sa)\n println(\"\\n In the cascade approach $(comp.approach), the following assumptions/simplifications are made: \")\n println(\" + orbitals from the initial multiplet are applied throughout; \")\n println(\" + all blocks (multiplets) are generated from single-CSF levels and without any configuration mixing even in the SC; \")\n println(\" + only E1 dipole transitions are applied in all radiative decay stets; \")\n println(\" + for each decay step, a (single) set of continuum orbitals with an configuration averaged energy is applied \" *\n \"for all transitions of the same step. \\n\")\n if printSummary \n println(iostream, \"\\n* Generate blocks \" * sa)\n println(iostream, \"\\n* In the cascade approach $(comp.approach), the following assumptions/simplifications are made: \")\n println(iostream, \" + orbitals from the initial multiplet are applied throughout; \")\n println(iostream, \" + all blocks (multiplets) are generated from single-CSF levels and without any configuration mixing even in the SC; \")\n println(iostream, \" + only E1 dipole transitions are applied in all radiative decay stets; \")\n println(iostream, \" + for each decay step, a (single) set of continuum orbitals with an configuration averaged energy is applied \" *\n \"for all transitions of the same step. \\n\")\n end\n end # printout\n #\n for confa in confs\n print(\" Multiplet computations for $(string(confa)[1:end]) with $(confa.NoElectrons) electrons ... \")\n if printSummary println(iostream, \"\\n* Multiplet computations for $(string(confa)[1:end]) with $(confa.NoElectrons) electrons ... \") end\n multiplet = Basics.perform(\"computation: mutiplet from orbitals, no CI, CSF diagonal\", [confa], initalOrbitals, \n comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n # Shift the total energies of all levels if requested for the StepwiseDecayScheme\n if typeof(comp.scheme) == StepwiseDecayScheme && haskey(comp.scheme.chargeStateShifts, confa.NoElectrons)\n energyShift = comp.scheme.chargeStateShifts[confa.NoElectrons]\n multiplet = Basics.shiftTotalEnergies(multiplet, energyShift)\n print(\"shift all levels by $energyShift [a.u.] ... \")\n end\n push!( blockList, Cascade.Block(confa.NoElectrons, [confa], true, multiplet) )\n println(\"and $(length(multiplet.levels[1].basis.csfs)) CSF done. \")\n end\n elseif comp.approach == SCA()\n if printout\n println(\"\\n* Generate blocks \" * sa)\n println(\"\\n In the cascade approach $(comp.approach), the following assumptions/simplifications are made: \")\n println(\" + orbitals are generated independently for each multiplet (block); \")\n println(\" + configuration interaction is included for each block; \")\n println(\" + only E1 dipole transitions are applied in all radiative decay stets; \\n\")\n if printSummary \n println(iostream, \"\\n* Generate blocks \" * sa)\n println(iostream, \"\\n* In the cascade approach $(comp.approach), the following assumptions/simplifications are made: \")\n println(iostream, \" + orbitals are generated independently for each multiplet (block); \")\n println(iostream, \" + configuration interaction is included for each block; \")\n println(iostream, \" + only E1 dipole transitions are applied in all radiative decay stets; \\n\")\n end\n end # printout\n #\n i = 0\n for confa in confs\n ## i = i + 1; if i in [1,2, 4,5,6,7,8,9,10,11,12,13,14] || i > 15 println(\" Block $i omitted.\"); continue end\n ## i = i + 1; if i < 11 || i > 11 println(\" Block $i omitted.\"); continue end\n print(\" Multiplet computations for $(string(confa)[1:end]) with $(confa.NoElectrons) electrons ... \")\n if printSummary print(iostream, \"* Multiplet computations for $(string(confa)[1:end]) with $(confa.NoElectrons) electrons ... \") end\n basis = Basics.performSCF([confa], comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplet = Basics.performCI(basis, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n push!( blockList, Cascade.Block(confa.NoElectrons, [confa], true, multiplet) )\n println(\"and $(length(multiplet.levels[1].basis.csfs)) CSF done. \")\n end\n else error(\"Unsupported cascade approach.\")\n end\n\n return( blockList )\n end\n \n\n \"\"\"\n `Cascade.generateConfigurationList(multiplets::Array{Multiplet,1}, further::Int64, NoShake::Int64)` \n ... generates all possible (decay) configurations with up to further holes and with NoShake displacements with regard\n to the given multiplets. First, all configuratons are generated for which the hole is either moved 'outwards' or \n is moved and a second 'outer' hole is created; this step is repated further + 2 times to make sure that all relevant\n configurations are met. From the generated list, however, only those configurations are kept eventually with \n up to further holes, when compared to the configurations of the given multiplets. A confList::Array{Configuration,1} \n is returned.\n \"\"\"\n function generateConfigurationList(multiplets::Array{Multiplet,1}, further::Int64, NoShake::Int64)\n # Determine all (different) configurations from multiplets\n confList = Configuration[]\n for mp in multiplets \n cfList = Basics.extractNonrelativisticConfigurations(mp.levels[1].basis)\n for cf in cfList if cf in confList nothing else push!(confList, cf) end end\n end\n cList = copy(confList); initialNoElectrons = multiplets[1].levels[1].basis.NoElectrons\n # First, move and generate new 'outer' hole without displacements\n for fur = 1:further+1\n newConfList = Configuration[]\n for conf in cList\n holeList = Basics.determineHoleShells(conf)\n for holeShell in holeList\n wa = generateConfigurationsWith1OuterHole(conf, holeShell); append!(newConfList, wa)\n wa = generateConfigurationsWith2OuterHoles(conf, holeShell); append!(newConfList, wa)\n end\n end\n newConfList = unique(newConfList)\n ##x if length(newConfList) > 0 newConfList = Basics.excludeDoubles(newConfList) end\n cList = newConfList\n append!(confList, newConfList)\n end\n # Make sure that only configurations with up to further holes are returned\n newConfList = Configuration[]\n for conf in confList \n if conf.NoElectrons + further >= initialNoElectrons push!(newConfList, conf) end\n end\n # Add further shake-displacements if appropriate\n ##x newConfList = Basics.excludeDoubles(newConfList)\n newConfList = unique(newConfList)\n return( newConfList )\n end\n\n\n \"\"\"\n `Cascade.generateConfigurationsWith1OuterHole(conf, holeShell)` \n ... generates all possible (decay) configurations where the hole in holeShell is moved 'outwards'. \n A confList::Array{Configuration,1} is returned.\n \"\"\"\n function generateConfigurationsWith1OuterHole(conf::Configuration, holeShell::Shell)\n shList = Basics.generate(\"shells: ordered list for NR configurations\", [conf]); i0 = 0\n for i = 1:length(shList)\n if holeShell == shList[i] i0 = i; break end\n end\n if i0 == 0 error(\"stop a\") end\n #\n # Now move the hole 'outwards'\n confList = Configuration[]\n for i = i0+1:length(shList)\n if haskey(conf.shells, shList[i]) && conf.shells[ shList[i] ] >= 1 \n newshells = copy( conf.shells )\n newshells[ shList[i] ] = newshells[ shList[i] ] - 1\n newshells[ holeShell ] = newshells[ holeShell ] + 1\n push!(confList, Configuration( newshells, conf.NoElectrons ) )\n end\n end\n return( confList )\n end\n\n\n \"\"\"\n `Cascade.generateConfigurationsWith2OuterHoles(conf, holeShell)` \n ... generates all possible (decay) configurations where the hole in holeShell is moved 'outwards'. \n A confList::Array{Configuration,1} is returned.\n \"\"\"\n function generateConfigurationsWith2OuterHoles(conf::Configuration, holeShell::Shell)\n shList = Basics.generate(\"shells: ordered list for NR configurations\", [conf]); i0 = 0\n for i = 1:length(shList)\n if holeShell == shList[i] i0 = i; break end\n end\n if i0 == 0 error(\"stop a\") end\n #\n # Now move the hole 'outwards'\n confList = Configuration[]\n for i = i0+1:length(shList)\n if haskey(conf.shells, shList[i]) && conf.shells[ shList[i] ] >= 2 \n newshells = copy( conf.shells )\n newshells[ shList[i] ] = newshells[ shList[i] ] - 2\n newshells[ holeShell ] = newshells[ holeShell ] + 1\n push!(confList, Configuration( newshells, conf.NoElectrons - 1 ) )\n end\n #\n for j = i0+1:length(shList)\n if i != j && haskey(conf.shells, shList[i]) && conf.shells[ shList[i] ] >= 1 &&\n haskey(conf.shells, shList[j]) && conf.shells[ shList[j] ] >= 1 \n newshells = copy( conf.shells )\n newshells[ shList[i] ] = newshells[ shList[i] ] - 1\n newshells[ shList[j] ] = newshells[ shList[j] ] - 1\n newshells[ holeShell ] = newshells[ holeShell ] + 1\n push!(confList, Configuration( newshells, conf.NoElectrons - 1 ) )\n end\n end\n end\n return( confList )\n end\n\n\n\n \"\"\"\n `Cascade.groupDisplayConfigurationList(Z::Float64, confs::Array{Configuration,1}; sa::String=\"\")` \n ... group & display the configuration list into sublists with the same No. of electrons; this lists are displayed together \n with an estimated total energy. An ordered confList::Array{Configuration,1} is returned with configurations of decreasing\n number of electrons.\n \"\"\"\n function groupDisplayConfigurationList(Z::Float64, confs::Array{Configuration,1}; sa::String=\"\")\n minNoElectrons = 1000; maxNoElectrons = 0 \n for conf in confs\n minNoElectrons = min(minNoElectrons, conf.NoElectrons)\n maxNoElectrons = max(maxNoElectrons, conf.NoElectrons)\n end\n #\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n #\n println(\"\\n* Electron configuration(s) used: \" * sa)\n ## @warn \"*** Limit to just 4 configurations for each No. of electrons. ***\" ## delete nxx\n if printSummary println(iostream, \"\\n* Electron configuration(s) used: \" * sa) end\n confList = Configuration[]; nc = 0\n for n = maxNoElectrons:-1:minNoElectrons\n nxx = 0 ## delete nxx\n println(\"\\n Configuration(s) with $n electrons:\")\n if printSummary println(iostream, \"\\n Configuration(s) with $n electrons:\") end\n nd = 0\n for conf in confs nd = max(nd, length(\" \" * string(conf))) end\n for conf in confs\n if n == conf.NoElectrons \n ## nxx = nxx + 1; if nxx > 4 break end ## delete nxx\n nc = nc + 1\n push!(confList, conf ) \n if Z > 36.0 wa = 0.\n else wa = Semiempirical.estimate(\"binding energy\", round(Int64, Z), conf); \n wa = Defaults.convertUnits(\"energy: from atomic\", wa)\n end\n sb = \" av. BE = \" * string( round(-wa) ) * \" \" * TableStrings.inUnits(\"energy\")\n sd = \" \" * string(conf) * \" \"\n println(sd[1:nd+3] * sb * \" ($nc)\" )\n if printSummary println(iostream, sd[1:nd+3] * sb * \" ($nc)\") end\n end \n end\n end\n \n println(\"\\n A total of $nc configuration have been defined for this \" * sa * \"cascade, and selected configurations could be \" *\n \"removed here: [currently not supported]\")\n if printSummary println(iostream, \"\\n* A total of $nc configuration have been defined for this cascade, and selected \" *\n \"configurations could be removed here: [currently not supported]\") end\n return( confList )\n end\n\n\n \"\"\"\n `Cascade.modifySteps(stepList::Array{Cascade.Step,1})` \n ... allows the user to modify the steps, for instance, by deleting selected steps of the cascade or by modifying the settings of\n one or several steps. A newStepList::Array{Cascade.Step,1} for which the transition data are eventually computed.\n \"\"\"\n function modifySteps(stepList::Array{Cascade.Step,1})\n #\n newStepList = Cascade.Step[]\n #\n println(\"\\n* Here, modify the individual steps explicitly in the code, if needed, ...... and just do it !!\")\n # \n # Delete individual steps from stepList\n # if i in [1,2,5, ...] modify the particular settings, etc.\n for i = 1:length(stepList)\n step = stepList[i]\n #\n if i in []\n println(\" Modify step $i :\")\n newStep = Cascade.Step(step.process, step.settings, step.initialConfs, step.finalConfs, step.initialMultiplet, step.initialMultiplet)\n push!(newStepList, newStep)\n else\n push!(newStepList, step)\n end\n end\n #\n # wa = [1,2,3]\n # delete from list\n #\n println(\"\\n A total of $(length(newStepList)) steps are still defined in the cascade.\")\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary println(iostream, \"\\n* A total of $(length(newStepList)) steps are still defined in the cascade.\") end \n \n return( newStepList )\n end\n", "meta": {"hexsha": "10bf1efdddcaf60d26cc05fb531125ca32a6ba6a", "size": 25668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-Cascade-inc-computations.jl", "max_stars_repo_name": "sostock/JAC.jl", "max_stars_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-Cascade-inc-computations.jl", "max_issues_repo_name": "sostock/JAC.jl", "max_issues_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-Cascade-inc-computations.jl", "max_forks_repo_name": "sostock/JAC.jl", "max_forks_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.1670378619, "max_line_length": 158, "alphanum_fraction": 0.5819697678, "num_tokens": 6196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.18949865165309504}} {"text": "### Latent models ####\ninclude(\"prior.jl\")\ninclude(\"posterior.jl\")\n\n## Exact Gaussian Process\nstruct LatentGP{T,Tpr<:GPPrior,Tpo<:Posterior{T},O} <: AbstractLatent{T,Tpr,Tpo}\n prior::Tpr\n post::Tpo\n opt::O\nend\n\nfunction LatentGP(T::DataType, dim::Int, kernel::Kernel, mean::PriorMean, opt)\n return LatentGP(\n GPPrior(deepcopy(kernel), deepcopy(mean), cholesky(Matrix{T}(I, dim, dim))),\n Posterior(dim, zeros(T, dim), cholesky(Matrix{T}(I(dim)))),\n deepcopy(opt),\n )\nend\n\n@traitimpl IsFull{LatentGP}\n\n## AbstractVarLatent\n\nabstract type AbstractVarLatent{T,Tpr,Tpo} <: AbstractLatent{T,Tpr,Tpo} end\n\n## Variational Gaussian Process\nmutable struct VarLatent{T,Tpr<:GPPrior,Tpo<:VarPosterior{T},O} <:\n AbstractVarLatent{T,Tpr,Tpo}\n prior::Tpr\n post::Tpo\n opt::O\nend\n\nfunction VarLatent(T::DataType, dim::Int, kernel::Kernel, mean::PriorMean, opt)\n return VarLatent(\n GPPrior(deepcopy(kernel), deepcopy(mean), cholesky(Matrix{T}(I, dim, dim))),\n VarPosterior{T}(dim),\n deepcopy(opt),\n )\nend\n\n@traitimpl IsFull{VarLatent}\n\n## Sparse Variational Gaussian Process\n\nmutable struct SparseVarLatent{\n T,Tpr<:GPPrior,Tpo<:VarPosterior{T},Topt,TZ<:AbstractVector,TZopt\n} <: AbstractVarLatent{T,Tpr,Tpo}\n prior::Tpr\n post::Tpo\n Z::TZ\n Knm::Matrix{T}\n κ::Matrix{T}\n K̃::Vector{T}\n opt::Topt\n Zopt::TZopt\nend\n\nfunction SparseVarLatent(\n T::DataType,\n dim::Int,\n S::Int,\n Z::AbstractVector,\n kernel::Kernel,\n mean::PriorMean,\n opt=nothing,\n Zopt=nothing\n)\n return SparseVarLatent(\n GPPrior(deepcopy(kernel), deepcopy(mean), cholesky(Matrix{T}(I(dim)))),\n VarPosterior{T}(dim),\n deepcopy(Z),\n Matrix{T}(undef, S, dim),\n Matrix{T}(undef, S, dim),\n Vector{T}(undef, S),\n deepcopy(opt),\n deepcopy(Zopt),\n )\nend\n\n@traitimpl IsSparse{SparseVarLatent}\n\n## Monte-Carlo Gaussian Process\n\nstruct SampledLatent{T,Tpr<:GPPrior,Tpo<:SampledPosterior{T}} <: AbstractLatent{T,Tpr,Tpo}\n prior::Tpr\n post::Tpo\nend\n\nfunction SampledLatent(T::DataType, dim::Int, kernel::Kernel, mean::PriorMean)\n return SampledLatent(\n GPPrior(deepcopy(kernel), deepcopy(mean), cholesky(Matrix{T}(I, dim, dim))),\n SampledPosterior(dim, zeros(T, dim), Symmetric(Matrix{T}(I(dim)))),\n )\nend\n\n@traitimpl IsFull{SampledLatent}\n\n## Online Sparse Variational Process\n\nmutable struct OnlineVarLatent{T,Tpr<:GPPrior,Tpo<:AbstractVarPosterior{T},Topt,TZ<:AbstractVector,\n TZalg<:InducingPoints.OnIPSA,TZopt} <:\n AbstractVarLatent{T,Tpo,Tpr}\n prior::Tpr\n post::Tpo\n Z::TZ\n Zalg::TZalg\n Knm::Matrix{T}\n κ::Matrix{T}\n K̃::Vector{T}\n Zupdated::Bool\n opt::Topt\n Zopt::TZopt\n Zₐ::AbstractVector\n Kab::Matrix{T}\n κₐ::Matrix{T}\n K̃ₐ::Matrix{T}\n invDₐ::Symmetric{T,Matrix{T}}\n prev𝓛ₐ::T\n prevη₁::Vector{T}\nend\n\nfunction OnlineVarLatent(\n T::DataType,\n dim::Int,\n nSamplesUsed::Int,\n Z::AbstractVector,\n Zalg::InducingPoints.OnIPSA,\n kernel::Kernel,\n mean::PriorMean,\n opt=nothing,\n Zopt=nothing\n)\n return OnlineVarLatent(\n GPPrior(deepcopy(kernel), deepcopy(mean), cholesky(Matrix{T}(I, dim, dim))),\n OnlineVarPosterior{T}(dim),\n Z,\n Zalg,\n Matrix{T}(undef, nSamplesUsed, dim),\n Matrix{T}(undef, nSamplesUsed, dim),\n Vector{T}(undef, nSamplesUsed),\n false,\n deepcopy(opt),\n deepcopy(Zopt),\n deepcopy(Z),\n Matrix{T}(I, dim, dim),\n Matrix{T}(I, dim, dim),\n Matrix{T}(I, dim, dim),\n Symmetric(Matrix{T}(I, dim, dim)),\n zero(T),\n Vector{T}(undef, dim),\n )\nend\n\n@traitimpl IsSparse{OnlineVarLatent}\n\n## Variational Student-T Process\n\nmutable struct TVarLatent{T<:Real,Tpr<:TPrior,Tpo<:VarPosterior{T},O} <:\n AbstractVarLatent{T,Tpr,Tpo}\n prior::Tpr\n post::Tpo\n opt::O\nend\n\nfunction TVarLatent(T::DataType, ν::Real, dim::Int, kernel::Kernel, mean::PriorMean, opt)\n return TVarLatent(\n TPrior(\n deepcopy(kernel),\n deepcopy(mean),\n cholesky(Matrix{T}(I, dim, dim)),\n ν,\n rand(T),\n rand(T),\n ),\n VarPosterior{T}(dim),\n deepcopy(opt),\n )\nend\n\n@traitimpl IsFull{TVarLatent}\n\n### Functions\n\nprior(gp::AbstractLatent) = gp.prior\nkernel(gp::AbstractLatent) = kernel(prior(gp))\nsetkernel!(gp::AbstractLatent, kernel::Kernel) = setkernel!(prior(gp), kernel)\npr_mean(gp::AbstractLatent) = mean(prior(gp))\npr_mean(gp::AbstractLatent, X::AbstractVector) = mean(prior(gp), X)\nsetpr_mean!(gp::AbstractLatent, μ₀::PriorMean) = setmean!(prior(gp), μ₀)\npr_cov(gp::AbstractLatent) = cov(prior(gp))\npr_cov(gp::TVarLatent) = prior(gp).χ * cov(prior(gp))\npr_cov!(gp::AbstractLatent, K::Cholesky) = gp.prior.K = K\n\nposterior(gp::AbstractLatent) = gp.post\nDistributions.dim(gp::AbstractLatent) = dim(posterior(gp))\nDistributions.mean(gp::AbstractLatent) = mean(posterior(gp))\nDistributions.cov(gp::AbstractLatent) = cov(posterior(gp))\nDistributions.var(gp::AbstractLatent) = var(posterior(gp))\nnat1(gp::AbstractVarLatent) = nat1(posterior(gp))\nnat2(gp::AbstractVarLatent) = nat2(posterior(gp))\n\nmean_f(model::AbstractGP) = mean_f.(model.f)\n\n@traitfn mean_f(gp::T) where {T <: AbstractLatent; IsFull{T}} = mean_f(mean(gp))\n@traitfn mean_f(gp::T) where {T <: AbstractLatent; !IsFull{T}} = mean_f(mean(gp), gp.κ)\n\nmean_f(μ::AbstractVector) = μ\nmean_f(μ::AbstractVector, κ::AbstractMatrix) = κ * μ\n\nvar_f(model::AbstractGP) = var_f.(model.f)\n\n@traitfn var_f(gp::T) where {T <: AbstractLatent; IsFull{T}} = var_f(cov(gp))\n@traitfn var_f(gp::T) where {T <: AbstractLatent; !IsFull{T}} = var_f(cov(gp), gp.κ, gp.K̃)\n\nvar_f(Σ::AbstractMatrix) = diag(Σ)\nvar_f(Σ::AbstractMatrix, κ::AbstractMatrix, K̃::AbstractVector) = diag_ABt(κ * Σ, κ) + K̃\n\nZview(gp::SparseVarLatent) = gp.Z\nZview(gp::OnlineVarLatent) = gp.Z\n\nsetZ!(gp::AbstractLatent, Z::AbstractVector) = gp.Z = Z\n\nopt(gp::AbstractLatent) = gp.opt\nZopt(::AbstractLatent) = nothing\nZopt(gp::SparseVarLatent) = gp.Zopt\nZopt(gp::OnlineVarLatent) = gp.Zopt\n\n@traitfn function compute_K!(\n gp::TGP, X::AbstractVector, jitt::Real\n) where {TGP <: AbstractLatent; IsFull{TGP}}\n return pr_cov!(gp, cholesky(kernelmatrix(kernel(gp), X) + jitt * I))\nend\n\n@traitfn function compute_K!(gp::T, jitt::Real) where {T <: AbstractLatent; !IsFull{T}}\n return pr_cov!(gp, cholesky(kernelmatrix(kernel(gp), gp.Z) + jitt * I))\nend\n\nfunction compute_κ!(gp::SparseVarLatent, X::AbstractVector, jitt::Real)\n gp.Knm = kernelmatrix(kernel(gp), X, gp.Z)\n gp.κ = copy(gp.Knm / pr_cov(gp))\n gp.K̃ = kernelmatrix_diag(kernel(gp), X) .+ jitt - diag_ABt(gp.κ, gp.Knm)\n return all(gp.K̃ .> 0) || error(\"K̃ has negative values\")\nend\n\nfunction compute_κ!(gp::OnlineVarLatent, X::AbstractVector, jitt::Real)\n # Covariance with the model at t-1\n gp.Kab = kernelmatrix(kernel(gp), gp.Zₐ, gp.Z)\n gp.κₐ = gp.Kab / pr_cov(gp)\n Kₐ = Symmetric(kernelmatrix(kernel(gp), gp.Zₐ) + jitt * I)\n gp.K̃ₐ = Kₐ - gp.κₐ * transpose(gp.Kab)\n\n # Covariance with a new batch\n gp.Knm = kernelmatrix(kernel(gp), X, gp.Z)\n gp.κ = gp.Knm / pr_cov(gp)\n gp.K̃ = kernelmatrix_diag(kernel(gp), X) .+ jitt - diag_ABt(gp.κ, gp.Knm)\n all(gp.K̃ .> 0) || error(\"K̃ has negative values\")\nend\n", "meta": {"hexsha": "ade16c2478e5fc39d4f291c924dc84b8f3e2a06c", "size": 7387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gpblocks/latentgp.jl", "max_stars_repo_name": "pitmonticone/AugmentedGaussianProcesses.jl", "max_stars_repo_head_hexsha": "8f45d3b607d7777e77b3392fed7f950261f6f715", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gpblocks/latentgp.jl", "max_issues_repo_name": "pitmonticone/AugmentedGaussianProcesses.jl", "max_issues_repo_head_hexsha": "8f45d3b607d7777e77b3392fed7f950261f6f715", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gpblocks/latentgp.jl", "max_forks_repo_name": "pitmonticone/AugmentedGaussianProcesses.jl", "max_forks_repo_head_hexsha": "8f45d3b607d7777e77b3392fed7f950261f6f715", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5212355212, "max_line_length": 99, "alphanum_fraction": 0.6484364424, "num_tokens": 2358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.18892817999311884}} {"text": "\n\"\"\"\n`module JAC.BascisPerform` \n ... a submodel of JAC that contains methods that support tasks related to spectroscopic computation.\n\"\"\"\nmodule BascisPerform\n\n using Printf, JAC, ..AngularMomentum, ..Atomic, ..Basics, ..Bsplines, ..Cascade, ..Continuum, ..Defaults, ..Einstein, ..ManyElectron, \n ..Nuclear, ..PlasmaShift, ..Radial\n \n export perform\n\n \"\"\"\n `Basics.perform(computation::Atomic.Computation)` \n ... to perform the computation as prescribed by comp. All relevant intermediate and final results are printed to screen (stdout). \n Nothing is returned.\n\n `Basics.perform(computation::Atomic.Computation; output=true)` \n ... to perform the same but to return the complete output in a dictionary; the particular output depends on the type and \n specifications of the computations but can easily accessed by the keys of this dictionary.\n \"\"\"\n function Basics.perform(computation::Atomic.Computation; output::Bool=false)\n if output results = Dict{String, Any}() else results = nothing end\n nModel = computation.nuclearModel\n\n # Distinguish between the computation of level energies and properties and the simulation of atomic processes\n if length(computation.configs) != 0\n ##x if computation.asfSettings.breitCI\n ##x @warn(\"perform: Test the Breit interaction; asfSettings = $(computation.asfSettings) \")\n ##x wx = ManyElectron.Multiplet(\"from Ratip2012\", \"../test/testBreit/FeX-small-csl.inp\",\n ##x \"../test/testBreit/FeX-small-scf.out\",\"../test/testBreit/FeX-small-relci.mix-coulomb\") \n ##x basis = wx.levels[1].basis\n ##x multiplet = perform(\"computation: CI\", basis, nModel, computation.grid, computation.asfSettings)\n ##x error(\"stop after Breit test\")\n ##x end =#\n basis = perform(\"computation: SCF\", computation.configs, nModel, computation.grid, computation.asfSettings)\n multiplet = perform(\"computation: CI\", basis, nModel, computation.grid, computation.asfSettings)\n LSjj.expandLevelsIntoLS(multiplet, computation.asfSettings.jjLS)\n #\n if output results = Base.merge( results, Dict(\"multiplet:\" => multiplet) ) \n results = Base.merge( results, Dict(\"grid:\" => computation.grid) ) end\n \n # Now compute all requested properties\n if JAC.EinsteinX in computation.properties \n outcome = JAC.Einstein.computeLines(multiplet, computation.grid, computation.einsteinSettings) \n if output results = Base.merge( results, Dict(\"Einstein lines:\" => outcome) ) end\n end\n if JAC.HFS in computation.properties && computation.hfsSettings.calcIJFexpansion \n outcome = JAC.Hfs.computeHyperfineMultiplet(multiplet, nModel, computation.grid, computation.hfsSettings) \n if output results = Base.merge( results, Dict(\"IJF multiplet:\" => outcome) ) end\n end\n if JAC.HFS in computation.properties\n outcome = JAC.Hfs.computeOutcomes(multiplet, nModel, computation.grid, computation.hfsSettings) \n if output results = Base.merge( results, Dict(\"HFS outcomes:\" => outcome) ) end\n end\n if JAC.LandeJ in computation.properties \n outcome = JAC.LandeZeeman.computeOutcomes(multiplet, nModel, computation.grid, computation.zeemanSettings) \n if output results = Base.merge( results, Dict(\"Zeeman parameter outcomes:\" => outcome) ) end\n end\n if JAC.Isotope in computation.properties \n outcome = JAC.IsotopeShift.computeOutcomes(multiplet, nModel, computation.grid, computation.isotopeSettings) \n if output results = Base.merge( results, Dict(\"Isotope parameter outcomes:\" => outcome) ) end\n end\n if JAC.AlphaX in computation.properties \n outcome = JAC.AlphaVariation.computeOutcomes(multiplet, nModel, computation.grid, computation.alphaSettings) \n if output results = Base.merge( results, Dict(\"alpha variation parameter outcomes:\" => outcome) ) end\n end\n if JAC.FormF in computation.properties \n outcome = JAC.FormFactor.computeOutcomes(multiplet, nModel, computation.grid, computation.formSettings) \n if output results = Base.merge( results, Dict(\"Form factor outcomes:\" => outcome) ) end\n end\n if JAC.Yields in computation.properties \n outcome = JAC.DecayYield.computeOutcomes(computation.configs, computation.asfSettings, \n multiplet, nModel, computation.grid, computation.yieldSettings) \n if output results = Base.merge( results, Dict(\"Fluorescence and AutoIonization yield outcomes:\" => outcome) ) end\n end\n if JAC.Green in computation.properties \n outcome = JAC.GreenFunction.computeRepresentation(computation.configs, multiplet, nModel, computation.grid, computation.greenSettings) \n if output results = Base.merge( results, Dict(\"Green function outcomes:\" => outcome) ) end\n end\n if JAC.Polarity in computation.properties \n outcome = JAC.MultipolePolarizibility.computeOutcomes(multiplet, nModel, computation.grid, computation.polaritySettings) \n if output results = Base.merge( results, Dict(\"Polarizibility outcomes:\" => outcome) ) end\n end\n if JAC.Plasma in computation.properties \n outcome = JAC.PlasmaShift.computeOutcomes(multiplet, nModel, computation.grid, computation.asfSettings, computation.plasmaSettings) \n if output results = Base.merge( results, Dict(\"Plasma shift outcomes:\" => outcome) ) end\n end\n \n # Evaluate processes that need special SCF and CI procedures\n elseif computation.process in [AugerInPlasma, PhotoInPlasma]\n pSettings = computation.processSettings\n plasmaSettings = PlasmaShift.Settings(pSettings.plasmaModel, pSettings.lambdaDebye, pSettings.ionSphereR0, pSettings.NoBoundElectrons)\n initialBasis = perform(\"computation: SCF\", computation.initialConfigs, nModel, computation.grid, \n computation.initialAsfSettings)\n initialMultiplet = perform(\"computation: CI for plasma\", initialBasis, nModel, computation.grid, computation.initialAsfSettings,\n plasmaSettings)\n finalBasis = perform(\"computation: SCF\", computation.finalConfigs, nModel, computation.grid, computation.finalAsfSettings)\n finalMultiplet = perform(\"computation: CI for plasma\", finalBasis, nModel, computation.grid, computation.finalAsfSettings,\n plasmaSettings)\n #\n if computation.process == JAC.AugerInPlasma \n outcome = JAC.AutoIonization.computeLinesPlasma(finalMultiplet, initialMultiplet, nModel, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"AutoIonization lines in plasma:\" => outcome) ) end\n elseif computation.process == JAC.PhotoInPlasma \n outcome = JAC.PhotoIonization.computeLinesPlasma(finalMultiplet, initialMultiplet, nModel, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"Photo lines in plasma:\" => outcome) ) end\n else\n error(\"stop a\")\n end\n \n else\n initialBasis = perform(\"computation: SCF\", computation.initialConfigs, nModel, computation.grid, computation.initialAsfSettings)\n initialMultiplet = perform(\"computation: CI\", initialBasis, nModel, computation.grid, computation.initialAsfSettings)\n finalBasis = perform(\"computation: SCF\", computation.finalConfigs, nModel, computation.grid, computation.finalAsfSettings)\n finalMultiplet = perform(\"computation: CI\", finalBasis, nModel, computation.grid, computation.finalAsfSettings)\n #\n if computation.process in [PhotoExcFluor, PhotoExcAuto, PhotoIonFluor, PhotoIonAuto, ImpactExcAuto, Dierec]\n intermediateBasis = perform(\"computation: SCF\", computation.intermediateConfigs, nModel, computation.grid, \n computation.intermediateAsfSettings)\n intermediateMultiplet = perform(\"computation: CI\", intermediateBasis, nModel, computation.grid, \n computation.intermediateAsfSettings)\n end\n #\n if computation.process == JAC.Auger \n ##x println(\" \")\n ##x for i = 1:3 println(\" perform-WARNING: Code modified to read in multiplets from Grasp computations and for testing integrals \" *\n ##x \"and Auger amplitudes !!\") \n ##x end\n ##x initialMultiplet = JAC.ManyElectron.Multiplet(\"from Grasp2013\", \"TestAuger/belike-resonance-a-csl.inp\",\n ##x \"TestAuger/belike-resonance-a-scf.out\",\"TestAuger/belike-resonance-a-relci.mix\") \n ##x finalMultiplet = JAC.ManyElectron.Multiplet(\"from Grasp2013\", \"TestAuger/belike-ground-a-csl.inp\",\n ##x \"TestAuger/belike-ground-a-scf.out\",\"TestAuger/belike-ground-a-relci.mix\") \n outcome = JAC.AutoIonization.computeLines(finalMultiplet, initialMultiplet, nModel, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"AutoIonization lines:\" => outcome) ) end\n elseif computation.process == JAC.Radiative \n ##x println(\" \")\n ##x for i = 1:3 println(\" perform-WARNING: Code modified to read in multiplets from Grasp computations and for testing integrals \" *\n ##x \"and radiative amplitudes !!\") \n ##x end\n ##x finalMultiplet = JAC.ManyElectron.Multiplet(\"from Grasp2013\", \"TestRaditive/helike-resonance-a-csl.inp\",\n ##x \"TestRaditive/helike-resonance-a-scf.out\",\"TestRaditive/helike-resonance-a-relci.mix\") \n ##x initialMultiplet = JAC.ManyElectron.Multiplet(\"from Grasp2013\", \"TestRaditive/helike-resonance-a-csl.inp\",\n ##x \"TestRaditive/helike-resonance-a-scf.out\",\"TestRaditive/helike-resonance-a-relci.mix\") \n outcome = JAC.PhotoEmission.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"radiative lines:\" => outcome) ) end\n elseif computation.process == JAC.Photo \n outcome = JAC.PhotoIonization.computeLines(finalMultiplet, initialMultiplet, nModel, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"photoionization lines:\" => outcome) ) end\n elseif computation.process == JAC.Rec \n outcome = JAC.PhotoRecombination.computeLines(finalMultiplet, initialMultiplet, nModel, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"photo recombination lines:\" => outcome) ) end\n elseif computation.process == JAC.Eimex \n outcome = JAC.ImpactExcitation.computeLines(finalMultiplet, initialMultiplet, nModel, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"impact-excitation lines:\" => outcome) ) end\n elseif computation.process == JAC.PhotoExc \n outcome = JAC.PhotoExcitation.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"photo-excitation lines:\" => outcome) ) end\n elseif computation.process == JAC.PairA1P \n outcome = JAC.PairAnnihilation1Photon.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"pair-annihilation-1-photon lines:\" => outcome) ) end\n elseif computation.process == JAC.MultiPhotonDE\n outcome = JAC.MultiPhotonDeExcitation.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"multi-photon-de-excitation lines:\" => outcome) ) end\n elseif computation.process == JAC.RAuger\n outcome = JAC.RadiativeAuger.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"radiative Auger sharings:\" => outcome) ) end\n elseif computation.process == JAC.Coulex\n outcome = JAC.CoulombExcitation.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"Coulomb excitation lines:\" => outcome) ) end\n elseif computation.process == JAC.Coulion\n outcome = JAC.CoulombIonization.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"Coulomb ionization lines:\" => outcome) ) end\n elseif computation.process == JAC.PhotoExcAuto \n outcome = JAC.PhotoExcitationAutoion.computePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, nModel, \n computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"photo-excitation-autoionization pathways:\" => outcome) ) end\n elseif computation.process == JAC.PhotoExcFluor \n outcome = JAC.PhotoExcitationFluores.computePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, \n computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"photo-excitation-fluorescence pathways:\" => outcome) ) end\n elseif computation.process == JAC.PhotoIonAuto \n outcome = JAC.PhotoIonizationAutoion.computePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, \n computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"photo-ionization-autoionization pathways:\" => outcome) ) end\n elseif computation.process == JAC.PhotoIonFluor \n outcome = JAC.PhotoIonizationFluores.computePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, \n computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"photo-ionizatiton-fluorescence pathways:\" => outcome) ) end\n elseif computation.process == JAC.ImpactExcAuto \n outcome = JAC.ImpactExcitationAutoion.computePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, \n computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"impact-excitation-autoionization pathways:\" => outcome) ) end\n elseif computation.process == JAC.Compton \n outcome = JAC.RayleighCompton.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"Rayleigh-Compton lines:\" => outcome) ) end\n elseif computation.process == JAC.MultiPI \n outcome = JAC.MultiPhotonIonization.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"multi-photon single ionization:\" => outcome) ) end\n elseif computation.process == JAC.MultiPDI \n outcome = JAC.MultiPhotonDoubleIon.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"multi-photon double ionization:\" => outcome) ) end\n elseif computation.process == JAC.InternalConv \n outcome = JAC.InternalConversion.computeLines(finalMultiplet, initialMultiplet, computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"internal conversion lines:\" => outcome) ) end\n elseif computation.process == JAC.Dierec \n outcome = JAC.Dielectronic.computePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, nModel, \n computation.grid, computation.processSettings) \n if output results = Base.merge( results, Dict(\"dielectronic recombination pathways:\" => outcome) ) end\n else\n error(\"stop b\")\n end\n end\n \n Defaults.warn(PrintWarnings)\n Defaults.warn(ResetWarnings)\n return( results )\n end\n\n\n\n \"\"\"\n `Basics.perform(comp::Cascade.Computation)` \n ... to set-up and perform a cascade computation that starts from a given set of initial configurations and proceeds via \n various steps until a given number of electrons has been removed or the decay stops at some stable levels with regard \n to the given atomic processes. The results of all individual steps are printed to screen but nothing is returned \n otherwise.\n\n `Basics.perform(comp::Cascade.Computation; output=true)` \n ... to perform the same but to return the complete output in a dictionary; the particular output depends on the type \n and specifications of the cascade but can easily accessed by the keys of this dictionary.\n \"\"\"\n function Basics.perform(comp::Cascade.Computation; output::Bool=false)\n if output results = Dict{String, Any}() else results = nothing end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n #\n # Perform the SCF and CI computation for the intial-state multiplet and print them out with their relative occupation\n basis = perform(\"computation: SCF\", comp.initialConfs, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplet = perform(\"computation: CI\", basis, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplet = Multiplet(\"initial states\", multiplet.levels)\n JAC.Cascade.displayInitialLevels(stdout, multiplet, comp.initialLevels)\n if printSummary JAC.Cascade.displayInitialLevels(iostream, multiplet, comp.initialLevels) end \n if output results = Base.merge( results, Dict(\"initial multiplet:\" => multiplet) ) end\n #\n # Generate subsequent cascade configurations as well as display and group them together\n wa = JAC.Cascade.generateConfigurationList(comp.initialConfs, comp.maxElectronLoss, comp.NoShakeDisplacements)\n wb = JAC.Cascade.groupDisplayConfigurationList(comp.nuclearModel.Z, wa)\n #\n # Determine first all configuration 'blocks' and from them the individual steps of the cascade\n wc = JAC.Cascade.generateBlocks(comp, wb, basis.orbitals)\n JAC.Cascade.displayBlocks(stdout, wc)\n if printSummary JAC.Cascade.displayBlocks(iostream, wc) end \n # Determine, modify and compute the transition data for all steps, ie. the PhotoEmission.Line's, the AutoIonization.Line's, etc.\n wd = JAC.Cascade.determineSteps(comp, wc)\n JAC.Cascade.displaySteps(stdout, wd)\n if printSummary JAC.Cascade.displaySteps(iostream, wd) end \n we = JAC.Cascade.modifySteps(wd)\n data = JAC.Cascade.computeSteps(comp, we)\n if output \n results = Base.merge( results, Dict(\"cascade data:\" => data) )\n #\n # Write out the result to file to later continue with simulations on the cascade data\n filename = \"zzz-Cascade-\" * string(now())[1:13] * \".jld\"\n println(\"\\nWrite all results to disk; use:\\n save($filename, results) \\n using JLD \" *\n \"\\n results = load($filename) ... to load the results back from file.\")\n if printSummary println(iostream, \"\\nWrite all results to disk; use:\\n save($filename, results) \\n using JLD \" *\n \"\\n results = load($filename) ... to load the results back from file.\" ) end \n save(filename, results)\n end\n ## return( results )\n return( data )\n end\n\n\n\n \"\"\"\n `Basics.perform(simulation::Cascade.Simulation, data::Cascade.Data)` \n ... to simulate a cascade decay (and excitation) by using the given data::Cascade.Data. Different computational methods and \n different properties of the ionic system, such as the ion distribution or final-level distribution can be derived and \n displayed from these simulations. Of course, the details of these simulations strongly depend on the atomic processes \n and data that have been generated before by performing a computation::Cascade.Computation. The results of all individual \n steps are printed to screen but nothing is returned otherwise.\n\n `Basics.perform(simulation::Cascade.Simulation, data::Cascade.Data; output=true)` \n ... to perform the same but to return the complete output in a dictionary; the particular output depends on the method and \n specifications of the cascade but can easily accessed by the keys of this dictionary.\n \"\"\"\n function Basics.perform(simulation::Cascade.Simulation, data::Cascade.Data; output::Bool=false)\n if output results = Dict{String, Any}() else results = nothing end\n #\n # Distinguish between the different computational methods for running the simulations\n if simulation.method == Cascade.ProbPropagation()\n if JAC.Cascade.FinalDist() in simulation.properties || JAC.Cascade.IonDist() in simulation.properties\n wa = Cascade.simulateLevelDistribution(simulation, data) \n end\n if JAC.Cascade.ElectronIntensity() in simulation.properties || JAC.Cascade.PhotonIntensity() in simulation.properties ||\n JAC.Cascade.ElectronCoincidence() in simulation.properties \n error(\"stop a: Not yet implemented\") \n end\n else error(\"stop b\")\n end\n\n if output \n wx = 0. \n results = Base.merge( results, Dict(\"ion distribution:\" => wx) )\n # Write out the result to file to later continue with simulations on the cascade data\n filename = \"xxx-simulation-\" * string(now())[1:13] * \".jld\"\n println(\"\\nWrite all results to disk; use:\\n save($filename, results) \\n using JLD \" *\n \"\\n results = load($filename) ... to load the results back from file.\")\n save(filename, results)\n end\n return( results )\n end\n\n\n\n \"\"\"\n `Basics.perform(computation::Atomic.CasComputation)` \n ... to perform the computation ... . Nothing is returned. **Not yet implemented !**\n\n `Basics.perform(computation::Atomic.CasComputation; output=true)` \n ... to perform the same .... **Not yet implemented !**\n \"\"\"\n function Basics.perform(computation::Atomic.CasComputation; output::Bool=false)\n error(\"Not yet implemented\")\n end\n\n\n\n \"\"\"\n `Basics.perform(\"computation: SCF\", configs::Array{Configuration,1}, nuclearModel::Nuclear.Model, grid::Radial.Grid, settings::AsfSettings;\n printout::Bool=true)` \n ... to generate an atomic basis and to compute the self-consistent field (SCF) for this basis due to the given settings; \n a basis::Basis is returned. \n \"\"\"\n function Basics.perform(sa::String, configs::Array{Configuration,1}, nuclearModel::Nuclear.Model, grid::Radial.Grid, settings::AsfSettings;\n printout::Bool=true)\n !(sa == \"computation: SCF\") && error(\"Unsupported keystring = $sa\")\n if printout println(\"\\n... in perform('computation: SCF', ...\") end\n \n # Generate a list of relativistic configurations and determine an ordered list of subshells for these configurations\n relconfList = ConfigurationR[]\n for conf in configs\n wa = Basics.generate(\"configuration list: relativistic\", conf)\n append!( relconfList, wa)\n end\n if printout for i = 1:length(relconfList) println(\"perform-aa: \", relconfList[i]) end end\n subshellList = Basics.generate(\"subshells: ordered list for relativistic configurations\", relconfList)\n Defaults.setDefaults(\"relativistic subshell list\", subshellList; printout=printout)\n\n # Generate the relativistic CSF's for the given subshell list\n csfList = CsfR[]\n for relconf in relconfList\n newCsfs = Basics.generate(\"CSF list: from single ConfigurationR\", relconf, subshellList)\n append!( csfList, newCsfs)\n end\n\n # Determine the number of electrons and the list of coreSubshells\n NoElectrons = sum( csfList[1].occupation )\n coreSubshellList = Subshell[]\n for k in 1:length(subshellList)\n mocc = Basics.subshell_2j(subshellList[k]) + 1; is_filled = true\n for csf in csfList\n if csf.occupation[k] != mocc is_filled = false; break end\n end\n if is_filled push!( coreSubshellList, subshellList[k]) end\n end\n \n ##x waL = JAC.Bsplines.generatePrimitives(7, 7, grid); nsL = length(waL.bsplines) - 3\n ##x waS = JAC.Bsplines.generatePrimitives(8, 7, grid); nsS = length(waS.bsplines) - 3 \n wa = Bsplines.generatePrimitives(grid)\n\n # Generate start orbitals\n if settings.startScf == \"hydrogenic\"\n # Generate start orbitals for the SCF field by using B-splines\n ##x orbitals = JAC.Bsplines.generateOrbitalsHydrogenic(waL, nsL, waS, nsS, nuclearModel, subshellList)\n orbitals = JAC.Bsplines.generateOrbitalsHydrogenic(wa, nuclearModel, subshellList; printout=printout)\n elseif settings.startScf == \"fromNRorbitals\"\n # Generate starting orbitals for this csfList by adapting non-relativistic orbitals with a proper nuclear charge\n orbitals = Dict{Subshell, Orbital}()\n for subsh in subshellList\n orb = JAC.HydrogenicIon.radialOrbital(subsh, nuclearModel.Z, grid)\n orbitals = Base.merge( orbitals, Dict( subsh => orb) ) \n end\n else error(\"stop a\")\n end\n\n ##x error(\"stop ** for test reasons ** \")\n \n # Perform the SCF computations for the orbitals due to the given settings\n basis = Basis(true, NoElectrons, subshellList, csfList, coreSubshellList, orbitals)\n if settings.methodScf in [\"meanDFS\", \"meanHS\"]\n ##x newBasis = JAC.Bsplines.solveSelfConsistentFieldMean(waL, nsL, waS, nsS, nuclearModel, basis, settings) \n newBasis = JAC.Bsplines.solveSelfConsistentFieldMean(wa, nuclearModel, basis, settings; printout=printout) \n elseif settings.methodScf in [\"AL\", \"OL\"] \n ##x newBasis = JAC.Bsplines.solveSelfConsistentFieldOptimized(waL, nsL, waS, nsS, nuclearModel, basis, settings)\n newBasis = JAC.Bsplines.solveSelfConsistentFieldOptimized(wa, nuclearModel, basis, settings; printout=printout)\n else error(\"stop b\")\n end\n \n return( newBasis ) \n end\n\n\n\n \"\"\"\n `Basics.perform(\"computation: mutiplet from orbitals, no CI, CSF diagonal\", configs::Array{Configuration,1}, \n initalOrbitals::Dict{Subshell, Orbital}, nuclearModel::Nuclear.Model, grid::Radial.Grid, settings::AsfSettings; printout::Bool=true)` \n ... to generate from the given initial orbitals a multiplet of single-CSF levels by just using the diagonal \n part of the Hamiltonian matrix; a multiplet::Multiplet is returned. \n \"\"\"\n function Basics.perform(sa::String, configs::Array{Configuration,1}, initalOrbitals::Dict{Subshell, Orbital}, nuclearModel::Nuclear.Model, \n grid::Radial.Grid, settings::AsfSettings; printout::Bool=true)\n !(sa == \"computation: mutiplet from orbitals, no CI, CSF diagonal\") && error(\"Unsupported keystring = $sa\")\n if printout println(\"\\n... in perform('computation: mutiplet from orbitals, no CI, CSF diagonal', ...\") end\n \n # Generate a list of relativistic configurations and determine an ordered list of subshells for these configurations\n relconfList = ConfigurationR[]\n for conf in configs\n wa = Basics.generate(\"configuration list: relativistic\", conf)\n append!( relconfList, wa)\n end\n if printout for i = 1:length(relconfList) println(\"perform-aa: \", relconfList[i]) end end\n subshellList = Basics.generate(\"subshells: ordered list for relativistic configurations\", relconfList)\n Defaults.setDefaults(\"relativistic subshell list\", subshellList; printout=printout)\n\n # Generate the relativistic CSF's for the given subshell list\n csfList = CsfR[]\n for relconf in relconfList\n newCsfs = Basics.generate(\"CSF list: from single ConfigurationR\", relconf, subshellList)\n append!( csfList, newCsfs)\n end\n\n # Determine the number of electrons and the list of coreSubshells\n NoElectrons = sum( csfList[1].occupation )\n coreSubshellList = Subshell[]\n for k in 1:length(subshellList)\n mocc = Basics.subshell_2j(subshellList[k]) + 1; is_filled = true\n for csf in csfList\n if csf.occupation[k] != mocc is_filled = false; break end\n end\n if is_filled push!( coreSubshellList, subshellList[k]) end\n end\n \n # Set-up a basis for calculating the Hamiltonian matrix\n basis = Basis(true, NoElectrons, subshellList, csfList, coreSubshellList, initalOrbitals)\n \n # Calculate the diagonal part of the Hamiltonian matrix and define a multiplet for these approximate ASf;\n # Generate first an effective nuclear charge Z(r) on the given grid\n potential = JAC.Nuclear.nuclearPotential(nuclearModel, grid)\n \n n = length(csfList); matrix = zeros(Float64, n, n)\n for r = 1:n\n wa = compute(\"angular coefficients: e-e, Ratip2013\", basis.csfs[r], basis.csfs[r])\n me = 0.\n for coeff in wa[1]\n jj = Basics.subshell_2j(basis.orbitals[coeff.a].subshell)\n me = me + coeff.T * sqrt( jj + 1) * JAC.RadialIntegrals.GrantIab(basis.orbitals[coeff.a], basis.orbitals[coeff.b], grid, potential)\n end\n\n for coeff in wa[2]\n if settings.coulombCI \n me = me + coeff.V * JAC.InteractionStrength.XL_Coulomb(coeff.nu, basis.orbitals[coeff.a], basis.orbitals[coeff.b],\n basis.orbitals[coeff.c], basis.orbitals[coeff.d], grid) end\n if settings.breitCI\n me = me + coeff.V * JAC.InteractionStrength.XL_Breit(coeff.nu, basis.orbitals[coeff.a], basis.orbitals[coeff.b],\n basis.orbitals[coeff.c], basis.orbitals[coeff.d], grid) end\n end\n matrix[r,r] = me\n end \n #\n eigen = Basics.diagonalize(\"matrix: Julia, eigfact\", matrix)\n levels = Level[]\n for ev = 1:length(eigen.values)\n vector = eigen.vectors[ev]; ns = 0\n for r = 1:length(vector) \n if (vector[r])^2 > 0.99 ns = r; break \n elseif (vector[r])^2 > 0.01 error(\"stop a; unexpected mixing coefficieint; vector = $vector \") \n end\n end\n J = csfList[ns].J\n newlevel = Level( J, AngularM64(J.num//J.den), csfList[ns].parity, 0, eigen.values[ev], 0., true, basis, vector ) \n push!( levels, newlevel)\n end\n mp = Multiplet(\"noName\", levels)\n mp = Basics.sortByEnergy(mp)\n \n # Display all level energies and energy splittings\n if printout\n Basics.tabulate(\"multiplet: energies\", mp)\n Basics.tabulate(\"multiplet: energy relative to immediately lower level\", mp)\n Basics.tabulate(\"multiplet: energy of each level relative to lowest level\", mp)\n end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary \n Basics.tabulate(\"multiplet: energies\", mp, stream=iostream)\n Basics.tabulate(\"multiplet: energy relative to immediately lower level\", mp, stream=iostream)\n Basics.tabulate(\"multiplet: energy of each level relative to lowest level\", mp, stream=iostream)\n end\n \n return( mp )\n end\n\n\n \"\"\"\n `Basics.perform(\"computation: CI\", basis::Basis, nuclearModel::Nuclear.Model, grid::Radial.Grid, settings::AsfSettings; printout::Bool=true)` \n ... to set-up and diagonalize from the (SCF) basis the configuration-interaction matrix and to derive and display the \n level structure of the corresponding multiplet due to the given settings; a multiplet::Multiplet is returned. \n \"\"\"\n function Basics.perform(sa::String, basis::Basis, nuclearModel::Nuclear.Model, grid::Radial.Grid, settings::AsfSettings; printout::Bool=true)\n !(sa == \"computation: CI\") && error(\"Unsupported keystring = $sa\")\n \n # Determine the J^P symmetry blocks\n symmetries = Dict{JAC.LevelSymmetry,Int64}()\n for csf in basis.csfs\n sym = LevelSymmetry(csf.J, csf.parity)\n if haskey(symmetries, sym) symmetries[sym] = symmetries[sym] + 1\n else symmetries = Base.merge( symmetries, Dict( sym => 1 ) )\n end\n end\n\n # Test the total number of CSF\n NoCsf = 0\n for (sym,v) in symmetries NoCsf = NoCsf + v end\n \n # Calculate for each symmetry block the corresponding CI matrix, diagonalize it and append a Multiplet for this block\n multiplets = Multiplet[]\n for (sym,v) in symmetries\n matrix = compute(\"matrix: CI, J^P symmetry\", sym, basis, nuclearModel, grid, settings; printout=printout)\n eigen = Basics.diagonalize(\"matrix: Julia, eigfact\", matrix)\n levels = Level[]\n for ev = 1:length(eigen.values)\n # Construct the eigenvector with regard to the given basis (not w.r.t the symmetry block)\n evSym = eigen.vectors[ev]; vector = zeros( length(basis.csfs) ); ns = 0\n for r = 1:length(basis.csfs) \n if LevelSymmetry(basis.csfs[r].J, basis.csfs[r].parity) == sym ns = ns + 1; vector[r] = evSym[ns] end\n end\n newlevel = Level( sym.J, AngularM64(sym.J.num//sym.J.den), sym.parity, 0, eigen.values[ev], 0., true, basis, vector ) \n push!( levels, newlevel)\n end\n wa = Multiplet(\"noName\", levels)\n push!( multiplets, wa)\n end\n \n # Merge all multiplets into a single one\n mp = Basics.merge(multiplets)\n mp = Basics.sortByEnergy(mp)\n \n # Display all level energies and energy splittings\n if printout\n Basics.tabulate(\"multiplet: energies\", mp)\n Basics.tabulate(\"multiplet: energy relative to immediately lower level\", mp)\n Basics.tabulate(\"multiplet: energy of each level relative to lowest level\", mp)\n end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary \n Basics.tabulate(\"multiplet: energies\", mp, stream=iostream)\n Basics.tabulate(\"multiplet: energy relative to immediately lower level\", mp, stream=iostream)\n Basics.tabulate(\"multiplet: energy of each level relative to lowest level\", mp, stream=iostream)\n end\n \n return( mp )\n end\n\n\n \"\"\"\n `Basics.perform(\"computation: CI for plasma\", basis::Basis, nuclearModel::Nuclear.Model, grid::Radial.Grid, \n settings::AsfSettings, plasmaSettings::PlasmaShift.Settings; printout::Bool=true)` \n ... to set-up and diagonalize from the given (SCF) basis the configuration-interaction matrix and to derive and\n display the level structure of the corresponding multiplet due to the given settings. Here, the CI matrix\n includes the modifications of the Hamiltonian due to the given plasmaSettings; a multiplet::Multiplet is returned. \n \"\"\"\n function Basics.perform(sa::String, basis::Basis, nuclearModel::Nuclear.Model, grid::Radial.Grid, \n settings::AsfSettings, plasmaSettings::PlasmaShift.Settings; printout::Bool=true)\n !(sa == \"computation: CI for plasma\") && error(\"Unsupported keystring = $sa\")\n \n # Determine the J^P symmetry blocks\n symmetries = Dict{JAC.LevelSymmetry,Int64}()\n for csf in basis.csfs\n sym = LevelSymmetry(csf.J, csf.parity)\n if haskey(symmetries, sym) symmetries[sym] = symmetries[sym] + 1\n else symmetries = Base.merge( symmetries, Dict( sym => 1 ) )\n end\n end\n\n # Test the total number of CSF\n NoCsf = 0\n for (sym,v) in symmetries NoCsf = NoCsf + v end\n \n # Calculate for each symmetry block the corresponding CI matrix for the given plasma model and parameters as specified by\n # plasmaSettings, diagonalize it and append a Multiplet for this block\n multiplets = Multiplet[]\n for (sym,v) in symmetries\n matrix = compute(\"matrix: CI for plasma, J^P symmetry\", sym, basis, nuclearModel, grid, settings, plasmaSettings; printout=printout)\n eigen = Basics.diagonalize(\"matrix: Julia, eigfact\", matrix)\n levels = Level[]\n for ev = 1:length(eigen.values)\n # Construct the eigenvector with regard to the given basis (not w.r.t the symmetry block)\n evSym = eigen.vectors[ev]; vector = zeros( length(basis.csfs) ); ns = 0\n for r = 1:length(basis.csfs) \n if LevelSymmetry(basis.csfs[r].J, basis.csfs[r].parity) == sym ns = ns + 1; vector[r] = evSym[ns] end\n end\n newlevel = Level( sym.J, AngularM64(sym.J.num//sym.J.den), sym.parity, 0, eigen.values[ev], 0., true, basis, vector ) \n push!( levels, newlevel)\n end\n wa = Multiplet(\"noName\", levels)\n push!( multiplets, wa)\n end\n \n # Merge all multiplets into a single one\n mp = Basics.merge(multiplets)\n mp = Basics.sortByEnergy(mp)\n \n # Display all level energies and energy splittings\n if printout\n Basics.tabulate(\"multiplet: energies\", mp)\n Basics.tabulate(\"multiplet: energy relative to immediately lower level\", mp)\n Basics.tabulate(\"multiplet: energy of each level relative to lowest level\", mp)\n end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary \n Basics.tabulate(\"multiplet: energies\", mp, stream=iostream)\n Basics.tabulate(\"multiplet: energy relative to immediately lower level\", mp, stream=iostream)\n Basics.tabulate(\"multiplet: energy of each level relative to lowest level\", mp, stream=iostream)\n end\n \n return( mp )\n end\n\nend # module\n", "meta": {"hexsha": "c15edb94860f0580fc5493f208d20440352f194e", "size": 41945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-BasicsPerform.jl", "max_stars_repo_name": "SanjiangYang/JAC.jl", "max_stars_repo_head_hexsha": "f5612dd0912d95da0a22efa1224381606f0012d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-BasicsPerform.jl", "max_issues_repo_name": "SanjiangYang/JAC.jl", "max_issues_repo_head_hexsha": "f5612dd0912d95da0a22efa1224381606f0012d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-BasicsPerform.jl", "max_forks_repo_name": "SanjiangYang/JAC.jl", "max_forks_repo_head_hexsha": "f5612dd0912d95da0a22efa1224381606f0012d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-30T13:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T13:09:52.000Z", "avg_line_length": 66.4738510301, "max_line_length": 159, "alphanum_fraction": 0.616569317, "num_tokens": 9366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18846261649487922}} {"text": "export\n edlimb,\n edterm,\n ekacec,\n ekaced,\n ekacei,\n ekaclc,\n ekacld,\n ekacli,\n ekappr,\n ekbseg,\n ekccnt,\n ekcii,\n ekcls,\n ekdelr,\n ekffld,\n ekfind,\n ekgc,\n ekgd,\n ekgi,\n ekinsr,\n ekifld,\n eklef,\n eknelt,\n eknseg,\n ekntab,\n ekopn,\n ekopr,\n ekops,\n ekopw,\n ekpsel,\n ekrcec,\n ekrced,\n ekrcei,\n ekssum,\n ektnam,\n ekucec,\n ekuced,\n ekucei,\n ekuef,\n el2cgv,\n elemc,\n elemd,\n elemi,\n eqncpv,\n eqstr,\n esrchc,\n et2lst,\n et2utc,\n etcal,\n eul2m,\n eul2xf,\n expool\n\n\"\"\"\n edlimb(a, b, c, viewpt)\n\nFind the limb of a triaxial ellipsoid, viewed from a specified point.\n\n### Arguments ###\n\n- `a`: Length of ellipsoid semi-axis lying on the x-axis\n- `b`: Length of ellipsoid semi-axis lying on the y-axis\n- `c`: Length of ellipsoid semi-axis lying on the z-axis\n- `viewpt`: Location of viewing point\n\n### Output ###\n\nReturns the limb of the ellipsoid as seen from the viewing point.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edlimb_c.html)\n\"\"\"\nfunction edlimb(a, b, c, viewpt)\n @checkdims 3 viewpt\n limb = Ref{Ellipse}()\n ccall((:edlimb_c, libcspice), Cvoid,\n (SpiceDouble, SpiceDouble, SpiceDouble, Ref{SpiceDouble}, Ref{Ellipse}),\n a, b, c, viewpt, limb)\n handleerror()\n limb[]\nend\n\n\"\"\"\n edterm(trmtyp, source, target, et, fixref, abcorr, obsrvr, npts)\n\nCompute a set of points on the umbral or penumbral terminator of a specified\ntarget body, where the target shape is modeled as an ellipsoid.\n\n### Arguments ###\n\n- `trmtyp`: Terminator type\n- `source`: Light source\n- `target`: Target body\n- `et`: Observation epoch\n- `fixref`: Body-fixed frame associated with target\n- `abcorr`: Aberration correction\n- `obsrvr`: Observer\n- `npts`: Number of points in terminator set\n\n### Output ###\n\n- `trgepc`: Epoch associated with target center\n- `obspos`: Position of observer in body-fixed frame\n- `trmpts`: Terminator point set\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edterm_c.html)\n\"\"\"\nfunction edterm(trmtyp, source, target, et, fixref, abcorr, obsrvr, npts)\n trgepc = Ref{SpiceDouble}()\n obspos = Array{SpiceDouble}(undef, 3)\n trmpts = Array{SpiceDouble}(undef, 3, npts)\n ccall((:edterm_c, libcspice), Cvoid,\n (Cstring, Cstring, Cstring, SpiceDouble, Cstring, Cstring, Cstring, SpiceInt,\n Ref{SpiceDouble}, Ref{SpiceDouble}, Ref{SpiceDouble}),\n trmtyp, source, target, et, fixref, abcorr, obsrvr, npts, trgepc, obspos, trmpts)\n handleerror()\n trgepc[], obspos, trmpts\nend\n\n\"\"\"\n ekacec(handle, segno, recno, column, cvals, isnull)\n\nAdd data to a character column in a specified EK record.\n\n### Arguments ###\n\n- `handle`: EK file handle\n- `segno`: Index of segment containing record\n- `recno`: Record to which data is to be added\n- `column`: Column name\n- `cvals`: Character values to add to column\n- `isnull`: Flag indicating whether column entry is null\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacec_c.html)\n\"\"\"\nfunction ekacec(handle, segno, recno, column, cvals, isnull)\n cvals_, nvals, vallen = chararray(cvals)\n ccall((:ekacec_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring, SpiceInt, SpiceInt, Ref{SpiceChar}, SpiceBoolean),\n handle, segno - 1, recno - 1, column, nvals, vallen, cvals_, isnull)\n handleerror()\nend\n\n\"\"\"\n ekaced(handle, segno, recno, column, dvals, isnull)\n\nAdd data to an double precision column in a specified EK record.\n\n### Arguments ###\n\n- `handle`: EK file handle\n- `segno`: Index of segment containing record\n- `recno`: Record to which data is to be added\n- `column`: Column name\n- `dvals`: Double precision values to add to column\n- `isnull`: Flag indicating whether column entry is null\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekaced_c.html)\n\"\"\"\nfunction ekaced(handle, segno, recno, column, dvals, isnull)\n nvals = length(dvals)\n ccall((:ekaced_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring, SpiceInt, Ref{SpiceDouble}, SpiceBoolean),\n handle, segno - 1, recno - 1, column, nvals, dvals, isnull)\n handleerror()\nend\n\n\"\"\"\n ekacei(handle, segno, recno, column, ivals, isnull)\n\nAdd data to an integer column in a specified EK record.\n\n### Arguments ###\n\n- `handle`: EK file handle\n- `segno`: Index of segment containing record\n- `recno`: Record to which data is to be added\n- `column`: Column name\n- `ivals`: Integer values to add to column\n- `isnull`: Flag indicating whether column entry is null\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacei_c.html)\n\"\"\"\nfunction ekacei(handle, segno, recno, column, ivals, isnull)\n nvals = length(ivals)\n ivals_ = SpiceInt.(ivals)\n ccall((:ekacei_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring, SpiceInt, Ref{SpiceInt}, SpiceBoolean),\n handle, segno - 1, recno - 1, column, nvals, ivals_, isnull)\n handleerror()\nend\n\n\"\"\"\n ekaclc(handle, segno, column, cvals, nlflgs, rcptrs)\n\nAdd an entire character column to an EK segment.\n\n### Arguments ###\n\n- `handle`: EK file handle.\n- `segno`: Number of segment to add column to.\n- `column`: Column name.\n- `cvals`: Character values to add to column.\n- `nlflgs`: Array of null flags for column entries.\n- `rcptrs`: Record pointers for segment.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekaclc_c.html)\n\"\"\"\nfunction ekaclc(handle, segno, column, cvals, nlflgs, rcptrs)\n cvals_, nrows, vallen = chararray(cvals)\n nlflgs_ = SpiceBoolean.(nlflgs)\n @checkdims nrows nlflgs rcptrs\n entszs = SpiceInt.(length.(cvals))\n entszs[nlflgs] .= 0\n wkindx = Array{SpiceInt}(undef, nrows)\n ccall((:ekaclc_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, Cstring, SpiceInt, Ref{SpiceChar}, Ref{SpiceInt}, Ref{SpiceBoolean},\n Ref{SpiceInt}, Ref{SpiceInt}),\n handle, segno - 1, column, vallen, cvals_, entszs, nlflgs_, rcptrs, wkindx)\n handleerror()\nend\n\n\"\"\"\n ekacld(handle, segno, column, dvals, nlflgs, rcptrs)\n\nAdd an entire double precision column to an EK segment.\n\n### Arguments ###\n\n- `handle`: EK file handle\n- `segno`: Number of segment to add column to\n- `column`: Column name\n- `dvals`: Double precision values to add to column\n- `nlflgs`: Array of null flags for column entries\n- `rcptrs`: Record pointers for segment\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html)\n\"\"\"\nfunction ekacld(handle, segno, column, dvals, nlflgs, rcptrs)\n nrows = length(dvals)\n entszs = SpiceInt.(length.(dvals))\n entszs[nlflgs] .= 0\n dvals_ = array_to_cmatrix(dvals)\n nlflgs_ = SpiceBoolean.(nlflgs)\n @checkdims nrows nlflgs rcptrs\n wkindx = Array{SpiceInt}(undef, nrows)\n ccall((:ekacld_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, Cstring, Ref{SpiceDouble}, Ref{SpiceInt}, Ref{SpiceBoolean},\n Ref{SpiceInt}, Ref{SpiceInt}),\n handle, segno - 1, column, dvals_, entszs, nlflgs_, rcptrs, wkindx)\n handleerror()\nend\n\n\"\"\"\n ekacli(handle, segno, column, ivals, nlflgs, rcptrs)\n\nAdd an entire integer column to an EK segment.\n\n### Arguments ###\n\n- `handle`: EK file handle\n- `segno`: Number of segment to add column to\n- `column`: Column name\n- `ivals`: Integer values to add to column\n- `nlflgs`: Array of null flags for column entries\n- `rcptrs`: Record pointers for segment\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacli_c.html)\n\"\"\"\nfunction ekacli(handle, segno, column, ivals, nlflgs, rcptrs)\n nrows = length(ivals)\n entszs = SpiceInt.(length.(ivals))\n entszs[nlflgs] .= 0\n ivals_ = array_to_cmatrix(ivals)\n nlflgs_ = SpiceBoolean.(nlflgs)\n @checkdims nrows nlflgs rcptrs\n wkindx = Array{SpiceInt}(undef, nrows)\n ccall((:ekacli_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, Cstring, Ref{SpiceInt}, Ref{SpiceInt}, Ref{SpiceBoolean},\n Ref{SpiceInt}, Ref{SpiceInt}),\n handle, segno - 1, column, ivals_, entszs, nlflgs_, rcptrs, wkindx)\n handleerror()\nend\n\n\"\"\"\n ekappr(handle, segno)\n\nAppend a new, empty record at the end of a specified E-kernel segment.\n\n### Arguments ###\n\n- `handle`: File handle\n- `segno`: Segment number\n\n### Output ###\n\nReturns the number of appended record.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekappr_c.html)\n\"\"\"\nfunction ekappr(handle, segno)\n recno = Ref{SpiceInt}()\n ccall((:ekappr_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, Ref{SpiceInt}),\n handle, segno - 1, recno)\n handleerror()\n recno[] + 1\nend\n\n\"\"\"\n ekbseg(handle, tabnam, cnames, decls)\n\nStart a new segment in an E-kernel.\n\n### Arguments ###\n\n- `handle`: File handle\n- `tabnam`: Table name\n- `cnames`: Names of columns\n- `decls `: Declarations of columns\n\n### Output ###\n\nReturns the segment number.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekbseg_c.html)\n\"\"\"\nfunction ekbseg(handle, tabnam, cnames, decls)\n cnames_, ncols, cnmlen = chararray(cnames)\n @checkdims ncols decls\n decls_, _, declen = chararray(decls)\n segno = Ref{SpiceInt}()\n ccall((:ekbseg_c, libcspice), Cvoid,\n (SpiceInt, Cstring, SpiceInt, SpiceInt, Ref{SpiceChar}, SpiceInt, Ref{SpiceChar},\n Ref{SpiceInt}),\n handle, tabnam, ncols, cnmlen, cnames_, declen, decls_, segno)\n handleerror()\n segno[] + 1\nend\n\n\"\"\"\n ekccnt(table)\n\nReturn the number of distinct columns in a specified, currently loaded table\n\n### Arguments ###\n\n- `table`: Name of table\n\n### Output ###\n\nReturns the count of distinct, currently loaded columns.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekccnt_c.html)\n\"\"\"\nfunction ekccnt(table)\n ccount = Ref{SpiceInt}()\n ccall((:ekccnt_c, libcspice), Cvoid, (Cstring, Ref{SpiceInt}), table, ccount)\n handleerror()\n Int(ccount[])\nend\n\n\"\"\"\n ekcii(table, cindex, lenout=256)\n\nReturn attribute information about a column belonging to a loaded EK table, specifying the column\nby table and index.\n\n### Arguments ###\n\n- `table`: Name of table containing column\n- `cindex`: Index of column whose attributes are to be found\n- `lenout`: Maximum allowed length of column name (default: 256)\n\n### Output ###\n\n- `column`: Name of column\n- `attdsc`: Column attribute descriptor\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcii_c.html)\n\"\"\"\nfunction ekcii(table, cindex, lenout=256)\n column = Array{SpiceChar}(undef, lenout)\n attdsc = Ref{EKAttDsc}()\n ccall((:ekcii_c, libcspice), Cvoid,\n (Cstring, SpiceInt, SpiceInt, Ref{SpiceChar}, Ref{EKAttDsc}),\n table, cindex - 1, lenout, column, attdsc)\n handleerror()\n chararray_to_string(column), attdsc[]\nend\n\n\"\"\"\n ekcls(handle)\n\nClose an E-kernel.\n\n### Arguments ###\n\n- `handle`: EK file handle\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcls_c.html)\n\"\"\"\nfunction ekcls(handle)\n ccall((:ekcls_c, libcspice), Cvoid, (SpiceInt,), handle)\n handleerror()\nend\n\n\"\"\"\n ekdelr(handle, segno, recno)\n\nDelete a specified record from a specified E-kernel segment.\n\n### Arguments ###\n\n- `handle`: File handle\n- `segno`: Segment number\n- `recno`: Record number\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekdelr_c.html)\n\"\"\"\nfunction ekdelr(handle, segno, recno)\n ccall((:ekdelr_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt),\n handle, segno - 1, recno - 1)\n handleerror()\nend\n\n\"\"\"\n ekffld(handle, segno, rcptrs)\n\nComplete a fast write operation on a new E-kernel segment.\n\n### Arguments ###\n\n- `handle`: File handle\n- `segno`: Segment number\n- `rcptrs`: Record pointers\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekffld_c.html)\n\"\"\"\nfunction ekffld(handle, segno, rcptrs)\n ccall((:ekffld_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, Ref{SpiceInt}),\n handle, segno - 1, rcptrs)\n handleerror()\nend\n\n\"\"\"\n ekfind(query, lenout=256)\n\nFind E-kernel data that satisfy a set of constraints.\n\n### Arguments ###\n\n- `query`: Query specifying data to be found.\n- `lenout`: Declared length of output error message string (default: 256)\n\n### Output ###\n\nReturns the number of matching rows.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekfind_c.html)\n\"\"\"\nfunction ekfind(query, lenout=256)\n nmrows = Ref{SpiceInt}()\n error = Ref{SpiceBoolean}()\n errmsg = Array{SpiceChar}(undef, lenout)\n ccall((:ekfind_c, libcspice), Cvoid,\n (Cstring, SpiceInt, Ref{SpiceInt}, Ref{SpiceBoolean}, Ref{SpiceChar}),\n query, lenout, nmrows, error, errmsg)\n handleerror()\n if Bool(error[])\n throw(SpiceError(chararray_to_string(errmsg)))\n end\n Int(nmrows[])\nend\n\n\"\"\"\n ekgc(selidx, row, elment, lenout=256)\n\nReturn an element of an entry in a column of character type in a specified row.\n\n### Arguments ###\n\n- `selidx`: Index of parent column in SELECT clause\n- `row`: Row to fetch from\n- `elment`: Index of element, within column entry, to fetch\n- `lenout`: Maximum length of column element (default: 256)\n\n### Output ###\n\nReturns the character string element of column entry or `missing` if it was null\nor `nothing` if the column was not found.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgc_c.html)\n\"\"\"\nfunction ekgc(selidx, row, elment, lenout=256)\n cdata = Array{SpiceChar}(undef, lenout)\n null = Ref{SpiceBoolean}()\n found = Ref{SpiceBoolean}()\n ccall((:ekgc_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, SpiceInt, Ref{SpiceChar}, Ref{SpiceBoolean}, Ref{SpiceBoolean}),\n selidx - 1, row - 1, elment - 1, lenout, cdata, null, found)\n handleerror()\n Bool(found[]) || return nothing\n Bool(null[]) && return missing\n chararray_to_string(cdata)\nend\n\n\"\"\"\n ekgd(selidx, row, element)\n\nReturn an element of an entry in a column of double precision type in a specified row.\n\n### Arguments ###\n\n- `selidx`: Index of parent column in SELECT clause\n- `row`: Row to fetch from\n- `elment`: Index of element, within column entry, to fetch\n\n### Output ###\n\nReturns the double precision element of column entry or `missing` if it was null\nor `nothing` if the column was not found.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgd_c.html)\n\"\"\"\nfunction ekgd(selidx, row, elment)\n null = Ref{SpiceBoolean}()\n found = Ref{SpiceBoolean}()\n ddata = Ref{SpiceDouble}()\n ccall((:ekgd_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Ref{SpiceDouble}, Ref{SpiceBoolean}, Ref{SpiceBoolean}),\n selidx - 1, row - 1, elment - 1, ddata, null, found)\n handleerror()\n Bool(found[]) || return nothing\n Bool(null[]) && return missing\n ddata[]\nend\n\n\"\"\"\n ekgi(selidx, row, element)\n\nReturn an element of an entry in a column of integer type in a specified row.\n\n### Arguments ###\n\n- `selidx`: Index of parent column in SELECT clause\n- `row`: Row to fetch from\n- `elment`: Index of element, within column entry, to fetch\n\n### Output ###\n\nReturns the integer element of column entry or `missing` if it was null\nor `nothing` if the column was not found.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgi_c.html)\n\"\"\"\nfunction ekgi(selidx, row, elment)\n null = Ref{SpiceBoolean}()\n found = Ref{SpiceBoolean}()\n idata = Ref{SpiceInt}()\n ccall((:ekgi_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Ref{SpiceInt}, Ref{SpiceBoolean}, Ref{SpiceBoolean}),\n selidx - 1, row - 1, elment - 1, idata, null, found)\n handleerror()\n Bool(found[]) || return nothing\n Bool(null[]) && return missing\n Int(idata[])\nend\n\n\"\"\"\n ekinsr(handle, segno, recno)\n\nAdd a new, empty record to a specified E-kernel segment at a specified index.\n\n### Arguments ###\n\n- `handle`: File handle\n- `segno`: Segment number\n- `recno`: Record number\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekinsr_c.html)\n\"\"\"\nfunction ekinsr(handle, segno, recno)\n ccall((:ekinsr_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt),\n handle, segno - 1, recno - 1)\n handleerror()\nend\n\n\"\"\"\n ekifld(handle, tabnam, nrows, cnames, decls)\n\nInitialize a new E-kernel segment to allow fast writing.\n\n### Arguments ###\n\n- `handle`: File handle\n- `tabnam`: Table name\n- `nrows`: Number of rows in the segment\n- `cnames`: Names of columns\n- `decls`: Declarations of columns\n\n### Output ###\n\n- `segno`: Segment number\n- `rcptrs`: Array of record pointers\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekifld_c.html)\n\"\"\"\nfunction ekifld(handle, tabnam, nrows, cnames, decls)\n cnames_, ncols, cnmlen = chararray(cnames)\n @checkdims ncols decls\n decls_, _, declen = chararray(decls)\n segno = Ref{SpiceInt}()\n rcptrs = Array{SpiceInt}(undef, nrows)\n ccall((:ekifld_c, libcspice), Cvoid,\n (SpiceInt, Cstring, SpiceInt, SpiceInt, SpiceInt, Ref{SpiceChar}, SpiceInt,\n Ref{SpiceChar}, Ref{SpiceInt}, Ref{SpiceInt}),\n handle, tabnam, ncols, nrows, cnmlen, cnames_, declen, decls_, segno, rcptrs)\n handleerror()\n segno[] + 1, rcptrs\nend\n\n\"\"\"\n eklef(fname)\n\nLoad an EK file, making it accessible to the EK readers.\n\n### Arguments ###\n\n- `fname`: Name of EK file to load\n\n### Output ###\n\nReturns the file handle of loaded EK file.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eklef_c.html)\n\"\"\"\nfunction eklef(fname)\n handle = Ref{SpiceInt}()\n ccall((:eklef_c, libcspice), Cvoid,\n (Cstring, Ref{SpiceInt}),\n fname, handle)\n handleerror()\n handle[]\nend\n\n\"\"\"\n eknelt(selidx, row)\n\nReturn the number of elements in a specified column entry in the current row.\n\n### Arguments ###\n\n- `selidx`: Index of parent column in SELECT clause\n- `row`: Row containing element\n\n### Output ###\n\nReturns the number of elements in entry in current row.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eknelt_c.html)\n\"\"\"\nfunction eknelt(selidx, row)\n res = ccall((:eknelt_c, libcspice), SpiceInt,\n (SpiceInt, SpiceInt),\n selidx - 1, row - 1)\n handleerror()\n Int(res)\nend\n\n\"\"\"\n eknseg(handle)\n\nReturn the number of segments in a specified EK.\n\n### Arguments ###\n\n- `handle`: EK file handle\n\n### Output ###\n\nReturns the number of segments in the specified E-kernel.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eknseg_c.html)\n\"\"\"\nfunction eknseg(handle)\n res = ccall((:eknseg_c, libcspice), SpiceInt, (SpiceInt,), handle)\n handleerror()\n Int(res)\nend\n\n\"\"\"\n ekntab()\n\nReturn the number of loaded EK tables.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html)\n\"\"\"\nfunction ekntab()\n n = Ref{SpiceInt}()\n ccall((:ekntab_c, libcspice), Cvoid, (Ref{SpiceInt},), n)\n Int(n[])\nend\n\n\"\"\"\n ekopn(fname, ifname, ncomch)\n\nOpen a new E-kernel file and prepare the file for writing.\n\n### Arguments ###\n\n- `fname`: Name of EK file\n- `ifname`: Internal file name\n- `ncomch`: The number of characters to reserve for comments\n\n### Output ###\n\nReturn the handle attached to the new EK file.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopn_c.html)\n\"\"\"\nfunction ekopn(fname, ifname, ncomch)\n handle = Ref{SpiceInt}()\n ccall((:ekopn_c, libcspice), Cvoid,\n (Cstring, Cstring, SpiceInt, Ref{SpiceInt}),\n fname, ifname, ncomch, handle)\n handleerror()\n handle[]\nend\n\n\"\"\"\n ekopr(fname)\n\nOpen an existing E-kernel file for reading.\n\n### Arguments ###\n\n- `fname`: Name of EK file\n\n### Output ###\n\nReturns the handle attached to the EK file.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html)\n\"\"\"\nfunction ekopr(fname)\n handle = Ref{SpiceInt}()\n ccall((:ekopr_c, libcspice), Cvoid,\n (Cstring, Ref{SpiceInt}),\n fname, handle)\n handleerror()\n handle[]\nend\n\n\"\"\"\n ekops()\n\nOpen a scratch (temporary) E-kernel file and prepare the file for writing.\n\n### Output ###\n\nReturns the handle attached to the EK file.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekops_c.html)\n\"\"\"\nfunction ekops()\n handle = Ref{SpiceInt}()\n ccall((:ekops_c, libcspice), Cvoid, (Ref{SpiceInt},), handle)\n handleerror()\n handle[]\nend\n\n\"\"\"\n ekopw(fname)\n\nOpen an existing E-kernel file for writing.\n\n### Arguments ###\n\n- `fname`: Name of EK file\n\n### Output ###\n\nReturns the handle attached to the EK file.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopw_c.html)\n\"\"\"\nfunction ekopw(fname)\n handle = Ref{SpiceInt}()\n ccall((:ekopw_c, libcspice), Cvoid,\n (Cstring, Ref{SpiceInt}),\n fname, handle)\n handleerror()\n handle[]\nend\n\n\"\"\"\n ekpsel(query, msglen=256, tablen=256, collen=256)\n\nParse the SELECT clause of an EK query, returning full particulars concerning each selected item.\n\n### Arguments ###\n\n- `query`: EK query\n- `msglen`: Available space in the output error message string (default: 256)\n- `tablen`: Length of strings in `tabs' output array (default: 256)\n- `collen`: Length of strings in `cols' output array (default: 256)\n\n### Output ###\n\n- `xbegs`: Begin positions of expressions in SELECT clause\n- `xends`: End positions of expressions in SELECT clause\n- `xtypes`: Data types of expressions\n- `xclass`: Classes of expressions\n- `tabs`: Names of tables qualifying SELECT columns\n- `cols`: Names of columns in SELECT clause of query\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekpsel_c.html)\n\"\"\"\nfunction ekpsel(query, msglen=256, tablen=256, collen=256)\n maxqsel = 100\n n = Ref{SpiceInt}()\n xbegs = Array{SpiceInt}(undef, maxqsel)\n xends = Array{SpiceInt}(undef, maxqsel)\n xtypes = Array{SpiceInt}(undef, maxqsel)\n xclass = Array{SpiceInt}(undef, maxqsel)\n tabs = Array{SpiceChar}(undef, tablen, maxqsel)\n cols = Array{SpiceChar}(undef, collen, maxqsel)\n error = Ref{SpiceBoolean}()\n errmsg = Array{SpiceChar}(undef, msglen)\n ccall((:ekpsel_c, libcspice), Cvoid,\n (Cstring, SpiceInt, SpiceInt, SpiceInt, Ref{SpiceInt}, Ref{SpiceInt}, Ref{SpiceInt},\n Ref{SpiceInt}, Ref{SpiceInt}, Ref{SpiceChar}, Ref{SpiceChar}, Ref{SpiceBoolean},\n Ref{SpiceChar}),\n query, msglen, tablen, collen, n, xbegs, xends, xtypes, xclass, tabs, cols, error, errmsg)\n handleerror()\n if Bool(error[])\n throw(SpiceError(chararray_to_string(errmsg)))\n end\n Int.(xbegs[1:n[]]), Int.(xends[1:n[]]), Int.(xtypes[1:n[]]), Int.(xclass[1:n[]]),\n chararray_to_string(tabs)[1:n[]], chararray_to_string(cols)[1:n[]]\nend\n\n\"\"\"\n ekrcec(handle, segno, recno, column, lenout=256, nelts=100)\n\nRead data from a character column in a specified EK record.\n\n### Arguments ###\n\n- `handle`: Handle attached to EK file\n- `segno`: Index of segment containing record\n- `recno`: Record from which data is to be read\n- `column`: Column name\n- `lenout`: Maximum length of output strings\n- `nelts`: Maximum number of elements to return (default: 100)\n\n### Output ###\n\nReturns the character values in column entry or `missing` if they are null.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrcec_c.html)\n\"\"\"\nfunction ekrcec(handle, segno, recno, column, lenout=256, nelts=100)\n nvals = Ref{SpiceInt}()\n cvals = Array{SpiceChar}(undef, lenout, nelts)\n isnull = Ref{SpiceBoolean}()\n ccall((:ekrcec_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring, SpiceInt,\n Ref{SpiceInt}, Ref{SpiceChar}, Ref{SpiceBoolean}),\n handle, segno - 1, recno - 1, column, lenout, nvals, cvals, isnull)\n handleerror()\n Bool(isnull[]) && return missing\n strip.(chararray_to_string(cvals)[1:nvals[]])\nend\n\n\"\"\"\n ekrced(handle, segno, recno, column, nelts=100)\n\nRead data from a double precision column in a specified EK record.\n\n### Arguments ###\n\n- `handle`: Handle attached to EK file\n- `segno`: Index of segment containing record\n- `recno`: Record from which data is to be read\n- `column`: Column name\n- `nelts`: Maximum number of elements to return (default: 100)\n\n### Output ###\n\nReturns the values in column entry.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrced_c.html)\n\"\"\"\nfunction ekrced(handle, segno, recno, column, nelts=100)\n nvals = Ref{SpiceInt}()\n dvals = Array{SpiceDouble}(undef, nelts)\n isnull = Ref{SpiceBoolean}()\n ccall((:ekrced_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring,\n Ref{SpiceInt}, Ref{SpiceDouble}, Ref{SpiceBoolean}),\n handle, segno - 1, recno - 1, column, nvals, dvals, isnull)\n handleerror()\n Bool(isnull[]) && return missing\n dvals[1:nvals[]]\nend\n\n\"\"\"\n ekrcei(handle, segno, recno, column, nelts=100)\n\nRead data from an integer column in a specified EK record.\n\n### Arguments ###\n\n- `handle`: Handle attached to EK file\n- `segno`: Index of segment containing record\n- `recno`: Record from which data is to be read\n- `column`: Column name\n- `nelts`: Maximum number of elements to return (default: 100)\n\n### Output ###\n\nReturns the values in column entry.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrcei_c.html)\n\"\"\"\nfunction ekrcei(handle, segno, recno, column, nelts=100)\n nvals = Ref{SpiceInt}()\n ivals = Array{SpiceInt}(undef, nelts)\n isnull = Ref{SpiceBoolean}()\n ccall((:ekrcei_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring,\n Ref{SpiceInt}, Ref{SpiceInt}, Ref{SpiceBoolean}),\n handle, segno - 1, recno - 1, column, nvals, ivals, isnull)\n handleerror()\n Bool(isnull[]) && return missing\n Int.(ivals[1:nvals[]])\nend\n\n\"\"\"\n ekssum(handle, segno)\n\nReturn summary information for a specified segment in a specified EK.\n\n### Arguments ###\n\n- `handle`: Handle of EK\n- `segno`: Number of segment to be summarized\n\n### Output ###\n\nReturns the EK segment summary.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html)\n\"\"\"\nfunction ekssum(handle, segno)\n sum = Ref{EKSegSum}()\n ccall((:ekssum_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, Ref{EKSegSum}),\n handle, segno - 1, sum)\n handleerror()\n sum[]\nend\n\n\"\"\"\n ektnam(n, lenout=256)\n\nReturn the name of a specified, loaded table.\n\n### Arguments ###\n\n- `n`: Index of table\n- `lenout`: Maximum table name length (default: 256)\n\n### Output ###\n\nReturns the name of table.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ektnam_c.html)\n\"\"\"\nfunction ektnam(n, lenout=256)\n table = Array{SpiceChar}(undef, lenout)\n ccall((:ektnam_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, Ref{SpiceChar}),\n n - 1, lenout, table)\n handleerror()\n chararray_to_string(table)\nend\n\n\"\"\"\n ekucec(handle, segno, recno, column, cvals, isnull)\n\nUpdate a character column entry in a specified EK record.\n\n### Arguments ###\n\n- `handle`: EK file handle\n- `segno`: Index of segment containing record\n- `recno`: Record to which data is to be updated\n- `column`: Column name\n- `cvals`: Character values comprising new column entry\n- `isnull`: Flag indicating whether column entry is null\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekucec_c.html)\n\"\"\"\nfunction ekucec(handle, segno, recno, column, cvals, isnull)\n cvals_, nvals, vallen = chararray(cvals)\n ccall((:ekucec_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring, SpiceInt, SpiceInt,\n Ref{SpiceChar}, SpiceBoolean),\n handle, segno - 1, recno - 1, column, nvals, vallen, cvals_, isnull)\n handleerror()\nend\n\n\"\"\"\n ekuced(handle, segno, recno, column, dvals, isnull)\n\nUpdate a double precision column entry in a specified EK record.\n\n### Arguments ###\n\n- `handle`: Handle attached to EK file\n- `segno`: Index of segment containing record\n- `recno`: Record in which entry is to be updated\n- `column`: Column name\n- `dvals`: Double precision values comprising new column entry\n- `isnull`: Flag indicating whether column entry is null\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekuced_c.html)\n\"\"\"\nfunction ekuced(handle, segno, recno, column, dvals, isnull)\n nvals = length(dvals)\n ccall((:ekuced_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring, SpiceInt,\n Ref{SpiceDouble}, SpiceBoolean),\n handle, segno - 1, recno - 1, column, nvals, dvals, isnull)\n handleerror()\nend\n\n\"\"\"\n ekucei(handle, segno, recno, column, dvals, isnull)\n\nUpdate an integer column entry in a specified EK record.\n\n### Arguments ###\n\n- `handle`: Handle attached to EK file\n- `segno`: Index of segment containing record\n- `recno`: Record in which entry is to be updated\n- `column`: Column name\n- `ivals`: Integer values comprising new column entry\n- `isnull`: Flag indicating whether column entry is null\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekucei_c.html)\n\"\"\"\nfunction ekucei(handle, segno, recno, column, ivals, isnull)\n nvals = length(ivals)\n ivals_ = SpiceInt.(ivals)\n ccall((:ekucei_c, libcspice), Cvoid,\n (SpiceInt, SpiceInt, SpiceInt, Cstring, SpiceInt,\n Ref{SpiceInt}, SpiceBoolean),\n handle, segno - 1, recno - 1, column, nvals, ivals_, isnull)\n handleerror()\nend\n\n\"\"\"\n ekuef(handle)\n\nUnload an EK file, making its contents inaccessible to the EK reader routines, and clearing space\nin order to allow other EK files to be loaded.\n\n### Arguments ###\n\n- `handle`: Handle of EK file\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekuef_c.html)\n\"\"\"\nfunction ekuef(handle)\n ccall((:ekuef_c, libcspice), Cvoid, (SpiceInt,), handle)\n handleerror()\nend\n\n\"\"\"\n\nConvert an ellipse to a center vector and two generating vectors.\nThe selected generating vectors are semi-axes of the ellipse.\n\n### Arguments ###\n\n- `ellipse`: An ellipse\n\n### Output ###\n\nReturns the center and semi-axes of ellipse.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/el2cgv_c.html)\n\"\"\"\nfunction el2cgv(ellipse)\n center = Array{SpiceDouble}(undef, 3)\n smajor = Array{SpiceDouble}(undef, 3)\n sminor = Array{SpiceDouble}(undef, 3)\n ccall((:el2cgv_c, libcspice), Cvoid,\n (Ref{Ellipse}, Ref{SpiceDouble}, Ref{SpiceDouble}, Ref{SpiceDouble}),\n ellipse, center, smajor, sminor)\n center, smajor, sminor\nend\n\n@deprecate elemc(item, cell) item in cell\n@deprecate elemd(item, cell) item in cell\n@deprecate elemi(item, cell) item in cell\n\n\"\"\"\n elem[c/d/i](item, cell)\n\n!!! warning \"Deprecated\"\n Use `item in cell` instead.\n\"\"\"\nelemc\nelemd\nelemi\n\n\"\"\"\n eqstr(a, b)\n\nDetermine whether two strings are equivalent.\n\n### Arguments ###\n\n- `a`, `b`: Arbitrary character strings\n\n### Output ###\n\nReturns `true` if `a` and `b` are equivalent.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html)\n\"\"\"\nfunction eqstr(a, b)\n res = ccall((:eqstr_c, libcspice), SpiceBoolean,\n (Cstring, Cstring), a, b)\n handleerror()\n Bool(res)\nend\n\n\"\"\"\n eqncpv(et, epoch, eqel, rapol, decpol)\n\nCompute the state (position and velocity of an object whose trajectory is described via equinoctial\nelements relative to some fixed plane (usually the equatorial plane of some planet).\n\n### Arguments ###\n\n- `et`: Epoch in seconds past J2000 to find state\n- `epoch`: Epoch of elements in seconds past J2000\n- `eqel`: Array of equinoctial elements\n- `rapol`: Right Ascension of the pole of the reference plane\n- `decpol`: Declination of the pole of the reference plane\n\n### Output ###\n\nReturns the state of the object described by `eqel`.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqncpv_c.html)\n\"\"\"\nfunction eqncpv(et, epoch, eqel, rapol, decpol)\n @checkdims 9 eqel\n state = Array{SpiceDouble}(undef, 6)\n ccall((:eqncpv_c, libcspice), Cvoid,\n (SpiceDouble, SpiceDouble, Ref{SpiceDouble}, SpiceDouble, SpiceDouble, Ref{SpiceDouble}),\n et, epoch, eqel, rapol, decpol, state)\n handleerror()\n state\nend\n\n\"\"\"\n esrchc(value, array)\n\nSearch for a given value within a character string array.\n\n### Arguments ###\n\n- `value`: Key value to be found in array\n- `array`: Character string array to search\n\n### Output ###\n\nReturns the index of the first equivalent array entry, or -1 if no equivalent element is found.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/esrchc_c.html)\n\"\"\"\nfunction esrchc(value, array)\n array_, ndim, lenvals = chararray(array)\n res = Int(ccall((:esrchc_c, libcspice), SpiceInt,\n (Cstring, SpiceInt, SpiceInt, Ref{SpiceChar}),\n value, ndim, lenvals, array_))\n handleerror()\n res == -1 ? res : res + 1\nend\n\n\"\"\"\n et2lst(et, body, lon, typ, timlen=128, ampmlen=128)\n\nGiven an ephemeris epoch, compute the local solar time for an object on the surface of a body at a\nspecified longitude.\n\n### Arguments ###\n\n- `et`: Epoch in seconds past J2000 epoch\n- `body`: ID-code of the body of interest\n- `lon`: Longitude of surface point (radians)\n- `typ`: Type of longitude \"PLANETOCENTRIC\", etc\n- `timlen`: Available room in output time string (default: 128)\n- `ampmlen`: Available room in output `ampm' string (default: 128)\n\n### Output ###\n\n- `hr`: Local hour on a \"24 hour\" clock\n- `mn`: Minutes past the hour\n- `sc`: Seconds past the minute\n- `time`: String giving local time on 24 hour clock\n- `ampm`: String giving time on A.M./ P.M. scale\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html)\n\"\"\"\nfunction et2lst(et, body, lon, typ, timlen=128, ampmlen=128)\n hr = Ref{SpiceInt}()\n mn = Ref{SpiceInt}()\n sc = Ref{SpiceInt}()\n time = Array{SpiceChar}(undef, timlen)\n ampm = Array{SpiceChar}(undef, ampmlen)\n ccall((:et2lst_c, libcspice), Cvoid,\n (SpiceDouble, SpiceInt, SpiceDouble, Cstring, SpiceInt, SpiceInt,\n Ref{SpiceInt}, Ref{SpiceInt}, Ref{SpiceInt}, Ref{SpiceChar}, Ref{SpiceChar}),\n et, body, lon, typ, timlen, ampmlen, hr, mn, sc, time, ampm)\n handleerror()\n Int(hr[]), Int(mn[]), Int(sc[]), chararray_to_string(time), chararray_to_string(ampm)\nend\n\n\"\"\"\n et2utc(et, format, prec)\n\nConvert an input time from ephemeris seconds past J2000\nto Calendar, Day-of-Year, or Julian Date format, UTC.\n\n### Arguments ###\n\n- `et`: Input epoch, given in ephemeris seconds past J2000\n- `format`: Format of output epoch. It may be any of the following:\n - `:C`: Calendar format, UTC\n - `:D`: Day-of-Year format, UTC\n - `:J`: Julian Date format, UTC\n - `:ISOC`: ISO Calendar format, UTC\n - `:ISOD`: ISO Day-of-Year format, UTC\n- `prec`: Digits of precision in fractional seconds or days\n\n### Output ###\n\nReturns an output time string equivalent to the input epoch, in the specified format.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2utc_c.html)\n\"\"\"\nfunction et2utc(et, format, prec)\n lenout = 32\n utcstr = Array{SpiceChar}(undef, lenout)\n ccall((:et2utc_c, libcspice), Cvoid,\n (SpiceDouble, Cstring, SpiceInt, SpiceInt, Ref{SpiceChar}),\n et, string(format), prec, lenout, utcstr)\n handleerror()\n chararray_to_string(utcstr)\nend\n\n\"\"\"\n etcal(et, lenout=128)\n\nConvert from an ephemeris epoch measured in seconds past the epoch of J2000 to\na calendar string format using a formal calendar free of leapseconds.\n\n### Arguments ###\n\n- `et`: Ephemeris time measured in seconds past J2000\n- `lenout`: Length of output string (default: 128)\n\n### Output ###\n\nReturns a standard calendar representation of `et`.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/etcal_c.html)\n\"\"\"\nfunction etcal(et, lenout=128)\n string = Array{SpiceChar}(undef, lenout)\n ccall((:etcal_c, libcspice), Cvoid, (SpiceDouble, SpiceInt, Ref{SpiceChar}),\n et, lenout, string)\n chararray_to_string(string)\nend\n\n\"\"\"\n eul2m(angle3, angle2, angle1, axis3, axis2, axis1)\n\nConstruct a rotation matrix from a set of Euler angles.\n\n### Arguments ###\n\n- `angle3`, `angle2`, `angle1`: Rotation angles about third, second, and first rotation axes (radians)\n- `axis3`, `axis2`, `axis1`: Axis numbers of third, second, and first rotation axes\n\n### Output ###\n\nA rotation matrix corresponding to the product of the 3 rotations.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eul2m_c.html)\n\"\"\"\nfunction eul2m(angle3, angle2, angle1, axis3, axis2, axis1)\n r = Matrix{SpiceDouble}(undef, 3, 3)\n ccall((:eul2m_c, libcspice), Cvoid,\n (SpiceDouble, SpiceDouble, SpiceDouble, SpiceInt, SpiceInt, SpiceInt, Ref{SpiceDouble}),\n angle3, angle2, angle1, axis3, axis2, axis1, r)\n handleerror()\n permutedims(r)\nend\n\n\"\"\"\n eul2xf(eulang, axisa, axisb, axisc)\n\nCompute a state transformation from an Euler angle factorization of a rotation and the derivatives\nof those Euler angles.\n\n### Arguments ###\n\n- `eulang`: An array of Euler angles and their derivatives\n- `axisa`: Axis A of the Euler angle factorization\n- `axisb`: Axis B of the Euler angle factorization\n- `axisc`: Axis C of the Euler angle factorization\n\n### Output ###\n\nReturns a state transformation matrix.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eul2xf_c.html)\n\"\"\"\nfunction eul2xf(eulang, axisa, axisb, axisc)\n @checkdims 6 eulang\n xform = Array{SpiceDouble}(undef, 6, 6)\n ccall((:eul2xf_c, libcspice), Cvoid,\n (Ref{SpiceDouble}, SpiceInt, SpiceInt, SpiceInt, Ref{SpiceDouble}),\n eulang, axisa, axisb, axisc, xform)\n handleerror()\n permutedims(xform)\nend\n\n\"\"\"\n expool(name)\n\nConfirm the existence of a kernel variable in the kernel pool.\n\n### Arguments ###\n\n- `name`: Name of the variable whose value is to be returned\n\n### Output ###\n\nReturns `true` when the variable is in the pool.\n\n### References ###\n\n- [NAIF Documentation](https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/expool_c.html)\n\"\"\"\nfunction expool(name)\n found = Ref{SpiceBoolean}()\n ccall((:expool_c, libcspice), Cvoid,\n (Cstring, Ref{SpiceBoolean}),\n name, found)\n handleerror()\n Bool(found[])\nend\n\n", "meta": {"hexsha": "2afce57851d340e2006c23c976009b776df49ec6", "size": 39957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/e.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SPICE.jl-5bab7191-041a-5c2e-a744-024b9c3a5062", "max_stars_repo_head_hexsha": "9ce25be3377e922642eb9d67241039ae293f0c44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2018-04-18T22:39:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T14:26:16.000Z", "max_issues_repo_path": "src/e.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SPICE.jl-5bab7191-041a-5c2e-a744-024b9c3a5062", "max_issues_repo_head_hexsha": "9ce25be3377e922642eb9d67241039ae293f0c44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-04-15T13:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T16:20:35.000Z", "max_forks_repo_path": "src/e.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SPICE.jl-5bab7191-041a-5c2e-a744-024b9c3a5062", "max_forks_repo_head_hexsha": "9ce25be3377e922642eb9d67241039ae293f0c44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-15T12:03:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T22:08:46.000Z", "avg_line_length": 27.0894915254, "max_line_length": 105, "alphanum_fraction": 0.67334885, "num_tokens": 11935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18715415471319582}} {"text": "function KolmogorovSmirnovTest()\n return KolmogorovSmirnovTest(())\nend\n\nfunction KolmogorovSmirnovTest(arg0::jlong)\n return KolmogorovSmirnovTest((jlong,), arg0)\nend\n\nfunction approximate_p(obj::KolmogorovSmirnovTest, arg0::jdouble, arg1::jint, arg2::jint)\n return jcall(obj, \"approximateP\", jdouble, (jdouble, jint, jint), arg0, arg1, arg2)\nend\n\nfunction bootstrap(obj::KolmogorovSmirnovTest, arg0::Vector{jdouble}, arg1::Vector{jdouble}, arg2::jint)\n return jcall(obj, \"bootstrap\", jdouble, (Vector{jdouble}, Vector{jdouble}, jint), arg0, arg1, arg2)\nend\n\nfunction bootstrap(obj::KolmogorovSmirnovTest, arg0::Vector{jdouble}, arg1::Vector{jdouble}, arg2::jint, arg3::jboolean)\n return jcall(obj, \"bootstrap\", jdouble, (Vector{jdouble}, Vector{jdouble}, jint, jboolean), arg0, arg1, arg2, arg3)\nend\n\nfunction cdf(obj::KolmogorovSmirnovTest, arg0::jdouble, arg1::jint)\n return jcall(obj, \"cdf\", jdouble, (jdouble, jint), arg0, arg1)\nend\n\nfunction cdf(obj::KolmogorovSmirnovTest, arg0::jdouble, arg1::jint, arg2::jboolean)\n return jcall(obj, \"cdf\", jdouble, (jdouble, jint, jboolean), arg0, arg1, arg2)\nend\n\nfunction cdf_exact(obj::KolmogorovSmirnovTest, arg0::jdouble, arg1::jint)\n return jcall(obj, \"cdfExact\", jdouble, (jdouble, jint), arg0, arg1)\nend\n\nfunction exact_p(obj::KolmogorovSmirnovTest, arg0::jdouble, arg1::jint, arg2::jint, arg3::jboolean)\n return jcall(obj, \"exactP\", jdouble, (jdouble, jint, jint, jboolean), arg0, arg1, arg2, arg3)\nend\n\nfunction kolmogorov_smirnov_statistic(obj::KolmogorovSmirnovTest, arg0::RealDistribution, arg1::Vector{jdouble})\n return jcall(obj, \"kolmogorovSmirnovStatistic\", jdouble, (RealDistribution, Vector{jdouble}), arg0, arg1)\nend\n\nfunction kolmogorov_smirnov_statistic(obj::KolmogorovSmirnovTest, arg0::Vector{jdouble}, arg1::Vector{jdouble})\n return jcall(obj, \"kolmogorovSmirnovStatistic\", jdouble, (Vector{jdouble}, Vector{jdouble}), arg0, arg1)\nend\n\nfunction kolmogorov_smirnov_test(obj::KolmogorovSmirnovTest, arg0::RealDistribution, arg1::Vector{jdouble})\n return jcall(obj, \"kolmogorovSmirnovTest\", jdouble, (RealDistribution, Vector{jdouble}), arg0, arg1)\nend\n\nfunction kolmogorov_smirnov_test(obj::KolmogorovSmirnovTest, arg0::RealDistribution, arg1::Vector{jdouble}, arg2::jboolean)\n return jcall(obj, \"kolmogorovSmirnovTest\", jdouble, (RealDistribution, Vector{jdouble}, jboolean), arg0, arg1, arg2)\nend\n\nfunction kolmogorov_smirnov_test(obj::KolmogorovSmirnovTest, arg0::RealDistribution, arg1::Vector{jdouble}, arg2::jdouble)\n return jcall(obj, \"kolmogorovSmirnovTest\", jboolean, (RealDistribution, Vector{jdouble}, jdouble), arg0, arg1, arg2)\nend\n\nfunction kolmogorov_smirnov_test(obj::KolmogorovSmirnovTest, arg0::Vector{jdouble}, arg1::Vector{jdouble})\n return jcall(obj, \"kolmogorovSmirnovTest\", jdouble, (Vector{jdouble}, Vector{jdouble}), arg0, arg1)\nend\n\nfunction kolmogorov_smirnov_test(obj::KolmogorovSmirnovTest, arg0::Vector{jdouble}, arg1::Vector{jdouble}, arg2::jboolean)\n return jcall(obj, \"kolmogorovSmirnovTest\", jdouble, (Vector{jdouble}, Vector{jdouble}, jboolean), arg0, arg1, arg2)\nend\n\nfunction ks_sum(obj::KolmogorovSmirnovTest, arg0::jdouble, arg1::jdouble, arg2::jint)\n return jcall(obj, \"ksSum\", jdouble, (jdouble, jdouble, jint), arg0, arg1, arg2)\nend\n\nfunction pelz_good(obj::KolmogorovSmirnovTest, arg0::jdouble, arg1::jint)\n return jcall(obj, \"pelzGood\", jdouble, (jdouble, jint), arg0, arg1)\nend\n\n", "meta": {"hexsha": "dd619e7b7f33596fe94259ad21774c896638c3e6", "size": 3443, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gen/HipparchusWrapper/StatWrapper/InferenceWrapper/kolmogorov_smirnov_test.jl", "max_stars_repo_name": "JuliaAstrodynamics/Orekit.jl", "max_stars_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-07T12:26:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T16:02:35.000Z", "max_issues_repo_path": "gen/HipparchusWrapper/StatWrapper/InferenceWrapper/kolmogorov_smirnov_test.jl", "max_issues_repo_name": "JuliaSpace/Orekit.jl", "max_issues_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-05T10:16:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T05:17:19.000Z", "max_forks_repo_path": "gen/HipparchusWrapper/StatWrapper/InferenceWrapper/kolmogorov_smirnov_test.jl", "max_forks_repo_name": "JuliaSpace/Orekit.jl", "max_forks_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1643835616, "max_line_length": 123, "alphanum_fraction": 0.7615451641, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.18647514443142074}} {"text": "const BaseRules = OrderedRuleSet(\n \"Base\",\n (\"LowCounts\", r -> get(r, :COUNTS, 2001.0) < 2000.0),\n (\n \"Maraging\",\n r -> (r.FIRSTELM == n\"Fe\") &&\n (r.NI > 5) && (r.CO > 2) && sum(r, :FE, :NI, :CO, :MO) > 80.0,\n ),\n (\"Quartz-like\", r -> r.SI > 80),\n (\n \"Biotite\",\n r -> (r.K > 5) &&\n (r.MG + r.FE > 20) &&\n (r.AL > 10) &&\n (r.SI > 10) && (r.K + r.MG + r.FE + r.AL + r.SI > 80) && (r.O > 5),\n ),\n (\n \"Plagioclaise\",\n r -> (r.CA + r.NA > 20) &&\n (r.AL > 10) && (r.SI > 10) && (r.NA + r.CA + r.AL + r.SI > 80) && (r.O > 5),\n ),\n (\n \"Othoclaise\",\n r -> (r.K > 5) &&\n (r.AL > 20) && (r.SI > 20) && (r.O > 10) && (r.K + r.AL + r.SI > 80),\n ),\n (\"Dolomite\", r -> (r.CA > 40) && (r.MG > 10) && (r.CA + r.MG > 70)),\n (\"Olivine\", r -> (r.MG + r.FE > 40) && (r.SI > 20) && (r.MG + r.FE + r.SI > 80)),\n (\n \"Feldspar\",\n r -> (r.K + r.NA + r.CA > 20) &&\n (r.AL > 10) && (r.SI > 20) && (r.K + r.NA + r.CA + r.AL + r.SI > 80),\n ),\n (\"Willemite\", r -> (r.ZN > 20) && (r.SI > 20) && (r.ZN + r.SI > 80)),\n (\n \"Garnet\",\n r -> (r.MG + r.FE + r.MN + r.CA > 10) &&\n (r.AL > 5) && (r.SI > 10) && (r.MG + r.FE + r.MN + r.CA + r.AL + r.SI > 80),\n ),\n (\n \"Al-Cu alloy (2XXX)\",\n r -> (r.AL > 60) && (r.SECONDELM == n\"Cu\") && (r.CU > 3) && (r.AL + r.CU > 90),\n ),\n (\n \"Al-Mn alloy (3XXX)\",\n r -> (r.AL > 60) && (r.SECONDELM == n\"Mn\") && (r.MN > 3) && (r.AL + r.MN > 90),\n ),\n (\n \"Al-Si alloy (4XXX)\",\n r -> (r.AL > 80) && (r.SECONDELM == n\"Si\") && (r.SI > 1) && (r.AL + r.SI > 90),\n ),\n (\n \"Al-Mg alloy (5XXX)\",\n r -> (r.FIRSTELM == n\"Al\") && (r.SECONDELM == n\"Mg\") && (r.MG > 5) && (r.AL + r.MG > 80),\n ),\n (\n \"Al-Si-Mg (6XXX)\",\n r -> (r.AL > 90) &&\n (r.SI > 0) && (r.MG > 0) && (r.AL + r.SI + r.MG + r.MN + r.CU + r.FE > 98),\n ),\n (\n \"Al-Zn alloy (7XXX)\",\n r -> (r.AL > 80) && (r.SECONDELM == n\"Zn\") && (r.ZN > 2) && (r.AL + r.ZN > 90),\n ),\n (\"Al-Fe alloy\", r -> (r.AL > 80) && (r.SECONDELM == n\"Fe\") && (r.FE > 2) && (r.AL + r.FE > 90)),\n (\"Aluminosilicate\", r -> (r.AL > 30) && (r.SI > 10) && (r.AL + r.SI > 80)),\n (\"Zircon\", r -> (r.ZR > 20) && (r.ZR + r.SI > 80)),\n (\n \"Elgiloy\",\n r -> (r.CO > 20) &&\n (r.CR > 10) &&\n (r.NI > 5) &&\n (r.FE > 5) &&\n ((r.MO > 2) || (r.S > 2)) &&\n (r.CO + r.CR + r.NI + r.FE + r.MO + r.MN + r.S > 80),\n ),\n (\"Aluminum\", r -> r.AL > 80),\n (\"Fe-Al alloy\", r -> (r.AL > 20) && (r.FE > 20) && (r.AL + r.FE > 80)),\n (\"Calcium silicate\", r -> (r.CA > 40) && (r.SI > 10) && (r.CA + r.SI > 80)),\n (\"Fe-Cr stainless\", r -> (r.FE > 50) && (r.CR > 5) && (r.NI < 3) && (r.FE + r.CR > 90)),\n (\n \"Fe-Cr-Ni Stainless\",\n r -> (r.FIRSTELM == n\"Fe\") && (r.CR > 5) && (r.NI > 5) && (r.FE + r.CR + r.NI > 80),\n ),\n (\"Fe-Ni stainless\", r -> (r.FE > 50) && (r.NI > 10) && (r.FE + r.NI > 90)),\n (\"Iron oxide\", r -> (r.FE > 80) && (r.O > 10)),\n (\"Iron\", r -> r.FE > 80),\n (\"Calcite\", r -> (r.CA > 80) && (r.O > 5)),\n (\"Zinc\", r -> r.ZN > 80),\n (\"Silicate\", r -> r.FIRSTELM == n\"Si\"),\n (\n \"Anglesite\",\n r -> (r.FIRSTELM == n\"Pb\") && (r.SECONDELM == n\"S\") && (r.PB + r.S > 80) && (r.O > 5),\n ),\n (\"Hashemite\", r -> (r.BA > 20) && (r.CR > 20) && (r.BA + r.CR > 80) && (r.O > 5)),\n (\"Barite\", r -> (r.BA > 40) && (r.S > 10) && (r.BA + r.S > 80) && (r.O > 5)),\n (\"Gypsum\", r -> (r.CA > 20) && (r.S > 20) && (r.CA + r.S > 80) && (r.O > 5)),\n (\"Lead\", r -> (r.PB > 60) && (r.PB + r.S > 80)),\n (\"Salt\", r -> (r.K + r.NA > 20) && (r.CL > 20) && (r.K + r.NA + r.CL > 80)),\n (\"Bismuth\", r -> (r.BI > 80)),\n (\"Brass\", r -> (r.CU > 20) && (r.ZN > 20) && (r.CU + r.ZN > 80)),\n (\"Bronze\", r -> (r.CU > 20) && (r.SN > 20) && (r.CU + r.SN > 80)),\n (\"Cupronickel\", r -> (r.CU > 30) && (r.NI > 10) && (r.CU + r.NI > 80)),\n (\"Sodium sulfide\", r -> (r.NA > 20) && (r.S > 10) && (r.NA + r.S > 80)),\n (\"Wurtzite (ZnS)\", r -> (r.ZN > 20) && (r.S > 10) && (r.ZN + r.S > 80)),\n (\"Pyrite (FeS2)\", r -> (r.FE > 20) && (r.S > 20) && (r.FE + r.S > 80)),\n (\"Silver sulfide\", r -> (r.AG > 20) && (r.S > 10) && (r.AG + r.S > 80)),\n (\n \"Sn62 solder\",\n r -> (r.SN > 30) && (r.PB > 10) && (r.AG > 1) && (r.SN + r.PB + r.AG > 80),\n ),\n (\n \"SACZ solder\",\n r -> (r.SN + r.AG + r.CU + r.ZN > 80) &&\n (r.SN > 10) && (r.CU > 10) && (r.AG > 10) && (r.ZN > 2),\n ),\n (\"Lead solder\", r -> (r.PB > 20) && (r.SN > 20) && (r.PB + r.SN > 80)),\n (\n \"SAC solder\",\n r -> (r.SN + r.AG + r.CU > 80) && (r.SN > 10) && (r.CU > 10) && (r.AG > 10),\n ),\n (\"Titanium\", r -> (r.TI > 80)),\n (\"Calcium phosphate\", r -> (r.CA > 40) && (r.P > 10) && (r.CA + r.P > 80)),\n (\"Calcium fluoride\", r -> (r.CA > 40) && (r.F > 10) && (r.CA + r.F > 80)),\n (\"Iron-bearing\", r -> (r.FE > 50)),\n (\"Ca-bearing\", r -> r.CA > 50),\n (\"Other Silicate\", r -> (r.SI > 20) && (r.AL + r.FE + r.CA + r.SI > 80)),\n (\"Gold-Silver alloy\", r -> (r.FIRSTELM == n\"Au\") && (r.SECONDELM == n\"Ag\") && (r.AU + r.AG > 80)),\n (\"Gold - other\", r -> r.AU > 80),\n (\"Tin\", r -> r.SN > 80),\n (\"Celestine\", r -> (r.SR > 40) && (r.S > 10) && (r.SR + r.S > 80) && (r.O > 5)),\n (\"Barite-Celestine\", r -> (r.BA + r.SR > 40) && (r.BA + r.SR + r.S > 80) && (r.O > 5)),\n (\"Cu-rich\", r -> r.CU > 80),\n (\"Cr-bearing\", r -> r.CR > 50),\n (\"Silver sulfide\", r -> (r.AG > 40) && (r.S > 10) && (r.AG + r.S > 80)),\n (\"Silver\", r -> r.AG > 80),\n (\"MoS2\", r -> r.MO > 40 && r.S > 30 && (r.MO + r.S > 90)),\n (\"Monazite\", r -> sum(r, :LA, :CE, :ND, :TH, :Y) > 30 && (r.P > 10) && sum(r, :LA, :CE, :ND, :TH, :Y, :P, :SI) > 80 ),\n (\"Lanthanide\", r -> sum(r, :LA, :CE, :ND, :Y) > 60),\n (\"Silver chloride\", r -> (r.AG > 40) && (r.CL > 10)),\n (\"Magnesium oxide\", r -> (r.MG > 80) && (r.O > 10)),\n (\"Nickel\", r -> r.NI > 80),\n (\"Ca-Fe silicate\", r -> (r.CA > 20) && (r.FE > 20) && (r.SI > 5)),\n (\"Ca-Ti silicate\", r -> (r.CA > 20) && (r.TI > 20) && (r.SI > 10)),\n (\"Al-Zr-Cl\", r -> (r.AL > 20) && (r.ZR > 20) && (r.CL > 5)),\n (\"Chlorine-rich\", r -> r.CL > 80),\n (\"Au-Cu alloy\", r -> (r.AU > 40) && (r.CU > 10) && (r.AU + r.CU + r.NI > 80)),\n (\"Uranium-bearing\", r -> r.U > 20),\n (\"Thorium-bearing\", r -> r.TH > 20),\n (\"Platinum\", r -> r.PT > 80)\n)", "meta": {"hexsha": "38e3b8cb3d97ab674902c2a327333c971a56fb7c", "size": 6683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/baseRules.jl", "max_stars_repo_name": "NicholasWMRitchie/NeXLParticle", "max_stars_repo_head_hexsha": "9d284df0a12b05b736b05134471673306b224e99", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/baseRules.jl", "max_issues_repo_name": "NicholasWMRitchie/NeXLParticle", "max_issues_repo_head_hexsha": "9d284df0a12b05b736b05134471673306b224e99", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/baseRules.jl", "max_forks_repo_name": "NicholasWMRitchie/NeXLParticle", "max_forks_repo_head_hexsha": "9d284df0a12b05b736b05134471673306b224e99", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2582781457, "max_line_length": 122, "alphanum_fraction": 0.3484961843, "num_tokens": 3044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.18621982605630719}} {"text": "function JComplex(arg0::jdouble)\n return JComplex((jdouble,), arg0)\nend\n\nfunction JComplex(arg0::jdouble, arg1::jdouble)\n return JComplex((jdouble, jdouble), arg0, arg1)\nend\n\nfunction abs(obj::JComplex)\n return jcall(obj, \"abs\", jdouble, ())\nend\n\nfunction acos(obj::JComplex)\n return jcall(obj, \"acos\", JComplex, ())\nend\n\nfunction acosh(obj::JComplex)\n return jcall(obj, \"acosh\", JComplex, ())\nend\n\nfunction add(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"add\", JComplex, (JComplex,), arg0)\nend\n\nfunction add(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"add\", JComplex, (jdouble,), arg0)\nend\n\nfunction asin(obj::JComplex)\n return jcall(obj, \"asin\", JComplex, ())\nend\n\nfunction asinh(obj::JComplex)\n return jcall(obj, \"asinh\", JComplex, ())\nend\n\nfunction atan(obj::JComplex)\n return jcall(obj, \"atan\", JComplex, ())\nend\n\nfunction atan2(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"atan2\", JComplex, (JComplex,), arg0)\nend\n\nfunction atanh(obj::JComplex)\n return jcall(obj, \"atanh\", JComplex, ())\nend\n\nfunction cbrt(obj::JComplex)\n return jcall(obj, \"cbrt\", JComplex, ())\nend\n\nfunction ceil(obj::JComplex)\n return jcall(obj, \"ceil\", JComplex, ())\nend\n\nfunction conjugate(obj::JComplex)\n return jcall(obj, \"conjugate\", JComplex, ())\nend\n\nfunction copy_sign(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"copySign\", JComplex, (JComplex,), arg0)\nend\n\nfunction copy_sign(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"copySign\", JComplex, (jdouble,), arg0)\nend\n\nfunction cos(obj::JComplex)\n return jcall(obj, \"cos\", JComplex, ())\nend\n\nfunction cosh(obj::JComplex)\n return jcall(obj, \"cosh\", JComplex, ())\nend\n\nfunction divide(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"divide\", JComplex, (JComplex,), arg0)\nend\n\nfunction divide(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"divide\", JComplex, (jdouble,), arg0)\nend\n\nfunction equals(::Type{JComplex}, arg0::JComplex, arg1::JComplex)\n return jcall(JComplex, \"equals\", jboolean, (JComplex, JComplex), arg0, arg1)\nend\n\nfunction equals(::Type{JComplex}, arg0::JComplex, arg1::JComplex, arg2::jdouble)\n return jcall(JComplex, \"equals\", jboolean, (JComplex, JComplex, jdouble), arg0, arg1, arg2)\nend\n\nfunction equals(::Type{JComplex}, arg0::JComplex, arg1::JComplex, arg2::jint)\n return jcall(JComplex, \"equals\", jboolean, (JComplex, JComplex, jint), arg0, arg1, arg2)\nend\n\nfunction equals(obj::JComplex, arg0::Object)\n return jcall(obj, \"equals\", jboolean, (Object,), arg0)\nend\n\nfunction equals_with_relative_tolerance(::Type{JComplex}, arg0::JComplex, arg1::JComplex, arg2::jdouble)\n return jcall(JComplex, \"equalsWithRelativeTolerance\", jboolean, (JComplex, JComplex, jdouble), arg0, arg1, arg2)\nend\n\nfunction exp(obj::JComplex)\n return jcall(obj, \"exp\", JComplex, ())\nend\n\nfunction expm1(obj::JComplex)\n return jcall(obj, \"expm1\", JComplex, ())\nend\n\nfunction floor(obj::JComplex)\n return jcall(obj, \"floor\", JComplex, ())\nend\n\nfunction get_argument(obj::JComplex)\n return jcall(obj, \"getArgument\", jdouble, ())\nend\n\nfunction get_exponent(obj::CalculusFieldElement)\n return jcall(obj, \"getExponent\", jint, ())\nend\n\nfunction get_field(obj::JComplex)\n return jcall(obj, \"getField\", ComplexField, ())\nend\n\nfunction get_imaginary(obj::JComplex)\n return jcall(obj, \"getImaginary\", jdouble, ())\nend\n\nfunction get_real(obj::JComplex)\n return jcall(obj, \"getReal\", jdouble, ())\nend\n\nfunction hash_code(obj::JComplex)\n return jcall(obj, \"hashCode\", jint, ())\nend\n\nfunction hypot(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"hypot\", JComplex, (JComplex,), arg0)\nend\n\nfunction is_infinite(obj::JComplex)\n return jcall(obj, \"isInfinite\", jboolean, ())\nend\n\nfunction is_mathematical_integer(obj::JComplex)\n return jcall(obj, \"isMathematicalInteger\", jboolean, ())\nend\n\nfunction is_na_n(obj::JComplex)\n return jcall(obj, \"isNaN\", jboolean, ())\nend\n\nfunction is_real(obj::JComplex)\n return jcall(obj, \"isReal\", jboolean, ())\nend\n\nfunction linear_combination(obj::JComplex, arg0::JComplex, arg1::JComplex, arg2::JComplex, arg3::JComplex)\n return jcall(obj, \"linearCombination\", JComplex, (JComplex, JComplex, JComplex, JComplex), arg0, arg1, arg2, arg3)\nend\n\nfunction linear_combination(obj::JComplex, arg0::JComplex, arg1::JComplex, arg2::JComplex, arg3::JComplex, arg4::JComplex, arg5::JComplex)\n return jcall(obj, \"linearCombination\", JComplex, (JComplex, JComplex, JComplex, JComplex, JComplex, JComplex), arg0, arg1, arg2, arg3, arg4, arg5)\nend\n\nfunction linear_combination(obj::JComplex, arg0::JComplex, arg1::JComplex, arg2::JComplex, arg3::JComplex, arg4::JComplex, arg5::JComplex, arg6::JComplex, arg7::JComplex)\n return jcall(obj, \"linearCombination\", JComplex, (JComplex, JComplex, JComplex, JComplex, JComplex, JComplex, JComplex, JComplex), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\nend\n\nfunction linear_combination(obj::JComplex, arg0::Vector{JComplex}, arg1::Vector{JComplex})\n return jcall(obj, \"linearCombination\", JComplex, (Vector{JComplex}, Vector{JComplex}), arg0, arg1)\nend\n\nfunction linear_combination(obj::JComplex, arg0::Vector{jdouble}, arg1::Vector{JComplex})\n return jcall(obj, \"linearCombination\", JComplex, (Vector{jdouble}, Vector{JComplex}), arg0, arg1)\nend\n\nfunction linear_combination(obj::JComplex, arg0::jdouble, arg1::JComplex, arg2::jdouble, arg3::JComplex)\n return jcall(obj, \"linearCombination\", JComplex, (jdouble, JComplex, jdouble, JComplex), arg0, arg1, arg2, arg3)\nend\n\nfunction linear_combination(obj::JComplex, arg0::jdouble, arg1::JComplex, arg2::jdouble, arg3::JComplex, arg4::jdouble, arg5::JComplex)\n return jcall(obj, \"linearCombination\", JComplex, (jdouble, JComplex, jdouble, JComplex, jdouble, JComplex), arg0, arg1, arg2, arg3, arg4, arg5)\nend\n\nfunction linear_combination(obj::JComplex, arg0::jdouble, arg1::JComplex, arg2::jdouble, arg3::JComplex, arg4::jdouble, arg5::JComplex, arg6::jdouble, arg7::JComplex)\n return jcall(obj, \"linearCombination\", JComplex, (jdouble, JComplex, jdouble, JComplex, jdouble, JComplex, jdouble, JComplex), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\nend\n\nfunction log(obj::JComplex)\n return jcall(obj, \"log\", JComplex, ())\nend\n\nfunction log10(obj::JComplex)\n return jcall(obj, \"log10\", JComplex, ())\nend\n\nfunction log1p(obj::JComplex)\n return jcall(obj, \"log1p\", JComplex, ())\nend\n\nfunction multiply(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"multiply\", JComplex, (JComplex,), arg0)\nend\n\nfunction multiply(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"multiply\", JComplex, (jdouble,), arg0)\nend\n\nfunction multiply(obj::JComplex, arg0::jint)\n return jcall(obj, \"multiply\", JComplex, (jint,), arg0)\nend\n\nfunction negate(obj::JComplex)\n return jcall(obj, \"negate\", JComplex, ())\nend\n\nfunction new_instance(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"newInstance\", JComplex, (jdouble,), arg0)\nend\n\nfunction norm(obj::JComplex)\n return jcall(obj, \"norm\", JComplex, ())\nend\n\nfunction nth_root(obj::JComplex, arg0::jint)\n return jcall(obj, \"nthRoot\", List, (jint,), arg0)\nend\n\nfunction pow(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"pow\", JComplex, (JComplex,), arg0)\nend\n\nfunction pow(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"pow\", JComplex, (jdouble,), arg0)\nend\n\nfunction pow(obj::JComplex, arg0::jint)\n return jcall(obj, \"pow\", JComplex, (jint,), arg0)\nend\n\nfunction reciprocal(obj::JComplex)\n return jcall(obj, \"reciprocal\", JComplex, ())\nend\n\nfunction remainder(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"remainder\", JComplex, (JComplex,), arg0)\nend\n\nfunction remainder(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"remainder\", JComplex, (jdouble,), arg0)\nend\n\nfunction rint(obj::JComplex)\n return jcall(obj, \"rint\", JComplex, ())\nend\n\nfunction root_n(obj::JComplex, arg0::jint)\n return jcall(obj, \"rootN\", JComplex, (jint,), arg0)\nend\n\nfunction scalb(obj::JComplex, arg0::jint)\n return jcall(obj, \"scalb\", JComplex, (jint,), arg0)\nend\n\nfunction signum(obj::JComplex)\n return jcall(obj, \"signum\", JComplex, ())\nend\n\nfunction sin(obj::JComplex)\n return jcall(obj, \"sin\", JComplex, ())\nend\n\nfunction sin_cos(obj::CalculusFieldElement)\n return jcall(obj, \"sinCos\", FieldSinCos, ())\nend\n\nfunction sinh(obj::JComplex)\n return jcall(obj, \"sinh\", JComplex, ())\nend\n\nfunction sqrt(obj::JComplex)\n return jcall(obj, \"sqrt\", JComplex, ())\nend\n\nfunction sqrt1z(obj::JComplex)\n return jcall(obj, \"sqrt1z\", JComplex, ())\nend\n\nfunction subtract(obj::JComplex, arg0::JComplex)\n return jcall(obj, \"subtract\", JComplex, (JComplex,), arg0)\nend\n\nfunction subtract(obj::JComplex, arg0::jdouble)\n return jcall(obj, \"subtract\", JComplex, (jdouble,), arg0)\nend\n\nfunction tan(obj::JComplex)\n return jcall(obj, \"tan\", JComplex, ())\nend\n\nfunction tanh(obj::JComplex)\n return jcall(obj, \"tanh\", JComplex, ())\nend\n\nfunction to_degrees(obj::CalculusFieldElement)\n return jcall(obj, \"toDegrees\", Object, ())\nend\n\nfunction to_radians(obj::CalculusFieldElement)\n return jcall(obj, \"toRadians\", Object, ())\nend\n\nfunction to_string(obj::JComplex)\n return jcall(obj, \"toString\", JString, ())\nend\n\nfunction value_of(::Type{JComplex}, arg0::jdouble)\n return jcall(JComplex, \"valueOf\", JComplex, (jdouble,), arg0)\nend\n\nfunction value_of(::Type{JComplex}, arg0::jdouble, arg1::jdouble)\n return jcall(JComplex, \"valueOf\", JComplex, (jdouble, jdouble), arg0, arg1)\nend\n\n", "meta": {"hexsha": "9f1894f9294ec5c370777779b855ab9a5ffc94db", "size": 9487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gen/HipparchusWrapper/ComplexWrapper/j_complex.jl", "max_stars_repo_name": "JuliaAstrodynamics/Orekit.jl", "max_stars_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-07T12:26:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T16:02:35.000Z", "max_issues_repo_path": "gen/HipparchusWrapper/ComplexWrapper/j_complex.jl", "max_issues_repo_name": "JuliaSpace/Orekit.jl", "max_issues_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-05T10:16:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T05:17:19.000Z", "max_forks_repo_path": "gen/HipparchusWrapper/ComplexWrapper/j_complex.jl", "max_forks_repo_name": "JuliaSpace/Orekit.jl", "max_forks_repo_head_hexsha": "e2dd3d8b2085dcbb1d2c75471dab42d6ddf52c99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8358662614, "max_line_length": 182, "alphanum_fraction": 0.7129756509, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18621981890568792}} {"text": "#file with the LaTeXSVG constant\nconst LaTeXSVG = Dict{LaTeXString,String}(\n L\"\\mathcal{O}(\\log{n})\" =>\n \"\\nscript upper O left-parenthesis log n right-parenthesis\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n \\n\\n \\n \\n \\n\\n \\n \\n\\n\",\n L\"\\mathcal{O}\\left(\\frac{\\log{x}}{2}\\right)\" =>\n \"\\nscript upper O left-parenthesis StartFrobject log x Over 2 EndFrobject right-parenthesis\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n\\n \\n\\n\\n\\n\\n \\n \\n \\n \\n\\n \\n\\n\\n \\n\\n\\n\",\n L\"E=mc^2\" =>\n \"\\nupper E equals m c squared\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n \\n \\n\\n \\n \\n\\n\\n\\n\",\n L\"8\" =>\n \"\\n8\\n\\n\\n\\n\\n \\n\\n\\n\",\n L\"$\\begin{equation}\\left[\\begin{array}{ccc}1 & 2 & 3 \\\\4 & 5 & 6 \\\\7 & 8 & 9 \\\\\\end{array}\\right]\\end{equation}$\" =>\n \"\\nStart 3 By 3 Matrix 1st Row 1st Column 1 2nd Column 2 3rd Column 3 2nd Row 1st Column 4 2nd Column 5 3rd Column 6 3rd Row 1st Column 7 2nd Column 8 3rd Column 9 EndMatrix\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n \\n \\n \\n\\n\\n \\n \\n \\n\\n\\n \\n \\n \\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n\",\n L\"$\\begin{equation}\\left[\\begin{array}{ccc}\\alpha & \\beta & \\gamma \\\\x^{2} & \\sqrt{y} & \\lambda \\\\1 & 2 & y \\\\\\end{array}\\right]\\end{equation}$\" =>\n \"\\nStart 3 By 3 Matrix 1st Row 1st Column alpha 2nd Column beta 3rd Column gamma 2nd Row 1st Column x squared 2nd Column StartRoot y EndRoot 3rd Column lamda 3rd Row 1st Column 1 2nd Column 2 3rd Column y EndMatrix\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n \\n\\n \\n \\n\\n \\n\\n\\n \\n\\n \\n\\n \\n\\n \\n\\n\\n \\n \\n \\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n\",\n L\"$\\begin{equation}\\left[\\begin{array}{ccc}\\alpha & x^{2} & 1 \\\\\\beta & \\sqrt{y} & 2 \\\\\\gamma & \\lambda & y \\\\\\end{array}\\right]\\end{equation}$\" =>\n \"\\nStart 3 By 3 Matrix 1st Row 1st Column alpha 2nd Column x squared 3rd Column 1 2nd Row 1st Column beta 2nd Column StartRoot y EndRoot 3rd Column 2 3rd Row 1st Column gamma 2nd Column lamda 3rd Column y EndMatrix\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n \\n \\n \\n\\n\\n\\n \\n \\n\\n\\n \\n\\n \\n\\n \\n\\n\\n \\n \\n \\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n\",\n L\"$\\begin{equation}\\left[\\begin{array}{cc}2 & -1\\\\-1 & 2 \\\\\\end{array}\\right]\\end{equation}$\" =>\n \"\\nStart 2 By 2 Matrix 1st Row 1st Column 2 2nd Column negative 1 2nd Row 1st Column negative 1 2nd Column 2 EndMatrix\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n\\n\\n \\n\\n \\n \\n\\n\\n\\n\\n \\n \\n\\n \\n\\n\\n \\n\\n\\n\",\n L\"$\\begin{equation}\\left[\\begin{array}{ccc} 2 & -1 & 0 \\\\ -1 & 2 & -1 \\\\ 0 & -1 & 2 \\\\\\end{array}\\right]\\end{equation}$\" =>\n \"\\nStart 3 By 3 Matrix 1st Row 1st Column 2 2nd Column negative 1 3rd Column 0 2nd Row 1st Column negative 1 2nd Column 2 3rd Column negative 1 3rd Row 1st Column 0 2nd Column negative 1 3rd Column 2 EndMatrix\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n \\n\\n \\n \\n\\n \\n\\n\\n\\n \\n \\n\\n \\n\\n \\n \\n\\n\\n\\n \\n\\n \\n \\n\\n \\n\\n\\n\\n \\n\\n \\n\\n \\n\\n\\n\\n\",\n)\n", "meta": {"hexsha": "41fbc00db349dacc94eb3bc700733d42ce48634c", "size": 47144, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/latexsvgfile.jl", "max_stars_repo_name": "Ved-Mahajan/Javis.jl", "max_stars_repo_head_hexsha": "9f34c88ce8f77d0bf7a434b3f57abb6d71bda3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/latexsvgfile.jl", "max_issues_repo_name": "Ved-Mahajan/Javis.jl", "max_issues_repo_head_hexsha": "9f34c88ce8f77d0bf7a434b3f57abb6d71bda3ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/latexsvgfile.jl", "max_forks_repo_name": "Ved-Mahajan/Javis.jl", "max_forks_repo_head_hexsha": "9f34c88ce8f77d0bf7a434b3f57abb6d71bda3ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 2142.9090909091, "max_line_length": 8025, "alphanum_fraction": 0.7240157814, "num_tokens": 21798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.31069437044942166, "lm_q1q2_score": 0.1853084253513494}} {"text": "### Abstract HMC state\n\nabstract HMCState{F<:VariateForm} <: HMCSamplerState{F}\n\n### HMC state subtypes\n\n## UnvHMCState holds the internal state (\"local variables\") of the HMC sampler for univariate parameters\n\ntype UnvHMCState <: HMCState{Univariate}\n pstate::ParameterState{Continuous, Univariate} # Parameter state used internally by HMC\n tune::MCTunerState\n nleaps::Integer\n ratio::Real\n a::Real\n momentum::Real\n oldhamiltonian::Real\n newhamiltonian::Real\n count::Integer\n\n function UnvHMCState(\n pstate::ParameterState{Continuous, Univariate},\n tune::MCTunerState,\n nleaps::Integer,\n ratio::Real,\n a::Real,\n momentum::Real,\n oldhamiltonian::Real,\n newhamiltonian::Real,\n count::Integer\n )\n if !isnan(ratio)\n @assert ratio > 0 \"Acceptance ratio should be positive\"\n end\n if !isnan(a)\n @assert 0 <= a <= 1 \"Acceptance probability should be in [0, 1]\"\n end\n @assert count >= 0 \"Number of iterations (count) should be non-negative\"\n new(pstate, tune, nleaps, ratio, a, momentum, oldhamiltonian, newhamiltonian, count)\n end\nend\n\nUnvHMCState(pstate::ParameterState{Continuous, Univariate}, tune::MCTunerState=BasicMCTune(), nleaps::Integer=0) =\n UnvHMCState(pstate, tune, nleaps, NaN, NaN, NaN, NaN, NaN, 0)\n\n## MuvHMCState holds the internal state (\"local variables\") of the HMC sampler for multivariate parameters\n\ntype MuvHMCState <: HMCState{Multivariate}\n pstate::ParameterState{Continuous, Multivariate} # Parameter state used internally by HMC\n tune::MCTunerState\n nleaps::Integer\n ratio::Real\n a::Real\n momentum::RealVector\n oldhamiltonian::Real\n newhamiltonian::Real\n count::Integer\n\n function MuvHMCState(\n pstate::ParameterState{Continuous, Multivariate},\n tune::MCTunerState,\n nleaps::Integer,\n ratio::Real,\n a::Real,\n momentum::RealVector,\n oldhamiltonian::Real,\n newhamiltonian::Real,\n count::Integer\n )\n if !isnan(ratio)\n @assert ratio > 0 \"Acceptance ratio should be positive\"\n end\n if !isnan(a)\n @assert 0 <= a <= 1 \"Acceptance probability should be in [0, 1]\"\n end\n @assert count >= 0 \"Number of iterations (count) should be non-negative\"\n new(pstate, tune, nleaps, ratio, a, momentum, oldhamiltonian, newhamiltonian, count)\n end\nend\n\nMuvHMCState(pstate::ParameterState{Continuous, Multivariate}, tune::MCTunerState=BasicMCTune(), nleaps::Integer=0) =\n MuvHMCState(pstate, tune, nleaps, NaN, NaN, Array(eltype(pstate), pstate.size), NaN, NaN, 0)\n\n### Hamiltonian Monte Carlo (HMC)\n\nimmutable HMC <: HMCSampler\n leapstep::Real\n nleaps::Integer\n\n function HMC(leapstep::Real, nleaps::Integer)\n @assert leapstep > 0 \"Leapfrog step is not positive\"\n @assert nleaps > 0 \"Number of leapfrog steps is not positive\"\n new(leapstep, nleaps)\n end\nend\n\nHMC(leapstep::Real=0.1) = HMC(leapstep, 10)\n\n### Initialize HMC sampler\n\n## Initialize parameter state\n\nfunction initialize!{F<:VariateForm}(\n pstate::ParameterState{Continuous, F},\n parameter::Parameter{Continuous, F},\n sampler::HMC,\n outopts::Dict\n)\n parameter.uptogradlogtarget!(pstate)\n @assert isfinite(pstate.logtarget) \"Log-target not finite: initial value out of support\"\n @assert all(isfinite(pstate.gradlogtarget)) \"Gradient of log-target not finite: initial values out of support\"\n\n if !isempty(outopts[:diagnostics])\n pstate.diagnostickeys = copy(outopts[:diagnostics])\n pstate.diagnosticvalues = Array(Any, length(pstate.diagnostickeys))\n end\nend\n\n## Initialize HMC state\n\ntuner_state(parameter::Parameter, sampler::HMC, tuner::DualAveragingMCTuner) =\n DualAveragingMCTune(\n step=sampler.leapstep,\n λ=sampler.nleaps*sampler.leapstep,\n εbar=tuner.ε0bar,\n hbar=tuner.h0bar,\n accepted=0,\n proposed=0,\n totproposed=tuner.period\n)\n\nsampler_state(\n parameter::Parameter{Continuous, Univariate},\n sampler::HMC,\n tuner::MCTuner,\n pstate::ParameterState{Continuous, Univariate},\n vstate::VariableStateVector\n) =\n UnvHMCState(generate_empty(pstate), tuner_state(parameter, sampler, tuner), sampler.nleaps)\n\nsampler_state(\n parameter::Parameter{Continuous, Multivariate},\n sampler::HMC,\n tuner::MCTuner,\n pstate::ParameterState{Continuous, Multivariate},\n vstate::VariableStateVector\n) =\n MuvHMCState(generate_empty(pstate), tuner_state(parameter, sampler, tuner), sampler.nleaps)\n\nfunction sampler_state(\n parameter::Parameter{Continuous, Univariate},\n sampler::HMC,\n tuner::DualAveragingMCTuner,\n pstate::ParameterState{Continuous, Univariate},\n vstate::VariableStateVector\n)\n sstate = UnvHMCState(generate_empty(pstate), tuner_state(parameter, sampler, tuner), 0)\n initialize_step!(sstate, parameter, sampler, tuner, randn())\n sstate.tune.μ = log(10*sstate.tune.step)\n sstate\nend\n\nfunction sampler_state(\n parameter::Parameter{Continuous, Multivariate},\n sampler::HMC,\n tuner::DualAveragingMCTuner,\n pstate::ParameterState{Continuous, Multivariate},\n vstate::VariableStateVector\n)\n sstate = MuvHMCState(generate_empty(pstate), tuner_state(parameter, sampler, tuner), 0)\n initialize_step!(sstate, parameter, sampler, tuner, randn(sstate.pstate.size))\n sstate.tune.μ = log(10*sstate.tune.step)\n sstate\nend\n\n## Reset parameter state\n\nfunction reset!(\n pstate::ParameterState{Continuous, Univariate},\n x::Real,\n parameter::Parameter{Continuous, Univariate},\n sampler::HMC\n)\n pstate.value = x\n parameter.uptogradlogtarget!(pstate)\nend\n\nfunction reset!(\n pstate::ParameterState{Continuous, Multivariate},\n x::RealVector,\n parameter::Parameter{Continuous, Multivariate},\n sampler::HMC\n)\n pstate.value = copy(x)\n parameter.uptogradlogtarget!(pstate)\nend\n\nfunction reset!(tune::DualAveragingMCTune, sampler::HMC, tuner::DualAveragingMCTuner)\n tune.step = 1\n tune.λ = sampler.nleaps*sampler.leapstep\n tune.εbar = tuner.ε0bar\n tune.hbar = tuner.h0bar\n (tune.accepted, tune.proposed, tune.totproposed, tune.rate) = (0, 0, tuner.period, NaN)\nend\n\nfunction reset!(\n sstate::MuvHMCState,\n pstate::ParameterState{Continuous, Univariate},\n parameter::Parameter{Continuous, Univariate},\n sampler::HMC,\n tuner::DualAveragingMCTuner\n)\n reset!(sstate.tune, sampler, tuner)\n initialize_step!(sstate, parameter, sampler, tuner, randn())\n sstate.tune.μ = log(10*sstate.tune.step)\n sstate.count = 0\nend\n\nfunction reset!(\n sstate::MuvHMCState,\n pstate::ParameterState{Continuous, Multivariate},\n parameter::Parameter{Continuous, Multivariate},\n sampler::HMC,\n tuner::DualAveragingMCTuner\n)\n reset!(sstate.tune, sampler, tuner)\n initialize_step!(sstate, parameter, sampler, tuner, randn(sstate.pstate.size))\n sstate.tune.μ = log(10*sstate.tune.step)\n sstate.count = 0\nend\n\nleapfrog!(sstate::HMCState{Univariate}, gradlogtarget!::Function) =\n sstate.momentum = leapfrog!(sstate.pstate, sstate.pstate, sstate.momentum, sstate.tune.step, gradlogtarget!)\n\nleapfrog!(sstate::HMCState{Multivariate}, gradlogtarget!::Function) =\n leapfrog!(sstate.pstate, sstate.momentum, sstate.pstate, sstate.momentum, sstate.tune.step, gradlogtarget!)\n\nBase.show(io::IO, sampler::HMC) =\n print(io, \"HMC sampler: number of leaps = $(sampler.nleaps), leap step = $(sampler.leapstep)\")\n\nBase.writemime(io::IO, ::MIME\"text/plain\", sampler::HMC) = show(io, sampler)\n", "meta": {"hexsha": "2535d70991ce57dd5abb3bc3e46c9858a3c43c06", "size": 7216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/samplers/HMC.jl", "max_stars_repo_name": "JuliaPackageMirrors/Klara.jl", "max_stars_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-10-05T21:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-30T15:32:39.000Z", "max_issues_repo_path": "src/samplers/HMC.jl", "max_issues_repo_name": "JuliaPackageMirrors/Lora.jl", "max_issues_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/samplers/HMC.jl", "max_forks_repo_name": "JuliaPackageMirrors/Lora.jl", "max_forks_repo_head_hexsha": "366d1e3829ebdc5021d6cd1fa2cc2b85d8abbc9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9419087137, "max_line_length": 116, "alphanum_fraction": 0.7373891353, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18529530316584755}} {"text": "\"\"\"\nTools for model edge analysis for automatic mechanism generation\n\"\"\"\n\nusing Logging\nusing Sundials\nusing SparseArrays\nusing DiffEqBase: build_solution\nusing Base.Iterators: flatten\n\nabstract type AbstractTerminationCriterion end\n\nstruct TerminationTime <: AbstractTerminationCriterion\n time::Float64\nend\nstruct TerminationConversion <: AbstractTerminationCriterion\n species::Species\n conversion::Float64\nend\nstruct TerminationRateRatio <: AbstractTerminationCriterion\n ratio::Float64\nend\n\nexport TerminationTime\nexport TerminationConversion\nexport TerminationRateRatio\n\n\"\"\"\nGenerate appropriate core Simulation/SystemSimulation object\n\"\"\"\nfunction tosim(sol,domains,inters,p)\n return Simulation(sol,domains,inters,p)\nend\n\n\"\"\"\nGenerate appropriate core Simulation/SystemSimulation object\n\"\"\"\nfunction tosim(sol,domains::Tuple,inters,p)\n return SystemSimulation(sol,domains,inters,p) \nend\n\n\"\"\"\nGenerate appropriate edge Simulation/SystemSimulation object\n\"\"\"\nfunction getsim(inte,react,coreedgedomain,inters,p,coretoedgespcmap)\n ycoreedge = getycoreedge(inte.u,coretoedgespcmap,coreedgedomain.indexes[end])\n sol = build_solution(react.ode,inte.alg,[0.0,inte.t],[ycoreedge,ycoreedge])\n sim = Simulation(sol,coreedgedomain,inters,p)\n return sim\nend\n\n\"\"\"\nGenerate appropriate edge Simulation/SystemSimulation object\n\"\"\"\nfunction getsim(inte,react,coreedgedomains::Tuple,inters,p,coretoedgespcmap)\n ycoreedge = getycoreedge(inte.u,coretoedgespcmap,coreedgedomains[end].indexes[end])\n sol = build_solution(react.ode,inte.alg,[0.0,inte.t],[ycoreedge,ycoreedge])\n ssys = SystemSimulation(sol,coreedgedomains,inters,p)\n return ssys\nend\n\n\"\"\"\nGenerate a state vector appropriate for both the edge and core from the core state vector\n\"\"\"\nfunction getycoreedge(y,coretoedgespcmap,numedgespc)\n ycoreedge = zeros(numedgespc)\n for (coreind,edgeind) in coretoedgespcmap\n ycoreedge[edgeind] = y[coreind]\n end\n return ycoreedge\nend\n\n\"\"\"\nCalculate key flux and concentration related quantities for edge analysis\n\"\"\"\n@inline function calcfluxes(sim::Simulation)\n t = sim.sol.t[end]\n dydt = zeros(sim.domain.indexes[end])\n ns,cs,T,P,V,C,N,mu,kfs,krevs,Hs,Us,Gs,diffs,Cvave,cpdivR,phi = calcthermo(sim.domain,sim.sol.u[end],sim.sol.t[end],DiffEqBase.NullParameters())\n rts,frts,rrts = addreactionratecontributionsforwardreverse!(dydt,sim.domain.rxnarray,cs,kfs,krevs,V)\n calcdomainderivatives!(sim.domain,dydt,[];t=t,T=T,P=P,Us=Us,Hs=Hs,V=V,C=C,ns=ns,N=N,Cvave=Cvave)\n return dydt,rts,frts,rrts,cs\nend\n\n\"\"\"\nCalculate key flux and concentration related quantities for edge analysis\n\"\"\"\n@inline function calcfluxes(ssys::SystemSimulation)\n cstot = zeros(sum([length(sim.domain.phase.species) for sim in ssys.sims]))\n dydt = zeros(length(ssys.sol.u[end]))\n y = ssys.sol.u[end]\n t = ssys.sol.t[end]\n p = ssys.p\n domains = [sim.domain for sim in ssys.sims]\n interfaces = ssys.interfaces\n domain = domains[1]\n ns,cs,T,P,V,C,N,mu,kfs,krevs,Hs,Us,Gs,diffs,Cvave,cpdivR,phi = calcthermo(domain,y,t,DiffEqBase.NullParameters())\n vns = Array{Any,1}(undef,length(domains))\n vns[1] = ns\n vcs = Array{Any,1}(undef,length(domains))\n vcs[1] = cs\n cstot[domain.indexes[1]:domain.indexes[2]] = cs\n vT = Array{Any,1}(undef,length(domains))\n vT[1] = T\n vP = Array{Any,1}(undef,length(domains))\n vP[1] = P\n vV = Array{Any,1}(undef,length(domains))\n vV[1] = V\n vC = Array{Any,1}(undef,length(domains))\n vC[1] = C\n vN = Array{Any,1}(undef,length(domains))\n vN[1] = N\n vmu = Array{Any,1}(undef,length(domains))\n vmu[1] = mu\n vkfs = Array{Any,1}(undef,length(domains))\n vkfs[1] = kfs\n vkrevs = Array{Any,1}(undef,length(domains))\n vkrevs[1] = krevs\n vHs = Array{Any,1}(undef,length(domains))\n vHs[1] = Hs\n vUs = Array{Any,1}(undef,length(domains))\n vUs[1] = Us\n vGs = Array{Any,1}(undef,length(domains))\n vGs[1] = Gs\n vdiffs = Array{Any,1}(undef,length(domains))\n vdiffs[1] = diffs\n vCvave = Array{Any,1}(undef,length(domains))\n vCvave[1] = Cvave\n vcpdivR = Array{Any,1}(undef,length(domains))\n vcpdivR[1] = cpdivR\n vphi = Array{Any,1}(undef,length(domains))\n vphi[1] = phi\n rts,frts,rrts = addreactionratecontributionsforwardreverse!(dydt,domain.rxnarray,cstot,kfs,krevs,V)\n rtsall = [rts]\n frtsall = [frts]\n rrtsall = [rrts]\n for (i,domain) in enumerate(@views domains[2:end])\n k = i + 1\n vns[k],vcs[k],vT[k],vP[k],vV[k],vC[k],vN[k],vmu[k],vkfs[k],vkrevs[k],vHs[k],vUs[k],vGs[k],vdiffs[k],vCvave[k],vcpdivR[k],vphi[k] = calcthermo(domain,y,t,DiffEqBase.NullParameters())\n cstot[domain.indexes[1]:domain.indexes[2]] .= vcs[k]\n rts,frts,rrts = addreactionratecontributionsforwardreverse!(dydt,domain.rxnarray,cstot,vkfs[k],vkrevs[k],vV[k])\n push!(rtsall,rts)\n push!(frtsall,frts)\n push!(rrtsall,rrts)\n end\n for (i,inter) in enumerate(interfaces)\n if isa(inter,ReactiveInternalInterface)\n kfs,krevs = getkfskrevs(inter,vT[inter.domaininds[1]],vT[inter.domaininds[2]],vphi[inter.domaininds[1]],vphi[inter.domaininds[2]],vGs[inter.domaininds[1]],vGs[inter.domaininds[2]],cstot)\n rts,frts,rrts = addreactionratecontributionsforwardreverse!(dydt,inter.rxnarray,cstot,kfs.*p[inter.parameterindexes[1]:inter.parameterindexes[2]],krevs.*p[inter.parameterindexes[1]:inter.parameterindexes[2]],inter.A)\n push!(rtsall,rts)\n push!(frtsall,frts)\n push!(rrtsall,rrts)\n elseif isa(inter,ReactiveInternalInterfaceConstantTPhi)\n rts,frts,rrts = addreactionratecontributionsforwardreverse!(dydt,inter.rxnarray,cstot,inter.kfs,inter.krevs,inter.A)\n push!(rtsall,rts)\n push!(frtsall,frts)\n push!(rrtsall,rrts)\n elseif isa(inter,AbstractReactiveInternalInterface)\n typ = typeof(inter)\n error(\"No handling available for AbstractReactiveInternalInterface: $typ\")\n end\n end\n for (i,domain) in enumerate(domains)\n calcdomainderivatives!(domain,dydt,interfaces;t=t,T=vT[i],P=vP[i],Us=vUs[i],Hs=vHs[i],V=vV[i],C=vC[i],ns=vns[i],N=vN[i],Cvave=vCvave[i])\n end\n return dydt,collect(flatten(rtsall)),collect(flatten(frtsall)),collect(flatten(rrtsall)),cstot\nend\nexport calcfluxes\n\n\"\"\"\nPrecalculate important indices and maps for use in edge analysis\n\"\"\"\nfunction getkeyselectioninds(coreedgedomains,coreedgeinters,domains,inters)\n corespcsinds = collect(flatten([coreedgedomains[i].indexes[1]:coreedgedomains[i].indexes[1]+domains[i].indexes[2]-domains[i].indexes[1] for i = 1:length(domains)]))\n edgespcsinds = collect(flatten([coreedgedomains[i].indexes[1]+domains[i].indexes[2]-domains[i].indexes[1]+1:coreedgedomains[i].indexes[2] for i = 1:length(domains)]))\n corerxninds = Array{Int64,1}()\n edgerxninds = Array{Int64,1}()\n Nrxns = sum(length(d.phase.reactions) for d in coreedgedomains)\n reactantindices = zeros(Int64,(3,Nrxns))\n productindices = zeros(Int64,(3,Nrxns))\n coretoedgespcmap = Dict{Int64,Int64}()\n coretoedgerxnmap = Dict{Int64,Int64}()\n spcindexcore = 0\n spcindexedge = 0\n rxnindexcore = 0\n rxnindexedge = 0\n ind = 1\n for i = 1:length(domains)\n for (j,spc) in enumerate(domains[i].phase.species)\n edgeind = findfirst(isequal(spc),coreedgedomains[i].phase.species)\n coretoedgespcmap[j+spcindexcore] = edgeind+spcindexedge\n end\n for j = 3:length(domains[i].indexes)\n coretoedgespcmap[domains[i].indexes[j]] = coreedgedomains[i].indexes[j]\n end\n for (j,rxn) in enumerate(coreedgedomains[i].phase.reactions)\n coreind = findfirst(isequal(rxn),domains[i].phase.reactions)\n if coreind === nothing\n push!(edgerxninds,j+rxnindexedge)\n else\n coretoedgerxnmap[coreind+rxnindexcore] = j+rxnindexedge\n push!(corerxninds,j+rxnindexedge)\n end\n end\n spcindexcore += length(domains[i].phase.species)\n spcindexedge += length(coreedgedomains[i].phase.species)\n rxnindexcore += length(domains[i].phase.reactions)\n rxnindexedge += length(coreedgedomains[i].phase.reactions)\n\n indend = length(domains[i].phase.reactions)\n reactantindices[:,ind:ind+indend-1] = domains[i].rxnarray[1:3,:]\n productindices[:,ind:ind+indend-1] = domains[i].rxnarray[4:6,:]\n ind += indend\n end\n \n for i = 1:length(inters)\n if isa(inters[i],ReactiveInternalInterface)\n push!(corerxnrangearray,index:index+length(inters[i].reactions))\n push!(edgerxnrangearray,index+length(inters[i].reactions):index+length(coreedgeinters[i].reactions))\n index += length(coreedgeinters[i].phase.reactions)\n \n indend = length(inters[i].reactions)\n reactantindices[:,ind:ind+indend] = inters[i].rxnarray[1:3,:]\n productindices[:,ind:ind+indend] = inters[i].rxnarray[4:6,:]\n ind += indend\n end\n end\n return corespcsinds,collect(flatten(corerxninds)),edgespcsinds,collect(flatten(edgerxninds)),reactantindices,productindices,coretoedgespcmap,coretoedgerxnmap\nend\n\n\"\"\"\nPrecalculate important indices and maps for use in edge analysis\n\"\"\"\nfunction getkeyselectioninds(coreedgedomain::AbstractDomain,coreedgeinters,domain,inters)\n corespcsinds = 1:length(domain.phase.species)\n edgespcsinds = length(domain.phase.species)+1:length(coreedgedomain.phase.species)\n corerxninds = 1:length(domain.phase.reactions)\n edgerxninds = length(domain.phase.reactions)+1:length(coreedgedomain.phase.reactions)\n reactantindices = coreedgedomain.rxnarray[1:3,:]\n productindices = coreedgedomain.rxnarray[4:6,:]\n coretoedgespcmap = Dict([i=>findfirst(isequal(spc),coreedgedomain.phase.species) for (i,spc) in enumerate(domain.phase.species)])\n coretoedgerxnmap = Dict([i=>findfirst(isequal(rxn),coreedgedomain.phase.reactions) for (i,rxn) in enumerate(domain.phase.reactions)])\n for j = 3:length(domain.indexes)\n coretoedgespcmap[domain.indexes[j]] = coreedgedomain.indexes[j]\n end\n return corespcsinds,corerxninds,edgespcsinds,edgerxninds,reactantindices,productindices,coretoedgespcmap,coretoedgerxnmap\nend\n\n\"\"\"\nProcess flux information into useful quantities for edge analysis\n\"\"\"\nfunction processfluxes(sim::SystemSimulation,\n corespcsinds,corerxninds,edgespcsinds,edgerxninds)\n \n dydt,rts,frts,rrts,cs = calcfluxes(sim)\n \n corespeciesrates = abs.(dydt[corespcsinds])\n charrate = sqrt(dot(corespeciesrates,corespeciesrates))\n edgespeciesrates = abs.(dydt[edgespcsinds])\n edgereactionrates = rts[edgerxninds]\n corespeciesrateratios = corespeciesrates./charrate\n edgespeciesrateratios = edgespeciesrates./charrate\n corereactionrates = rts[corerxninds]\n corespeciesconcentrations = cs[corespcsinds]\n corespeciesconsumptionrates = zeros(length(corespeciesconcentrations))\n corespeciesproductionrates = zeros(length(corespeciesconcentrations))\n \n #process core species consumption and production rates\n index = 1\n for d in getfield.(sim.sims,:domain)\n for i = 1:size(d.rxnarray)[2]\n if any(d.rxnarray[:,i].>length(corespeciesconcentrations))\n continue\n end\n for j = 1:3\n if d.rxnarray[j,i] != 0\n corespeciesconsumptionrates[d.rxnarray[j,i]] += frts[i+index]\n corespeciesproductionrates[d.rxnarray[j,i]] += rrts[i+index]\n else\n break\n end\n end\n for j = 4:6\n if d.rxnarray[j,i] != 0\n corespeciesproductionrates[d.rxnarray[j,i]] += frts[i+index]\n corespeciesconsumptionrates[d.rxnarray[j,i]] += rrts[i+index]\n else\n break\n end\n end\n end\n index += size(d.rxnarray)[2]\n end\n for d in sim.interfaces\n if hasproperty(d,:rxnarray)\n for i = 1:size(d.rxnarray)[2]\n if any(d.rxnarray[:,i].>length(corespeciesconcentrations))\n continue\n end\n for j = 1:3\n if d.rxnarray[j,i] != 0\n corespeciesconsumptionrates[d.rxnarray[j,i]] += frts[i+index]\n corespeciesproductionrates[d.rxnarray[j,i]] += rrts[i+index]\n else\n break\n end\n end\n for j = 4:6\n if d.rxnarray[j,i] != 0\n corespeciesproductionrates[d.rxnarray[j,i]] += frts[i+index]\n corespeciesconsumptionrates[d.rxnarray[j,i]] += rrts[i+index]\n else\n break\n end\n end\n end\n index += size(d.rxnarray)[2]\n end\n end\n\n return dydt,rts,frts,rrts,cs,corespeciesrates,charrate,edgespeciesrates,edgereactionrates,corespeciesrateratios,edgespeciesrateratios,corereactionrates,corespeciesconcentrations,corespeciesproductionrates,corespeciesconsumptionrates\nend\n\n\"\"\"\nProcess flux information into useful quantities for edge analysis\n\"\"\"\nfunction processfluxes(sim::Simulation,corespcsinds,corerxninds,edgespcsinds,edgerxninds)\n \n dydt,rts,frts,rrts,cs = calcfluxes(sim)\n \n corespeciesrates = abs.(dydt[corespcsinds])\n charrate = sqrt(dot(corespeciesrates,corespeciesrates))\n edgespeciesrates = abs.(dydt[edgespcsinds])\n edgereactionrates = rts[edgerxninds]\n corespeciesrateratios = corespeciesrates./charrate\n edgespeciesrateratios = edgespeciesrates./charrate\n corereactionrates = rts[corerxninds]\n corespeciesconcentrations = cs[corespcsinds]\n corespeciesconsumptionrates = zeros(length(corespeciesconcentrations))\n corespeciesproductionrates = zeros(length(corespeciesconcentrations))\n \n #process core species consumption and production rates\n d = sim.domain\n for i = 1:size(d.rxnarray)[2]\n if any(d.rxnarray[:,i].>length(corespeciesconcentrations))\n continue\n end\n for j = 1:3\n if d.rxnarray[j,i] != 0\n corespeciesconsumptionrates[d.rxnarray[j,i]] += frts[i]\n corespeciesproductionrates[d.rxnarray[j,i]] += rrts[i]\n else\n break\n end\n end\n for j = 4:6\n if d.rxnarray[j,i] != 0\n corespeciesproductionrates[d.rxnarray[j,i]] += frts[i]\n corespeciesconsumptionrates[d.rxnarray[j,i]] += rrts[i]\n else\n break\n end\n end\n end\n \n return dydt,rts,frts,rrts,cs,corespeciesrates,charrate,edgespeciesrates,edgereactionrates,corespeciesrateratios,edgespeciesrateratios,corereactionrates,corespeciesconcentrations,corespeciesproductionrates,corespeciesconsumptionrates\nend\n\nexport processfluxes\n\n\"\"\"\nCalculate branching numbers for appropriate reactions for use in evaluating\nthe branching criterion: 1.0 < branchfactor * max(branchingratio,branchingratiomax) * rateratio^branchingindex\n\"\"\"\nfunction calcbranchingnumbers(sim,reactantinds,productinds,corespcsinds,corerxninds,edgereactionrates,corespeciesrateratios,\n corespeciesconsumptionrates,branchfactor,branchingratiomax,branchingindex)\n branchingnums = zeros(length(edgereactionrates))\n for index in 1:length(edgereactionrates)\n reactionrate = edgereactionrates[index]\n \n if reactionrate > 0\n reactantside = reactantinds[:,index+length(corerxninds)]\n productside = productinds[:,index+length(corerxninds)]\n else\n reactantside = productinds[:,index+length(corerxninds)]\n productside = reactantinds[:,index+length(corerxninds)]\n end\n \n rade = [sim.species[i].radicalelectrons for i in productside if i != 0]\n \n if maximum(rade) > 1\n continue\n end\n \n for spcindex in reactantside\n if spcindex == 0 \n continue\n elseif spcindex < length(corespcsinds)\n if sim.species[spcindex].radicalelectrons != 1\n continue\n end\n consumption = corespeciesconsumptionrates[spcindex]\n if consumption != 0\n br = reactionrate / consumption\n rr = corespeciesrateratios[spcindex]\n if br > branchingratiomax\n br = branchingratiomax\n end\n \n bnum = branchfactor * br * rr^branchingindex\n \n if bnum > branchingnums[index]\n branchingnums[index] = bnum\n end\n end\n end\n end\n end\n return branchingnums \nend\n\nexport calcbranchingnumbers\n\n\"\"\"\ndetermine species pairings that are concentrated enough that they should be reacted\n\"\"\"\nfunction updatefilterthresholds!(sim,corespcsinds,corespeciesconcentrations,charrate,\n unimolecularthreshold,bimolecularthreshold,trimolecularthreshold,tolmovetocore,\n filterthreshold)\n unimolecularthresholdrateconstant,bimolecularthresholdrateconstant,trimolecularthresholdrateconstant = getthresholdrateconstants(sim,sim.domain.phase,filterthreshold)\n \n unimolecularthresholdval = tolmovetocore * charrate / unimolecularthresholdrateconstant\n bimolecularthresholdval = tolmovetocore * charrate / bimolecularthresholdrateconstant\n trimolecularthresholdval = tolmovetocore * charrate / trimolecularthresholdrateconstant\n \n for i in 1:length(corespcsinds)\n if !unimolecularthreshold[i]\n if corespeciesconcentrations[i] > unimolecularthresholdval\n unimolecularthreshold[i] = true\n end\n end\n end\n for i in 1:length(corespcsinds)\n for j in i:length(corespcsinds)\n if !bimolecularthreshold[i,j]\n if corespeciesconcentrations[i] * corespeciesconcentrations[j] > bimolecularthresholdval\n bimolecularthreshold[i,j] = true\n end\n end\n end\n end\n for i in 1:length(corespcsinds)\n for j in i:length(corespcsinds)\n for k in j:length(corespcsinds)\n if !trimolecularthreshold[i,j,k]\n if corespeciesconcentrations[i] * corespeciesconcentrations[j] * corespeciesconcentrations[k] > trimolecularthresholdval\n trimolecularthreshold[i,j,k] = true\n end\n end\n end\n end\n end\nend\n\nexport updatefilterthresholds!\n\n\"\"\"\nDetermine species/reactions that should be added to the model core, react thresholding and \nwhether the simulation should be interrupted or terminated\n\"\"\"\nfunction identifyobjects!(sim,corespcsinds,corerxninds,edgespcsinds,\n edgerxninds,reactantinds,productinds,unimolecularthreshold,bimolecularthreshold,\n trimolecularthreshold,maxedgespeciesrateratios,tolmovetocore,tolinterruptsimulation,\n ignoreoverallfluxcriterion,filterreactions,maxnumobjsperiter,branchfactor,branchingratiomax,\n branchingindex,terminateatmaxobjects,termination,y0,invalidobjects,firsttime,\n filterthreshold)\n \n rxnarray = vcat()\n t = sim.sol.t[end]\n y = sim.sol.u[end]\n breakflag = false\n numcorespc = length(corespcsinds)\n numcorerxns = length(corerxninds)\n invalidobjectsprintboolean = true\n terminated = false\n conversion = 0.0\n \n (dydt,rts,frts,rrts,cs,corespeciesratse,charrate,edgespeciesrates,\n edgereactionrates,corespeciesrateratios,edgespeciesrateratios,\n corereactionrates,corespeciesconcentrations,corespeciesproductionrates,\n corespeciesconsumptionrates) = processfluxes(sim,corespcsinds,corerxninds,edgespcsinds,edgerxninds)\n \n for i = 1:length(edgespeciesrateratios)\n if edgespeciesrateratios[i] > maxedgespeciesrateratios[i]\n maxedgespeciesrateratios[i] = edgespeciesrateratios[i]\n end\n end\n \n if charrate == 0 && length(edgereactionrates) > 0\n maxspeciesindex = argmax(edgespeciesrates)\n maxspeciesrate = edgespeciesrates[maxspeciesindex]\n name = sim.names[maxspeciesindex]\n @info \"at time $t s, species $name was added to model core to avoid singularity\"\n push!(invalidobjects,sim.species[maxspeciesindex])\n return (false,true)\n end\n \n if branchfactor != 0.0 && !firsttime\n branchingnums = calcbranchingnumbers(sim,reactantinds,productinds,corespcsinds,corerxninds,edgereactionrates,\n corespeciesrateratios,corespeciesconsumptionrates,branchfactor,branchingratiomax,branchingindex)\n end\n \n if filterreactions\n updatefilterthresholds!(sim,corespcsinds,corespeciesconcentrations,charrate,\n unimolecularthreshold,bimolecularthreshold,trimolecularthreshold,tolmovetocore,\n filterthreshold)\n end\n \n newobjectinds = Array{Int64,1}()\n newobjects = []\n newobjectvals = Array{Float64,1}()\n newobjecttype = []\n \n tempnewobjects = []\n tempnewobjectinds = Array{Int64,1}()\n tempnewobjectvals = Array{Float64,1}()\n tempnewobjecttype = []\n \n interrupt = false\n \n #movement of species to core based on rate ratios\n \n if !ignoreoverallfluxcriterion\n for (i,ind) in enumerate(edgespcsinds)\n rr = edgespeciesrateratios[i]\n obj = sim.species[ind]\n name = obj.name\n if rr > tolmovetocore\n if !(obj in newobjects || obj in invalidobjects)\n push!(tempnewobjects,obj)\n push!(tempnewobjectinds,ind)\n push!(tempnewobjectvals,rr)\n push!(tempnewobjecttype,\"rr\")\n end\n end\n if rr > tolinterruptsimulation\n @info \"at time $t sec, species $name at $rr exceeded the minimum rate for simulation interruption of $tolinterruptsimulation\"\n interrupt = true\n end\n end\n \n sortedinds = reverse(sortperm(tempnewobjectvals))\n \n for q in sortedinds\n push!(newobjects,tempnewobjects[q])\n push!(newobjectinds,tempnewobjectinds[q])\n push!(newobjectvals,tempnewobjectvals[q])\n push!(newobjecttype,tempnewobjecttype[q])\n end\n \n tempnewobjects = []\n tempnewobjectinds = Array{Int64,1}()\n tempnewobjectvals = Array{Float64,1}()\n tempnewobjecttype = []\n end\n \n if branchfactor != 0.0 && !firsttime\n for (i,ind) in enumerate(edgerxninds)\n bnum = branchingnums[i]\n if bnum > 1\n obj = sim.reactions[ind+numcorerxns]\n if !(obj in newobjects || obj in invalidobjects)\n push!(tempnewobjects,obj)\n push!(tempnewobjectinds,ind)\n push!(tempnewobjectvals,bnum)\n push!(tempnewobjecttype,\"branching\")\n end\n end\n end\n sortedinds = reverse(sortperm(tempnewobjectvals))\n \n for q in sortedinds\n push!(newobjects,tempnewobjects[q])\n push!(newobjectinds,tempnewobjectinds[q])\n push!(newobjectvals,tempnewobjectvals[q])\n push!(newobjecttype,tempnewobjecttype[q])\n end\n \n tempnewobjects = []\n tempnewobjectinds = Array{Int64,1}()\n tempnewobjectvals = Array{Float64,1}()\n tempnewobjecttype = []\n end\n \n if length(invalidobjects) + length(newobjects) > maxnumobjsperiter\n if invalidobjectsprintboolean\n @info \"Exceeded max number of objects...removing excess objects\"\n invalidobjectsprintboolean = false\n end\n num = maxnumobjsperiter - length(invalidobjects)\n newobjects = newobjects[1:num]\n newobjectinds = newobjectinds[1:num]\n newobjectvals = newobjectvals[1:num]\n newobjecttype = newobjecttype[1:num]\n end\n \n if terminateatmaxobjects && length(invalidobjects) + length(newobjects) >= maxnumobjsperiter\n @info \"Reached max number of objects...preparing to terminate\"\n interrupt = true\n end\n \n if length(newobjects) > 0\n for (i,obj) in enumerate(newobjects)\n val = newobjectvals[i]\n ind = newobjectinds[i]\n if isa(obj, Species)\n name = obj.name\n @info \"At time $t sec, species $name at rate ratio $val exceeded the minimum rate for moving to model core of $tolmovetocore\"\n elseif isa(obj,ElementaryReaction)\n rstr = getrxnstr(obj)\n @info \"at time $t sec, reaction $rstr at a branching number of $val exceeded the threshold of 1 for moving to model core\"\n end\n end\n \n append!(invalidobjects,newobjects)\n end\n \n if interrupt\n @info \"Terminating simulation due to interrupt\"\n end\n \n for term in termination\n if isa(term, TerminationTime)\n if t > term.time\n terminated = true\n @info \"at time $t sec, reached target termination time\"\n end\n elseif isa(term, TerminationRateRatio)\n if maxcharrate != 0.0 && charrate / maxcharrate < term.ratio\n terminated = true\n ratio = term.ratio\n @info \"At time $t sec, reached target termination rate ratio $ratio\"\n end\n else isa(term, TerminationConversion)\n index = findfirst(isequal(term.species.name),sim.names)\n conversion = 1 - (y[index] / y0[index])\n name = sim.species[index].name\n if conversion >= term.conversion\n terminated = true\n @info \"At time $t sec, reeached target termination conversion $conversion of $name\"\n end\n end\n end\n \n if terminated\n for term in termination\n if isa(term, TerminationConversion)\n index = findfirst(isequal(term.species.name),sim.names)\n conversion = 1 - (y[index] / y0[index])\n name = sim.species[index].name\n @info \"$name conversion: $conversion\"\n end\n end\n end\n \n return (terminated,interrupt,conversion) \nend\n\nexport identifyobjects!\n\n\"\"\"\nrun edge analysis to determine objects (species/reactions) that should be added to model core\n\"\"\"\nfunction selectobjects(react,coreedgedomains,coreedgeinters,domains,inters,\n corep,coreedgep,tolmovetocore,tolinterruptsimulation,ignoreoverallfluxcriterion,filterreactions,\n maxnumobjsperiter,tolbranchrxntocore,branchingratiomax,\n branchingindex,terminateatmaxobjects,termination,\n filterthreshold;\n atol=1e-20,rtol=1e-6,solver=CVODE_BDF())\n \n (corespcsinds,corerxninds,edgespcsinds,edgerxninds,reactantindices,\n productindices,coretoedgespcmap,coretoedgerxnmap) = getkeyselectioninds(coreedgedomains,coreedgeinters,domains,inters)\n \n unimolecularthreshold = falses(length(corespcsinds))\n bimolecularthreshold = falses((length(corespcsinds),length(corespcsinds)))\n trimolecularthreshold = falses((length(corespcsinds),length(corespcsinds),length(corespcsinds)))\n maxedgespeciesrateratios = zeros(length(edgespcsinds))\n invalidobjects = []\n terminated = false\n conversion = 0.0\n code = :Success\n \n if tolbranchrxntocore != 0.0\n branchfactor = 1.0/tolbranchrxntocore\n else\n branchfactor = 0.0\n end\n \n tf = react.ode.tspan[2]\n inte = init(react.ode,solver,abstol=atol,reltol=rtol);\n \n t = inte.t\n sim = getsim(inte,react,coreedgedomains,coreedgeinters,corep,coretoedgespcmap)\n\n y0 = sim.sol[end]\n spcsaddindices = Array{Int64,1}()\n firsttime = true\n \n n = 1\n while t < tf && code == :Success\n for i = 1:n\n step!(inte)\n end\n code = check_error(inte)\n t = inte.t\n sim = getsim(inte,react,coreedgedomains,coreedgeinters,coreedgep,coretoedgespcmap)\n terminated,interrupt,conversion = identifyobjects!(sim,corespcsinds,corerxninds,edgespcsinds,\n edgerxninds,reactantindices,productindices,unimolecularthreshold,bimolecularthreshold,\n trimolecularthreshold,maxedgespeciesrateratios,tolmovetocore,tolinterruptsimulation,ignoreoverallfluxcriterion,filterreactions,\n maxnumobjsperiter,branchfactor,branchingratiomax,\n branchingindex,terminateatmaxobjects,termination,y0,invalidobjects,firsttime,\n filterthreshold)\n if firsttime\n firsttime = false\n end\n if terminated || interrupt\n break\n end\n end\n\n if code == :Success\n return (terminated,false,invalidobjects,unimolecularthreshold,\n bimolecularthreshold,trimolecularthreshold,maxedgespeciesrateratios,t,conversion)\n else\n @error \"Solver failed with code $code resurrecting job\"\n dydt,rts,frts,rrts,cs,corespeciesrates,charrate,edgespeciesrates,edgereactionrates,\n corespeciesrateratios,edgespeciesrateratios,corereactionrates,corespeciesconcentrations,\n corespeciesproductionrates,corespeciesconsumptionrates = processfluxes(sim,corespcsinds,corerxninds,edgespcsinds,edgerxninds)\n ind = edgespcsinds[argmax(edgespeciesrates)]\n invalidobjects = [sim.species[ind]]\n return (terminated,true,invalidobjects,unimolecularthreshold,\n bimolecularthreshold,trimolecularthreshold,maxedgespeciesrateratios,t,conversion)\n end\n \nend\n\nexport selectobjects\n\n\"\"\"\ncalculate threshold rate constants for different numbers of reactants\n(to some extent the filter assumes rate constants can't be faster than these thresholds)\n\"\"\"\nfunction getthresholdrateconstants(sim::Simulation,phase,filterthreshold)\n return 2.08366122e10*getT(sim,sim.sol.t[end]),filterthreshold,filterthreshold/1.0e3\nend\n\n\"\"\"\ncalculate threshold rate constants for different numbers of reactants\n(to some extent the filter assumes rate constants can't be faster than these thresholds)\n\"\"\"\nfunction getthresholdrateconstants(sim::Simulation,phase::IdealDiluteSolution,filterthreshold)\n T = getT(sim,sim.sol.t[end])\n mu = phase.solvent.mu(T)\n return 2.08366122e10*T,22.2*T/mu,0.11*T/mu\nend\n\nexport getthresholdrateconstants", "meta": {"hexsha": "5b7f7e0458fade2b7b1f7101fd667ea500c82845", "size": 30777, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EdgeAnalysis.jl", "max_stars_repo_name": "MechGen3SO/ReactionMechanismSimulator.jl", "max_stars_repo_head_hexsha": "09ef14046b786dea6b53a0517016b9b154386d3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2020-05-19T17:27:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:22:07.000Z", "max_issues_repo_path": "src/EdgeAnalysis.jl", "max_issues_repo_name": "MechGen3SO/ReactionMechanismSimulator.jl", "max_issues_repo_head_hexsha": "09ef14046b786dea6b53a0517016b9b154386d3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 108, "max_issues_repo_issues_event_min_datetime": "2019-09-05T17:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:29:41.000Z", "max_forks_repo_path": "src/EdgeAnalysis.jl", "max_forks_repo_name": "MechGen3SO/ReactionMechanismSimulator.jl", "max_forks_repo_head_hexsha": "09ef14046b786dea6b53a0517016b9b154386d3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2019-06-23T21:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T04:19:51.000Z", "avg_line_length": 40.1264667536, "max_line_length": 236, "alphanum_fraction": 0.6604282419, "num_tokens": 8122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18483263589821314}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\nimport LinearAlgebra: BlasInt\n@static if isdefined(LinearAlgebra, :ARPACKException)\n import LinearAlgebra: ARPACKException\nelse\n struct ARPACKException <: Exception\n info::BlasInt\n end\n\n function Base.showerror(io::IO, ex::ARPACKException)\n print(io, \"ARPACKException: \")\n if ex.info == -8\n print(io, \"error return from calculation of a real Schur form.\")\n elseif ex.info == -9\n print(io, \"error return from calculation of eigenvectors.\")\n elseif ex.info == -14\n print(io, string(\"did not find any eigenvalues to sufficient accuracy. \",\n \"Try with a different starting vector or more Lanczos vectors \",\n \"by increasing the value of ncv.\"))\n else\n print(io, \"unspecified ARPACK error: $(ex.info)\")\n end\n end\nend\n\n## aupd and eupd wrappers\n\nfunction aupd_wrapper(T, matvecA!::Function, matvecB::Function, solveSI::Function, n::Integer,\n sym::Bool, cmplx::Bool, bmat::String,\n nev::Integer, ncv::Integer, which::String,\n tol::Real, maxiter::Integer, mode::Integer, v0::Vector)\n lworkl = cmplx ? ncv * (3*ncv + 5) : (sym ? ncv * (ncv + 8) : ncv * (3*ncv + 6) )\n TR = cmplx ? T.types[1] : T\n TOL = Ref{TR}(tol)\n\n v = Matrix{T}(undef, n, ncv)\n workd = Vector{T}(undef, 3*n)\n workl = Vector{T}(undef, lworkl)\n rwork = cmplx ? Vector{TR}(undef, ncv) : Vector{TR}()\n\n if isempty(v0)\n resid = Vector{T}(undef, n)\n info = Ref{BlasInt}(0)\n else\n resid = deepcopy(v0)\n info = Ref{BlasInt}(1)\n end\n iparam = zeros(BlasInt, 11)\n ipntr = zeros(BlasInt, (sym && !cmplx) ? 11 : 14)\n ido = Ref{BlasInt}(0)\n\n iparam[1] = BlasInt(1) # ishifts\n iparam[3] = BlasInt(maxiter) # maxiter\n iparam[7] = BlasInt(mode) # mode\n\n zernm1 = 0:(n-1)\n\n while true\n if cmplx\n naupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n,\n iparam, ipntr, workd, workl, lworkl, rwork, info)\n elseif sym\n saupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n,\n iparam, ipntr, workd, workl, lworkl, info)\n else\n naupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n,\n iparam, ipntr, workd, workl, lworkl, info)\n end\n if info[] != 0\n throw(ARPACKException(info[]))\n end\n\n x = view(workd, ipntr[1] .+ zernm1)\n y = view(workd, ipntr[2] .+ zernm1)\n if mode == 1 # corresponds to dsdrv1, dndrv1 or zndrv1\n if ido[] == 1\n matvecA!(y, x)\n elseif ido[] == 99\n break\n else\n throw(ARPACKException(\"unexpected behavior\"))\n end\n elseif mode == 3 && bmat == \"I\" # corresponds to dsdrv2, dndrv2 or zndrv2\n if ido[] == -1 || ido[] == 1\n y[:] = solveSI(x)\n elseif ido[] == 99\n break\n else\n throw(ARPACKException(\"unexpected behavior\"))\n end\n elseif mode == 2 # corresponds to dsdrv3, dndrv3 or zndrv3\n if ido[] == -1 || ido[] == 1\n matvecA!(y, x)\n if sym\n x[:] = y # overwrite as per Remark 5 in dsaupd.f\n end\n y[:] = solveSI(y)\n elseif ido[] == 2\n y[:] = matvecB(x)\n elseif ido[] == 99\n break\n else\n throw(ARPACKException(\"unexpected behavior\"))\n end\n elseif mode == 3 && bmat == \"G\" # corresponds to dsdrv4, dndrv4 or zndrv4\n if ido[] == -1\n y[:] = solveSI(matvecB(x))\n elseif ido[] == 1\n y[:] = solveSI(view(workd,ipntr[3] .+ zernm1))\n elseif ido[] == 2\n y[:] = matvecB(x)\n elseif ido[] == 99\n break\n else\n throw(ARPACKException(\"unexpected behavior\"))\n end\n else\n throw(ArgumentError(\"ARPACK mode ($mode) not yet supported\"))\n end\n end\n\n return (resid, v, n, iparam, ipntr, workd, workl, lworkl, rwork, TOL)\nend\n\nfunction eupd_wrapper(T, n::Integer, sym::Bool, cmplx::Bool, bmat::String,\n nev::Integer, which::String, ritzvec::Bool,\n TOL::Ref, resid, ncv::Integer, v, ldv, sigma, iparam, ipntr,\n workd, workl, lworkl, rwork)\n howmny = \"A\"\n select = Vector{BlasInt}(undef, ncv)\n info = Ref{BlasInt}(0)\n\n dmap = x -> abs.(x)\n if iparam[7] == 3 # shift-and-invert\n dmap = x -> abs.(1 ./ (x .- sigma))\n elseif which == \"LR\" || which == \"LA\" || which == \"BE\"\n dmap = real\n elseif which == \"SR\" || which == \"SA\"\n dmap = x -> -real(x)\n elseif which == \"LI\"\n dmap = imag\n elseif which == \"SI\"\n dmap = x -> -imag(x)\n end\n\n if cmplx\n d = Vector{T}(undef, nev+1)\n sigmar = Ref{T}(sigma)\n workev = Vector{T}(undef, 2ncv)\n neupd(ritzvec, howmny, select, d, v, ldv, sigmar, workev,\n bmat, n, which, nev, TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, rwork, info)\n if info[] != 0\n throw(ARPACKException(info[]))\n end\n\n p = sortperm(dmap(d[1:nev]), rev=true)\n return ritzvec ? (d[p], v[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid)\n elseif sym\n d = Vector{T}(undef, nev)\n sigmar = Ref{T}(sigma)\n seupd(ritzvec, howmny, select, d, v, ldv, sigmar,\n bmat, n, which, nev, TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, info)\n if info[] != 0\n throw(ARPACKException(info[]))\n end\n\n p = sortperm(dmap(d), rev=true)\n return ritzvec ? (d[p], v[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid)\n else\n dr = Vector{T}(undef, nev+1)\n di = Vector{T}(undef, nev+1)\n fill!(dr,NaN)\n fill!(di,NaN)\n sigmar = Ref{T}(real(sigma))\n sigmai = Ref{T}(imag(sigma))\n workev = Vector{T}(undef, 3*ncv)\n neupd(ritzvec, howmny, select, dr, di, v, ldv, sigmar, sigmai,\n workev, bmat, n, which, nev, TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, info)\n if info[] != 0\n throw(ARPACKException(info[]))\n end\n evec = complex.(Matrix{T}(undef, n, nev+1), Matrix{T}(undef, n, nev+1))\n\n j = 1\n while j <= nev\n if di[j] == 0\n evec[:,j] = v[:,j]\n else # For complex conjugate pairs\n evec[:,j] = v[:,j] + im*v[:,j+1]\n evec[:,j+1] = v[:,j] - im*v[:,j+1]\n j += 1\n end\n j += 1\n end\n if j == nev+1 && !isnan(di[j])\n if di[j] == 0\n evec[:,j] = v[:,j]\n j += 1\n else\n throw(ARPACKException(\"unexpected behavior\"))\n end\n end\n\n d = complex.(dr, di)\n\n if j == nev+1\n p = sortperm(dmap(d[1:nev]), rev=true)\n else\n p = sortperm(dmap(d), rev=true)\n p = p[1:nev]\n end\n\n return ritzvec ? (d[p], evec[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid)\n end\nend\n\nfor (T, saupd_name, seupd_name, naupd_name, neupd_name) in\n ((:Float64, :dsaupd_, :dseupd_, :dnaupd_, :dneupd_),\n (:Float32, :ssaupd_, :sseupd_, :snaupd_, :sneupd_))\n @eval begin\n function naupd(ido, bmat, n, evtype, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,\n iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)\n ccall(($(string(naupd_name)), libarpack), Cvoid,\n (Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},\n Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},\n Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong),\n ido, bmat, n, evtype, nev,\n TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, info, sizeof(bmat), sizeof(evtype))\n end\n\n function neupd(rvec, howmny, select, dr, di, z, ldz, sigmar, sigmai,\n workev::Vector{$T}, bmat, n, evtype, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v, ldv,\n iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)\n ccall(($(string(neupd_name)), libarpack), Cvoid,\n (Ref{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{$T}, Ref{BlasInt},\n Ref{$T}, Ref{$T}, Ptr{$T}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},\n Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},\n Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong, Clong),\n rvec, howmny, select, dr, di, z, ldz,\n sigmar, sigmai, workev, bmat, n, evtype, nev,\n TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, info, sizeof(howmny), sizeof(bmat), sizeof(evtype))\n end\n\n function saupd(ido, bmat, n, which, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,\n iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)\n ccall(($(string(saupd_name)), libarpack), Cvoid,\n (Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},\n Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},\n Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong),\n ido, bmat, n, which, nev,\n TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, info, sizeof(bmat), sizeof(which))\n end\n\n function seupd(rvec, howmny, select, d, z, ldz, sigma,\n bmat, n, evtype, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,\n iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)\n ccall(($(string(seupd_name)), libarpack), Cvoid,\n (Ref{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt},\n Ptr{$T}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},\n Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},\n Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong, Clong),\n rvec, howmny, select, d, z, ldz,\n sigma, bmat, n, evtype, nev,\n TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, info, sizeof(howmny), sizeof(bmat), sizeof(evtype))\n end\n end\nend\n\nfor (T, TR, naupd_name, neupd_name) in\n ((:ComplexF64, :Float64, :znaupd_, :zneupd_),\n (:ComplexF32, :Float32, :cnaupd_, :cneupd_))\n @eval begin\n function naupd(ido, bmat, n, evtype, nev, TOL::Ref{$TR}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,\n iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl,\n rwork::Vector{$TR}, info)\n ccall(($(string(naupd_name)), libarpack), Cvoid,\n (Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},\n Ptr{$TR}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},\n Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$TR}, Ref{BlasInt}),\n ido, bmat, n, evtype, nev,\n TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, rwork, info)\n end\n\n function neupd(rvec, howmny, select, d, z, ldz, sigma, workev::Vector{$T},\n bmat, n, evtype, nev, TOL::Ref{$TR}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,\n iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl,\n rwork::Vector{$TR}, info)\n ccall(($(string(neupd_name)), libarpack), Cvoid,\n (Ref{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt},\n Ptr{$T}, Ptr{$T}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},\n Ptr{$TR}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},\n Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$TR}, Ref{BlasInt}),\n rvec, howmny, select, d, z, ldz,\n sigma, workev, bmat, n, evtype, nev,\n TOL, resid, ncv, v, ldv,\n iparam, ipntr, workd, workl, lworkl, rwork, info)\n end\n end\nend\n", "meta": {"hexsha": "c532fb947d29011b69d204474e47eea54fb30d5a", "size": 13062, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/libarpack.jl", "max_stars_repo_name": "alyst/Arpack.jl", "max_stars_repo_head_hexsha": "d29b6cc0248ea88f3e29477f6f45856aa7c03706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libarpack.jl", "max_issues_repo_name": "alyst/Arpack.jl", "max_issues_repo_head_hexsha": "d29b6cc0248ea88f3e29477f6f45856aa7c03706", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libarpack.jl", "max_forks_repo_name": "alyst/Arpack.jl", "max_forks_repo_head_hexsha": "d29b6cc0248ea88f3e29477f6f45856aa7c03706", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2718446602, "max_line_length": 126, "alphanum_fraction": 0.5001531159, "num_tokens": 4281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.18472682321115247}} {"text": "function backtest(strat, data; mode = \"train\")\n 记忆仓位 = @staticvar zeros(Float32, 100000)\n F, N, T = size(data.特征)\n T < 1 && return 0f0\n @unpack sim, 最大持仓, 持仓天数, 最多交易次数, 禁止平今,\n 夜盘最早开仓时间, 夜盘最晚开仓时间, 夜盘最晚平仓时间,\n 早盘最早开仓时间, 早盘最晚开仓时间,早盘最晚平仓时间 = strat\n 最大持仓 = iszero(最大持仓) ? ncodes(data) : clamp(最大持仓, 1, ncodes(data))\n 虚拟信号, 综合评分 = simulate(sim, data)\n 持仓天数′ = size(虚拟信号, 1) ÷ N\n if 持仓天数′ == 1\n 虚拟信号 = lockphase(虚拟信号, 持仓天数)\n 综合评分 = lockphase(综合评分, 持仓天数)\n else\n 持仓天数 = 持仓天数′\n end\n data = repeat(data, 持仓天数)\n @unpack 涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 涨停, 跌停, 交易池 = data\n map!(fillnan, 时间戳, 时间戳)\n if size(记忆仓位, 1) != size(虚拟信号, 1)\n fill!(resize!(记忆仓位, size(虚拟信号, 1)), 0f0)\n end\n 转移函数 = transition(sim)\n # TODO: merge select\n if select(sim)\n 是否为ST = repeat(getfeat(data, r\"is_st\", errors = \"ignore\"), 持仓天数)\n 实际仓位 = select_stocks(时间戳, 代码, 买1价, 卖1价, 涨停, 跌停, 交易池, 是否为ST, 虚拟信号, 综合评分, \n 记忆仓位, 最大持仓, 持仓天数, 最多交易次数, 转移函数, 禁止平今, 夜盘最早开仓时间, 夜盘最晚开仓时间, \n 夜盘最晚平仓时间, 早盘最早开仓时间, 早盘最晚开仓时间, 早盘最晚平仓时间)\n else\n 实际仓位 = constraint(时间戳, 代码, 买1价, 卖1价, 涨停, 跌停, 虚拟信号, 记忆仓位, 转移函数, 最多交易次数, 禁止平今, \n 夜盘最早开仓时间, 夜盘最晚开仓时间, 夜盘最晚平仓时间, 早盘最早开仓时间, 早盘最晚开仓时间, 早盘最晚平仓时间)\n end\n if size(实际仓位, 2) == 1 && !any(isnan, 实际仓位)\n 记忆仓位 .= 实际仓位[:, end]\n end\n if T > 1 && parseenv(\"CLOSE_LAST_POS\", true)\n 实际仓位[:, end] .= 0\n end\n pnl = if mode == \"train\"\n summarize_train(涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 交易池, 记忆仓位, 实际仓位, 综合评分, 最大持仓)\n else\n summarize_test(涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 交易池, 记忆仓位, 实际仓位, 综合评分, 虚拟信号, 最大持仓 * 持仓天数)\n end\n return pnl\nend\n\nfunction constraint(时间戳, 代码, 买1价, 卖1价, 涨停, 跌停, 虚拟信号, 记忆仓位, 转移函数, 最多交易次数, 禁止平今, 夜盘最早开仓时间, 夜盘最晚开仓时间, 夜盘最晚平仓时间, 早盘最早开仓时间, 早盘最晚开仓时间, 早盘最晚平仓时间)\n 实际仓位 = zero(虚拟信号)\n N, T = size(实际仓位)\n 交易次数 = zeros(Float32, N)\n @inbounds for t in 1:T, n in 1:N\n 小时 = to_trade_hour(时间戳[n, t])\n 之前仓位 = t > 1 ? 实际仓位[n, t - 1] : 记忆仓位[n]\n 是否平仓 = 夜盘最晚平仓时间 <= 小时 <= 8 || 早盘最晚平仓时间 <= 小时 <= 16\n 当前仓位 = 是否平仓 ? 0f0 : 转移函数(之前仓位, 虚拟信号[n, t])\n if (涨停[n, t] == 1 || isnan(卖1价[n, t])) && 当前仓位 > 之前仓位 ||\n (跌停[n, t] == 1 || isnan(买1价[n, t])) && 当前仓位 < 之前仓位 ||\n abs(当前仓位) > abs(之前仓位) && (交易次数[n] >= 最多交易次数 ||\n !(夜盘最早开仓时间 <= 小时 <= 夜盘最晚开仓时间) ||\n !(早盘最早开仓时间 <= 小时 <= 早盘最晚开仓时间)) ||\n abs(当前仓位) < abs(之前仓位) && 交易次数[n] >= 1 && 禁止平今 && !是否平仓\n 当前仓位 = 之前仓位\n end\n 时间差 = 时间戳[n, t] - 时间戳[n, max(1, t - 1)]\n if 小时 > 8 && 时间差 > 3600 * 5\n 交易次数[n] = 0\n else\n 交易次数[n] += abs(当前仓位 - 之前仓位)\n end\n if 代码[n, t] != 代码[n, min(t + 1, end)] # || 时间戳[n, t] == 0\n 当前仓位 = 0f0\n 交易次数[n] = 0\n end\n 实际仓位[n, t] = 当前仓位\n end\n return 实际仓位\nend\n\nfunction select_stocks(时间戳, 代码, 买1价, 卖1价, 涨停, 跌停, 交易池, 是否为ST, 虚拟信号, 综合评分, \n 记忆仓位, 最大持仓, 持仓天数, 最多交易次数, 转移函数, 禁止平今, 夜盘最早开仓时间, \n 夜盘最晚开仓时间, 夜盘最晚平仓时间, 早盘最早开仓时间, 早盘最晚开仓时间, 早盘最晚平仓时间)\n 实际仓位 = zero(虚拟信号)\n N, T = size(虚拟信号)\n 交易次数 = zeros(Int, N)\n 选股池 = zeros(Bool, N)\n for t in 1:T\n fill!(选股池, 0)\n 选股数 = 最大持仓 * 持仓天数\n for n in 1:N\n 小时 = to_trade_hour(时间戳[n, t])\n 之前仓位 = t > 1 ? 实际仓位[n, t - 1] : 记忆仓位[n]\n 是否平仓 = 夜盘最晚平仓时间 <= 小时 <= 8 || 早盘最晚平仓时间 <= 小时 <= 16\n 当前仓位 = 是否平仓 ? 0f0 : 转移函数(之前仓位, 虚拟信号[n, t])\n if (涨停[n, t] == 1 || isnan(卖1价[n, t])) && 当前仓位 > 之前仓位 ||\n (跌停[n, t] == 1 || isnan(买1价[n, t])) && 当前仓位 < 之前仓位 ||\n abs(当前仓位) > abs(之前仓位) && (交易次数[n] >= 最多交易次数 ||\n !(夜盘最早开仓时间 <= 小时 <= 夜盘最晚开仓时间) ||\n !(早盘最早开仓时间 <= 小时 <= 早盘最晚开仓时间)) ||\n abs(当前仓位) < abs(之前仓位) && 交易次数[n] >= 1 && 禁止平今 && !是否平仓\n 当前仓位 = 之前仓位\n end\n 时间差 = 时间戳[n, t] - 时间戳[n, max(1, t - 1)]\n if 小时 > 8 && 时间差 > 3600 * 5\n 交易次数[n] = 0\n else\n 交易次数[n] += 当前仓位 != 之前仓位\n end\n if 代码[n, t] != 代码[n, min(t + 1, end)] || 时间戳[n, t] == 0\n 当前仓位 = 0f0\n 交易次数[n] = 0\n end\n if isnan(虚拟信号[n, t]) || 当前仓位 > 之前仓位\n 选股池[n] = 1\n 实际仓位[n, t] = 0\n else\n 实际仓位[n, t] = 当前仓位\n end\n if 代码[n, t] != 代码[n, min(t + 1, end)] || 时间戳[n, t] == 0\n 实际仓位[n, t] = 0\n 选股池[n] = 0 \n 交易次数[n] = 0\n elseif 交易池[n, t] == 0 || 是否为ST[n, t] == 1\n 实际仓位[n, t] = 0\n 选股池[n] = 0\n elseif 涨停[n, t] == 1 || 跌停[n, t] == 1\n 实际仓位[n, t] = 之前仓位\n 选股池[n] = 0\n end\n 选股数 -= 实际仓位[n, t] == 1\n end\n 选股数 = min(选股数, 最大持仓)\n 选股列表 = findall(选股池)\n if length(选股列表) <= 选股数\n 实际仓位[选股列表, t] .= 1\n else\n 选股列表索引 = partialsortperm(综合评分[选股列表, t], 1:选股数, rev = true)\n 实际仓位[选股列表[选股列表索引], t] .= 1\n end\n end\n return 实际仓位\nend\n\nfunction summarize_core(涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 交易池, 记忆仓位, 实际仓位, 综合评分, 最大持仓)\n 记忆收益率 = @staticvar Dict{UInt64, Array{Float32}}()\n N, T = size(实际仓位)\n 天数 = 1\n for n in 1:size(时间戳, 1)\n 时间戳一行 = filter(!iszero, 时间戳[n, :])\n if !isempty(时间戳一行)\n 天数 = sortednunique(unix2date, 时间戳一行)\n break\n end\n end\n 复利 = get(ENV, \"USE_COMPLEX\", \"0\") == \"1\"\n 收益率 = zero(实际仓位)\n 之前仓位 = copy(记忆仓位)\n 之前盈亏 = zeros(Float32, N)\n @inbounds for t in 1:T\n 当前平均涨幅 = @views mean(涨幅[:, t])\n for n in 1:N\n 当前仓位 = 实际仓位[n, t]\n 仓位变化 = 当前仓位 - 之前仓位[n]\n 买滑点 = fillnan((卖1价[n, t] - 最新价[n, t]) ⧶ 最新价[n, t])\n 卖滑点 = fillnan((最新价[n, t] - 买1价[n, t]) ⧶ 最新价[n, t])\n 交易成本 = fillnan(手续费率[n, t]) * abs(仓位变化)\n 滑点 = ifelse(仓位变化 > 0, 买滑点, -卖滑点) * 仓位变化\n 收益率[n, t] = 之前盈亏[n] - 交易成本 - 滑点\n 之前仓位[n] = 当前仓位\n end\n t < T && for n in 1:N\n 当前仓位 = 实际仓位[n, t]\n 未来涨幅 = fillnan(涨幅[n, t + 1])\n 之前盈亏[n] = 当前仓位 * 未来涨幅\n end\n end\n 倍数 = 年化收益率 = 1f0\n 资金曲线 = ones(Float32, T)\n if 复利\n @inbounds for t in 1:size(实际仓位, 2)\n Δ = @views sum(收益率[:, t]) ⧶ 最大持仓\n 资金曲线[t] = 倍数 = (1 + Δ) * 倍数\n end\n 年化收益率 = 倍数^(240f0 / 天数) - 1\n else\n @inbounds for t in 1:T\n Δ = @views sum(收益率[:, t]) ⧶ 最大持仓\n 资金曲线[t] = 倍数 = 倍数 + Δ\n end\n 年化收益率 = 240f0 * (倍数 - 1f0) / 天数\n end\n 最大回撤, 最大回撤期 = drawdown(资金曲线)\n 夏普率 = sharperatio(资金曲线, 240T / 天数)\n length(记忆收益率) > 10 && empty!(记忆收益率)\n 记忆收益率[objectid(时间戳)] = 收益率\n return 收益率, 资金曲线, 年化收益率, 最大回撤, 夏普率\nend\n\nfunction summarize_train(涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 交易池, 记忆仓位, 实际仓位, 综合评分, 最大持仓)\n 收益率, 资金曲线, 年化收益率, 最大回撤, 夏普率 = \n summarize_core(涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 交易池, 记忆仓位, 实际仓位, 综合评分, 最大持仓)\n 评分模式 = parseenv(\"SCORE\", \"R\")\n if 评分模式 == \"R\" # Return\n 分数 = 年化收益率\n elseif 评分模式 == \"SHARPE\"\n 分数 = 夏普率\n elseif 评分模式 == \"RoMaD\" # Return Over Maximum Drawdown\n 分数 = 年化收益率 ⧶ abs(最大回撤)\n elseif occursin(\"LAR\", 评分模式) # Loss Amplified Return\n λ = Meta.parse(split(评分模式, '_')[2])\n 分数 = sum(x -> amploss(x, λ), 年化收益率)\n elseif occursin(\"IR\", 评分模式) # Information Rank\n nonan(x) = ifelse(isnan(x), zero(x), x)\n 分数 = mean(nonan(corspearman(综合评分[:, t], 涨幅[:, t])) for t in 1:size(实际仓位, 2))\n elseif occursin(\"WR\", 评分模式) # Average Winning Ratio\n 分数 = mean(mean(涨幅[实际仓位[:, t] .> 0, t]) >\n mean(涨幅[交易池[:, t] .> 0, t])\n for t in 1:(size(实际仓位, 2) - 1))\n elseif occursin(\"ACC\", 评分模式) # Accuracy\n 分数 = mean(mean(涨幅[实际仓位[:, t] .> 0, t] .>\n mean(涨幅[交易池[:, t] .> 0, t]))\n for t in 1:(size(实际仓位, 2) - 1))\n end\n @assert !isnan(分数)\n return 分数\nend\n\nfunction summarize_test(涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 交易池, 记忆仓位, 实际仓位, 综合评分, 虚拟信号, 最大持仓)\n 收益率, 资金曲线, 年化收益率, 最大回撤, 夏普率 = summarize_core(涨幅, 时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 交易池, 记忆仓位, 实际仓位, 综合评分, 最大持仓)\n 目录名 = mkpath(产生目录(时间戳, 代码, 年化收益率, 最大回撤, 夏普率))\n @indir 目录名 begin\n 输出每日持股明细(代码, 时间戳, 实际仓位)\n 输出资金和仓位曲线(时间戳, 实际仓位, 资金曲线)\n 输出个股交易记录(时间戳, 代码, 最新价, 买1价, 卖1价, 手续费率, 收益率, 实际仓位)\n 新目录名 = 输出资金曲线(时间戳, 代码, 实际仓位, 收益率, 最大持仓)\n 报告后处理()\n parseenv(\"OUTPUT_POS\", false) && 输出仓位评分信号(代码, 时间戳, 实际仓位, 综合评分, 虚拟信号)\n parseenv(\"OUTPUT_MINPOS\", false) && 输出分钟仓位(代码, 时间戳, 最新价, 实际仓位, 收益率)\n end\n return 年化收益率\nend", "meta": {"hexsha": "a58daea0ff5d51ee53666f6baa1c2e912653f538", "size": 8724, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/backtest.jl", "max_stars_repo_name": "AStupidBear/Backtester.jl", "max_stars_repo_head_hexsha": "5129ad1fb92aefb364b4c728b3fc7df068118955", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backtest.jl", "max_issues_repo_name": "AStupidBear/Backtester.jl", "max_issues_repo_head_hexsha": "5129ad1fb92aefb364b4c728b3fc7df068118955", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-18T00:56:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T04:11:46.000Z", "max_forks_repo_path": "src/backtest.jl", "max_forks_repo_name": "AStupidBear/Backtester.jl", "max_forks_repo_head_hexsha": "5129ad1fb92aefb364b4c728b3fc7df068118955", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:56:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T06:45:15.000Z", "avg_line_length": 36.1991701245, "max_line_length": 138, "alphanum_fraction": 0.4762723521, "num_tokens": 5234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.18452086173064738}} {"text": "module Inference\n\nusing ..Core, ..Core.RandomVariables, ..Utilities\nusing ..Core.RandomVariables: Metadata, _tail, TypedVarInfo, \n islinked, invlink!, getlogp, tonamedtuple\nusing Distributions, Libtask, Bijectors\nusing ProgressMeter, LinearAlgebra\nusing ..Turing: PROGRESS, CACHERESET, AbstractSampler\nusing ..Turing: Model, runmodel!, get_pvars, get_dvars,\n Sampler, SampleFromPrior, SampleFromUniform,\n Selector, AbstractSamplerState\nusing ..Turing: in_pvars, in_dvars, Turing\nusing StatsFuns: logsumexp\nusing Random: GLOBAL_RNG, AbstractRNG\nusing ..Turing.Interface\n\nimport MCMCChains: Chains\nimport AdvancedHMC; const AHMC = AdvancedHMC\nimport ..Turing: getspace\nimport Distributions: sample\nimport ..Core: getchunksize, getADtype\nimport ..Interface: AbstractTransition, sample, step!, sample_init!,\n transitions_init, sample_end!, AbstractSampler, transition_type,\n callback, init_callback, AbstractCallback, psample\n\nexport InferenceAlgorithm,\n Hamiltonian,\n AbstractGibbs,\n GibbsComponent,\n StaticHamiltonian,\n AdaptiveHamiltonian,\n SampleFromUniform,\n SampleFromPrior,\n MH,\n Gibbs, # classic sampling\n HMC,\n SGLD,\n SGHMC,\n HMCDA,\n NUTS, # Hamiltonian-like sampling\n DynamicNUTS,\n IS,\n SMC,\n CSMC,\n PG,\n PIMH,\n PMMH,\n IPMCMC, # particle-based sampling\n assume,\n observe,\n step,\n WelfordVar,\n WelfordCovar,\n NaiveCovar,\n get_var,\n get_covar,\n add_sample!,\n reset!,\n step!\n\n#######################\n# Sampler abstraction #\n#######################\nabstract type AbstractAdapter end\nabstract type InferenceAlgorithm end\nabstract type ParticleInference <: InferenceAlgorithm end\nabstract type Hamiltonian{AD} <: InferenceAlgorithm end\nabstract type StaticHamiltonian{AD} <: Hamiltonian{AD} end\nabstract type AdaptiveHamiltonian{AD} <: Hamiltonian{AD} end\n\ngetchunksize(::T) where {T <: Hamiltonian} = getchunksize(T)\ngetchunksize(::Type{<:Hamiltonian{AD}}) where AD = getchunksize(AD)\ngetADtype(alg::Hamiltonian) = getADtype(typeof(alg))\ngetADtype(::Type{<:Hamiltonian{AD}}) where {AD} = AD\n\n\"\"\"\n mh_accept(H::T, H_new::T, log_proposal_ratio::T) where {T<:Real}\n\nPeform MH accept criteria with log acceptance ratio. Returns a `Bool` for acceptance.\n\nNote: This function is only used in PMMH.\n\"\"\"\nfunction mh_accept(H::T, H_new::T, log_proposal_ratio::T) where {T<:Real}\n return log(rand()) + H_new < H + log_proposal_ratio, min(0, -(H_new - H))\nend\n\n######################\n# Default Transition #\n######################\n\nstruct Transition{T, F<:AbstractFloat} <: AbstractTransition\n θ :: T\n lp :: F\nend\n\nfunction Transition(spl::Sampler, nt::NamedTuple=NamedTuple())\n theta = merge(tonamedtuple(spl.state.vi), nt)\n lp = getlogp(spl.state.vi)\n return Transition{typeof(theta), typeof(lp)}(theta, lp)\nend\n\nfunction additional_parameters(::Type{<:Transition})\n return [:lp]\nend\n\nInterface.transition_type(::Sampler{alg}) where alg = transition_type(alg)\n\n##########################################\n# Internal variable names for MCMCChains #\n##########################################\n\nconst TURING_INTERNAL_VARS = (internals = [\n \"elapsed\",\n \"eval_num\",\n \"lf_eps\",\n \"lp\",\n \"weight\",\n \"le\",\n \"acceptance_rate\",\n \"hamiltonian_energy\",\n \"hamiltonian_energy_error\",\n \"max_hamiltonian_energy_error\",\n \"is_accept\",\n \"log_density\",\n \"n_steps\",\n \"numerical_error\",\n \"step_size\",\n \"nom_step_size\",\n \"tree_depth\",\n \"is_adapt\",\n],)\n\n#########################################\n# Default definitions for the interface #\n#########################################\n\nfunction Interface.sample(\n rng::AbstractRNG,\n model::ModelType,\n alg::AlgType,\n N::Integer;\n kwargs...\n) where {\n ModelType<:Sampleable,\n SamplerType<:AbstractSampler,\n AlgType<:InferenceAlgorithm\n}\n return sample(rng, model, Sampler(alg, model), N; progress=PROGRESS[], kwargs...)\nend\n\nfunction Interface.sample(\n model::ModelType,\n alg::AlgType,\n N::Integer;\n resume_from=nothing,\n kwargs...\n) where {\n ModelType<:Sampleable,\n SamplerType<:AbstractSampler,\n AlgType<:InferenceAlgorithm\n}\n if resume_from === nothing\n return sample(model, Sampler(alg, model), N; progress=PROGRESS[], kwargs...)\n else\n return resume(resume_from, N)\n end\nend\n\n\nfunction Interface.psample(\n model::ModelType,\n alg::AlgType,\n N::Integer,\n n_chains::Integer;\n kwargs...\n) where {\n ModelType<:Sampleable,\n SamplerType<:AbstractSampler,\n AlgType<:InferenceAlgorithm\n}\n return psample(GLOBAL_RNG, model, alg, N, n_chains; progress=false, kwargs...)\nend\n\nfunction Interface.psample(\n rng::AbstractRNG,\n model::ModelType,\n alg::AlgType,\n N::Integer,\n n_chains::Integer;\n kwargs...\n) where {\n ModelType<:Sampleable,\n SamplerType<:AbstractSampler,\n AlgType<:InferenceAlgorithm\n}\n return psample(rng, model, Sampler(alg, model), N, n_chains; progress=false, kwargs...)\nend\n\nfunction Interface.sample_init!(\n ::AbstractRNG,\n model::Model,\n spl::Sampler,\n N::Integer;\n kwargs...\n)\n # Resume the sampler.\n set_resume!(spl; kwargs...)\n\n # Set the parameters to a starting value.\n initialize_parameters!(spl; kwargs...)\nend\n\nfunction Interface.sample_end!(\n ::AbstractRNG,\n ::Model,\n spl::AbstractSampler,\n ::Integer,\n ::Vector{TransitionType};\n kwargs...\n) where {TransitionType<:AbstractTransition}\n # Silence the default API function.\nend\n\nfunction initialize_parameters!(\n spl::AbstractSampler;\n init_theta::Union{Nothing,Array{<:Any,1}}=nothing,\n verbose::Bool=false,\n kwargs...\n)\n # Get `init_theta`\n if init_theta !== nothing\n verbose && @info \"Using passed-in initial variable values\" init_theta\n # Convert individual numbers to length 1 vector; `ismissing(v)` is needed as `size(missing)` is undefined`\n init_theta = [ismissing(v) || size(v) == () ? [v] : v for v in init_theta]\n # Flatten `init_theta`\n init_theta_flat = foldl(vcat, map(vec, init_theta))\n # Create a mask to inidicate which values are not missing\n theta_mask = map(x -> !ismissing(x), init_theta_flat)\n # Get all values\n theta = spl.state.vi[spl]\n @assert length(theta) == length(init_theta_flat) \"Provided initial value doesn't match the dimension of the model\"\n # Update those which are provided (i.e. not missing)\n theta[theta_mask] .= init_theta_flat[theta_mask]\n # Update in `vi`\n spl.state.vi[spl] = theta\n end\nend\n\n\n##########################\n# Chain making utilities #\n##########################\n\nfunction _params_to_array(ts::Vector{T}, spl::Sampler) where {T<:AbstractTransition}\n names = Set{String}()\n dicts = Vector{Dict{String, Any}}()\n\n # Extract the parameter names and values from each transition.\n for t in ts\n nms, vs = flatten_namedtuple(t.θ)\n push!(names, nms...)\n\n # Convert the names and values to a single dictionary.\n d = Dict{String, Any}()\n for (k, v) in zip(nms, vs)\n d[k] = v\n end\n push!(dicts, d)\n end\n \n # Convert the set to an ordered vector so the parameter ordering \n # is deterministic.\n ordered_names = collect(names)\n vals = Matrix{Union{Real, Missing}}(undef, length(ts), length(ordered_names))\n\n # Place each element of all dicts into the returned value matrix.\n for i in eachindex(dicts)\n for (j, key) in enumerate(ordered_names)\n vals[i,j] = get(dicts[i], key, missing)\n end\n end\n\n return ordered_names, vals\nend\n\nfunction flatten_namedtuple(nt::NamedTuple{pnames}) where {pnames}\n vals = Vector{Real}()\n names = Vector{AbstractString}()\n\n for k in pnames\n v = nt[k]\n if length(v) == 1\n flatten(names, vals, string(k), v)\n else\n for (vnval, vn) in zip(v[1], v[2])\n flatten(names, vals, vn, vnval)\n end\n end\n end\n\n return names, vals\nend\n\nfunction flatten(names, value :: AbstractArray, k :: String, v)\n if isa(v, Number)\n name = k\n push!(value, v)\n push!(names, name)\n elseif isa(v, Array)\n for i = eachindex(v)\n if isa(v[i], Number)\n name = string(ind2sub(size(v), i))\n name = replace(name, \"(\" => \"[\");\n name = replace(name, \",)\" => \"]\");\n name = replace(name, \")\" => \"]\");\n name = k * name\n isa(v[i], Nothing) && println(v, i, v[i])\n push!(value, v[i])\n push!(names, name)\n elseif isa(v[i], AbstractArray)\n name = k * string(ind2sub(size(v), i))\n flatten(names, value, name, v[i])\n else\n error(\"Unknown var type: typeof($v[i])=$(typeof(v[i]))\")\n end\n end\n else\n error(\"Unknown var type: typeof($v)=$(typeof(v))\")\n end\n return\nend\n\nind2sub(v, i) = Tuple(CartesianIndices(v)[i])\n\nfunction get_transition_extras(ts::Vector{T}) where T<:AbstractTransition\n # Get the extra field names from the sampler state type.\n # This handles things like :lp or :weight.\n extra_params = additional_parameters(T)\n\n # Get the values of the extra parameters.\n local extra_names\n all_vals = []\n\n # Iterate through each transition.\n for t in ts\n extra_names = String[]\n vals = []\n\n # Iterate through each of the additional field names\n # in the struct.\n for p in extra_params\n # Check whether the field contains a NamedTuple,\n # in which case we need to iterate through each\n # key/value pair.\n prop = getproperty(t, p)\n if prop isa NamedTuple\n for (k, v) in pairs(prop)\n push!(extra_names, string(k))\n push!(vals, v)\n end\n else\n push!(extra_names, string(p))\n push!(vals, prop)\n end\n end\n push!(all_vals, vals)\n end\n\n # Convert the vector-of-vectors to a matrix.\n valmat = [all_vals[i][j] for i in 1:length(ts), j in 1:length(all_vals[1])]\n\n return extra_names, valmat\nend\n\n# Default Chains constructor.\nfunction Chains(\n rng::AbstractRNG,\n model::ModelType,\n spl::Sampler,\n N::Integer,\n ts::Vector{T};\n discard_adapt::Bool=true,\n save_state=false,\n kwargs...\n) where {ModelType<:Sampleable, T<:AbstractTransition}\n # Check if we have adaptation samples.\n if discard_adapt && :n_adapts in fieldnames(typeof(spl.alg))\n ts = ts[(spl.alg.n_adapts+1):end]\n end\n\n # Convert transitions to array format.\n # Also retrieve the variable names.\n nms, vals = _params_to_array(ts, spl)\n\n # Get the values of the extra parameters in each Transition struct.\n extra_params, extra_values = get_transition_extras(ts)\n\n # Extract names & construct param array.\n nms = string.(vcat(nms..., string.(extra_params)...))\n parray = hcat(vals, extra_values)\n\n # If the state field has average_logevidence or final_logevidence, grab that.\n le = missing\n if :average_logevidence in fieldnames(typeof(spl.state))\n le = getproperty(spl.state, :average_logevidence)\n elseif :final_logevidence in fieldnames(typeof(spl.state))\n le = getproperty(spl.state, :final_logevidence)\n end\n\n # Check whether to invlink! the varinfo\n if islinked(spl.state.vi, spl)\n invlink!(spl.state.vi, spl)\n end\n\n # Set up the info tuple.\n info = if save_state\n (range = rng,\n model = model,\n spl = spl)\n else\n NamedTuple()\n end\n\n # Chain construction.\n return Chains(\n parray,\n string.(nms),\n deepcopy(TURING_INTERNAL_VARS);\n evidence=le,\n info=info\n )\nend\n\nfunction save(c::Chains, spl::AbstractSampler, model, vi, samples)\n nt = NamedTuple{(:spl, :model, :vi, :samples)}((spl, model, deepcopy(vi), samples))\n return setinfo(c, merge(nt, c.info))\nend\n\nfunction resume(c::Chains, n_iter::Int; kwargs...)\n @assert !isempty(c.info) \"[Turing] cannot resume from a chain without state info\"\n return sample(\n c.info[:range],\n c.info[:model],\n c.info[:spl],\n n_iter; # this is actually not used\n resume_from=c,\n reuse_spl_n=n_iter,\n kwargs...\n )\nend\n\nfunction set_resume!(\n s::Sampler;\n resume_from::Union{Chains, Nothing}=nothing,\n kwargs...\n)\n # If we're resuming, grab the sampler info.\n if resume_from !== nothing\n s = resume_from.info[:spl]\n end\nend\n\nfunction split_var_str(var_str)\n ind = findfirst(c -> c == '[', var_str)\n inds = Vector{String}[]\n if ind === nothing\n return var_str, inds\n end\n sym = var_str[1:ind-1]\n ind = length(sym)\n while ind < length(var_str)\n ind += 1\n @assert var_str[ind] == '['\n push!(inds, String[])\n while var_str[ind] != ']'\n ind += 1\n if var_str[ind] == '['\n ind2 = findnext(c -> c == ']', var_str, ind)\n push!(inds[end], strip(var_str[ind:ind2]))\n ind = ind2+1\n else\n ind2 = findnext(c -> c == ',' || c == ']', var_str, ind)\n push!(inds[end], strip(var_str[ind:ind2-1]))\n ind = ind2\n end\n end\n end\n return sym, inds\nend\n\n#########################\n# Default sampler state #\n#########################\n\n\"\"\"\nA blank `AbstractSamplerState` that contains only `VarInfo` information.\n\"\"\"\nmutable struct SamplerState{VIType<:VarInfo} <: AbstractSamplerState\n vi :: VIType\nend\n\n#######################################\n# Concrete algorithm implementations. #\n#######################################\n\ninclude(\"hmc.jl\")\ninclude(\"mh.jl\")\ninclude(\"is.jl\")\ninclude(\"AdvancedSMC.jl\")\ninclude(\"gibbs.jl\")\ninclude(\"../contrib/inference/sghmc.jl\")\ninclude(\"../contrib/inference/AdvancedSMCExtensions.jl\")\n\n################\n# Typing tools #\n################\n\nfor alg in (:SMC, :PG, :PMMH, :IPMCMC, :MH, :IS)\n @eval getspace(::$alg{space}) where {space} = space\n @eval getspace(::Type{<:$alg{space}}) where {space} = space\nend\nfor alg in (:HMC, :HMCDA, :NUTS, :SGLD, :SGHMC)\n @eval getspace(::$alg{<:Any, space}) where {space} = space\n @eval getspace(::Type{<:$alg{<:Any, space}}) where {space} = space\nend\ngetspace(::Gibbs) = Tuple{}()\ngetspace(::Type{<:Gibbs}) = Tuple{}()\n\n@inline floatof(::Type{T}) where {T <: Real} = typeof(one(T)/one(T))\n@inline floatof(::Type) = Real\n\n@inline Turing.Core.get_matching_type(spl::Turing.Sampler, vi::Turing.RandomVariables.VarInfo, ::Type{T}) where {T <: AbstractFloat} = floatof(eltype(vi, spl))\n@inline Turing.Core.get_matching_type(spl::Turing.Sampler{<:Hamiltonian}, vi::Turing.RandomVariables.VarInfo, ::Type{TV}) where {T, N, TV <: Array{T, N}} = Array{Turing.Core.get_matching_type(spl, vi, T), N}\n@inline Turing.Core.get_matching_type(spl::Turing.Sampler{<:Union{PG, SMC}}, vi::Turing.RandomVariables.VarInfo, ::Type{TV}) where {T, N, TV <: Array{T, N}} = TArray{T, N}\n\n## Fallback functions\n\n# utility funcs for querying sampler information\nrequire_gradient(spl::Sampler) = false\nrequire_particles(spl::Sampler) = false\n\nassume(spl::Sampler, dist::Distribution) =\nerror(\"Turing.assume: unmanaged inference algorithm: $(typeof(spl))\")\n\nobserve(spl::Sampler, weight::Float64) =\nerror(\"Turing.observe: unmanaged inference algorithm: $(typeof(spl))\")\n\n## Default definitions for assume, observe, when sampler = nothing.\nfunction assume(spl::A,\n dist::Distribution,\n vn::VarName,\n vi::VarInfo) where {A<:Union{SampleFromPrior, SampleFromUniform}}\n\n if haskey(vi, vn)\n r = vi[vn]\n else\n r = isa(spl, SampleFromUniform) ? init(dist) : rand(dist)\n push!(vi, vn, r, dist, spl)\n end\n # NOTE: The importance weight is not correctly computed here because\n # r is genereated from some uniform distribution which is different from the prior\n # acclogp!(vi, logpdf_with_trans(dist, r, istrans(vi, vn)))\n\n r, logpdf_with_trans(dist, r, istrans(vi, vn))\n\nend\n\nfunction assume(spl::A,\n dists::Vector{T},\n vn::VarName,\n var::Any,\n vi::VarInfo) where {T<:Distribution, A<:Union{SampleFromPrior, SampleFromUniform}}\n\n @assert length(dists) == 1 \"Turing.assume only support vectorizing i.i.d distribution\"\n dist = dists[1]\n n = size(var)[end]\n\n vns = map(i -> VarName(vn, \"[$i]\"), 1:n)\n\n if haskey(vi, vns[1])\n rs = vi[vns]\n else\n rs = isa(spl, SampleFromUniform) ? init(dist, n) : rand(dist, n)\n\n if isa(dist, UnivariateDistribution) || isa(dist, MatrixDistribution)\n for i = 1:n\n push!(vi, vns[i], rs[i], dist, spl)\n end\n @assert size(var) == size(rs) \"Turing.assume: variable and random number dimension unmatched\"\n var = rs\n elseif isa(dist, MultivariateDistribution)\n for i = 1:n\n push!(vi, vns[i], rs[:,i], dist, spl)\n end\n if isa(var, Vector)\n @assert length(var) == size(rs)[2] \"Turing.assume: variable and random number dimension unmatched\"\n for i = 1:n\n var[i] = rs[:,i]\n end\n elseif isa(var, Matrix)\n @assert size(var) == size(rs) \"Turing.assume: variable and random number dimension unmatched\"\n var = rs\n else\n @error(\"Turing.assume: unsupported variable container\"); error()\n end\n end\n end\n\n # acclogp!(vi, sum(logpdf_with_trans(dist, rs, istrans(vi, vns[1]))))\n\n var, sum(logpdf_with_trans(dist, rs, istrans(vi, vns[1])))\n\nend\n\n\nobserve(::Nothing,\n dist::T,\n value::Any,\n vi::VarInfo) where T = observe(SampleFromPrior(), dist, value, vi)\n\nfunction observe(spl::A,\n dist::Distribution,\n value::Any,\n vi::VarInfo) where {A<:Union{SampleFromPrior, SampleFromUniform}}\n\n vi.num_produce += one(vi.num_produce)\n Turing.DEBUG && @debug \"dist = $dist\"\n Turing.DEBUG && @debug \"value = $value\"\n\n # acclogp!(vi, logpdf(dist, value))\n logpdf(dist, value)\nend\n\nfunction observe(spl::A,\n dists::Vector{T},\n value::Any,\n vi::VarInfo) where {T<:Distribution, A<:Union{SampleFromPrior, SampleFromUniform}}\n\n @assert length(dists) == 1 \"Turing.observe only support vectorizing i.i.d distribution\"\n dist = dists[1]\n @assert isa(dist, UnivariateDistribution) || \n isa(dist, MultivariateDistribution) \"Turing.observe: vectorizing matrix distribution is not supported\"\n if isa(dist, UnivariateDistribution) # only univariate distributions support broadcast operation (logpdf.) by Distributions.jl\n # acclogp!(vi, sum(logpdf.(Ref(dist), value)))\n sum(logpdf.(Ref(dist), value))\n else\n # acclogp!(vi, sum(logpdf(dist, value)))\n sum(logpdf(dist, value))\n end\n\nend\n\n\n##############\n# Utilities #\n##############\n\ngetspace(spl::Sampler) = getspace(typeof(spl))\ngetspace(::Type{<:Sampler{Talg}}) where {Talg} = getspace(Talg)\n\n\nend # module\n", "meta": {"hexsha": "fb63967283ab57821a37de6b7e7d41216a0aff78", "size": 19400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/inference/Inference.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Turing.jl-fce5fe82-541a-59a6-adf8-730c64b5f9a0", "max_stars_repo_head_hexsha": "1c3bce5a467c27784d1a1b0184e83a4aef571b10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-22T03:43:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-22T03:43:42.000Z", "max_issues_repo_path": "src/inference/Inference.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Turing.jl-fce5fe82-541a-59a6-adf8-730c64b5f9a0", "max_issues_repo_head_hexsha": "955f6c16089ddda3a0e462051aa3d78bae90f785", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inference/Inference.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Turing.jl-fce5fe82-541a-59a6-adf8-730c64b5f9a0", "max_forks_repo_head_hexsha": "955f6c16089ddda3a0e462051aa3d78bae90f785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2609351433, "max_line_length": 207, "alphanum_fraction": 0.6078865979, "num_tokens": 5051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.1844727076557814}} {"text": "\"\"\"\nCode declaring SpectralTimeSeriesCommonWavelengths and their abstract versions.\n\nAuthor: Eric Ford\nCreated: August 2020\n\"\"\"\n\n\"\"\" Abstract type for a time series of spectra that share a common wavelength grid. \"\"\"\nabstract type AbstractSpectralTimeSeriesCommonWavelengths <: AbstractSpectra1D end\n\n\"\"\" Time series of spectra that share a common wavelength grid. \"\"\"\nstruct SpectralTimeSeriesCommonWavelengths{T1<:Real,T2<:Real,T3<:Real,AA1<:AbstractArray{T1,1},AA2<:AbstractArray{T2,2},AA3<:AbstractArray{T3,2},\n AA4<:AbstractArray{UnitRange{Int64},1}, InstT<:AbstractInstrument } <: AbstractSpectralTimeSeriesCommonWavelengths\n λ::AA1\n flux::AA2\n var::AA3\n chunk_map::AA4\n inst::InstT\n metadata::MetadataT\nend\n\nfunction SpectralTimeSeriesCommonWavelengths(λ::A1, flux::A2, var::A3, chunk_map::A4, inst::InstT;\n metadata::MetadataT = MetadataT() ) where {\n T1<:Real, T2<:Real, T3<:Real, A1<:AbstractArray{T1,1}, A2<:AbstractArray{T2,2}, A3<:AbstractArray{T3,2},\n A4<:AbstractArray{UnitRange{Int64},1}, InstT<:AbstractInstrument }\n #println(\"len(λ) = \", length(λ))\n #println(\"size(flux) = \", size(flux))\n @assert length(λ) == size(flux,1)\n @assert length(λ) == size(var,1)\n @assert 1 <= length(λ)\n SpectralTimeSeriesCommonWavelengths{eltype(λ),eltype(flux),eltype(var),typeof(λ),typeof(flux),typeof(var),typeof(chunk_map),typeof(inst)}(λ,flux,var,chunk_map,inst,metadata)\nend\n\n\"\"\" make_spectral_time_series_common_wavelengths_with_selected_times( input, time_idx )\nReturns a SpectralTimeSeriesCommonWavelengths, retaining only those times and spectra specified by time_idx.\n\"\"\"\nfunction make_spectral_time_series_common_wavelengths_with_selected_times(input::STSCWT, time_idx::AbstractVector{T1} ) where { STSCWT<:AbstractSpectralTimeSeriesCommonWavelengths, T1<:Integer }\n @assert minimum(time_idx) >= 1\n @assert maximum(time_idx) <= size(input.flux,2)\n metadata = length(input.metadata) == size(input.flux,2) ? input.metadata[time_idx] : MetadataT()\n SpectralTimeSeriesCommonWavelengths(input.λ, input.flux[:,time_idx], input.var[:,time_idx], input.chunk_map, input.inst, metadata=metadata )\nend\n", "meta": {"hexsha": "71c3fed55a846fdc11e1944e3770f488267cc543", "size": 2188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/types/spectra_timeseries_common_wavelengths.jl", "max_stars_repo_name": "RvSpectML/RvSpectMLTemplate", "max_stars_repo_head_hexsha": "b53d04f48c70f74cdd12500f116e5252322c61e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-14T18:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T18:12:44.000Z", "max_issues_repo_path": "src/types/spectra_timeseries_common_wavelengths.jl", "max_issues_repo_name": "RvSpectML/RvSpectMLTemplate", "max_issues_repo_head_hexsha": "b53d04f48c70f74cdd12500f116e5252322c61e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-10-15T08:21:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T08:19:42.000Z", "max_forks_repo_path": "src/types/spectra_timeseries_common_wavelengths.jl", "max_forks_repo_name": "RvSpectML/RvSpectMLTemplate", "max_forks_repo_head_hexsha": "b53d04f48c70f74cdd12500f116e5252322c61e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-15T07:34:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T19:27:12.000Z", "avg_line_length": 50.8837209302, "max_line_length": 194, "alphanum_fraction": 0.7422303473, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18432007592949032}} {"text": "include(joinpath(\"tasks\", \"task_types.jl\"))\ninclude(joinpath(\"tasks\", \"product_tasks.jl\"))\ninclude(joinpath(\"tasks\", \"identity.jl\"))\ninclude(joinpath(\"tasks\", \"position_around_point.jl\"))\ninclude(joinpath(\"tasks\", \"distance_from_point.jl\"))\ninclude(joinpath(\"tasks\", \"distance_from_sphere_surface.jl\"))\ninclude(joinpath(\"tasks\", \"distance_sphere_to_sphere.jl\"))\ninclude(joinpath(\"tasks\", \"distance_sphere_to_cup.jl\"))\ninclude(joinpath(\"tasks\", \"distance_sphere_to_cylinder.jl\"))\ninclude(joinpath(\"tasks\", \"distance_sphere_to_box.jl\"))\ninclude(joinpath(\"tasks\", \"distance_sphere_to_line.jl\"))\ninclude(joinpath(\"tasks\", \"angular_distance.jl\"))\ninclude(joinpath(\"tasks\", \"angular_position_around_point.jl\"))\ninclude(joinpath(\"tasks\", \"coordinate.jl\"))\ninclude(joinpath(\"tasks\", \"coordinate_distance.jl\"))\ninclude(joinpath(\"tasks\", \"arm\", \"joint_to_link_position.jl\"))\ninclude(joinpath(\"tasks\", \"arm\", \"link_sphere_pair_distance.jl\"))\ninclude(joinpath(\"tasks\", \"arm\", \"link_sphere_position.jl\"))\ninclude(joinpath(\"tasks\", \"arm\", \"link_frame_transform.jl\"))\n\nBase.eltype(::Type{TaskMapX{A,B,S}}) where {A,B,S} = S\n\ndomain_manifold(task_map::Union{TaskMap{M,N},TaskMapT{M,N}}) where {M,N} = M\ncodomain_manifold(task_map::Union{TaskMap{M,N},TaskMapT{M,N}}) where {M,N} = N\ndomain_manifold(task::TaskX) = domain_manifold(task.task_map)\ncodomain_manifold(task::TaskX) = codomain_manifold(task.task_map)\ndomain_manifold(M::Manifold) = M\n\ndomain_coord_rep(task_map::TaskMapT) = domain_coord_rep(task_map.base_map)\ncodomain_coord_rep(task_map::TaskMapT) = codomain_coord_rep(task_map.base_map)\n\ndefault_coord_rep(::TaskX) = ChartRep()\n\nchoose_chart_emb(xme, taskx::Union{TaskX,TaskMapX}, CM, CN) =\n choose_chart_emb(xme, base_task_map(taskx), CM, CN)\nchoose_chart_chart(xm, taskx::Union{TaskX,TaskMapX}, CM, CN) =\n choose_chart_chart(xm, base_task_map(taskx), CM, CN)\n\nchoose_chart_emb(xme, task_map::TaskMap, CM, CN) =\n choose_chart_emb(chart_choice_coord_rep(CN), xme, task_map, CM, CN)\nchoose_chart_chart(xm, task_map::TaskMap, CM, CN) =\n choose_chart_chart(chart_choice_coord_rep(CN), xm, task_map, CM, CN)\n\nchoose_chart_emb(::EmbRep, xme, task_map::TaskMap, CM, CN) =\n choose_chart_emb(EmbRep(), task_map_emb(xme, task_map, CM, CN), CN)\nchoose_chart_emb(::ChartRep, xme, task_map::TaskMap, CM, CN) =\n choose_chart_chart(ChartRep(), task_map_emb_chart(xme, task_map, CM, CN), CN)\nchoose_chart_chart(::EmbRep, xm, task_map::TaskMap, CM, CN) =\n choose_chart_emb(EmbRep(), task_map_chart_emb(xm, task_map, CM, CN), CN)\nchoose_chart_chart(::ChartRep, xm, task_map::TaskMap, CM, CN) =\n choose_chart_chart(ChartRep(), task_map_chart(xm, task_map, CM, CN), CN)\n\nchoose_chart(::EmbRep, xme, taskx::Union{TaskX,TaskMapX}, CM, CN) =\n choose_chart_emb(xme, taskx, CM, CN)\nchoose_chart(::ChartRep, xm, taskx::Union{TaskX,TaskMapX}, CM, CN) =\n choose_chart_chart(xm, taskx, CM, CN)\n\nbase_task_map(task::TaskX) = base_task_map(task.task_map)\nbase_task_map(task_map::TaskMap) = task_map\nbase_task_map(task_map::TaskMapX) = task_map.base_map\n\ntask_map_emb(pme, task_map::TaskMapX, arg...) =\n task_map_emb(domain_coord_rep(task_map), codomain_coord_rep(task_map), pme, task_map, arg...)\ntask_map_emb_chart(pme, task_map::TaskMapX, arg...) =\n task_map_emb_chart(domain_coord_rep(task_map), codomain_coord_rep(task_map),\n pme, task_map, arg...)\ntask_map_chart_emb(pm, task_map::TaskMapX, arg...) =\n task_map_chart_emb(domain_coord_rep(task_map), codomain_coord_rep(task_map),\n pm, task_map, arg...)\ntask_map_chart(pm, task_map::TaskMapX, arg...) =\n task_map_chart(domain_coord_rep(task_map), codomain_coord_rep(task_map), pm, task_map, arg...)\n\ntask_map_emb(pme, task::TaskX, arg...) = task_map_emb(pme, task.task_map, arg...)\ntask_map_emb_chart(pme, task::TaskX, arg...) = task_map_emb_chart(pme, task.task_map, arg...)\ntask_map_chart_emb(pm, task::TaskX, arg...) = task_map_chart_emb(pm, task.task_map, arg...)\ntask_map_chart(pm, task::TaskX, arg...) = task_map_chart(pm, task.task_map, arg...)\n\nbase_task_map_emb(pme, taskx::Union{TaskX,TaskMapX}, arg...) =\n task_map_emb(pme, base_task_map(taskx), arg...)\nbase_task_map_emb_chart(pme, taskx::Union{TaskX,TaskMapX}, arg...) =\n task_map_emb_chart(pme, base_task_map(taskx), arg...)\nbase_task_map_chart_emb(pm, taskx::Union{TaskX,TaskMapX}, arg...) =\n task_map_chart_emb(pm, base_task_map(taskx), arg...)\nbase_task_map_chart(pm, taskx::Union{TaskX,TaskMapX}, arg...) =\n task_map_chart(pm, base_task_map(taskx), arg...)\n\n## No chart specified\n# task_map_emb(::EmbRep, ::EmbRep, pme, task_map::TaskMap) # Should be defined for specific task\n# Throw out given charts as needed; base emb map should be defined\ntask_map_emb(::EmbRep, ::EmbRep, pme, task_map::TaskMap, arg...) =\n task_map_emb(EmbRep(), EmbRep(), pme, task_map)\ntask_map_emb(::CoordinateRep, ::CoordinateRep, pme, task_map) =\n throw(ArgumentError(\"Chart(s) not specified\"))\n\ntask_map_emb_chart(::CoordinateRep, ::CoordinateRep, pme, task_map) =\n throw(ArgumentError(\"Chart not specified\"))\ntask_map_chart_emb(::CoordinateRep, ::CoordinateRep, pm, task_map) =\n throw(ArgumentError(\"Chart not specified\"))\ntask_map_chart(::CoordinateRep, ::CoordinateRep, pm, task_map) =\n throw(ArgumentError(\"Charts not specified\"))\n\n## One chart specified\nfunction task_map_emb(::EmbRep, ::ChartRep, pme, task_map::TaskMap, CN)\n pn = task_map_emb_chart(pme, task_map, CN)\n pne = chart_to_emb(pn, CN)\nend\nfunction task_map_emb(::ChartRep, ::EmbRep, pme, task_map::TaskMap, CM)\n pm = emb_to_chart(pme, CM)\n pne = task_map_chart_emb(pm, task_map, CM)\nend\ntask_map_emb(::ChartRep, ::ChartRep, pme, task_map, C) =\n throw(ArgumentError(\"Second chart not specified\"))\n\nfunction task_map_emb_chart(::EmbRep, ::EmbRep, pme, task_map::TaskMap{M,N},\n CN::Chart{J,N}) where {M,N,J}\n pne = task_map_emb(pme, task_map)\n pn = emb_to_chart(pne, CN)\nend\n# Should be defined for specific task:\n# task_map_emb_chart(::EmbRep, ::ChartRep, pm, task_map::TaskMap, CN) \ntask_map_emb_chart(::ChartRep, ::EmbRep, pme, task_map, C) =\n throw(ArgumentError(\"Second chart not specified\"))\ntask_map_emb_chart(::ChartRep, ::ChartRep, pme, task_map, C) =\n throw(ArgumentError(\"Second chart not specified\"))\n\nfunction task_map_chart_emb(::EmbRep, ::EmbRep, pm, task_map::TaskMap{M,N},\n CM::Chart{I,M}) where {M,N,I}\n pme = chart_to_emb(pm, CM)\n pne = task_map_emb(pme, task_map)\nend\ntask_map_chart_emb(::EmbRep, ::ChartRep, pm, task_map, C) =\n throw(ArgumentError(\"Second chart not specified\"))\n# Should be defined for specific task:\n# task_map_chart_emb(::ChartRep, ::EmbRep, pm, task_map::TaskMap, C) \ntask_map_chart_emb(::ChartRep, ::ChartRep, pm, task_map, C) =\n throw(ArgumentError(\"Second chart not specified\"))\n\ntask_map_chart(::CoordinateRep, ::CoordinateRep, pm, task_map, C) =\n throw(ArgumentError(\"Second chart not specified\"))\n\n## Both charts specified\ntask_map_emb(::EmbRep, ::ChartRep, pme, task_map::TaskMap, CM, CN) =\n task_map_emb(pme, task_map, CN)\ntask_map_emb(::ChartRep, ::EmbRep, pme, task_map::TaskMap, CM, CN) =\n task_map_emb(pme, task_map, CM)\nfunction task_map_emb(::ChartRep, ::ChartRep, pme, task_map::TaskMap, CM, CN)\n pm = emb_to_chart(pme, CM)\n pn = task_map_chart(pm, task_map, CM, CN)\n pne = chart_to_emb(pn, CN)\nend\n\ntask_map_emb_chart(::EmbRep, ::EmbRep, pme, task_map::TaskMap, CM, CN) =\n task_map_emb_chart(pme, task_map, CN)\ntask_map_emb_chart(::EmbRep, ::ChartRep, pme, task_map::TaskMap, CM, CN) =\n task_map_emb_chart(pme, task_map, CN)\nfunction task_map_emb_chart(::ChartRep, ::EmbRep, pme, task_map::TaskMap{M,N}, CM,\n CN::Chart{J,N}) where {M,N,J}\n pm = emb_to_chart(pme, CM)\n pne = task_map_chart_emb(pm, task_map, CM)\n pn = emb_to_chart(pne, CN)\nend\nfunction task_map_emb_chart(::ChartRep, ::ChartRep, pme, task_map::TaskMap, CM, CN)\n pm = emb_to_chart(pme, CM)\n pn = task_map_chart(pm, task_map, CM, CN)\nend\n\ntask_map_chart_emb(::EmbRep, ::EmbRep, pm, task_map::TaskMap, CM, CN) =\n task_map_chart_emb(pm, task_map, CM)\nfunction task_map_chart_emb(::EmbRep, ::ChartRep, pm, task_map::TaskMap{M,N}, CM::Chart{I,M},\n CN) where {M,N,I}\n pme = chart_to_emb(pm, CM)\n pn = task_map_emb_chart(pme, task_map, CN)\n pne = chart_to_emb(pn, CN)\nend\ntask_map_chart_emb(::ChartRep, ::EmbRep, pm, task_map::TaskMap, CM, CN) =\n task_map_chart_emb(pm, task_map, CM)\nfunction task_map_chart_emb(::ChartRep, ::ChartRep, pm, task_map::TaskMap, CM, CN)\n pn = task_map_chart(pm, task_map, CM, CN)\n pne = chart_to_emb(pn, CN)\nend\n\nfunction task_map_chart(::EmbRep, ::EmbRep, pm, task_map::TaskMap{M,N}, CM::Chart{I,M},\n CN::Chart{J,N}) where {M,N,I,J}\n pme = chart_to_emb(pm, CM)\n pne = task_map_emb(pme, task_map)\n pn = emb_to_chart(pne, CN)\nend\nfunction task_map_chart(::EmbRep, ::ChartRep, pm, task_map::TaskMap{M,N}, CM::Chart{I,M},\n CN) where {M,N,I}\n pme = chart_to_emb(pm, CM)\n pn = task_map_emb_chart(pme, task_map, CN)\nend\nfunction task_map_chart(::ChartRep, ::EmbRep, pm, task_map::TaskMap{M,N}, CM,\n CN::Chart{J,N}) where {M,N,J}\n pne = task_map_chart_emb(pm, task_map, CM)\n pn = emb_to_chart(pne, CN)\nend\n# Should be defined for specific task\n# task_map_chart(::ChartRep, ::ChartRep, pm, task_map::TaskMap, CM, CN)\n\nfunction task_differential_map_emb(pme, wme, task_map::TaskMap, arg...)\n pne = task_map_emb(pme, task_map, arg...)\n ∂pne_∂pme = task_jacobian_emb(pme, task_map, arg...)\n wne = ∂pne_∂pme*wme\n pne, wne\nend\n\nfunction task_differential_map_emb_chart(pme, wme, task_map::TaskMap, arg...)\n pn = task_map_emb_chart(pme, task_map, arg...)\n ∂pn_∂pme = task_jacobian_emb_chart(pme, task_map, arg...)\n wn = ∂pn_∂pme*wme\n pn, wn\nend\n\nfunction task_differential_map_chart_emb(pm, wm, task_map::TaskMap, arg...)\n pne = task_map_chart_emb(pm, task_map, arg...)\n ∂pne_∂pm = task_jacobian_chart_emb(pm, task_map, arg...)\n wne = ∂pne_∂pm*wm\n pne, wne\nend\n\nfunction task_differential_map_chart(pm, wm, task_map::TaskMap, arg...)\n pn = task_map_chart(pm, task_map, arg...)\n ∂pn_∂pm = task_jacobian_chart(pm, task_map, arg...)\n wn = ∂pn_∂pm*wm\n pn, wn\nend\n\ntask_differential_map_emb(pme, wme, task::TaskX, arg...) =\n task_differential_map_emb(pme, wme, base_task_map(task), arg...)\ntask_differential_map_emb_chart(pme, wme, task::TaskX, arg...) =\n task_differential_map_emb_chart(pme, wme, base_task_map(task), arg...) \ntask_differential_map_chart_emb(pm, wme, task::TaskX, arg...) =\n task_differential_map_chart_emb(pm, wme, base_task_map(task), arg...)\ntask_differential_map_chart(pm, wme, task::TaskX, arg...) =\n task_differential_map_chart(pm, wme, base_task_map(task), arg...) \n\n## Tangent bundle task maps\nfunction task_map_emb(pme, task_map::TaskMapT{M,N}, arg...) where {M,N}\n xme, vme = tangent_vector_emb_splitview(pme, T{M})\n xne, vne = task_differential_map_emb(xme, vme, task_map.base_map, arg...)\n pne = [xne; vne]\nend\n\nfunction task_map_emb_chart(pme, task_map::TaskMapT{M,N}, arg...) where {M,N}\n xme, vme = tangent_vector_emb_splitview(pme, T{M})\n xn, vn = task_differential_map_emb_chart(xme, vme, task_map.base_map, arg...)\n pn = [xn; vn]\nend\n\nfunction task_map_chart_emb(pm, task_map::TaskMapT{M,N}, arg...) where {M,N}\n xm, vm = tangent_vector_chart_splitview(pm, T{M})\n xne, vne = task_differential_map_chart_emb(xm, vm, task_map.base_map, arg...)\n pne = [xne; vne]\nend\n\nfunction task_map_chart(pm, task_map::TaskMapT{M,N}, arg...) where {M,N}\n xm, vm = tangent_vector_chart_splitview(pm, T{M})\n xn, vn = task_differential_map_chart(xm, vm, task_map.base_map, arg...)\n pn = [xn; vn]\nend\n\n## Jacobians\ntask_jacobian_emb(pme, task_map::TaskMapX, arg...) =\n ForwardDiff.jacobian(pme -> task_map_emb(pme, task_map, arg...), pme)\ntask_jacobian_emb_chart(pme, task_map::TaskMapX, arg...) =\n ForwardDiff.jacobian(pme -> task_map_emb_chart(pme, task_map, arg...), pme)\ntask_jacobian_chart_emb(pm, task_map::TaskMapX, arg...) =\n ForwardDiff.jacobian(pm -> task_map_chart_emb(pm, task_map, arg...), pm)\ntask_jacobian_chart(pm, task_map::TaskMapX, arg...) =\n ForwardDiff.jacobian(pm -> task_map_chart(pm, task_map, arg...), pm)\n\nbase_task_jacobian_emb(pme, taskx::Union{TaskX,TaskMapX}, arg...) = \n task_jacobian_emb(pme, base_task_map(taskx), arg...)\nbase_task_jacobian_emb_chart(pme, taskx::Union{TaskX,TaskMapX}, arg...) = \n task_jacobian_emb_chart(pme, base_task_map(taskx), arg...)\nbase_task_jacobian_chart_emb(pm, taskx::Union{TaskX,TaskMapX}, arg...) = \n task_jacobian_chart_emb(pm, base_task_map(taskx), arg...)\nbase_task_jacobian_chart(pm, taskx::Union{TaskX,TaskMapX}, arg...) = \n task_jacobian_chart(pm, base_task_map(taskx), arg...)\n\ntask_jacobian_emb(pme, task::TaskX, arg...) = task_jacobian_emb(pme, task.task_map, arg...)\ntask_jacobian_emb_chart(pme, task::TaskX, arg...) =\n task_jacobian_emb_chart(pme, task.task_map, arg...)\ntask_jacobian_chart_emb(pm, task::TaskX, arg...) =\n task_jacobian_chart_emb(pm, task.task_map, arg...)\ntask_jacobian_chart(pm, task::TaskX, arg...) = task_jacobian_chart(pm, task.task_map, arg...)\n\n## Jacobian Time Derivatives\nbase_task_jacobian_emb_dot(xme, vme, taskx::Union{TaskX,TaskMapX}, arg...) =\n task_jacobian_emb_dot(xme, vme, base_task_map(taskx), arg...)\nbase_task_jacobian_chart_dot(xm, vm, taskx::Union{TaskX,TaskMapX}, arg...) =\n task_jacobian_chart_dot(xm, vm, base_task_map(taskx), arg...)\n\ntask_jacobian_emb_dot(xme, vme, task::TaskX, arg...) =\n task_jacobian_emb_dot(xme, vme, task.task_map, arg...)\ntask_jacobian_chart_dot(xm, vm, task::TaskX, arg...) =\n task_jacobian_chart_dot(xm, vm, task.task_map, arg...)\n\nfunction task_jacobian_emb_dot(xme, vme, task_map::BaseTaskMap, arg...)\n m, n = embdim(domain_manifold(task_map)), embdim(codomain_manifold(task_map))\n ∇xf = ForwardDiff.jacobian(xme -> SVector{m*n,eltype(xme)}(reshape(task_jacobian_emb(xme,\n task_map, arg...), m*n)), xme)::SArray{Tuple{m*n,m},eltype(xme),2,m*m*n}\n Jfdot_emb = reshape(∇xf*vme, Size(n,m))\nend\n\nfunction task_jacobian_chart_dot(xm, vm, task_map::BaseTaskMap, arg...)\n m, n = dim(domain_manifold(task_map)), dim(codomain_manifold(task_map))\n ∇xf = ForwardDiff.jacobian(xm -> SVector{m*n,eltype(xm)}(reshape(task_jacobian_chart(xm,\n task_map, arg...), m*n)), xm)::SArray{Tuple{m*n,m},eltype(xm),2,m*m*n}\n Jfdot = reshape(∇xf*vm, Size(n,m))\nend\n\n# Default coordinate representations for tasks on Rn\ndomain_coord_rep(::TaskMap{ℝ{m},N}) where {m,N} = EmbRep()\ncodomain_coord_rep(::TaskMap{M,ℝ{n}}) where {M,n} = EmbRep()\n\n# Default home task charts for tasks on Rn\nhome_task_chart(::Task{<:TaskMap{M,ℝ{n}}}) where {M,n} = Chart{1,ℝ{n}}()\nhome_task_chart(::Task{<:TaskMapT{M,ℝ{n}}}) where {M,n} = Chart{1,ℝ{n}}()\nhome_task_chart(::TaskGDS{<:TaskMapT{M,ℝ{n}}}) where {M,n} = Chart{1,ℝ{n}}()\nhome_task_chart(::Task{<:PTM{<:TaskMap{M1,ℝ{n1}},<:TaskMap{M2,ℝ{n2}}}}\n ) where {M1,M2,n1,n2} = Chart{Tuple{1,1},PM{ℝ{n1},ℝ{n2}}}()\nhome_task_chart(::Task{<:PTMT{<:PTM{<:TaskMap{M1,ℝ{n1}},<:TaskMap{M2,ℝ{n2}}}}}\n ) where {M1,M2,n1,n2} = Chart{Tuple{1,1},PM{ℝ{n1},ℝ{n2}}}()\n# Default home task charts for S1\nhome_task_chart(::Task{<:TaskMap{M,S1}}) where M = Chart{Angleπ,S1}()\nhome_task_chart(::Task{<:PTM{<:TaskMap{M1,ℝ{n}},<:TaskMap{M2,S1}}}\n ) where {M1,M2,n} = Chart{Tuple{1,Angleπ},PM{ℝ{n},S1}}()\n\n## Task Weighting\ntask_weight(pn1, task::TaskX, C1) = 1. # Default weighting is 1 everywhere\ntask_weight(xn1, vn1, task::TaskX, C1) = 1.\n", "meta": {"hexsha": "bd95cbc9ce077f3a22946dd3f7bf19965c3e23f6", "size": 15561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tasks.jl", "max_stars_repo_name": "sid-dey/PBDS.jl", "max_stars_repo_head_hexsha": "d4d1d2af0753c60d7082e24c714734eb3ad5fda6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-01-05T01:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:10:45.000Z", "max_issues_repo_path": "src/tasks.jl", "max_issues_repo_name": "sid-dey/PBDS.jl", "max_issues_repo_head_hexsha": "d4d1d2af0753c60d7082e24c714734eb3ad5fda6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-03T03:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T03:39:30.000Z", "max_forks_repo_path": "src/tasks.jl", "max_forks_repo_name": "sid-dey/PBDS.jl", "max_forks_repo_head_hexsha": "d4d1d2af0753c60d7082e24c714734eb3ad5fda6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T23:52:02.000Z", "avg_line_length": 46.5898203593, "max_line_length": 98, "alphanum_fraction": 0.7124863441, "num_tokens": 4919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.18404824920856355}} {"text": "\"\"\"\nCode get from github:\nhttps://github.com/JuliaGPU/CUDA.jl/issues/177#issuecomment-838311843\n\"\"\"\n\nimport Zygote\n\nimport Base: _RepeatInnerOuter\n\n@kernel function repeat_inner_kernel!(a::AbstractArray{<:Any, N}, inner::NTuple{N}, out) where {N}\n inds = @index(Global, NTuple)\n inds_a = ntuple(i -> (inds[i] - 1) ÷ inner[i] + 1, N)\n\n @inbounds out[inds...] = a[inds_a...]\nend\n\nfunction repeat_inner(a::TV, inner) where {TV<:AbstractArray}\n out = TV(undef, inner .* size(a))\n\n kernel! = if out isa CuArray\n repeat_inner_kernel!(CUDADevice(), 512)\n else\n repeat_inner_kernel!(CPU(), Threads.nthreads())\n end\n\n ev = kernel!(a, inner, out, ndrange=size(out))\n wait(ev)\n return out\nend\n# Non-cached coherent loads\n@kernel function repeat_outer_kernel!(a::AbstractArray{<:Any, N}, sa::NTuple{N}, outer::NTuple{N}, out) where {N}\n inds = @index(Global, NTuple)\n inds_a = ntuple(i -> (inds[i] - 1) % sa[i] + 1, N)\n\n @inbounds out[inds...] = a[inds_a...]\nend\n\nfunction repeat_outer(a::TV, outer) where {TV<:AbstractArray}\n out = TV(undef, outer .* size(a))\n\n kernel! = if out isa CuArray\n repeat_outer_kernel!(CUDADevice(), 512)\n else\n repeat_outer_kernel!(CPU(), Threads.nthreads())\n end\n\n ev = kernel!(a, size(a), outer, out, ndrange=size(out))\n wait(ev)\n return out\nend\n\n\n# Overload methods used by `Base.repeat`.\n# No need to implement `repeat_inner_outer` since this is implemented in `Base` as\n# `repeat_outer(repeat_inner(arr, inner), outer)`.\nfunction _RepeatInnerOuter.repeat_inner(a::CuArray{<:Any, N}, dims::NTuple{N}) where {N}\n return repeat_inner(a, dims)\nend\n\nfunction _RepeatInnerOuter.repeat_outer(a::CuArray{<:Any, N}, dims::NTuple{N}) where {N}\n return repeat_outer(a, dims)\nend\n\nfunction _RepeatInnerOuter.repeat_outer(a::CuVector, dims::Tuple{Any})\n return repeat_outer(a, dims)\nend\n\nfunction _RepeatInnerOuter.repeat_outer(a::CuMatrix, dims::NTuple{2, Any})\n return repeat_outer(a, dims)\nend\n\n### Adjoint implementation for `repeat`\n@kernel function repeat_adjoint_gpu_kernel!(\n Δ::AbstractArray{T},\n inner::NTuple,\n outer::NTuple,\n out::AbstractArray{T},\n outsize::NTuple{N}\n) where {N, T<:Real}\n dest_inds = @index(Global, NTuple)\n src_inds = ntuple(i -> mod1((dest_inds[i] - 1) ÷ inner[i] + 1, outsize[i]), N)\n CUDA.@atomic out[src_inds...] += Δ[dest_inds...]\nend;\n\n# FIXME: not threadsafe atm!!! And therefore not used anywhere (we only overload) the\n# adjoint for `CuArray`. But if we have something like `@atomic_addindex!`\n# from https://github.com/JuliaLang/julia/pull/37683, we'd be golden.\n@kernel function repeat_adjoint_cpu_kernel!(\n Δ::AbstractArray,\n inner::NTuple,\n outer::NTuple,\n out::AbstractArray,\n outsize::NTuple{N}\n) where {N}\n dest_inds = @index(Global, NTuple)\n src_inds = ntuple(i -> mod1((dest_inds[i] - 1) ÷ inner[i] + 1, outsize[i]), N)\n # FIXME: make threadsafe\n out[src_inds...] += Δ[dest_inds...]\nend;\n\nfunction repeat_adjoint(\n x,\n Δ::AbstractArray{<:Any, N},\n inner::NTuple{N},\n outer::NTuple{N}\n) where {N}\n out = zero(x)\n\n kernel! = if out isa CuArray\n repeat_adjoint_gpu_kernel!(CUDADevice(), 512)\n else\n repeat_adjoint_cpu_kernel!(CPU(), Threads.nthreads())\n end\n\n ev = kernel!(Δ, inner, outer, out, size(out), ndrange=size(Δ))\n wait(ev)\n\n return out\nend;\n\n\nZygote.@adjoint function _RepeatInnerOuter.repeat_inner_outer(xs::AbstractArray, inner::Nothing, outer::Nothing)\n return xs, Δ -> (Δ, )\nend\nZygote.@adjoint function _RepeatInnerOuter.repeat_inner_outer(\n xs::AbstractArray,\n inner::Nothing,\n outer::NTuple{N}\n) where {N}\n inner_new = ntuple(_ -> 1, N)\n return (\n _RepeatInnerOuter.repeat_outer(xs, outer),\n Δ -> (repeat_adjoint(xs, Δ, inner_new, outer), )\n )\nend\nZygote.@adjoint function _RepeatInnerOuter.repeat_inner_outer(\n xs::AbstractArray,\n inner::NTuple{N},\n outer::Nothing\n) where {N}\n outer_new = ntuple(_ -> 1, N)\n return (\n _RepeatInnerOuter.repeat_inner(xs, inner),\n Δ -> (repeat_adjoint(xs, Δ, inner, outer_new), )\n )\nend\nZygote.@adjoint function _RepeatInnerOuter.repeat_inner_outer(\n xs::AbstractArray,\n inner::NTuple{N},\n outer::NTuple{N}\n) where {N}\n return (\n _RepeatInnerOuter.repeat_outer(_RepeatInnerOuter.repeat_inner(xs, inner), outer),\n Δ -> (repeat_adjoint(xs, Δ, inner, outer), )\n )\nend\n\n# We need to stop Zygote from using the rule implemented in\n# https://github.com/FluxML/Zygote.jl/blob/d5be4d5ca80e79278d714eaac15ca71904a262e3/src/lib/array.jl#L149-L163\n# We stop this adjoint from triggering, and then call the underlying `repeat_inner_outer`.\n# Unfortunately we need to replicate the body of `_RepeatInnerOuter.repeat` since we can't do `Zygote.pullback`\n# for kwargs.\nZygote.@adjoint function Base.repeat(arr::CuArray; inner = nothing, outer = nothing)\n _RepeatInnerOuter.check(arr, inner, outer)\n arr, inner, outer = _RepeatInnerOuter.resolve(arr, inner, outer)\n return Zygote.pullback(_RepeatInnerOuter.repeat_inner_outer, arr, inner, outer)\nend\n", "meta": {"hexsha": "9c988e7d5f4f88aa2ba5873b8b38948e2cae39e8", "size": 5144, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RL/cuda/repeat.jl", "max_stars_repo_name": "pitmonticone/SeaPearl.jl", "max_stars_repo_head_hexsha": "0c0ca5ec5cce81515acd202ea2d87c985c0c3fea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RL/cuda/repeat.jl", "max_issues_repo_name": "pitmonticone/SeaPearl.jl", "max_issues_repo_head_hexsha": "0c0ca5ec5cce81515acd202ea2d87c985c0c3fea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RL/cuda/repeat.jl", "max_forks_repo_name": "pitmonticone/SeaPearl.jl", "max_forks_repo_head_hexsha": "0c0ca5ec5cce81515acd202ea2d87c985c0c3fea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.619047619, "max_line_length": 113, "alphanum_fraction": 0.6788491446, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18389260723565776}} {"text": "\n# This file is part of UnitSystems.jl\n# It is licensed under the MIT license\n# UnitSystems Copyright (C) 2021 Michael Reed\n# _ _ _\n# | | | | | |\n# ___| |__ __ _| | ___ __ __ ___ ____ _| | __ _\n# / __| '_ \\ / _` | |/ / '__/ _` \\ \\ / / _` | |/ _` |\n# | (__| | | | (_| | <| | | (_| |\\ V / (_| | | (_| |\n# \\___|_| |_|\\__,_|_|\\_\\_| \\__,_| \\_/ \\__,_|_|\\__,_|\n#\n# https://github.com/chakravala\n# https://crucialflow.com\n\nexport deka,hecto,kilo,mega,giga,tera,peta,exa,zetta,yotta\nexport deci,centi,milli,micro,nano,pico,femto,atto,zepto,yocto\nexport byte,kibi,mebi,gibi,tebi,pebi,exbi,zebi,yobi\n\nexport slug, ft, KJ1990, KJ2014, RK1990, RK2014, mₑ1990, mₑ2014, temp, units, °R, T₀, eV\nexport slugs, kilograms, lbm, meters, feet, rankine, kelvin, moles, molecules, universal\nexport Universe, UnitSystem, US, universe, HOUR, DAY, th, lc, mc, tcq, lcq, mcq\nexport similitude, 𝟙, F, M, L, T, Q, Θ, N, J, A, Λ, C, sackurtetrode\nexport °R, τ, 𝟏𝟎, 𝟐, 𝟑, 𝟓, nm, 𝟏, mₑ, μ₀, Mᵤ, Rᵤ, αG, GG, slug, ħ, μₚₑ, αL, 𝟕, 𝟏𝟏, 𝟏𝟗, 𝟒𝟑\n\nconst EMU2019,ESU2019,stiffness = EMU,ESU,fluence\n\n# == Metric is different\nconst eV = electronvolt(SI2019)\nconst κ = einstein(SI2019)\nconst σ = stefan(SI2019) #\nconst μB = magneton(SI2019) #\nconst ε₀ = vacuumpermittivity(SI2019) #\nconst kₑ = electrostatic(SI2019) #\nconst mₚ = protonmass(SI2019)\nconst mᵤ = atomicmass(SI2019)\nconst 𝔉 = faraday(SI2019) #\nconst Φ₀ = magneticfluxquantum(SI2019) #\nconst Z₀ = vacuumimpedance(SI2019) #\nconst G₀ = conductancequantum(SI2019) #\nconst Eₕ = hartree(SI2019)\nconst a₀ = bohr(SI2019)\nconst rₑ = electronradius(SI2019)\nconst RH,Ry = R∞*mₚ/(electronmass(SI2019)+mₚ),𝘩*𝘤*R∞\n\nconst ℓP = length(PlanckGauss,SI2019)\nconst tP = time(PlanckGauss,SI2019)\nconst TP = temperature(PlanckGauss,SI2019)\n\nconst lS = length(Stoney,SI2019)\nconst tS = time(Stoney,SI2019)\nconst mS = mass(Stoney,SI2019)\nconst qS = charge(Stoney,SI2019)\n\nconst lA = length(Hartree,SI2019)\nconst tA = time(Hartree,SI2019)\nconst mA = mass(Hartree,SI2019)\nconst qA = charge(Hartree,SI2019)\n\nconst lQCD = length(QCD,SI2019)\nconst tQCD = time(QCD,SI2019)\nconst mQCD = mass(QCD,SI2019)\n\n# non standard units\n\nconst BTU = thermalunit(British)\nconst BTUftlb = thermalunit(British) # BTU⋅ft⁻¹⋅lb⁻¹\nconst BTUJ = thermalunit(SI2019) # BTU⋅J⁻¹\nconst HP = horsepower(Metric)\nconst gal = gallon(Metric)\nconst kcal = kilocalorie(SI2019)\nconst cal = calorie(SI2019)\nconst universal = molargas\n\n# constant aliases\n\nconst US,mpe, meu, mpu, ainv, aG = UnitSystem,μₚₑ, μₑᵤ, μₚᵤ, αinv, αG\nconst Mu,Ru,SB,hh,cc,m0,e0,ke,me,mp,mu,ee,FF,Z0,G0,Eh,a0,re,g0,lP,aL,ϵ₀ = Mᵤ,Rᵤ,σ,𝘩,𝘤,μ₀,ε₀,kₑ,mₑ,mₚ,mᵤ,𝘦,𝔉,Z₀,G₀,Eₕ,a₀,rₑ,g₀,ℓP,αL,ε₀\nexport κ, G, GG, NA, kB, Rᵤ, σ, 𝘩, ħ, 𝘤, μ₀, ε₀, kₑ, mₑ, mₚ, mᵤ, 𝘦, 𝔉, Φ₀, Z₀, G₀, Eₕ, R∞, a₀, rₑ, KJ, RK, Ru, SB, hh, cc, m0, e0, ke, me, mp, mu, ee, FF, Z0, G0, Eh, a0, re, μB\nexport αG, αinv, μₚₑ, μₑᵤ, μₚᵤ, mpe, meu, mpu, mP, δμ₀, Mᵤ, Mu, RH, Ry, ΔνCs, Kcd, ainv\nexport cal, kcal, calₜₕ, kcalₜₕ, calᵢₜ, kcalᵢₜ, ℓP, g₀, g0, atm, lbm, BTUJ, BTUftlb, aG\nexport lP, tP, TP, lS, tS, mS, qS, lA, tA, mA, qA, lQCD, tQCD, mQCD, ϵ₀, αL, aL\n\n@doc \"\"\"\n Constant{D} <: Real\n\nNumerical constant `D` used in `UnitSystem` derivations.\n```Julia\njulia> Constant(100)\n$(Constant(100))\n```\nCan be multiplied, added, subtracted, and so on.\n\"\"\" Constant\n\n# engineering unit systems docs\n\n@doc \"\"\"\n Metric = MetricSystem(milli,𝟐*τ/𝟏𝟎^7)\n\nStandard `Metric` system based on exact `molarmass` and `vacuumpermeability`.\n\n```Julia\njulia> boltzmann(Metric) # J⋅K⁻¹\n$(boltzmann(Metric))\n\njulia> planckreduced(Metric) # J⋅s⋅rad⁻¹\n$(planckreduced(Metric))\n\njulia> lightspeed(Metric) # m⋅s⁻¹\n$(lightspeed(Metric))\n\njulia> vacuumpermeability(Metric) # H⋅m⁻¹\n$(vacuumpermeability(Metric))\n\njulia> electronmass(Metric) # kg\n$(electronmass(Metric))\n\njulia> molarmass(Metric) # kg⋅mol⁻¹\n$(molarmass(Metric))\n\njulia> luminousefficacy(Metric) # lm⋅W⁻¹\n$(luminousefficacy(Metric))\n```\n\"\"\" Metric, MKS\n\n@doc \"\"\"\n SI2019 = MetricSystem(Mᵤ,μ₀)\n\nSysteme International d'Unites based on approximate `molarmass` and `vacuumpermeability`.\n\n```Julia\njulia> boltzmann(SI2019) # J⋅K⁻¹\n$(boltzmann(SI2019))\n\njulia> planckreduced(SI2019) # J⋅s⋅rad⁻¹\n$(planckreduced(SI2019))\n\njulia> lightspeed(SI2019) # m⋅s⁻¹\n$(lightspeed(SI2019))\n\njulia> vacuumpermeability(SI2019) # H⋅m⁻¹\n$(vacuumpermeability(SI2019))\n\njulia> electronmass(SI2019) # kg\n$(electronmass(SI2019))\n\njulia> molarmass(SI2019) # kg⋅mol⁻¹\n$(molarmass(SI2019))\n\njulia> luminousefficacy(SI2019) # lm⋅W⁻¹\n$(luminousefficacy(SI2019))\n```\n\"\"\" SI2019, SI\n\n@doc \"\"\"\n MetricEngineering = MetricSystem(milli,𝟐*τ/𝟏𝟎^7,Rᵤ,g₀)\n\nStandard `MetricEngineering` system based on kilogram and kilopond (kilogram-force) units.\n\n```Julia\njulia> boltzmann(MetricEngineering) # kgf⋅m⋅K⁻¹\n$(boltzmann(MetricEngineering))\n\njulia> planckreduced(MetricEngineering) # kgf⋅m⋅s⋅rad⁻¹\n$(planckreduced(MetricEngineering))\n\njulia> lightspeed(MetricEngineering) # m⋅s⁻¹\n$(lightspeed(MetricEngineering))\n\njulia> vacuumpermeability(MetricEngineering) # kgf⋅s²⋅C⁻²\n$(vacuumpermeability(MetricEngineering))\n\njulia> electronmass(MetricEngineering) # kg\n$(electronmass(MetricEngineering))\n\njulia> molarmass(MetricEngineering) # kg⋅mol⁻¹\n$(molarmass(MetricEngineering))\n\njulia> luminousefficacy(MetricEngineering) # lm⋅s⋅m⁻¹⋅kgf⁻¹\n$(luminousefficacy(MetricEngineering))\n\njulia> gravity(MetricEngineering) # kg⋅m⋅kgf⁻¹⋅s⁻²\n$(gravity(MetricEngineering))\n```\n\"\"\" MetricEngineering, ME\n\n@doc \"\"\"\n SI2019Engineering = MetricSystem(Mᵤ,μ₀,Rᵤ,g₀)\n\nSysteme International d'Unites based on kilogram and kilopond (kilogram-force) units.\n\n```Julia\njulia> boltzmann(SI2019Engineering) # kgf⋅m⋅K⁻¹\n$(boltzmann(SI2019Engineering))\n\njulia> planckreduced(SI2019Engineering) # kgf⋅m⋅s⋅rad⁻¹\n$(planckreduced(SI2019Engineering))\n\njulia> lightspeed(SI2019Engineering) # m⋅s⁻¹\n$(lightspeed(SI2019Engineering))\n\njulia> vacuumpermeability(SI2019Engineering) # kgf⋅s²⋅C⁻²\n$(vacuumpermeability(SI2019Engineering))\n\njulia> electronmass(SI2019Engineering) # kg\n$(electronmass(SI2019Engineering))\n\njulia> molarmass(SI2019Engineering) # kg⋅mol⁻¹\n$(molarmass(SI2019Engineering))\n\njulia> luminousefficacy(SI2019Engineering) # lm⋅s⋅m⁻¹⋅kgf⁻¹\n$(luminousefficacy(SI2019Engineering))\n\njulia> gravity(SI2019Engineering) # kg⋅m⋅kgf⁻¹⋅s⁻²\n$(gravity(SI2019Engineering))\n```\n\"\"\" SI2019Engineering, SIE\n\n@doc \"\"\"\n SI1976 = MetricSystem(milli,𝟐*τ/𝟏𝟎^7,8.31432)\n\nReference `UnitSystem` with universal gas constant of `8.31432` from 1976 standard atmosphere.\n\n```Julia\njulia> boltzmann(SI1976) # J⋅K⁻¹\n$(boltzmann(SI1976))\n\njulia> planckreduced(SI1976) # J⋅s⋅rad⁻¹\n$(planckreduced(SI1976))\n\njulia> lightspeed(SI1976) # m⋅s⁻¹\n$(lightspeed(SI1976))\n\njulia> vacuumpermeability(SI1976) # H⋅m⁻¹\n$(vacuumpermeability(SI1976))\n\njulia> electronmass(SI1976) # kg\n$(electronmass(SI1976))\n\njulia> molarmass(SI1976) # kg⋅mol⁻¹\n$(molarmass(SI1976))\n\njulia> luminousefficacy(SI1976) # lm⋅W⁻¹\n$(luminousefficacy(SI1976))\n```\n\"\"\" SI1976\n\n@doc \"\"\"\n CODATA = ConventionalSystem(RK2014,KJ2014,Rᵤ2014)\n\nReference `UnitSystem` based on Committee on Data of the International Science Council.\n\n```Julia\njulia> josephson(CODATA) # Hz⋅V⁻¹\n$(josephson(CODATA))\n\njulia> klitzing(CODATA) # Ω\n$(klitzing(CODATA))\n\njulia> boltzmann(CODATA) # J⋅K⁻¹\n$(boltzmann(CODATA))\n\njulia> planckreduced(CODATA) # J⋅s⋅rad⁻¹\n$(planckreduced(CODATA))\n\njulia> lightspeed(CODATA) # m⋅s⁻¹\n$(lightspeed(CODATA))\n\njulia> vacuumpermeability(CODATA) # H⋅m⁻¹\n$(vacuumpermeability(CODATA))\n\njulia> electronmass(CODATA) # kg\n$(electronmass(CODATA))\n\njulia> molarmass(CODATA) # kg⋅mol⁻¹\n$(molarmass(CODATA))\n\njulia> luminousefficacy(CODATA) # lm⋅W⁻¹\n$(luminousefficacy(CODATA))\n```\n\"\"\" CODATA\n\n@doc \"\"\"\n Conventional = ConventionalSystem(RK1990,KJ2014)\n\nConventional electronic `UnitSystem` with 1990 tuned `josephson` and `klitzing` constants.\n\n```Julia\njulia> josephson(Conventional) # Hz⋅V⁻¹\n$(josephson(Conventional))\n\njulia> klitzing(Conventional) # Ω\n$(klitzing(Conventional))\n\njulia> boltzmann(Conventional) # J⋅K⁻¹\n$(boltzmann(Conventional))\n\njulia> planckreduced(Conventional) # J⋅s⋅rad⁻¹\n$(planckreduced(Conventional))\n\njulia> lightspeed(Conventional) # m⋅s⁻¹\n$(lightspeed(Conventional))\n\njulia> vacuumpermeability(Conventional) # H⋅m⁻¹\n$(vacuumpermeability(Conventional))\n\njulia> electronmass(Conventional) # kg\n$(electronmass(Conventional))\n\njulia> molarmass(Conventional) # kg⋅mol⁻¹\n$(molarmass(Conventional))\n\njulia> luminousefficacy(Conventional) # lm⋅W⁻¹\n$(luminousefficacy(Conventional))\n```\n\"\"\" Conventional\n\n@doc \"\"\"\n International = ElectricSystem(Metric,$Ωᵢₜ,$Vᵢₜ)\n\nInternational `UnitSystem` with United States measurements of `Ωᵢₜ` and `Vᵢₜ`.\n\n```Julia\njulia> resistance(International,Metric) # Ω⋅Ω⁻¹\n$(resistance(International,Metric))\n\njulia> electricpotential(International,Metric) # V⋅V⁻¹\n$(electricpotential(International,Metric))\n\njulia> boltzmann(International) # J⋅K⁻¹\n$(boltzmann(International))\n\njulia> planckreduced(International) # J⋅s⋅rad⁻¹\n$(planckreduced(International))\n\njulia> lightspeed(International) # m⋅s⁻¹\n$(lightspeed(International))\n\njulia> vacuumpermeability(International) # H⋅m⁻¹\n$(vacuumpermeability(International))\n\njulia> electronmass(International) # kg\n$(electronmass(International))\n\njulia> molarmass(International) # kg⋅mol⁻¹\n$(molarmass(International))\n\njulia> luminousefficacy(International) # lm⋅W⁻¹\n$(luminousefficacy(International))\n```\n\"\"\" International\n\n@doc \"\"\"\n InternationalMean = ElectricSystem(Metric,1.00049,1.00034)\n\nInternational `UnitSystem` with mean measurements of `Ωᵢₜ` and `Vᵢₜ`.\n\n```Julia\njulia> resistance(InternationalMean,Metric) # Ω⋅Ω⁻¹\n$(resistance(InternationalMean,Metric))\n\njulia> electricpotential(InternationalMean,Metric) # V⋅V⁻¹\n$(electricpotential(InternationalMean,Metric))\n\njulia> boltzmann(InternationalMean) # J⋅K⁻¹\n$(boltzmann(InternationalMean))\n\njulia> planckreduced(InternationalMean) # J⋅s⋅rad⁻¹\n$(planckreduced(InternationalMean))\n\njulia> lightspeed(InternationalMean) # m⋅s⁻¹\n$(lightspeed(InternationalMean))\n\njulia> vacuumpermeability(InternationalMean) # H⋅m⁻¹\n$(vacuumpermeability(InternationalMean))\n\njulia> electronmass(InternationalMean) # kg\n$(electronmass(InternationalMean))\n\njulia> molarmass(InternationalMean) # kg⋅mol⁻¹\n$(molarmass(InternationalMean))\n\njulia> luminousefficacy(International) # lm⋅W⁻¹\n$(luminousefficacy(International))\n```\n\"\"\" InternationalMean\n\n@doc \"\"\"\n Meridian = EntropySystem(Metric,𝟏,em,em^3,𝟏,τ/𝟐^6/𝟓^7,milli)\n\nModern ideal `Meridian` system defined by France's original `earthmeter` definition.\n\n```Julia\njulia> greatcircle(Meridian) # em\n$(greatcircle(Meridian))\n\njulia> boltzmann(Meridian) # eJ⋅K⁻¹\n$(boltzmann(Meridian))\n\njulia> planckreduced(Meridian) # eJ⋅s⋅rad⁻¹\n$(planckreduced(Meridian))\n\njulia> lightspeed(Meridian) # em⋅s⁻¹\n$(lightspeed(Meridian))\n\njulia> vacuumpermeability(Meridian) # kegf⋅s²⋅eC⁻²\n$(vacuumpermeability(Meridian))\n\njulia> electronmass(Meridian) # keg\n$(electronmass(Meridian))\n\njulia> molarmass(Meridian) # keg⋅eg-mol⁻¹\n$(molarmass(Meridian))\n\njulia> luminousefficacy(Meridian) # lm⋅W⁻¹\n$(luminousefficacy(Meridian))\n```\n\"\"\" Meridian\n\n@doc \"\"\"\n MeridianEngineering = EntropySystem(MetricEngineering,𝟏,em,em^3,𝟏,τ/𝟐^6/𝟓^7/g₀^2,milli)\n\nModern ideal engineering `UnitSystem` variant of the original French `Meridian` system.\n\n```Julia\njulia> greatcircle(MeridianEngineering) # em\n$(greatcircle(MeridianEngineering))\n\njulia> boltzmann(MeridianEngineering) # kegf⋅em⋅K⁻¹\n$(boltzmann(MeridianEngineering))\n\njulia> planckreduced(MeridianEngineering) # kegf⋅em⋅s⋅rad⁻¹\n$(planckreduced(MeridianEngineering))\n\njulia> lightspeed(MeridianEngineering) # em⋅s⁻¹\n$(lightspeed(MeridianEngineering))\n\njulia> vacuumpermeability(MeridianEngineering) # kegf⋅s²⋅eC⁻²\n$(vacuumpermeability(MeridianEngineering))\n\njulia> electronmass(MeridianEngineering) # keg\n$(electronmass(MeridianEngineering))\n\njulia> molarmass(MeridianEngineering) # keg⋅eg-mol⁻¹\n$(molarmass(MeridianEngineering))\n\njulia> luminousefficacy(MeridianEngineering) # lm⋅s⋅m⁻¹⋅kgf⁻¹\n$(luminousefficacy(MeridianEngineering))\n\njulia> gravity(MeridianEngineering) # keg⋅em⋅kegf⁻¹⋅s⁻²\n$(gravity(MeridianEngineering))\n```\n\"\"\" MeridianEngineering\n\n\ncgstext(US,AMP,cgs=eval(US)) = \"\"\"\n```Julia\njulia> boltzmann($US) # erg⋅K⁻¹\n$(boltzmann(cgs))\n\njulia> planckreduced($US) # erg⋅s⋅rad⁻¹\n$(planckreduced(cgs))\n\njulia> lightspeed($US) # cm⋅s⁻¹\n$(lightspeed(cgs))\n\njulia> vacuumpermeability($US) # statH⋅cm⁻¹\n$(vacuumpermeability(cgs))\n\njulia> electronmass($US) # g\n$(electronmass(cgs))\n\njulia> molarmass($US) # g⋅mol⁻¹\n$(molarmass(cgs))\n\njulia> luminousefficacy($US) # lm⋅s⋅erg⁻¹\n$(luminousefficacy(cgs))\n\njulia> rationalization($US)\n$(rationalization(cgs))\n```\n\"\"\"\n\nfor U ∈ (:CGSm,:CGSe,:EMU,:ESU)\n (EU,AMP) = QuoteNode.(U ∉ (:CGSe,:ESU) ? (:EMU,:Bi) : (:ESU,:statA))\n@eval @doc \"\"\"\n $($(QuoteNode(U))) = GaussSystem(Metric,$($EU≠:EMU ? \"(𝟏𝟎*𝘤)^-2\" : \"𝟏\"),𝟐*τ)\n\nCentimetre-gram-second `UnitSystem` variant based on `$($EU)` (non-rationalized).\n\n$(cgstext($(QuoteNode(U)),$AMP))\n\"\"\" $U\n\n#=U ∉ (:CGSm,:CGSe) && @eval @doc \"\"\"\n $(Symbol($(QuoteNode(U)),:2019)) = EntropySystem(SI2019,𝟏,0.01,0.001,𝟏,$($EU≠:EMU ? \"1e3*μ₀/𝘤^2\" : \"1e7*μ₀\"))\n\nCentimetre-gram-second `UnitSystem` variant of tuned `SI2019` based on `$($EU)` (rationalized).\n\n$(cgstext(Symbol($(QuoteNode(U)),:2019),$AMP))\n\"\"\" $(Symbol(U,:2019))=#\nend\n\n#=@doc \"\"\"\n Thomson = GaussSystem(Metric,𝟏,𝟐*τ,𝟏/𝟐)\n\nCentimetre-gram-second `UnitSystem` variant `Thomson` (EMU-Lorentz, non-rationalized).\n\n```Julia\njulia> boltzmann(Thomson) # erg⋅K⁻¹\n$(boltzmann(Thomson))\n\njulia> planckreduced(Thomson) # erg⋅s⋅rad⁻¹\n$(planckreduced(Thomson))\n\njulia> lightspeed(Thomson) # cm⋅s⁻¹\n$(lightspeed(Thomson))\n\njulia> vacuumpermeability(Thomson) # abH⋅cm⁻¹\n$(vacuumpermeability(Thomson))\n\njulia> electronmass(Thomson) # g\n$(electronmass(Thomson))\n\njulia> molarmass(Thomson) # g⋅mol⁻¹\n$(molarmass(Thomson))\n\njulia> luminousefficacy(Thomson) # lm⋅s⋅erg⁻¹\n$(luminousefficacy(Thomson))\n\njulia> rationalization(Thomson)\n$(rationalization(Thomson))\n\njulia> lorentz(Thomson)\n$(lorentz(Thomson))\n```\n\"\"\" Thomson=#\n\n@doc \"\"\"\n Gauss = GaussSystem(Metric,𝟏,𝟐*τ,𝟏𝟎^-2/𝘤)\n\nCentimetre-gram-second `UnitSystem` variant `CGS` (Gauss-Lorentz, non-rationalized).\n\n```Julia\njulia> boltzmann(Gauss) # erg⋅K⁻¹\n$(boltzmann(Gauss))\n\njulia> planckreduced(Gauss) # erg⋅s⋅rad⁻¹\n$(planckreduced(Gauss))\n\njulia> lightspeed(Gauss) # cm⋅s⁻¹\n$(lightspeed(Gauss))\n\njulia> vacuumpermeability(Gauss) # statH⋅cm⁻¹\n$(vacuumpermeability(Gauss))\n\njulia> electronmass(Gauss) # g\n$(electronmass(Gauss))\n\njulia> molarmass(Gauss) # g⋅mol⁻¹\n$(molarmass(Gauss))\n\njulia> luminousefficacy(Gauss) # lm⋅s⋅erg⁻¹\n$(luminousefficacy(Gauss))\n\njulia> rationalization(Gauss)\n$(rationalization(Gauss))\n\njulia> lorentz(Gauss)\n$(lorentz(Gauss))\n```\n\"\"\" Gauss, CGS\n\n@doc \"\"\"\n LorentzHeaviside = GaussSystem(Metric,𝟏,𝟏,centi/𝘤)\n\nCentimetre-gram-second `UnitSystem` variant `HLU` (Heaviside-Lorentz, rationalized).\n\n```Julia\njulia> boltzmann(LorentzHeaviside) # erg⋅K⁻¹\n$(boltzmann(LorentzHeaviside))\n\njulia> planckreduced(LorentzHeaviside) # erg⋅s⋅rad⁻¹\n$(planckreduced(LorentzHeaviside))\n\njulia> lightspeed(LorentzHeaviside) # cm⋅s⁻¹\n$(lightspeed(LorentzHeaviside))\n\njulia> vacuumpermeability(HLU) # hlH⋅cm⁻¹\n$(vacuumpermeability(LorentzHeaviside))\n\njulia> electronmass(LorentzHeaviside) # g\n$(electronmass(LorentzHeaviside))\n\njulia> molarmass(LorentzHeaviside) # g⋅mol⁻¹\n$(molarmass(LorentzHeaviside))\n\njulia> luminousefficacy(LorentzHeaviside) # lm⋅s⋅erg⁻¹\n$(luminousefficacy(LorentzHeaviside))\n\njulia> rationalization(LorentzHeaviside)\n$(rationalization(LorentzHeaviside))\n\njulia> lorentz(LorentzHeaviside)\n$(lorentz(LorentzHeaviside))\n```\n\"\"\" LorentzHeaviside, HLU\n\n@doc \"\"\"\n Kennelly = GaussSystem(Metric,𝟏𝟎^-7,𝟐*τ,𝟏,𝟏,𝟏)\n\nKennelly ? variant `UnitSystem` of the standard `Metric` units ???\n\n```Julia\njulia> boltzmann(Kennelly) # J⋅K⁻¹\n$(boltzmann(Kennelly))\n\njulia> planckreduced(Kennelly) # J⋅s⋅rad⁻¹\n$(planckreduced(Kennelly))\n\njulia> lightspeed(Kennelly) # m⋅s⁻¹\n$(lightspeed(Kennelly))\n\njulia> vacuumpermeability(Kennelly) # H⋅m⁻¹\n$(vacuumpermeability(Kennelly))\n\njulia> electronmass(Kennelly) # kg\n$(electronmass(Kennelly))\n\njulia> molarmass(Kennelly) # kg⋅mol⁻¹\n$(molarmass(Kennelly))\n\njulia> luminousefficacy(Kennelly) # lm⋅W⁻¹\n$(luminousefficacy(Kennelly))\n\njulia> rationalization(Kennelly)\n$(rationalization(Kennelly))\n```\n\"\"\" Kennelly\n\n@doc \"\"\"\n GravitationalMetric = EntropySystem(Metric,𝟏,𝟏,g₀)\n\nStandard `GravitationalMetric` system based on `hyl` and `kilopond` units.\n\n```Julia\njulia> boltzmann(GravitationalMetric) # kgf⋅m⋅K⁻¹\n$(boltzmann(GravitationalMetric))\n\njulia> planckreduced(GravitationalMetric) # kgf⋅m⋅s⋅rad⁻¹\n$(planckreduced(GravitationalMetric))\n\njulia> lightspeed(GravitationalMetric) # m⋅s⁻¹\n$(lightspeed(GravitationalMetric))\n\njulia> vacuumpermeability(GravitationalMetric) # H⋅m⁻¹\n$(vacuumpermeability(GravitationalMetric))\n\njulia> electronmass(GravitationalMetric) # hyl\n$(electronmass(GravitationalMetric))\n\njulia> molarmass(GravitationalMetric) # hyl⋅mol⁻¹\n$(molarmass(GravitationalMetric))\n\njulia> luminousefficacy(GravitationalMetric) # lm⋅s⋅m⁻¹⋅kgf⁻¹\n$(luminousefficacy(GravitationalMetric))\n```\n\"\"\" GravitationalMetric, GM\n\n@doc \"\"\"\n GraviationalSI2019 = EntropySystem(SI2019,𝟏,𝟏,g₀)\n\nGravitational Systeme International d'Unites based on `hyl` and `kilopond` units.\n\n```Julia\njulia> boltzmann(GravitationalSI2019) # kgf⋅m⋅K⁻¹\n$(boltzmann(GravitationalSI2019))\n\njulia> planckreduced(GravitationalSI2019) # kgf⋅m⋅s⋅rad⁻¹\n$(planckreduced(GravitationalSI2019))\n\njulia> lightspeed(GravitationalSI2019) # m⋅s⁻¹\n$(lightspeed(GravitationalSI2019))\n\njulia> vacuumpermeability(GravitationalSI2019) # kgf⋅s²⋅C⁻²\n$(vacuumpermeability(GravitationalSI2019))\n\njulia> electronmass(GravitationalSI2019) # hyl\n$(electronmass(GravitationalSI2019))\n\njulia> molarmass(GravitationalSI2019) # hyl⋅mol⁻¹\n$(molarmass(GravitationalSI2019))\n\njulia> luminousefficacy(GravitationalMetric) # lm⋅s⋅m⁻¹⋅kgf⁻¹\n$(luminousefficacy(GravitationalMetric))\n```\n\"\"\" GravitationalSI2019, GSI, GSI2019\n\n@doc \"\"\"\n GravitationalMeridian = EntropySystem(Metric,𝟏,em,g₀*em^3,𝟏,τ/𝟐^6/𝟓^7/g₀,milli)\n\nGravitational `UnitSystem` variant of the original French `Meridian` unit defintion.\n\n```Julia\njulia> greatcircle(GravitationalMeridian) # em\n$(greatcircle(GravitationalMeridian))\n\njulia> boltzmann(GravitationalMeridian) # kegf⋅em⋅K⁻¹\n$(boltzmann(GravitationalMeridian))\n\njulia> planckreduced(GravitationalMeridian) # kegf⋅em⋅s⋅rad⁻¹\n$(planckreduced(GravitationalMeridian))\n\njulia> lightspeed(GravitationalMeridian) # em⋅s⁻¹\n$(lightspeed(GravitationalMeridian))\n\njulia> vacuumpermeability(GravitationalMeridian) # kegf⋅s²⋅eC⁻²\n$(vacuumpermeability(GravitationalMeridian))\n\njulia> electronmass(GravitationalMeridian) # ehyl\n$(electronmass(GravitationalMeridian))\n\njulia> molarmass(GravitationalMeridian) # ehyl⋅eg-mol⁻¹\n$(molarmass(GravitationalMeridian))\n\njulia> luminousefficacy(GravitationalMeridian) # lm⋅s⋅em⁻¹⋅kegf⁻¹\n$(luminousefficacy(GravitationalMeridian))\n```\n\"\"\" GravitationalMeridian\n\n@doc \"\"\"\n MTS = EntropySystem(SI2019,𝟏,𝟏,kilo)\n\nMetre-tonne-second `UnitSystem` variant of `Metric` system.\n\n```Julia\njulia> boltzmann(MTS) # kJ⋅K⁻¹\n$(boltzmann(MTS))\n\njulia> planckreduced(MTS) # kJ⋅s⋅rad⁻¹\n$(planckreduced(MTS))\n\njulia> lightspeed(MTS) # m⋅s⁻¹\n$(lightspeed(MTS))\n\njulia> vacuumpermeability(MTS) # kH⋅m⁻¹\n$(vacuumpermeability(MTS))\n\njulia> electronmass(MTS) # t\n$(electronmass(MTS))\n\njulia> molarmass(MTS) # t⋅mol⁻¹\n$(molarmass(MTS))\n\njulia> luminousefficacy(MTS) # lm⋅kW⁻¹\n$(luminousefficacy(MTS))\n```\n\"\"\" MTS\n\n@doc \"\"\"\n KKH = EntropySystem(Metric,HOUR,kilo,𝟏)\n\nKilometer-kilogram-hour `UnitSystem` variant of `Metric` system.\n\n```Julia\njulia> boltzmann(KKH) # kg⋅km²⋅h⁻²⋅K⁻¹\n$(boltzmann(KKH))\n\njulia> planckreduced(KKH) # kg⋅km²⋅h⁻¹\n$(planckreduced(KKH))\n\njulia> lightspeed(KKH) # km⋅hr⁻¹\n$(lightspeed(KKH))\n\njulia> vacuumpermeability(KKH) # kg⋅km⋅C⁻²\n$(vacuumpermeability(KKH))\n\njulia> electronmass(KKH) # kg\n$(electronmass(KKH))\n\njulia> molarmass(KKH) # kg⋅mol⁻¹\n$(molarmass(KKH))\n\njulia> luminousefficacy(KKH) # lm⋅h³⋅kg⁻¹⋅km⁻²\n$(luminousefficacy(KKH))\n```\n\"\"\" KKH\n\n@doc \"\"\"\n IAU☉ = EntropySystem(Metric,DAY,au,GM☉/G)\n\nSolar `UnitSystem` defined by International Astronomical Union and `solarmass`.\n\n```Julia\njulia> boltzmann(IAU) # M⊙⋅au²⋅D⁻²⋅K⁻¹\n$(boltzmann(IAU))\n\njulia> planckreduced(IAU) # M⊙⋅au²⋅D⁻¹⋅rad⁻¹\n$(planckreduced(IAU))\n\njulia> lightspeed(IAU) # au⋅D⁻¹\n$(lightspeed(IAU))\n\njulia> vacuumpermeability(IAU) # M⊙⋅au²⋅C⁻²\n$(vacuumpermeability(IAU))\n\njulia> electronmass(IAU) # M⊙\n$(electronmass(IAU))\n\njulia> molarmass(IAU) # M☉⋅mol⁻¹\n$(molarmass(IAU))\n\njulia> luminousefficacy(IAU) # lm⋅D³⋅M☉⁻¹⋅au⁻²\n$(luminousefficacy(IAU))\n\njulia> gaussgravitation(IAU) # D⁻¹\n$(gaussgravitation(IAU))\n```\n\"\"\" IAU☉, IAU\n\n@doc \"\"\"\n IAUE = EntropySystem(Metric,DAY,LD,GME/G)\n\nAstronomical (Earth) `UnitSystem` defined by `lunardistance` around the `earthmass`.\n\n```Julia\njulia> boltzmann(IAUE) # ME⋅LD²⋅D⁻²⋅K⁻¹\n$(boltzmann(IAUE))\n\njulia> planckreduced(IAUE) # ME⋅LD²⋅D⁻¹⋅rad⁻¹\n$(planckreduced(IAUE))\n\njulia> lightspeed(IAUE) # LD⋅D⁻¹\n$(lightspeed(IAUE))\n\njulia> vacuumpermeability(IAUE) # ME⋅LD²⋅C⁻²\n$(vacuumpermeability(IAUE))\n\njulia> electronmass(IAUE) # ME\n$(electronmass(IAUE))\n\njulia> molarmass(IAUE) # ME⋅mol⁻¹\n$(molarmass(IAUE))\n\njulia> luminousefficacy(IAUE) # lm⋅D³⋅ME⁻¹⋅LD⁻²\n$(luminousefficacy(IAUE))\n\njulia> turn(IAU)/gaussianmonth(IAU) # D⁻¹\n$(turn(IAU)/gaussianmonth(IAU))\n```\n\"\"\" IAUE\n\n@doc \"\"\"\n IAUJ = EntropySystem(Metric,DAY,JD,GMJ/G)\n\nAstronomical (Jupiter) `UnitSystem` defined by `jupiterdistance` around the `solarmass`.\n\n```Julia\njulia> boltzmann(IAUJ) # MJ⋅JD²⋅D⁻²⋅K⁻¹\n$(boltzmann(IAUJ))\n\njulia> planckreduced(IAUJ) # MJ⋅JD²⋅D⁻¹⋅rad⁻¹\n$(planckreduced(IAUJ))\n\njulia> lightspeed(IAUJ) # JD⋅D⁻¹\n$(lightspeed(IAUJ))\n\njulia> vacuumpermeability(IAUJ) # MJ⋅JD²⋅C⁻²\n$(vacuumpermeability(IAUJ))\n\njulia> electronmass(IAUJ) # MJ\n$(electronmass(IAUJ))\n\njulia> molarmass(IAUJ) # MJ⋅mol⁻¹\n$(molarmass(IAUJ))\n\njulia> luminousefficacy(IAUJ) # lm⋅D³⋅MJ⁻¹⋅JD⁻²\n$(luminousefficacy(IAUJ))\n\njulia> sqrt(gravitation(IAUJ)*solarmass(IAUJ)/jupiterdistance(IAUJ)^3) # D⁻¹\n$(sqrt(gravitation(IAUJ)*solarmass(IAUJ)/jupiterdistance(IAUJ)^3))\n```\n\"\"\" IAUJ\n\n#=@doc \"\"\"\n Astronomical = AstronomicalSystem(Metric)\n\nAstronomical `UnitSystem` defined by making the `newton` gravitational constant 1.\n\n```Julia\njulia> boltzmann(Astronomical)\n$(boltzmann(Astronomical))\n\njulia> planckreduced(Astronomical)\n$(planckreduced(Astronomical))\n\njulia> lightspeed(Astronomical)\n$(lightspeed(Astronomical))\n\njulia> vacuumpermeability(Astronomical)\n$(vacuumpermeability(Astronomical))\n\njulia> electronmass(Astronomical)\n$(electronmass(Astronomical))\n\njulia> molarmass(Astronomical)\n$(molarmass(Astronomical))\n\njulia> luminousefficacy(Astronomical)\n$(luminousefficacy(Astronomical))\n\njulia> gravitation(Astronomical)\n$(gravitation(Astronomical))\n```\n\"\"\" Astronomical=#\n\n@doc \"\"\"\n Hubble = EntropySystem(Metric,th,𝘤*th,𝟏)\n\nHubble `UnitSystem` defined by `hubble` parameter.\n\n```Julia\njulia> boltzmann(Hubble)\n$(boltzmann(Hubble))\n\njulia> planckreduced(Hubble)\n$(planckreduced(Hubble))\n\njulia> lightspeed(Hubble)\n$(lightspeed(Hubble))\n\njulia> vacuumpermeability(Hubble)\n$(vacuumpermeability(Hubble))\n\njulia> electronmass(Hubble)\n$(electronmass(Hubble))\n\njulia> molarmass(Hubble)\n$(molarmass(Hubble))\n\njulia> luminousefficacy(Hubble)\n$(luminousefficacy(Hubble))\n\njulia> hubble(Hubble)\n$(hubble(Hubble))\n\njulia> cosmological(Hubble)\n$(cosmological(Hubble))\n```\n\"\"\" Hubble\n\n@doc \"\"\"\n Cosmological = EntropySystem(Metric,lc/𝘤,lc,mc)\n\nCosmological scale `UnitSystem` defined by `darkenergydensity`.\n\n```Julia\njulia> boltzmann(Cosmological)\n$(boltzmann(Cosmological))\n\njulia> planckreduced(Cosmological)\n$(planckreduced(Cosmological))\n\njulia> lightspeed(Cosmological)\n$(lightspeed(Cosmological))\n\njulia> vacuumpermeability(Cosmological)\n$(vacuumpermeability(Cosmological))\n\njulia> electronmass(Cosmological)\n$(electronmass(Cosmological))\n\njulia> molarmass(Cosmological)\n$(molarmass(Cosmological))\n\njulia> luminousefficacy(Cosmological)\n$(luminousefficacy(Cosmological))\n\njulia> hubble(Cosmological)\n$(hubble(Cosmological))\n\njulia> cosmological(Cosmological)\n$(cosmological(Cosmological))\n```\n\"\"\" Cosmological\n\n@doc \"\"\"\n CosmologicalQuantum = EntropySystem(Metric,tcq,lcq,mcq)\n\nCosmological quantum scale `UnitSystem` defined by `darkenergydensity`.\n\n```Julia\njulia> boltzmann(CosmologicalQuantum)\n$(boltzmann(CosmologicalQuantum))\n\njulia> planckreduced(CosmologicalQuantum)\n$(planckreduced(CosmologicalQuantum))\n\njulia> lightspeed(CosmologicalQuantum)\n$(lightspeed(CosmologicalQuantum))\n\njulia> vacuumpermeability(CosmologicalQuantum)\n$(vacuumpermeability(CosmologicalQuantum))\n\njulia> electronmass(CosmologicalQuantum)\n$(electronmass(CosmologicalQuantum))\n\njulia> molarmass(CosmologicalQuantum)\n$(molarmass(CosmologicalQuantum))\n\njulia> luminousefficacy(CosmologicalQuantum)\n$(luminousefficacy(CosmologicalQuantum))\n```\n\"\"\" CosmologicalQuantum\n\n@doc \"\"\"\n British = RankineSystem(Metric,ft,slug)\n\nBritish Gravitational `UnitSystem` historically used by Britain and United States.\n\n```Julia\njulia> boltzmann(British) # ft⋅lb⋅°R⁻¹\n$(boltzmann(British))\n\njulia> planckreduced(British) # ft⋅lb⋅s⋅rad⁻¹\n$(planckreduced(British))\n\njulia> lightspeed(British) # ft⋅s⁻¹\n$(lightspeed(British))\n\njulia> vacuumpermeability(British) # slug⋅ft⋅C⁻²\n$(vacuumpermeability(British))\n\njulia> electronmass(British) # slugs\n$(electronmass(British))\n\njulia> molarmass(British) # slug⋅slug-mol⁻¹\n$(molarmass(British))\n\njulia> luminousefficacy(British) # lm⋅s⋅ft⁻¹⋅lb⁻¹\n$(luminousefficacy(British))\n```\n\"\"\" British, BritishGravitational, BG\n\n@doc \"\"\"\n English = RankineSystem(Metric,ft,lb,g₀/ft)\n\nEnglish Engineering `UnitSystem` historically used in the United States of America.\n\n```Julia\njulia> boltzmann(English) # ft⋅lbf⋅°R⁻¹\n$(boltzmann(English))\n\njulia> planckreduced(English) # ft⋅lbf⋅s⋅rad⁻¹\n$(planckreduced(English))\n\njulia> lightspeed(English) # ft⋅s⁻¹\n$(lightspeed(English))\n\njulia> vacuumpermeability(English) # lbm⋅ft⋅C⁻²\n$(vacuumpermeability(English))\n\njulia> electronmass(English) # lbm\n$(electronmass(English))\n\njulia> molarmass(English) # lbm⋅lb-mol⁻¹\n$(molarmass(English))\n\njulia> luminousefficacy(English) # lm⋅s⋅ft⁻¹⋅lbf⁻¹\n$(luminousefficacy(English))\n\njulia> gravity(English) # lbm⋅ft⋅lbf⁻¹⋅s⁻²\n$(gravity(English))\n```\n\"\"\" English, EnglishEngineering, EE\n\n@doc \"\"\"\n Survey = RankineSystem(Metric,ftUS,lb,g₀/ftUS)\n\nEnglish Engineering `UnitSystem` based on the geophysical US survey foot (1200/3937).\n\n```Julia\njulia> boltzmann(Survey) # ftUS⋅lbf⋅°R⁻¹\n$(boltzmann(Survey))\n\njulia> planckreduced(Survey) # ftUS⋅lbf⋅s⋅rad⁻¹\n$(planckreduced(Survey))\n\njulia> lightspeed(Survey) # ftUS⋅s⁻¹\n$(lightspeed(Survey))\n\njulia> vacuumpermeability(Survey) # lbm⋅ftUS⋅C⁻²\n$(vacuumpermeability(Survey))\n\njulia> electronmass(Survey) # lbm\n$(electronmass(Survey))\n\njulia> molarmass(Survey) # lbm⋅lb-mol⁻¹\n$(molarmass(Survey))\n\njulia> luminousefficacy(Survey) # lm⋅s⋅ft⁻¹⋅lbf⁻¹\n$(luminousefficacy(Survey))\n\njulia> gravity(Survey) # lbm⋅ftUS⋅lbf⁻¹⋅s⁻²\n$(gravity(Survey))\n```\n\"\"\" Survey, EnglishUS\n\n@doc \"\"\"\n FPS = RankineSystem(Metric,ft,lb)\n\nAbsolute English `UnitSystem` based on the foot, pound, second, and poundal.\n\n```Julia\njulia> boltzmann(FPS) # ft⋅pdl⋅°R⁻¹\n$(boltzmann(FPS))\n\njulia> planckreduced(FPS) # ft⋅pdl⋅s⋅rad⁻¹\n$(planckreduced(FPS))\n\njulia> lightspeed(FPS) # ft⋅s⁻¹\n$(lightspeed(FPS))\n\njulia> vacuumpermeability(FPS) # lb⋅ft⋅C⁻²\n$(vacuumpermeability(FPS))\n\njulia> electronmass(FPS) # lb\n$(electronmass(FPS))\n\njulia> molarmass(FPS) # lb⋅lb-mol⁻¹\n$(molarmass(FPS))\n\njulia> luminousefficacy(FPS) # lm⋅s³⋅lb⁻¹⋅ft⁻²\n$(luminousefficacy(FPS))\n```\n\"\"\" FPS, AbsoluteEnglish, AE\n\n@doc \"\"\"\n IPS = RankineSystem(Metric,ft/𝟐^2/𝟑,lb*g₀*𝟐^2*𝟑/ft)\n\nBritish Gravitational `UnitSystem` historically used in the United States of America.\n\n```Julia\njulia> boltzmann(IPS) # in⋅lb⋅°R⁻¹\n$(boltzmann(IPS))\n\njulia> planckreduced(IPS) # in⋅lb⋅s⋅rad⁻¹\n$(planckreduced(IPS))\n\njulia> lightspeed(IPS) # in⋅s⁻¹\n$(lightspeed(IPS))\n\njulia> vacuumpermeability(IPS) # slinch⋅in⋅C⁻²\n$(vacuumpermeability(IPS))\n\njulia> electronmass(IPS) # slinch\n$(electronmass(IPS))\n\njulia> molarmass(IPS) # slinch⋅slinch-mol⁻¹\n$(molarmass(IPS))\n\njulia> luminousefficacy(IPS) # lm⋅s⋅in⁻¹⋅lb⁻¹\n$(luminousefficacy(IPS))\n```\n\"\"\" IPS\n\n@doc \"\"\"\n FFF = EntropySystem(Metric,𝟐*𝟕*DAY,fur,𝟐*𝟑^2*𝟓*lb,°R,0,𝟏)\n\nFurlong–firkin–fortnight `FFF` is a humorous `UnitSystem` based on unusal impractical units.\n\n```Julia\njulia> boltzmann(FFF) # fir⋅fur²⋅ftn⁻²⋅F⁻¹\n$(boltzmann(FFF))\n\njulia> planckreduced(FFF) # fir⋅fur²⋅ftn⁻¹⋅rad⁻¹\n$(planckreduced(FFF))\n\njulia> lightspeed(FFF) # fur⋅ftn⁻¹\n$(lightspeed(FFF))\n\njulia> vacuumpermeability(FFF) # fir⋅fur⋅Inf⁻²\n$(vacuumpermeability(FFF))\n\njulia> electronmass(FFF) # fir\n$(electronmass(FFF))\n\njulia> molarmass(FFF) # fir⋅fir-mol⁻¹\n$(molarmass(FFF))\n\njulia> luminousefficacy(FFF) # lm⋅ftn³⋅fir⁻¹⋅fur⁻²\n$(luminousefficacy(FFF))\n```\n\"\"\" FFF\n\n@doc \"\"\"\n MPH = EntropySystem(FPS,HOUR,mi,𝟏)\n\nMile-pound-hour specification based on `FPS` absolute `UnitSystem`.\n\n```Julia\njulia> boltzmann(MPH) # lbf⋅mi²⋅hr⁻²⋅F⁻¹\n$(boltzmann(MPH))\n\njulia> planckreduced(MPH) # lbf⋅mi²⋅hr⁻¹⋅rad⁻¹\n$(planckreduced(MPH))\n\njulia> lightspeed(MPH) # mi⋅hr⁻¹\n$(lightspeed(MPH))\n\njulia> vacuumpermeability(MPH) # lbm⋅mi⋅C⁻²\n$(vacuumpermeability(MPH))\n\njulia> electronmass(MPH) # lbm\n$(electronmass(MPH))\n\njulia> molarmass(MPH) # lbm⋅lb-mol⁻¹\n$(molarmass(MPH))\n\njulia> luminousefficacy(MPH) # lm⋅h³⋅lb⁻¹⋅mi⁻²\n$(luminousefficacy(MPH))\n```\n\"\"\" MPH\n\n@doc \"\"\"\n Nautical = EntropySystem(Metric,HOUR,nm,em^3,𝟏,τ*𝟑^3/𝟐^10/𝟓^12,milli)\n\nNautical miles, kilo-earthgram, hour specification based on `Meridian` definition.\n\n```Julia\njulia> greatcircle(Nautical) # nm\n$(greatcircle(Nautical))\n\njulia> boltzmann(Nautical) # keg⋅nm²⋅hr⁻²⋅K⁻¹\n$(boltzmann(Nautical))\n\njulia> planckreduced(Nautical) # keg⋅nm²⋅hr⁻¹⋅rad⁻¹\n$(planckreduced(Nautical))\n\njulia> lightspeed(Nautical) # nm⋅hr⁻¹\n$(lightspeed(Nautical))\n\njulia> vacuumpermeability(Nautical) # keg⋅nm⋅eC⁻²\n$(vacuumpermeability(Nautical))\n\njulia> electronmass(Nautical) # keg\n$(electronmass(Nautical))\n\njulia> molarmass(Nautical) # keg⋅eg-mol⁻¹\n$(molarmass(Nautical))\n\njulia> luminousefficacy(Nautical) # lm⋅h³⋅keg⁻¹⋅nm⁻²\n$(luminousefficacy(Nautical))\n```\n\"\"\" Nautical\n\n# natural unit system docs\n\ntextunits(U,S) = \"\"\"\n```Julia\njulia> boltzmann($S)\n$(boltzmann(U))\n\njulia> planckreduced($S)\n$(planckreduced(U))\n\njulia> lightspeed($S)\n$(lightspeed(U))\n\njulia> vacuumpermeability($S)\n$(vacuumpermeability(U))\n\njulia> electronmass($S)\n$(electronmass(U))\n```\n\"\"\"\n\n@doc \"\"\"\n Planck = UnitSystem(𝟏,𝟏,𝟏,𝟏,√(𝟐*τ*αG))\n\nPlanck `UnitSystem` with the `electronmass` value `√(4π*αG)` using gravitational coupling.\n\n$(textunits(Planck,:Planck))\n\"\"\" Planck\n\n@doc \"\"\"\n PlanckGauss = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ,√αG)\n\nPlanck (Gauss) `UnitSystem` with `permeability` of `4π` and `electronmass` coupling `√αG`.\n\n$(textunits(PlanckGauss,:PlanckGauss))\n\nThe well known `PlanckGauss` values for `length`, `time`, `mass`, and `temperature` are:\n```Julia\njulia> length(PlanckGauss,Metric) # ℓP\n$(length(PlanckGauss,Metric))\n\njulia> time(PlanckGauss,Metric) # tP\n$(time(PlanckGauss,Metric))\n\njulia> mass(PlanckGauss,Metric) # mP\n$(mass(PlanckGauss,Metric))\n\njulia> temperature(PlanckGauss,Metric) # TP\n$(temperature(PlanckGauss,Metric))\n```\n\"\"\" PlanckGauss\n\n@doc \"\"\"\n Stoney = UnitSystem(𝟏,𝟏/α,𝟏,𝟐*τ,√(αG/α)}\n\nStoney `UnitSystem` with `permeability` of `4π` and `electronmass` coupling `√(αG/α)`.\n\n$(textunits(Stoney,:Stoney))\n\nThe well known `Stoney` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(Stoney,Metric) # lS\n$(length(Stoney,Metric))\n\njulia> time(Stoney,Metric) # tS\n$(time(Stoney,Metric))\n\njulia> mass(Stoney,Metric) # mS\n$(mass(Stoney,Metric))\n\njulia> charge(Stoney,Metric) # qS\n$(charge(Stoney,Metric))\n```\n\"\"\" Stoney\n\n@doc \"\"\"\n Hartree = UnitSystem(𝟏,𝟏,𝟏/α,𝟐*τ*α^2,𝟏)\n\nHartree atomic `UnitSystem` with `lightspeed` of `αinv` and `permeability` of `𝟐*τ*α^2`.\n\n$(textunits(Hartree,:Hartree))\n\nThe well known `Hartree` atomic unit values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(Hartree,Metric) # lA\n$(length(Hartree,Metric))\n\njulia> time(Hartree,Metric) # tA\n$(time(Hartree,Metric))\n\njulia> mass(Hartree,Metric) # mA\n$(mass(Hartree,Metric))\n\njulia> charge(Hartree,Metric) # qA\n$(charge(Hartree,Metric))\n```\n\"\"\" Hartree\n\n@doc \"\"\"\n Rydberg = UnitSystem(𝟏,𝟏,𝟐/α,τ/𝟐*α^2,𝟏/𝟐)\n\nRydberg `UnitSystem` with `lightspeed` of `𝟐/α` and `permeability` of `π*α^2`.\n\n$(textunits(Rydberg,:Rydberg))\n\"\"\" Rydberg\n\n@doc \"\"\"\n Schrodinger = UnitSystem(𝟏,𝟏,𝟏/α,𝟐*τ*α^2,√(αG/α))\n\nSchrodinger `UnitSystem` with `permeability` of `4π/αinv^2` and `electronmass` of `√(αG*αinv)`.\n\n$(textunits(Schrodinger,:Schrodinger))\n\"\"\" Schrodinger\n\n@doc \"\"\"\n Electronic = UnitSystem(𝟏,𝟏/α,𝟏,𝟐*τ,𝟏}\n\nElectronic `UnitSystem` with `planckreduced` of `1/α` and `permeability` of `4π`.\n\n$(textunits(Electronic,:Electronic))\n\"\"\" Electronic\n\n@doc \"\"\"\n Natural = UnitSystem(𝟏,𝟏,𝟏,𝟏,𝟏)\n\nNatural `UnitSystem` with all primary constants having unit value.\n\n$(textunits(Natural,:Natural))\n\nThe well known `Natural` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(Natural,Metric)\n$(length(Natural,Metric))\n\njulia> time(Natural,Metric)\n$(time(Natural,Metric))\n\njulia> mass(Natural,Metric)\n$(mass(Natural,Metric))\n\njulia> charge(Natural,Metric)\n$(charge(Natural,Metric))\n```\n\"\"\" Natural\n\n@doc \"\"\"\n NaturalGauss = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ,𝟏}\n\nNatural (Gauss) `UnitSystem` with the Gaussian `permeability` value of `4π`.\n\n$(textunits(NaturalGauss,:NaturalGauss))\n\"\"\" NaturalGauss\n\n@doc \"\"\"\n QCD = UnitSystem(𝟏,𝟏,𝟏,𝟏,𝟏/μₚₑ)\n\nQunatum chromodynamics `UnitSystem` with `electronmass` of `𝟏/μₚₑ` or `𝟏/$μₚₑ`.\n\n$(textunits(QCD,:QCD))\n\nThe well known `QCD` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(QCD,Metric) # lQCD\n$(length(QCD,Metric))\n\njulia> time(QCD,Metric) # tQCD\n$(time(QCD,Metric))\n\njulia> mass(QCD,Metric) # mQCD\n$(mass(QCD,Metric))\n\njulia> charge(QCD,Metric)\n$(charge(QCD,Metric))\n```\n\"\"\" QCD\n\n@doc \"\"\"\n QCDGauss = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ,𝟏/μₚₑ)\n\nQunatum chromodynamics (Gauss) `UnitSystem` with `electronmass` of `𝟏/μₚₑ`.\n\n$(textunits(QCDGauss,:QCDGauss))\n\nThe well known `QCDGauss` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(QCDGauss,Metric) # lQCD\n$(length(QCDGauss,Metric))\n\njulia> time(QCDGauss,Metric) # tQCD\n$(time(QCDGauss,Metric))\n\njulia> mass(QCDGauss,Metric) # mQCD\n$(mass(QCDGauss,Metric))\n\njulia> charge(QCDGauss,Metric)\n$(charge(QCDGauss,Metric))\n```\n\"\"\" QCDGauss\n\n@doc \"\"\"\n QCDoriginal = UnitSystem(𝟏,𝟏,𝟏,𝟐*τ*α,𝟏/μₚₑ)\n\nQunatum chromodynamics (original) `UnitSystem` with `permeability` of `4π*α`.\n\n$(textunits(QCDoriginal,:QCDoriginal))\n\nThe well known `QCDoriginal` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(QCDoriginal,Metric) # lQCD\n$(length(QCDoriginal,Metric))\n\njulia> time(QCDoriginal,Metric) # tQCD\n$(time(QCDoriginal,Metric))\n\njulia> mass(QCDoriginal,Metric) # mQCD\n$(mass(QCDoriginal,Metric))\n\njulia> charge(QCDoriginal,Metric)\n$(charge(QCDoriginal,Metric))\n```\n\"\"\" QCDoriginal\n", "meta": {"hexsha": "15e0f14ce9565447fbfa7a3dfc874bfb497ebadc", "size": 35183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems.jl", "max_stars_repo_name": "chakravala/UnitSystems.wl", "max_stars_repo_head_hexsha": "21715195698bf2beee05e9b69cd15f4a1497e62e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/systems.jl", "max_issues_repo_name": "chakravala/UnitSystems.wl", "max_issues_repo_head_hexsha": "21715195698bf2beee05e9b69cd15f4a1497e62e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems.jl", "max_forks_repo_name": "chakravala/UnitSystems.wl", "max_forks_repo_head_hexsha": "21715195698bf2beee05e9b69cd15f4a1497e62e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8367208672, "max_line_length": 177, "alphanum_fraction": 0.7260608817, "num_tokens": 14378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.18293282003973224}} {"text": "# define the generative model for the urban pomdp environment\n\n### REWARD MODEL ##################################################################################\n\nfunction POMDPs.reward(pomdp::UrbanPOMDP, s::UrbanState, a::UrbanAction, sp::UrbanState)\n r = 0.\n ego = sp[findfirst(EGO_ID, sp)]\n if is_crash(sp)\n r += pomdp.collision_cost\n end\n if ego.state.posF.s >= get_end(pomdp.env.roadway[pomdp.ego_goal]) &&\n get_lane(pomdp.env.roadway, ego).tag == pomdp.ego_goal\n r += pomdp.goal_reward\n elseif a.acc > 0.\n r += pomdp.action_cost\n else\n r += pomdp.action_cost\n end\n return r\nend\n\n\n### TERMINAL STATES ###############################################################################\n\nfunction POMDPs.isterminal(pomdp::UrbanPOMDP, s::UrbanState)\n ego = s[findfirst(EGO_ID, s)]\n return is_crash(s) || (ego.state.posF.s >= get_end(pomdp.env.roadway[pomdp.ego_goal]) &&\n get_lane(pomdp.env.roadway, ego).tag == pomdp.ego_goal)\nend\n\n\n### TRANSITION MODEL ##############################################################################\n\nfunction POMDPs.gen(::DDNNode{:sp}, pomdp::UrbanPOMDP, s::UrbanState, a::UrbanAction, rng::AbstractRNG)\n # clean dict \n ids = [veh.id for veh in s]\n key_ = deepcopy(keys(pomdp.models))\n for k in key_\n if !(k ∈ ids) && k!=1\n delete!(pomdp.models, k)\n end\n end\n actions = Array{Any}(undef, length(s))\n pomdp.models[1].a = a\n ego_ind = findfirst(EGO_ID, s)\n is_ego_here = ego_ind == nothing ? 0 : 1\n sp = deepcopy(s) #XXX bad\n if rand(rng) < pomdp.car_birth && n_cars(s) < pomdp.max_cars + is_ego_here\n new_car = initial_car(pomdp, sp, rng)\n if can_push(pomdp.env, sp, new_car)\n lane = get_lane(pomdp.env.roadway, new_car)\n route = find_route(pomdp.env, random_route(rng, pomdp.env.roadway, lane))\n pomdp.models[new_car.id] = pomdp.car_models[SVector(route[1], route[end])]\n reset_hidden_state!(pomdp.models[new_car.id])\n push!(sp, new_car)\n end\n end\n if rand(rng) < pomdp.ped_birth && n_pedestrians(s) < pomdp.max_peds\n # println(\"Spawning new pedestrians\")\n new_ped = initial_pedestrian(pomdp, sp, rng)\n # pomdp.models[new_ped.id] = ConstantPedestrian(dt = pomdp.ΔT)#TODO parameterized\n new_ped_cw = get_lane(pomdp.env.roadway, new_ped)\n new_ped_conflict_lanes = get_conflict_lanes(new_ped_cw, pomdp.env.roadway)\n pomdp.models[new_ped.id] = IntelligentPedestrian(dt = pomdp.ΔT, crosswalk=new_ped_cw, conflict_lanes=new_ped_conflict_lanes)\n reset_hidden_state!(pomdp.models[new_ped.id])\n push!(sp, new_ped)\n end\n actions = Array{Any}(undef, length(sp))\n get_actions!(actions, sp, pomdp.env.roadway, pomdp.models)\n tick!(sp, pomdp.env.roadway, actions, pomdp.ΔT)\n clean_scene!(pomdp.env, sp)\n return sp\nend\n\nfunction POMDPModelTools.gen(::DDNOut{(:sp, :o, :r, :info)}, p::UrbanPOMDP, s, a, rng::AbstractRNG)\n return gen(DDNOut(:sp, :o, :r), p, s, a, rng)..., deepcopy(p.models)\nend\n\n#TODO move to helpers\n\nfunction AutomotiveDrivingModels.propagate(veh::Vehicle, a::UrbanAction, roadway::Roadway, Δt::Float64)\n acc = LonAccelDirection(a.acc, 4) #TODO Parameterize\n return propagate(veh, acc, roadway, Δt)\nend\n\n\n### INITIAL STATES ################################################################################\n\nfunction POMDPs.initialstate(pomdp::UrbanPOMDP, rng::AbstractRNG, burn_in::Int64=1)\n scene = initial_scene(pomdp, rng, true)\n for t = 1:burn_in\n scene = gen(DDNOut(:sp), pomdp, scene, UrbanAction(0.), rng)\n end\n clean_scene!(pomdp.env, scene)\n # push! ego after traffic is steady\n ego = initial_ego(pomdp, rng)\n push!(scene, ego)\n clean_scene!(pomdp.env, scene)\n return scene\nend\n\n\nfunction initial_scene(pomdp::UrbanPOMDP, rng::AbstractRNG, no_ego::Bool=false)\n empty_obstacles!(pomdp.env)\n if pomdp.max_obstacles > 0\n for i=1:pomdp.max_obstacles\n sample_obstacle!(pomdp.env, pomdp.obs_dist, rng)\n end\n end\n scene = Scene()\n if !no_ego\n ego = initial_ego(pomdp, rng)\n push!(scene, ego)\n end\n\n # add cars\n for i=1:pomdp.max_cars\n if rand(rng) < pomdp.car_birth && n_cars(scene) < pomdp.max_cars + 1-Int(no_ego)\n new_car = initial_car(pomdp, scene, rng, true)\n if can_push(pomdp.env, scene, new_car)\n push!(scene, new_car)\n lane = get_lane(pomdp.env.roadway, new_car)\n route = find_route(pomdp.env, random_route(rng, pomdp.env.roadway, lane))\n pomdp.models[new_car.id] = pomdp.car_models[SVector(route[1], route[end])]\n reset_hidden_state!(pomdp.models[new_car.id])\n end\n clean_scene!(pomdp.env, scene)\n end\n end\n\n # add pedestrians\n for i=1:pomdp.max_peds\n if rand(rng) < pomdp.ped_birth && n_pedestrians(scene) < pomdp.max_peds # pedestrian appear\n new_ped = initial_pedestrian(pomdp, scene, rng, true)\n # pomdp.models[new_ped.id] = ConstantPedestrian(dt = pomdp.ΔT)#TODO parameterized\n new_ped_cw = get_lane(pomdp.env.roadway, new_ped)\n new_ped_conflict_lanes = get_conflict_lanes(new_ped_cw, pomdp.env.roadway)\n pomdp.models[new_ped.id] = IntelligentPedestrian(dt = pomdp.ΔT, crosswalk=new_ped_cw, conflict_lanes=new_ped_conflict_lanes)\n reset_hidden_state!(pomdp.models[new_ped.id])\n push!(scene, new_ped)\n end\n end\n clean_scene!(pomdp.env, scene)\n return scene\nend\n\nfunction initial_car(pomdp::UrbanPOMDP, scene::Scene, rng::AbstractRNG, first_scene::Bool = false)\n env = pomdp.env\n\n #velocity\n v0 = rand(rng, 4.0:1.0:7.0) #XXX parameterize!\n s0 = 0.\n if first_scene\n lanes = get_lanes(pomdp.env.roadway)\n lanes = delete!(Set(lanes),pomdp.env.roadway[LaneTag(6,1)])\n lane = rand(rng, lanes) # could be precomputed\n s0 = rand(rng, 0.:0.5:get_end(lane))\n else\n lanes = get_start_lanes(pomdp.env.roadway)\n # lanes = delete!(Set(lanes),pomdp.env.roadway[LaneTag(6,1)])\n lane = rand(rng, lanes) # could be precomputed\n end\n initial_posF = Frenet(lane, s0)\n initialstate = VehicleState(initial_posF, env.roadway, v0)\n\n id = next_car_id(pomdp, scene)\n\n return Vehicle(initialstate, pomdp.car_type, id)\nend\n\n\nfunction initial_ego(pomdp::UrbanPOMDP, rng::AbstractRNG)\n posF = Frenet(get_ego_route(pomdp)[1], pomdp.ego_start)\n state = VehicleState(posF, pomdp.env.roadway, 0.)\n return Vehicle(state, pomdp.ego_type, EGO_ID)\nend\n\n\n\"\"\"\n initial_pedestrian(pomdp::UrbanPOMDP, scene::Scene, rng::AbstractRNG)\nCreate a new pedestrian entity at its initial state\n\"\"\"\nfunction initial_pedestrian(pomdp::UrbanPOMDP, scene::Scene, rng::AbstractRNG, first_scene::Bool = false)\n env = pomdp.env\n cw_ind = rand(rng, 1:length(env.params.crosswalk_pos))\n crosswalk_pos = env.params.crosswalk_pos[cw_ind]\n\n # position along the crosswalk\n t0 = rand(rng, Distributions.Uniform(-env.params.crosswalk_width[cw_ind]/2 + 1., env.params.crosswalk_width[cw_ind]/2 - 1.))\n s0 = rand(rng, [0., get_end(env.crosswalks[cw_ind])])\n ϕ0 = float(π)\n if s0 == 0.\n ϕ0 = 0.\n end\n if first_scene\n s0 = rand(rng, Distributions.Uniform(0., get_end(env.crosswalks[cw_ind])))\n end\n\n #velocity\n v0 = rand(rng, Distributions.Uniform(0., env.params.ped_max_speed))\n posF = Frenet(env.crosswalks[cw_ind], s0, t0, ϕ0)\n\n ped_initialstate = VehicleState(posF, env.ped_roadway, v0);\n\n id = next_ped_id(pomdp, scene)\n\n return Vehicle(ped_initialstate, pomdp.ped_type, id)\nend\n\nfunction POMDPs.initialstate_distribution(pomdp::UrbanPOMDP)\n return GenerativeDist(pomdp)\nend\n\n\n\n### Observations ##################################################################################\n\nfunction POMDPs.gen(::DDNNode{:o}, pomdp::UrbanPOMDP, s::UrbanState, a::UrbanAction, sp::UrbanState, rng::AbstractRNG)\n if pomdp.lidar\n return measure_lidar(pomdp, s, a, sp, rng)\n else\n return measure_gaussian(pomdp, s, a, sp, rng)\n end\nend\n\nfunction measure_gaussian(pomdp::UrbanPOMDP, s::UrbanState, a::UrbanAction, sp::UrbanState, rng::AbstractRNG)\n ego = get_ego(sp)\n obs = measure(pomdp.sensor, ego, sp, pomdp.env.roadway, pomdp.env.obstacles)\n o = obs_to_array(pomdp, ego, obs)\n return o \nend\n\nfunction obs_to_array(pomdp::UrbanPOMDP, ego_veh::Vehicle, obs::Vector{Vehicle})\n sorted_vehicles = sort!(obs, by=x->x.id)\n n_features = 4\n n_obstacles = pomdp.max_obstacles\n o = zeros(n_features*(pomdp.max_cars + pomdp.max_peds + n_obstacles + 1))\n ego = ego_veh.state\n o[1] = ego.posG.x\n o[2] = ego.posG.y\n o[3] = ego.posG.θ\n o[4] = ego.v\n pos_off = get_off_the_grid(pomdp)\n for i=2:pomdp.max_cars + pomdp.max_peds + n_obstacles + 1\n o[n_features*i - 3] = pos_off.posG.x - ego.posG.x\n o[n_features*i - 2] = pos_off.posG.y - ego.posG.y\n o[n_features*i - 1] = pos_off.posG.θ\n o[n_features*i] = 0.\n end\n for veh in sorted_vehicles\n if veh.id == EGO_ID\n continue\n end\n if veh.def.class == AgentClass.CAR\n @assert veh.id <= pomdp.max_cars+1 \"$(veh.id)\"\n o[n_features*veh.id - 3] = veh.state.posG.x - ego.posG.x\n o[n_features*veh.id - 2] = veh.state.posG.y - ego.posG.y\n o[n_features*veh.id - 1] = veh.state.posG.θ\n o[n_features*veh.id] = veh.state.v \n end\n if veh.def.class == AgentClass.PEDESTRIAN\n o[n_features*(veh.id - 100 + pomdp.max_cars + 1) - 3] = veh.state.posG.x - ego.posG.x\n o[n_features*(veh.id - 100 + pomdp.max_cars + 1) - 2] = veh.state.posG.y - ego.posG.y\n o[n_features*(veh.id - 100 + pomdp.max_cars + 1) - 1] = veh.state.posG.θ \n o[n_features*(veh.id - 100 + pomdp.max_cars + 1)] = veh.state.v\n end\n end\n for (j,obs) in enumerate(pomdp.env.obstacles)\n o[n_features*(j + pomdp.max_cars + pomdp.max_peds + 1) - 3] = get_width(obs)\n o[n_features*(j + pomdp.max_cars + pomdp.max_peds + 1) - 2] = get_height(obs)\n o[n_features*(j + pomdp.max_cars + pomdp.max_peds + 1) - 1] = get_center(obs).x - ego.posG.x\n o[n_features*(j + pomdp.max_cars + pomdp.max_peds + 1)] = get_center(obs).y - ego.posG.y\n end\n return rescale!(o, pomdp)\nend\n\nfunction POMDPs.convert_s(::Type{Vector{Float64}}, s::UrbanState, pomdp::UrbanPOMDP)\n ego = get_ego(s)\n obs = [veh for veh in s if veh.id != ego]\n svec = obs_to_array(pomdp, ego, obs)\n return svec\nend\n\nfunction n_dims(pomdp::UrbanPOMDP)\n n_features = 4\n n_obstacles = pomdp.max_obstacles\n return n_features*(pomdp.max_cars + pomdp.max_peds + n_obstacles + 1)\nend\n\nfunction POMDPs.initialobs(pomdp::UrbanPOMDP, s::UrbanState, rng::AbstractRNG)\n return gen(DDNNode(:o), pomdp, s, UrbanAction(0.), s, rng::AbstractRNG)\nend\n\nfunction rescale!(o::UrbanObs, pomdp::UrbanPOMDP)\n # rescale\n n_features = 4\n n_obstacles = pomdp.max_obstacles\n max_ego_dist = get_end(pomdp.env.roadway[pomdp.ego_goal])\n o[1] /= max_ego_dist\n o[2] /= max_ego_dist\n o[3] /= pi/2\n o[4] /= pomdp.env.params.speed_limit\n for i=2:pomdp.max_cars + pomdp.max_peds + 1\n o[n_features*i - 3] /= max_ego_dist\n o[n_features*i - 2] /= max_ego_dist\n o[n_features*i - 1] /= pi\n o[n_features*i] /= pomdp.env.params.speed_limit # XXX parameterized\n end\n for i=pomdp.max_cars + pomdp.max_peds + 2:pomdp.max_cars + pomdp.max_peds + 1 + n_obstacles\n o[n_features*i - 3] /= max_ego_dist\n o[n_features*i - 2] /= max_ego_dist\n o[n_features*i - 1] /= max_ego_dist\n o[n_features*i] /= max_ego_dist\n end\n\n return o\nend\n\nfunction unrescale!(o::UrbanObs, pomdp::UrbanPOMDP)\n # unrescale\n n_features = 4\n n_obstacles = pomdp.max_obstacles\n max_ego_dist = get_end(pomdp.env.roadway[pomdp.ego_goal])\n o[1] *= max_ego_dist\n o[2] *= max_ego_dist\n o[3] *= pi/2\n o[4] *= pomdp.env.params.speed_limit\n for i=2:pomdp.max_cars + pomdp.max_peds + 1\n o[n_features*i - 3] *= max_ego_dist\n o[n_features*i - 2] *= max_ego_dist\n o[n_features*i - 1] *= pi\n o[n_features*i] *= pomdp.env.params.speed_limit # XXX parameterized\n end\n for i=pomdp.max_cars + pomdp.max_peds + 2:pomdp.max_cars + pomdp.max_peds + 1 + n_obstacles\n o[n_features*i - 3] *= max_ego_dist\n o[n_features*i - 2] *= max_ego_dist\n o[n_features*i - 1] *= max_ego_dist\n o[n_features*i] *= max_ego_dist\n end\n\n return o\nend\n\nfunction to_global_coordinates!(o::UrbanObs, pomdp::UrbanPOMDP)\n n_features = 4\n n_obstacles = pomdp.max_obstacles\n ego = o[1:n_features]\n for i=2:pomdp.max_cars + pomdp.max_peds + 1\n o[n_features*i - 3] += ego[1]\n o[n_features*i - 2] += ego[2]\n end\n for i=pomdp.max_cars + pomdp.max_peds + 2:pomdp.max_cars + pomdp.max_peds + 1 + n_obstacles\n o[n_features*i - 1] += ego[1] \n o[n_features*i]+= ego[2]\n end\n return o\nend\n\n\nfunction get_normalized_absent_state(pomdp::UrbanPOMDP, ego::Vector{Float64})\n ego_x, ego_y, theta, v = ego\n pos_off = get_off_the_grid(pomdp)\n max_ego_dist = get_end(pomdp.env.roadway[pomdp.ego_goal])\n return [pos_off.posG.x/max_ego_dist - ego_x,\n pos_off.posG.y/max_ego_dist - ego_y,\n pos_off.posG.θ/float(pi),\n 0. ]\nend\n\nfunction measure_lidar(pomdp::UrbanPOMDP, s::UrbanState, a::UrbanAction, sp::UrbanState, rng::AbstractRNG)\n observe!(pomdp.sensor, sp, pomdp.env.roadway, EGO_ID)\n return vcat(pomdp.sensor.ranges/pomdp.sensor.max_range, pomdp.sensor.range_rates/pomdp.env.params.speed_limit)\nend\n\nfunction POMDPs.convert_o(::Type{Vector{Float64}}, o::UrbanObs, pomdp::UrbanPOMDP)\n return o\nend\n\nfunction POMDPs.gen(::DDNOut{(:sp, :o, :r, :info)}, p::UrbanPOMDP, s::UrbanState, a::UrbanAction, rng::AbstractRNG)\n if p.lidar\n return gen(DDNOut(:sp,:o,:r), p, s, a, rng)..., p.sensor\n else\n return gen(DDNOut(:sp,:o,:r), p, s, a, rng)..., nothing\n end\nend\n\n# uncomment for Lidar\n# uncomment for LIDAR observation\n\n#\n# function POMDPs.generate_o(pomdp::OCPOMDP, s::OCState, rng::AbstractRNG)\n# observe!(pomdp.sensor, s, pomdp.env.roadway, EGO_INDEX)\n# return pomdp.sensor\n# end\n#\n# function POMDPs.convert_o(::Type{Vector{Float64}}, o::OCObs, pomdp::OCPOMDP)\n# return [o.ranges/pomdp.sensor.max_range, o.range_rates/pomdp.env.params.speed_limit]\n# end\n\n\n#### Helpers\n# \"\"\"\n# ego_state(pomdp:ICPOMDP, s::Float64, v::Float64)\n# Helper that returns the ego car state given its position on the lane and the velocity\n# \"\"\"\n# function ego_state(pomdp::UrbanPOMDP, s::Float64, v::Float64)\n# # ego_lane = pomdp.env.lane_map[\"ego_left\"] #TODO parameterized\n# posF = Frenet(get_ego_route(pomdp)[1], s)\n# return VehicleState(posF, pomdp.env.roadway, v)\n# end\n\n\"\"\"\n car_state(pomdp::UrbanPOMDP, lane_id::String, s::Float64, v::Float64)\n car_state(pomdp::UrbanPOMDP, lane::Lane, s::Float64, v::Float64)\n car_state(pomdp::UrbanPOMDP, x::Float64, y::Float64, θ::Float64, v::Float64)\nHelper that returns the state of a car given the lane and the position on the lane\n\"\"\"\nfunction car_state(pomdp::UrbanPOMDP, lane_id::String, s::Float64, v::Float64)\n lane = pomdp.env.lane_map[lane_id]\n posF = Frenet(lane, s)\n return VehicleState(posF, pomdp.env.roadway, v)\nend\nfunction car_state(pomdp::UrbanPOMDP, lane::Lane, s::Float64, v::Float64)\n posF = Frenet(lane, s)\n return VehicleState(posF, pomdp.env.roadway, v)\nend\nfunction car_state(pomdp::UrbanPOMDP, x::Float64, y::Float64, θ::Float64, v::Float64)\n posG = VecSE2(x, y, θ)\n return VehicleState(posG, pomdp.env.roadway, v)\nend\n\n\"\"\"\n get_off_the_grid(pomdp::UrbanPOMDP)\nreturn the off the grid state\n\"\"\"\nfunction get_off_the_grid(pomdp::UrbanPOMDP)\n posG = pomdp.off_grid\n return VehicleState(posG, pomdp.env.roadway, 0.)\nend\n\nfunction off_the_grid(veh::VehicleState, pomdp::UrbanPOMDP)\n return veh.posG == pomdp.off_grid\nend\n\n\n\"\"\"\nreturn the list of lanes the ego car should take\n\"\"\"\nfunction get_ego_route(pomdp::UrbanPOMDP)\n tags = [LaneTag(6,1), LaneTag(13, 1), LaneTag(2,pomdp.env.params.nlanes_main)]\n lanes = Array{Lane}(undef, length(tags))\n for (i,tag) in enumerate(tags)\n lanes[i] = pomdp.env.roadway[tag]\n end\n lanes\nend\n\n\n\"\"\"\ncreate a unique ID for a new car\n\"\"\"\nfunction next_car_id(pomdp::UrbanPOMDP, scene::Scene, rng::AbstractRNG)\n max_id = pomdp.max_cars+1\n current_car_ids = []\n for veh in scene\n if veh.def.class == AgentClass.CAR\n push!(current_car_ids, veh.id)\n end\n end\n possible_ids = setdiff(2:max_id, current_car_ids)\n id = rand(rng, possible_ids)\n return id\nend\n\nfunction next_car_id(pomdp::UrbanPOMDP, scene::Scene)\n max_id = pomdp.max_cars+1\n current_car_ids = []\n for veh in scene\n if veh.def.class == AgentClass.CAR\n push!(current_car_ids, veh.id)\n end\n end\n possible_ids = setdiff(2:max_id, current_car_ids)\n return possible_ids[1]\nend\n\n\"\"\"\ncreate a unique ID for a new pedestrian\n\"\"\"\nfunction next_ped_id(pomdp::UrbanPOMDP, scene::Scene, rng::AbstractRNG)\n max_id = pomdp.max_peds\n current_ped_ids = []\n for veh in scene\n if veh.def.class == AgentClass.PEDESTRIAN\n push!(current_ped_ids, veh.id)\n end\n end\n possible_ids = setdiff(101:100+max_id, current_ped_ids)\n id = rand(rng, possible_ids)\n return id\nend\nfunction next_ped_id(pomdp::UrbanPOMDP, scene::Scene)\n max_id = pomdp.max_peds\n current_ped_ids = []\n for veh in scene\n if veh.def.class == AgentClass.PEDESTRIAN\n push!(current_ped_ids, veh.id)\n end\n end\n possible_ids = setdiff(101:100+max_id, current_ped_ids)\n return possible_ids[1]\nend\n\nfunction n_cars(scene::Scene)\n n = 0\n for veh in scene\n if veh.def.class == AgentClass.CAR\n n += 1\n end\n end\n return n\nend\n\nfunction n_pedestrians(scene::Scene)\n n = 0\n for veh in scene\n if veh.def.class == AgentClass.PEDESTRIAN\n n += 1\n end\n end\n return n\nend\n\n\"\"\"\nCreate a scene that can be rendered from an observation\n\"\"\"\nfunction obs_to_scene(pomdp::UrbanPOMDP, obs::UrbanObs)\n o = deepcopy(obs)\n o = unrescale!(o, pomdp)\n o = to_global_coordinates!(o, pomdp)\n scene = Scene()\n # extract\n ego, car_map, ped_map, obs_map = split_o(o, pomdp, false)\n # println(\"cars observed : \", keys(car_map), \"ped observed :\", keys(ped_map))\n # project to roadway\n params = pomdp.env.params\n intersection_params = TInterParams(params.x_min, params.x_max, params.y_min, params.inter_x,\n params.inter_y, params.inter_width, params.inter_height,\n params. lane_width, params.nlanes_main, params.nlanes,\n params. stop_line, params.speed_limit, params.car_rate)\n car_roadway = gen_T_roadway(intersection_params)\n ego_state = VehicleState(VecSE2(ego[1], ego[2], ego[3]), car_roadway, ego[4])\n ego = Vehicle(ego_state, pomdp.ego_type, EGO_ID)\n push!(scene, ego)\n for (str_id, vec_state) in car_map\n # make sure to not project it on a crosswalk\n car_state = VehicleState(VecSE2(vec_state[1], vec_state[2], vec_state[3]), car_roadway, vec_state[4])\n if !off_the_grid(car_state, pomdp)\n id = next_car_id(pomdp, scene)\n car = Vehicle(car_state, pomdp.car_type, id)\n push!(scene, car)\n end\n end\n for (str_id, vec_state) in ped_map\n ped_state = VehicleState(VecSE2(vec_state[1], vec_state[2], vec_state[3]), pomdp.env.ped_roadway, vec_state[4])\n # println(\"ped_state \", ped_state)\n if !off_the_grid(ped_state, pomdp)\n id = next_ped_id(pomdp, scene)\n ped = Vehicle(ped_state, pomdp.ped_type, id)\n push!(scene, ped)\n end\n end\n @assert issorted([veh.id for veh in scene])\n return scene\nend\n\n# given a big observation vector, split to an entity-wise representation\nfunction split_o(obs::UrbanObs, pomdp::UrbanPOMDP, normalized=true)\n car_map, ped_map, obs_map = OrderedDict{Int64, Vector{Float64}}(), OrderedDict{Int64, Vector{Float64}}(), OrderedDict{Int64, Vector{Float64}}() #XXX Dictionary creation is sloooooow\n n_features = pomdp.n_features\n ego = obs[1:n_features]\n if normalized\n absent = normalized_off_the_grid_pos(pomdp, ego[1], ego[2])\n else \n pos_off = get_off_the_grid(pomdp)\n absent= [pos_off.posG.x, pos_off.posG.y, pos_off.posG.θ, pos_off.v]\n end\n # println(\"ego \", ego)\n # println(\"absent state :\", absent)\n# println(\"ego idx \", 1, \":\", n_features)\n for (j,i) in enumerate(1:pomdp.max_cars)\n if !isapprox(obs[i*n_features+1:(i+1)*n_features], absent, atol=1.0)\n car_map[j+1] = obs[i*n_features+1:(i+1)*n_features]\n end\n# println(\"car$j idx \", i*n_features+1:(i+1)*n_features)\n end\n for (j,i) in enumerate(pomdp.max_cars + 1:pomdp.max_cars + pomdp.max_peds)\n if !isapprox(obs[i*n_features+1:(i+1)*n_features], absent, atol=1.0)\n # println(norm(obs[i*n_features+1:(i+1)*n_features] - absent))\n ped_map[100+j] = obs[i*n_features+1:(i+1)*n_features]\n end\n# println(\"ped$j idx \", i*n_features+1:(i+1)*n_features)\n end\n for (j,i) in enumerate(pomdp.max_cars + pomdp.max_peds + 1:pomdp.max_cars + pomdp.max_peds + pomdp.max_obstacles)\n obs_map[j] = obs[i*n_features+1:(i+1)*n_features]\n# println(\"obs$j idx \", i*n_features+1:(i+1)*n_features)\n end\n return ego, car_map, ped_map, obs_map\nend\n\nfunction normalized_off_the_grid_pos(pomdp::UrbanPOMDP,normalized_ego_x::Float64, normalized_ego_y::Float64)\n pos_off = get_off_the_grid(pomdp)\n max_ego_dist = get_end(pomdp.env.roadway[pomdp.ego_goal])\n return [pos_off.posG.x/max_ego_dist - normalized_ego_x, pos_off.posG.y/max_ego_dist - normalized_ego_y, pos_off.posG.θ, 0.]\nend\n", "meta": {"hexsha": "c60aee739af9e741055f5becce7d6411a573c717", "size": 22304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generative_pomdps/urban/generative_model.jl", "max_stars_repo_name": "MaximeBouton/AutomotivePOMDPs", "max_stars_repo_head_hexsha": "eac7eef25a758b3ea20ce58c0e56bd1e5c32c3d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-04-28T08:55:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T11:24:55.000Z", "max_issues_repo_path": "src/generative_pomdps/urban/generative_model.jl", "max_issues_repo_name": "MaximeBouton/AutomotivePOMDPs", "max_issues_repo_head_hexsha": "eac7eef25a758b3ea20ce58c0e56bd1e5c32c3d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-03-09T04:59:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T11:43:48.000Z", "max_forks_repo_path": "src/generative_pomdps/urban/generative_model.jl", "max_forks_repo_name": "MaximeBouton/AutomotivePOMDPs", "max_forks_repo_head_hexsha": "eac7eef25a758b3ea20ce58c0e56bd1e5c32c3d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-07-03T09:51:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T07:49:13.000Z", "avg_line_length": 36.2077922078, "max_line_length": 185, "alphanum_fraction": 0.6405577475, "num_tokens": 6947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.18248795484901}} {"text": "function get_sim_data_indirect(mechanism::Mechanism,env::Environment,Δt::Real;\n relax_comp=false)\n vs = VariableSelector()\n add_var!(vs, :qnext, num_positions(mechanism))\n add_var!(vs, :vnext, num_velocities(mechanism))\n for i = 1:length(env.contacts)\n β_dim = size(env.contacts[i].obstacle.basis,2)\n add_var!(vs, Symbol(\"β\", i), β_dim)\n add_var!(vs, Symbol(\"λ\", i), 1)\n add_var!(vs, Symbol(\"c_n\", i), 1)\n if relax_comp\n add_var!(vs, Symbol(\"slack\", i), 3)\n end\n end\n\n cs = ConstraintSelector()\n add_eq!(cs, :kin, num_positions(mechanism))\n add_eq!(cs, :dyn, num_velocities(mechanism))\n for i = 1:length(env.contacts)\n β_dim = size(env.contacts[i].obstacle.basis,2)\n add_ineq!(cs, Symbol(\"β_pos\", i), β_dim)\n add_ineq!(cs, Symbol(\"λ_pos\", i), 1)\n add_ineq!(cs, Symbol(\"c_n_pos\", i), 1)\n add_ineq!(cs, Symbol(\"ϕ_pos\", i), 1)\n add_ineq!(cs, Symbol(\"fric_pos\", i), β_dim)\n add_ineq!(cs, Symbol(\"cone_pos\", i), 1)\n if relax_comp\n add_ineq!(cs, Symbol(\"slack_pos\", i), 3)\n add_ineq!(cs, Symbol(\"ϕ_c_n_comp\", i), 1)\n add_ineq!(cs, Symbol(\"fric_β_comp\", i), β_dim)\n add_ineq!(cs, Symbol(\"cone_λ_comp\", i), 1)\n else\n add_eq!(cs, Symbol(\"ϕ_c_n_comp\", i), 1)\n add_eq!(cs, Symbol(\"fric_β_comp\", i), β_dim)\n add_eq!(cs, Symbol(\"cone_λ_comp\", i), 1)\n end\n end\n\n state_cache = [StateCache(mechanism) for n = 1:2]\n envj_cache = [EnvironmentJacobianCache(env) for n = 1:2]\n\n generate_solver_fn = :generate_solver_fn_sim_indirect\n extract_sol = :extract_sol_sim_indirect\n\n sim_data = SimData(mechanism,env,\n state_cache,envj_cache,\n Δt,vs,cs,generate_solver_fn,extract_sol,\n [],[],[],[],[],[],[],[],[],1,[],[],[],[])\n\n sim_data\nend\n\nfunction extract_sol_sim_indirect(sim_data::SimData, results::AbstractArray{T,2}) where T\n vs = sim_data.vs\n relax_comp = haskey(vs.vars, :slack1)\n env = sim_data.env\n N = size(results,2)\n\n qtraj = Array{Array{Float64,1},1}(undef, 0)\n vtraj = Array{Array{Float64,1},1}(undef, 0)\n utraj = Array{Array{Float64,1},1}(undef, 0)\n contact_traj = Array{Array{Array{Float64,1},1},1}(undef, 0)\n slack_traj = Array{Array{Float64,1},1}(undef, 0)\n x = MechanismState(sim_data.mechanism)\n for n = 1:N\n set_configuration!(x, vs(results[:,n], Symbol(\"qnext\")))\n normalize_configuration!(x)\n qnext = configuration(x)\n push!(qtraj, qnext)\n push!(vtraj, vs(results[:,n], Symbol(\"vnext\")))\n contact_sol = Array{Array{Float64,1},1}(undef, 0)\n for i = 1:length(env.contacts)\n if relax_comp\n push!(slack_traj, vs(results[:,n], Symbol(\"slack\", i)))\n end\n push!(contact_sol, vcat(vs(results[:,n], Symbol(\"c_n\", i)),\n vs(results[:,n], Symbol(\"β\", i)),\n vs(results[:,n], Symbol(\"λ\", i))))\n end\n push!(contact_traj, contact_sol)\n end\n\n # some other usefull vectors\n ttraj = [(i-1)*sim_data.Δt for i = 1:N]\n qv_mat = vcat(hcat(qtraj...),hcat(vtraj...))\n\n qtraj, vtraj, utraj, contact_traj, slack_traj, ttraj, qv_mat, results\nend\n\nfunction generate_solver_fn_sim_indirect(sim_data,q0,v0,u0)\n x0 = sim_data.state_cache[1][Float64]\n Δt = sim_data.Δt\n vs = sim_data.vs\n cs = sim_data.cs\n\n relax_comp = haskey(vs.vars, :slack1)\n num_contacts = length(sim_data.env.contacts)\n num_vel = num_velocities(sim_data.mechanism)\n world = root_body(sim_data.mechanism)\n world_frame = default_frame(world)\n\n set_configuration!(x0, q0)\n set_velocity!(x0, v0)\n setdirty!(x0)\n H = mass_matrix(x0)\n\n function eval_obj(x::AbstractArray{T}) where T\n f = 0.\n\n if relax_comp\n for i = 1:num_contacts\n slack = vs(x, Symbol(\"slack\", i))\n f += sum(slack)\n end\n end\n\n f\n end\n\n function eval_cons(x::AbstractArray{T}) where T\n xn = sim_data.state_cache[2][T]\n envj = sim_data.envj_cache[2][T]\n\n contact_bias = Vector{T}(undef, num_vel)\n g = Vector{T}(undef, cs.num_eqs + cs.num_ineqs) # TODO preallocate\n\n qnext = vs(x, :qnext)\n vnext = vs(x, :vnext)\n\n set_configuration!(xn, qnext)\n set_velocity!(xn, vnext)\n setdirty!(xn)\n\n normalize_configuration!(xn)\n\n config_derivative = configuration_derivative(xn) # TODO preallocate\n dyn_bias = dynamics_bias(xn) # TODO preallocate\n if (num_contacts > 0)\n contact_jacobian!(envj, xn)\n contact_τ_indirect!(contact_bias, sim_data, envj, x)\n end\n\n g[cs(:kin)] .= qnext .- q0 .- Δt .* config_derivative\n g[cs(:dyn)] .= H * (vnext - v0) .- Δt .* (u0 .- dyn_bias .- contact_bias)\n for i = 1:num_contacts\n cj = envj.contact_jacobians[i]\n c = cj.contact\n\n # TODO preallocate\n contact_v = cj.contact_rot' * point_jacobian(xn, path(sim_data.mechanism, world, c.body), transform(xn, c.point, world_frame)).J * vnext\n\n β = vs(x, Symbol(\"β\", i))\n λ = vs(x, Symbol(\"λ\", i))\n c_n = vs(x, Symbol(\"c_n\", i))\n\n Dtv = c.obstacle.basis' * contact_v\n\n g[cs(Symbol(\"β_pos\", i))] .= -β\n g[cs(Symbol(\"λ_pos\", i))] .= -λ\n g[cs(Symbol(\"c_n_pos\", i))] .= -c_n\n g[cs(Symbol(\"ϕ_pos\", i))] .= -envj.contact_jacobians[i].ϕ\n # λe + D'*v >= 0\n g[cs(Symbol(\"fric_pos\", i))] .= -(λ .+ Dtv)\n # μ*c_n - sum(β) >= 0\n g[cs(Symbol(\"cone_pos\", i))] .= -(c.obstacle.μ .* c_n .- sum(β))\n if !relax_comp\n # dist * c_n = 0\n g[cs(Symbol(\"ϕ_c_n_comp\", i))] .= envj.contact_jacobians[i].ϕ .* c_n\n # (λe + Dtv)' * β = 0\n g[cs(Symbol(\"fric_β_comp\", i))] .= (λ .+ Dtv) .* β\n # (μ * c_n - sum(β)) * λ = 0\n g[cs(Symbol(\"cone_λ_comp\", i))] .= (c.obstacle.μ .* c_n .- sum(β)) .* λ\n else\n slack = vs(x, Symbol(\"slack\", i))\n g[cs(Symbol(\"slack_pos\", i))] .= -slack\n g[cs(Symbol(\"ϕ_c_n_comp\", i))] .= envj.contact_jacobians[i].ϕ .* c_n .- slack[1]\n g[cs(Symbol(\"fric_β_comp\", i))] .= (λ .+ Dtv) .* β .- slack[2]\n g[cs(Symbol(\"cone_λ_comp\", i))] .= (c.obstacle.μ .* c_n .- sum(β)) .* λ .- slack[3]\n end\n end\n\n g\n end\n\n generate_autodiff_solver_fn(eval_obj,eval_cons,cs.eqs,cs.ineqs,vs.num_vars)\nend\n", "meta": {"hexsha": "34b21a9c7c310ae27d0207889faad359a4f88a5e", "size": 6766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simulation_indirect.jl", "max_stars_repo_name": "blandry/Bilevel.jl", "max_stars_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-03-14T01:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T19:15:50.000Z", "max_issues_repo_path": "src/simulation_indirect.jl", "max_issues_repo_name": "blandry/Bilevel.jl", "max_issues_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-07T15:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T16:17:26.000Z", "max_forks_repo_path": "src/simulation_indirect.jl", "max_forks_repo_name": "blandry/Bilevel.jl", "max_forks_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-27T10:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T07:00:49.000Z", "avg_line_length": 36.1818181818, "max_line_length": 148, "alphanum_fraction": 0.546556311, "num_tokens": 2083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.18145183260309983}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\n\"\"\"\n Random\n\nSupport for generating random numbers. Provides [`rand`](@ref), [`randn`](@ref),\n[`AbstractRNG`](@ref), [`MersenneTwister`](@ref), and [`RandomDevice`](@ref).\n\"\"\"\nmodule Random\n\ninclude(\"DSFMT.jl\")\n\nusing .DSFMT\nusing Base.GMP.MPZ\nusing Base.GMP: Limb\nimport SHA\n\nusing Base: BitInteger, BitInteger_types, BitUnsigned, require_one_based_indexing\n\nimport Base: copymutable, copy, copy!, ==, hash, convert,\n rand, randn, show\n\nexport rand!, randn!,\n randexp, randexp!,\n bitrand,\n randstring,\n randsubseq, randsubseq!,\n shuffle, shuffle!,\n randperm, randperm!,\n randcycle, randcycle!,\n AbstractRNG, MersenneTwister, RandomDevice, TaskLocalRNG, Xoshiro\n\n## general definitions\n\n\"\"\"\n AbstractRNG\n\nSupertype for random number generators such as [`MersenneTwister`](@ref) and [`RandomDevice`](@ref).\n\"\"\"\nabstract type AbstractRNG end\n\nBase.broadcastable(x::AbstractRNG) = Ref(x)\n\ngentype(::Type{X}) where {X} = eltype(X)\ngentype(x) = gentype(typeof(x))\n\n\n### integers\n\n# we define types which encode the generation of a specific number of bits\n# the \"raw\" version means that the unused bits are not zeroed\n\nabstract type UniformBits{T<:BitInteger} end\n\nstruct UInt10{T} <: UniformBits{T} end\nstruct UInt10Raw{T} <: UniformBits{T} end\n\nstruct UInt23{T} <: UniformBits{T} end\nstruct UInt23Raw{T} <: UniformBits{T} end\n\nstruct UInt52{T} <: UniformBits{T} end\nstruct UInt52Raw{T} <: UniformBits{T} end\n\nstruct UInt104{T} <: UniformBits{T} end\nstruct UInt104Raw{T} <: UniformBits{T} end\n\nstruct UInt2x52{T} <: UniformBits{T} end\nstruct UInt2x52Raw{T} <: UniformBits{T} end\n\nuint_sup(::Type{<:Union{UInt10,UInt10Raw}}) = UInt16\nuint_sup(::Type{<:Union{UInt23,UInt23Raw}}) = UInt32\nuint_sup(::Type{<:Union{UInt52,UInt52Raw}}) = UInt64\nuint_sup(::Type{<:Union{UInt104,UInt104Raw}}) = UInt128\nuint_sup(::Type{<:Union{UInt2x52,UInt2x52Raw}}) = UInt128\n\nfor UI = (:UInt10, :UInt10Raw, :UInt23, :UInt23Raw, :UInt52, :UInt52Raw,\n :UInt104, :UInt104Raw, :UInt2x52, :UInt2x52Raw)\n @eval begin\n $UI(::Type{T}=uint_sup($UI)) where {T} = $UI{T}()\n # useful for defining rand generically:\n uint_default(::$UI) = $UI{uint_sup($UI)}()\n end\nend\n\ngentype(::Type{<:UniformBits{T}}) where {T} = T\n\n### floats\n\nabstract type FloatInterval{T<:AbstractFloat} end\n\nstruct CloseOpen01{T<:AbstractFloat} <: FloatInterval{T} end # interval [0,1)\nstruct CloseOpen12{T<:AbstractFloat} <: FloatInterval{T} end # interval [1,2)\n\nconst FloatInterval_64 = FloatInterval{Float64}\nconst CloseOpen01_64 = CloseOpen01{Float64}\nconst CloseOpen12_64 = CloseOpen12{Float64}\n\nCloseOpen01(::Type{T}=Float64) where {T<:AbstractFloat} = CloseOpen01{T}()\nCloseOpen12(::Type{T}=Float64) where {T<:AbstractFloat} = CloseOpen12{T}()\n\ngentype(::Type{<:FloatInterval{T}}) where {T<:AbstractFloat} = T\n\nconst BitFloatType = Union{Type{Float16},Type{Float32},Type{Float64}}\n\n### Sampler\n\nabstract type Sampler{E} end\n\ngentype(::Type{<:Sampler{E}}) where {E} = E\n\n# temporarily for BaseBenchmarks\nRangeGenerator(x) = Sampler(default_rng(), x)\n\n# In some cases, when only 1 random value is to be generated,\n# the optimal sampler can be different than if multiple values\n# have to be generated. Hence a `Repetition` parameter is used\n# to choose the best one depending on the need.\nconst Repetition = Union{Val{1},Val{Inf}}\n\n# these default fall-back for all RNGs would be nice,\n# but generate difficult-to-solve ambiguities\n# Sampler(::AbstractRNG, X, ::Val{Inf}) = Sampler(X)\n# Sampler(::AbstractRNG, ::Type{X}, ::Val{Inf}) where {X} = Sampler(X)\n\n\"\"\"\n Sampler(rng, x, repetition = Val(Inf))\n\nReturn a sampler object that can be used to generate random values from `rng` for `x`.\n\nWhen `sp = Sampler(rng, x, repetition)`, `rand(rng, sp)` will be used to draw random values,\nand should be defined accordingly.\n\n`repetition` can be `Val(1)` or `Val(Inf)`, and should be used as a suggestion for deciding\nthe amount of precomputation, if applicable.\n\n[`Random.SamplerType`](@ref) and [`Random.SamplerTrivial`](@ref) are default fallbacks for\n*types* and *values*, respectively. [`Random.SamplerSimple`](@ref) can be used to store\npre-computed values without defining extra types for only this purpose.\n\"\"\"\nSampler(rng::AbstractRNG, x, r::Repetition=Val(Inf)) = Sampler(typeof_rng(rng), x, r)\nSampler(rng::AbstractRNG, ::Type{X}, r::Repetition=Val(Inf)) where {X} =\n Sampler(typeof_rng(rng), X, r)\n\ntypeof_rng(rng::AbstractRNG) = typeof(rng)\n\n# this method is necessary to prevent rand(rng::AbstractRNG, X) from\n# recursively constructing nested Sampler types.\nSampler(T::Type{<:AbstractRNG}, sp::Sampler, r::Repetition) =\n throw(MethodError(Sampler, (T, sp, r)))\n\n# default shortcut for the general case\nSampler(::Type{RNG}, X) where {RNG<:AbstractRNG} = Sampler(RNG, X, Val(Inf))\nSampler(::Type{RNG}, ::Type{X}) where {RNG<:AbstractRNG,X} = Sampler(RNG, X, Val(Inf))\n\n#### pre-defined useful Sampler types\n\n\"\"\"\n SamplerType{T}()\n\nA sampler for types, containing no other information. The default fallback for `Sampler`\nwhen called with types.\n\"\"\"\nstruct SamplerType{T} <: Sampler{T} end\n\nSampler(::Type{<:AbstractRNG}, ::Type{T}, ::Repetition) where {T} = SamplerType{T}()\n\nBase.getindex(::SamplerType{T}) where {T} = T\n\nstruct SamplerTrivial{T,E} <: Sampler{E}\n self::T\nend\n\n\"\"\"\n SamplerTrivial(x)\n\nCreate a sampler that just wraps the given value `x`. This is the default fall-back for\nvalues.\nThe `eltype` of this sampler is equal to `eltype(x)`.\n\nThe recommended use case is sampling from values without precomputed data.\n\"\"\"\nSamplerTrivial(x::T) where {T} = SamplerTrivial{T,gentype(T)}(x)\n\nSampler(::Type{<:AbstractRNG}, x, ::Repetition) = SamplerTrivial(x)\n\nBase.getindex(sp::SamplerTrivial) = sp.self\n\n# simple sampler carrying data (which can be anything)\nstruct SamplerSimple{T,S,E} <: Sampler{E}\n self::T\n data::S\nend\n\n\"\"\"\n SamplerSimple(x, data)\n\nCreate a sampler that wraps the given value `x` and the `data`.\nThe `eltype` of this sampler is equal to `eltype(x)`.\n\nThe recommended use case is sampling from values with precomputed data.\n\"\"\"\nSamplerSimple(x::T, data::S) where {T,S} = SamplerSimple{T,S,gentype(T)}(x, data)\n\nBase.getindex(sp::SamplerSimple) = sp.self\n\n# simple sampler carrying a (type) tag T and data\nstruct SamplerTag{T,S,E} <: Sampler{E}\n data::S\n SamplerTag{T}(s::S) where {T,S} = new{T,S,gentype(T)}(s)\nend\n\n\n#### helper samplers\n\n# TODO: make constraining constructors to enforce that those\n# types are <: Sampler{T}\n\n##### Adapter to generate a randome value in [0, n]\n\nstruct LessThan{T<:Integer,S} <: Sampler{T}\n sup::T\n s::S # the scalar specification/sampler to feed to rand\nend\n\nfunction rand(rng::AbstractRNG, sp::LessThan)\n while true\n x = rand(rng, sp.s)\n x <= sp.sup && return x\n end\nend\n\nstruct Masked{T<:Integer,S} <: Sampler{T}\n mask::T\n s::S\nend\n\nrand(rng::AbstractRNG, sp::Masked) = rand(rng, sp.s) & sp.mask\n\n##### Uniform\n\nstruct UniformT{T} <: Sampler{T} end\n\nuniform(::Type{T}) where {T} = UniformT{T}()\n\nrand(rng::AbstractRNG, ::UniformT{T}) where {T} = rand(rng, T)\n\n\n### machinery for generation with Sampler\n\n# This describes how to generate random scalars or arrays, by generating a Sampler\n# and calling rand on it (which should be defined in \"generation.jl\").\n# NOTE: this section could be moved into a separate file when more containers are supported.\n\n#### scalars\n\nrand(rng::AbstractRNG, X) = rand(rng, Sampler(rng, X, Val(1)))\n# this is needed to disambiguate\nrand(rng::AbstractRNG, X::Dims) = rand(rng, Sampler(rng, X, Val(1)))\nrand(rng::AbstractRNG=default_rng(), ::Type{X}=Float64) where {X} = rand(rng, Sampler(rng, X, Val(1)))::X\n\nrand(X) = rand(default_rng(), X)\nrand(::Type{X}) where {X} = rand(default_rng(), X)\n\n#### arrays\n\nrand!(A::AbstractArray{T}, X) where {T} = rand!(default_rng(), A, X)\nrand!(A::AbstractArray{T}, ::Type{X}=T) where {T,X} = rand!(default_rng(), A, X)\n\nrand!(rng::AbstractRNG, A::AbstractArray{T}, X) where {T} = rand!(rng, A, Sampler(rng, X))\nrand!(rng::AbstractRNG, A::AbstractArray{T}, ::Type{X}=T) where {T,X} = rand!(rng, A, Sampler(rng, X))\n\nfunction rand!(rng::AbstractRNG, A::AbstractArray{T}, sp::Sampler) where T\n for i in eachindex(A)\n @inbounds A[i] = rand(rng, sp)\n end\n A\nend\n\nrand(r::AbstractRNG, dims::Integer...) = rand(r, Float64, Dims(dims))\nrand( dims::Integer...) = rand(Float64, Dims(dims))\n\nrand(r::AbstractRNG, X, dims::Dims) = rand!(r, Array{gentype(X)}(undef, dims), X)\nrand( X, dims::Dims) = rand(default_rng(), X, dims)\n\nrand(r::AbstractRNG, X, d::Integer, dims::Integer...) = rand(r, X, Dims((d, dims...)))\nrand( X, d::Integer, dims::Integer...) = rand(X, Dims((d, dims...)))\n# note: the above methods would trigger an ambiguity warning if d was not separated out:\n# rand(r, ()) would match both this method and rand(r, dims::Dims)\n# moreover, a call like rand(r, NotImplementedType()) would be an infinite loop\n\nrand(r::AbstractRNG, ::Type{X}, dims::Dims) where {X} = rand!(r, Array{X}(undef, dims), X)\nrand( ::Type{X}, dims::Dims) where {X} = rand(default_rng(), X, dims)\n\nrand(r::AbstractRNG, ::Type{X}, d::Integer, dims::Integer...) where {X} = rand(r, X, Dims((d, dims...)))\nrand( ::Type{X}, d::Integer, dims::Integer...) where {X} = rand(X, Dims((d, dims...)))\n\n# SamplerUnion(X, Y, ...}) == Union{SamplerType{X}, SamplerType{Y}, ...}\nSamplerUnion(U...) = Union{Any[SamplerType{T} for T in U]...}\nconst SamplerBoolBitInteger = SamplerUnion(Bool, BitInteger_types...)\n\n\ninclude(\"Xoshiro.jl\")\ninclude(\"RNGs.jl\")\ninclude(\"generation.jl\")\ninclude(\"normal.jl\")\ninclude(\"misc.jl\")\ninclude(\"XoshiroSimd.jl\")\n\n## rand & rand! & seed! docstrings\n\n\"\"\"\n rand([rng=default_rng()], [S], [dims...])\n\nPick a random element or array of random elements from the set of values specified by `S`;\n`S` can be\n\n* an indexable collection (for example `1:9` or `('x', \"y\", :z)`),\n* an `AbstractDict` or `AbstractSet` object,\n* a string (considered as a collection of characters), or\n* a type: the set of values to pick from is then equivalent to `typemin(S):typemax(S)` for\n integers (this is not applicable to [`BigInt`](@ref)), to ``[0, 1)`` for floating\n point numbers and to ``[0, 1)+i[0, 1)`` for complex floating point numbers;\n\n`S` defaults to [`Float64`](@ref).\nWhen only one argument is passed besides the optional `rng` and is a `Tuple`, it is interpreted\nas a collection of values (`S`) and not as `dims`.\n\n\n!!! compat \"Julia 1.1\"\n Support for `S` as a tuple requires at least Julia 1.1.\n\n# Examples\n```julia-repl\njulia> rand(Int, 2)\n2-element Array{Int64,1}:\n 1339893410598768192\n 1575814717733606317\n\njulia> using Random\n\njulia> rand(MersenneTwister(0), Dict(1=>2, 3=>4))\n1=>2\n\njulia> rand((2, 3))\n3\n\njulia> rand(Float64, (2, 3))\n2×3 Array{Float64,2}:\n 0.999717 0.0143835 0.540787\n 0.696556 0.783855 0.938235\n```\n\n!!! note\n The complexity of `rand(rng, s::Union{AbstractDict,AbstractSet})`\n is linear in the length of `s`, unless an optimized method with\n constant complexity is available, which is the case for `Dict`,\n `Set` and dense `BitSet`s. For more than a few calls, use `rand(rng,\n collect(s))` instead, or either `rand(rng, Dict(s))` or `rand(rng,\n Set(s))` as appropriate.\n\"\"\"\nrand\n\n\"\"\"\n rand!([rng=default_rng()], A, [S=eltype(A)])\n\nPopulate the array `A` with random values. If `S` is specified\n(`S` can be a type or a collection, cf. [`rand`](@ref) for details),\nthe values are picked randomly from `S`.\nThis is equivalent to `copyto!(A, rand(rng, S, size(A)))`\nbut without allocating a new array.\n\n# Examples\n```jldoctest\njulia> rng = MersenneTwister(1234);\n\njulia> rand!(rng, zeros(5))\n5-element Vector{Float64}:\n 0.5908446386657102\n 0.7667970365022592\n 0.5662374165061859\n 0.4600853424625171\n 0.7940257103317943\n```\n\"\"\"\nrand!\n\n\"\"\"\n seed!([rng=default_rng()], seed) -> rng\n seed!([rng=default_rng()]) -> rng\n\nReseed the random number generator: `rng` will give a reproducible\nsequence of numbers if and only if a `seed` is provided. Some RNGs\ndon't accept a seed, like `RandomDevice`.\nAfter the call to `seed!`, `rng` is equivalent to a newly created\nobject initialized with the same seed.\n\nIf `rng` is not specified, it defaults to seeding the state of the\nshared task-local generator.\n\n# Examples\n```julia-repl\njulia> Random.seed!(1234);\n\njulia> x1 = rand(2)\n2-element Vector{Float64}:\n 0.32597672886359486\n 0.5490511363155669\n\njulia> Random.seed!(1234);\n\njulia> x2 = rand(2)\n2-element Vector{Float64}:\n 0.32597672886359486\n 0.5490511363155669\n\njulia> x1 == x2\ntrue\n\njulia> rng = Xoshiro(1234); rand(rng, 2) == x1\ntrue\n\njulia> Xoshiro(1) == Random.seed!(rng, 1)\ntrue\n\njulia> rand(Random.seed!(rng), Bool) # not reproducible\ntrue\n\njulia> rand(Random.seed!(rng), Bool) # not reproducible either\nfalse\n\njulia> rand(Xoshiro(), Bool) # not reproducible either\ntrue\n```\n\"\"\"\nseed!(rng::AbstractRNG, ::Nothing) = seed!(rng)\n\nend # module\n", "meta": {"hexsha": "02bc609e556794e00da9edccd234a18418e594bf", "size": 13236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stdlib/Random/src/Random.jl", "max_stars_repo_name": "Physolia/julia", "max_stars_repo_head_hexsha": "f0b1c5fa0e57f60446bba7d0c83bfda93a2b8b63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-28T12:55:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-28T12:55:51.000Z", "max_issues_repo_path": "stdlib/Random/src/Random.jl", "max_issues_repo_name": "Eurus-Holmes/julia", "max_issues_repo_head_hexsha": "c8c9e04c32f7f5929cf9d1c34d3071fa7297e88a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-20T04:27:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T04:27:27.000Z", "max_forks_repo_path": "stdlib/Random/src/Random.jl", "max_forks_repo_name": "Nexuscompute/julia", "max_forks_repo_head_hexsha": "6dae654e91c5cb104148cc4e9b066da4b4b0c164", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2191780822, "max_line_length": 105, "alphanum_fraction": 0.6768661227, "num_tokens": 3975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18103578731277928}} {"text": "\n\"\"\"\n AutoDiff.Jacobian(polar, func::Function, variable::AbstractVariable)\n\nInstantiate a Jacobian AD factory for constraint function\n`func`, w.r.t. state ``x`` (if `variable=State()`) or control\n``u`` (if `variable=Control()`).\n\nThe coloring is done using Jacobian's expressions from MATPOWER.\n\n### Examples\n\n```julia\njulia> Jacx = AutoDiff.Jacobian(polar, ExaPF.power_balance, State())\n```\n\"\"\"\nfunction AutoDiff.Jacobian(\n polar::PolarForm{T, VI, VT, MT}, func, variable,\n) where {T, VI, VT, MT}\n @assert is_constraint(func)\n\n if isa(polar.device, CPU)\n SMT = SparseMatrixCSC{Float64,Int}\n A = Vector\n elseif isa(polar.device, CUDADevice)\n SMT = CUSPARSE.CuSparseMatrixCSR{Float64}\n A = CUDA.CuVector\n end\n\n pf = polar.network\n nbus = PS.get(pf, PS.NumberOfBuses())\n if isa(variable, State)\n map = VI(polar.mapx)\n elseif isa(variable, Control)\n map = VI(polar.mapu)\n end\n\n nmap = length(map)\n\n # Sparsity pattern\n J = jacobian_sparsity(polar, func, variable)\n\n # Coloring\n coloring = AutoDiff.SparseDiffTools.matrix_colors(J)\n ncolor = size(unique(coloring),1)\n\n # TODO: clean\n nx = 2 * nbus\n x = VT(zeros(Float64, nx))\n m = size(J, 1)\n\n # Move Jacobian to the GPU\n J = convert(SMT, J)\n\n # Seedings\n t1s{N} = ForwardDiff.Dual{Nothing,Float64, N} where N\n t1sx = A{t1s{ncolor}}(x)\n t1sF = A{t1s{ncolor}}(zeros(Float64, m))\n t1sseeds = AutoDiff.init_seed(coloring, ncolor, nmap)\n\n # Move the seeds over to the device, if necessary\n gput1sseeds = A{ForwardDiff.Partials{ncolor,Float64}}(t1sseeds)\n compressedJ = MT(zeros(Float64, ncolor, m))\n\n # Views\n varx = view(x, map)\n t1svarx = view(t1sx, map)\n\n return AutoDiff.Jacobian{typeof(func), VI, VT, MT, SMT, typeof(gput1sseeds), typeof(t1sx), typeof(varx), typeof(t1svarx)}(\n func, variable, J, compressedJ, coloring,\n gput1sseeds, t1sF, x, t1sx, map, varx, t1svarx\n )\nend\n\n\"\"\"\n AutoDiff.jacobian!(polar::PolarForm, jac::AutoDiff.Jacobian, buffer)\n\nUpdate the sparse Jacobian entries `jacobian.J` using AutoDiff.\nNo allocations are taking place in this function.\n\n* `polar::PolarForm`: polar formulation, stores all parameters.\n* `jac::AutoDiff.Jacobian`: AutoDiff Factory with Jacobian to update.\n* `buffer::PolarNetworkState`: store current values for network's variables.\n\n\"\"\"\nfunction AutoDiff.jacobian!(polar::PolarForm, jac::AutoDiff.Jacobian, buffer)\n nbus = get(polar, PS.NumberOfBuses())\n type = jac.var\n if isa(type, State)\n copyto!(jac.x, 1, buffer.vmag, 1, nbus)\n copyto!(jac.x, nbus+1, buffer.vang, 1, nbus)\n jac.t1sx .= jac.x\n jac.t1sF .= 0.0\n elseif isa(type, Control)\n copyto!(jac.x, 1, buffer.vmag, 1, nbus)\n copyto!(jac.x, nbus+1, buffer.pinj, 1, nbus)\n jac.t1sx .= jac.x\n jac.t1sF .= 0.0\n end\n\n AutoDiff.seed!(jac.t1sseeds, jac.varx, jac.t1svarx)\n\n if isa(type, State)\n jac.func(\n polar,\n jac.t1sF,\n view(jac.t1sx, 1:nbus),\n view(jac.t1sx, nbus+1:2*nbus),\n buffer.pinj,\n buffer.qinj,\n )\n elseif isa(type, Control)\n jac.func(\n polar,\n jac.t1sF,\n view(jac.t1sx, 1:nbus),\n buffer.vang,\n view(jac.t1sx, nbus+1:2*nbus),\n buffer.qinj,\n )\n end\n\n AutoDiff.getpartials_kernel!(jac.compressedJ, jac.t1sF)\n AutoDiff.uncompress_kernel!(jac.J, jac.compressedJ, jac.coloring)\n return jac.J\nend\n\n# Handle properly constant Jacobian case\nfunction AutoDiff.ConstantJacobian(polar::PolarForm, func::Function, variable::Union{State,Control})\n @assert is_constraint(func)\n\n if isa(polar.device, CPU)\n SMT = SparseMatrixCSC{Float64,Int}\n elseif isa(polar.device, CUDADevice)\n SMT = CUSPARSE.CuSparseMatrixCSR{Float64}\n end\n\n nbus = get(polar, PS.NumberOfBuses())\n vmag = ones(nbus)\n vang = ones(nbus)\n V = vmag .* exp.(im .* vang)\n # Evaluate Jacobian with MATPOWER\n J = matpower_jacobian(polar, variable, func, V)\n # Move Jacobian to the GPU\n if isa(polar.device, CUDADevice) && iszero(J)\n # CUSPARSE does not support zero matrix. Return nothing instead.\n J = nothing\n else\n J = convert(SMT, J)\n end\n return AutoDiff.ConstantJacobian(J)\nend\n\nfunction AutoDiff.jacobian!(polar::PolarForm, jac::AutoDiff.ConstantJacobian, buffer)\n return jac.J\nend\n\n\nfunction AutoDiff.Hessian(polar::PolarForm{T, VI, VT, MT}, func) where {T, VI, VT, MT}\n @assert is_constraint(func)\n\n if isa(polar.device, CPU)\n A = Vector\n elseif isa(polar.device, CUDADevice)\n A = CUDA.CuVector\n end\n\n pf = polar.network\n nbus = PS.get(pf, PS.NumberOfBuses())\n n_cons = size_constraint(polar, func)\n\n map = VI(polar.hessianstructure.map)\n nmap = length(map)\n\n x = VT(zeros(Float64, 3*nbus))\n\n t1s{N} = ForwardDiff.Dual{Nothing,Float64, N} where N\n t1sx = A{t1s{1}}(x)\n t1sF = A{t1s{1}}(zeros(Float64, n_cons))\n host_t1sseeds = Vector{ForwardDiff.Partials{1,Float64}}(undef, nmap)\n t1sseeds = A{ForwardDiff.Partials{1,Float64}}(undef, nmap)\n varx = view(x, map)\n t1svarx = view(t1sx, map)\n VHP = typeof(host_t1sseeds)\n VP = typeof(t1sseeds)\n VD = typeof(t1sx)\n adj_t1sx = similar(t1sx)\n adj_t1sF = similar(t1sF)\n buffer = AutoDiff.TapeMemory(polar, func, VD; with_stack=false)\n return AutoDiff.Hessian{typeof(func), VI, VT, VHP, VP, VD, typeof(varx), typeof(t1svarx), typeof(buffer)}(\n func, host_t1sseeds, t1sseeds, x, t1sF, adj_t1sF, t1sx, adj_t1sx, map, varx, t1svarx, buffer,\n )\nend\n\nfunction _init_seed_hessian!(dest, tmp, v::AbstractArray, nmap)\n @inbounds for i in 1:nmap\n dest[i] = ForwardDiff.Partials{1, Float64}(NTuple{1, Float64}(v[i]))\n end\n return\nend\nfunction _init_seed_hessian!(dest, tmp, v::CUDA.CuArray, nmap)\n hostv = Array(v)\n @inbounds Threads.@threads for i in 1:nmap\n tmp[i] = ForwardDiff.Partials{1, Float64}(NTuple{1, Float64}(hostv[i]))\n end\n copyto!(dest, tmp)\n return\nend\n\n# λ' * H * v\nfunction AutoDiff.adj_hessian_prod!(\n polar, H::AutoDiff.Hessian, hv, buffer, λ, v,\n)\n @assert length(hv) == length(v)\n nbus = get(polar, PS.NumberOfBuses())\n x = H.x\n ntgt = length(v)\n t1sx = H.t1sx\n adj_t1sx = H.∂t1sx\n t1sF = H.t1sF\n adj_t1sF = H.∂t1sF\n # Move data\n copyto!(x, 1, buffer.vmag, 1, nbus)\n copyto!(x, nbus+1, buffer.vang, 1, nbus)\n copyto!(x, 2*nbus+1, buffer.pinj, 1, nbus)\n # Init dual variables\n t1sx .= H.x\n adj_t1sx .= 0.0\n t1sF .= 0.0\n adj_t1sF .= λ\n # Seeding\n nmap = length(H.map)\n\n # Init seed\n _init_seed_hessian!(H.t1sseeds, H.host_t1sseeds, v, nmap)\n AutoDiff.seed!(H.t1sseeds, H.varx, H.t1svarx)\n\n adjoint!(\n polar, H.buffer,\n t1sF, adj_t1sF,\n view(t1sx, 1:nbus), view(adj_t1sx, 1:nbus), # vmag\n view(t1sx, nbus+1:2*nbus), view(adj_t1sx, nbus+1:2*nbus), # vang\n view(t1sx, 2*nbus+1:3*nbus), view(adj_t1sx, 2*nbus+1:3*nbus), # pinj\n )\n\n AutoDiff.getpartials_kernel!(hv, adj_t1sx, H.map)\n return nothing\nend\n\n\n# Adjoint's structure\n\"\"\"\n AdjointStackObjective{VT}\n\nAn object for storing the adjoint stack in the adjoint objective computation.\n\n\"\"\"\nstruct AdjointStackObjective{VT<:AbstractVector}\n ∇fₓ::VT\n ∇fᵤ::VT\n ∂pg::VT\n ∂vm::VT\n ∂va::VT\n ∂pinj::VT\n jvₓ::VT\n jvᵤ::VT\nend\n\nfunction AdjointStackObjective(polar::PolarForm{T, VI, VT, MT}) where {T, VI, VT, MT}\n nbus = get(polar, PS.NumberOfBuses())\n return AdjointStackObjective{VT}(\n xzeros(VT, get(polar, NumberOfState())),\n xzeros(VT, get(polar, NumberOfControl())),\n xzeros(VT, get(polar, PS.NumberOfGenerators())),\n xzeros(VT, nbus),\n xzeros(VT, nbus),\n xzeros(VT, nbus),\n xzeros(VT, get(polar, NumberOfState())),\n xzeros(VT, get(polar, NumberOfControl())),\n )\nend\n\n# Adjoint's stack for Polar\nstruct AdjointPolar{VT} <: AutoDiff.AbstractAdjointStack{VT}\n ∂vm::VT\n ∂va::VT\n ∂pinj::VT\n ∂qinj::VT\n ∂x::VT\n ∂u::VT\nend\n\nfunction AdjointPolar{VT}(nx::Int, nu::Int, nbus::Int) where {VT}\n return AdjointPolar{VT}(\n xzeros(VT, nbus),\n xzeros(VT, nbus),\n xzeros(VT, nbus),\n xzeros(VT, nbus),\n xzeros(VT, nx),\n xzeros(VT, nu),\n )\nend\n\nfunction reset!(adj::AdjointPolar)\n adj.∂vm .= 0.0\n adj.∂va .= 0.0\n adj.∂pinj .= 0.0\n adj.∂x .= 0.0\n adj.∂u .= 0.0\nend\n\n# Stack constructor for each constraint\nfunction AdjointPolar(polar::PolarForm{T, VI, VT, MT}) where {T, VI, VT, MT}\n nbus = get(polar, PS.NumberOfBuses())\n nx = get(polar, NumberOfState())\n nu = get(polar, NumberOfControl())\n return AdjointPolar{VT}(nx, nu, nbus)\nend\n\n\nstruct FullSpaceJacobian{Jacx,Jacu}\n x::Jacx\n u::Jacu\nend\n\nstruct FullSpaceHessian{SpMT}\n xx::SpMT\n xu::SpMT\n uu::SpMT\nend\n\nstruct ConstraintsJacobianStorage{SpMT}\n Jx::SpMT\n Ju::SpMT\n constraints_ad::Vector{FullSpaceJacobian}\nend\n\nfunction ConstraintsJacobianStorage(polar::PolarForm{T, VI, VT, MT}, constraints::Vector{Function}) where {T, VI, VT, MT}\n if isa(polar.device, CPU)\n SpMT = SparseMatrixCSC{Float64, Int}\n elseif isa(polar.device, CUDADevice)\n SpMT = CUSPARSE.CuSparseMatrixCSR{Float64}\n end\n\n SparseCPU = SparseMatrixCSC{Float64, Int}\n\n Jx = SparseCPU[]\n Ju = SparseCPU[]\n # Build global Jacobian on the CPU\n for cons in constraints\n push!(Jx, jacobian_sparsity(polar, cons, State()))\n push!(Ju, jacobian_sparsity(polar, cons, Control()))\n end\n gJx = convert(SpMT, vcat(Jx...))\n gJu = convert(SpMT, vcat(Ju...))\n\n # Build AD\n cons_ad = FullSpaceJacobian[]\n for cons in constraints\n jac_ad_x = _build_jacobian(polar, cons, State())\n jac_ad_u = _build_jacobian(polar, cons, Control())\n push!(cons_ad, FullSpaceJacobian(jac_ad_x, jac_ad_u))\n end\n\n return ConstraintsJacobianStorage{SpMT}(\n gJx,\n gJu,\n cons_ad,\n )\nend\n\nfunction update_full_jacobian!(\n polar::PolarForm,\n cons_jac::ConstraintsJacobianStorage{SpMT},\n buffer::PolarNetworkState\n) where {SpMT}\n shift = 0\n for ad in cons_jac.constraints_ad\n # Update Jacobian\n Jx = AutoDiff.jacobian!(polar, ad.x, buffer)::SpMT\n Ju = AutoDiff.jacobian!(polar, ad.u, buffer)::Union{Nothing, SpMT}\n # Copy back results\n _transfer_sparse!(cons_jac.Jx, Jx, shift)\n if !isnothing(Ju)\n _transfer_sparse!(cons_jac.Ju, Ju, shift)\n end\n\n shift += size(Jx, 1)\n end\n return\nend\n\nstruct HessianStorage{VT,Hess1,Hess2}\n state::Hess1\n obj::Hess2\n constraints::Vector{AutoDiff.Hessian}\n # Adjoints\n z::VT\n ψ::VT\n tmp_tgt::VT\n tmp_hv::VT\nend\n\nfunction HessianStorage(polar::PolarForm{T, VI, VT, MT}, constraints::Vector{Function}) where {T, VI, VT, MT}\n nx = get(polar, NumberOfState())\n nu = get(polar, NumberOfControl())\n\n Hstate = AutoDiff.Hessian(polar, power_balance)\n Hobj = AutoDiff.Hessian(polar, active_power_generation)\n Hcons = AutoDiff.Hessian[]\n for cons in constraints\n push!(Hcons, _build_hessian(polar, cons))\n end\n\n z = xzeros(VT, nx)\n ψ = xzeros(VT, nx)\n\n tgt = xzeros(VT, nx+nu)\n hv = xzeros(VT, nx+nu)\n\n return HessianStorage{VT, typeof(Hstate), typeof(Hobj)}(Hstate, Hobj, Hcons, z, ψ, tgt, hv)\nend\n\n", "meta": {"hexsha": "ee99228c851f9343429804c59d16c9ec98b83c56", "size": 11550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Polar/derivatives.jl", "max_stars_repo_name": "exanauts/ExaPF.jl", "max_stars_repo_head_hexsha": "cd1bcb8a0782fe448d46a10816f82c5d28c3854e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2020-07-15T16:01:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T21:28:25.000Z", "max_issues_repo_path": "src/Polar/derivatives.jl", "max_issues_repo_name": "exanauts/ExaPF.jl", "max_issues_repo_head_hexsha": "cd1bcb8a0782fe448d46a10816f82c5d28c3854e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 129, "max_issues_repo_issues_event_min_datetime": "2020-07-02T11:59:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:10:54.000Z", "max_forks_repo_path": "src/Polar/derivatives.jl", "max_forks_repo_name": "exanauts/ExaPF.jl", "max_forks_repo_head_hexsha": "cd1bcb8a0782fe448d46a10816f82c5d28c3854e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-15T18:49:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T20:12:19.000Z", "avg_line_length": 27.2405660377, "max_line_length": 126, "alphanum_fraction": 0.6313419913, "num_tokens": 3828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.18090453074992266}} {"text": "## Exercise 2-2\n## Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong.\n\n## 1. We’ve seen that n = 42 is legal. What about 42 = n?\nprintln(\"Ans 1:\")\n# 42 = n # Error: syntax: invalid assignment location \"42\"\n\n## 2. How about x = y = 1?\nprintln(\"Ans 2:\")\nx = y = 1 # works fine x and y get assigned 1\n\n## 3. In some languages every statement ends with a semi-colon, ;. What happens if you put a semi-colon at the end of a Julia statement?\nprintln(\"Ans 3:\")\nx = 17; # when in interactive environment it does not print the value, in script no change.\n\n## 4. What if you put a period at the end of a statement?\nprintln(\"Ans 4:\")\nx + 6. # working fine\n# x + y. # Error syntax incomplete OR Load Error type Int64 has no field println\n\n## In math notation you can multiply x and y like this: x y. What happens if you try that in Julia? What about 5x?\nprintln(\"Ans 5:\")\nx = 3\ny = 4\nprintln(5x) # works, 'yey\n# println(xy) # error UndefVarError, as xy will be different from x * y\n# println(x y) # error syntax, missing `,` or `)`\nprintln(x * y)\n\nprintln(\"End.\")\n", "meta": {"hexsha": "43ba1a72a9671a250dd4b9f5cfceb2db2dda80c0", "size": 1183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter2/ex2.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter2/ex2.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2/ex2.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1612903226, "max_line_length": 176, "alphanum_fraction": 0.685545224, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18043112570681338}} {"text": "module SrtmKgb23\n # KURUCZ\n sfluxref = [53.2101 , 51.4143, 49.3348, 45.4612 ,40.8294 , 35.1801, 28.6947, 21.5751 ,14.6388 , 1.59111, 1.31860, 1.04018 ,0.762140,0.484214,0.182275, 2.54948e-02]\n\n # Rayleigh extinction coefficient at all v \n rayl = [5.94837e-08,5.70593e-08,6.27845e-08,5.56602e-08,5.25571e-08,4.73388e-08,4.17466e-08,3.98097e-08,4.00786e-08,3.67478e-08,3.45186e-08,3.46156e-08,3.32155e-08,3.23642e-08,2.72590e-08,2.96813e-08]\n\n # Average Giver et al. correction factor for this band.\n givfac = 1.029\n\n layreffr = 6\n\n # ------------------------------------------------------------------\n\n # The array KA contains absorption coefs at the 16 chosen g-values \n # for a range of pressure levels> ~100mb:and binary:temperatures\n # species parameters (see taumol.f for definition). The first \n # index in the array, JS, runs from 1 to 9, and corresponds to \n # different values of the binary species parameter. For instance, \n # JS=1 refers to dry air, JS = 2 corresponds to the paramter value 1/8, \n # JS = 3 corresponds to the parameter value 2/8, etc. The second index\n # in the array, JT, which runs from 1 to 5, corresponds to different\n # temperatures. More specifically, JT = 3 means that the data are for\n # the reference temperature TREF for this pressure level:JT = 2 refers\n # to TREF-15, JT = 1 is for TREF-30:and JT = 5:JT = 4 is for TREF+15\n # is for TREF+30. The third index:runs from 1 to 13 and refers:JP\n # to the JPth reference pressure level (see taumol.f for these levels\n # in mb). The fourth index, IG, goes from 1 to 16, and indicates\n # which g-interval the absorption coefficients are for.\n # -----------------------------------------------------------------\n ka = zeros(5,13,16)\n ka[:, 1, 1] = [0.33078e-07,0.34034e-07,0.35124e-07,0.34187e-07,0.34744e-07]\n ka[:, 2, 1] = [0.25544e-07,0.25873e-07,0.26742e-07,0.27512e-07,0.27504e-07]\n ka[:, 3, 1] = [0.18549e-07,0.19611e-07,0.20840e-07,0.22548e-07,0.23069e-07]\n ka[:, 4, 1] = [0.28794e-07,0.30837e-07,0.32679e-07,0.34307e-07,0.36901e-07]\n ka[:, 5, 1] = [0.36776e-07,0.39144e-07,0.41300e-07,0.43264e-07,0.46626e-07]\n ka[:, 6, 1] = [0.59710e-07,0.62941e-07,0.65500e-07,0.67353e-07,0.68774e-07]\n ka[:, 7, 1] = [0.12143e-06,0.12932e-06,0.13250e-06,0.13526e-06,0.13849e-06]\n ka[:, 8, 1] = [0.12531e-06,0.13241e-06,0.13939e-06,0.14705e-06,0.15465e-06]\n ka[:, 9, 1] = [0.20209e-06,0.21134e-06,0.22163e-06,0.23098e-06,0.24004e-06]\n ka[:,10, 1] = [0.10750e-05,0.11204e-05,0.11575e-05,0.11923e-05,0.12227e-05]\n ka[:,11, 1] = [0.27782e-05,0.28204e-05,0.28406e-05,0.28380e-05,0.28440e-05]\n ka[:,12, 1] = [0.38510e-05,0.39934e-05,0.40697e-05,0.41102e-05,0.41571e-05]\n ka[:,13, 1] = [0.43157e-05,0.44488e-05,0.45799e-05,0.46585e-05,0.47223e-05]\n ka[:, 1, 2] = [0.84637e-06,0.86989e-06,0.90697e-06,0.90000e-06,0.91373e-06]\n ka[:, 2, 2] = [0.67062e-06,0.68649e-06,0.72334e-06,0.73645e-06,0.72978e-06]\n ka[:, 3, 2] = [0.52317e-06,0.53924e-06,0.55425e-06,0.58347e-06,0.57813e-06]\n ka[:, 4, 2] = [0.39868e-06,0.41431e-06,0.42761e-06,0.43892e-06,0.45982e-06]\n ka[:, 5, 2] = [0.32074e-06,0.33452e-06,0.34754e-06,0.35582e-06,0.37378e-06]\n ka[:, 6, 2] = [0.42465e-06,0.44058e-06,0.45605e-06,0.47192e-06,0.48493e-06]\n ka[:, 7, 2] = [0.47581e-06,0.50000e-06,0.52487e-06,0.54192e-06,0.55955e-06]\n ka[:, 8, 2] = [0.10592e-05,0.11093e-05,0.11483e-05,0.11923e-05,0.12169e-05]\n ka[:, 9, 2] = [0.50835e-05,0.51710e-05,0.52329e-05,0.52644e-05,0.52818e-05]\n ka[:,10, 2] = [0.77867e-05,0.82156e-05,0.86002e-05,0.89664e-05,0.92394e-05]\n ka[:,11, 2] = [0.89031e-05,0.93573e-05,0.97686e-05,0.10236e-04,0.10591e-04]\n ka[:,12, 2] = [0.98068e-05,0.10238e-04,0.10700e-04,0.11108e-04,0.11471e-04]\n ka[:,13, 2] = [0.11145e-04,0.11697e-04,0.12123e-04,0.12482e-04,0.12856e-04]\n ka[:, 1, 3] = [0.66049e-05,0.67547e-05,0.70104e-05,0.69745e-05,0.70687e-05]\n ka[:, 2, 3] = [0.54104e-05,0.55245e-05,0.57623e-05,0.58532e-05,0.58099e-05]\n ka[:, 3, 3] = [0.43608e-05,0.44784e-05,0.45778e-05,0.47665e-05,0.47295e-05]\n ka[:, 4, 3] = [0.35399e-05,0.36454e-05,0.37356e-05,0.38107e-05,0.39586e-05]\n ka[:, 5, 3] = [0.28576e-05,0.29552e-05,0.30325e-05,0.31028e-05,0.32276e-05]\n ka[:, 6, 3] = [0.21017e-05,0.21836e-05,0.22554e-05,0.23121e-05,0.23486e-05]\n ka[:, 7, 3] = [0.19384e-05,0.19914e-05,0.20428e-05,0.20879e-05,0.21191e-05]\n ka[:, 8, 3] = [0.32672e-05,0.33753e-05,0.34694e-05,0.35273e-05,0.35984e-05]\n ka[:, 9, 3] = [0.82257e-05,0.84975e-05,0.86969e-05,0.88995e-05,0.90123e-05]\n ka[:,10, 3] = [0.35363e-04,0.36204e-04,0.36916e-04,0.37708e-04,0.38294e-04]\n ka[:,11, 3] = [0.48837e-04,0.50952e-04,0.52710e-04,0.54347e-04,0.55976e-04]\n ka[:,12, 3] = [0.56059e-04,0.58301e-04,0.60100e-04,0.61776e-04,0.63179e-04]\n ka[:,13, 3] = [0.57871e-04,0.59505e-04,0.60930e-04,0.62289e-04,0.63278e-04]\n ka[:, 1, 4] = [0.27624e-04,0.28017e-04,0.29078e-04,0.28567e-04,0.28724e-04]\n ka[:, 2, 4] = [0.23107e-04,0.23464e-04,0.24357e-04,0.24519e-04,0.24024e-04]\n ka[:, 3, 4] = [0.19113e-04,0.19400e-04,0.19615e-04,0.20420e-04,0.19962e-04]\n ka[:, 4, 4] = [0.15873e-04,0.16138e-04,0.16349e-04,0.16528e-04,0.17176e-04]\n ka[:, 5, 4] = [0.13198e-04,0.13437e-04,0.13641e-04,0.13810e-04,0.14393e-04]\n ka[:, 6, 4] = [0.10951e-04,0.11172e-04,0.11352e-04,0.11506e-04,0.11631e-04]\n ka[:, 7, 4] = [0.86121e-05,0.88300e-05,0.90149e-05,0.91565e-05,0.92594e-05]\n ka[:, 8, 4] = [0.71478e-05,0.72918e-05,0.74035e-05,0.74959e-05,0.75566e-05]\n ka[:, 9, 4] = [0.16458e-04,0.17092e-04,0.17686e-04,0.17967e-04,0.18273e-04]\n ka[:,10, 4] = [0.47953e-04,0.49663e-04,0.51524e-04,0.52800e-04,0.54192e-04]\n ka[:,11, 4] = [0.94263e-04,0.95557e-04,0.96513e-04,0.97430e-04,0.97733e-04]\n ka[:,12, 4] = [0.12087e-03,0.12152e-03,0.12240e-03,0.12318e-03,0.12403e-03]\n ka[:,13, 4] = [0.12781e-03,0.12897e-03,0.13049e-03,0.13171e-03,0.13337e-03]\n ka[:, 1, 5] = [0.82859e-04,0.84817e-04,0.89056e-04,0.88057e-04,0.89410e-04]\n ka[:, 2, 5] = [0.70937e-04,0.72685e-04,0.76796e-04,0.77955e-04,0.76735e-04]\n ka[:, 3, 5] = [0.59876e-04,0.61448e-04,0.62837e-04,0.66293e-04,0.64996e-04]\n ka[:, 4, 5] = [0.50598e-04,0.52054e-04,0.53293e-04,0.54332e-04,0.57333e-04]\n ka[:, 5, 5] = [0.42742e-04,0.44035e-04,0.45164e-04,0.46134e-04,0.48935e-04]\n ka[:, 6, 5] = [0.35769e-04,0.36975e-04,0.38038e-04,0.38917e-04,0.39681e-04]\n ka[:, 7, 5] = [0.29747e-04,0.30824e-04,0.31756e-04,0.32589e-04,0.33314e-04]\n ka[:, 8, 5] = [0.21994e-04,0.22945e-04,0.23786e-04,0.24517e-04,0.25155e-04]\n ka[:, 9, 5] = [0.22298e-04,0.22688e-04,0.23127e-04,0.23803e-04,0.24335e-04]\n ka[:,10, 5] = [0.88898e-04,0.91280e-04,0.93333e-04,0.95224e-04,0.96298e-04]\n ka[:,11, 5] = [0.12299e-03,0.12407e-03,0.12536e-03,0.12642e-03,0.12813e-03]\n ka[:,12, 5] = [0.14539e-03,0.14851e-03,0.15022e-03,0.15157e-03,0.15204e-03]\n ka[:,13, 5] = [0.15949e-03,0.16239e-03,0.16467e-03,0.16667e-03,0.16801e-03]\n ka[:, 1, 6] = [0.25339e-03,0.25995e-03,0.27170e-03,0.26963e-03,0.27413e-03]\n ka[:, 2, 6] = [0.21908e-03,0.22404e-03,0.23522e-03,0.23902e-03,0.23717e-03]\n ka[:, 3, 6] = [0.18611e-03,0.19076e-03,0.19518e-03,0.20503e-03,0.20222e-03]\n ka[:, 4, 6] = [0.15769e-03,0.16210e-03,0.16597e-03,0.16948e-03,0.17817e-03]\n ka[:, 5, 6] = [0.13402e-03,0.13792e-03,0.14153e-03,0.14434e-03,0.15267e-03]\n ka[:, 6, 6] = [0.11390e-03,0.11743e-03,0.12065e-03,0.12316e-03,0.12543e-03]\n ka[:, 7, 6] = [0.96417e-04,0.99612e-04,0.10233e-03,0.10453e-03,0.10652e-03]\n ka[:, 8, 6] = [0.81395e-04,0.84205e-04,0.86346e-04,0.88406e-04,0.90122e-04]\n ka[:, 9, 6] = [0.47776e-04,0.48971e-04,0.49736e-04,0.49917e-04,0.50289e-04]\n ka[:,10, 6] = [0.10698e-03,0.10815e-03,0.10817e-03,0.10799e-03,0.10851e-03]\n ka[:,11, 6] = [0.20220e-03,0.20727e-03,0.21241e-03,0.21675e-03,0.21989e-03]\n ka[:,12, 6] = [0.23474e-03,0.23601e-03,0.23974e-03,0.24383e-03,0.24876e-03]\n ka[:,13, 6] = [0.23410e-03,0.23809e-03,0.24185e-03,0.24554e-03,0.24952e-03]\n ka[:, 1, 7] = [0.67024e-03,0.68026e-03,0.70419e-03,0.70159e-03,0.71089e-03]\n ka[:, 2, 7] = [0.58729e-03,0.59778e-03,0.62097e-03,0.62912e-03,0.62423e-03]\n ka[:, 3, 7] = [0.50967e-03,0.51900e-03,0.52765e-03,0.54794e-03,0.54266e-03]\n ka[:, 4, 7] = [0.44167e-03,0.45006e-03,0.45793e-03,0.46469e-03,0.48335e-03]\n ka[:, 5, 7] = [0.38096e-03,0.38881e-03,0.39576e-03,0.40259e-03,0.42086e-03]\n ka[:, 6, 7] = [0.32818e-03,0.33539e-03,0.34192e-03,0.34829e-03,0.35405e-03]\n ka[:, 7, 7] = [0.28259e-03,0.28946e-03,0.29584e-03,0.30203e-03,0.30742e-03]\n ka[:, 8, 7] = [0.24273e-03,0.24912e-03,0.25546e-03,0.26110e-03,0.26607e-03]\n ka[:, 9, 7] = [0.19937e-03,0.20653e-03,0.21314e-03,0.21968e-03,0.22520e-03]\n ka[:,10, 7] = [0.13306e-03,0.13331e-03,0.13393e-03,0.13538e-03,0.13616e-03]\n ka[:,11, 7] = [0.16236e-03,0.16154e-03,0.16187e-03,0.16113e-03,0.16209e-03]\n ka[:,12, 7] = [0.17872e-03,0.18355e-03,0.18612e-03,0.18792e-03,0.18745e-03]\n ka[:,13, 7] = [0.18970e-03,0.19384e-03,0.19773e-03,0.20261e-03,0.20377e-03]\n ka[:, 1, 8] = [0.18130e-02,0.18305e-02,0.18716e-02,0.18655e-02,0.18814e-02]\n ka[:, 2, 8] = [0.16420e-02,0.16600e-02,0.17006e-02,0.17156e-02,0.17108e-02]\n ka[:, 3, 8] = [0.14687e-02,0.14870e-02,0.15042e-02,0.15423e-02,0.15376e-02]\n ka[:, 4, 8] = [0.13068e-02,0.13248e-02,0.13421e-02,0.13592e-02,0.13960e-02]\n ka[:, 5, 8] = [0.11574e-02,0.11753e-02,0.11928e-02,0.12097e-02,0.12467e-02]\n ka[:, 6, 8] = [0.10167e-02,0.10342e-02,0.10515e-02,0.10681e-02,0.10840e-02]\n ka[:, 7, 8] = [0.88992e-03,0.90662e-03,0.92299e-03,0.93844e-03,0.95347e-03]\n ka[:, 8, 8] = [0.78445e-03,0.80031e-03,0.81639e-03,0.83131e-03,0.84631e-03]\n ka[:, 9, 8] = [0.69812e-03,0.71312e-03,0.72801e-03,0.74222e-03,0.75605e-03]\n ka[:,10, 8] = [0.32521e-03,0.33835e-03,0.35194e-03,0.36381e-03,0.37594e-03]\n ka[:,11, 8] = [0.31406e-03,0.32013e-03,0.32456e-03,0.33261e-03,0.33741e-03]\n ka[:,12, 8] = [0.28132e-03,0.28732e-03,0.29674e-03,0.30509e-03,0.31393e-03]\n ka[:,13, 8] = [0.25704e-03,0.26316e-03,0.27195e-03,0.27732e-03,0.28905e-03]\n ka[:, 1, 9] = [0.67370e-02,0.67873e-02,0.68896e-02,0.68819e-02,0.69268e-02]\n ka[:, 2, 9] = [0.63111e-02,0.63622e-02,0.64623e-02,0.65060e-02,0.65027e-02]\n ka[:, 3, 9] = [0.58834e-02,0.59361e-02,0.59858e-02,0.60811e-02,0.60806e-02]\n ka[:, 4, 9] = [0.54753e-02,0.55309e-02,0.55823e-02,0.56306e-02,0.57229e-02]\n ka[:, 5, 9] = [0.50781e-02,0.51373e-02,0.51895e-02,0.52391e-02,0.53328e-02]\n ka[:, 6, 9] = [0.46791e-02,0.47408e-02,0.47949e-02,0.48470e-02,0.48993e-02]\n ka[:, 7, 9] = [0.42724e-02,0.43381e-02,0.43951e-02,0.44503e-02,0.45061e-02]\n ka[:, 8, 9] = [0.38568e-02,0.39254e-02,0.39848e-02,0.40431e-02,0.41005e-02]\n ka[:, 9, 9] = [0.35657e-02,0.36362e-02,0.36994e-02,0.37608e-02,0.38215e-02]\n ka[:,10, 9] = [0.33774e-02,0.34501e-02,0.35171e-02,0.35811e-02,0.36450e-02]\n ka[:,11, 9] = [0.23923e-02,0.24623e-02,0.25263e-02,0.25890e-02,0.26517e-02]\n ka[:,12, 9] = [0.16959e-02,0.17542e-02,0.18077e-02,0.18614e-02,0.19187e-02]\n ka[:,13, 9] = [0.11732e-02,0.12232e-02,0.12712e-02,0.13221e-02,0.13677e-02]\n ka[:, 1,10] = [0.19604e-01,0.19698e-01,0.19938e-01,0.19854e-01,0.19950e-01]\n ka[:, 2,10] = [0.18714e-01,0.18803e-01,0.19035e-01,0.19131e-01,0.19102e-01]\n ka[:, 3,10] = [0.17676e-01,0.17785e-01,0.17904e-01,0.18189e-01,0.18156e-01]\n ka[:, 4,10] = [0.16662e-01,0.16773e-01,0.16908e-01,0.17056e-01,0.17303e-01]\n ka[:, 5,10] = [0.15655e-01,0.15775e-01,0.15942e-01,0.16103e-01,0.16359e-01]\n ka[:, 6,10] = [0.14694e-01,0.14838e-01,0.15029e-01,0.15200e-01,0.15320e-01]\n ka[:, 7,10] = [0.13797e-01,0.13959e-01,0.14174e-01,0.14350e-01,0.14471e-01]\n ka[:, 8,10] = [0.12902e-01,0.13089e-01,0.13313e-01,0.13489e-01,0.13626e-01]\n ka[:, 9,10] = [0.11897e-01,0.12105e-01,0.12333e-01,0.12512e-01,0.12656e-01]\n ka[:,10,10] = [0.11834e-01,0.12072e-01,0.12331e-01,0.12548e-01,0.12721e-01]\n ka[:,11,10] = [0.11416e-01,0.11699e-01,0.11968e-01,0.12141e-01,0.12311e-01]\n ka[:,12,10] = [0.10776e-01,0.11070e-01,0.11309e-01,0.11507e-01,0.11702e-01]\n ka[:,13,10] = [0.99577e-02,0.10263e-01,0.10492e-01,0.10719e-01,0.10951e-01]\n ka[:, 1,11] = [0.29783e-01,0.29883e-01,0.30210e-01,0.30141e-01,0.30248e-01]\n ka[:, 2,11] = [0.28562e-01,0.28743e-01,0.29186e-01,0.29339e-01,0.29258e-01]\n ka[:, 3,11] = [0.27212e-01,0.27429e-01,0.27654e-01,0.28083e-01,0.28023e-01]\n ka[:, 4,11] = [0.25949e-01,0.26197e-01,0.26424e-01,0.26623e-01,0.27069e-01]\n ka[:, 5,11] = [0.24686e-01,0.24942e-01,0.25176e-01,0.25403e-01,0.25908e-01]\n ka[:, 6,11] = [0.23430e-01,0.23686e-01,0.23923e-01,0.24158e-01,0.24433e-01]\n ka[:, 7,11] = [0.22171e-01,0.22424e-01,0.22653e-01,0.22909e-01,0.23203e-01]\n ka[:, 8,11] = [0.20928e-01,0.21171e-01,0.21407e-01,0.21699e-01,0.22018e-01]\n ka[:, 9,11] = [0.19076e-01,0.19320e-01,0.19548e-01,0.19858e-01,0.20150e-01]\n ka[:,10,11] = [0.19537e-01,0.19788e-01,0.20064e-01,0.20391e-01,0.20843e-01]\n ka[:,11,11] = [0.19137e-01,0.19444e-01,0.19793e-01,0.20268e-01,0.20695e-01]\n ka[:,12,11] = [0.18393e-01,0.18715e-01,0.19143e-01,0.19652e-01,0.20037e-01]\n ka[:,13,11] = [0.17255e-01,0.17680e-01,0.18170e-01,0.18641e-01,0.19010e-01]\n ka[:, 1,12] = [0.46641e-01,0.46796e-01,0.47107e-01,0.46977e-01,0.47093e-01]\n ka[:, 2,12] = [0.46819e-01,0.46956e-01,0.47337e-01,0.47426e-01,0.47339e-01]\n ka[:, 3,12] = [0.46276e-01,0.46366e-01,0.46462e-01,0.46935e-01,0.46862e-01]\n ka[:, 4,12] = [0.44986e-01,0.45103e-01,0.45287e-01,0.45535e-01,0.46152e-01]\n ka[:, 5,12] = [0.43367e-01,0.43552e-01,0.43761e-01,0.44035e-01,0.44674e-01]\n ka[:, 6,12] = [0.41584e-01,0.41793e-01,0.42020e-01,0.42344e-01,0.42701e-01]\n ka[:, 7,12] = [0.39785e-01,0.40007e-01,0.40269e-01,0.40635e-01,0.41003e-01]\n ka[:, 8,12] = [0.37918e-01,0.38155e-01,0.38468e-01,0.38839e-01,0.39210e-01]\n ka[:, 9,12] = [0.35060e-01,0.35328e-01,0.35698e-01,0.36105e-01,0.36551e-01]\n ka[:,10,12] = [0.35216e-01,0.35547e-01,0.35872e-01,0.36327e-01,0.36542e-01]\n ka[:,11,12] = [0.35158e-01,0.35374e-01,0.35869e-01,0.36242e-01,0.36691e-01]\n ka[:,12,12] = [0.34264e-01,0.34598e-01,0.35106e-01,0.35505e-01,0.36021e-01]\n ka[:,13,12] = [0.32716e-01,0.33195e-01,0.33830e-01,0.34228e-01,0.34925e-01]\n ka[:, 1,13] = [0.76084e-01,0.76052e-01,0.76051e-01,0.75851e-01,0.75753e-01]\n ka[:, 2,13] = [0.79580e-01,0.79564e-01,0.79664e-01,0.79619e-01,0.79414e-01]\n ka[:, 3,13] = [0.82218e-01,0.82302e-01,0.82367e-01,0.82543e-01,0.82246e-01]\n ka[:, 4,13] = [0.83613e-01,0.83740e-01,0.83824e-01,0.83866e-01,0.84103e-01]\n ka[:, 5,13] = [0.83913e-01,0.84123e-01,0.84289e-01,0.84403e-01,0.84840e-01]\n ka[:, 6,13] = [0.83159e-01,0.83442e-01,0.83718e-01,0.83891e-01,0.83993e-01]\n ka[:, 7,13] = [0.81401e-01,0.81826e-01,0.82202e-01,0.82451e-01,0.82656e-01]\n ka[:, 8,13] = [0.78949e-01,0.79505e-01,0.79978e-01,0.80351e-01,0.80690e-01]\n ka[:, 9,13] = [0.76002e-01,0.76671e-01,0.77279e-01,0.77752e-01,0.78257e-01]\n ka[:,10,13] = [0.69777e-01,0.70425e-01,0.71054e-01,0.71706e-01,0.72167e-01]\n ka[:,11,13] = [0.72929e-01,0.73732e-01,0.74323e-01,0.75246e-01,0.75786e-01]\n ka[:,12,13] = [0.73007e-01,0.74429e-01,0.74922e-01,0.75916e-01,0.76947e-01]\n ka[:,13,13] = [0.71376e-01,0.72507e-01,0.73710e-01,0.74716e-01,0.75702e-01]\n ka[:, 1,14] = [0.12585e+00,0.12569e+00,0.12576e+00,0.12571e+00,0.12570e+00]\n ka[:, 2,14] = [0.13868e+00,0.13853e+00,0.13849e+00,0.13824e+00,0.13803e+00]\n ka[:, 3,14] = [0.15142e+00,0.15135e+00,0.15112e+00,0.15093e+00,0.15074e+00]\n ka[:, 4,14] = [0.16359e+00,0.16359e+00,0.16339e+00,0.16311e+00,0.16285e+00]\n ka[:, 5,14] = [0.17462e+00,0.17472e+00,0.17456e+00,0.17421e+00,0.17393e+00]\n ka[:, 6,14] = [0.18403e+00,0.18447e+00,0.18450e+00,0.18424e+00,0.18395e+00]\n ka[:, 7,14] = [0.19179e+00,0.19239e+00,0.19256e+00,0.19253e+00,0.19252e+00]\n ka[:, 8,14] = [0.19772e+00,0.19863e+00,0.19901e+00,0.19923e+00,0.19947e+00]\n ka[:, 9,14] = [0.20154e+00,0.20279e+00,0.20355e+00,0.20417e+00,0.20473e+00]\n ka[:,10,14] = [0.18853e+00,0.19028e+00,0.19160e+00,0.19253e+00,0.19393e+00]\n ka[:,11,14] = [0.18013e+00,0.18167e+00,0.18320e+00,0.18375e+00,0.18507e+00]\n ka[:,12,14] = [0.19011e+00,0.19027e+00,0.19283e+00,0.19402e+00,0.19478e+00]\n ka[:,13,14] = [0.19594e+00,0.19738e+00,0.19911e+00,0.20124e+00,0.20282e+00]\n ka[:, 1,15] = [0.22369e+00,0.22259e+00,0.22155e+00,0.22059e+00,0.21997e+00]\n ka[:, 2,15] = [0.25602e+00,0.25478e+00,0.25377e+00,0.25306e+00,0.25237e+00]\n ka[:, 3,15] = [0.29258e+00,0.29107e+00,0.28998e+00,0.28920e+00,0.28830e+00]\n ka[:, 4,15] = [0.33067e+00,0.32888e+00,0.32753e+00,0.32646e+00,0.32566e+00]\n ka[:, 5,15] = [0.37114e+00,0.36880e+00,0.36713e+00,0.36598e+00,0.36499e+00]\n ka[:, 6,15] = [0.41494e+00,0.41167e+00,0.40935e+00,0.40779e+00,0.40636e+00]\n ka[:, 7,15] = [0.46115e+00,0.45729e+00,0.45455e+00,0.45230e+00,0.45004e+00]\n ka[:, 8,15] = [0.50906e+00,0.50463e+00,0.50137e+00,0.49843e+00,0.49550e+00]\n ka[:, 9,15] = [0.55829e+00,0.55330e+00,0.54936e+00,0.54557e+00,0.54168e+00]\n ka[:,10,15] = [0.60814e+00,0.60274e+00,0.59806e+00,0.59326e+00,0.58833e+00]\n ka[:,11,15] = [0.62954e+00,0.62588e+00,0.62076e+00,0.61665e+00,0.61184e+00]\n ka[:,12,15] = [0.62585e+00,0.62437e+00,0.61807e+00,0.61303e+00,0.60869e+00]\n ka[:,13,15] = [0.64856e+00,0.64505e+00,0.63861e+00,0.63277e+00,0.62702e+00]\n ka[:, 1,16] = [0.33327e+00,0.33385e+00,0.33538e+00,0.33638e+00,0.33736e+00]\n ka[:, 2,16] = [0.40916e+00,0.40842e+00,0.40848e+00,0.40865e+00,0.40854e+00]\n ka[:, 3,16] = [0.50099e+00,0.49888e+00,0.49727e+00,0.49588e+00,0.49422e+00]\n ka[:, 4,16] = [0.60389e+00,0.60029e+00,0.59704e+00,0.59367e+00,0.59071e+00]\n ka[:, 5,16] = [0.71868e+00,0.71337e+00,0.70835e+00,0.70318e+00,0.69852e+00]\n ka[:, 6,16] = [0.84815e+00,0.84138e+00,0.83446e+00,0.82728e+00,0.82023e+00]\n ka[:, 7,16] = [0.99512e+00,0.98644e+00,0.97698e+00,0.96695e+00,0.95712e+00]\n ka[:, 8,16] = [0.11606e+01,0.11485e+01,0.11354e+01,0.11218e+01,0.11077e+01]\n ka[:, 9,16] = [0.13444e+01,0.13282e+01,0.13102e+01,0.12917e+01,0.12735e+01]\n ka[:,10,16] = [0.15423e+01,0.15207e+01,0.14970e+01,0.14733e+01,0.14494e+01]\n ka[:,11,16] = [0.17462e+01,0.17138e+01,0.16827e+01,0.16518e+01,0.16199e+01]\n ka[:,12,16] = [0.19577e+01,0.19145e+01,0.18728e+01,0.18320e+01,0.17910e+01]\n ka[:,13,16] = [0.21716e+01,0.21171e+01,0.20639e+01,0.20113e+01,0.19587e+01]\n \n # -----------------------------------------------------------------\n forref = zeros(3,16)\n forref[:, 1] = [ 0.315770e-07, 0.671978e-07, 0.440649e-06 ]\n forref[:, 2] = [ 0.313674e-06, 0.285252e-06, 0.421024e-05 ]\n forref[:, 3] = [ 0.135818e-05, 0.145071e-05, 0.611285e-05 ]\n forref[:, 4] = [ 0.534065e-05, 0.586268e-05, 0.933970e-05 ]\n forref[:, 5] = [ 0.964007e-05, 0.107110e-04, 0.104486e-04 ]\n forref[:, 6] = [ 0.302775e-04, 0.357530e-04, 0.340724e-04 ]\n forref[:, 7] = [ 0.102437e-03, 0.108475e-03, 0.105245e-03 ]\n forref[:, 8] = [ 0.146054e-03, 0.141490e-03, 0.133071e-03 ]\n forref[:, 9] = [ 0.163978e-03, 0.150208e-03, 0.142864e-03 ]\n forref[:,10] = [ 0.220412e-03, 0.182943e-03, 0.150941e-03 ]\n forref[:,11] = [ 0.228877e-03, 0.197679e-03, 0.163220e-03 ]\n forref[:,12] = [ 0.234177e-03, 0.217734e-03, 0.185038e-03 ]\n forref[:,13] = [ 0.257187e-03, 0.241570e-03, 0.221178e-03 ]\n forref[:,14] = [ 0.272455e-03, 0.270637e-03, 0.256269e-03 ]\n forref[:,15] = [ 0.339445e-03, 0.300268e-03, 0.286574e-03 ]\n forref[:,16] = [ 0.338841e-03, 0.355428e-03, 0.353794e-03 ]\n\n # -----------------------------------------------------------------\n # The array SELFREF contains the coefficient of the water vapor\n # self-continuum (including the energy term). The first index\n # refers to temperature in 7.2 degree increments. For instance,\n # JT = 1 refers to a temperature of 245.6, JT = 2 refers to 252.8,\n # etc. The second index runs over the g-channel (1 to 16).\n selfref = zeros(10,16)\n selfref[:, 1] = [0.100945e-04, 0.801113e-05, 0.635771e-05, 0.504554e-05, 0.400419e-05,0.317777e-05, 0.252191e-05, 0.200141e-05, 0.158834e-05, 0.126052e-05]\n selfref[:, 2] = [0.107573e-04, 0.999809e-05, 0.929245e-05, 0.863661e-05, 0.802706e-05,0.746053e-05, 0.693399e-05, 0.644460e-05, 0.598976e-05, 0.556702e-05]\n selfref[:, 3] = [0.350389e-04, 0.319234e-04, 0.290850e-04, 0.264989e-04, 0.241428e-04,0.219962e-04, 0.200404e-04, 0.182586e-04, 0.166351e-04, 0.151560e-04]\n selfref[:, 4] = [0.122993e-03, 0.110885e-03, 0.999691e-04, 0.901277e-04, 0.812551e-04,0.732559e-04, 0.660443e-04, 0.595426e-04, 0.536809e-04, 0.483963e-04]\n selfref[:, 5] = [0.206434e-03, 0.187435e-03, 0.170185e-03, 0.154522e-03, 0.140301e-03,0.127388e-03, 0.115664e-03, 0.105019e-03, 0.953540e-04, 0.865783e-04]\n selfref[:, 6] = [0.590645e-03, 0.533109e-03, 0.481177e-03, 0.434305e-03, 0.391998e-03,0.353812e-03, 0.319346e-03, 0.288238e-03, 0.260160e-03, 0.234817e-03]\n selfref[:, 7] = [0.163029e-02, 0.148773e-02, 0.135763e-02, 0.123891e-02, 0.113057e-02,0.103170e-02, 0.941483e-03, 0.859153e-03, 0.784023e-03, 0.715462e-03]\n selfref[:, 8] = [0.204528e-02, 0.189258e-02, 0.175128e-02, 0.162053e-02, 0.149954e-02,0.138758e-02, 0.128398e-02, 0.118812e-02, 0.109941e-02, 0.101733e-02]\n selfref[:, 9] = [0.210589e-02, 0.197078e-02, 0.184434e-02, 0.172601e-02, 0.161528e-02,0.151164e-02, 0.141466e-02, 0.132390e-02, 0.123896e-02, 0.115947e-02]\n selfref[:,10] = [0.245098e-02, 0.233745e-02, 0.222918e-02, 0.212592e-02, 0.202745e-02,0.193353e-02, 0.184397e-02, 0.175856e-02, 0.167710e-02, 0.159941e-02]\n selfref[:,11] = [0.267460e-02, 0.253325e-02, 0.239936e-02, 0.227255e-02, 0.215244e-02,0.203868e-02, 0.193093e-02, 0.182888e-02, 0.173222e-02, 0.164067e-02]\n selfref[:,12] = [0.304510e-02, 0.283919e-02, 0.264720e-02, 0.246820e-02, 0.230130e-02,0.214568e-02, 0.200059e-02, 0.186531e-02, 0.173918e-02, 0.162157e-02]\n selfref[:,13] = [0.338445e-02, 0.314719e-02, 0.292655e-02, 0.272139e-02, 0.253060e-02,0.235319e-02, 0.218822e-02, 0.203482e-02, 0.189217e-02, 0.175952e-02]\n selfref[:,14] = [0.388649e-02, 0.357018e-02, 0.327961e-02, 0.301269e-02, 0.276750e-02,0.254226e-02, 0.233535e-02, 0.214528e-02, 0.197068e-02, 0.181029e-02]\n selfref[:,15] = [0.412547e-02, 0.387413e-02, 0.363810e-02, 0.341646e-02, 0.320831e-02,0.301285e-02, 0.282930e-02, 0.265693e-02, 0.249506e-02, 0.234305e-02]\n selfref[:,16] = [0.534327e-02, 0.482967e-02, 0.436544e-02, 0.394583e-02, 0.356655e-02,0.322373e-02, 0.291387e-02, 0.263378e-02, 0.238062e-02, 0.215179e-02]\nend", "meta": {"hexsha": "2a4ce5655da9f49c094ce63a8b8c919071bcd6f7", "size": 22126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "srtm_kgbs/srtm_kgb23.jl", "max_stars_repo_name": "jsbj/RRTM.jl", "max_stars_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-05-25T03:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T12:05:50.000Z", "max_issues_repo_path": "srtm_kgbs/srtm_kgb23.jl", "max_issues_repo_name": "jsbj/RRTM.jl", "max_issues_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srtm_kgbs/srtm_kgb23.jl", "max_forks_repo_name": "jsbj/RRTM.jl", "max_forks_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 78.183745583, "max_line_length": 202, "alphanum_fraction": 0.6365813975, "num_tokens": 13342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.23651624182730094, "lm_q1q2_score": 0.1799062337147158}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ c4cccb7a-7d16-4dca-95d9-45c4115cfbf0\nbegin\n import Pkg\n Pkg.activate(mktempdir())\n Pkg.add([\n Pkg.PackageSpec(name=\"BenchmarkTools\", version=\"1\"),\n Pkg.PackageSpec(name=\"Distributions\", version=\"0.25\"),\n Pkg.PackageSpec(name=\"KernelDensity\", version=\"0.6\"),\n Pkg.PackageSpec(name=\"LaTeXStrings\", version=\"1\"),\n Pkg.PackageSpec(name=\"Plots\", version=\"1\"),\n Pkg.PackageSpec(name=\"PlutoUI\", version=\"0.7\"),\n Pkg.PackageSpec(name=\"StatsBase\", version=\"0.33\"),\n Pkg.PackageSpec(name=\"StatsPlots\", version=\"0.14\"),\n ])\n using BenchmarkTools, Distributions, KernelDensity, LaTeXStrings, LinearAlgebra, Plots, PlutoUI, StatsBase, Statistics, StatsPlots\nend\n\n# ╔═╡ 09a9d9f9-fa1a-4192-95cc-81314582488b\nhtml\"\"\"\n
\n\n
\n

ATS 872: Lecture 1

\n

\n Sampling and random variables \n

\n\n\"\"\"\n\n# ╔═╡ 41eb90d1-9262-42b1-9eb2-d7aa6583da17\nhtml\"\"\"\n\n\"\"\"\n\n# ╔═╡ f4a548e6-8949-4528-8b26-d30275b9e2c8\nmd\" # Introduction \"\n\n# ╔═╡ c65ae735-b404-4798-97f2-29083e7ae44c\nmd\" > **Note:** A significant portion of the material for this lecture is based on [Computational Thinking](https://computationalthinking.mit.edu), a live online Julia/Pluto textbook. You should check out the course for some amazing notebooks! \"\n\n# ╔═╡ 000021af-87ce-4d6d-a315-153cecce5091\nmd\" In our introductory session (Lecture 0) we had a brief introduction to Julia via the QuantEcon website. In this first tutorial we will be looking at some basic ideas such as sampling and random variables. Julia is an amazing language for computational problems and is much faster than R for most practical applications in Bayesian Econometrics. You are welcome to still code in R if you wish. I will steer you in the right direction with resources from last year. However, I think it is worthwhile to learn Julia since the syntax is similar to Python and Matlab. \n\n**Note**: In terms of the project that you have to do at the end of the semester, most of you might want to use packages that are available in R, since the ecosystem is more mature and more packages are available. If you want to code up your own routines for your project using Julia, this will be more difficult. However, if you follow the notebooks carefully it should be within your reach. \"\n\n# ╔═╡ 49033e09-fd64-4707-916c-9435d3f0a9d2\nmd\" This notebook we are working with is called a `Pluto` notebook and is useful for educational purposes. If you want to code in an integrated development environment, almost like `Rstudio`, then I recommend `VSCode`. \"\n\n# ╔═╡ 2eb626bc-43c5-4d73-bd71-0de45f9a3ca1\nTableOfContents() # Uncomment for TOC\n\n# ╔═╡ d65de56f-a210-4428-9fac-20a7888d3627\nmd\" Packages used for this notebook are given above. Check them out on **Github** and give a star ⭐ if you want.\"\n\n# ╔═╡ da871a80-a6d8-4be2-92bb-c3f10e51efe3\nmd\" ## Resources \"\n\n# ╔═╡ 98a8dd21-8dc4-4880-8975-265249f816ce\nmd\" Here are some links to useful resources for this course. I have tried to not introduce long textbook treatments. I will strive to provide free resources for the course whenever possible. \"\n\n# ╔═╡ 15dcbe6b-b51e-4472-a8e0-08cbd49d1e8c\nmd\"\"\"\n!!! note \"Some cool links 😎\"\n\n1. MIT (2021). [Computational Thinking](https://computationalthinking.mit.edu). -- NB resource! Most of the lecture based on this. \n2. QuantEcon (2021). [Quantitative Economics with Julia](https://julia.quantecon.org/). -- Lectures 0, 4, 8.\n3. Aki Vehtari (2020). [Bayesian Data Analysis](https://avehtari.github.io/BDA_course_Aalto/index.html). -- Lectures 2, 3, 4, 5\n5. Mattias Villani (2021). [Bayesian Learning](https://github.com/mattiasvillani/BayesianLearningBook) -- Lectures 2, 3, 4, 5\n4. José Eduardo Storopoli (2021). [Bayesian Statistics with Julia and Turing.](https://storopoli.io/Bayesian-Julia/) -- Lectures 2, 3, 4, 9\n5. Gary Koop (2021). [Bayesian Econometrics](https://sites.google.com/site/garykoop/teaching/sgpe-bayesian-econometrics). -- Lectures 5, 6, 7\n6. Joshua Chan (2017). [Notes on Bayesian Econometrics](https://joshuachan.org/notes_BayesMacro.html). -- Lectures 5, 6, 7\n\n\"\"\"\n\n# ╔═╡ be11b67f-d04d-46b1-a935-eedd7e59ede3\nmd\" There is a book by Gary Koop, called Bayesian Econometrics, that accompanies the course above. However, it is not essential to have the book. I will upload some articles that with similar content. Let us get going with the first lecture, we will start with the idea of random sampling. \"\n\n# ╔═╡ 040c011f-1653-446d-8641-824dc82162eb\nmd\" ## Random sampling \"\n\n# ╔═╡ 0d0f08f3-48e2-402c-bbb5-33bd3d09ab06\nmd\" One thing that we will be using quite frequently in Bayesian econometrics is the idea of random sampling. This means sampling from different types of distributions. \"\n\n# ╔═╡ b78745cc-84ef-4bbe-a916-9c87cde47145\nrand(1:6) # Choose random value from 1 to 6 \n\n# ╔═╡ 08fc15b7-2cc6-4a21-82a6-521f6294ee79\nrand([2, 3, 5, 7, 11]) # Choose random value from this set of values\n\n# ╔═╡ 4c48df5c-33c6-4d26-b6e4-80e3c883d389\nrand() # random number between 0 and 1 -- similar to runif() in R\n\n# ╔═╡ 350bb07e-6e88-49fc-ae69-c24b1549650d\ndcolours = distinguishable_colors(10)\n\n# ╔═╡ 07b17b42-e968-4a7a-bf56-da1a3a1bef52\nrand(dcolours) \n\n# ╔═╡ dc306e4a-7841-4c36-8c5b-d96acc7714de\nmd\" We can also sample several random objects from the same collection. In this case we use an **array comprehension**. \"\n\n# ╔═╡ 71482500-7ca7-4a4e-8635-f29ee6f11ced\n[rand(1:6) for i in 1:10]\n\n# ╔═╡ b028662e-a8ac-45c4-86aa-d684bbb864c8\nmd\" An easier way to do this is to simply add another argument to the `rand` function. \"\n\n# ╔═╡ f882026e-3393-46a7-b284-f0313386f214\nrand(1:6, 10) # This generates an array in the same way as above\n\n# ╔═╡ a69254ad-d7e2-4ddd-9a8f-58eaa9a45ce8\nmd\" We can also generate random matrices in with this function. \"\n\n# ╔═╡ 94a2862e-1f6b-4c4e-ad32-4b6c49924454\nrand(1:6, 10, 10) # Generates a 10x10 matrix with values that range from 1 to 6\n\n# ╔═╡ fa929cc1-ce08-4c9a-922b-cdf611fa3e2a\nrand(dcolours, 10, 10) # Generate matrix of colours\n\n# ╔═╡ 909ea3be-9b65-465a-ab31-0d3d525c021f\nmd\" ## Uniform sampling \"\n\n# ╔═╡ b1d3017e-8caf-462f-bb0b-8154202f21e6\nmd\" The `rand` function has performed uniform sampling, which means that each object has the same probability of being selected. For our next example we will be counting heads and tails using the `countmap` function. \"\n\n# ╔═╡ 9492ddc5-301d-46d2-bf34-5396563f5d5b\ntosses = rand( [\"head\", \"tail\"], 10000)\n\n# ╔═╡ 4f5e9c1f-d510-4897-9176-218a1a2f4057\ntoss_counts = countmap(tosses)\n\n# ╔═╡ 7254eb45-8170-40f2-afd3-e30ec5c26781\nmd\" In this case we have a dictionary that maps keys, such as `heads` and `tails`, to specific values. \"\n\n# ╔═╡ caeee82e-b854-4b34-b34f-5899e5a9b952\nprob_tail = toss_counts[\"tail\"] / length(tosses) # Determines the probability of a tail. \n\n# ╔═╡ cdad68ca-dac9-49ad-8149-939d18f00778\nmd\" ## Tossing a weighted coin \"\n\n# ╔═╡ ea5a71b7-845b-4310-b1fb-f69ee71ac3fb\nmd\"\"\"\nHow could we model a coin that is **weighted**, so that it is more likely to come up heads? We want to assign a probability $p = 0.7$ to heads, and $q = 0.3$ to tails. \n\"\"\"\n\n# ╔═╡ d6aa79f3-45c8-4ff5-84d6-1cd79b845b2f\nmd\"\"\"\nOne way would be to generate random integers between $1$ and $10$ and assign heads to a subset of the possible results with the desired probability, e.g. $1:7$ get heads, and $8:10$ get tails. We will use this same logic later in other examples, so it is important to understand what we are doing here. \n\"\"\"\n\n# ╔═╡ 0d46dd99-c614-40a6-9cd0-69b453ec782f\nfunction simple_weighted_coin()\n\tif rand(1:10) ≤ 7\n\t\t\"heads\"\n\telse \n\t\t\"tails\"\n\tend\nend # Quite verbose, but good for pedagogical purposes. \n\n# ╔═╡ da3b79da-3d14-405f-80af-d58d04b4f801\nsimple_weighted_coin()\n\n# ╔═╡ 18d07eee-60af-4dad-8f4a-9426f5907ad3\nmd\" Another way to do this might be with a **ternary operator**, see the Julia documentation [here](https://docs.julialang.org/en/v1/manual/control-flow/). \"\n\n# ╔═╡ f40f5823-f383-4d6e-a651-91c5a03cbf1e\nsimple_weighted_coin2() = rand(1:10) ≤ 7 ? \"heads\" : \"tails\" \n\n# ╔═╡ 2970a6d2-599a-44ce-ab09-d52db64c0c64\nsimple_weighted_coin2()\n\n# ╔═╡ 5b54210f-9a7d-447e-9491-f8fbb0892e7f\nmd\" If we generate a uniform number between $0$ and $1$ and then check if it is less than some probability, this is known as one **Bernoulli trial**. Binomial and Bernoulli random variables will be covered in more detail later in the lecture and also defined more formally in the next lecture. For now you simply need to understand the process. We can construct a simple Bernoulli function that encapsulates this idea. \"\n\n# ╔═╡ e9df057d-3781-4fe1-b0ca-fab08b895ca2\nbernoulli(p) = rand() < p # Takes in a value p between 0 and 1 to compare against\n\n# ╔═╡ 7f8b5d7b-25cf-4464-b01a-e9649001b1a1\nmd\"\"\"\np = $(@bind p₁ PlutoUI.Slider(0.0:0.01:1.0, show_value=true, default=0.7))\n\"\"\"\n\n# ╔═╡ 3d1e1190-2ba6-42ad-9c5b-3c3316fd75a0\ncountmap( [bernoulli(p₁) for _ in 1:1000] ) # 10000 iterations, count how many true and false given the value of p\n\n# ╔═╡ bda26511-d961-413a-8389-ad5be48f79fe\nmd\" **Note**: the output for this function is `true` or `false` instead of `heads` or `tails` in the weighted coin example. \"\n\n# ╔═╡ 4c6dd3ba-268e-4fad-b8d1-4bc78f24a46f\nmd\" A Bernoulli random variable model for a weighted coin, for example, will take value $1$ with probability $p$ and $0$ with probability $(1- p)$. Our Bernoulli function that we wrote provides `true` and `false` values. Let us sample some Bernoulli random variates. \"\n\n# ╔═╡ c817e5e6-4cb4-4392-8f7e-e1a4bb009537\nflips = [Int(bernoulli(p₁)) for _ in 1:100];\n\n# ╔═╡ 46bb14fb-62b4-402b-8a0b-8096bd2a6289\nmean(flips) \n\n# ╔═╡ b9cdd1c8-2f8f-48c5-846d-e40cedc949b7\nmd\" The calculation for the mean is just the proportion of `true` values, which should be roughly equal to our probability parameter. Accuracy increases with the number of flips. How would you increase the number of flips in the code above? Play around with the code to see if you can do it. \"\n\n# ╔═╡ 370a4ccb-fdb6-4e3f-8004-d6f88f025945\nmd\" # Probability distributions and types \"\n\n# ╔═╡ c6d85f60-c820-4269-a6b4-57483de13bd8\nmd\"\"\"\nIn this section I will provide some basic properties of common probability distributions that are often used in Bayesian econometrics. We will brielfy introduce three distributions in this section, and then as we progress we will introduce more. We will also discuss the type system in Julia, which is a key feature of the language. To keep the code clear in the following lectures we won't always use best coding practice, but every now and then we will discuss some core principles. \n\"\"\"\n\n# ╔═╡ 601f3dfa-4ea5-4418-aeba-5ab1203f8753\nmd\" ## Bernoulli \"\n\n# ╔═╡ ce3b13a8-38e8-449a-8b11-7a61b8632fc9\nmd\" As we have stated, the Bernoulli distribution describes a binary event of a successful experiment. We usually represent $0$ as failure and $1$ as success, so the result of a Bernoulli distribution is a binary variable. The Bernoulli distribution is widely used to model discrete binary outcomes in which there are only two possible results. The value of $p$ represents the probability of success. \"\n\n# ╔═╡ c61504df-808a-46f0-b8cc-dcc7197ffb3e\nmd\"\"\"\np = $(@bind p₂ PlutoUI.Slider(0.0:0.01:1.0, show_value=true, default=0.7))\n\"\"\"\n\n# ╔═╡ ed8b654f-f964-4d8f-a998-1032c197f014\nbegin\n\tPlots.plot(Distributions.Bernoulli(p₂),\n\t markershape=:circle,\n\t alpha=0.7,\n\t xlabel=L\"\\theta\",\n\t ylabel=\"Mass\",\n\t ylim=(0, 1), \n\t\t\tlw = 2,\n\t\tlegend = false\n\t )\nend\n\n# ╔═╡ c361ae07-61af-44bb-a5ee-be991390fa88\nmd\" We might want to know what the mean (or expected value) of the process is. We can do this easily by constructing a Bernoulli `type` with certain properties. If you are new to programming, the idea of types will be strange. However, try and follow along with the example to see what the benefit is in creating types. \"\n\n# ╔═╡ 0a98082a-94c3-41d8-a129-4f42e217bcd1\nmd\" ### Make Bernoulli a type \"\n\n# ╔═╡ 5b38607d-6cfc-4fa0-b19f-5bea8ad38b39\nmd\"\nCurrently we need one function for sampling from a Bernoulli random variable, a different function to calculate the mean and a different function for the standard deviation. So many different functions! \n\nIn mathematical terms we have this Bernoulli random variable and we are calculating properties of the particular concept. We can do the same thing computationally by creating a new object that represents the Bernoulli random variable. \"\n\n# ╔═╡ 5aed1914-6960-41c8-91d4-09614766583d\nstruct Bernoulli_New\n\tp::Float64\nend\n\n# ╔═╡ 5a358aa5-bb4b-4b48-9d46-8628a9722023\nmd\" We want to be able to sample from this using the `rand()` function and also take its mean. In order to do this we will extend the rand function from the `Base` library of Julia and the `mean` function from the `Statistics.jl` library. \n\nNote that we are adding [methods](https://docs.julialang.org/en/v1/manual/methods/) to these particular functions. \"\n\n# ╔═╡ 2afe4168-640f-4b7e-ab28-7ae22fba16c9\nBase.rand(X::Bernoulli_New) = Int( rand() < X.p ) # Add method to the rand function\n\n# ╔═╡ cc4578f7-358c-4635-9a16-816e0b0f9d4e\nmd\" Adding a method to a function in Julia means that depending on the `type` of the input received, the function will output something different. This is the idea behind multiple dispatch in Julia. You can read more about multiple dispatch [here](https://opensourc.es/blog/basics-multiple-dispatch/).\"\n\n# ╔═╡ 198663dd-941a-4258-800f-80ad0638f884\nB = Bernoulli_New(0.25)\n\n# ╔═╡ 8893ec3a-7b9b-4887-9776-0c9c4f07cf14\nmd\" The object `B` represents a Bernoulli random variable with probability of success $p$. One should note that this type already exists in a package like `Distributions.jl`, so you should be careful about naming conventions. \"\n\n# ╔═╡ b186f0b5-721e-4757-9a4d-a839162b22f2\nrand(B)\n\n# ╔═╡ ad2cadea-d982-4b4c-939d-7c8c4b587539\nmd\" Next we can extend the `mean` function to accept our Bernoulli `type`. This means that whenever we input a variable of the `Bernoulli_New` type the mean will be calculated in the way specified. If we were for example to calculate the mean of a sum of floating point values, Julia would recognise that we are inputting a different type and therefore look for the associated method. \"\n\n# ╔═╡ 827e960e-057e-40ae-beeb-f3c013d9f883\nStatistics.mean(X::Bernoulli_New) = X.p\n\n# ╔═╡ 96787e59-a958-404b-b610-42a28bd0353b\nmean(B)\n\n# ╔═╡ 797f952a-abac-4dde-9834-0e46a06bfa96\nsum_of = 2.0 + 3 + 4 + 5 # If we have one floating point value then the sum gets `promoted` to a floating point value, even if the other values are integers. \n\n# ╔═╡ 16db4c10-cac0-4cc4-a473-9c5ccf488e92\nmean(sum_of)\n\n# ╔═╡ 8aa2ed56-95e4-48ee-8f7e-3da02e7c51c6\ntypeof(sum_of) # In this case the type relates to the sum that we have taken\n\n# ╔═╡ 55bb47ce-558c-451d-a752-aa56b8640832\ntypeof(B) # You can see that this is an instance of our created type!\n\n# ╔═╡ 28578d77-1439-49cf-a9f6-120557bce924\nmd\" ## Binomial \"\n\n# ╔═╡ b6fc9ad1-5f44-4697-be2e-407e2b9308c0\nmd\" The binomial distribution describes an event of the number of successes in a sequence of $n$ independent experiment(s), each asking a yes-no question with a probability of success $p$. Note that the Bernoulli distribution is a special case of the binomial distribution where the number of experiments is $1$. \"\n\n# ╔═╡ 71f12fb3-901d-4feb-9fbc-a5fc6e0f4750\nmd\" The binomial distribution has two parameters and its notation is $\\text{Bin}(n, p)$. An example would be the number of heads in $5$ coin flips (as illustrated below for different values of $p$). We will deal with the coin flip problem in more detail in the next lecture. \"\n\n# ╔═╡ b061d6f2-bcd1-410e-a005-d2e993616b3a\nmd\"\"\"\np = $(@bind p₃ PlutoUI.Slider(0.0:0.01:1.0, show_value=true, default=0.7))\n\"\"\"\n\n# ╔═╡ 1c20116c-339c-453c-b6d1-4ed1477fcf12\nbegin\n\tPlots.plot(Binomial(5, p₃),\n\t markershape=:circle,\n\t alpha=0.7,\n\t xlabel=L\"\\theta\",\n\t ylabel=\"Mass\", \n\t\t\tlw = 2, \n\t\t\tlegend = false\n\t )\nend\n\n# ╔═╡ 0a5ed3ea-12d9-46f9-aab8-472eae8a971d\nmd\" We can make the binomial random variable a type. We only require information on $n$ and $p$, so the `struct` is: \"\n\n# ╔═╡ 1056e659-b358-451f-85b3-a7ec9a6dac92\nstruct Binomial_New\n\tn::Int64\n\tp::Float64\nend\n\n# ╔═╡ 86d8016f-9179-4bb2-be71-3708896ba216\nmd\" Note that this does not require methods at first. We can add the methods later, and other people can add methods too if they are able to load the package. \"\n\n# ╔═╡ 3a9c6bbe-5078-4f99-9418-dc22f73706cb\nBase.rand(X::Binomial_New) = sum(rand(Bernoulli_New(X.p)) for _ in 1:X.n)\n\n# ╔═╡ 310e07b1-ef44-4588-9fc2-7f70b84e527d\nmd\" We will discuss how to code up the Binomial random variable in the next lecture. For now one can simply take this code as given. If you understand what is written there that is great, but it is not the focus of this section. \"\n\n# ╔═╡ e41adcb9-3c78-404b-a501-b359511b9a39\nrand(Binomial_New(10, 0.25))\n\n# ╔═╡ d34b5710-2f37-4bb1-9e02-6e95996f7242\nmd\"\"\"\nn = $(@bind binomial_n PlutoUI.Slider(1:100, show_value=true, default=1)); \np = $(@bind binomial_p PlutoUI.Slider(0.0:0.01:1, show_value=true, default=0.5))\n\n\"\"\"\n\n# ╔═╡ 31675329-f1bd-4752-8da1-af82475fe900\nbegin\n\tbinomial_data = [rand(Binomial_New(binomial_n, binomial_p)) for _ in 1:10000]\n\t\n\tbar(countmap(binomial_data), alpha=0.5, size=(500, 300), leg=false, bin_width=0.5)\nend\n\n# ╔═╡ 71128267-d23a-4162-b9b3-52b86ec5f9de\nmd\" We will encounter a similar graph in the next lecture. We will go through the code more methodically there. \"\n\n# ╔═╡ 7d74a6be-4aac-4f12-9391-528f9cbf37ba\nmd\" ## Gaussian \"\n\n# ╔═╡ 37cbf7a2-6679-40a4-8085-21a4e900c59d\nmd\" While this section is going to be about the Gaussian distribution, we are also going to use it as a platform to discuss software engineering principles. If you don't care much for the programming side of things then you can still learn some things about the Gaussian distribution. In our third lecture we will delve into some further theorethical properties of the Gaussian distribution, so this will definitely not be the last time you encounter it. In fact, this distribution will feature in almost all our lectures so it is a good idea to introduce the concepts early and then reiterate as we move on to other topics. \"\n\n# ╔═╡ f99c393f-308f-4821-8f5a-ee8ebcf5b77b\nmd\"\"\"\nThe two important parameters for the Gaussian distribution are the mean $\\mu$ and standard deviation $\\sigma$. We can sample from the Gaussian distribution with mean $0$ and variance $1$ with the `randn()` function. \n\"\"\"\n\n# ╔═╡ 06f497e4-d1a3-4e99-86f4-f63f69920f53\ngauss = randn(10^5)\n\n# ╔═╡ 6747980b-7072-4267-84c5-a352abf4ec25\nmd\"\"\"\nA Gaussian random variable is a **continuous** random variable, i.e. it has a continuous range of possible outcomes. The possible range of outcomes is called the **support** of the distribution. For a Gaussian it is the whole real line, $(-\\infty, \\infty)$.\n\"\"\"\n\n# ╔═╡ fe0ee6b7-9c42-41b8-929c-2dd7101490a3\nmd\"\"\"\nOne way to specify a continous random variable $X$ is via its **probability density function**, or **PDF**, $f_X$. The probability that $X$ lies in the interval $[a, b]$ is given by an area under the curve $f_X(x)$ from $a$ to $b$:\n\n$$\\mathbb{P}(X \\in [a, b]) = \\int_{a}^b f_X(y) \\, dx.$$\n\n**Notation remark**: The tradition in statistics is to use capital letters for random variables and then lowe case letters for realisation of that random variable. Our notation will change from the second lecture onward. Please make a note of this so that you do not get confused by notation. I will mention this again in another lecture. \n\n\"\"\"\n\n# ╔═╡ 7550ccac-ca63-4f96-b576-595888071c34\nmd\"\"\"\nFor a Gaussian distribution with mean $\\mu$ and variance $\\sigma^2$, the PDF is given by\n\n$$f_X(X) = \\frac{1}{\\sqrt{2\\pi \\sigma^2}} \\exp \\left[ -\\frac{1}{2} \\left( \\frac{x - \\mu}{\\sigma} \\right)^2 \\right]$$\n\"\"\"\n\n# ╔═╡ abe288f3-9a80-4c29-a918-73c57ab16dc2\nmd\" This PDF of the Gaussian is captured in the functions below. It is important to remember the equation for the PDF of the Gaussian since we will need to work with and manipulate it a lot in this course. \" \n\n# ╔═╡ c23627d6-91a2-4b69-9e35-71b8a9578dd6\nbell_curve(x) = exp(-x^2 / 2) / √(2π)\n\n# ╔═╡ 24f945be-f3d5-48bd-80e1-12a7cc92d976\nbell_curve(x, μ, σ) = bell_curve( (x - μ) / σ ) / σ\n\n# ╔═╡ 9c93fdce-c678-4c53-986d-e870c53a50e4\nmethods(bell_curve);\n\n# ╔═╡ 62c3c7f1-2839-4c7e-bba7-1741649b3620\nmd\"\"\"\nWe can shift and scale the Gaussian distribution in the following manner. \n\"\"\"\n\n# ╔═╡ b153e5e7-95ba-4425-91aa-ce9986a64392\nmd\"\"\"\nμ = $(@bind μ PlutoUI.Slider(-3:0.01:3, show_value=true, default=0.0))\nσ = $(@bind σ PlutoUI.Slider(0.01:0.01:3, show_value=true, default=1))\n\"\"\"\n\n# ╔═╡ 0f7184f5-a03f-482e-8339-fd12c7391e01\ndata = μ .+ σ .* randn(10^5) # Take note of the broadcasting performed by the dot operator\n\n# ╔═╡ ff9355dc-3e5f-4558-9027-668bd17a7a30\nbegin\n\thistogram(data, alpha=0.5, norm=true, bins=100, leg=false, title=\"μ=$(μ), σ=$(σ)\", size=(600, 400))\n\t\n\txlims!(-6, 6)\n\tylims!(0, 0.6)\n\t\n\txs = [μ - σ, μ, μ + σ]\n\t\n\tplot!(-6:0.01:6, x -> bell_curve(x, μ, σ), lw=2, color = :black)\n\t\n\tplot!((μ - σ):0.01:(μ + σ), x -> bell_curve(x, μ, σ), fill=true, alpha=0.6, c=:black)\n\t\n\tplot!([μ, μ], [0.05, bell_curve(μ, μ, σ)], ls=:dash, lw=2, c=:white)\n\tannotate!(μ, 0.03, text(\"μ\", :white))\n#\tannotate!(μ + σ, 0.03, text(\"μ+σ\", :yellow))\n#\tannotate!(μ, 0.03, text(\"μ\", :white))\n\n\t\nend\n\n# ╔═╡ a825e358-1fdc-42cb-87cf-ab0dbd092cb0\nmd\" One fo the nice things about Gaussians is that the sum of two Gaussians is also Gaussian. We will make use of this property of the Gaussian in future, so take note. In order to show this, let us sample from two Gaussian random variables and add the resulting random variable. \"\n\n# ╔═╡ 2279f195-a9fa-46ee-925b-f54222d61d9a\nbegin\n\tdata1 = 4 .+ sqrt(0.3) .* randn(10^5)\n\tdata2 = 6 .+ sqrt(0.7) .* randn(10^5)\n\t\n\ttotal = data1 + data2\nend\n\n# ╔═╡ 677da773-6130-41b2-8188-209a8d751f99\nbegin\n\t\n\thistogram(data1, alpha=0.4, norm=true, size=(600, 400), label = \"data1\", title=\"Sum of Gaussians\")\n\thistogram!(data2, alpha=0.4, norm=true, size=(600, 400), label = \"data2\", color = :black)\n\thistogram!(total, alpha=0.8, norm=true, size=(600, 400), label = \"total\")\n\tplot!(2:0.01:14, x -> bell_curve(x, 10, 1), lw=2, color = :black, legend = false)\nend\n\n# ╔═╡ c55f846d-d578-4c81-bdc4-ce5d03c62dba\nmd\" Quite interesting, we get a Gaussian again -- the green one at the end is the sum. Gaussians form part of a larger group of distributions called [stable distributions](https://en.wikipedia.org/wiki/Stable_distribution) that share this property. \n\nImportantly, the sum of two Gaussians with means $\\mu_1$ and $\\mu_2$ and variances $\\sigma^{2}_{1}$ and $\\sigma^{2}_{2}$ is Gaussian with mean $\\mu_1 + \\mu_2$ and variance $\\sigma_1^2 + \\sigma_2^2$. \"\n\n# ╔═╡ 071d902e-a952-480e-9c21-5a3315162a6a\nmd\" ### Let's talk about types \"\n\n# ╔═╡ 54bf4640-fa81-4ef4-978a-a87682dd3401\nmd\"\"\"\nWe have shown how we can represent a random variable in software with Bernoulli and Binomial types that we have defined before. In some other programming languages there are different names for the functions associated to certain random variables, but no specific name for the random variable itself. \n\nLet us take a look at R as an example. Most of you are comfortable with R, so this should pehaps be more familiar. In R there is a standard naming convention with respect to sampling from random variables, which is best explained by an example. Consider the `norm` function, which allows us to sample from the Normal distribution. There are four functions that we can attach as prefix to `norm`. These indicators are `d` for the density, `p` for the distribution function , `q` for the quantile function and `r` for generating random variates. \n\nIn other words, if you want to generate a random draw from the Normal distribution you should use the `rnorm` function. This seems quite intuitive. However, what is wrong with this? \n\nAll these functions are referring to an underlying random variable (or probability distribution), which you will find in any course on probability. However, there is no way for us to refer to the underlying mathematical object. Think on this point for a second. \n\nHow do we rectify this? We would like to be able to refer to the random variable (or probability distribution) itself. We should be able to provide a type with the name and parameters of a random variable, but not yet specify how to generate random instances. This is an example of thinking ahead by providing **abstraction**.\n\nOnce we have established the random variable with our type system we can always provide means for random sampling (and more).\n\n\"\"\"\n\n# ╔═╡ 8a01d833-3220-4144-8c2a-dde4c1399795\nmd\" ### Defining abstract types \"\n\n# ╔═╡ 760eaee1-0af1-41c1-b38a-c0041559c0ed\nmd\"\"\"\nThus far we have only defined **concrete types**. Think about concrete types as the types with specific data attached. Now we will define an **abstract type** using `abstract type end`, where `` is replaced with name of the type.\n\nWe can think of an abstract type as being a collection of types that share a particular property. In our case, we want to create a type to represent \"any random variable\", and also the sub-types \"any continuous(-valued) random variable\" and \"any discrete(-valued) random variable\".\n\nThis will allow us to specify later on whether a given concrete (i.e. particular) random variable is discrete or continuous.\n\nWe use `<:` to denote **sub-type**:\n\"\"\"\n\n# ╔═╡ bf4df54b-6631-4b59-bf6a-26caea5ab7df\nbegin\n\tabstract type RandomVariable end\n\t\n\tabstract type DiscreteRandomVariable <: RandomVariable end # Subtype of RandomVariable\n\tabstract type ContinuousRandomVariable <: RandomVariable end\nend\n\n# ╔═╡ 18fbb98d-87a2-4f29-b6f0-3e19ad843b00\nmd\"\"\"\nLet's start off by looking at **Gaussian** random variables.\n\"\"\"\n\n# ╔═╡ fc5709fc-337d-4d42-b023-373089de2c8d\nbegin\n\tstruct Gaussian <: ContinuousRandomVariable # Subtype of ContinuousRandomVariable\n\t\tμ # mean\n\t\tσ² # variance\n\tend\n\t\n\tGaussian() = Gaussian(0.0, 1.0) # normalised Gaussian with mean 0 and variance 1\nend\n\n# ╔═╡ e91fe8c0-d13e-401f-b3f1-77e04fe4df34\nG = Gaussian(1, 2)\n\n# ╔═╡ ada8809b-8f3a-4298-94d9-e8225df4087d\nmd\" We have now created a Gaussian random variable with given parameter value, without sampling from it. We have not even defined the notion of sampling. However, we will easily be able to apply it to our Gaussian type. More importantly, we will be able to apply it to any random variable that falls under the RandomVariable type that we have defined. \n\nImportant to note that the `Gaussian` type that we have created here is a **concrete type**.\n\nWe now extend the `mean`, `var` and `std` function from the Statistics library to act on our newly created object. \"\n\n# ╔═╡ 7580a872-47b1-4efc-9c51-9591d3552c5b\nbegin\n\tStatistics.mean(X::Gaussian) = X.μ\n\tStatistics.var(X::Gaussian) = X.σ²\nend\n\n# ╔═╡ a6945e5b-0516-49d1-a978-e4af5090aca3\nmean(G)\n\n# ╔═╡ 30b5ae33-c009-4ad5-8950-c75a614acde3\nvar(G)\n\n# ╔═╡ 265d6bdf-2381-471a-a99a-3d163b96e620\nmd\" Now let us show that we can calculate the standard deviation for any random variable, not just the Gaussian. Calculating the standard deviation is simply going to be the square root of the variance for **any** random variable. \n\nWe can define this to act on any random variable, even ones that we have not created yet!\"\n\n# ╔═╡ ec39a8d0-be30-4c7c-9727-f7cffdd117a9\nStatistics.std(X::RandomVariable) = sqrt(var(X))\n\n# ╔═╡ d3387ea9-032f-4b62-96fe-3965ad187672\nstd(G)\n\n# ╔═╡ 9aef8d51-eb5b-4342-8ad5-02e6187b2953\nmd\" #### Sum of two Gaussians (redux) \"\n\n# ╔═╡ 9260827c-3262-4870-9e5a-ac49bfa1dbae\nmd\" Gaussians have the special property that we mentioned before that the sum of two Gaussians is always a Gaussian. We can code this property up with our type specification as follows. \" \n\n# ╔═╡ fbe80edb-7964-4103-bffa-c01a89904bd1\nBase.:+(X::Gaussian, Y::Gaussian) = Gaussian(X.μ + Y.μ, X.σ² + Y.σ²)\n\n# ╔═╡ 2c91f496-3780-4257-8da1-8fbf8eeca908\nmd\" We are essentially saying that we can extend the $+$ operator from the `Base` Julia package to include a summation over two Gaussian distributions. \" \n\n# ╔═╡ 215e2f59-0541-46d5-8d48-fa381139fd54\nbegin\n\tG1 = Gaussian(0, 1)\n\tG2 = Gaussian(5, 6)\nend\n\n# ╔═╡ 5f537343-2d7d-433f-a3aa-b075425fc9e2\nG1 + G2\n\n# ╔═╡ c28e6273-bad5-4688-af21-484c5de2bdf0\nmean(G1 + G2) == mean(G1) + mean(G2)\n\n# ╔═╡ df7f90b7-c989-4856-9adf-41be3f4e6444\nmd\" #### Probability distribution of Gaussian \"\n\n# ╔═╡ de83e0a2-6655-469e-8ab9-6e00b60e245c\nmd\" We have already provided a mathematical description of the PDF of the Gaussian, which is provided again below as a reminder. \n\nFor a Gaussian distribution with mean $\\mu$ and variance $\\sigma^2$, the PDF is given by\n\n$$f_X(X) = \\frac{1}{\\sqrt{2\\pi \\sigma^2}} \\exp \\left[ -\\frac{1}{2} \\left( \\frac{x - \\mu}{\\sigma} \\right)^2 \\right]$$\n\nNow let us define the pdf function with our Gaussian type. \n\"\n\n# ╔═╡ 7d92b70f-fc40-47e4-97c4-0703181e2322\npdf(X::Gaussian) = x -> exp(-0.5 * ( (x - X.μ)^2 / X.σ²) ) / √(2π * X.σ²)\n\n# ╔═╡ f4f723ea-3574-419a-84a4-655d09375c3a\npdf(G)\n\n# ╔═╡ 544822a0-329e-48f7-9a16-1e18053ea9f0\npdf(Gaussian())(0.0)\n\n# ╔═╡ 321b215c-ca89-4fe5-8f15-9bf37fe10064\nmd\"\"\"\nμ = $(@bind μμ Slider(-3:0.01:3, show_value=true, default=0.0))\nσ = $(@bind σσ Slider(0.01:0.01:3, show_value=true, default=1.0))\n\"\"\"\n\n# ╔═╡ 118957fc-e85a-4829-b3ae-9aa8fccc0a33\nbegin\n\tplot(pdf(Gaussian(μμ, σσ)), leg=false, lw = 2)\n\txlims!(-6, 6)\n\tylims!(0, 0.5)\nend\n\n# ╔═╡ bf84e5cc-8617-4a29-b5c9-ff7de784e29b\nmd\"\"\"\n#### Sampling from a Gaussian distribution\n\"\"\"\n\n# ╔═╡ 7255af4d-611d-489d-b607-70eefb858170\nmd\"\"\"\nWe can also specify how to sample from a Gaussian distribution. We can re-purpose `rand` for this!\n\"\"\"\n\n# ╔═╡ 0fcbe952-87af-4c56-a6e8-cf80ada41497\nBase.rand(X::Gaussian) = X.μ + √(X.σ²) * randn()\n\n# ╔═╡ 75afbded-6b3b-4a7e-ad53-a5f34808c056\nhistogram!([rand(Gaussian(μμ, σσ)) for i in 1:10^4], alpha=0.5, norm=true)\n\n# ╔═╡ 248e90a9-6c28-4ef2-bd51-112077f93f9c\nmd\" #### General application \"\n\n# ╔═╡ aba1a15f-15a8-495a-a585-77fc18ccb7dd\nmd\"\"\"\nLet's recall the Bernoulli distribution. This represents a weighted coin with probability $p$ to come up \"heads\" (1), and probability $1-p$ to come up \"tails\" (0).\n\nNote that this is a **discrete** random variable: the possible outcomes are the discrete values $0$ and $1$.\n\"\"\"\n\n# ╔═╡ efb934f0-2b02-42c6-9d5d-b0243bf889bd\nstruct Bernoulli <: DiscreteRandomVariable\n\tp::Float64\nend\n\n# ╔═╡ 24a2dc89-51db-40d2-8990-832ac2c65fe2\nB1 = Bernoulli(0.25)\n\n# ╔═╡ 29d1ca09-60f4-4786-9623-3e09584aeece\nbegin\n\tStatistics.mean(X::Bernoulli) = X.p\n\tStatistics.var(X::Bernoulli) = X.p * (1 - X.p)\nend\n\n# ╔═╡ 46e74b96-7f94-408c-a63d-d898e538bd59\nmd\" Now for the amazing part... The `std` function can be called, even though we did not write it directly for the Bernoulli random variable. \"\n\n# ╔═╡ 6dd8ebb3-a23f-4071-becd-94a8de5fd4f7\nmean(B1), var(B1), std(B1)\n\n# ╔═╡ 686e2146-46ae-4799-bab7-51b42a3074eb\nmd\"\"\"\nFinally we specify how to sample:\n\"\"\"\n\n# ╔═╡ 5415b2b7-9c7c-4420-a664-a96e4bd23199\nBase.rand(X::Bernoulli) = Int(rand() < X.p)\n\n# ╔═╡ ea8e9149-7c8f-492d-9577-19284fe50238\nmd\"\"\"\n#### Adding two random variables\n\"\"\"\n\n# ╔═╡ 8d22a8ff-3bf5-4226-b605-1a496a03d667\nmd\"\"\"\nWhat happens if we add two Bernoulli random variables? There are two routes we could go: We could use the known theoretical sum, or we could write a general-purpose tool. Let's do the latter.\n\"\"\"\n\n# ╔═╡ 3cbe3970-098e-4476-9062-87ce8dbf747c\nmd\"\"\"\nWhen we add two Bernoulli random variables we do *not* get a Bernoulli back. To see this it's enough to observe that the sum can have the outcome 2, which is impossible for a Bernoulli. \n\t\t\nSo the result is just the random variable \"the sum of these two given random variables\". In general it won't even have a common name. \n\t\t\nSo we actually need to *define a new type* to represent the \"sum of two given random variables\", which itself will be a random variable!:\n\t\t\n\t\t\n\"\"\"\n\n# ╔═╡ f51e0a4a-3d2c-47ee-8eee-dfc6e5c522ac\nstruct SumOfTwoRandomVariables <: RandomVariable\n\tX1::RandomVariable\n\tX2::RandomVariable\nend\n\n# ╔═╡ 70b112cc-3b6e-4c9e-a2fb-5282f2cc5605\nbegin\n\tB2 = Bernoulli(0.25)\n\tB3 = Bernoulli(0.6)\nend\n\n# ╔═╡ 5acc26ff-fe68-4b6e-a67c-fd753efc949b\nmd\"\"\"\nNow we can define the sum of two random variables of *any* type:\n\"\"\"\n\n# ╔═╡ b4c5f5e3-4975-4fa6-91ea-c4d634825c0e\nBase.:+(X1::RandomVariable, X2::RandomVariable) = SumOfTwoRandomVariables(X1, X2)\n\n# ╔═╡ 6031286a-85c9-4770-b03e-3bf6ddd12451\nmd\"\"\"\nFor example, let's sum two Bernoullis:\n\"\"\"\n\n# ╔═╡ 34908b18-2277-4d80-b615-2ddaf7d12d85\nB2 + B3\n\n# ╔═╡ 9ec9be96-c127-4124-ae7a-3eaddf21dd49\nmd\"\"\"\nFor the special case of Gaussians we still get the correct result (we have *not* overwritten the previous definition):\n\"\"\"\n\n# ╔═╡ dc66f1b5-f04a-4c2b-8ed2-295394c10a79\nG1 + G2\n\n# ╔═╡ 4e86f431-8737-4055-be4d-51d8fb1250aa\nmd\"\"\"\nNow we need to define the various functions on this type representing a sum\n\"\"\"\n\n# ╔═╡ 7469e43a-f963-4228-bbe3-4cffd113cb2b\nStatistics.mean(S::SumOfTwoRandomVariables) = mean(S.X1) + mean(S.X2)\n\n# ╔═╡ a2228c42-03d6-45e0-b3b1-18db8737e848\nmean(B2 + B3)\n\n# ╔═╡ d9eafc22-71c3-48e8-88ec-c332148ea98d\nmd\"\"\"\nTo have a simple equation for the variance, we need to assume that the two random variables are **independent**. Perhaps the name should have been `SumOfTwoIndependentRandomVariables`, but it seems too long.\n\"\"\"\n\n# ╔═╡ 43e5b217-965a-4312-bd1b-ffda74253653\nStatistics.var(S::SumOfTwoRandomVariables) = var(S.X1) + var(S.X2)\n\n# ╔═╡ b76070e9-ef7a-4cb5-ade7-625073173c5c\nmd\"\"\"\nHow can we sample from the sum? It's actually easy!\n\"\"\"\n\n# ╔═╡ 3d11987d-5afb-4bc6-b0be-a355d804b6c6\nBase.rand(S::SumOfTwoRandomVariables) = rand(S.X1) + rand(S.X2)\n\n# ╔═╡ f180e914-af0c-4d8a-afe4-bdc54ee988f6\nmd\"\"\"\nNow it's easy to look at the sum of a Bernoulli and a Gaussian. This is an example of a [**mixture distribution**](https://en.wikipedia.org/wiki/Mixture_distribution).\n\"\"\"\n\n# ╔═╡ bf20d3e0-64b5-49d4-aabc-059aa6a390ad\nmd\"\"\"\nLet's extend the `histogram` function to easily draw the histogram of a random variable:\n\"\"\"\n\n# ╔═╡ d93dfb88-0602-4913-a59e-587803a9b5a3\nPlots.histogram(X::RandomVariable; kw...) = histogram([rand(X) for i in 1:10^6], norm=true, leg=false, alpha=0.5, size=(500, 300), kw...)\n\n# ╔═╡ b2265d0c-9f85-4eff-8872-2fa968474e3f\nhistogram(Bernoulli(0.25) + Bernoulli(0.75))\n\n# ╔═╡ 485c79a6-2c47-4320-81c8-2d2ac2b5d5a2\nhistogram(Bernoulli(0.25) + Gaussian(0, 0.1))\n\n# ╔═╡ 0244cc32-6371-42c0-8564-570d3424460d\nmixture = Bernoulli(0.25) + Bernoulli(0.75) + Gaussian(0, 0.1)\n\n# ╔═╡ 913c8389-3501-4a0c-abe3-4faa42ef9a04\nrand( mixture )\n\n# ╔═╡ 8d29975c-5adc-458b-95b0-f4369c5c2f3a\nhistogram( mixture )\n\n# ╔═╡ b0ccc2ee-0355-4591-b243-5f56715a01b8\nmd\" #### Generic programming \"\n\n# ╔═╡ c9cd7943-7b2a-4387-a4fb-766d9ee00594\nmd\"\"\"\nNow we have defined `+`, Julia's generic definition of `sum` can kick in to define the sum of many random variables!\n\"\"\"\n\n# ╔═╡ d2a12c25-4277-4f19-9811-9d371d91022c\nS = sum(Bernoulli(0.25) for i in 1:30)\n\n# ╔═╡ 3f3b7906-7bd0-4a9f-8a49-14b8a8924218\nmd\"\"\"\nNote that we do not need the `[...]` in the following expression. There is no need to actually create an array of random variables; instead we are using an **iterator** or **generator expression**:\n\"\"\"\n\n# ╔═╡ 25e39a6b-5d8e-419f-9a44-8d72a8fde502\nhistogram(S)\n\n# ╔═╡ 6560fe42-daa9-47ce-8a88-dbddcc2d3a1c\nmean(S)\n\n# ╔═╡ ea7b83b9-2e95-43da-b089-cdf4d6d5247d\nvar(S)\n\n# ╔═╡ 3245d573-ffe6-44b2-9734-753a011ab10c\nrand(S)\n\n# ╔═╡ 5c294ee4-1d99-4d7d-a94d-afc3a643614e\nmd\"\"\"\nThis is a big deal! Everything just works. That is it for today, next time we will move on to Bayesian statistics.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─09a9d9f9-fa1a-4192-95cc-81314582488b\n# ╟─41eb90d1-9262-42b1-9eb2-d7aa6583da17\n# ╟─f4a548e6-8949-4528-8b26-d30275b9e2c8\n# ╟─c65ae735-b404-4798-97f2-29083e7ae44c\n# ╟─000021af-87ce-4d6d-a315-153cecce5091\n# ╟─49033e09-fd64-4707-916c-9435d3f0a9d2\n# ╠═c4cccb7a-7d16-4dca-95d9-45c4115cfbf0\n# ╠═2eb626bc-43c5-4d73-bd71-0de45f9a3ca1\n# ╟─d65de56f-a210-4428-9fac-20a7888d3627\n# ╟─da871a80-a6d8-4be2-92bb-c3f10e51efe3\n# ╟─98a8dd21-8dc4-4880-8975-265249f816ce\n# ╟─15dcbe6b-b51e-4472-a8e0-08cbd49d1e8c\n# ╟─be11b67f-d04d-46b1-a935-eedd7e59ede3\n# ╟─040c011f-1653-446d-8641-824dc82162eb\n# ╟─0d0f08f3-48e2-402c-bbb5-33bd3d09ab06\n# ╠═b78745cc-84ef-4bbe-a916-9c87cde47145\n# ╠═08fc15b7-2cc6-4a21-82a6-521f6294ee79\n# ╠═4c48df5c-33c6-4d26-b6e4-80e3c883d389\n# ╠═350bb07e-6e88-49fc-ae69-c24b1549650d\n# ╠═07b17b42-e968-4a7a-bf56-da1a3a1bef52\n# ╟─dc306e4a-7841-4c36-8c5b-d96acc7714de\n# ╠═71482500-7ca7-4a4e-8635-f29ee6f11ced\n# ╟─b028662e-a8ac-45c4-86aa-d684bbb864c8\n# ╠═f882026e-3393-46a7-b284-f0313386f214\n# ╟─a69254ad-d7e2-4ddd-9a8f-58eaa9a45ce8\n# ╠═94a2862e-1f6b-4c4e-ad32-4b6c49924454\n# ╠═fa929cc1-ce08-4c9a-922b-cdf611fa3e2a\n# ╟─909ea3be-9b65-465a-ab31-0d3d525c021f\n# ╟─b1d3017e-8caf-462f-bb0b-8154202f21e6\n# ╠═9492ddc5-301d-46d2-bf34-5396563f5d5b\n# ╠═4f5e9c1f-d510-4897-9176-218a1a2f4057\n# ╟─7254eb45-8170-40f2-afd3-e30ec5c26781\n# ╠═caeee82e-b854-4b34-b34f-5899e5a9b952\n# ╟─cdad68ca-dac9-49ad-8149-939d18f00778\n# ╟─ea5a71b7-845b-4310-b1fb-f69ee71ac3fb\n# ╟─d6aa79f3-45c8-4ff5-84d6-1cd79b845b2f\n# ╠═0d46dd99-c614-40a6-9cd0-69b453ec782f\n# ╠═da3b79da-3d14-405f-80af-d58d04b4f801\n# ╟─18d07eee-60af-4dad-8f4a-9426f5907ad3\n# ╠═f40f5823-f383-4d6e-a651-91c5a03cbf1e\n# ╠═2970a6d2-599a-44ce-ab09-d52db64c0c64\n# ╟─5b54210f-9a7d-447e-9491-f8fbb0892e7f\n# ╠═e9df057d-3781-4fe1-b0ca-fab08b895ca2\n# ╟─7f8b5d7b-25cf-4464-b01a-e9649001b1a1\n# ╠═3d1e1190-2ba6-42ad-9c5b-3c3316fd75a0\n# ╟─bda26511-d961-413a-8389-ad5be48f79fe\n# ╟─4c6dd3ba-268e-4fad-b8d1-4bc78f24a46f\n# ╠═c817e5e6-4cb4-4392-8f7e-e1a4bb009537\n# ╠═46bb14fb-62b4-402b-8a0b-8096bd2a6289\n# ╟─b9cdd1c8-2f8f-48c5-846d-e40cedc949b7\n# ╟─370a4ccb-fdb6-4e3f-8004-d6f88f025945\n# ╟─c6d85f60-c820-4269-a6b4-57483de13bd8\n# ╟─601f3dfa-4ea5-4418-aeba-5ab1203f8753\n# ╟─ce3b13a8-38e8-449a-8b11-7a61b8632fc9\n# ╟─c61504df-808a-46f0-b8cc-dcc7197ffb3e\n# ╟─ed8b654f-f964-4d8f-a998-1032c197f014\n# ╟─c361ae07-61af-44bb-a5ee-be991390fa88\n# ╟─0a98082a-94c3-41d8-a129-4f42e217bcd1\n# ╟─5b38607d-6cfc-4fa0-b19f-5bea8ad38b39\n# ╠═5aed1914-6960-41c8-91d4-09614766583d\n# ╟─5a358aa5-bb4b-4b48-9d46-8628a9722023\n# ╠═2afe4168-640f-4b7e-ab28-7ae22fba16c9\n# ╟─cc4578f7-358c-4635-9a16-816e0b0f9d4e\n# ╠═198663dd-941a-4258-800f-80ad0638f884\n# ╟─8893ec3a-7b9b-4887-9776-0c9c4f07cf14\n# ╠═b186f0b5-721e-4757-9a4d-a839162b22f2\n# ╟─ad2cadea-d982-4b4c-939d-7c8c4b587539\n# ╠═827e960e-057e-40ae-beeb-f3c013d9f883\n# ╠═96787e59-a958-404b-b610-42a28bd0353b\n# ╠═797f952a-abac-4dde-9834-0e46a06bfa96\n# ╠═16db4c10-cac0-4cc4-a473-9c5ccf488e92\n# ╠═8aa2ed56-95e4-48ee-8f7e-3da02e7c51c6\n# ╠═55bb47ce-558c-451d-a752-aa56b8640832\n# ╟─28578d77-1439-49cf-a9f6-120557bce924\n# ╟─b6fc9ad1-5f44-4697-be2e-407e2b9308c0\n# ╟─71f12fb3-901d-4feb-9fbc-a5fc6e0f4750\n# ╟─b061d6f2-bcd1-410e-a005-d2e993616b3a\n# ╟─1c20116c-339c-453c-b6d1-4ed1477fcf12\n# ╟─0a5ed3ea-12d9-46f9-aab8-472eae8a971d\n# ╠═1056e659-b358-451f-85b3-a7ec9a6dac92\n# ╟─86d8016f-9179-4bb2-be71-3708896ba216\n# ╠═3a9c6bbe-5078-4f99-9418-dc22f73706cb\n# ╟─310e07b1-ef44-4588-9fc2-7f70b84e527d\n# ╠═e41adcb9-3c78-404b-a501-b359511b9a39\n# ╟─d34b5710-2f37-4bb1-9e02-6e95996f7242\n# ╟─31675329-f1bd-4752-8da1-af82475fe900\n# ╟─71128267-d23a-4162-b9b3-52b86ec5f9de\n# ╟─7d74a6be-4aac-4f12-9391-528f9cbf37ba\n# ╟─37cbf7a2-6679-40a4-8085-21a4e900c59d\n# ╟─f99c393f-308f-4821-8f5a-ee8ebcf5b77b\n# ╠═06f497e4-d1a3-4e99-86f4-f63f69920f53\n# ╟─6747980b-7072-4267-84c5-a352abf4ec25\n# ╟─fe0ee6b7-9c42-41b8-929c-2dd7101490a3\n# ╟─7550ccac-ca63-4f96-b576-595888071c34\n# ╟─abe288f3-9a80-4c29-a918-73c57ab16dc2\n# ╠═c23627d6-91a2-4b69-9e35-71b8a9578dd6\n# ╠═24f945be-f3d5-48bd-80e1-12a7cc92d976\n# ╠═9c93fdce-c678-4c53-986d-e870c53a50e4\n# ╟─62c3c7f1-2839-4c7e-bba7-1741649b3620\n# ╟─b153e5e7-95ba-4425-91aa-ce9986a64392\n# ╠═0f7184f5-a03f-482e-8339-fd12c7391e01\n# ╠═ff9355dc-3e5f-4558-9027-668bd17a7a30\n# ╟─a825e358-1fdc-42cb-87cf-ab0dbd092cb0\n# ╠═2279f195-a9fa-46ee-925b-f54222d61d9a\n# ╟─677da773-6130-41b2-8188-209a8d751f99\n# ╟─c55f846d-d578-4c81-bdc4-ce5d03c62dba\n# ╟─071d902e-a952-480e-9c21-5a3315162a6a\n# ╟─54bf4640-fa81-4ef4-978a-a87682dd3401\n# ╟─8a01d833-3220-4144-8c2a-dde4c1399795\n# ╟─760eaee1-0af1-41c1-b38a-c0041559c0ed\n# ╠═bf4df54b-6631-4b59-bf6a-26caea5ab7df\n# ╟─18fbb98d-87a2-4f29-b6f0-3e19ad843b00\n# ╠═fc5709fc-337d-4d42-b023-373089de2c8d\n# ╠═e91fe8c0-d13e-401f-b3f1-77e04fe4df34\n# ╟─ada8809b-8f3a-4298-94d9-e8225df4087d\n# ╠═7580a872-47b1-4efc-9c51-9591d3552c5b\n# ╠═a6945e5b-0516-49d1-a978-e4af5090aca3\n# ╠═30b5ae33-c009-4ad5-8950-c75a614acde3\n# ╟─265d6bdf-2381-471a-a99a-3d163b96e620\n# ╠═ec39a8d0-be30-4c7c-9727-f7cffdd117a9\n# ╠═d3387ea9-032f-4b62-96fe-3965ad187672\n# ╟─9aef8d51-eb5b-4342-8ad5-02e6187b2953\n# ╟─9260827c-3262-4870-9e5a-ac49bfa1dbae\n# ╠═fbe80edb-7964-4103-bffa-c01a89904bd1\n# ╟─2c91f496-3780-4257-8da1-8fbf8eeca908\n# ╠═215e2f59-0541-46d5-8d48-fa381139fd54\n# ╠═5f537343-2d7d-433f-a3aa-b075425fc9e2\n# ╠═c28e6273-bad5-4688-af21-484c5de2bdf0\n# ╟─df7f90b7-c989-4856-9adf-41be3f4e6444\n# ╟─de83e0a2-6655-469e-8ab9-6e00b60e245c\n# ╠═7d92b70f-fc40-47e4-97c4-0703181e2322\n# ╠═f4f723ea-3574-419a-84a4-655d09375c3a\n# ╠═544822a0-329e-48f7-9a16-1e18053ea9f0\n# ╟─321b215c-ca89-4fe5-8f15-9bf37fe10064\n# ╠═118957fc-e85a-4829-b3ae-9aa8fccc0a33\n# ╟─bf84e5cc-8617-4a29-b5c9-ff7de784e29b\n# ╟─7255af4d-611d-489d-b607-70eefb858170\n# ╠═0fcbe952-87af-4c56-a6e8-cf80ada41497\n# ╠═75afbded-6b3b-4a7e-ad53-a5f34808c056\n# ╟─248e90a9-6c28-4ef2-bd51-112077f93f9c\n# ╟─aba1a15f-15a8-495a-a585-77fc18ccb7dd\n# ╠═efb934f0-2b02-42c6-9d5d-b0243bf889bd\n# ╠═24a2dc89-51db-40d2-8990-832ac2c65fe2\n# ╠═29d1ca09-60f4-4786-9623-3e09584aeece\n# ╟─46e74b96-7f94-408c-a63d-d898e538bd59\n# ╠═6dd8ebb3-a23f-4071-becd-94a8de5fd4f7\n# ╟─686e2146-46ae-4799-bab7-51b42a3074eb\n# ╠═5415b2b7-9c7c-4420-a664-a96e4bd23199\n# ╟─ea8e9149-7c8f-492d-9577-19284fe50238\n# ╟─8d22a8ff-3bf5-4226-b605-1a496a03d667\n# ╟─3cbe3970-098e-4476-9062-87ce8dbf747c\n# ╠═f51e0a4a-3d2c-47ee-8eee-dfc6e5c522ac\n# ╠═70b112cc-3b6e-4c9e-a2fb-5282f2cc5605\n# ╟─5acc26ff-fe68-4b6e-a67c-fd753efc949b\n# ╠═b4c5f5e3-4975-4fa6-91ea-c4d634825c0e\n# ╟─6031286a-85c9-4770-b03e-3bf6ddd12451\n# ╠═34908b18-2277-4d80-b615-2ddaf7d12d85\n# ╟─9ec9be96-c127-4124-ae7a-3eaddf21dd49\n# ╠═dc66f1b5-f04a-4c2b-8ed2-295394c10a79\n# ╟─4e86f431-8737-4055-be4d-51d8fb1250aa\n# ╠═7469e43a-f963-4228-bbe3-4cffd113cb2b\n# ╠═a2228c42-03d6-45e0-b3b1-18db8737e848\n# ╟─d9eafc22-71c3-48e8-88ec-c332148ea98d\n# ╠═43e5b217-965a-4312-bd1b-ffda74253653\n# ╟─b76070e9-ef7a-4cb5-ade7-625073173c5c\n# ╠═3d11987d-5afb-4bc6-b0be-a355d804b6c6\n# ╟─f180e914-af0c-4d8a-afe4-bdc54ee988f6\n# ╟─bf20d3e0-64b5-49d4-aabc-059aa6a390ad\n# ╠═d93dfb88-0602-4913-a59e-587803a9b5a3\n# ╠═b2265d0c-9f85-4eff-8872-2fa968474e3f\n# ╠═485c79a6-2c47-4320-81c8-2d2ac2b5d5a2\n# ╠═0244cc32-6371-42c0-8564-570d3424460d\n# ╠═913c8389-3501-4a0c-abe3-4faa42ef9a04\n# ╠═8d29975c-5adc-458b-95b0-f4369c5c2f3a\n# ╟─b0ccc2ee-0355-4591-b243-5f56715a01b8\n# ╟─c9cd7943-7b2a-4387-a4fb-766d9ee00594\n# ╠═d2a12c25-4277-4f19-9811-9d371d91022c\n# ╟─3f3b7906-7bd0-4a9f-8a49-14b8a8924218\n# ╠═25e39a6b-5d8e-419f-9a44-8d72a8fde502\n# ╠═6560fe42-daa9-47ce-8a88-dbddcc2d3a1c\n# ╠═ea7b83b9-2e95-43da-b089-cdf4d6d5247d\n# ╠═3245d573-ffe6-44b2-9734-753a011ab10c\n# ╟─5c294ee4-1d99-4d7d-a94d-afc3a643614e\n", "meta": {"hexsha": "596a955332ebf1102cab13b3d559fedb7851a581", "size": 43981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture1-sampling.jl", "max_stars_repo_name": "DawievLill/pluto-static-export", "max_stars_repo_head_hexsha": "7788556c551dcd94bb4453d00738f732b1f26de3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture1-sampling.jl", "max_issues_repo_name": "DawievLill/pluto-static-export", "max_issues_repo_head_hexsha": "7788556c551dcd94bb4453d00738f732b1f26de3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture1-sampling.jl", "max_forks_repo_name": "DawievLill/pluto-static-export", "max_forks_repo_head_hexsha": "7788556c551dcd94bb4453d00738f732b1f26de3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2487992315, "max_line_length": 626, "alphanum_fraction": 0.7384325049, "num_tokens": 18252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.1798009527021047}} {"text": "# These functions (variants of sa_numerical_method)\n# return an instance of a numerical method to solve\n# saturation adjustment, for different combinations\n# of thermodynamic variable inputs.\n\n# @print only accepts literal strings, so we must\n# branch to print which method is being used.\nfunction print_numerical_method(\n ::Type{sat_adjust_method},\n) where {sat_adjust_method}\n if sat_adjust_method <: NewtonsMethod\n @print(\" Method=NewtonsMethod\")\n elseif sat_adjust_method <: NewtonsMethodAD\n @print(\" Method=NewtonsMethodAD\")\n elseif sat_adjust_method <: SecantMethod\n @print(\" Method=SecantMethod\")\n elseif sat_adjust_method <: RegulaFalsiMethod\n @print(\" Method=RegulaFalsiMethod\")\n else\n error(\"Unsupported numerical method\")\n end\nend\n\n#####\n##### Thermodynamic variable inputs: ρ, e_int, q_tot\n#####\nfunction sa_numerical_method(\n ::Type{NM},\n param_set::APS,\n ρ::FT,\n e_int::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: NewtonsMethod}\n _T_min::FT = T_min(param_set)\n T_init =\n max(_T_min, air_temperature(param_set, e_int, PhasePartition(q_tot))) # Assume all vapor\n return NewtonsMethod(\n T_init,\n T_ -> ∂e_int_∂T(param_set, heavisided(T_), e_int, ρ, q_tot, phase_type),\n )\nend\n\nfunction sa_numerical_method(\n ::Type{NM},\n param_set::APS,\n ρ::FT,\n e_int::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: NewtonsMethodAD}\n _T_min::FT = T_min(param_set)\n T_init =\n max(_T_min, air_temperature(param_set, e_int, PhasePartition(q_tot))) # Assume all vapor\n return NewtonsMethodAD(T_init)\nend\n\nfunction sa_numerical_method(\n ::Type{NM},\n param_set::APS,\n ρ::FT,\n e_int::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: SecantMethod}\n _T_min::FT = T_min(param_set)\n q_pt = PhasePartition(q_tot, FT(0), q_tot) # Assume all ice\n T_2 = air_temperature(param_set, e_int, q_pt)\n T_1 = max(_T_min, air_temperature(param_set, e_int, PhasePartition(q_tot))) # Assume all vapor\n T_2 = bound_upper_temperature(T_1, T_2)\n return SecantMethod(T_1, T_2)\nend\n\nfunction sa_numerical_method(\n ::Type{NM},\n param_set::APS,\n ρ::FT,\n e_int::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: RegulaFalsiMethod}\n _T_min::FT = T_min(param_set)\n q_pt = PhasePartition(q_tot, FT(0), q_tot) # Assume all ice\n T_2 = air_temperature(param_set, e_int, q_pt)\n T_1 = max(_T_min, air_temperature(param_set, e_int, PhasePartition(q_tot))) # Assume all vapor\n T_2 = bound_upper_temperature(T_1, T_2)\n return RegulaFalsiMethod(T_1, T_2)\nend\n\n#####\n##### Thermodynamic variable inputs: ρ, p, q_tot\n#####\n\nfunction sa_numerical_method_ρpq(\n ::Type{NM},\n param_set::APS,\n ρ::FT,\n p::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: NewtonsMethodAD}\n q_pt = PhasePartition(q_tot)\n T_init = air_temperature_from_ideal_gas_law(param_set, p, ρ, q_pt)\n return NewtonsMethodAD(T_init)\nend\n\nfunction sa_numerical_method_ρpq(\n ::Type{NM},\n param_set::APS,\n ρ::FT,\n p::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: RegulaFalsiMethod}\n q_pt = PhasePartition(q_tot)\n T_1 = air_temperature_from_ideal_gas_law(param_set, p, ρ, q_pt) - 5\n T_2 = air_temperature_from_ideal_gas_law(param_set, p, ρ, q_pt) + 5\n return RegulaFalsiMethod(T_1, T_2)\nend\n\n#####\n##### Thermodynamic variable inputs: p, e_int, q_tot\n#####\n\nfunction sa_numerical_method_peq(\n ::Type{NM},\n param_set::APS,\n p::FT,\n e_int::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: NewtonsMethodAD}\n _T_min::FT = T_min(param_set)\n T_init =\n max(_T_min, air_temperature(param_set, e_int, PhasePartition(q_tot))) # Assume all vapor\n return NewtonsMethodAD(T_init)\nend\n\nfunction sa_numerical_method_peq(\n ::Type{NM},\n param_set::APS,\n p::FT,\n e_int::FT,\n q_tot::FT,\n phase_type::Type{<:PhaseEquil},\n) where {FT, NM <: SecantMethod}\n _T_min::FT = T_min(param_set)\n q_pt = PhasePartition(q_tot, FT(0), q_tot) # Assume all ice\n T_2 = air_temperature(param_set, e_int, q_pt)\n T_1 = max(_T_min, air_temperature(param_set, e_int, PhasePartition(q_tot))) # Assume all vapor\n T_2 = bound_upper_temperature(T_1, T_2)\n return SecantMethod(T_1, T_2)\nend\n", "meta": {"hexsha": "c1b311f0a89ef761f9ff60079493196179aeb8d3", "size": 4445, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Common/Thermodynamics/config_numerical_method.jl", "max_stars_repo_name": "thomasgibson/ClimateMachine.jl", "max_stars_repo_head_hexsha": "147eee06be26269a596adc31666d82fddfb95ac4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Common/Thermodynamics/config_numerical_method.jl", "max_issues_repo_name": "thomasgibson/ClimateMachine.jl", "max_issues_repo_head_hexsha": "147eee06be26269a596adc31666d82fddfb95ac4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Common/Thermodynamics/config_numerical_method.jl", "max_forks_repo_name": "thomasgibson/ClimateMachine.jl", "max_forks_repo_head_hexsha": "147eee06be26269a596adc31666d82fddfb95ac4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8636363636, "max_line_length": 98, "alphanum_fraction": 0.674015748, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.17966915353558557}} {"text": "### A Pluto.jl notebook ###\n# v0.14.2\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ 74b008f6-ed6b-11ea-291f-b3791d6d1b35\nbegin\n\timport Pkg\n\tPkg.activate(mktempdir())\n\tPkg.add([\n\t\tPkg.PackageSpec(name=\"ImageIO\", version=\"0.5\"),\n\t\tPkg.PackageSpec(name=\"ImageShow\", version=\"0.2\"),\n\t\tPkg.PackageSpec(name=\"FileIO\", version=\"1.6\"),\n\t\tPkg.PackageSpec(name=\"PNGFiles\", version=\"0.3.6\"),\n\t\tPkg.PackageSpec(name=\"Colors\", version=\"0.12\"),\n\t\tPkg.PackageSpec(name=\"ColorVectorSpace\", version=\"0.8\"),\n\t\tPkg.PackageSpec(name=\"PlutoUI\", version=\"0.7\"), \n\t\tPkg.PackageSpec(name=\"HypertextLiteral\", version=\"0.5\")\n\t])\n\n\tusing Colors, ColorVectorSpace, ImageShow, FileIO\n\tusing PlutoUI\n\tusing HypertextLiteral\nend\n\n# ╔═╡ 71a1e08a-6abc-48d5-b177-5184dbdd76a8\nfilter!(LOAD_PATH) do path\n\tpath != \"@v#.#\"\nend;\n\n# ╔═╡ e91d7926-ec6e-41e7-aba2-9dca333c8aa5\nhtml\"\"\"\n
\n\n
\n

Section 1.1

\n

\n Images as Data and Arrays \n

\n\n

Lecture Video

\n
\n
\n
\n
\n
\n\n\"\"\"\n\n# ╔═╡ d07fcdb0-7afc-4a25-b68a-49fd1e3405e7\nPlutoUI.TableOfContents(aside=true)\n\n# ╔═╡ 9b49500c-0164-4556-a17b-7595e35c5ede\nmd\"\"\"\n#### Intializing packages\n\n_When running this notebook for the first time, this could take up to 15 minutes. Hang in there!_\n\"\"\"\n\n# ╔═╡ ca1b507e-6017-11eb-34e6-6b85cd189002\nmd\"\"\"\n# Images as examples of data all around us\nWelcome to the Computational Thinking using Julia for Real-World Problems, at MIT in Spring 2021!\n\nThe aim of this course is to bring together concepts from computer science and applied math with coding in the modern **Julia language**, and to see how to apply these techniques to study interesting applications (and of course to have fun).\n\nWe would be pleased if students who have been interested in computer science now become interested in computational science and those interested in scientific applications learn computer science they may not see elsewhere.\n... and for all students, we wish to share the value of \nthe Julia language as the best of both worlds.\n\"\"\"\n\n# ╔═╡ e9ff96d8-6bc1-11eb-0f6a-234b9fae047e\nmd\"\"\"\n\n## Alan's Essay: Are all programming languages the same? \n\n>Superficially, many programming languages are very similar. \"Showoffs\" will compare functional programming vs imperative programming. Others will compare compiled languages vs dynamic languages. I will avoid such fancy terms in this little essay, preferring to provide this course's pedagogical viewpoint.\n>\n>Generally speaking beginning programmers should learn to create \"arrays\" write \"for loops\", \"conditionals\", \"comparisons\", express mathematical formulas, etc. So why Julia at a time when Python seems to be the language of teaching, and Java and C++ so prominent in the corporate world?\n>\n>As you might imagine, we believe Julia is special. Oh you will still have the nitty gritty of when to use a bracket and a comma. You might have strong opinions as to whether arrays should begin with 0 or 1 (joke: some say it's time to compromise and use ½.) Getting past these irrelevant issues, you will begin to experience one by one what makes Julia so very special. For starters, a language that runs fast is more fun. We can have you try things that would just be so slow in other languages it would be boring. We also think you will start to notice how natural Julia is, how it feels like the mathematics, and how flexible it can be. \n>\n>Getting to see the true value of fancy terms like multiple dispatch, strong typing, generic programming, and composable software will take a little longer, but stick with us, and you too will see why Julia is so very special.\n\"\"\"\n\n# ╔═╡ 9111db10-6bc3-11eb-38e5-cf3f58536914\nmd\"\"\"\n## Computer Science and Computational Science Working Together\n\"\"\"\n\n# ╔═╡ fb8a99ac-6bc1-11eb-0835-3146734a1c99\nmd\"\"\"\nApplications of computer science in the real world use **data**, i.e. information that we can **measure** in some way. Data take many different forms, for example:\n\n- Numbers that change over time (**time series**): \n - Stock price each second / minute / day\n - Weekly number of infections\n - Earth's global average temperature\n\n- Video:\n - The view from a window of a self-driving car\n - A hurricane monitoring station\n - Ultrasound e.g. prenatal\n\n- Images:\n - Diseased versus healthy tissue in a medical scan\n - Pictures of your favourite dog\n\"\"\"\n\n# ╔═╡ b795dcb4-6bc3-11eb-20ec-db2cc4b89bfb\nmd\"\"\"\n#### Exercise: \n> Think of another two examples in each category. Can you think of other categories of data?\n\"\"\"\n\n# ╔═╡ 8691e434-6bc4-11eb-07d1-8169158484e6\nmd\"\"\"\nComputational science can be summed up by a simplified workflow:\n\"\"\"\n\n# ╔═╡ 546db74c-6d4e-11eb-2e27-f5bed9dbd9ba\nmd\"\"\"\n## data ⟶ input ⟶ process ⟶ model ⟶ visualize ⟶ output\n\"\"\"\n\n# ╔═╡ 6385d174-6d4e-11eb-093b-6f6fafb79f84\nmd\"\"\"\n$(html\"
\")\nTo use any data source, we need to **input** the data of interest, for example by downloading it, reading in the resulting file, and converting it into a form that we can use in the computer. Then we need to **process** it in some way to extract information of interest. We usually want to **visualize** the results, and we may want to **output** them, for example by saving to disc or putting them on a website.\n\nWe often want to make a mathematical or computational **model** that can help us to understand and predict the behavior of the system of interest.\n\n> In this course we aim to show how programming, computer science and applied math combine to help us with these goals.\n\"\"\"\n\n# ╔═╡ 132f6596-6bc6-11eb-29f1-1b2478c929af\nmd\"\"\"\n# Data: Images (as an example of data)\nLet's start off by looking at **images** and how we can process them. \nOur goal is to process the data contained in an image in some way, which we will do by developing and coding certain **algorithms**.\n\nHere is the the Fall 2020 version of this lecture (small variations) by 3-Blue-1-Brown (Grant Sanderson) for your reference.\n\"\"\"\n\n# ╔═╡ 635a03dd-abd7-49c8-a3d2-e68c7d83cc9b\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ 9eb6efd2-6018-11eb-2db8-c3ce41d9e337\nmd\"\"\"\n\n\nIf we open an image on our computer or the web and zoom in enough, we will see that it consists of many tiny squares, or **pixels** (\"picture elements\"). Each pixel is a block of one single colour, and the pixels are arranged in a two-dimensional square grid. \n\nYou probably already know that these pixels are stored in a computer numerically\nperhaps in some form of RGB (red,green,blue) format. This is the computer's represenation of the data. \n\nNote that an image is already an **approximation** of the real world -- it is a two-dimensional, discrete representation of a three-dimensional reality.\n\n\"\"\"\n\n# ╔═╡ e37e4d40-6018-11eb-3e1d-093266c98507\nmd\"\"\"\n# Input and Visualize: loading and viewing an Image (in Julia)\n\"\"\"\n\n# ╔═╡ e1c9742a-6018-11eb-23ba-d974e57f78f9\nmd\"\"\"\nLet's use Julia to load actual images and play around with them. We can download images from the internet, your own file, or your own webcam.\n\"\"\"\n\n# ╔═╡ 9b004f70-6bc9-11eb-128c-914eadfc9a0e\nmd\"\"\"\n## Downloading an image from the internet or a local file\nWe can use the `Images.jl` package to load an image file in three steps.\n\"\"\"\n\n# ╔═╡ 62fa19da-64c6-11eb-0038-5d40a6890cf5\nmd\"\"\"\nStep 1: (from internet) we specify the URL (web address) to download from:\n$(html\"
\")\n(note that Pluto places results before commands because some people believe\noutput is more interesting than code. This takes some getting used to.)\n\"\"\"\n\n# ╔═╡ 34ee0954-601e-11eb-1912-97dc2937fd52\nurl = \"https://user-images.githubusercontent.com/6933510/107239146-dcc3fd00-6a28-11eb-8c7b-41aaf6618935.png\" \n\n# ╔═╡ 9180fbcc-601e-11eb-0c22-c920dc7ee9a9\nmd\"\"\"\nStep 2: Now we use the aptly-named `download` function to download the image file to our own computer. (Philip is Prof. Edelman's corgi.)\n\"\"\"\n\n# ╔═╡ 34ffc3d8-601e-11eb-161c-6f9a07c5fd78\nphilip_filename = download(url) # download to a local file. The filename is returned\n\n# ╔═╡ abaaa980-601e-11eb-0f71-8ff02269b775\nmd\"\"\"\nStep 3:\nUsing the `Images.jl` package (loaded at the start of this notebook; scroll up and take a look.) we can **load** the file, which automatically converts it into usable data. We'll store the result in a variable. (Remember the code is after the output.)\n\"\"\"\n\n# ╔═╡ aafe76a6-601e-11eb-1ff5-01885c5238da\nphilip = load(philip_filename)\n\n# ╔═╡ e86ed944-ee05-11ea-3e0f-d70fc73b789c\nmd\"_Hi there Philip_\"\n\n# ╔═╡ c99d2aa8-601e-11eb-3469-497a246db17c\nmd\"\"\"\nWe see that the Pluto notebook has recognised that we created an object representing an image, and automatically displayed the resulting image of Philip, the cute Welsh Pembroke corgi and co-professor of this course.\nPoor Philip will undergo quite a few transformations as we go along!\n\"\"\"\n\n# ╔═╡ 11dff4ce-6bca-11eb-1056-c1345c796ed4\nmd\"\"\"\n- Exercise : change the url.\n- Exercise: download a file that is already on your own computer.\n\"\"\"\n\n# ╔═╡ efef3a32-6bc9-11eb-17e9-dd2171be9c21\nmd\"\"\"\n## Capturing an Image from your own camera\n\"\"\"\n\n# ╔═╡ e94dcc62-6d4e-11eb-3d53-ff9878f0091e\nmd\"\"\"\nEven more fun is to use your own webcam. Try pressing the enable button below. Then\npress the camera to capture an image. Kind of fun to keep pressing the button as you move your hand etc.\n\"\"\"\n\n# ╔═╡ cef1a95a-64c6-11eb-15e7-636a3621d727\nmd\"\"\"\n## Inspecting your data\n\"\"\"\n\n# ╔═╡ f26d9326-64c6-11eb-1166-5d82586422ed\nmd\"\"\"\n### Image size\n\"\"\"\n\n# ╔═╡ 6f928b30-602c-11eb-1033-71d442feff93\nmd\"\"\"\nThe first thing we might want to know is the size of the image:\n\"\"\"\n\n# ╔═╡ 75c5c85a-602c-11eb-2fb1-f7e7f2c5d04b\nphilip_size = size(philip)\n\n# ╔═╡ 77f93eb8-602c-11eb-1f38-efa56cc93ca5\nmd\"\"\"\nJulia returns a pair of two numbers. Comparing these with the picture of the image, we see that the first number is the height, i.e. the vertical number of pixels, and the second is the width.\n\"\"\"\n\n# ╔═╡ 96b7d801-c427-4e27-ab1f-e2fd18fc24d0\nphilip_height = philip_size[1]\n\n# ╔═╡ f08d02af-6e38-4ace-8b11-7af4930b64ea\nphilip_width = philip_size[2]\n\n# ╔═╡ f9244264-64c6-11eb-23a6-cfa76f8aff6d\nmd\"\"\"\n### Locations in an image: Indexing\n\nNow suppose that we want to examine a piece of the image in more detail. We need some way of specifying which piece of the image we want. \n\nThinking of the image as a grid of pixels, we need a way to tell the computer which pixel or group of pixels we want to refer to. \nSince the image is a two-dimensional grid, we can use two integers (whole numbers) to give the coordinates of a single pixel. Specifying coordinates like this is called **indexing**: think of the index of a book, which tells you *on which page* an idea is discussed.\n\nIn Julia we use (square) brackets, `[` and `]` for indexing: \n\"\"\"\n\n# ╔═╡ bd22d09a-64c7-11eb-146f-67733b8be241\na_pixel = philip[200, 100]\n\n# ╔═╡ 28860d48-64c8-11eb-240f-e1232b3638df\nmd\"\"\"\nWe see that Julia knows to draw our pixel object for us a block of the relevant color.\n\nWhen we index into an image like this, the first number indicates the *row* in the image, starting from the top, and the second the *column*, starting from the left. In Julia, the first row and column are numbered starting from 1, not from 0 as in some other programming languages.\n\"\"\"\n\n# ╔═╡ 4ef99715-4d8d-4f9d-bf0b-8df9907a14cf\n\n\n# ╔═╡ a510fc33-406e-4fb5-be83-9e4b5578717c\nmd\"\"\"\nWe can also use variables as indices...\n\"\"\"\n\n# ╔═╡ 13844ebf-52c4-47e9-bda4-106a02fad9d7\nmd\"\"\"\n...and these variables can be controlled by sliders!\n\"\"\"\n\n# ╔═╡ 08d61afb-c641-4aa9-b995-2552af89f3b8\n@bind row_i Slider(1:size(philip)[1], show_value=true)\n\n# ╔═╡ 6511a498-7ac9-445b-9c15-ec02d09783fe\n@bind col_i Slider(1:size(philip)[2], show_value=true)\n\n# ╔═╡ 94b77934-713e-11eb-18cf-c5dc5e7afc5b\nrow_i,col_i\n\n# ╔═╡ ff762861-b186-4eb0-9582-0ce66ca10f60\nphilip[row_i, col_i]\n\n# ╔═╡ c9ed950c-dcd9-4296-a431-ee0f36d5b557\nmd\"\"\"\n### Locations in an image: Range indexing\n\nWe saw that we can use the **row number** and **column number** to index a _single pixel_ of our image. Next, we will use a **range of numbers** to index _multiple rows or columns_ at once, returning a subarray:\n\"\"\"\n\n# ╔═╡ f0796032-8105-4f6d-b5ee-3647b052f2f6\nphilip[550:650, 1:philip_width]\n\n# ╔═╡ b9be8761-a9c9-49eb-ba1b-527d12097362\nmd\"\"\"\nHere, we use `a:b` to mean \"_all numbers between `a` and `b`_\". For example:\n\n\"\"\"\n\n# ╔═╡ d515286b-4ad4-449b-8967-06b9b4c87684\ncollect(1:10)\n\n# ╔═╡ eef8fbc8-8887-4628-8ba8-114575d6b91f\nmd\"\"\"\n\nYou can also use a `:` without start and end to mean \"_every index_\"\n\"\"\"\n\n# ╔═╡ 4e6a31d6-1ef8-4a69-b346-ad58cfc4d8a5\nphilip[550:650, :]\n\n# ╔═╡ e11f0e47-02d9-48a6-9b1a-e313c18db129\nmd\"\"\"\nLet's get a single row of pixels:\n\"\"\"\n\n# ╔═╡ 9e447eab-14b6-45d8-83ab-1f7f1f1c70d2\nphilip[550, :]\n\n# ╔═╡ c926435c-c648-419c-9951-ac8a1d4f3b92\nphilip_head = philip[470:800, 140:410]\n\n# ╔═╡ 32e7e51c-dd0d-483d-95cb-e6043f2b2975\nmd\"\"\"\n#### Scroll in on Philip's nose!\n\nUse the widgets below (slide left and right sides).\n\"\"\"\n\n# ╔═╡ 4b64e1f2-d0ca-4e22-a89d-1d9a16bd6788\n@bind range_rows RangeSlider(1:size(philip_head)[1])\n\n# ╔═╡ 85919db9-1444-4904-930f-ba572cff9460\n@bind range_cols RangeSlider(1:size(philip_head)[2])\n\n# ╔═╡ 2ac47b91-bbc3-49ae-9bf5-4def30ff46f4\nnose = philip_head[range_rows, range_cols]\n\n# ╔═╡ 5a0cc342-64c9-11eb-1211-f1b06d652497\nmd\"\"\"\n# Process: Modifying an image\n\nNow that we have access to image data, we can start to **process** that data to extract information and/or modify it in some way.\n\nWe might want to detect what type of objects are in the image, say to detect whether a patient has a certain disease. To achieve a high-level goal like this, we will need to perform mid-level operations, such as detecting edges that separate different objects based on their color. And, in turn, to carry that out we will need to do low-level operations like comparing colors of neighboring pixels and somehow deciding if they are \"different\".\n\n\"\"\"\n\n# ╔═╡ 4504577c-64c8-11eb-343b-3369b6d10d8b\nmd\"\"\"\n## Representing colors\n\nWe can use indexing to *modify* a pixel's color. To do so, we need a way to specify a new color.\n\nColor turns out to be a complicated concept, having to do with the interaction of the physical properties of light with the physiological mechanisms and mental processes by which we detect it!\n\nWe will ignore this complexity by using a standard method of representing colours in the computer as an **RGB triple**, i.e. a triple of three numbers $(r, g, b)$, giving the amount of red, of green and of blue in a colour, respectively. These are numbers between 0 (none) and 1 (full). The final colour that we perceive is the result of \"adding\" the corresponding amount of light of each colour; the details are fascinating, but beyond the scope of this course!\n\"\"\"\n\n# ╔═╡ 40886d36-64c9-11eb-3c69-4b68673a6dde\nmd\"\"\"\nWe can create a new color in Julia as follows:\n\"\"\"\n\n# ╔═╡ 552235ec-64c9-11eb-1f7f-f76da2818cb3\nRGB(1.0, 0.0, 0.0)\n\n# ╔═╡ c2907d1a-47b1-4634-8669-a68022706861\nbegin\n\tmd\"\"\"\n\tA pixel with $(@bind test_r Scrubbable(0:0.1:1; default=0.1)) red, $(@bind test_g Scrubbable(0:0.1:1; default=0.5)) green and $(@bind test_b Scrubbable(0:0.1:1; default=1.0)) blue looks like:\n\t\"\"\"\nend\n\t\n\n# ╔═╡ ff9eea3f-cab0-4030-8337-f519b94316c5\nRGB(test_r, test_g, test_b)\n\n# ╔═╡ f6cc03a0-ee07-11ea-17d8-013991514d42\nmd\"\"\"\n#### Exercise 2.5\n👉 Write a function `invert` that inverts a color, i.e. sends $(r, g, b)$ to $(1 - r, 1-g, 1-b)$.\n\"\"\"\n\n# ╔═╡ 63e8d636-ee0b-11ea-173d-bd3327347d55\nfunction invert(color::AbstractRGB)\n\t\n\treturn RGB(1 - color.r, 1 - color.g, 1 - color.b)\nend\n\n# ╔═╡ 2cc2f84e-ee0d-11ea-373b-e7ad3204bb00\nmd\"Let's invert some colors:\"\n\n# ╔═╡ b8f26960-ee0a-11ea-05b9-3f4bc1099050\nblack = RGB(0.0, 0.0, 0.0)\n\n# ╔═╡ 5de3a22e-ee0b-11ea-230f-35df4ca3c96d\ninvert(black)\n\n# ╔═╡ 4e21e0c4-ee0b-11ea-3d65-b311ae3f98e9\nred = RGB(0.8, 0.1, 0.1)\n\n# ╔═╡ 6dbf67ce-ee0b-11ea-3b71-abc05a64dc43\ninvert(red)\n\n# ╔═╡ 846b1330-ee0b-11ea-3579-7d90fafd7290\nmd\"Can you invert the picture of Philip?\"\n\n# ╔═╡ 943103e2-ee0b-11ea-33aa-75a8a1529931\nphilip_inverted = invert.(philip)\n\n# ╔═╡ 2ee543b2-64d6-11eb-3c39-c5660141787e\nmd\"\"\"\n\n## Modifying a pixel\n\nLet's start by seeing how to modify an image, e.g. in order to hide sensitive information.\n\nWe do this by assigning a new value to the color of a pixel:\n\"\"\"\n\n# ╔═╡ 53bad296-4c7b-471f-b481-0e9423a9288a\nlet\n\ttemp = copy(philip_head)\n\ttemp[100, 200] = RGB(1.0, 0.0, 0.0)\n\ttemp\nend\n\n# ╔═╡ 81b88cbe-64c9-11eb-3b26-39011efb2089\nmd\"\"\"\nBe careful: We are actually *modifying* the original image here, even though if we look at the image it is hard to spot, since a single pixel is so small.\n\"\"\"\n\n# ╔═╡ ab9af0f6-64c9-11eb-13d3-5dbdb75a69a7\nmd\"\"\"\n## Groups of pixels\n\nWe probably want to examine and modify several pixels at once.\nFor example, we can extract a horizontal strip 1 pixel tall:\n\"\"\"\n\n# ╔═╡ e29b7954-64cb-11eb-2768-47de07766055\nphilip_head[50, 50:100]\n\n# ╔═╡ 8e7c4866-64cc-11eb-0457-85be566a8966\nmd\"\"\"\nHere, Julia is showing the strip as a collection of rectangles in a row.\n\n\n\"\"\"\n\n# ╔═╡ f2ad501a-64cb-11eb-1707-3365d05b300a\nmd\"\"\"\nAnd then modify it:\n\"\"\"\n\n# ╔═╡ 4f03f651-56ed-4361-b954-e6848ac56089\nlet\n\ttemp = copy(philip_head)\n\ttemp[50, 50:100] .= RGB(1.0, 0.0, 0.0)\n\ttemp\nend\n\n# ╔═╡ 2808339c-64cc-11eb-21d1-c76a9854aa5b\nmd\"\"\"\nSimilarly we can modify a whole rectangular block of pixels:\n\"\"\"\n\n# ╔═╡ 1bd53326-d705-4d1a-bf8f-5d7f2a4e696f\nlet\n\ttemp = copy(philip_head)\n\ttemp[50:100, 50:100] .= RGB(1.0, 0.0, 0.0)\n\ttemp\nend\n\n# ╔═╡ a5f8bafe-edf0-11ea-0da3-3330861ae43a\nmd\"\"\"\n#### Exercise 1.2\n\n👉 Generate a vector of 100 zeros. Change the center 20 elements to 1.\n\"\"\"\n\n# ╔═╡ b6b65b94-edf0-11ea-3686-fbff0ff53d08\nfunction create_bar()\n\tbar = zeros(100)\n\tbar[41:60] .= 1\n\t\n\treturn bar\nend\n\n# ╔═╡ 693af19c-64cc-11eb-31f3-57ab2fbae597\nmd\"\"\"\n## Reducing the size of an image\n\"\"\"\n\n# ╔═╡ 6361d102-64cc-11eb-31b7-fb631b632040\nmd\"\"\"\nMaybe we would also like to reduce the size of this image, since it's rather large. For example, we could take every 10th row and every 10th column and make a new image from the result:\n\"\"\"\n\n# ╔═╡ ae542fe4-64cc-11eb-29fc-73b7a66314a9\nreduced_image = philip[1:10:end, 1:10:end]\n\n# ╔═╡ c29292b8-64cc-11eb-28db-b52c46e865e6\nmd\"\"\"\nNote that the resulting image doesn't look very good, since we seem to have lost too much detail. \n\n#### Exercise\n\n> Think about what we might do to reduce the size of an image without losing so much detail.\n\"\"\"\n\n# ╔═╡ 7b04331a-6bcb-11eb-34fa-1f5b151e5510\nmd\"\"\"\n# Model: Creating synthetic images \n\nThink about your favorite Pixar movie (e.g. Monsters Inc.) Movie frames are images that are generated from complicated mathematical models. Ray tracing (which may be covered in this class)\nis a method for making images feel realistic. \n\"\"\"\n\n# ╔═╡ 5319c03c-64cc-11eb-0743-a1612476e2d3\nmd\"\"\"\n# Output: Saving an image to a file\n\nFinally, we want to be able to save our new creation to a file. To do so, you can **right click** on a displayed image, or you can write it to a file. Fill in a path below:\n\"\"\"\n\n# ╔═╡ 3db09d92-64cc-11eb-0333-45193c0fd1fe\nsave(\"reduced_phil.png\", reduced_image)\n\n# ╔═╡ 61606acc-6bcc-11eb-2c80-69ceec9f9702\nmd\"\"\"\n# $(html\"
\") \n\"\"\"\n\n# ╔═╡ dd183eca-6018-11eb-2a83-2fcaeea62942\nmd\"\"\"\n# Computer science: Arrays\n\nAn image is a concrete example of a fundamental concept in computer science, namely an **array**. \n\nJust as an image is a rectangular grid, where each grid cell contains a single color,\nan array is a rectangular grid for storing data. Data is stored and retrieved using indexing, just as in the image examples: each cell in the grid can store a single \"piece of data\" of a given type.\n\n\n## Dimension of an array\n\nAn array can be one-dimensional, like the strip of pixels above, two-dimensional, three-dimensional, and so on. The dimension tells us the number of indices that we need to specify a unique location in the grid.\nThe array object also needs to know the length of the data in each dimension.\n\n## Names for different types of array\n\nOne-dimensional arrays are often called **vectors** (or, in some other languages, \"lists\") and two-dimensional arrays are **matrices**. Higher-dimensional arrays are **tensors**.\n\n\n## Arrays as data structures\n\nAn array is an example of a **data structure**, i.e. a way of arranging data such that we can access it. A key theme in computer science is that of designing different data structures that represent data in different ways.\n\nConceptually, we can think of an array as a block of data that has a position or location in space. This can be a useful way to arrange data if, for example, we want to represent the fact that values in nearby locations in array are somehow near to one another.\n\nImages are a good example of this: neighbouring pixels often represent different pieces of the same object, for example the rug or floor, or Philip himself, in the photo. We thus expect neighbouring pixels to be of a similar color. On the other hand, if they are not, this is also useful information, since that may correspond to the edge of an object.\n\n\"\"\"\n\n# ╔═╡ 8ddcb286-602a-11eb-3ae0-07d3c77a0f8c\nmd\"\"\"\n# Julia: constructing arrays\n\n## Creating vectors and matrices\nJulia has strong support for arrays of any dimension.\n\nVectors, or one-dimensional arrays, are written using square brackets and commas:\n\"\"\"\n\n# ╔═╡ f4b0aa23-2d76-4d88-b2a4-3807e88d27ce\n[1, 20, \"hello\"]\n\n# ╔═╡ 1b2b2b18-64d4-11eb-2d43-e31cb8bc25d1\n[RGB(1, 0, 0), RGB(0, 1, 0), RGB(0, 0, 1)]\n\n# ╔═╡ 2b0e6450-64d4-11eb-182b-ff1bd515b56f\nmd\"\"\"\nMatrices, or two-dimensional arrays, also use square brackets, but with spaces and new lines instead of commas:\n\"\"\"\n\n# ╔═╡ 3b2b041a-64d4-11eb-31dd-47d7321ee909\n[RGB(1, 0, 0) RGB(0, 1, 0)\n RGB(0, 0, 1) RGB(0.5, 0.5, 0.5)]\n\n# ╔═╡ 0f35603a-64d4-11eb-3baf-4fef06d82daa\nmd\"\"\"\n\n## Array comprehensions\n\nIt's clear that if we want to create an array with more than a few elements, it will be *very* tedious to do so by hand like this.\nRather, we want to *automate* the process of creating an array by following some pattern, for example to create a whole palette of colors!\n\nLet's start with all the possible colors interpolating between black, `RGB(0, 0, 0)`, and red, `RGB(1, 0, 0)`. Since only one of the values is changing, we can represent this as a vector, i.e. a one-dimensional array.\n\nA neat method to do this is an **array comprehension**. Again we use square brackets to create an array, but now we use a **variable** that varies over a given **range** values:\n\"\"\"\n\n# ╔═╡ e69b02c6-64d6-11eb-02f1-21c4fb5d1043\n[RGB(x, 0, 0) for x in 0:0.1:1]\n\n# ╔═╡ fce76132-64d6-11eb-259d-b130038bbae6\nmd\"\"\"\nHere, `0:0.1:1` is a **range**; the first and last numbers are the start and end values, and the middle number is the size of the step.\n\"\"\"\n\n# ╔═╡ 17a69736-64d7-11eb-2c6c-eb5ebf51b285\nmd\"\"\"\nIn a similar way we can create two-dimensional matrices, by separating the two variables for each dimension with a comma (`,`):\n\"\"\"\n\n# ╔═╡ 291b04de-64d7-11eb-1ee0-d998dccb998c\n[RGB(i, j, 0) for i in 0:0.1:1, j in 0:0.1:1]\n\n# ╔═╡ 647fddf2-60ee-11eb-124d-5356c7014c3b\nmd\"\"\"\n## Joining matrices\n\nWe often want to join vectors and matrices together. We can do so using an extension of the array creation syntax:\n\"\"\"\n\n# ╔═╡ 7d9ad134-60ee-11eb-1b2a-a7d63f3a7a2d\n[philip_head philip_head]\n\n# ╔═╡ 8433b862-60ee-11eb-0cfc-add2b72997dc\n[philip_head reverse(philip_head, dims=2)\n reverse(philip_head, dims=1) rot180(philip_head)]\n\n# ╔═╡ 5e52d12e-64d7-11eb-0905-c9038a404e24\nmd\"\"\"\n# Pluto: Interactivity using sliders\n\"\"\"\n\n# ╔═╡ 6aba7e62-64d7-11eb-2c49-7944e9e2b94b\nmd\"\"\"\nSuppose we want to see the effect of changing the number of colors in our vector or matrix. We could, of course, do so by manually fiddling with the range.\n\nIt would be nice if we could do so using a **user interface**, for example with a **slider**. Fortunately, the Pluto notebook allows us to do so!\n\"\"\"\n\n# ╔═╡ afc66dac-64d7-11eb-1ad0-7f62c20ffefb\nmd\"\"\"\nWe can define a slider using\n\"\"\"\n\n# ╔═╡ b37c9868-64d7-11eb-3033-a7b5d3065f7f\n@bind number_reds Slider(1:100, show_value=true)\n\n# ╔═╡ b1dfe122-64dc-11eb-1104-1b8852b2c4c5\nmd\"\"\"\n[The `Slider` type is defined in the `PlutoUI.jl` package.]\n\"\"\"\n\n# ╔═╡ cfc55140-64d7-11eb-0ff6-e59c70d01d67\nmd\"\"\"\nThis creates a new variable called `number_reds`, whose value is the value shown by the slider. When we move the slider, the value of the variable gets updated. Since Pluto is a **reactive** notebook, other cells which use the value of this variable will *automatically be updated too*!\n\"\"\"\n\n# ╔═╡ fca72490-64d7-11eb-1464-f5e0582c4d18\nmd\"\"\"\nLet's use this to make a slider for our one-dimensional collection of reds:\n\"\"\"\n\n# ╔═╡ 88933746-6028-11eb-32de-13eb6ff43e29\n[RGB(red_value / number_reds, 0, 0) for red_value in 0:number_reds]\n\n# ╔═╡ 1c539b02-64d8-11eb-3505-c9288357d139\nmd\"\"\"\nWhen you move the slider, you should see the number of red color patches change!\n\"\"\"\n\n# ╔═╡ 10f6e6da-64d8-11eb-366f-11f16e73043b\nmd\"\"\"\nWhat is going on here is that we are creating a vector in which `red_value` takes each value in turn from the range from `0` up to the current value of `number_reds`. If we change `number_reds`, then we create a new vector with that new number of red patches.\n\"\"\"\n\n# ╔═╡ 82a8314c-64d8-11eb-1acb-e33625381178\nmd\"\"\"\n#### Exercise\n\n> Make three sliders with variables `r`, `g` and `b`. Then make a single color patch with the RGB color given by those values.\n\"\"\"\n\n# ╔═╡ e01fb06a-3be2-4f02-af8a-88d1141bf223\n@bind r Slider(0:0.01:1, show_value=true)\n\n# ╔═╡ 19956bda-2828-4931-bc15-e6577e66bbe1\n@bind g Slider(0:0.01:1, show_value=true)\n\n# ╔═╡ 3b420ccf-4ecb-4d9d-b052-6c6398c6dc1c\n@bind b Slider(0:0.01:1, show_value=true)\n\n# ╔═╡ 40331f9c-8a83-4819-bd6d-cfef1fe91fc2\nRGB(r, g, b)\n\n# ╔═╡ 576d5e3a-64d8-11eb-10c9-876be31f7830\nmd\"\"\"\nWe can do the same to create different size matrices, by creating two sliders, one for reds and one for greens. Try it out!\n\"\"\"\n\n# ╔═╡ ace86c8a-60ee-11eb-34ef-93c54abc7b1a\nmd\"\"\"\n# Summary\n\"\"\"\n\n# ╔═╡ b08e57e4-60ee-11eb-0e1a-2f49c496668b\nmd\"\"\"\nLet's summarize the main ideas from this notebook:\n- Images are **arrays** of colors\n- We can inspect and modify arrays using **indexing**\n- We can create arrays directly or using **array comprehensions**\n\"\"\"\n\n# ╔═╡ 9025a5b4-6066-11eb-20e8-099e9b8f859e\nmd\"\"\"\n----\n\"\"\"\n\n# ╔═╡ 5da8cbe8-eded-11ea-2e43-c5b7cc71e133\nbegin\n\tcolored_line(x::Vector{<:Real}) = Gray.(Float64.((hcat(x)')))\n\tcolored_line(x::Any) = nothing\nend\n\n# ╔═╡ d862fb16-edf1-11ea-36ec-615d521e6bc0\ncolored_line(create_bar())\n\n# ╔═╡ e074560a-601b-11eb-340e-47acd64f03b2\nhint(text) = Markdown.MD(Markdown.Admonition(\"hint\", \"Hint\", [text]))\n\n# ╔═╡ e0776548-601b-11eb-2563-57ba2cf1d5d1\nalmost(text) = Markdown.MD(Markdown.Admonition(\"warning\", \"Almost there!\", [text]))\n\n# ╔═╡ e083bef6-601b-11eb-2134-e3063d5c4253\nstill_missing(text=md\"Replace `missing` with your answer.\") = Markdown.MD(Markdown.Admonition(\"warning\", \"Here we go!\", [text]))\n\n# ╔═╡ e08ecb84-601b-11eb-0e25-152ed3a262f7\nkeep_working(text=md\"The answer is not quite right.\") = Markdown.MD(Markdown.Admonition(\"danger\", \"Keep working on it!\", [text]))\n\n# ╔═╡ e09036a4-601b-11eb-1a8b-ef70105ab91c\nyays = [md\"Great!\", md\"Yay ❤\", md\"Great! 🎉\", md\"Well done!\", md\"Keep it up!\", md\"Good job!\", md\"Awesome!\", md\"You got the right answer!\", md\"Let's move on to the next section.\"]\n\n# ╔═╡ e09af1a2-601b-11eb-14c8-57a46546f6ce\ncorrect(text=rand(yays)) = Markdown.MD(Markdown.Admonition(\"correct\", \"Got it!\", [text]))\n\n# ╔═╡ e0a4fc10-601b-11eb-211d-03570aca2726\nnot_defined(variable_name) = Markdown.MD(Markdown.Admonition(\"danger\", \"Oopsie!\", [md\"Make sure that you define a variable called **$(Markdown.Code(string(variable_name)))**\"]))\n\n# ╔═╡ e3394c8a-edf0-11ea-1bb8-619f7abb6881\nif !@isdefined(create_bar)\n\tnot_defined(:create_bar)\nelse\n\tlet\n\t\tresult = create_bar()\n\t\tif ismissing(result)\n\t\t\tstill_missing()\n\t\telseif isnothing(result)\n\t\t\tkeep_working(md\"Did you forget to write `return`?\")\n\t\telseif !(result isa Vector) || length(result) != 100\n\t\t\tkeep_working(md\"The result should be a `Vector` with 100 elements.\")\n\t\telseif result[[1,50,100]] != [0,1,0]\n\t\t\tkeep_working()\n\t\telse\n\t\t\tcorrect()\n\t\tend\n\tend\nend\n\n# ╔═╡ e0a6031c-601b-11eb-27a5-65140dd92897\nbigbreak = html\"




\";\n\n# ╔═╡ 45815734-ee0a-11ea-2982-595e1fc0e7b1\nbigbreak\n\n# ╔═╡ e0b15582-601b-11eb-26d6-bbf708933bc8\nfunction camera_input(;max_size=150, default_url=\"https://i.imgur.com/SUmi94P.png\")\n\"\"\"\n\n\n\n\t
\n\t\t
\n\t\t\t\n\t\t\t\n\t\t
\n\t\t\n\t\t
\n\t\t\n\t\t
\n\t
\n\t\t\n\t
\n\t\t\n\t\tEnable webcam\n\t\t\n\t
\n\n\n
\n\"\"\" |> HTML\nend\n\n# ╔═╡ d6742ea0-1106-4f3c-a5b8-a31a48d33f19\n@bind webcam_data1 camera_input()\n\n# ╔═╡ 2a94a2cf-b697-4b0b-afd0-af2e35af2bb1\n@bind webcam_data camera_input()\n\n# ╔═╡ e891fce0-601b-11eb-383b-bde5b128822e\n\nfunction process_raw_camera_data(raw_camera_data)\n\t# the raw image data is a long byte array, we need to transform it into something\n\t# more \"Julian\" - something with more _structure_.\n\t\n\t# The encoding of the raw byte stream is:\n\t# every 4 bytes is a single pixel\n\t# every pixel has 4 values: Red, Green, Blue, Alpha\n\t# (we ignore alpha for this notebook)\n\t\n\t# So to get the red values for each pixel, we take every 4th value, starting at \n\t# the 1st:\n\treds_flat = UInt8.(raw_camera_data[\"data\"][1:4:end])\n\tgreens_flat = UInt8.(raw_camera_data[\"data\"][2:4:end])\n\tblues_flat = UInt8.(raw_camera_data[\"data\"][3:4:end])\n\t\n\t# but these are still 1-dimensional arrays, nicknamed 'flat' arrays\n\t# We will 'reshape' this into 2D arrays:\n\t\n\twidth = raw_camera_data[\"width\"]\n\theight = raw_camera_data[\"height\"]\n\t\n\t# shuffle and flip to get it in the right shape\n\treds = reshape(reds_flat, (width, height))' / 255.0\n\tgreens = reshape(greens_flat, (width, height))' / 255.0\n\tblues = reshape(blues_flat, (width, height))' / 255.0\n\t\n\t# we have our 2D array for each color\n\t# Let's create a single 2D array, where each value contains the R, G and B value of \n\t# that pixel\n\t\n\tRGB.(reds, greens, blues)\nend\n\n# ╔═╡ 1d7375b7-7ea6-4d67-ab73-1c69d6b8b87f\nmyface1 = process_raw_camera_data(webcam_data1);\n\n# ╔═╡ 6224c74b-8915-4983-abf0-30e6ba04a46d\n[\n\tmyface1 myface1[ : , end:-1:1]\n\tmyface1[end:-1:1, :] myface1[end:-1:1, end:-1:1]\n]\n\n# ╔═╡ 3e0ece65-b8a7-4be7-ae44-6d7210c2e15b\nmyface = process_raw_camera_data(webcam_data);\n\n# ╔═╡ 4ee18bee-13e6-4478-b2ca-ab66100e57ec\n[\n\tmyface myface[ : , end:-1:1]\n\tmyface[end:-1:1, :] myface[end:-1:1, end:-1:1]\n]\n\n# ╔═╡ 3ef77236-1867-4d02-8af2-ff4777fcd6d9\nexercise_css = html\"\"\"\n\n\n\"\"\"\n\n# ╔═╡ 61b29e7d-5aba-4bc8-870b-c1c43919c236\nexercise(x, number=\"\") = \n@htl(\"\"\"\n\t\n\t

Exercise $(number)

\n\t
$(x)\n\t
\n\t
\n\t\"\"\")\n\n# ╔═╡ a9fef6c9-e911-4d8c-b141-a4832b40a260\nquick_question(x, number, options, correct) = let\n\tname = join(rand('a':'z',16))\n@htl(\"\"\"\n\t\n\t

Quick Question $(number)

\n\t
$(x)\n\t\n\t$(map(enumerate(options)) do (i, o)\n\t\t@htl(\"$(o)\")\n\tend)\n\t\n\t
\n\t
\n\t\"\"\")\nend\n\n# ╔═╡ edf900be-601b-11eb-0456-3f7cfc5e876b\nmd\"_Lecture 1, Spring 2021, version 0_\"\n\n# ╔═╡ Cell order:\n# ╟─e91d7926-ec6e-41e7-aba2-9dca333c8aa5\n# ╟─d07fcdb0-7afc-4a25-b68a-49fd1e3405e7\n# ╟─9b49500c-0164-4556-a17b-7595e35c5ede\n# ╠═74b008f6-ed6b-11ea-291f-b3791d6d1b35\n# ╟─71a1e08a-6abc-48d5-b177-5184dbdd76a8\n# ╟─ca1b507e-6017-11eb-34e6-6b85cd189002\n# ╟─e9ff96d8-6bc1-11eb-0f6a-234b9fae047e\n# ╟─9111db10-6bc3-11eb-38e5-cf3f58536914\n# ╟─fb8a99ac-6bc1-11eb-0835-3146734a1c99\n# ╟─b795dcb4-6bc3-11eb-20ec-db2cc4b89bfb\n# ╟─8691e434-6bc4-11eb-07d1-8169158484e6\n# ╟─546db74c-6d4e-11eb-2e27-f5bed9dbd9ba\n# ╟─6385d174-6d4e-11eb-093b-6f6fafb79f84\n# ╟─132f6596-6bc6-11eb-29f1-1b2478c929af\n# ╟─635a03dd-abd7-49c8-a3d2-e68c7d83cc9b\n# ╟─9eb6efd2-6018-11eb-2db8-c3ce41d9e337\n# ╟─e37e4d40-6018-11eb-3e1d-093266c98507\n# ╟─e1c9742a-6018-11eb-23ba-d974e57f78f9\n# ╟─9b004f70-6bc9-11eb-128c-914eadfc9a0e\n# ╟─62fa19da-64c6-11eb-0038-5d40a6890cf5\n# ╠═34ee0954-601e-11eb-1912-97dc2937fd52\n# ╟─9180fbcc-601e-11eb-0c22-c920dc7ee9a9\n# ╠═34ffc3d8-601e-11eb-161c-6f9a07c5fd78\n# ╟─abaaa980-601e-11eb-0f71-8ff02269b775\n# ╠═aafe76a6-601e-11eb-1ff5-01885c5238da\n# ╟─e86ed944-ee05-11ea-3e0f-d70fc73b789c\n# ╟─c99d2aa8-601e-11eb-3469-497a246db17c\n# ╟─11dff4ce-6bca-11eb-1056-c1345c796ed4\n# ╟─efef3a32-6bc9-11eb-17e9-dd2171be9c21\n# ╟─e94dcc62-6d4e-11eb-3d53-ff9878f0091e\n# ╟─d6742ea0-1106-4f3c-a5b8-a31a48d33f19\n# ╠═1d7375b7-7ea6-4d67-ab73-1c69d6b8b87f\n# ╠═6224c74b-8915-4983-abf0-30e6ba04a46d\n# ╟─cef1a95a-64c6-11eb-15e7-636a3621d727\n# ╟─f26d9326-64c6-11eb-1166-5d82586422ed\n# ╟─6f928b30-602c-11eb-1033-71d442feff93\n# ╠═75c5c85a-602c-11eb-2fb1-f7e7f2c5d04b\n# ╟─77f93eb8-602c-11eb-1f38-efa56cc93ca5\n# ╠═96b7d801-c427-4e27-ab1f-e2fd18fc24d0\n# ╠═f08d02af-6e38-4ace-8b11-7af4930b64ea\n# ╟─f9244264-64c6-11eb-23a6-cfa76f8aff6d\n# ╠═bd22d09a-64c7-11eb-146f-67733b8be241\n# ╟─28860d48-64c8-11eb-240f-e1232b3638df\n# ╟─4ef99715-4d8d-4f9d-bf0b-8df9907a14cf\n# ╟─a510fc33-406e-4fb5-be83-9e4b5578717c\n# ╠═94b77934-713e-11eb-18cf-c5dc5e7afc5b\n# ╠═ff762861-b186-4eb0-9582-0ce66ca10f60\n# ╟─13844ebf-52c4-47e9-bda4-106a02fad9d7\n# ╠═08d61afb-c641-4aa9-b995-2552af89f3b8\n# ╠═6511a498-7ac9-445b-9c15-ec02d09783fe\n# ╟─c9ed950c-dcd9-4296-a431-ee0f36d5b557\n# ╠═f0796032-8105-4f6d-b5ee-3647b052f2f6\n# ╟─b9be8761-a9c9-49eb-ba1b-527d12097362\n# ╠═d515286b-4ad4-449b-8967-06b9b4c87684\n# ╟─eef8fbc8-8887-4628-8ba8-114575d6b91f\n# ╠═4e6a31d6-1ef8-4a69-b346-ad58cfc4d8a5\n# ╟─e11f0e47-02d9-48a6-9b1a-e313c18db129\n# ╠═9e447eab-14b6-45d8-83ab-1f7f1f1c70d2\n# ╠═c926435c-c648-419c-9951-ac8a1d4f3b92\n# ╟─32e7e51c-dd0d-483d-95cb-e6043f2b2975\n# ╠═4b64e1f2-d0ca-4e22-a89d-1d9a16bd6788\n# ╠═85919db9-1444-4904-930f-ba572cff9460\n# ╠═2ac47b91-bbc3-49ae-9bf5-4def30ff46f4\n# ╟─5a0cc342-64c9-11eb-1211-f1b06d652497\n# ╟─4504577c-64c8-11eb-343b-3369b6d10d8b\n# ╟─40886d36-64c9-11eb-3c69-4b68673a6dde\n# ╠═552235ec-64c9-11eb-1f7f-f76da2818cb3\n# ╟─c2907d1a-47b1-4634-8669-a68022706861\n# ╠═ff9eea3f-cab0-4030-8337-f519b94316c5\n# ╟─f6cc03a0-ee07-11ea-17d8-013991514d42\n# ╠═63e8d636-ee0b-11ea-173d-bd3327347d55\n# ╟─2cc2f84e-ee0d-11ea-373b-e7ad3204bb00\n# ╟─b8f26960-ee0a-11ea-05b9-3f4bc1099050\n# ╠═5de3a22e-ee0b-11ea-230f-35df4ca3c96d\n# ╠═4e21e0c4-ee0b-11ea-3d65-b311ae3f98e9\n# ╠═6dbf67ce-ee0b-11ea-3b71-abc05a64dc43\n# ╟─846b1330-ee0b-11ea-3579-7d90fafd7290\n# ╠═943103e2-ee0b-11ea-33aa-75a8a1529931\n# ╟─2ee543b2-64d6-11eb-3c39-c5660141787e\n# ╠═53bad296-4c7b-471f-b481-0e9423a9288a\n# ╟─81b88cbe-64c9-11eb-3b26-39011efb2089\n# ╟─ab9af0f6-64c9-11eb-13d3-5dbdb75a69a7\n# ╠═e29b7954-64cb-11eb-2768-47de07766055\n# ╟─8e7c4866-64cc-11eb-0457-85be566a8966\n# ╟─f2ad501a-64cb-11eb-1707-3365d05b300a\n# ╠═4f03f651-56ed-4361-b954-e6848ac56089\n# ╟─2808339c-64cc-11eb-21d1-c76a9854aa5b\n# ╠═1bd53326-d705-4d1a-bf8f-5d7f2a4e696f\n# ╟─a5f8bafe-edf0-11ea-0da3-3330861ae43a\n# ╠═b6b65b94-edf0-11ea-3686-fbff0ff53d08\n# ╟─d862fb16-edf1-11ea-36ec-615d521e6bc0\n# ╟─e3394c8a-edf0-11ea-1bb8-619f7abb6881\n# ╟─693af19c-64cc-11eb-31f3-57ab2fbae597\n# ╟─6361d102-64cc-11eb-31b7-fb631b632040\n# ╠═ae542fe4-64cc-11eb-29fc-73b7a66314a9\n# ╟─c29292b8-64cc-11eb-28db-b52c46e865e6\n# ╟─7b04331a-6bcb-11eb-34fa-1f5b151e5510\n# ╟─5319c03c-64cc-11eb-0743-a1612476e2d3\n# ╠═3db09d92-64cc-11eb-0333-45193c0fd1fe\n# ╟─61606acc-6bcc-11eb-2c80-69ceec9f9702\n# ╟─dd183eca-6018-11eb-2a83-2fcaeea62942\n# ╟─8ddcb286-602a-11eb-3ae0-07d3c77a0f8c\n# ╠═f4b0aa23-2d76-4d88-b2a4-3807e88d27ce\n# ╠═1b2b2b18-64d4-11eb-2d43-e31cb8bc25d1\n# ╟─2b0e6450-64d4-11eb-182b-ff1bd515b56f\n# ╠═3b2b041a-64d4-11eb-31dd-47d7321ee909\n# ╟─0f35603a-64d4-11eb-3baf-4fef06d82daa\n# ╠═e69b02c6-64d6-11eb-02f1-21c4fb5d1043\n# ╟─fce76132-64d6-11eb-259d-b130038bbae6\n# ╟─17a69736-64d7-11eb-2c6c-eb5ebf51b285\n# ╠═291b04de-64d7-11eb-1ee0-d998dccb998c\n# ╟─647fddf2-60ee-11eb-124d-5356c7014c3b\n# ╠═7d9ad134-60ee-11eb-1b2a-a7d63f3a7a2d\n# ╠═8433b862-60ee-11eb-0cfc-add2b72997dc\n# ╟─5e52d12e-64d7-11eb-0905-c9038a404e24\n# ╟─6aba7e62-64d7-11eb-2c49-7944e9e2b94b\n# ╟─afc66dac-64d7-11eb-1ad0-7f62c20ffefb\n# ╠═b37c9868-64d7-11eb-3033-a7b5d3065f7f\n# ╟─b1dfe122-64dc-11eb-1104-1b8852b2c4c5\n# ╟─cfc55140-64d7-11eb-0ff6-e59c70d01d67\n# ╟─fca72490-64d7-11eb-1464-f5e0582c4d18\n# ╠═88933746-6028-11eb-32de-13eb6ff43e29\n# ╟─1c539b02-64d8-11eb-3505-c9288357d139\n# ╟─10f6e6da-64d8-11eb-366f-11f16e73043b\n# ╟─82a8314c-64d8-11eb-1acb-e33625381178\n# ╠═e01fb06a-3be2-4f02-af8a-88d1141bf223\n# ╠═19956bda-2828-4931-bc15-e6577e66bbe1\n# ╠═3b420ccf-4ecb-4d9d-b052-6c6398c6dc1c\n# ╠═40331f9c-8a83-4819-bd6d-cfef1fe91fc2\n# ╟─576d5e3a-64d8-11eb-10c9-876be31f7830\n# ╠═2a94a2cf-b697-4b0b-afd0-af2e35af2bb1\n# ╠═3e0ece65-b8a7-4be7-ae44-6d7210c2e15b\n# ╠═4ee18bee-13e6-4478-b2ca-ab66100e57ec\n# ╟─ace86c8a-60ee-11eb-34ef-93c54abc7b1a\n# ╟─b08e57e4-60ee-11eb-0e1a-2f49c496668b\n# ╟─9025a5b4-6066-11eb-20e8-099e9b8f859e\n# ╟─45815734-ee0a-11ea-2982-595e1fc0e7b1\n# ╟─5da8cbe8-eded-11ea-2e43-c5b7cc71e133\n# ╟─e074560a-601b-11eb-340e-47acd64f03b2\n# ╟─e0776548-601b-11eb-2563-57ba2cf1d5d1\n# ╟─e083bef6-601b-11eb-2134-e3063d5c4253\n# ╟─e08ecb84-601b-11eb-0e25-152ed3a262f7\n# ╟─e09036a4-601b-11eb-1a8b-ef70105ab91c\n# ╟─e09af1a2-601b-11eb-14c8-57a46546f6ce\n# ╟─e0a4fc10-601b-11eb-211d-03570aca2726\n# ╠═e0a6031c-601b-11eb-27a5-65140dd92897\n# ╟─e0b15582-601b-11eb-26d6-bbf708933bc8\n# ╟─e891fce0-601b-11eb-383b-bde5b128822e\n# ╟─3ef77236-1867-4d02-8af2-ff4777fcd6d9\n# ╟─61b29e7d-5aba-4bc8-870b-c1c43919c236\n# ╟─a9fef6c9-e911-4d8c-b141-a4832b40a260\n# ╟─edf900be-601b-11eb-0456-3f7cfc5e876b\n", "meta": {"hexsha": "9449f88a26390bc8eb1778a732f91cc75fd38b36", "size": 43511, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/week1/images.jl", "max_stars_repo_name": "rfhklwt/18S191_notebook", "max_stars_repo_head_hexsha": "beb6001d2fc92a317cb9e578a60d83222512bebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/week1/images.jl", "max_issues_repo_name": "rfhklwt/18S191_notebook", "max_issues_repo_head_hexsha": "beb6001d2fc92a317cb9e578a60d83222512bebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/week1/images.jl", "max_forks_repo_name": "rfhklwt/18S191_notebook", "max_forks_repo_head_hexsha": "beb6001d2fc92a317cb9e578a60d83222512bebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4708955224, "max_line_length": 650, "alphanum_fraction": 0.723954862, "num_tokens": 17109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.17915942452585246}} {"text": "struct DGModel{BL,G,NFND,NFD,GNF,AS,DS,D,MD}\n balancelaw::BL\n grid::G\n numfluxnondiff::NFND\n numfluxdiff::NFD\n gradnumflux::GNF\n auxstate::AS\n diffstate::DS\n direction::D\n modeldata::MD\nend\nfunction DGModel(balancelaw, grid, numfluxnondiff, numfluxdiff, gradnumflux;\n auxstate=create_auxstate(balancelaw, grid),\n diffstate=create_diffstate(balancelaw, grid),\n direction=EveryDirection(), modeldata=nothing)\n DGModel(balancelaw, grid, numfluxnondiff, numfluxdiff, gradnumflux, auxstate,\n diffstate, direction, modeldata)\nend\n\nfunction (dg::DGModel)(dQdt, Q, ::Nothing, t; increment=false)\n bl = dg.balancelaw\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n Nfp = Nq * Nqk\n nrealelem = length(topology.realelems)\n\n Qvisc = dg.diffstate\n auxstate = dg.auxstate\n\n FT = eltype(Q)\n nviscstate = num_diffusive(bl, FT)\n\n Np = dofs_per_element(grid)\n\n communicate = !(isstacked(topology) &&\n typeof(dg.direction) <: VerticalDirection)\n\n aux_comm = update_aux!(dg, bl, Q, t)\n @assert typeof(aux_comm) == Bool\n\n ########################\n # Gradient Computation #\n ########################\n if communicate\n MPIStateArrays.start_ghost_exchange!(Q)\n if aux_comm\n MPIStateArrays.start_ghost_exchange!(auxstate)\n end\n end\n\n if nviscstate > 0\n\n @launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,\n volumeviscterms!(bl, Val(dim), Val(N), dg.direction, Q.data,\n Qvisc.data, auxstate.data, grid.vgeo, t, grid.D,\n topology.realelems))\n\n if communicate\n MPIStateArrays.finish_ghost_recv!(Q)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n end\n\n @launch(device, threads=Nfp, blocks=nrealelem,\n faceviscterms!(bl, Val(dim), Val(N), dg.direction,\n dg.gradnumflux, Q.data, Qvisc.data, auxstate.data,\n grid.vgeo, grid.sgeo, t, grid.vmapM, grid.vmapP, grid.elemtobndy,\n topology.realelems))\n\n if communicate\n MPIStateArrays.start_ghost_exchange!(Qvisc)\n end\n\n aux_comm = update_aux_diffusive!(dg, bl, Q, t)\n @assert typeof(aux_comm) == Bool\n\n if aux_comm\n MPIStateArrays.start_ghost_exchange!(auxstate)\n end\n end\n\n\n ###################\n # RHS Computation #\n ###################\n @launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,\n volumerhs!(bl, Val(dim), Val(N), dg.direction, dQdt.data,\n Q.data, Qvisc.data, auxstate.data, grid.vgeo, t,\n grid.ω, grid.D, topology.realelems, increment))\n\n if communicate\n if nviscstate > 0\n MPIStateArrays.finish_ghost_recv!(Qvisc)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n else\n MPIStateArrays.finish_ghost_recv!(Q)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n end\n end\n\n @launch(device, threads=Nfp, blocks=nrealelem,\n facerhs!(bl, Val(dim), Val(N), dg.direction,\n dg.numfluxnondiff,\n dg.numfluxdiff,\n dQdt.data, Q.data, Qvisc.data,\n auxstate.data, grid.vgeo, grid.sgeo, t, grid.vmapM, grid.vmapP, grid.elemtobndy,\n topology.realelems))\n\n # Just to be safe, we wait on the sends we started.\n if communicate\n MPIStateArrays.finish_ghost_send!(Qvisc)\n MPIStateArrays.finish_ghost_send!(Q)\n end\nend\n\nfunction init_ode_state(dg::DGModel, args...;\n forcecpu=false,\n commtag=888)\n device = arraytype(dg.grid) <: Array ? CPU() : CUDA()\n\n bl = dg.balancelaw\n grid = dg.grid\n\n state = create_state(bl, grid, commtag)\n\n topology = grid.topology\n Np = dofs_per_element(grid)\n\n auxstate = dg.auxstate\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n nrealelem = length(topology.realelems)\n\n if !forcecpu\n @launch(device, threads=(Np,), blocks=nrealelem,\n initstate!(bl, Val(dim), Val(N), state.data, auxstate.data, grid.vgeo,\n topology.realelems, args...))\n else\n h_state = similar(state, Array)\n h_auxstate = similar(auxstate, Array)\n h_auxstate .= auxstate\n @launch(CPU(), threads=(Np,), blocks=nrealelem,\n initstate!(bl, Val(dim), Val(N), h_state.data, h_auxstate.data, Array(grid.vgeo),\n topology.realelems, args...))\n state .= h_state\n end\n\n MPIStateArrays.start_ghost_exchange!(state)\n MPIStateArrays.finish_ghost_exchange!(state)\n\n return state\nend\n\n# fallback\nfunction update_aux!(dg::DGModel, bl::BalanceLaw, Q::MPIStateArray, t::Real)\n return false\nend\n\nfunction update_aux_diffusive!(dg::DGModel, bl::BalanceLaw, Q::MPIStateArray, t::Real)\n return false\nend\n\nfunction indefinite_stack_integral!(dg::DGModel, m::BalanceLaw,\n Q::MPIStateArray,\n auxstate::MPIStateArray,\n t::Real)\n\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n FT = eltype(Q)\n\n # do integrals\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,\n knl_indefinite_stack_integral!(m, Val(dim), Val(N),\n Val(nvertelem),\n Q.data, auxstate.data,\n grid.vgeo, grid.Imat, 1:nhorzelem))\nend\n\nfunction reverse_indefinite_stack_integral!(dg::DGModel,\n m::BalanceLaw,\n Q::MPIStateArray,\n auxstate::MPIStateArray, t::Real)\n\n device = typeof(auxstate.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n FT = eltype(auxstate)\n\n # do integrals\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,\n knl_reverse_indefinite_stack_integral!(m, Val(dim), Val(N),\n Val(nvertelem),\n Q.data, auxstate.data,\n 1:nhorzelem))\nend\n\nfunction nodal_update_aux!(f!, dg::DGModel, m::BalanceLaw, Q::MPIStateArray,\n t::Real; diffusive=false)\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n nrealelem = length(topology.realelems)\n\n Np = dofs_per_element(grid)\n\n ### update aux variables\n if diffusive\n @launch(device, threads=(Np,), blocks=nrealelem,\n knl_nodal_update_aux!(m, Val(dim), Val(N), f!,\n Q.data, dg.auxstate.data, dg.diffstate.data, t,\n topology.realelems))\n else\n @launch(device, threads=(Np,), blocks=nrealelem,\n knl_nodal_update_aux!(m, Val(dim), Val(N), f!,\n Q.data, dg.auxstate.data, t,\n topology.realelems))\n end\nend\n\n\"\"\"\n courant(local_courant::Function, dg::DGModel, m::BalanceLaw,\n Q::MPIStateArray, direction=EveryDirection())\nReturns the maximum of the evaluation of the function `local_courant`\npointwise throughout the domain. The function `local_courant` is given an\napproximation of the local node distance `Δx`. The `direction` controls which\nreference directions are considered when computing the minimum node distance\n`Δx`.\nAn example `local_courant` function is\n function local_courant(m::AtmosModel, state::Vars, aux::Vars,\n diffusive::Vars, Δx)\n return Δt * cmax / Δx\n end\nwhere `Δt` is the time step size and `cmax` is the maximum flow speed in the\nmodel.\n\"\"\"\nfunction courant(local_courant::Function, dg::DGModel, m::BalanceLaw,\n Q::MPIStateArray, Δt, direction=EveryDirection())\n grid = dg.grid\n topology = grid.topology\n nrealelem = length(topology.realelems)\n\n if nrealelem > 0\n N = polynomialorder(grid)\n dim = dimensionality(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n device = grid.vgeo isa Array ? CPU() : CUDA()\n pointwise_courant = similar(grid.vgeo, Nq^dim, nrealelem)\n @launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,\n Grids.knl_min_neighbor_distance!(Val(N), Val(dim), direction,\n pointwise_courant, grid.vgeo, topology.realelems))\n @launch(device, threads=(Nq*Nq*Nqk,), blocks=nrealelem,\n knl_local_courant!(m, Val(dim), Val(N), pointwise_courant,\n local_courant, Q.data, dg.auxstate.data,\n dg.diffstate.data, topology.realelems, direction, Δt))\n rank_courant_max = maximum(pointwise_courant)\n else\n rank_courant_max = typemin(eltype(Q))\n end\n\n MPI.Allreduce(rank_courant_max, max, topology.mpicomm)\nend\n\nfunction copy_stack_field_down!(dg::DGModel, m::BalanceLaw,\n auxstate::MPIStateArray, fldin, fldout)\n\n device = typeof(auxstate.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n # do integrals\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,\n knl_copy_stack_field_down!(Val(dim), Val(N), Val(nvertelem),\n auxstate.data, 1:nhorzelem, Val(fldin),\n Val(fldout)))\nend\n\nfunction MPIStateArrays.MPIStateArray(dg::DGModel, commtag=888)\n bl = dg.balancelaw\n grid = dg.grid\n\n state = create_state(bl, grid, commtag)\n\n return state\nend\n\n", "meta": {"hexsha": "629f6bac4c56597edc2eed2bcca05104cfabfa82", "size": 10430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DGmethods/DGmodel.jl", "max_stars_repo_name": "favba/CLIMA", "max_stars_repo_head_hexsha": "0fd99247903bba86497c6b50333cc7e38fc949aa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DGmethods/DGmodel.jl", "max_issues_repo_name": "favba/CLIMA", "max_issues_repo_head_hexsha": "0fd99247903bba86497c6b50333cc7e38fc949aa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DGmethods/DGmodel.jl", "max_forks_repo_name": "favba/CLIMA", "max_forks_repo_head_hexsha": "0fd99247903bba86497c6b50333cc7e38fc949aa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8579881657, "max_line_length": 99, "alphanum_fraction": 0.6005752637, "num_tokens": 2837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17912319260816784}} {"text": "#=\nThis file is auto-generated. Do not edit.\n=#\n\"\"\"\n mutable struct OneDOneQMachine <: Machine\n R::Float64\n Xd::Float64\n Xq::Float64\n Xd_p::Float64\n Xq_p::Float64\n Td0_p::Float64\n Tq0_p::Float64\n ext::Dict{String, Any}\n states::Vector{Symbol}\n n_states::Int\n internal::InfrastructureSystemsInternal\n end\n\nParameters of 4-states synchronous machine: Simplified Marconato model\n The derivative of stator fluxes (ψd and ψq) is neglected and ωψd = ψd and\n ωψq = ψq is assumed (i.e. ω=1.0). This is standard when\n transmission network dynamics is neglected.\n\n# Arguments\n- `R::Float64`: Resistance after EMF in machine per unit, validation range: `(0, nothing)`\n- `Xd::Float64`: Reactance after EMF in d-axis per unit, validation range: `(0, nothing)`\n- `Xq::Float64`: Reactance after EMF in q-axis per unit, validation range: `(0, nothing)`\n- `Xd_p::Float64`: Transient reactance after EMF in d-axis per unit, validation range: `(0, nothing)`\n- `Xq_p::Float64`: Transient reactance after EMF in q-axis per unit, validation range: `(0, nothing)`\n- `Td0_p::Float64`: Time constant of transient d-axis voltage, validation range: `(0, nothing)`\n- `Tq0_p::Float64`: Time constant of transient q-axis voltage, validation range: `(0, nothing)`\n- `ext::Dict{String, Any}`\n- `states::Vector{Symbol}`: The states are:\n\teq_p: q-axis transient voltage,\n\ted_p: d-axis transient voltage\n- `n_states::Int`: OneDOneQMachine has 2 states\n- `internal::InfrastructureSystemsInternal`: power system internal reference, do not modify\n\"\"\"\nmutable struct OneDOneQMachine <: Machine\n \"Resistance after EMF in machine per unit\"\n R::Float64\n \"Reactance after EMF in d-axis per unit\"\n Xd::Float64\n \"Reactance after EMF in q-axis per unit\"\n Xq::Float64\n \"Transient reactance after EMF in d-axis per unit\"\n Xd_p::Float64\n \"Transient reactance after EMF in q-axis per unit\"\n Xq_p::Float64\n \"Time constant of transient d-axis voltage\"\n Td0_p::Float64\n \"Time constant of transient q-axis voltage\"\n Tq0_p::Float64\n ext::Dict{String, Any}\n \"The states are:\n\teq_p: q-axis transient voltage,\n\ted_p: d-axis transient voltage\"\n states::Vector{Symbol}\n \"OneDOneQMachine has 2 states\"\n n_states::Int\n \"power system internal reference, do not modify\"\n internal::InfrastructureSystemsInternal\nend\n\nfunction OneDOneQMachine(R, Xd, Xq, Xd_p, Xq_p, Td0_p, Tq0_p, ext=Dict{String, Any}(), )\n OneDOneQMachine(R, Xd, Xq, Xd_p, Xq_p, Td0_p, Tq0_p, ext, [:eq_p, :ed_p], 2, InfrastructureSystemsInternal(), )\nend\n\nfunction OneDOneQMachine(; R, Xd, Xq, Xd_p, Xq_p, Td0_p, Tq0_p, ext=Dict{String, Any}(), states=[:eq_p, :ed_p], n_states=2, internal=InfrastructureSystemsInternal(), )\n OneDOneQMachine(R, Xd, Xq, Xd_p, Xq_p, Td0_p, Tq0_p, ext, states, n_states, internal, )\nend\n\n# Constructor for demo purposes; non-functional.\nfunction OneDOneQMachine(::Nothing)\n OneDOneQMachine(;\n R=0,\n Xd=0,\n Xq=0,\n Xd_p=0,\n Xq_p=0,\n Td0_p=0,\n Tq0_p=0,\n ext=Dict{String, Any}(),\n )\nend\n\n\"\"\"Get [`OneDOneQMachine`](@ref) `R`.\"\"\"\nget_R(value::OneDOneQMachine) = value.R\n\"\"\"Get [`OneDOneQMachine`](@ref) `Xd`.\"\"\"\nget_Xd(value::OneDOneQMachine) = value.Xd\n\"\"\"Get [`OneDOneQMachine`](@ref) `Xq`.\"\"\"\nget_Xq(value::OneDOneQMachine) = value.Xq\n\"\"\"Get [`OneDOneQMachine`](@ref) `Xd_p`.\"\"\"\nget_Xd_p(value::OneDOneQMachine) = value.Xd_p\n\"\"\"Get [`OneDOneQMachine`](@ref) `Xq_p`.\"\"\"\nget_Xq_p(value::OneDOneQMachine) = value.Xq_p\n\"\"\"Get [`OneDOneQMachine`](@ref) `Td0_p`.\"\"\"\nget_Td0_p(value::OneDOneQMachine) = value.Td0_p\n\"\"\"Get [`OneDOneQMachine`](@ref) `Tq0_p`.\"\"\"\nget_Tq0_p(value::OneDOneQMachine) = value.Tq0_p\n\"\"\"Get [`OneDOneQMachine`](@ref) `ext`.\"\"\"\nget_ext(value::OneDOneQMachine) = value.ext\n\"\"\"Get [`OneDOneQMachine`](@ref) `states`.\"\"\"\nget_states(value::OneDOneQMachine) = value.states\n\"\"\"Get [`OneDOneQMachine`](@ref) `n_states`.\"\"\"\nget_n_states(value::OneDOneQMachine) = value.n_states\n\"\"\"Get [`OneDOneQMachine`](@ref) `internal`.\"\"\"\nget_internal(value::OneDOneQMachine) = value.internal\n\n\"\"\"Set [`OneDOneQMachine`](@ref) `R`.\"\"\"\nset_R!(value::OneDOneQMachine, val) = value.R = val\n\"\"\"Set [`OneDOneQMachine`](@ref) `Xd`.\"\"\"\nset_Xd!(value::OneDOneQMachine, val) = value.Xd = val\n\"\"\"Set [`OneDOneQMachine`](@ref) `Xq`.\"\"\"\nset_Xq!(value::OneDOneQMachine, val) = value.Xq = val\n\"\"\"Set [`OneDOneQMachine`](@ref) `Xd_p`.\"\"\"\nset_Xd_p!(value::OneDOneQMachine, val) = value.Xd_p = val\n\"\"\"Set [`OneDOneQMachine`](@ref) `Xq_p`.\"\"\"\nset_Xq_p!(value::OneDOneQMachine, val) = value.Xq_p = val\n\"\"\"Set [`OneDOneQMachine`](@ref) `Td0_p`.\"\"\"\nset_Td0_p!(value::OneDOneQMachine, val) = value.Td0_p = val\n\"\"\"Set [`OneDOneQMachine`](@ref) `Tq0_p`.\"\"\"\nset_Tq0_p!(value::OneDOneQMachine, val) = value.Tq0_p = val\n\"\"\"Set [`OneDOneQMachine`](@ref) `ext`.\"\"\"\nset_ext!(value::OneDOneQMachine, val) = value.ext = val\n\n", "meta": {"hexsha": "f89cfec70343ba3cf8e5661d741f8c341c0b8bae", "size": 4933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/models/generated/OneDOneQMachine.jl", "max_stars_repo_name": "jd-lara/PowerSystems.jl", "max_stars_repo_head_hexsha": "b61dc4d079168c55d96ec46e085d64b8f2e97d13", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-04-02T22:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:40:38.000Z", "max_issues_repo_path": "src/models/generated/OneDOneQMachine.jl", "max_issues_repo_name": "jd-lara/PowerSystems.jl", "max_issues_repo_head_hexsha": "b61dc4d079168c55d96ec46e085d64b8f2e97d13", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 339, "max_issues_repo_issues_event_min_datetime": "2020-04-01T21:11:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:24:53.000Z", "max_forks_repo_path": "src/models/generated/OneDOneQMachine.jl", "max_forks_repo_name": "jd-lara/PowerSystems.jl", "max_forks_repo_head_hexsha": "b61dc4d079168c55d96ec46e085d64b8f2e97d13", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44, "max_forks_repo_forks_event_min_datetime": "2020-05-27T15:30:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:36:50.000Z", "avg_line_length": 38.842519685, "max_line_length": 167, "alphanum_fraction": 0.6813298196, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.17903827714869822}} {"text": "using QuantumControlBase.QuantumPropagators: propstep!, write_to_storage!, get_from_storage!\nusing QuantumControlBase: evalcontrols!\nusing QuantumControlBase.Functionals: make_chi\nusing QuantumControlBase.ConditionalThreads: @threadsif\nusing LinearAlgebra\nusing Printf\n\n\n\"\"\"Optimize a control problem using Krotov's method.\n\n```julia\nresult = optimize_krotov(problem)\n```\n\noptimizes the given\ncontrol [`problem`](@ref QuantumControlBase.ControlProblem),\nreturning a [`KrotovResult`](@ref).\n\n!!! note\n\n It is recommended to call [`optimize`](@ref QuantumControlBase.optimize)\n with `method=:krotov` instead of calling `optimize_krotov` directly.\n\nKeyword arguments that control the optimization are taken from the keyword\narguments used in the instantiation of `problem`.\n\n# Required problem keyword arguments\n\n* `J_T`: A function `J_T(ϕ, objectives)` that evaluates the final time\n functional from a list `ϕ` of forward-propagated states and\n `problem.objectives`.\n\n# Optional problem keyword arguments\n\nThe following keyword arguments are supported (with default values):\n\n* `chi`: A function `chi!(χ, ϕ, objectives)` what receives a list `ϕ`\n of the forward propagates state and must set ``-χₖ=∂J_T/∂⟨ϕₖ|``. If not\n given, it will be automatically determined from `J_T` via [`make_chi`](@ref)\n* `force_zygote=false`: Whether to force the use of automatic differentiation\n when calling [`make_chi`](@ref).\n* `sigma=nothing`: Function that calculate the second-order contribution. If\n not given, the first-order Krotov method is used.\n* `iter_start=0`: the initial iteration number\n* `iter_stop=5000`: the maximum iteration number\n* `prop_method`/`fw_prop_method`/`bw_prop_method`: The propagation method to\n use for each objective, see below.\n* `update_hook`: A function that receives the Krotov workspace, the iteration\n number, the list of updated pulses and the list of guess pulses as\n positional arguments. The function may mutate any of its arguments. This may\n be used e.g. to apply a spectral filter to the updated pulses, or to update\n propagation workspaces inside the Krotov workspace.\n* `info_hook`: A function that receives the same argumens as `update_hook`, in\n order to write information about the current iteration to the screen or to a\n file. The default `info_hook` prints a table with convergence information to\n the screen. Runs after `update_hook`. The `info_hook` function may return a\n tuple, which is stored in the list of `records` inside the\n [`KrotovResult`](@ref) object.\n* `check_convergence`: a function to check whether convergence has been\n reached. Receives a [`KrotovResult`](@ref) object `result`, and should set\n `result.converged` to `true` and `result.message` to an appropriate string in\n case of convergence. Multiple convergence checks can be performed by chaining\n functions with `∘`. The convergence check is performed after any calls to\n `update_hook` and `info_hook`.\n* `verbose=false`: If `true`, print information during initialization\n\nThe propagation method for the forward propagation of each objective is\ndetermined by the first available item of the following:\n\n* a `fw_prop_method` keyword argument\n* a `prop_method` keyword argument\n* a property `fw_prop_method` of the objective\n* a property `prop_method` of the objective\n* the value `:auto`\n\nThe propagation method for the backword propagation is determined similarly,\nbut with `bw_prop_method` instead of `fw_prop_method`.\n\"\"\"\nfunction optimize_krotov(problem)\n sigma = get(problem.kwargs, :sigma, nothing)\n iter_start = get(problem.kwargs, :iter_start, 0)\n update_hook! = get(problem.kwargs, :update_hook, (args...) -> nothing)\n info_hook = get(problem.kwargs, :info_hook, print_table)\n check_convergence! = get(problem.kwargs, :check_convergence, res -> res)\n # note: the default `check_convergence!` is a no-op. We still always check\n # for \"Reached maximum number of iterations\" in `update_result!`\n verbose = get(problem.kwargs, :verbose, false)\n skip_initial_forward_propagation =\n get(problem.kwargs, :skip_initial_forward_propagation, false)\n\n wrk = KrotovWrk(problem; verbose)\n\n ϵ⁽ⁱ⁾ = wrk.pulses0\n ϵ⁽ⁱ⁺¹⁾ = wrk.pulses1\n\n if skip_initial_forward_propagation\n @info \"Skipping initial forward propagation\"\n else\n @threadsif wrk.use_threads for (k, obj) in collect(enumerate(wrk.objectives))\n krotov_initial_fw_prop!(ϵ⁽ⁱ⁾, wrk.result.states[k], obj.initial_state, k, wrk)\n end\n end\n\n # TODO: if sigma, fw_storage0 = fw_storage\n update_result!(wrk, 0)\n update_hook!(wrk, 0, ϵ⁽ⁱ⁺¹⁾, ϵ⁽ⁱ⁾)\n info_tuple = info_hook(wrk, 0, ϵ⁽ⁱ⁺¹⁾, ϵ⁽ⁱ⁾)\n (info_tuple !== nothing) && push!(wrk.records, info_tuple)\n\n i = wrk.result.iter # = 0, unless continuing from previous optimization\n while !wrk.result.converged\n i = i + 1\n krotov_iteration(wrk, ϵ⁽ⁱ⁾, ϵ⁽ⁱ⁺¹⁾)\n update_result!(wrk, i)\n update_hook!(wrk, i, ϵ⁽ⁱ⁺¹⁾, ϵ⁽ⁱ⁾)\n info_tuple = info_hook(wrk, i, ϵ⁽ⁱ⁺¹⁾, ϵ⁽ⁱ⁾)\n (info_tuple !== nothing) && push!(wrk.records, info_tuple)\n check_convergence!(wrk.result)\n ϵ⁽ⁱ⁾, ϵ⁽ⁱ⁺¹⁾ = ϵ⁽ⁱ⁺¹⁾, ϵ⁽ⁱ⁾\n end\n\n finalize_result!(ϵ⁽ⁱ⁾, wrk)\n\n return wrk.result\n\nend\n\n\nfunction krotov_initial_fw_prop!(ϵ⁽⁰⁾, ϕₖ, ϕₖⁱⁿ, k, wrk)\n Φ₀ = wrk.fw_storage[k]\n copyto!(ϕₖ, ϕₖⁱⁿ)\n (Φ₀ !== nothing) && write_to_storage!(Φ₀, 1, ϕₖⁱⁿ)\n N_T = length(wrk.result.tlist) - 1\n for n = 1:N_T\n G, dt = _fw_gen(ϵ⁽⁰⁾, k, n, wrk)\n propstep!(ϕₖ, G, dt, wrk.fw_prop_wrk[k])\n (Φ₀ !== nothing) && write_to_storage!(Φ₀, n + 1, ϕₖ)\n end\n # TODO: allow a custom propstep! routine\nend\n\n\nfunction krotov_iteration(wrk, ϵ⁽ⁱ⁾, ϵ⁽ⁱ⁺¹⁾)\n\n ϕ = wrk.result.states # assumed to contain the results of forward propagation\n χ = wrk.bw_states\n J_T_func = wrk.kwargs[:J_T]\n force_zygote = get(wrk.kwargs, :get_zygote, false)\n chi! = get(wrk.kwargs, :chi, make_chi(J_T_func, wrk.objectives; force_zygote))\n N_T = length(wrk.result.tlist) - 1\n N = length(wrk.objectives)\n L = length(wrk.controls)\n X = wrk.bw_storage\n Φ = wrk.fw_storage # TODO: pass in Φ₁, Φ₀ as parameters\n ∫gₐdt = wrk.g_a_int\n Im = imag\n\n # backward propagation\n chi!(χ, ϕ, wrk.objectives)\n @threadsif wrk.use_threads for k = 1:N\n write_to_storage!(X[k], N_T + 1, χ[k])\n for n = N_T:-1:1\n local (G, dt) = _bw_gen(ϵ⁽ⁱ⁾, k, n, wrk)\n propstep!(χ[k], G, dt, wrk.bw_prop_wrk[k])\n write_to_storage!(X[k], n, χ[k])\n end\n end\n\n # pulse update and forward propagation\n\n @threadsif wrk.use_threads for k = 1:N\n copyto!(ϕ[k], wrk.objectives[k].initial_state)\n end\n\n ∫gₐdt .= 0.0\n for n = 1:N_T # `n` is the index for the time interval\n dt = wrk.result.tlist[n+1] - wrk.result.tlist[n]\n for k = 1:N\n get_from_storage!(χ[k], X[k], n)\n end\n ϵₙ⁽ⁱ⁺¹⁾ = [ϵ⁽ⁱ⁾[l][n] for l ∈ 1:L] # ϵₙ⁽ⁱ⁺¹⁾ ≈ ϵₙ⁽ⁱ⁾ for non-linear controls\n # TODO: we could add a self-consistent loop here for ϵₙ⁽ⁱ⁺¹⁾\n Δuₙ′ = zeros(L) # for step size 1\n for l = 1:L # `l` is the index for the different controls\n ∂ϵₗ╱∂u::Function = wrk.parametrization[l].de_du_derivative\n uₗ = wrk.parametrization[l].u_of_epsilon\n for k = 1:N # k is the index over the objectives\n ∂Hₖ╱∂ϵₗ::Union{Function,Nothing} = wrk.control_derivs[k][l]\n if !isnothing(∂Hₖ╱∂ϵₗ)\n μₗₖₙ = (∂Hₖ╱∂ϵₗ)(ϵₙ⁽ⁱ⁺¹⁾[l])\n if wrk.is_parametrized[l]\n ∂ϵₗ╱∂uₗ = (∂ϵₗ╱∂u)(uₗ(ϵₙ⁽ⁱ⁺¹⁾[l]))\n Δuₙ′[l] += ∂ϵₗ╱∂uₗ * Im(dot(χ[k], μₗₖₙ, ϕ[k]))\n else\n Δuₙ′[l] += Im(dot(χ[k], μₗₖₙ, ϕ[k]))\n end\n end\n end\n end\n # TODO: second order update\n for l = 1:L\n Sₗ = wrk.update_shapes[l]\n λₐ = wrk.lambda_vals[l]\n αₗ = (Sₗ[n] / λₐ) # Krotov step size\n Δuₗₙ = αₗ * Δuₙ′[l]\n if wrk.is_parametrized[l]\n uₗ = wrk.parametrization[l].u_of_epsilon\n ϵₗ = wrk.parametrization[l].epsilon_of_u\n ϵ⁽ⁱ⁺¹⁾[l][n] = ϵₗ(uₗ(ϵ⁽ⁱ⁾[l][n]) + Δuₗₙ)\n else\n Δϵₗₙ = Δuₗₙ\n ϵ⁽ⁱ⁺¹⁾[l][n] = ϵ⁽ⁱ⁾[l][n] + Δϵₗₙ\n end\n (∫gₐdt)[l] += αₗ * abs(Δuₙ′[l])^2 * dt\n end\n # TODO: end of self-consistent loop\n @threadsif wrk.use_threads for k = 1:N\n local (G, dt) = _fw_gen(ϵ⁽ⁱ⁺¹⁾, k, n, wrk)\n propstep!(ϕ[k], G, dt, wrk.fw_prop_wrk[k])\n write_to_storage!(Φ[k], n, ϕ[k])\n end\n # TODO: update sigma\n end # time loop\nend\n\n\n# The dynamical generator for the forward propagation\nfunction _fw_gen(ϵ, k, n, wrk)\n vals_dict = wrk.vals_dict[k]\n t = wrk.result.tlist\n for (l, control) in enumerate(wrk.controls)\n vals_dict[control] = ϵ[l][n]\n end\n dt = t[n+1] - t[n]\n evalcontrols!(wrk.G[k], wrk.objectives[k].generator, vals_dict)\n return wrk.G[k], dt\nend\n\n\n# The dynamical generator for the backward propagation\nfunction _bw_gen(ϵ, k, n, wrk)\n vals_dict = wrk.vals_dict[k]\n t = wrk.result.tlist\n for (l, control) in enumerate(wrk.controls)\n vals_dict[control] = ϵ[l][n]\n end\n dt = t[n+1] - t[n]\n evalcontrols!(wrk.G[k], wrk.adjoint_objectives[k].generator, vals_dict)\n return wrk.G[k], -dt\nend\n\n\nfunction update_result!(wrk::KrotovWrk, i::Int64)\n res = wrk.result\n J_T_func = wrk.kwargs[:J_T]\n res.J_T_prev = res.J_T\n res.J_T = J_T_func(res.states, wrk.objectives)\n (i > 0) && (res.iter = i)\n if i >= res.iter_stop\n res.converged = true\n res.message = \"Reached maximum number of iterations\"\n # Note: other convergence checks are done in user-supplied\n # check_convergence routine\n end\n prev_time = res.end_local_time\n res.end_local_time = now()\n res.secs = Dates.toms(res.end_local_time - prev_time) / 1000.0\n # TODO: calculate τ values\nend\n\n\nfunction finalize_result!(ϵ_opt, wrk::KrotovWrk)\n res = wrk.result\n res.end_local_time = now()\n for l = 1:length(ϵ_opt)\n res.optimized_controls[l] = discretize(ϵ_opt[l], res.tlist)\n end\nend\n\n\n\"\"\"Print optimization progress as a table.\n\nThis functions serves as the default `info_hook` for an optimization with\nKrotov's method.\n\"\"\"\nfunction print_table(wrk, iteration, args...)\n J_T = wrk.result.J_T\n g_a_int = sum(wrk.g_a_int)\n J = J_T + g_a_int\n ΔJ_T = J_T - wrk.result.J_T_prev\n ΔJ = ΔJ_T + g_a_int\n secs = wrk.result.secs\n\n iter_stop = \"$(get(wrk.kwargs, :iter_stop, 5000))\"\n widths = [max(length(\"$iter_stop\"), 6), 11, 11, 11, 11, 11, 8]\n\n if iteration == 0\n header = [\"iter.\", \"J_T\", \"∫gₐ(t)dt\", \"J\", \"ΔJ_T\", \"ΔJ\", \"secs\"]\n for (header, w) in zip(header, widths)\n print(lpad(header, w))\n end\n print(\"\\n\")\n end\n\n strs = (\n \"$iteration\",\n @sprintf(\"%.2e\", J_T),\n @sprintf(\"%.2e\", g_a_int),\n @sprintf(\"%.2e\", J),\n (iteration > 0) ? @sprintf(\"%.2e\", ΔJ_T) : \"n/a\",\n (iteration > 0) ? @sprintf(\"%.2e\", ΔJ) : \"n/a\",\n @sprintf(\"%.1f\", secs),\n )\n for (str, w) in zip(strs, widths)\n print(lpad(str, w))\n end\n print(\"\\n\")\n flush(stdout)\nend\n", "meta": {"hexsha": "9204cb3b66682f492ac7202c91aaee72469791a8", "size": 11414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimize.jl", "max_stars_repo_name": "JuliaQuantumControl/Krotov.jl", "max_stars_repo_head_hexsha": "6eab22b1d2e084210ecaf7fe32fcf28a2183be83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-13T03:01:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:52:11.000Z", "max_issues_repo_path": "src/optimize.jl", "max_issues_repo_name": "JuliaQuantumControl/Krotov.jl", "max_issues_repo_head_hexsha": "6eab22b1d2e084210ecaf7fe32fcf28a2183be83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-10-02T04:17:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T01:52:40.000Z", "max_forks_repo_path": "src/optimize.jl", "max_forks_repo_name": "JuliaQuantumControl/Krotov.jl", "max_forks_repo_head_hexsha": "6eab22b1d2e084210ecaf7fe32fcf28a2183be83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-10T00:52:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:52:12.000Z", "avg_line_length": 35.66875, "max_line_length": 92, "alphanum_fraction": 0.6336954617, "num_tokens": 3779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17896253574164256}} {"text": "\n\"\"\"\n`module JAC.AtomicState` \n ... a submodel of JAC that contains all methods to set-up and process atomic representations.\n\"\"\"\nmodule AtomicState\n\n ## using Interact\n using ..Basics, ..Radial, ..ManyElectron, ..Nuclear\n\n export MeanFieldSettings, MeanFieldBasis, CiSettings, CiExpansion, RasSettings, RasStep, RasExpansion, \n GreenSettings, GreenChannel, GreenExpansion, Representation\n\n \n \"\"\"\n `abstract type AtomicState.AbstractRepresentationType` \n ... defines an abstract type and a number of data types to work with and distinguish different atomic representations; see also:\n \n + struct MeanFieldBasis ... to represent (and generate) a mean-field basis and, especially, a set of (mean-field) orbitals.\n + struct CiExpansion ... to represent (and generate) a configuration-interaction representation.\n + struct RasExpansion ... to represent (and generate) a restricted active-space representation.\n + struct GreenFunction ... to represent (and generate) an approximate (many-electron) Green functions.\n \"\"\"\n abstract type AbstractRepresentationType end\n\n \n \"\"\"\n `struct AtomicState.MeanFieldSettings` \n ... a struct for defining the settings for a mean-field basis (orbital) representation.\n\n + scField ::AbstractScField \n ... Specify the (mean) self-consistent field as DFSField() or HSField(); note that not all AbstractScField's \n allowed here.\n \"\"\"\n struct MeanFieldSettings\n scField ::AbstractScField\n end\n\n \"\"\"\n `AtomicState.MeanFieldSettings()` ... constructor for setting the default values.\n \"\"\"\n function MeanFieldSettings()\n \tMeanFieldSettings(DFSField())\n end\n \n \n # `Base.show(io::IO, settings::MeanFieldSettings)` ... prepares a proper printout of the settings::MeanFieldSettings.\n function Base.show(io::IO, settings::MeanFieldSettings)\n \t println(io, \"scField: $(settings.scField) \")\n end\n\n\n \"\"\"\n `struct AtomicState.MeanFieldBasis <: AbstractRepresentationType` \n ... a struct to represent (and generate) a mean-field orbital basis.\n\n + settings ::AtomicState.MeanFieldSettings ... Settings for the given mean-field orbital basis\n \"\"\"\n struct MeanFieldBasis <: AbstractRepresentationType\n settings ::AtomicState.MeanFieldSettings\n end\n\n\n # `Base.string(basis::MeanFieldBasis)` ... provides a String notation for the variable basis::MeanFieldBasi.\n function Base.string(basis::MeanFieldBasis)\n if !(basis.settings.scField in [DFSField(), HSField()])\n error(\"A MeanFieldBasis presently supports only a DFSField() or HSField() but received: $(basis.settings.scField)\")\n end\n #\n sa = \"Mean-field orbital basis for a $(basis.settings.scField) SCF field:\"\n return( sa )\n end\n\n\n # `Base.show(io::IO, basis::MeanFieldBasis)` ... prepares a proper printout of the basis::MeanFieldBasis.\n function Base.show(io::IO, basis::MeanFieldBasis)\n sa = Base.string(basis); print(io, sa, \"\\n\")\n end\n\n \n \n ### RAS: Restricted-Active-Space expansions ##################################################################################\n \"\"\"\n `struct AtomicState.RasSettings` \n ... a struct for defining the settings for a restricted active-space computations.\n\n + levelsScf ::Array{Int64,1} ... Levels on which the optimization need to be carried out.\n + maxIterationsScf ::Int64 ... maximum number of SCF iterations in each RAS step.\n + accuracyScf ::Float64 ... convergence criterion for the SCF field.\n \n \t+ eeInteractionCI ::AbstractEeInteraction ... logical flag to include Breit interactions.\n + levelSelectionCI ::LevelSelection ... Specifies the selected levels, if any.\n \"\"\"\n struct RasSettings\n levelsScf ::Array{Int64,1}\n maxIterationsScf ::Int64 \n accuracyScf ::Float64 \n \teeInteractionCI ::AbstractEeInteraction \n \tlevelSelectionCI ::LevelSelection\n end\n\n \"\"\"\n `AtomicState.RasSettings()` ... constructor for setting the default values.\n \"\"\"\n function RasSettings()\n \tRasSettings(Int64[1], 24, 1.0e-6, false, LevelSelection() )\n end\n \n \n # `Base.show(io::IO, settings::RasSettings)` ... prepares a proper printout of the settings::RasSettings.\n function Base.show(io::IO, settings::RasSettings)\n \t println(io, \"levelsScf: $(settings.levelsScf) \")\n \t println(io, \"maxIterationsScf: $(settings.maxIterationsScf) \")\n \t println(io, \"accuracyScf: $(settings.accuracyScf) \")\n \t println(io, \"eeInteractionCI: $(settings.eeInteractionCI) \")\n \t println(io, \"levelSelectionCI: $(settings.levelSelectionCI) \")\n end\n\n\n \"\"\"\n `struct AtomicState.RasStep` \n ... specifies an individual step of a (relativistic) restricted active space computation for a set of levels. This struct \n comprises all information to generate the orbital basis and to perform the associated SCF and multiplet computations for a \n selected number of levels.\n\n + seFrom ::Array{Shell,1} ... Single-excitations from shells [sh_1, sh_2, ...]\n + seTo ::Array{Shell,1} ... Single-excitations to shells [sh_1, sh_2, ...]\n + deFrom ::Array{Shell,1} ... Double-excitations from shells [sh_1, sh_2, ...]\n + deTo ::Array{Shell,1} ... Double-excitations to shells [sh_1, sh_2, ...]\n + teFrom ::Array{Shell,1} ... Triple-excitations from shells [sh_1, sh_2, ...]\n + teTo ::Array{Shell,1} ... Triple-excitations to shells [sh_1, sh_2, ...]\n + qeFrom ::Array{Shell,1} ... Quadrupole-excitations from shells [sh_1, sh_2, ...]\n + qeTo ::Array{Shell,1} ... Quadrupole-excitations to shells [sh_1, sh_2, ...]\n + frozenShells ::Array{Shell,1} ... List of shells that are kept 'frozen' in this step.\n + constraints ::Array{String,1} ... List of Strings to define 'constraints/restrictions' to the generated CSF basis.\n \"\"\"\n struct RasStep\n seFrom ::Array{Shell,1}\n seTo ::Array{Shell,1}\n deFrom ::Array{Shell,1}\n deTo ::Array{Shell,1}\n teFrom ::Array{Shell,1}\n teTo ::Array{Shell,1}\n qeFrom ::Array{Shell,1}\n qeTo ::Array{Shell,1}\n frozenShells ::Array{Shell,1}\n constraints ::Array{String,1}\n end\n\n \"\"\"\n `AtomicState.RasStep()` ... constructor for an 'empty' instance of a variable::AtomicState.RasStep\n \"\"\"\n function RasStep()\n RasStep(Shell[], Shell[], Shell[], Shell[], Shell[], Shell[], Shell[], Shell[], Shell[], String[])\n end\n\n\n \"\"\"\n `AtomicState.RasStep(rasStep::AtomicState.RasStep;`\n \n seFrom::Array{Shell,1}=Shell[], seTo::Array{Shell,1}=Shell[], \n deFrom::Array{Shell,1}=Shell[], deTo::Array{Shell,1}=Shell[], \n teFrom::Array{Shell,1}=Shell[], teTo::Array{Shell,1}=Shell[], \n qeFrom::Array{Shell,1}=Shell[], qeTo::Array{Shell,1}=Shell[], \n frozen::Array{Shell,1}=Shell[], constraints::Array{String,1}=String[] \n \n ... constructor for modifying the given rasStep by specifying all excitations, frozen shells and constraints optionally.\n \"\"\"\n function RasStep(rasStep::AtomicState.RasStep;\n seFrom::Array{Shell,1}=Shell[], seTo::Array{Shell,1}=Shell[], \n deFrom::Array{Shell,1}=Shell[], deTo::Array{Shell,1}=Shell[], \n teFrom::Array{Shell,1}=Shell[], teTo::Array{Shell,1}=Shell[], \n qeFrom::Array{Shell,1}=Shell[], qeTo::Array{Shell,1}=Shell[], \n frozen::Array{Shell,1}=Shell[], constraints::Array{String,1}=String[])\n if seFrom == Shell[] sxFrom = rasStep.seFrom else sxFrom = seFrom end\n if seTo == Shell[] sxTo = rasStep.seTo else sxTo = seTo end\n if deFrom == Shell[] dxFrom = rasStep.deFrom else dxFrom = deFrom end\n if deTo == Shell[] dxTo = rasStep.deTo else dxTo = deTo end\n if teFrom == Shell[] txFrom = rasStep.teFrom else txFrom = teFrom end\n if teTo == Shell[] txTo = rasStep.teTo else txTo = teTo end\n if qeFrom == Shell[] qxFrom = rasStep.qeFrom else qxFrom = qeFrom end\n if qeTo == Shell[] qxTo = rasStep.qeTo else qxTo = qeTo end\n if frozen == Shell[] frozx = rasStep.frozenShells else frozx = frozen end\n if constraints ==String[] consx = rasStep.constraints else consx = constraints end\n \n RasStep( sxFrom, sxTo, dxFrom, dxTo, txFrom, txTo, qxFrom, qxTo, frozx, consx)\n end\n\n\n # `Base.string(step::AtomicState.RasStep)` ... provides a String notation for the variable step::AtomicState.RasStep.\n function Base.string(step::AtomicState.RasStep)\n sa = \"\\nCI or RAS step with $(length(step.frozenShells)) (explicitly) frozen shell(s): $(step.frozenShells) ... and virtual excitations\"\n return( sa )\n end\n\n\n # `Base.show(io::IO, step::AtomicState.RasStep)` ... prepares a proper printout of the (individual step of computations) step::AtomicState.RasStep.\n function Base.show(io::IO, step::AtomicState.RasStep)\n sa = Base.string(step); print(io, sa, \"\\n\")\n if length(step.seFrom) > 0\n sa = \" Singles from: { \"; for sh in step.seFrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.seTo sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n if length(step.deFrom) > 0\n sa = \" Doubles from: { \"; for sh in step.deFrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.deTo sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n if length(step.teFrom) > 0\n sa = \" Triples from: { \"; for sh in step.teFrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.teTo sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n if length(step.qeFrom) > 0\n sa = \" Quadruples from: { \"; for sh in step.qeFrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.qeTo sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n end\n \n \n \"\"\"\n `struct AtomicState.RasExpansion <: AbstractRepresentationType` \n ... a struct to represent (and generate) a restricted active-space representation.\n\n + symmetry ::LevelSymmetry ... Symmetry of the levels/CSF in the many-electron basis.\n + NoElectrons ::Int64 ... Number of electrons.\n + steps ::Array{AtomicState.RasStep,1} ... List of SCF steps that are to be done in this model computation.\n + settings ::AtomicState.RasSettings ... Settings for the given RAS computation\n \"\"\"\n struct RasExpansion <: AbstractRepresentationType\n symmetry ::LevelSymmetry\n NoElectrons ::Int64\n steps ::Array{AtomicState.RasStep,1}\n settings ::AtomicState.RasSettings \n end\n\n\n \"\"\"\n `AtomicState.RasExpansion()` ... constructor for an 'empty' instance of the a variable::AtomicState.RasExpansion\n \"\"\"\n function RasExpansion()\n RasExpansion(Basics.LevelSymmetry(0, Basics.plus), 0, 0, AtomicState.RasStep[], AtomicState.RasSettings())\n end\n\n\n # `Base.string(expansion::RasExpansion)` ... provides a String notation for the variable expansion::RasExpansion.\n function Base.string(expansion::RasExpansion)\n sa = \"RAS expansion for symmétry $(expansion.symmetry) and with $(length(expansion.steps)) steps:\"\n return( sa )\n end\n\n\n # `Base.show(io::IO, expansion::RasExpansion)` ... prepares a proper printout of the (individual step of computations) expansion::RasExpansion.\n function Base.show(io::IO, expansion::RasExpansion)\n sa = Base.string(expansion); print(io, sa, \"\\n\")\n println(io, \"$(expansion.steps) \")\n println(io, \"... and the current settings:\")\n println(io, \"$(expansion.settings) \")\n end\n\n \n \n ### CI: Configuration Interaction expansions ##################################################################################\n \"\"\"\n `struct AtomicState.CiSettings` \n ... a struct for defining the settings for a configuration-interaction (CI) expansion.\n\n \t+ eeInteractionCI ::AbstractEeInteraction ... logical flag to include Breit interactions.\n + levelSelectionCI ::LevelSelection ... Specifies the selected levels, if any.\n \"\"\"\n struct CiSettings\n \teeInteractionCI ::AbstractEeInteraction \n \tlevelSelectionCI ::LevelSelection\n end\n\n \"\"\"\n `AtomicState.CiSettings()` ... constructor for setting the default values.\n \"\"\"\n function CiSettings()\n \tCiSettings(CoulombInteraction(), LevelSelection() )\n end\n\n\n \"\"\"\n `AtomicState.CiSettings(settings::AtomicState.CiSettings;`\n \n eeInteractionCI::Union{Nothing,AbstractEeInteraction}=nothing, levelSelectionCI::Union{Nothing,LevelSelection}=nothing)\n \n ... constructor for modifying the given CiSettings by 'overwriting' the explicitly selected parameters.\n \"\"\"\n function CiSettings(settings::AtomicState.CiSettings;\n eeInteractionCI::Union{Nothing,AbstractEeInteraction}=nothing, levelSelectionCI::Union{Nothing,LevelSelection}=nothing)\n \n if eeInteractionCI == nothing eeInteractionCIx = settings.eeInteractionCI else eeInteractionCIx = eeInteractionCI end \n if levelSelectionCI == nothing levelSelectionCIx = settings.levelSelectionCI else levelSelectionCIx = levelSelectionCI end \n \n CiSettings( eeInteractionCIx, levelSelectionCIx)\n end\n \n \n # `Base.show(io::IO, settings::CiSettings)` ... prepares a proper printout of the settings::CiSettings.\n function Base.show(io::IO, settings::CiSettings)\n \t println(io, \"eeInteractionCI: $(settings.eeInteractionCI) \")\n \t println(io, \"levelSelectionCI: $(settings.levelSelectionCI) \")\n end\n\n\n \"\"\"\n `struct AtomicState.CiExpansion <: AbstractRepresentationType` \n ... a struct to represent (and generate) a configuration-interaction representation.\n\n + applyOrbitals ::Dict{Subshell, Orbital}\n + excitations ::AtomicState.RasStep ... Excitations beyond refConfigs.\n + settings ::AtomicState.CiSettings ... Settings for the given CI expansion\n \"\"\"\n struct CiExpansion <: AbstractRepresentationType\n applyOrbitals ::Dict{Subshell, Orbital}\n excitations ::AtomicState.RasStep\n settings ::AtomicState.CiSettings\n end\n\n\n # `Base.string(expansion::CiExpansion)` ... provides a String notation for the variable expansion::CiExpansion.\n function Base.string(expansion::CiExpansion)\n sa = \"CI expansion with (additional) excitations:\"\n return( sa )\n end\n\n\n # `Base.show(io::IO, expansion::CiExpansion)` ... prepares a proper printout of the (individual step of computations) expansion::CiExpansion.\n function Base.show(io::IO, expansion::CiExpansion)\n sa = Base.string(expansion); print(io, sa, \"\\n\")\n println(io, \"$(expansion.excitations) \")\n println(io, \"... and the current settings:\")\n println(io, \"$(expansion.settings) \")\n end\n\n\n \n ### Green function representation ##################################################################################\n\n \"\"\"\n `abstract type AtomicState.AbstractGreenApproach` \n ... defines an abstract and a number of singleton types for approximating a many-electron Green\n function expansion for calculating second-order processes.\n\n + struct SingleCSFwithoutCI \n ... to approximate the many-electron multiplets (gMultiplet) for every chosen level symmetry by dealing with each CSF \n independently, and without any configuration interaction. This is a fast but also very rough approximation.\n \n + struct CoreSpaceCI \n ... to approximate the many-electron multiplets (gMultiplet) by taking the electron-electron interaction between the \n bound-state orbitals into account.\n \n + struct DampedSpaceCI \n ... to approximate the many-electron multiplets (gMultiplet) by taking the electron-electron interaction for all, the \n bound and free-electron, orbitals into account but by including a damping factor e^{tau*r}, tau > 0 into the \n electron densities rho_ab (r) --> rho_ab (r) * e^{tau*r}\n \"\"\"\n abstract type AbstractGreenApproach end\n struct SingleCSFwithoutCI <: AtomicState.AbstractGreenApproach end\n struct CoreSpaceCI <: AtomicState.AbstractGreenApproach end\n struct DampedSpaceCI <: AtomicState.AbstractGreenApproach end\n\n \n \"\"\"\n `struct AtomicState.GreenSettings` \n ... defines a type for defining the details and parameters of the approximate Green (function) expansion.\n\n + nMax ::Int64 ... maximum principal quantum numbers of (single-electron) \n excitations that are to be included into the representation.\n + lValues ::Array{Int64,1} ... List of (non-relativistic) orbital angular momenta for which\n (single-electron) excitations are to be included.\n + dampingTau ::Float64 ... factor tau (> 0.) that is used to 'damp' the one- and two-electron\n interactions strength: exp( - tau * r)\n + printBefore ::Bool ... True if a short overview is to be printed before. \n + levelSelection ::LevelSelection ... Specifies the selected levels, if any.\n \"\"\"\n struct GreenSettings \n nMax ::Int64\n lValues ::Array{Int64,1}\n dampingTau ::Float64\n printBefore ::Bool \n levelSelection ::LevelSelection\n end \n\n\n \"\"\"\n `AtomicState.GreenSettings()` ... constructor for an `empty` instance of AtomicState.GreenSettings.\n \"\"\"\n function GreenSettings()\n Settings( 0, Int64[], 0., false, LevelSelection() )\n end\n\n\n # `Base.show(io::IO, settings::AtomicState.GreenSettings)` ... prepares a proper printout of the variable settings::AtomicState.GreenSettings.\n function Base.show(io::IO, settings::AtomicState.GreenSettings) \n println(io, \"nMax: $(settings.nMax) \")\n println(io, \"lValues: $(settings.lValues) \")\n println(io, \"dampingTau: $(settings.dampingTau) \")\n println(io, \"printBefore: $(settings.printBefore) \")\n println(io, \"levelSelection: $(settings.levelSelection) \")\n end\n\n\n \"\"\"\n `struct AtomicState.GreenChannel` \n ... defines a type for a single symmetry channel of an (approximate) Green (function) expansion.\n\n + symmetry ::LevelSymmetry ... Level symmetry of this part of the representation.\n + gMultiplet ::Multiplet ... Multiplet of (scattering) levels of this symmetry.\n \"\"\"\n struct GreenChannel \n symmetry ::LevelSymmetry\n gMultiplet ::Multiplet\n end \n\n\n \"\"\"\n `AtomicState.GreenChannel()` ... constructor for an `empty` instance of AtomicState.GreenChannel.\n \"\"\"\n function GreenChannel()\n GreenChannel( LevelSymmetry(0, Basics.plus), ManyElectron.Multiplet)\n end\n\n\n # `Base.show(io::IO, channel::AtomicState.GreenChannel)` ... prepares a proper printout of the variable channel::AtomicState.GreenChannel.\n function Base.show(io::IO, channel::AtomicState.GreenChannel) \n println(io, \"symmetry: $(channel.symmetry) \")\n println(io, \"gMultiplet: $(channel.gMultiplet) \")\n end\n\n\n \"\"\"\n `struct AtomicState.GreenExpansion <: AbstractRepresentationType` \n ... defines a type to keep an (approximate) Green (function) expansion that is associated with a given set of reference\n configurations.\n\n + approach ::AtomicState.AbstractGreenApproach ... Approach used to approximate the representation.\n + excitationScheme ::Basics.AbstractExcitationScheme ... Applied excitation scheme w.r.t. refConfigs. \n + levelSymmetries ::Array{LevelSymmetry,1} ... Total symmetries J^P to be included into Green expansion.\n + NoElectrons ::Int64 ... Number of electrons.\n + settings ::AtomicState.GreenSettings ... settings for the Green (function) expansion.\n \"\"\"\n struct GreenExpansion <: AbstractRepresentationType\n approach ::AtomicState.AbstractGreenApproach\n excitationScheme ::Basics.AbstractExcitationScheme \n levelSymmetries ::Array{LevelSymmetry,1}\n NoElectrons ::Int64 \n settings ::AtomicState.GreenSettings\n end \n\n\n \"\"\"\n `AtomicState.GreenExpansion()` ... constructor for an `empty` instance of AtomicState.GreenExpansion.\n \"\"\"\n function GreenExpansion()\n GreenExpansion( AtomicState.SingleCSFwithoutCI(), Basics.NoExcitationScheme(), LevelSymmetry[], 0, AtomicState.GreenSettings())\n end\n\n\n # `Base.string(expansion::GreenExpansion)` ... provides a String notation for the variable expansion::GreenExpansion.\n function Base.string(expansion::GreenExpansion)\n sa = \"Green (function) expansion in $(expansion.approach) approach and for excitation scheme $(expansion.excitationScheme),\" *\n \"\\nincluding (Green function channels with) symmetries $(expansion.levelSymmetries):\"\n return( sa )\n end\n\n\n # `Base.show(io::IO, expansion::GreenExpansion)` ... prepares a proper printout of the (individual step of computations) expansion::GreenExpansion.\n function Base.show(io::IO, expansion::GreenExpansion)\n sa = Base.string(expansion); print(io, sa, \"\\n\")\n println(io, \"... and the current settings:\")\n println(io, \"$(expansion.settings) \")\n end\n\n\n\n ### Representation ##################################################################################\n \"\"\"\n `struct AtomicState.Representation` \n ... a struct for defining an atomic state representation. Such representations often refer to approximate wave function approximations of\n one or several levels but may concern also a mean-field basis (for some multiplet of some given configurations) or Green functions,\n etc.\n\n + name ::String ... to assign a name to the given model.\n + nuclearModel ::Nuclear.Model ... Model, charge and parameters of the nucleus.\n + grid ::Radial.Grid ... The radial grid to be used for the computation.\n + refConfigs ::Array{Configuration,1} ... List of references configurations, at least 1.\n + repType ::AbstractRepresentationType ... Specifies the particular representation.\n \"\"\"\n struct Representation\n name ::String \n nuclearModel ::Nuclear.Model\n grid ::Radial.Grid\n refConfigs ::Array{Configuration,1} \n repType ::AbstractRepresentationType\n end\n\n\n \"\"\"\n `AtomicState.Representation()` ... constructor for an 'empty' instance of the a variable::AtomicState.Representation\n \"\"\"\n function Representation()\n Representation(\"\", Nuclear.Model(1.0), Radial.Grid(), ManyElectron.Configuration[], CiExpansion())\n end\n\n \n \"\"\"\n `AtomicState.Representation( ... example for the generation of a mean-field basis)` \n \n name = \"Oxygen 1s^2 2s^2 2p^4 ground configuration\"\n grid = Radial.Grid(true)\n nuclearM = Nuclear.Model(8.)\n refConfigs = [Configuration(\"[He] 2s^2 2p^4\")]\n mfSettings = MeanFieldSettings()\n Representation(name, nuclearM, grid, refConfigs, MeanFieldBasis(mfSettings) )\n \n `AtomicState.Representation( ... example for the computation of a configuration-interaction (CI) expansion)` \n \n name = \"Oxygen 1s^2 2s^2 2p^4 ground configuration\"\n grid = Radial.Grid(true)\n nuclearM = Nuclear.Model(8.)\n refConfigs = [Configuration(\"[He] 2s^2 2p^4\")]\n orbitals = wb[\"mean-field basis\"].orbitals # get a proper set of orbitals\n ciSettings = CiSettings(true, false, Int64[], false, LevelSymmetry[] )\n from = [Shell(\"2s\")]\n to = [Shell(\"2s\"), Shell(\"2p\")]\n excitations = RasStep(RasStep(), seFrom=from, seTo=to, deFrom=from, deTo=to, frozen=[Shell(\"1s\")])\n Representation(name, nuclearM, grid, refConfigs, CiExpansion(orbitals, excitations, ciSettings) )\n \n `AtomicState.Representation( ... example for the computation of a restricted-active-space (RAS) expansion)` \n \n name = \"Beryllium 1s^2 2s^2 ^1S_0 ground state\"\n refConfigs = [Configuration(\"[He] 2s^2\")]\n rasSettings = RasSettings([1], 24, 1.0e-6, CoulombInteraction(), true, [1,2,3] )\n from = [Shell(\"2s\")]\n \n frozen = [Shell(\"1s\")]\n to = [Shell(\"2s\"), Shell(\"2p\")]\n step1 = RasStep(RasStep(), seFrom=from, seTo=deepcopy(to), deFrom=from, deTo=deepcopy(to), frozen=deepcopy(frozen))\n\n append!(frozen, [Shell(\"2s\"), Shell(\"2p\")])\n append!(to, [Shell(\"3s\"), Shell(\"3p\"), Shell(\"3d\")])\n step2 = RasStep(step1; seTo=deepcopy(to), deTo=deepcopy(to), frozen=deepcopy(frozen))\n\n append!(frozen, [Shell(\"3s\"), Shell(\"3p\"), Shell(\"3d\")])\n append!(to, [Shell(\"4s\"), Shell(\"4p\"), Shell(\"4d\"), Shell(\"4f\")])\n step3 = RasStep(step2, seTo=deepcopy(to), deTo=deepcopy(to), frozen=deepcopy(frozen))\n\n Representation(name, Nuclear.Model(4.), Radial.Grid(true), refConfigs, \n RasExpansion(LevelSymmetry(0, Basics.plus), 4, [step1, step2, step3], rasSettings) )\n \n `AtomicState.Representation( ... example for the computation of Green(function) expansion)` \n\n name = \"Lithium 1s^2 2s ground configuration\"\n refConfigs = [Configuration(\"[He] 2s\")]\n levelSymmetries = [LevelSymmetry(1//2, Basics.plus), LevelSymmetry(3//2, Basics.plus)]\n greenSettings = GreenSettings(5, [0, 1, 2], 0.01, true, false, Int64[])\n Representation(name, Nuclear.Model(8.), Radial.Grid(true), refConfigs, \n GreenExpansion( AtomicState.DampedSpaceCI(), Basics.DeExciteSingleElectron(), levelSymmetries, 3, greenSettings) ) \n \n ... These simple examples can be further improved by overwriting the corresponding parameters.\n \"\"\"\n function Representation(wa::Bool) \n AtomicState.Representation() \n end\n\n\n # `Base.string(rep::Representation)` ... provides a String notation for the variable rep::AtomicState.Representation\n function Base.string(rep::Representation)\n sa = \"Atomic representation: $(rep.name) for Z = $(rep.nuclearModel.Z) and with reference configurations: \\n \"\n for refConfig in rep.refConfigs sa = sa * string(refConfig) * \", \" end\n return( sa )\n end\n\n\n # `Base.show(io::IO, rep::Representation)` ... prepares a printout of rep::Representation.\n function Base.show(io::IO, rep::Representation)\n sa = Base.string(rep); print(io, sa, \"\\n\")\n println(io, \"representation type: $(rep.repType) \")\n println(io, \"nuclearModel: $(rep.nuclearModel) \")\n println(io, \"grid: $(rep.grid) \")\n end\n\nend # module\n", "meta": {"hexsha": "04f3485aed52adb299a1d1eb78adcf5308d59491", "size": 29850, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-AtomicState.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-AtomicState.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-AtomicState.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.6791171477, "max_line_length": 156, "alphanum_fraction": 0.5825125628, "num_tokens": 6984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.17788592751294857}} {"text": "module SrtmKgb25\n # KURUCZ\n sfluxref = [42.6858 , 45.7720, 44.9872, 45.9662 ,46.5458 , 41.6926, 32.2893, 24.0928 ,16.7686 , 1.86048, 1.54057, 1.23503 ,0.915085,0.590099,0.218622, 3.21287e-02]\n\n # Rayleigh extinction coefficient at v = 2925 cm-1.\n rayl = [9.81132e-07,8.25605e-07,6.71302e-07,5.53556e-07, \n 3.97383e-07,3.68206e-07,4.42379e-07,4.57799e-07,4.22683e-07,3.87113e-07,3.79810e-07,3.63192e-07,3.51921e-07,3.34231e-07,3.34294e-07,3.32673e-07]\n \n abso3a = [2.32664e-02,5.76154e-02,0.125389,0.250158,0.378756 ,0.402196 ,0.352026,0.352036,0.386253 ,0.414598 ,0.420079,0.435471,0.445487 ,0.459549 ,0.452920,0.456838]\n\n abso3b = [ \n 1.76917e-02,4.64185e-02,1.03640e-01,0.189469,0.303858 ,0.400248 ,0.447357 ,0.470009,0.498673 ,0.515696 ,0.517053 ,0.517930,0.518345 ,0.524952 ,0.508244 ,0.468981]\n\n layreffr = 2\n\n # ------------------------------------------------------------------\n\n # The array KA contains absorption coefs at the 16 chosen g-values \n # for a range of pressure levels> ~100mb:and binary:temperatures\n # species parameters (see taumol.f for definition). The first \n # index in the array, JS, runs from 1 to 9, and corresponds to \n # different values of the binary species parameter. For instance, \n # JS=1 refers to dry air, JS = 2 corresponds to the paramter value 1/8, \n # JS = 3 corresponds to the parameter value 2/8, etc. The second index\n # in the array, JT, which runs from 1 to 5, corresponds to different\n # temperatures. More specifically, JT = 3 means that the data are for\n # the reference temperature TREF for this pressure level:JT = 2 refers\n # to TREF-15, JT = 1 is for TREF-30:and JT = 5:JT = 4 is for TREF+15\n # is for TREF+30. The third index:runs from 1 to 13 and refers:JP\n # to the JPth reference pressure level (see taumol.f for these levels\n # in mb). The fourth index, IG, goes from 1 to 16, and indicates\n # which g-interval the absorption coefficients are for.\n # -----------------------------------------------------------------\n ka = zeros(5,13,16)\n ka[:, 1, 1] = [0.16461e-08,0.16782e-08,0.19339e-08,0.17100e-08,0.17045e-08]\n ka[:, 2, 1] = [0.28759e-08,0.29469e-08,0.33789e-08,0.34357e-08,0.28833e-08]\n ka[:, 3, 1] = [0.55148e-08,0.54808e-08,0.54190e-08,0.68260e-08,0.51972e-08]\n ka[:, 4, 1] = [0.95336e-08,0.94552e-08,0.93001e-08,0.90961e-08,0.14451e-07]\n ka[:, 5, 1] = [0.14930e-07,0.14736e-07,0.14432e-07,0.14074e-07,0.24102e-07]\n ka[:, 6, 1] = [0.22770e-07,0.22301e-07,0.21778e-07,0.21194e-07,0.20569e-07]\n ka[:, 7, 1] = [0.34699e-07,0.33951e-07,0.33124e-07,0.32144e-07,0.31220e-07]\n ka[:, 8, 1] = [0.62339e-07,0.60405e-07,0.59548e-07,0.58214e-07,0.56977e-07]\n ka[:, 9, 1] = [0.17411e-06,0.17654e-06,0.18315e-06,0.18100e-06,0.17839e-06]\n ka[:,10, 1] = [0.23526e-06,0.22729e-06,0.21947e-06,0.21188e-06,0.20454e-06]\n ka[:,11, 1] = [0.23535e-06,0.22737e-06,0.21956e-06,0.21196e-06,0.20461e-06]\n ka[:,12, 1] = [0.23539e-06,0.22740e-06,0.21959e-06,0.21199e-06,0.20465e-06]\n ka[:,13, 1] = [0.23543e-06,0.22744e-06,0.21962e-06,0.21202e-06,0.20467e-06]\n ka[:, 1, 2] = [0.62912e-08,0.61559e-08,0.84640e-08,0.59240e-08,0.58217e-08]\n ka[:, 2, 2] = [0.83749e-08,0.80756e-08,0.11623e-07,0.11272e-07,0.73636e-08]\n ka[:, 3, 2] = [0.13304e-07,0.12795e-07,0.12343e-07,0.21235e-07,0.11577e-07]\n ka[:, 4, 2] = [0.20704e-07,0.19736e-07,0.18900e-07,0.18228e-07,0.31601e-07]\n ka[:, 5, 2] = [0.31149e-07,0.29669e-07,0.28318e-07,0.27101e-07,0.49649e-07]\n ka[:, 6, 2] = [0.45713e-07,0.43519e-07,0.41488e-07,0.39918e-07,0.38291e-07]\n ka[:, 7, 2] = [0.77265e-07,0.73848e-07,0.70437e-07,0.67945e-07,0.66127e-07]\n ka[:, 8, 2] = [0.15754e-06,0.15664e-06,0.15378e-06,0.15027e-06,0.14633e-06]\n ka[:, 9, 2] = [0.16439e-06,0.14678e-06,0.12610e-06,0.11532e-06,0.10591e-06]\n ka[:,10, 2] = [0.14366e-06,0.13506e-06,0.12583e-06,0.11774e-06,0.11011e-06]\n ka[:,11, 2] = [0.14521e-06,0.13766e-06,0.13072e-06,0.12218e-06,0.11400e-06]\n ka[:,12, 2] = [0.14524e-06,0.13769e-06,0.13074e-06,0.12241e-06,0.11552e-06]\n ka[:,13, 2] = [0.14525e-06,0.13770e-06,0.13075e-06,0.12252e-06,0.11553e-06]\n ka[:, 1, 3] = [0.14060e-07,0.13587e-07,0.24644e-07,0.12716e-07,0.12367e-07]\n ka[:, 2, 3] = [0.17055e-07,0.16577e-07,0.32443e-07,0.31273e-07,0.15381e-07]\n ka[:, 3, 3] = [0.25414e-07,0.24672e-07,0.23874e-07,0.47281e-07,0.22346e-07]\n ka[:, 4, 3] = [0.39536e-07,0.38124e-07,0.36836e-07,0.35587e-07,0.72260e-07]\n ka[:, 5, 3] = [0.59488e-07,0.57630e-07,0.55623e-07,0.53878e-07,0.11230e-06]\n ka[:, 6, 3] = [0.99996e-07,0.96206e-07,0.93184e-07,0.90812e-07,0.89206e-07]\n ka[:, 7, 3] = [0.17678e-06,0.17554e-06,0.17358e-06,0.17091e-06,0.16830e-06]\n ka[:, 8, 3] = [0.18672e-06,0.17850e-06,0.16967e-06,0.16275e-06,0.15875e-06]\n ka[:, 9, 3] = [0.13558e-06,0.13493e-06,0.13633e-06,0.13799e-06,0.13932e-06]\n ka[:,10, 3] = [0.18883e-06,0.20452e-06,0.22206e-06,0.24347e-06,0.26091e-06]\n ka[:,11, 3] = [0.21296e-06,0.23580e-06,0.26439e-06,0.30148e-06,0.34942e-06]\n ka[:,12, 3] = [0.22072e-06,0.25535e-06,0.28661e-06,0.34814e-06,0.39337e-06]\n ka[:,13, 3] = [0.22515e-06,0.26161e-06,0.30833e-06,0.36527e-06,0.40123e-06]\n ka[:, 1, 4] = [0.32735e-07,0.31345e-07,0.58846e-07,0.28258e-07,0.27022e-07]\n ka[:, 2, 4] = [0.37754e-07,0.36873e-07,0.82776e-07,0.80947e-07,0.35190e-07]\n ka[:, 3, 4] = [0.76368e-07,0.75292e-07,0.74075e-07,0.10820e-06,0.73183e-07]\n ka[:, 4, 4] = [0.16392e-06,0.16130e-06,0.15926e-06,0.15700e-06,0.22041e-06]\n ka[:, 5, 4] = [0.29704e-06,0.28924e-06,0.28301e-06,0.27633e-06,0.42284e-06]\n ka[:, 6, 4] = [0.48466e-06,0.47240e-06,0.46143e-06,0.45012e-06,0.43867e-06]\n ka[:, 7, 4] = [0.71637e-06,0.69847e-06,0.67384e-06,0.65368e-06,0.63375e-06]\n ka[:, 8, 4] = [0.11904e-05,0.11714e-05,0.11524e-05,0.11354e-05,0.11172e-05]\n ka[:, 9, 4] = [0.21976e-05,0.21606e-05,0.21332e-05,0.20944e-05,0.20536e-05]\n ka[:,10, 4] = [0.21713e-05,0.21144e-05,0.20553e-05,0.19901e-05,0.19286e-05]\n ka[:,11, 4] = [0.21443e-05,0.20785e-05,0.20048e-05,0.19232e-05,0.18295e-05]\n ka[:,12, 4] = [0.21363e-05,0.20578e-05,0.19811e-05,0.18729e-05,0.17807e-05]\n ka[:,13, 4] = [0.21319e-05,0.20513e-05,0.19580e-05,0.18546e-05,0.17725e-05]\n ka[:, 1, 5] = [0.36050e-07,0.36125e-07,0.46253e-07,0.37280e-07,0.37359e-07]\n ka[:, 2, 5] = [0.65102e-07,0.64266e-07,0.68896e-07,0.65925e-07,0.61190e-07]\n ka[:, 3, 5] = [0.12173e-06,0.11889e-06,0.11625e-06,0.17574e-06,0.10921e-06]\n ka[:, 4, 5] = [0.20555e-06,0.19853e-06,0.19068e-06,0.18313e-06,0.30241e-06]\n ka[:, 5, 5] = [0.30900e-06,0.29996e-06,0.28857e-06,0.27772e-06,0.51631e-06]\n ka[:, 6, 5] = [0.43774e-06,0.42465e-06,0.40920e-06,0.39315e-06,0.37901e-06]\n ka[:, 7, 5] = [0.63869e-06,0.61654e-06,0.60324e-06,0.58966e-06,0.57948e-06]\n ka[:, 8, 5] = [0.98362e-06,0.96271e-06,0.94180e-06,0.92206e-06,0.91105e-06]\n ka[:, 9, 5] = [0.12061e-05,0.11895e-05,0.11564e-05,0.11296e-05,0.11110e-05]\n ka[:,10, 5] = [0.12958e-05,0.12694e-05,0.12425e-05,0.12153e-05,0.11880e-05]\n ka[:,11, 5] = [0.12962e-05,0.12698e-05,0.12429e-05,0.12156e-05,0.11883e-05]\n ka[:,12, 5] = [0.12964e-05,0.12701e-05,0.12431e-05,0.12158e-05,0.11885e-05]\n ka[:,13, 5] = [0.12966e-05,0.12702e-05,0.12433e-05,0.12160e-05,0.11886e-05]\n ka[:, 1, 6] = [0.73925e-07,0.70231e-07,0.21454e-06,0.63477e-07,0.60912e-07]\n ka[:, 2, 6] = [0.67794e-07,0.65807e-07,0.13854e-06,0.13061e-06,0.59361e-07]\n ka[:, 3, 6] = [0.98353e-07,0.95275e-07,0.92426e-07,0.15768e-06,0.87986e-07]\n ka[:, 4, 6] = [0.15855e-06,0.15394e-06,0.14948e-06,0.14655e-06,0.23172e-06]\n ka[:, 5, 6] = [0.27764e-06,0.26941e-06,0.26299e-06,0.25975e-06,0.40526e-06]\n ka[:, 6, 6] = [0.45469e-06,0.44417e-06,0.43276e-06,0.42440e-06,0.41489e-06]\n ka[:, 7, 6] = [0.71540e-06,0.71291e-06,0.70656e-06,0.69823e-06,0.68342e-06]\n ka[:, 8, 6] = [0.79651e-06,0.79807e-06,0.80621e-06,0.80941e-06,0.79835e-06]\n ka[:, 9, 6] = [0.18716e-06,0.16713e-06,0.14725e-06,0.13728e-06,0.11763e-06]\n ka[:,10, 6] = [0.92638e-07,0.86207e-07,0.80877e-07,0.70432e-07,0.64517e-07]\n ka[:,11, 6] = [0.13396e-06,0.12820e-06,0.12387e-06,0.10427e-06,0.94091e-07]\n ka[:,12, 6] = [0.14877e-06,0.14827e-06,0.14350e-06,0.12154e-06,0.10552e-06]\n ka[:,13, 6] = [0.15437e-06,0.15323e-06,0.14992e-06,0.12715e-06,0.10933e-06]\n ka[:, 1, 7] = [0.72717e-06,0.70656e-06,0.13933e-05,0.66449e-06,0.64269e-06]\n ka[:, 2, 7] = [0.52595e-06,0.50791e-06,0.11171e-05,0.10538e-05,0.45644e-06]\n ka[:, 3, 7] = [0.29919e-06,0.29227e-06,0.28284e-06,0.65215e-06,0.26347e-06]\n ka[:, 4, 7] = [0.27961e-06,0.27579e-06,0.27068e-06,0.26343e-06,0.41265e-06]\n ka[:, 5, 7] = [0.37031e-06,0.36318e-06,0.35475e-06,0.34488e-06,0.53740e-06]\n ka[:, 6, 7] = [0.53195e-06,0.52692e-06,0.52224e-06,0.51934e-06,0.51146e-06]\n ka[:, 7, 7] = [0.83043e-06,0.84552e-06,0.84833e-06,0.82800e-06,0.80930e-06]\n ka[:, 8, 7] = [0.14910e-05,0.15179e-05,0.15248e-05,0.15091e-05,0.14853e-05]\n ka[:, 9, 7] = [0.37340e-05,0.37823e-05,0.38311e-05,0.38453e-05,0.38567e-05]\n ka[:,10, 7] = [0.86791e-05,0.89697e-05,0.92118e-05,0.93991e-05,0.95564e-05]\n ka[:,11, 7] = [0.11878e-04,0.12201e-04,0.12588e-04,0.12897e-04,0.13151e-04]\n ka[:,12, 7] = [0.13192e-04,0.13732e-04,0.14137e-04,0.14465e-04,0.14643e-04]\n ka[:,13, 7] = [0.13716e-04,0.14229e-04,0.14617e-04,0.14944e-04,0.15182e-04]\n ka[:, 1, 8] = [0.39538e-05,0.38949e-05,0.56188e-05,0.37475e-05,0.36648e-05]\n ka[:, 2, 8] = [0.34231e-05,0.33633e-05,0.51877e-05,0.50048e-05,0.31425e-05]\n ka[:, 3, 8] = [0.28073e-05,0.27497e-05,0.26875e-05,0.44405e-05,0.25492e-05]\n ka[:, 4, 8] = [0.19229e-05,0.18818e-05,0.18382e-05,0.17896e-05,0.33073e-05]\n ka[:, 5, 8] = [0.11453e-05,0.11293e-05,0.11095e-05,0.10866e-05,0.19344e-05]\n ka[:, 6, 8] = [0.14565e-05,0.14517e-05,0.14369e-05,0.14141e-05,0.13944e-05]\n ka[:, 7, 8] = [0.23228e-05,0.22753e-05,0.22395e-05,0.22124e-05,0.21731e-05]\n ka[:, 8, 8] = [0.34877e-05,0.34362e-05,0.33796e-05,0.33389e-05,0.32924e-05]\n ka[:, 9, 8] = [0.63448e-05,0.63701e-05,0.63619e-05,0.62632e-05,0.61645e-05]\n ka[:,10, 8] = [0.12155e-04,0.11880e-04,0.11762e-04,0.11759e-04,0.11651e-04]\n ka[:,11, 8] = [0.14093e-04,0.13835e-04,0.13547e-04,0.13205e-04,0.12690e-04]\n ka[:,12, 8] = [0.14428e-04,0.14056e-04,0.13932e-04,0.13396e-04,0.12885e-04]\n ka[:,13, 8] = [0.15229e-04,0.14534e-04,0.13849e-04,0.13292e-04,0.12704e-04]\n ka[:, 1, 9] = [0.19250e-04,0.19148e-04,0.21702e-04,0.18906e-04,0.18761e-04]\n ka[:, 2, 9] = [0.18132e-04,0.18040e-04,0.20884e-04,0.20523e-04,0.17656e-04]\n ka[:, 3, 9] = [0.16928e-04,0.16843e-04,0.16742e-04,0.19715e-04,0.16470e-04]\n ka[:, 4, 9] = [0.15526e-04,0.15463e-04,0.15377e-04,0.15268e-04,0.18367e-04]\n ka[:, 5, 9] = [0.13545e-04,0.13511e-04,0.13455e-04,0.13362e-04,0.16722e-04]\n ka[:, 6, 9] = [0.97183e-05,0.97218e-05,0.97084e-05,0.96717e-05,0.96030e-05]\n ka[:, 7, 9] = [0.50307e-05,0.50984e-05,0.51628e-05,0.52093e-05,0.52354e-05]\n ka[:, 8, 9] = [0.45837e-05,0.45939e-05,0.45938e-05,0.45639e-05,0.45109e-05]\n ka[:, 9, 9] = [0.12254e-04,0.12319e-04,0.12397e-04,0.12584e-04,0.12620e-04]\n ka[:,10, 9] = [0.21545e-04,0.21836e-04,0.21718e-04,0.21511e-04,0.21211e-04]\n ka[:,11, 9] = [0.20079e-04,0.19539e-04,0.18859e-04,0.18393e-04,0.18181e-04]\n ka[:,12, 9] = [0.17115e-04,0.16357e-04,0.15410e-04,0.15220e-04,0.15207e-04]\n ka[:,13, 9] = [0.14935e-04,0.14679e-04,0.14593e-04,0.14448e-04,0.14436e-04]\n ka[:, 1,10] = [0.53569e-04,0.53042e-04,0.55454e-04,0.52098e-04,0.51678e-04]\n ka[:, 2,10] = [0.52196e-04,0.51739e-04,0.54777e-04,0.54075e-04,0.50624e-04]\n ka[:, 3,10] = [0.50339e-04,0.50046e-04,0.49769e-04,0.53168e-04,0.49370e-04]\n ka[:, 4,10] = [0.48505e-04,0.48316e-04,0.48143e-04,0.47993e-04,0.51621e-04]\n ka[:, 5,10] = [0.46313e-04,0.46267e-04,0.46119e-04,0.46064e-04,0.50279e-04]\n ka[:, 6,10] = [0.42662e-04,0.42818e-04,0.42935e-04,0.43007e-04,0.43099e-04]\n ka[:, 7,10] = [0.35762e-04,0.36149e-04,0.36450e-04,0.36639e-04,0.36887e-04]\n ka[:, 8,10] = [0.13516e-05,0.18607e-05,0.23061e-05,0.27339e-05,0.36516e-05]\n ka[:, 9,10] = [0.36432e-05,0.40739e-05,0.43830e-05,0.41136e-05,0.43128e-05]\n ka[:,10,10] = [0.62049e-05,0.69116e-05,0.73244e-05,0.65087e-05,0.78951e-05]\n ka[:,11,10] = [0.32156e-05,0.38834e-05,0.41231e-05,0.43386e-05,0.43405e-05]\n ka[:,12,10] = [0.22152e-05,0.26754e-05,0.31971e-05,0.34911e-05,0.37935e-05]\n ka[:,13,10] = [0.19792e-05,0.26543e-05,0.31511e-05,0.34597e-05,0.40624e-05]\n ka[:, 1,11] = [0.75384e-04,0.75103e-04,0.77406e-04,0.74222e-04,0.73734e-04]\n ka[:, 2,11] = [0.75458e-04,0.75244e-04,0.77778e-04,0.77018e-04,0.73942e-04]\n ka[:, 3,11] = [0.75023e-04,0.74844e-04,0.74477e-04,0.77271e-04,0.73633e-04]\n ka[:, 4,11] = [0.73633e-04,0.73539e-04,0.73257e-04,0.72934e-04,0.76232e-04]\n ka[:, 5,11] = [0.71348e-04,0.71322e-04,0.71227e-04,0.71069e-04,0.75258e-04]\n ka[:, 6,11] = [0.67784e-04,0.67873e-04,0.67974e-04,0.67924e-04,0.67903e-04]\n ka[:, 7,11] = [0.61855e-04,0.61922e-04,0.61973e-04,0.62206e-04,0.62496e-04]\n ka[:, 8,11] = [0.36622e-04,0.37413e-04,0.38740e-04,0.40550e-04,0.41833e-04]\n ka[:, 9,11] = [0.28544e-05,0.28831e-05,0.31445e-05,0.32900e-05,0.27967e-05]\n ka[:,10,11] = [0.53755e-05,0.42123e-05,0.51154e-05,0.63481e-05,0.54219e-05]\n ka[:,11,11] = [0.12605e-05,0.14078e-05,0.19167e-05,0.23729e-05,0.30161e-05]\n ka[:,12,11] = [0.11370e-05,0.91524e-06,0.11150e-05,0.14746e-05,0.20128e-05]\n ka[:,13,11] = [0.10511e-05,0.10014e-05,0.11405e-05,0.13852e-05,0.15576e-05]\n ka[:, 1,12] = [0.11184e-03,0.11117e-03,0.11327e-03,0.10989e-03,0.10910e-03]\n ka[:, 2,12] = [0.11379e-03,0.11322e-03,0.11555e-03,0.11462e-03,0.11135e-03]\n ka[:, 3,12] = [0.11508e-03,0.11459e-03,0.11421e-03,0.11671e-03,0.11339e-03]\n ka[:, 4,12] = [0.11596e-03,0.11563e-03,0.11538e-03,0.11511e-03,0.11770e-03]\n ka[:, 5,12] = [0.11597e-03,0.11581e-03,0.11569e-03,0.11553e-03,0.11890e-03]\n ka[:, 6,12] = [0.11443e-03,0.11445e-03,0.11443e-03,0.11443e-03,0.11438e-03]\n ka[:, 7,12] = [0.10852e-03,0.10888e-03,0.10912e-03,0.10934e-03,0.10942e-03]\n ka[:, 8,12] = [0.93194e-04,0.94766e-04,0.95355e-04,0.95090e-04,0.94926e-04]\n ka[:, 9,12] = [0.11836e-05,0.16115e-05,0.12883e-05,0.14202e-05,0.16541e-05]\n ka[:,10,12] = [0.18748e-05,0.34401e-05,0.39984e-05,0.44576e-05,0.33683e-05]\n ka[:,11,12] = [0.29890e-06,0.48741e-06,0.66276e-06,0.99698e-06,0.19230e-05]\n ka[:,12,12] = [0.15034e-06,0.39966e-06,0.56523e-06,0.70494e-06,0.10046e-05]\n ka[:,13,12] = [0.15016e-06,0.25751e-06,0.48928e-06,0.63534e-06,0.93575e-06]\n ka[:, 1,13] = [0.17305e-03,0.17234e-03,0.17389e-03,0.17055e-03,0.16974e-03]\n ka[:, 2,13] = [0.18170e-03,0.18075e-03,0.18265e-03,0.18138e-03,0.17772e-03]\n ka[:, 3,13] = [0.18990e-03,0.18892e-03,0.18776e-03,0.18950e-03,0.18494e-03]\n ka[:, 4,13] = [0.19649e-03,0.19552e-03,0.19424e-03,0.19281e-03,0.19464e-03]\n ka[:, 5,13] = [0.20197e-03,0.20109e-03,0.19993e-03,0.19856e-03,0.20092e-03]\n ka[:, 6,13] = [0.20595e-03,0.20549e-03,0.20452e-03,0.20331e-03,0.20199e-03]\n ka[:, 7,13] = [0.20703e-03,0.20710e-03,0.20649e-03,0.20552e-03,0.20428e-03]\n ka[:, 8,13] = [0.19874e-03,0.19767e-03,0.19696e-03,0.19655e-03,0.19591e-03]\n ka[:, 9,13] = [0.20434e-04,0.23398e-04,0.27400e-04,0.32409e-04,0.38451e-04]\n ka[:,10,13] = [0.18617e-05,0.99513e-06,0.10554e-05,0.16516e-05,0.37792e-05]\n ka[:,11,13] = [0.12517e-06,0.29518e-06,0.77058e-06,0.11660e-05,0.15349e-05]\n ka[:,12,13] = [0.12734e-06,0.36524e-06,0.66699e-06,0.10362e-05,0.14158e-05]\n ka[:,13,13] = [0.12431e-06,0.39389e-06,0.67331e-06,0.10292e-05,0.14448e-05]\n ka[:, 1,14] = [0.29365e-03,0.29046e-03,0.29008e-03,0.28509e-03,0.28286e-03]\n ka[:, 2,14] = [0.31990e-03,0.31668e-03,0.31617e-03,0.31332e-03,0.30885e-03]\n ka[:, 3,14] = [0.34787e-03,0.34432e-03,0.34112e-03,0.34052e-03,0.33589e-03]\n ka[:, 4,14] = [0.37401e-03,0.37027e-03,0.36696e-03,0.36394e-03,0.36355e-03]\n ka[:, 5,14] = [0.39840e-03,0.39446e-03,0.39082e-03,0.38763e-03,0.38760e-03]\n ka[:, 6,14] = [0.42165e-03,0.41729e-03,0.41335e-03,0.41006e-03,0.40721e-03]\n ka[:, 7,14] = [0.44257e-03,0.43782e-03,0.43364e-03,0.43014e-03,0.42736e-03]\n ka[:, 8,14] = [0.45299e-03,0.44953e-03,0.44586e-03,0.44260e-03,0.44006e-03]\n ka[:, 9,14] = [0.40190e-03,0.39751e-03,0.39238e-03,0.38812e-03,0.38612e-03]\n ka[:,10,14] = [0.64278e-05,0.18248e-05,0.16996e-05,0.31086e-06,0.16836e-06]\n ka[:,11,14] = [0.14350e-05,0.94778e-06,0.41349e-06,0.20817e-06,0.20238e-06]\n ka[:,12,14] = [0.16805e-05,0.15323e-05,0.62348e-06,0.99743e-07,0.12977e-06]\n ka[:,13,14] = [0.16858e-05,0.17103e-05,0.80574e-06,0.15825e-06,0.15032e-06]\n ka[:, 1,15] = [0.52181e-03,0.51578e-03,0.51251e-03,0.50356e-03,0.49731e-03]\n ka[:, 2,15] = [0.59491e-03,0.58822e-03,0.58413e-03,0.57646e-03,0.56692e-03]\n ka[:, 3,15] = [0.67653e-03,0.66881e-03,0.66126e-03,0.65540e-03,0.64461e-03]\n ka[:, 4,15] = [0.76388e-03,0.75456e-03,0.74556e-03,0.73649e-03,0.72840e-03]\n ka[:, 5,15] = [0.85507e-03,0.84417e-03,0.83378e-03,0.82338e-03,0.81349e-03]\n ka[:, 6,15] = [0.95034e-03,0.93798e-03,0.92553e-03,0.91287e-03,0.89957e-03]\n ka[:, 7,15] = [0.10496e-02,0.10352e-02,0.10206e-02,0.10054e-02,0.98958e-03]\n ka[:, 8,15] = [0.11507e-02,0.11337e-02,0.11169e-02,0.10991e-02,0.10806e-02]\n ka[:, 9,15] = [0.12408e-02,0.12207e-02,0.11996e-02,0.11773e-02,0.11531e-02]\n ka[:,10,15] = [0.12042e-03,0.11501e-03,0.11424e-03,0.11450e-03,0.13219e-03]\n ka[:,11,15] = [0.68914e-06,0.83960e-06,0.74591e-06,0.18660e-05,0.32503e-05]\n ka[:,12,15] = [0.35963e-07,0.46256e-06,0.56223e-06,0.98816e-06,0.92366e-06]\n ka[:,13,15] = [0.36605e-07,0.56591e-06,0.84008e-06,0.86042e-06,0.68452e-06]\n ka[:, 1,16] = [0.76517e-03,0.75944e-03,0.76010e-03,0.76100e-03,0.76498e-03]\n ka[:, 2,16] = [0.92375e-03,0.91357e-03,0.90997e-03,0.90997e-03,0.90993e-03]\n ka[:, 3,16] = [0.11142e-02,0.10974e-02,0.10835e-02,0.10789e-02,0.10748e-02]\n ka[:, 4,16] = [0.13278e-02,0.13025e-02,0.12802e-02,0.12631e-02,0.12539e-02]\n ka[:, 5,16] = [0.15712e-02,0.15343e-02,0.15017e-02,0.14713e-02,0.14497e-02]\n ka[:, 6,16] = [0.18525e-02,0.17982e-02,0.17525e-02,0.17101e-02,0.16714e-02]\n ka[:, 7,16] = [0.21731e-02,0.20986e-02,0.20340e-02,0.19757e-02,0.19210e-02]\n ka[:, 8,16] = [0.25325e-02,0.24346e-02,0.23473e-02,0.22687e-02,0.21950e-02]\n ka[:, 9,16] = [0.29269e-02,0.28006e-02,0.26863e-02,0.25805e-02,0.24878e-02]\n ka[:,10,16] = [0.29442e-02,0.27008e-02,0.23913e-02,0.21437e-02,0.18865e-02]\n ka[:,11,16] = [0.23220e-05,0.22310e-04,0.48349e-04,0.67183e-04,0.88908e-04]\n ka[:,12,16] = [0.22857e-05,0.11848e-04,0.42066e-04,0.67613e-04,0.86033e-04]\n ka[:,13,16] = [0.22823e-05,0.69105e-05,0.36212e-04,0.66247e-04,0.85488e-04]\nend", "meta": {"hexsha": "b892e4f182c6bf4af7724a9e780995e923a7df5d", "size": 18384, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "srtm_kgbs/srtm_kgb25.jl", "max_stars_repo_name": "jsbj/RRTM.jl", "max_stars_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-05-25T03:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T12:05:50.000Z", "max_issues_repo_path": "srtm_kgbs/srtm_kgb25.jl", "max_issues_repo_name": "jsbj/RRTM.jl", "max_issues_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srtm_kgbs/srtm_kgb25.jl", "max_forks_repo_name": "jsbj/RRTM.jl", "max_forks_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.6543209877, "max_line_length": 184, "alphanum_fraction": 0.6354982594, "num_tokens": 11290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.24798743735585305, "lm_q1q2_score": 0.17741616333722815}} {"text": "using DFTK\nusing Unitful\nusing UnitfulAtomic\nusing JLD2\nusing PyCall\nusing MPI\n\nif mpi_nprocs() == 1\n setup_threading()\nelse\n disable_threading()\nend\n\n# This tries to replicate the computational setup used for generating\n# the materials project data as closely as possible. For details on\n# the parameter choices see\n#\n# https://docs.materialsproject.org/methodology/total-energies/\n#\n#\n# All functions are MPI-ready, i.e. can be used through an MPI-parallelised julia session.\n\n#\n# If convergence issues on a system, try one of them (in this order and separately)\n# (a) is_metal=false\n# (b) use_experimental=false\n# (c) use_experimental=false, lower the damping (to 0.6, 0.4 and below if needed.)\n#\n\nfunction compute_formation_energy_per_atom(file::String; kwargs_bulk=(; ),\n kwargs_compound=(; ), kwargs...)\n scfres = run_if_needed(file; kwargs..., kwargs_compound...)\n\n bulk_energy_per_atom = Dict(map(scfres.basis.model.atoms) do (element, _)\n scfres_bulk = run_if_needed(element.symbol; kwargs..., kwargs_bulk...)\n n_atoms_bulk = sum(el_pos -> length(el_pos[2]), scfres_bulk.basis.model.atoms)\n element => scfres_bulk.energies.total / n_atoms_bulk\n end)\n\n atoms = scfres.basis.model.atoms\n n_atoms = sum(el_pos -> length(el_pos[2]), atoms)\n energy_bulk = sum(el_pos -> bulk_energy_per_atom[el_pos[1]] * length(el_pos[2]), atoms)\n formation_energy_hartree = (scfres.energies.total - energy_bulk) / n_atoms\n auconvert(u\"eV\", formation_energy_hartree)\nend\n\n\nfunction run_if_needed(file::String; kwargs...)\n outfile = joinpath(@__DIR__, file * \".jld2\")\n if !isfile(outfile)\n mpi_master() && println(\"#\\n# -- $file\\n#\")\n scfres = run_from_file(file; kwargs...)\n store_results(scfres, outfile)\n scfres\n else\n load_results(outfile)\n end\nend\nfunction run_if_needed(element::Symbol; kwargs...)\n mkpath(joinpath(@__DIR__, \"reference\"))\n outfile = joinpath(@__DIR__, \"reference\", \"$element.jld2\")\n if !isfile(outfile)\n mpi_master() && println(\"#\\n# -- $element\\n#\")\n scfres = run_bulk(element; kwargs...)\n store_results(scfres, outfile)\n scfres\n else\n load_results(outfile)\n end\nend\n\n\nfunction run_bulk(element::Symbol; kwargs...)\n bulkstructure = pyimport(\"ase.build\").bulk(string(element))\n lattice = load_lattice(bulkstructure)\n atoms = load_atoms(bulkstructure)\n run_dftk(lattice, atoms; kwargs...)\nend\n\n\nfunction run_from_file(file::AbstractString; kwargs...)\n lattice = load_lattice(file)\n atoms = load_atoms(file)\n run_dftk(lattice, atoms; kwargs...)\nend\n\n\n# Store the results from `run_from_file`\nfunction store_results(scfres, file)\n basis_master = DFTK.gather_kpts(scfres.basis)\n if mpi_master()\n JLD2.jldopen(file, \"w\") do jld\n jld[\"basis\"] = basis_master\n jld[\"ρ\"] = scfres.ρ\n jld[\"energies\"] = scfres.energies\n end\n end\nend\n\n\nfunction load_results(file)\n JLD2.jldopen(file, \"r\") do jld\n (energies=jld[\"energies\"], basis=jld[\"basis\"], ρ=jld[\"ρ\"])\n end\nend\n\n\nfunction run_dftk(lattice, atoms; use_experimental=true, is_metal=true, damping=0.8, debug=false, kwargs...)\n n_atoms = sum(el_pos -> length(el_pos[2]), atoms)\n\n # Check there are no atoms in the atoms list that require GGA+U\n has_ggau_metal = any(atoms) do (element, positions)\n element.symbol in (:V, :Cr, :Mn, :Fe, :Co, :Ni, :W, :Mo)\n end\n has_oxygen = any(el_pos -> el_pos[1].symbol == :O, atoms)\n has_flouride = any(el_pos -> el_pos[1].symbol == :F, atoms)\n if (has_oxygen || has_flouride) && has_ggau_metal\n error(\"This compound requires GGA+U which is not implemented in DFTK.\")\n end\n\n # Pseudos: Select the ones with largest number of electrons\n atoms = map(atoms) do (element, positions)\n symbol = element.symbol\n pspid = sort(list_psp(symbol, functional=\"pbe\"), by=t->t.n_elec_valence)[end]\n ElementPsp(symbol, psp=load_psp(pspid.identifier)) => positions\n end\n\n magnetic_moments = map(atoms) do (element, positions)\n element => fill(default_magnetic_moment(element.symbol), length(positions))\n end\n # https://docs.materialsproject.org/methodology/total-energies/#calculation-details\n\n # They used the Tetrahedron method + Blöchl corrections ... which we don't have in DFTK.\n smearing = Smearing.Gaussian()\n temperature = 0.2u\"eV\"\n model = model_PBE(lattice, atoms; temperature, magnetic_moments, smearing)\n\n if debug\n kgrid = kgrid_from_minimal_n_kpoints(lattice, 6)\n Ecut = 10\n else\n kgrid = kgrid_from_minimal_n_kpoints(lattice, min(500, ceil(Int, 1000 / n_atoms)))\n Ecut = 520u\"eV\"\n end\n basis = PlaneWaveBasis(model; Ecut, kgrid)\n\n ρ = guess_density(basis, magnetic_moments)\n tol = austrip(n_atoms * 5e-5u\"eV\")\n n_bands = DFTK.default_n_bands(basis.model)\n\n if use_experimental\n mixing = is_metal ? KerkerMixing() : SimpleMixing()\n damping = :adaptive\n algorithm = (\"adaptive damping\", DFTK.scf_potential_mixing_adaptive)\n extra = (; )\n else\n mixing = LdosMixing()\n extra = (damping=damping, )\n algorithm = (\"fixed damping\", self_consistent_field)\n end\n\n if mpi_master()\n magmom_compact = [element.symbol => values for (element, values) in magnetic_moments]\n display(basis)\n println()\n println()\n println(\"Solver parameters:\")\n println(\" magmom : $magmom_compact\")\n println(\" tol : $tol\")\n println(\" n_bands : $n_bands\")\n println(\" algorithm : $(algorithm[1])\")\n println(\" mixing : $mixing\")\n println(\" damping : $damping\")\n println(\" kwargs : $(Dict(kwargs...))\")\n println()\n flush(stdout)\n end\n\n DFTK.reset_timer!(DFTK.timer)\n run_scf = algorithm[2]\n scfres = run_scf(basis; ρ, tol, mixing, n_bands, maxiter=200, extra..., kwargs...)\n if mpi_master()\n println()\n println(DFTK.timer)\n println()\n end\n scfres\nend\n\n\nfunction default_magnetic_moment(element::Symbol)\n # TODO Consider adding this to PeriodicTable\n # ... or DFTK ... or both\n get(Dict(\n :H => 1.0,\n :He => 0.0,\n :Li => 1.0,\n :Be => 0.0,\n :B => 1.0,\n :C => 2.0,\n :N => 3.0,\n :O => 2.0,\n :F => 1.0,\n :Ne => 0.0,\n :Na => 1.0,\n :Mg => 0.0,\n :Al => 1.0,\n :Si => 2.0,\n :P => 3.0,\n :S => 2.0,\n :Cl => 1.0,\n :Ar => 0.0,\n :K => 1.0,\n :Ca => 0.0,\n :Sc => 1.0,\n :Ti => 2.0,\n :V => 3.0,\n :Cr => 6.0,\n :Mn => 5.0,\n :Fe => 4.0,\n :Co => 3.0,\n :Ni => 2.0,\n :Cu => 1.0,\n :Zn => 0.0,\n :Ga => 1.0,\n :Ge => 2.0,\n :As => 3.0,\n :Se => 2.0,\n :Br => 1.0,\n :Kr => 0.0,\n :Rb => 1.0,\n :Sr => 0.0,\n :Y => 1.0,\n :Zr => 2.0,\n :Nb => 5.0,\n :Mo => 6.0,\n :Tc => 5.0,\n :Ru => 4.0,\n :Rh => 3.0,\n :Pd => 0.0,\n :Ag => 1.0,\n :Cd => 0.0,\n :In => 1.0,\n :Sn => 2.0,\n :Sb => 3.0,\n :Te => 2.0,\n :I => 1.0,\n :Xe => 0.0,\n :Cs => 1.0,\n :Ba => 0.0,\n :La => 1.0,\n :Ce => 1.0,\n :Pr => 3.0,\n :Nd => 4.0,\n :Pm => 5.0,\n :Sm => 6.0,\n :Eu => 7.0,\n :Gd => 8.0,\n :Tb => 5.0,\n :Dy => 4.0,\n :Ho => 3.0,\n :Er => 2.0,\n :Tm => 1.0,\n :Yb => 0.0,\n :Lu => 1.0,\n :Hf => 2.0,\n :Ta => 3.0,\n :W => 4.0,\n :Re => 5.0,\n :Os => 4.0,\n :Ir => 3.0,\n :Pt => 2.0,\n :Au => 1.0,\n :Hg => 0.0,\n :Tl => 1.0,\n :Pb => 2.0,\n :Bi => 3.0,\n :Po => 2.0,\n :At => 1.0,\n :Rn => 0.0,\n :Fr => 1.0,\n :Ra => 0.0,\n :Ac => 1.0,\n :Th => 2.0,\n :Pa => 3.0,\n :U => 4.0,\n :Np => 5.0,\n :Pu => 6.0,\n :Am => 7.0,\n :Cm => 8.0,\n :Bk => 5.0,\n :Cf => 4.0,\n :Es => 4.0,\n :Fm => 2.0,\n :Md => 1.0,\n :No => 0.0,\n ), element, 0)\nend\n", "meta": {"hexsha": "7dd736527ec71e08ea8548ce11ec0b8c3b3fab08", "size": 8429, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "common.jl", "max_stars_repo_name": "mfherbst/DFTK-materialsproject", "max_stars_repo_head_hexsha": "37049b9d19c5402271a75bb47dddd5f330f06d6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T14:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T14:57:16.000Z", "max_issues_repo_path": "common.jl", "max_issues_repo_name": "mfherbst/DFTK-materialsproject", "max_issues_repo_head_hexsha": "37049b9d19c5402271a75bb47dddd5f330f06d6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common.jl", "max_forks_repo_name": "mfherbst/DFTK-materialsproject", "max_forks_repo_head_hexsha": "37049b9d19c5402271a75bb47dddd5f330f06d6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1906354515, "max_line_length": 108, "alphanum_fraction": 0.5356507296, "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17659610096676734}} {"text": "module Model\n\nusing LightGraphs\nusing GraphIO\n\nusing DataStructures\nusing SparseArrays\nusing Optim\nusing LineSearches\nusing StatsBase\nusing Statistics\nusing JSON\nusing Dates\nusing Serialization\nimport Optim: converged\n\n\ninclude(\"./structures.jl\")\ninclude(\"./nodemap.jl\")\n\nsetprecision(BigFloat, 64)\n\nmutable struct GraphModel\n dataset::String # constant\n structure_alphabet_size::Int64 # constant\n G::LightGraphs.SimpleGraph{Int64} # constant\n A::SparseArrays.SparseMatrixCSC{Int64,Int64} # constant\n n::Int64 # constant\n m::Int64 # constant\n maximum_m_simple::Int64 # constant\n maximum_m_loopy::Int64 # constant\n lambdas::Array{BigFloat,1} # growing at end (and values changing by optimization)\n constraint_values::Array{BigFloat,1} # growing at end\n micro_structures::Array{Union{Bool, Set{Tuple{Int64,Int64}}},1} # growing at end\n edge_lambda_indices::SortedDict{Tuple{Int64,Int64},Array{Int64,1}} # new edges inserted, growing at selected value ends\n edge_equivalence_classes::Dict{Set{Int64},Array{Tuple{Int64,Int64},1}} # currently reconstructed but could be smarter\n backup_optimization_result::Optim.MultivariateOptimizationResults # reconstructed\n last_optimization_result::Optim.MultivariateOptimizationResults # reconstructed\n entropy::BigFloat # changing\n equivalence_class_edge_probabilities::Dict{Set{Int64},BigFloat} # reconstructed\n surprise_matrix::SparseArrays.SparseMatrixCSC{BigFloat,Int64} # reconstructed\n surprise_matrix_transpose::SparseArrays.SparseMatrixCSC{BigFloat,Int64} # reconstructed\n macro_structures::Array{Structures.Structure} # growing at end\n macro_structure_description_lengths::Array{BigFloat} # growing at end\n edge_probability_description_length_maxent::BigFloat # changing\n structure_type_description_length::BigFloat # changing\n node_surprises::Array{Tuple{Int64,BigFloat},1} # reconstructed\n surprising_edges::Array{Tuple{Int64,Int64},1} # reconstructed\n start_description_length_maxent::BigFloat # constant\n total_description_length_maxent::BigFloat # changing\n description_lengths_over_time::Array{BigFloat,1} # growing at end\n parameters::Dict{String,Float64} # constant resp. set only upon saving\n io::IO # constant\n hub_spoke_edges::Set{Tuple{Int64,Int64}} # changing\n star_spoke_edges::Set{Tuple{Int64,Int64}} # changing\n zero_edges::Set{Tuple{Int64,Int64}} # changing\n last_hub_spoke_edges::Set{Tuple{Int64,Int64}} # changing\n last_star_spoke_edges::Set{Tuple{Int64,Int64}} # changing\n last_zero_edges::Set{Tuple{Int64,Int64}} # changing - note that we'll be a bit imprecise here: if a zero edge is discovered after already having been covered, it will remain also in its previous equivalence class, if any\n covered_nodes::Set{Int64} # growing\n function GraphModel(dataset::String, io=stdout)\n setup_graph!(new(), dataset, io)\n end\n function GraphModel(kwargs::Dict)\n M = new()\n for (k,v) in kwargs\n setproperty!(M, k, v)\n end\n return M\n end\nend\n\nBase.show(io::IO, M::GraphModel) = print(io, \"Model for $(M.dataset):\\n$(typeof(M.G)) with n = $(M.n), m=$(M.m)\")\nJSON.lower(M::GraphModel) = Dict(key=> getfield(M, key) for key in fieldnames(GraphModel) if key in\n (:dataset, :n, :m, :macro_structures, :macro_structure_description_lengths,\n :edge_probability_description_length_maxent,\n :start_description_length_maxent,\n :total_description_length_maxent,\n :description_lengths_over_time,\n :lambdas,\n :parameters,\n :structure_alphabet_size,\n :structure_type_description_length\n )\n)\n\n\"\"\"\nhelper providing basic logging\n\"\"\"\nfunction log_progress!(M::GraphModel, msg::String)\n println(M.io, now(), \" - \", msg)\n flush(M.io)\nend\n\n\"\"\"\nsave model as jldb (serialization format) or json\n\"\"\"\nfunction save_model(M::GraphModel, directory::String; final=true, overwrite=true)\n path, file = splitdir(M.dataset)\n last_folder = splitdir(path)[end]\n file_base, ext = splitext(file)\n size_threshold = M.parameters[\"size_threshold\"]\n stop_after_n_structures = M.parameters[\"stop_after_n_structures\"]\n filepath = \"$(directory)/$(last_folder)/$(file_base)_size-$(size_threshold)_max-$(stop_after_n_structures)\"\n mkpath(splitdir(filepath)[1])\n if !final\n open(filepath*\".jldb\", \"w\") do io\n serialize(io, M)\n end\n else\n open(filepath*\".json\", \"w\") do io\n write(io, json(M, 4))\n end\n log_progress!(M, \"Saved model to $(filepath).json\")\n end\n mv(\"$(path)/$(file_base)-nodemap.csv\", \"$(directory)/$(last_folder)/$(file_base)-nodemap.csv\", force=overwrite)\nend\n\n\"\"\"\nrestore model from json\n\"\"\"\nfunction restore_model(path_to_file::String)\n model_dict = JSON.parsefile(path_to_file)\n M = Model.GraphModel(model_dict[\"dataset\"])\n structures = Array{Structures.Structure,1}()\n for sd in model_dict[\"macro_structures\"]\n if sd[\"structure_type\"] == \"clique\"\n structure = Structures.Clique(sd[\"n_edges_total\"], Array{Int64,1}(sd[\"nodes\"]))\n elseif sd[\"structure_type\"] == \"star\"\n structure = Structures.Star(sd[\"n_edges_total\"], sd[\"hub\"], Array{Int64,1}(sd[\"spokes\"]))\n elseif sd[\"structure_type\"] == \"biclique\"\n structure = Structures.Biclique(sd[\"n_edges_total\"], Array{Int64,1}(sd[\"left_nodes\"]), Array{Int64,1}(sd[\"right_nodes\"]), sd[\"n_edges_in_left\"], sd[\"n_edges_in_right\"])\n elseif sd[\"structure_type\"] == \"starclique\"\n structure = Structures.Starclique(sd[\"n_edges_total\"], Array{Int64,1}(sd[\"left_nodes\"]), Array{Int64,1}(sd[\"right_nodes\"]), sd[\"n_edges_in_left\"], sd[\"n_edges_in_right\"])\n # generic structures are already present\n else\n continue\n end\n push!(structures, structure)\n end\n add_macro_structures!(M, structures; lambdas=get!(model_dict, \"lambdas\", []))\n if model_dict[\"lambdas\"] == []\n println(\"WARNING: Recomputing lambdas when restoring model - true edge probability description length for computed lambdas might differ from restored edge probability description length due to different optimization process...\")\n end\n M.parameters[\"surprise_threshold\"] = model_dict[\"parameters\"][\"surprise_threshold\"] === nothing ? Inf : model_dict[\"parameters\"][\"surprise_threshold\"]\n M.parameters[\"size_threshold\"] = model_dict[\"parameters\"][\"size_threshold\"] === nothing ? Inf : model_dict[\"parameters\"][\"size_threshold\"]\n M.description_lengths_over_time = model_dict[\"description_lengths_over_time\"]\n M.macro_structure_description_lengths = model_dict[\"macro_structure_description_lengths\"]\n M.edge_probability_description_length_maxent = model_dict[\"edge_probability_description_length_maxent\"]\n M.total_description_length_maxent = M.edge_probability_description_length_maxent + M.structure_type_description_length + sum(M.macro_structure_description_lengths)\n return M\nend\n\n\"\"\"\ninitial graph setup with first optimization\n\"\"\"\nfunction setup_graph!(M::GraphModel, dataset::String, io::IO)\n set_constant_terms!(M, dataset, io)\n M.lambdas = zeros(2)\n M.constraint_values = [M.m, 0]\n M.micro_structures = [true, Set([(i,i) for i=1:M.n])]\n M.edge_lambda_indices = SortedDict((i,i)=>[1,2] for i=1:M.n)\n M.edge_equivalence_classes = Dict(Set([1,2])=>[(i,i) for i=1:M.n])\n M.macro_structures = [Structures.GenericStructure(\"Overall number of edges\", M.m), Structures.GenericStructure(\"Loop-freeness\", 0)]\n # below, we add the cost of transmitting n to the cost of transmitting m (since it is not a proper structure but necessary to specify m)\n M.macro_structure_description_lengths = [Structures.MDL.universal_integer(M.n) + Structures.MDL.log2(M.maximum_m_loopy), 1.]\n M.structure_type_description_length = 0\n M.description_lengths_over_time = []\n M.star_spoke_edges = Set()\n M.hub_spoke_edges = Set()\n M.zero_edges = Set()\n M.last_star_spoke_edges = Set()\n M.last_hub_spoke_edges = Set()\n M.last_zero_edges = Set()\n M.covered_nodes = Set()\n update_variable_terms!(M)\n M.backup_optimization_result = deepcopy(M.last_optimization_result)\n M.start_description_length_maxent = M.total_description_length_maxent\n # the below is to account for the fact that we have two initial constraints but perform only one optimization\n append!(M.description_lengths_over_time, [M.start_description_length_maxent])\n M.parameters = Dict(\"surprise_threshold\" => Inf, \"size_threshold\" => Inf)\n return M\nend\n\n\"\"\"\ninitial graph setup: set constant terms - NB: dataset now needs to be full path with extension\n\"\"\"\nfunction set_constant_terms!(M::GraphModel, dataset::String, io::IO)\n M.dataset = dataset\n M.structure_alphabet_size = 4 # cliques, stars, bicliques, starcliques\n M.io = io\n M.G = SimpleGraph(NodeMap.loadgraph(dataset, GraphIO.EdgeList.EdgeListFormat())[1])\n NodeMap.create_node_map(dataset)\n remove_loops!(M.G)\n M.A = LightGraphs.LinAlg.adjacency_matrix(M.G)\n M.n = nv(M.G)\n M.m = ne(M.G)\n M.maximum_m_simple = Structures.MDL.choose(M.n, 2)\n M.maximum_m_loopy = M.maximum_m_simple + M.n\nend\n\n\"\"\"\nmake graph loop-free\n\"\"\"\nfunction remove_loops!(G::SimpleGraph)\n for e in [e for e in edges(G) if src(e) == dst(e)]\n rem_edge!(G, e)\n end\nend\n\n\"\"\"\neach step: update model (re-optimize, update description length, update surprises)\n\"\"\"\nfunction update_variable_terms!(M::GraphModel)\n log_progress!(M, \"starting optimization\")\n optimize_maxent!(M)\n log_progress!(M, \"finished optimization\")\n log_progress!(M, \"updating description length\")\n update_description_length!(M)\nend\n\n\"\"\"\noptimization wrapper function\n\"\"\"\nfunction optimize_maxent!(M::Model.GraphModel)\n n_iter = 50\n td = TwiceDifferentiable(x -> lagrange_dual_equiv(x, M), M.lambdas; autodiff = :forward)\n result = optimize(\n td, M.lambdas,\n Newton(linesearch=LineSearches.BackTracking()), # the solver - using BackTracking instead of the default HagerZhang because that sometimes throws a weird assertion error\n Optim.Options(allow_f_increases=true,\n show_trace=false, show_every=100, iterations=n_iter, x_tol=1e-8, f_tol=1e-8, g_tol=1e-6)\n )\n M.last_optimization_result = result\n M.lambdas = M.last_optimization_result.minimizer\n M.entropy = M.last_optimization_result.minimum\n if !converged(result)\n log_progress!(M, \"NO CONVERGENCE AFTER $(n_iter) ITERATIONS\")\n end\nend\n\n\"\"\"\noptimization computation: wrapper\n\"\"\"\nfunction lagrange_dual_equiv(lambdas, M::Model.GraphModel)\n return (get_first_term(lambdas, M) - get_second_term(lambdas, M))\nend\n\n\"\"\"\noptimization computation: first term\n\"\"\"\nfunction get_first_term(lambdas, M::Model.GraphModel)\n #log_progress!(M, \"computing first term in optimization\")\n rest_lambda = lambdas[1]\n if isempty(M.edge_equivalence_classes)\n return M.maximum_m_loopy * log(get_normalizer(rest_lambda))\n else\n lambda_total_contribution = BigFloat(0)\n lambda_total_sizes = 0\n for equivalence_class_key in keys(M.edge_equivalence_classes)\n size = get_equiv_size(equivalence_class_key, M.edge_equivalence_classes)\n lambda_sum = get_lambda_sum_from_equiv(equivalence_class_key, lambdas)\n normalized_sum = get_normalizer(lambda_sum)\n contribution = log(normalized_sum)\n lambda_total_contribution += size * contribution\n lambda_total_sizes += size\n end\n rest_class_n = M.maximum_m_loopy - sum(lambda_total_sizes)\n rest_contribution = rest_class_n * log(get_normalizer(rest_lambda))\n return lambda_total_contribution + rest_contribution\n end\nend\n\n\"\"\"\noptimization helper (normalization)\n\"\"\"\nfunction get_normalizer(lambda_sum)\n return (1 + exp(lambda_sum))\nend\n\n\"\"\"\noptimization helper (size of equivalence class)\n\"\"\"\nfunction get_equiv_size(equivalence_class_key::Set{Int64}, equivalence_classes::Dict{Set{Int64},Array{Tuple{Int64,Int64},1}})\n return length(equivalence_classes[equivalence_class_key])\nend\n\n\"\"\"\noptimization helper (lambda sum for equivalence class)\n\"\"\"\nfunction get_lambda_sum_from_equiv(equivalence_class_key::Set{Int64}, lambdas)\n lambda_sum = BigFloat(0)\n for idx in equivalence_class_key\n lambda_sum += lambdas[idx]\n end\n return lambda_sum \nend\n\n\"\"\"\noptimization computation: second term\n\"\"\"\nfunction get_second_term(lambdas, M::Model.GraphModel)\n #log_progress!(M, \"computing second term in optimization\")\n second_term = BigFloat(0)\n for (lambda, constraint_value) in zip(lambdas, M.constraint_values)\n second_term += lambda * constraint_value\n end\n return second_term\nend\n\n\"\"\"\ndescription length computation wrapper\n\"\"\"\nfunction update_description_length!(M::Model.GraphModel)\n update_equivalence_class_edge_probabilities!(M)\n update_edge_probability_description_length!(M)\n update_structure_type_description_length!(M)\n update_total_description_length!(M)\n # NB: the below gives misleading results when multiple structures are added at a time, e.g., during replay -> we have taken care of that in restore_model\n append!(M.description_lengths_over_time, M.total_description_length_maxent)\nend\n\n\"\"\"\ndescription length helper: structure type encoding costs\n\"\"\"\nfunction update_structure_type_description_length!(M::Model.GraphModel)\n n_different_structures = length(M.macro_structures) - 2 # we don't count the generic macro structures as their type is equivalence_class_edge_probabilities\n M.structure_type_description_length = (Structures.MDL.universal_integer(n_different_structures + 1) + Structures.MDL.log2_choose(M.structure_alphabet_size + n_different_structures - 1, n_different_structures - 1)\n )\nend\n\n\"\"\"\ndescription length helper: edge probabilities for equivalence classes\n\"\"\"\nfunction update_equivalence_class_edge_probabilities!(M::Model.GraphModel)\n probabilities = Dict{Array{Int64,1},BigFloat}(\n equivalence_class=>edge_probability_for_equiv(equivalence_class, M.lambdas) for equivalence_class in keys(M.edge_equivalence_classes))\n probabilities[[1,]] = edge_probability_for_equiv(Set([1,]), M.lambdas)\n M.equivalence_class_edge_probabilities = probabilities\nend\n\n\"\"\"\ndescription length helper: edge probability for one equivalence class\n\"\"\"\nfunction edge_probability_for_equiv(equivalence_class, lambdas)\n if equivalence_class == Set([1,])\n lambda_sum = lambdas[1]\n else\n lambda_sum = get_lambda_sum_from_equiv(equivalence_class, lambdas)\n end\n edge_prop = exp(lambda_sum) / get_normalizer(lambda_sum)\n return edge_prop\nend\n\n\"\"\"\ndescription length helper: surprise matrices update\n\"\"\"\nfunction update_surprise_matrices!(M::Model.GraphModel)\n # NB: we currently keep track only of surprising EDGES (else we get a non-sparse matrix :( )\n surprise_matrix = SparseMatrixCSC{BigFloat,Int64}(M.A)\n for idx in filter!(x->(x[1] < x[2]), findall(isone, M.A))\n edge = (idx[1],idx[2])\n # due to symmetry\n eq_class = Set(get(M.edge_lambda_indices, edge, [1,]))\n rest_class_probability = M.equivalence_class_edge_probabilities[Set([1,])]\n if eq_class == Set([1,])\n surprise_matrix[edge...] = 1 - rest_class_probability\n else\n surprise_matrix[edge...] = 0\n end\n surprise_matrix[reverse(edge)...] = 0\n end\n M.surprise_matrix = surprise_matrix\n M.surprise_matrix_transpose = sparse(transpose(M.surprise_matrix))\nend\n\n\"\"\"\ndescription length helper: total description length of edge probabilities (error in MDL, L(D|M))\n\"\"\"\nfunction update_edge_probability_description_length!(M::Model.GraphModel)\n dl = 0.\n rest_size = M.maximum_m_loopy # because we have loop-freeness as a separate constraint\n n_guaranteed_edges = length(M.hub_spoke_edges) # guaranteed to be there and not appearing in any equivalence class\n n_zero_edges = length(M.zero_edges) # guaranteed to be not there and not appearing in any equivalence class\n rest_size -= (n_guaranteed_edges + n_zero_edges)\n rest_edges = M.m - n_guaranteed_edges\n for (eq_class, edges) in M.edge_equivalence_classes\n size = length(edges)\n size_ones = length(filter(edge -> has_edge(M.G, edge...), edges))\n size_zeros = size - size_ones\n eq_class_probability = M.equivalence_class_edge_probabilities[eq_class]\n contribution = size_ones * -Structures.MDL.log2_zero(eq_class_probability) + size_zeros * -Structures.MDL.log2_zero(1 - eq_class_probability)\n dl += contribution\n rest_size -= size\n rest_edges -= size_ones\n end\n rest_probability = M.equivalence_class_edge_probabilities[Set([1,])]\n rest_contribution = rest_edges * -Structures.MDL.log2_zero(rest_probability) + (rest_size - rest_edges) * -Structures.MDL.log2_zero(1 - rest_probability)\n dl += rest_contribution\n M.edge_probability_description_length_maxent = dl\nend\n\n\"\"\"\ndescription length helper: total description length (L(M) + L(D|M))\n\"\"\"\nfunction update_total_description_length!(M::Model.GraphModel)\n M.total_description_length_maxent = sum(M.macro_structure_description_lengths) + M.edge_probability_description_length_maxent + M.structure_type_description_length\nend\n\n\"\"\"\nsanity check whether probability mass approximately sums to 1\n\"\"\"\nfunction sanity_check(M::Model.GraphModel)\n if !isempty(M.edge_equivalence_classes)\n equiv = sum([edge_probability_for_equiv(equivalence_class, M.lambdas) * get_equiv_size(equivalence_class, M.edge_equivalence_classes)\n for equivalence_class in keys(M.edge_equivalence_classes)])\n rest_size = M.maximum_m_loopy - sum([get_equiv_size(equivalence_class, M.edge_equivalence_classes)\n for equivalence_class in keys(M.edge_equivalence_classes)])\n else\n equiv = 0\n rest_size = M.maximum_m_loopy\n end\n rest = edge_probability_for_equiv([1,], M.lambdas)\n probability_mass_sum = equiv + rest * rest_size\n print(\"Sanity Check: probability mass sums to $(probability_mass_sum), expected $(M.m)\\n\")\n return abs(probability_mass_sum-M.m) <= 1.0e-2\nend\n\n\"\"\"\ngenerate micro structures and constraints from clique candidate\n\"\"\"\nfunction generate_micro_structures(structure::Structures.Clique, M::Model.GraphModel)\n micro_structures = [Set([(n1,n2) for n1 in structure.nodes for n2 in structure.nodes if n1 < n2])]\n clique_edges_in_hs_edges = intersect(micro_structures[1], M.hub_spoke_edges)\n setdiff!(micro_structures[1], clique_edges_in_hs_edges)\n constraint_values = [structure.n_edges_total - length(clique_edges_in_hs_edges)]\n return micro_structures, constraint_values\nend\n\n\"\"\"\ngenerate micro structures and constraints from star candidate\n\"\"\"\nfunction generate_micro_structures(structure::Structures.Star, M::Model.GraphModel)\n hub = structure.hub \n micro_structures = [Set([(hub < n ? (hub,n) : (n, hub)) for n in structure.spokes]),\n Set([(n1,n2) for n1 in structure.spokes for n2 in structure.spokes if (n1 < n2) && (n1,n2) ∉ M.star_spoke_edges])]\n hs_edges_in_hs_edges = intersect(micro_structures[1], M.hub_spoke_edges)\n setdiff!(micro_structures[1],hs_edges_in_hs_edges)\n ss_edges_in_hs_edges = intersect(micro_structures[end], M.hub_spoke_edges)\n setdiff!(micro_structures[end],ss_edges_in_hs_edges)\n constraint_values = [structure.n_nodes_in_spokes-length(hs_edges_in_hs_edges), structure.n_edges_in_spokes-length(ss_edges_in_hs_edges)] # note that this is theoretically wrong - we do it for performance reasons\n return micro_structures, constraint_values\nend\n\n\"\"\"\ngenerate micro structures and constraints from biclique candidate\n\"\"\"\nfunction generate_micro_structures(structure::Union{Structures.Biclique,Structures.Starclique}, M::Model.GraphModel)\n if structure isa Structures.Biclique\n left = Set([(n1, n2) for n1 in structure.left_nodes for n2 in structure.left_nodes if n1 < n2 && (n1,n2) ∉ M.star_spoke_edges])\n else # assuming Starclique\n left = Set([(n1, n2) for n1 in structure.left_nodes for n2 in structure.left_nodes if n1 < n2])\n end\n left_edges_in_hs_edges = intersect(left, M.hub_spoke_edges)\n setdiff!(left,left_edges_in_hs_edges)\n right = Set([(n1, n2) for n1 in structure.right_nodes for n2 in structure.right_nodes if n1 < n2 && (n1,n2) ∉ M.star_spoke_edges])\n right_edges_in_hs_edges = intersect(right, M.hub_spoke_edges)\n setdiff!(right,right_edges_in_hs_edges)\n across = Set([(n1 < n2) ? (n1, n2) : (n2, n1) for n1 in structure.left_nodes for n2 in structure.right_nodes])\n across_edges_in_hs_edges = intersect(across, M.hub_spoke_edges)\n setdiff!(across, across_edges_in_hs_edges)\n micro_structures = [left, right, across]\n constraint_values = [ structure.n_edges_in_left - length(left_edges_in_hs_edges), \n structure.n_edges_in_right - length(right_edges_in_hs_edges), \n structure.n_edges_across - length(across_edges_in_hs_edges)\n ]\n return micro_structures, constraint_values\nend\n\n\"\"\"\ntry adding structure to model, keeping the result only if it reduces the description length\n\"\"\"\nfunction test_adding_structure!(M::Model.GraphModel, structure::Structures.Structure, size_threshold::Float64=1.)\n log_progress!(M, \"saving previous state...\")\n M.backup_optimization_result = deepcopy(M.last_optimization_result)\n log_progress!(M, \"testing structure $(structure)...\")\n if structure.n_nodes_total < size_threshold\n log_progress!(M, \"failure: structure too small\")\n return false\n end\n add_macro_structures!(M, Array{Structures.Structure,1}([structure]))\n if converged(M.last_optimization_result) && M.description_lengths_over_time[end] <= M.description_lengths_over_time[end-1]\n log_progress!(M, \"success: new description length $(M.total_description_length_maxent)\")\n return true\n else\n roll_back_model!(M)\n log_progress!(M, \"failure: no decrease in description length\")\n return false\n end\nend\n\n\"\"\"\nadd macro structures to model (assuming no connector knowledge)\nwe allow for adding multiple structures at once to enable faster replay of macro_structure_description_lengths\n(in the model building phase, we test adding one structure at a time only)\n\"\"\"\nfunction add_macro_structures!(M::Model.GraphModel, structures::Array{Structures.Structure,1}; lambdas=[])\n log_progress!(M, \"updating micro structures et al\")\n for structure in structures\n micro_structures, constraint_values = generate_micro_structures(structure, M)\n if structure isa Structures.Star\n M.last_hub_spoke_edges = deepcopy(M.hub_spoke_edges)\n M.last_star_spoke_edges = deepcopy(M.star_spoke_edges)\n n_edges_in_spokes = structure.n_edges_in_spokes\n union!(M.star_spoke_edges, micro_structures[end])\n union!(M.hub_spoke_edges, micro_structures[1])\n if n_edges_in_spokes > 0 # if the star is perfect, we know exactly what its associated probabilities are\n append!(M.micro_structures, [micro_structures[end]])\n append!(M.constraint_values, [constraint_values[end]])\n append!(M.lambdas, zeros(1))\n update_edge_lambda_indices!(M, [micro_structures[end]], [constraint_values[end]])\n update_equivalence_classes_from_edge_lambda_indices!(M)\n else\n M.last_zero_edges = deepcopy(M.last_zero_edges)\n union!(M.zero_edges, micro_structures[1])\n end\n elseif structure isa Structures.Starclique || structure isa Structures.Biclique\n M.last_star_spoke_edges = deepcopy(M.star_spoke_edges)\n union!(M.star_spoke_edges, micro_structures[2])\n if structure isa Structures.Biclique\n union!(M.star_spoke_edges, micro_structures[1])\n end\n append!(M.micro_structures, micro_structures)\n append!(M.constraint_values, constraint_values)\n append!(M.lambdas, zeros(length(micro_structures)))\n update_edge_lambda_indices!(M, micro_structures, constraint_values)\n update_equivalence_classes_from_edge_lambda_indices!(M)\n else\n append!(M.micro_structures, micro_structures)\n append!(M.constraint_values, constraint_values)\n append!(M.lambdas, zeros(length(micro_structures)))\n update_edge_lambda_indices!(M, micro_structures, constraint_values)\n update_equivalence_classes_from_edge_lambda_indices!(M)\n end \n end\n if !isempty(lambdas)\n M.lambdas = lambdas\n end\n update_variable_terms!(M)\n for structure in structures\n append!(M.macro_structures, [structure])\n append!(M.macro_structure_description_lengths, [Structures.compute_description_length(structure, M.n, false)])\n end\nend\n\nfunction update_edge_lambda_indices!(M::Model.GraphModel, new_micro_structures, new_constraint_values)\n log_progress!(M, \"updating edge lambda indices\")\n start_lambda_index = length(M.lambdas) - length(new_constraint_values)\n for (idx, structure) in enumerate(new_micro_structures)\n new_idx = start_lambda_index+idx\n present_edges = intersect(keys(M.edge_lambda_indices), structure)\n for edge in present_edges\n append!(M.edge_lambda_indices[edge], new_idx)\n end\n absent_edge_dict = Dict(e=>[1,new_idx] for e in setdiff(structure,present_edges))\n merge!(M.edge_lambda_indices,absent_edge_dict)\n end\nend\n\n\"\"\"\nroll back the model if the added structure is no good\neliminates last macro structure added and all its consequences\n\"\"\"\nfunction roll_back_model!(M::Model.GraphModel)\n structure_to_remove = M.macro_structures[end]\n micros_to_remove = determine_micros_to_remove(structure_to_remove)\n if structure_to_remove isa Structures.Star\n M.hub_spoke_edges = deepcopy(M.last_hub_spoke_edges)\n M.star_spoke_edges = deepcopy(M.last_star_spoke_edges)\n if structure_to_remove.n_edges_in_spokes == 0\n micros_to_remove = 0\n M.last_zero_edges = deepcopy(M.last_zero_edges)\n end\n elseif structure_to_remove isa Structures.Starclique || structure_to_remove isa Structures.Biclique\n M.star_spoke_edges = deepcopy(M.last_star_spoke_edges)\n end\n if micros_to_remove > 0\n roll_back_edge_lambda_indices!(M, micros_to_remove)\n roll_back_lambda_related!(M, micros_to_remove)\n update_equivalence_classes_from_edge_lambda_indices!(M)\n end\n update_equivalence_class_edge_probabilities!(M)\n update_edge_probability_description_length!(M)\n pop!(M.macro_structures)\n pop!(M.macro_structure_description_lengths)\n pop!(M.description_lengths_over_time)\n roll_back_total_description_length!(M)\n roll_back_optimization_result!(M)\nend\n\nfunction determine_micros_to_remove(structure_to_remove::Structures.Structure)\n if structure_to_remove isa Structures.Clique || structure_to_remove isa Structures.Star\n micros_to_remove = 1\n elseif structure_to_remove isa Structures.Biclique || structure_to_remove isa Structures.Starclique\n micros_to_remove = 3\n else\n throw(ErrorException(\"Cannot roll back for structure of type $(typeof(structure_to_remove))!\"))\n end\n return micros_to_remove\nend\n\nfunction roll_back_edge_lambda_indices!(M::Model.GraphModel, micros_to_remove::Int64)\n for micro_structure in M.micro_structures[end-micros_to_remove+1:end]\n for edge in micro_structure\n pop!(M.edge_lambda_indices[edge])\n if M.edge_lambda_indices[edge] == [1]\n delete!(M.edge_lambda_indices, edge)\n end\n end\n end\nend\n\nfunction roll_back_lambda_related!(M::Model.GraphModel, micros_to_remove::Int64)\n first_to_delete = length(M.micro_structures)-micros_to_remove+1\n last_to_delete = length(M.micro_structures)\n deleteat!(M.lambdas, first_to_delete:last_to_delete)\n deleteat!(M.constraint_values, first_to_delete:last_to_delete)\n deleteat!(M.micro_structures, first_to_delete:last_to_delete)\nend\n\nfunction update_equivalence_classes_from_edge_lambda_indices!(M::Model.GraphModel)\n equivalence_classes = Dict{Set{Int64},Array{Tuple{Int64,Int64},1}}()\n for (k,v) in M.edge_lambda_indices\n append!(get!(equivalence_classes, Set(v), Array{Int64,1}()), [k])\n end\n M.edge_equivalence_classes = equivalence_classes\nend\n\nfunction update_equivalence_class_edge_probabilities!(M::Model.GraphModel)\n probabilities = Dict{Set{Int64},BigFloat}(\n equivalence_class=>edge_probability_for_equiv(equivalence_class, M.lambdas) for equivalence_class in keys(M.edge_equivalence_classes))\n probabilities[Set([1,])] = edge_probability_for_equiv(Set([1,]), M.lambdas)\n M.equivalence_class_edge_probabilities = probabilities\nend\n\nfunction roll_back_total_description_length!(M::Model.GraphModel)\n M.total_description_length_maxent = M.description_lengths_over_time[end]\nend\n\nfunction roll_back_optimization_result!(M::Model.GraphModel)\n M.last_optimization_result = deepcopy(M.backup_optimization_result)\n M.entropy = M.last_optimization_result.minimum\nend\n\nend", "meta": {"hexsha": "1fc48a915798528cb3ebb5e72629f5e4ccfa280c", "size": 29446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/model.jl", "max_stars_repo_name": "dataspider/momo", "max_stars_repo_head_hexsha": "c3c16839dfed0fa3ba5deabc7ecf1431280df74c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-21T01:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T12:41:28.000Z", "max_issues_repo_path": "code/model.jl", "max_issues_repo_name": "dataspider/momo", "max_issues_repo_head_hexsha": "c3c16839dfed0fa3ba5deabc7ecf1431280df74c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/model.jl", "max_forks_repo_name": "dataspider/momo", "max_forks_repo_head_hexsha": "c3c16839dfed0fa3ba5deabc7ecf1431280df74c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9557251908, "max_line_length": 236, "alphanum_fraction": 0.7298784215, "num_tokens": 7048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1754052486805411}} {"text": "using Unitful\nusing YAML\nusing PyCall\nusing StaticArrays\n\nmodule Calc\n include(\"Calculators/RateUncertainty.jl\")\n include(\"Calculators/ThermoUncertainty.jl\")\n include(\"Calculators/Thermo.jl\")\n include(\"Calculators/Diffusion.jl\")\n include(\"Calculators/Rate.jl\")\n include(\"Calculators/Viscosity.jl\")\n include(\"Calculators/Thermovec.jl\")\n include(\"Calculators/Ratevec.jl\")\nend\nmodule Spc\n include(\"Calculators/ThermoUncertainty.jl\")\n include(\"Calculators/Thermo.jl\")\n include(\"Calculators/Diffusion.jl\")\n include(\"Species.jl\")\nend\nmodule Rxn\n include(\"Calculators/RateUncertainty.jl\")\n include(\"Calculators/ThermoUncertainty.jl\")\n include(\"Calculators/Thermo.jl\")\n include(\"Calculators/Diffusion.jl\")\n include(\"Calculators/Rate.jl\")\n include(\"Species.jl\")\n include(\"Reaction.jl\")\nend\nmodule Solv\n include(\"Calculators/Viscosity.jl\")\n include(\"Solvent.jl\")\nend\n\n\nconst unitsdict = Dict()\nconst elementdict = Dict([1=>\"H\",6=>\"C\",8=>\"O\",7=>\"N\",17=>\"Cl\",16=>\"S\",18=>\"Ar\",10=>\"Ne\",2=>\"He\",\n 15=>\"P\",9=>\"F\",35=>\"Br\",53=>\"I\",289=>\"Fl\"])\n\nconst allowedfcnlist = vcat(names(Calc),names(Spc),names(Rxn),names(Solv))\n\n\"\"\"\nZhao et al 2003\n\"\"\"\nconst mcgowanvolumes = Dict([\"H\"=> upreferred(8.71u\"mL/mol\").val, \"He\"=> upreferred(6.75u\"mL/mol\").val,\n \"C\"=> upreferred(16.35u\"mL/mol\").val, \"N\"=> upreferred(14.39u\"mL/mol\").val,\n \"O\"=> upreferred(12.43u\"mL/mol\").val, \"F\"=> upreferred(10.47u\"mL/mol\").val,\n \"Ne\"=> upreferred(8.51u\"mL/mol\").val,\"Si\"=> upreferred(26.83u\"mL/mol\").val, \"P\"=> upreferred(24.87u\"mL/mol\").val,\n \"S\"=> upreferred(22.91u\"mL/mol\").val, \"Cl\"=> upreferred(20.95u\"mL/mol\").val,\n \"Ar\"=> upreferred(18.99u\"mL/mol\").val,\"Br\"=> upreferred(26.21u\"mL/mol\").val,])\n\nfunction parseentry(q,units=nothing)\n \"\"\"\n parses single YAML lines into strings, numbers and arrays of Numbers in SI units\n \"\"\"\n if isa(q,String)\n q = parsestring(q)\n end\n\n if isa(q,String)\n return q\n elseif isa(q,Quantity)\n return upreferred(q).val\n elseif isa(q,Number)\n if units == nothing\n return q\n else\n return upreferred(Quantity(q,units)).val\n end\n elseif isa(q,AbstractArray)\n if units == nothing\n if typeof(q[1]) <: AbstractArray\n return convert(Array,hcat(q...)')\n else\n return q\n end\n else\n if typeof(q[1]) <: AbstractArray\n return convert(Array,hcat(upreferred(Quantity(q,units)).val...)')\n else\n return upreferred(Quantity(q,units)).val\n end\n end\n elseif isa(q,Dict)\n return q\n else\n tq = typeof(q)\n throw(error(\"unable to parse $q of type $tq\"))\n end\n\nend\nexport parseentry\n\nfunction parsestring(s)\n \"\"\"\n Detects if a given string is actually a quantity input using metaprogramming\n the string is parsed by julia's parser and then analyzed to check if it is in\n the format of a quantity input\n \"\"\"\n try\n ex = Meta.parse(s)\n if !isa(ex,Symbol) && !isa(ex,String) && length(ex.args) == 3 && ex.args[1] == :* &&\n (isa(ex.args[2],Number) || (ex.args[2].head == :vec && all([isa(x,Number) for x in ex.args[2].args]))) &&\n ex.args[3].args[1] == Symbol(\"@u_str\") &&\n isa(ex.args[3].args[2],LineNumberNode) && ex.args[3].args[2].line == 1 &&\n ex.args[3].args[2].file == :none && isa(ex.args[3].args[3],String)\n return eval(ex)\n else\n return s\n end\n catch\n return s\n end\nend\nexport parsestring\n\nfunction getatomdictfromrdkit(mol)\n \"\"\"\n retrives the number of each type of atom and the number of bonds of an rdkit molecule\n \"\"\"\n atmD = Dict{String,Int64}()\n for atm in mol.GetAtoms()\n v = elementdict[atm.GetAtomicNum()]\n if v in keys(atmD)\n atmD[v] += 1\n else\n atmD[v] = 1\n end\n end\n nbonds = length(mol.GetBonds())\n return atmD,nbonds\nend\nexport getatomdictfromrdkit\n\ngetatomdictsmiles(smiles) = getatomdictfromrdkit(Chem.AddHs(Chem.MolFromSmiles(smiles)))\nexport getatomdictsmiles\ngetatomdictinchi(inchi) = getatomdictfromrdkit(Chem.AddHs(Chem.MolFromInchi(inchi)))\nexport getatomdictinchi\n\nfunction getspeciesradius(atomdict::Dict{String,Int64},nbonds::Int64)\n \"\"\"\n estimates the McGowan radius by calculating the McGowan Volume\n from the number of each type of atom and the number of bonds\n as described in Zhao et al. 2003\n \"\"\"\n Vtot = 0.0\n for (atm,n) in atomdict\n Vtot += n*mcgowanvolumes[atm]\n end\n Vtot -= nbonds*upreferred(6.56u\"mL/mol\").val\n V = Vtot/Na\n r = (0.75/Base.pi*V)^(1.0/3.0)\n return r\nend\nexport getspeciesradius\n\nfunction fcndict2obj(d::T,ymlunitsdict::Q) where {T,Q<:Any}\n \"\"\"\n constructs an object from a dictionary by recursively constructing\n the objects in its fields\n the dictionary entry for \"type\" denotes the object being constructed\n which must be in the allowedfcnlist\n \"\"\"\n strfcn = d[\"type\"]\n fcn = Symbol(strfcn)\n @assert fcn in allowedfcnlist fcn\n kwexprs = Array{Expr,1}()\n for (key,val) in d\n if key == \"type\"\n continue\n end\n if isa(val,AbstractDict) && \"type\" in keys(val)\n val = fcndict2obj(val,ymlunitsdict)\n elseif isa(val,AbstractArray) && typeof(val).parameters[1] <: AbstractDict\n val = [fcndict2obj(x,ymlunitsdict) for x in val]\n else\n if (strfcn,key) in keys(unitsdict)\n if unitsdict[(strfcn,key)] in keys(ymlunitsdict)\n val = parseentry(val,ymlunitsdict[unitsdict[(strfcn,key)]])\n else\n val = parseentry(val)\n end\n else\n #@warn(\"assuming values for $strfcn,$key are in SI units\")\n val = parseentry(val)\n end\n end\n kwexpr = Expr(:kw,Symbol(key),val)\n push!(kwexprs,kwexpr)\n end\n ex = Expr(:call,fcn,Expr(:parameters,kwexprs...))\n return eval(ex)\nend\nexport fcndict2obj\n\n\"\"\"\nexamines the input file and parses as appropriate\nfor chemkin (.inp files) with or without species dictionaries\ncalls rmgpy to convert it to yml and then parses the yml file\nfor rms (.rms, .yml, .rmg) it parses it directly\n\"\"\"\nfunction readinput(fname::String;spcdict::String=\"\",output::String=\"chem.rms\")\n extension = split(fname,\".\")[end]\n if extension in [\"rms\",\"yml\",\"rmg\"]\n return readinputyml(fname)\n elseif extension in [\"inp\"]\n if spcdict == \"\"\n convertchemkin2yml(fname,output=output)\n else\n convertchemkin2yml(fname,spcdictpath=spcdict,output=output)\n end\n return readinputyml(output)\n else\n throw(error(\"file extension $extension not understood, use .inp for chemkin files or .rms for rms yaml files\"))\n end\nend\nexport readinput\n\n\"\"\"\nparses a YAML input file into a dictionary containing\npartitions of Species and Reaction objects\n\"\"\"\nfunction readinputyml(fname::String)\n D = YAML.load(open(fname))\n outdict = Dict()\n\n #Units\n ymlunitsdict=D[\"Units\"] #for now don't use\n\n #Solvents\n if \"Solvents\" in keys(D)\n s = D[\"Solvents\"]\n for sol in s\n sol[\"type\"] = \"Solvent\"\n end\n solvents = [fcndict2obj(q,ymlunitsdict) for q in s]\n outdict[\"Solvents\"] = solvents\n end\n\n #phases\n spcindex = 1\n spcdict = Dict()\n for p in D[\"Phases\"]\n name = p[\"name\"]\n spclist = Array{Species,1}()\n for d in p[\"Species\"]\n d[\"index\"] = spcindex\n spcindex += 1\n spcname = d[\"name\"]\n #attempt to generate molecular information from rdkit if possible\n if !(\"atomnums\" in keys(d)) || !(\"bondnum\" in keys(d))\n if \"smiles\" in keys(d)\n try\n d[\"atomnums\"],d[\"bondnum\"] = getatomdictsmiles(d[\"smiles\"])\n catch\n @warn(\"failed to generate molecular information from smiles for species $spcname\")\n end\n elseif \"inchi\" in keys(d)\n try\n d[\"atomnums\"],d[\"bondnum\"] = getatomdictinchi(d[\"inchi\"])\n catch\n @warn(\"failed to generate molecular information from inchi for species $spcname\")\n end\n end\n end\n #if diffusion model is not present and we can calculate molecular radius and stokesdiffusivity\n if !(\"diffusion\" in keys(d)) && \"atomnums\" in keys(d) && \"bondnum\" in keys(d)\n try\n diffD = Dict()\n diffD[\"type\"] = \"StokesDiffusivity\"\n diffD[\"r\"] = getspeciesradius(d[\"atomnums\"],d[\"bondnum\"])\n d[\"diffusion\"] = diffD\n if !(\"radius\" in keys(d))\n d[\"radius\"] = diffD[\"r\"]\n end\n catch\n @warn(\"failed to generate StokesDiffusivity model for species $spcname\")\n end\n end\n\n spc = fcndict2obj(d,ymlunitsdict)\n push!(spclist,spc)\n spcdict[spc.name] = (spc,p[\"name\"])\n end\n outdict[name] = Dict()\n outdict[name][\"Species\"] = spclist\n outdict[name][\"Reactions\"] = Array{ElementaryReaction,1}()\n end\n\n #reactions\n rxnindex = 1\n for rxn in D[\"Reactions\"]\n phs = Array{String,1}()\n rxn[\"reactants\"] = convert(Array{Any},rxn[\"reactants\"])\n rxn[\"index\"] = rxnindex\n rxnindex += 1\n for (i,item) in enumerate(rxn[\"reactants\"])\n spc,ph = spcdict[item]\n push!(phs,ph)\n rxn[\"reactants\"][i] = spc\n end\n rxn[\"products\"] = convert(Array{Any},rxn[\"products\"])\n for (i,item) in enumerate(rxn[\"products\"])\n spc,ph = spcdict[item]\n push!(phs,ph)\n rxn[\"products\"][i] = spc\n end\n rxn[\"reactants\"] = [r for r in rxn[\"reactants\"]]\n rxn[\"reactants\"] = SVector(rxn[\"reactants\"]...)\n rxn[\"products\"] = [r for r in rxn[\"products\"]]\n rxn[\"products\"] = SVector(rxn[\"products\"]...)\n rxn[\"reactantinds\"] = [r.index for r in rxn[\"reactants\"]]\n rxn[\"reactantinds\"] = SVector(rxn[\"reactantinds\"]...)\n rxn[\"productinds\"] = [r.index for r in rxn[\"products\"]]\n rxn[\"productinds\"] = SVector(rxn[\"productinds\"]...)\n if \"efficiencies\" in keys(rxn[\"kinetics\"])\n rxn[\"kinetics\"][\"efficiencies\"] = Dict{Int64,Float64}([spcdict[name][1].index=>val-1.0 for (name,val) in rxn[\"kinetics\"][\"efficiencies\"]]) #in RMS we correct [M] rather than calculate it so we subtract 1\n end\n r = fcndict2obj(rxn,ymlunitsdict)\n unique!(phs)\n if length(phs) == 1\n push!(outdict[phs[1]][\"Reactions\"],r)\n else\n if Set(phs) in keys(outDict)\n push!(outdict[Set(phs)],r)\n else\n outdict[Set(phs)]=[r]\n end\n end\n end\n\n return outdict\nend\n\nexport readinputyml\n", "meta": {"hexsha": "538c30ab82fadd1c9a695669b0c9355b4f3378b3", "size": 11267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Parse.jl", "max_stars_repo_name": "ChrisRackauckas/ReactionMechanismSimulator.jl", "max_stars_repo_head_hexsha": "91420ccbd633d0caa1e0dbb673fdbcee92a6e936", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Parse.jl", "max_issues_repo_name": "ChrisRackauckas/ReactionMechanismSimulator.jl", "max_issues_repo_head_hexsha": "91420ccbd633d0caa1e0dbb673fdbcee92a6e936", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-17T19:33:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T19:34:58.000Z", "max_forks_repo_path": "src/Parse.jl", "max_forks_repo_name": "ChrisRackauckas/ReactionMechanismSimulator.jl", "max_forks_repo_head_hexsha": "91420ccbd633d0caa1e0dbb673fdbcee92a6e936", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4332344214, "max_line_length": 215, "alphanum_fraction": 0.5754859324, "num_tokens": 3177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.17517681226241266}} {"text": "export iauAtoc13\n\"\"\"\nObserved place at a groundbased site to to ICRS astrometric RA,Dec.\nThe caller supplies UTC, site coordinates, ambient air conditions\nand observing wavelength.\n\nThis function is part of the International Astronomical Union's\nSOFA (Standards of Fundamental Astronomy) software collection.\n\nStatus: support function.\n\nGiven:\n type char[] type of coordinates - \"R\", \"H\" or \"A\" (Notes 1,2)\n ob1 double observed Az, HA or RA (radians; Az is N=0,E=90)\n ob2 double observed ZD or Dec (radians)\n utc1 double UTC as a 2-part...\n utc2 double ...quasi Julian Date (Notes 3,4)\n dut1 double UT1-UTC (seconds, Note 5)\n elong double longitude (radians, east +ve, Note 6)\n phi double geodetic latitude (radians, Note 6)\n hm double height above ellipsoid (m, geodetic Notes 6,8)\n xp,yp double polar motion coordinates (radians, Note 7)\n phpa double pressure at the observer (hPa = mB, Note 8)\n tc double ambient temperature at the observer (deg C)\n rh double relative humidity at the observer (range 0-1)\n wl double wavelength (micrometers, Note 9)\n\nReturned:\n rc,dc double ICRS astrometric RA,Dec (radians)\n\nReturned (function value):\n int status: +1 = dubious year (Note 4)\n 0 = OK\n -1 = unacceptable date\n\nNotes:\n\n 1. \"Observed\" Az,ZD means the position that would be seen by a\n perfect geodetically aligned theodolite. (Zenith distance is\n used rather than altitude in order to reflect the fact that no\n allowance is made for depression of the horizon.) This is\n related to the observed HA,Dec via the standard rotation, using\n the geodetic latitude (corrected for polar motion), while the\n observed HA and RA are related simply through the Earth rotation\n angle and the site longitude. \"Observed\" RA,Dec or HA,Dec thus\n means the position that would be seen by a perfect equatorial\n with its polar axis aligned to the Earth's axis of rotation.\n\n 2. Only the first character of the type argument is significant.\n \"R\" or \"r\" indicates that ob1 and ob2 are the observed right\n ascension and declination; \"H\" or \"h\" indicates that they are\n hour angle (west +ve) and declination; anything else (\"A\" or\n \"a\" is recommended) indicates that ob1 and ob2 are azimuth\n (north zero, east 90 deg) and zenith distance.\n\n 3. utc1+utc2 is quasi Julian Date (see Note 2), apportioned in any\n convenient way between the two arguments, for example where utc1\n is the Julian Day Number and utc2 is the fraction of a day.\n\n However, JD cannot unambiguously represent UTC during a leap\n second unless special measures are taken. The convention in the\n present function is that the JD day represents UTC days whether\n the length is 86399, 86400 or 86401 SI seconds.\n\n Applications should use the function iauDtf2d to convert from\n calendar date and time of day into 2-part quasi Julian Date, as\n it implements the leap-second-ambiguity convention just\n described.\n\n 4. The warning status \"dubious year\" flags UTCs that predate the\n introduction of the time scale or that are too far in the\n future to be trusted. See iauDat for further details.\n\n 5. UT1-UTC is tabulated in IERS bulletins. It increases by exactly\n one second at the end of each positive UTC leap second,\n introduced in order to keep UT1-UTC within +/- 0.9s. n.b. This\n practice is under review, and in the future UT1-UTC may grow\n essentially without limit.\n\n 6. The geographical coordinates are with respect to the WGS84\n reference ellipsoid. TAKE CARE WITH THE LONGITUDE SIGN: the\n longitude required by the present function is east-positive\n (i.e. right-handed), in accordance with geographical convention.\n\n 7. The polar motion xp,yp can be obtained from IERS bulletins. The\n values are the coordinates (in radians) of the Celestial\n Intermediate Pole with respect to the International Terrestrial\n Reference System (see IERS Conventions 2003), measured along the\n meridians 0 and 90 deg west respectively. For many\n applications, xp and yp can be set to zero.\n\n 8. If hm, the height above the ellipsoid of the observing station\n in meters, is not known but phpa, the pressure in hPa (=mB), is\n available, an adequate estimate of hm can be obtained from the\n expression\n\n hm = -29.3 * tsl * log ( phpa / 1013.25 );\n\n where tsl is the approximate sea-level air temperature in K\n (See Astrophysical Quantities, C.W.Allen, 3rd edition, section\n 52). Similarly, if the pressure phpa is not known, it can be\n estimated from the height of the observing station, hm, as\n follows:\n\n phpa = 1013.25 * exp ( -hm / ( 29.3 * tsl ) );\n\n Note, however, that the refraction is nearly proportional to\n the pressure and that an accurate phpa value is important for\n precise work.\n\n 9. The argument wl specifies the observing wavelength in\n micrometers. The transition from optical to radio is assumed to\n occur at 100 micrometers (about 3000 GHz).\n\n 10. The accuracy of the result is limited by the corrections for\n refraction, which use a simple A*tan(z) + B*tan^3(z) model.\n Providing the meteorological parameters are known accurately and\n there are no gross local effects, the predicted astrometric\n coordinates should be within 0.05 arcsec (optical) or 1 arcsec\n (radio) for a zenith distance of less than 70 degrees, better\n than 30 arcsec (optical or radio) at 85 degrees and better\n than 20 arcmin (optical) or 30 arcmin (radio) at the horizon.\n\n Without refraction, the complementary functions iauAtco13 and\n iauAtoc13 are self-consistent to better than 1 microarcsecond\n all over the celestial sphere. With refraction included,\n consistency falls off at high zenith distances, but is still\n better than 0.05 arcsec at 85 degrees.\n\n 11. It is advisable to take great care with units, as even unlikely\n values of the input parameters are accepted and processed in\n accordance with the models used.\n\nCalled:\n iauApco13 astrometry parameters, ICRS-observed\n iauAtoiq quick observed to CIRS\n iauAticq quick CIRS to ICRS\n\nThis revision: 2013 October 9\n\nSOFA release 2018-01-30\n\nCopyright (C) 2018 IAU SOFA Board. See notes at end.\n\"\"\"\n# int iauAtoc13(const char *type, double ob1, double ob2,\n# double utc1, double utc2, double dut1,\n# double elong, double phi, double hm, double xp, double yp,\n# double phpa, double tc, double rh, double wl,\n# double *rc, double *dc)\n\nfunction iauAtoc13(type_::Char, ob1::Real, ob2::Real,\n utc1::Real, utc2::Real, dut1::Real,\n elong::Real, phi::Real, hm::Real, xp::Real, yp::Real,\n phpa::Real, tc::Real, rh::Real, wl::Real)\n\n # Allocate return values\n ref_type_ = Ref{UInt8}(convert(UInt8, type_))\n ref_rc = Ref{Float64}(0.0)\n ref_dc = Ref{Float64}(0.0)\n\n status = ccall((:iauAtoc13, libsofa_c), Cint, \n (Ref{UInt8}, Cdouble, Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble, Ref{Cdouble}, Ref{Cdouble}), \n ref_type_, convert(Float64, ob1), convert(Float64, ob2),\n convert(Float64, utc1), convert(Float64, utc2),\n convert(Float64, dut1), convert(Float64, elong),\n convert(Float64, phi), convert(Float64, hm),\n convert(Float64, xp), convert(Float64, yp),\n convert(Float64, phpa), convert(Float64, tc),\n convert(Float64, rh), convert(Float64, wl),\n ref_rc, ref_dc)\n\n return status, ref_rc[], ref_dc[]\nend", "meta": {"hexsha": "466dcc4e7b400cf141538d46a43652afae284422", "size": 7713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atoc13.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_stars_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-12-11T05:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T03:10:26.000Z", "max_issues_repo_path": "src/atoc13.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_issues_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-02T00:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T06:42:23.000Z", "max_forks_repo_path": "src/atoc13.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SOFA.jl-ad3d3fd0-b5f2-51ee-b274-8cdbe62317e2", "max_forks_repo_head_hexsha": "528ba57a011551cac11c62712e69d03da6bebdef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:41:12.000Z", "avg_line_length": 44.0742857143, "max_line_length": 74, "alphanum_fraction": 0.7029690134, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.17486590310124908}} {"text": "# ==================================================================================================================\nfunction solveStokes_penalty( U, P, θ, r, Ucartesian,Upolar, g, ρ, η, 𝓒,\n theta, rr, TT,\n ∂Ωu, ufix, ifree,\n PhaseID, EL2NOD, EL2NODP,\n KKidx, GGidx, invMMidx,\n to)\n @timeit to \"Stokes\" begin\n @timeit to \"Assembly\" KK, GG, invMM, Rhs =\n assembly_stokes_penalty(EL2NOD, EL2NODP, theta, rr, g, ρ, η, 𝓒, PhaseID, KKidx, GGidx, invMMidx)\n @timeit to \"BCs\" begin\n KK, GG, Rhs = _prepare_matrices_penalty(KK, GG, Rhs, TT)\n U, Rhs = _apply_bcs(U,KK,Rhs,∂Ωu,ufix)\n end\n @timeit to \"Solve\" U, P = PowellHesteness(U, P, KK, invMM, GG, Rhs, ifree)\n @timeit to \"Remove net rotation\" U, Ucart, Upolar, Ucartesian = updatevelocity(U,Ucartesian, Upolar, θ, r,TT)\n # @timeit to \"Remove nullspace\" U, Ucart, Upolar, Ucartesian = updatevelocity2(U, Ucartesian, Upolar, ρ, EL2NOD, TT, theta, rr, r)\n\n end\n return Ucartesian,Upolar,U,Ucart,P,to\nend\n# ==================================================================================================================\n\n@inline function _apply_bcs_penalty(U, KK, Rhs, ∂Ω, vfix)\n U[∂Ω] = vfix # write prescribed temperature values\n Rhs -= KK[:,∂Ω] * vfix\n return U,Rhs\nend\n\n@inline function _prepare_matrices_penalty(KK, GG, Fb,TT)\n \n dropzeros!(GG) \n KK = SparseMatrixCSC(Symmetric(KK,:L))\n dropzeros!(KK)\n transTT = SparseMatrixCSC(TT')\n KK = transTT*KK*TT\n GG = transTT*GG\n Fb = transTT*Fb\n KK = SparseMatrixCSC(Symmetric(KK,:L))\n return KK,GG,Fb\nend\n\nfunction assembly_stokes_penalty(EL2NOD, EL2NODP, theta, r, g, ρ, η, 𝓒, PhaseID, KKidx, GGidx, invMMidx) \n penalty = 1e6\n # ============================================ MODEL AND BLOCKING PARAMETERS\n ndim = 2\n # nvert = 3\n # EL2NOD0 = deepcopy(EL2NOD)\n nnodel = size(EL2NOD,1)\n nel = size(EL2NOD,2)\n nelblk = min(nel, 1200)\n nblk = ceil(Int,nel/nelblk)\n il = one(nelblk); iu = nelblk\n # =========== PREPARE INTEGRATION POINTS & DERIVATIVES wrt LOCAL COORDINATES\n nip = 6\n # nUdof = ndim*maximum(EL2NOD)\n # nPdof = maximum(EL2NODP)\n nUdofel = ndim * nnodel\n nPdofel = size(EL2NODP,1)\n ni, nn, nnP, nn3 = Val(nip), Val(nnodel), Val(3), Val(3)\n N,dNds,_,w_ip = _get_SF(ni,nn)\n NP,_,_,_ = _get_SF(ni,nnP)\n N3,_,dN3ds,_ = _get_SF(ni,nn3)\n # ============================================================= ALLOCATIONS\n detJ_PL = Vector{Float64}(undef,nelblk)\n R_31 = similar(detJ_PL) # = detJa_PL*dxi_dth\n R_21 = similar(detJ_PL) # = -detJa_PL*deta_dth\n Th_31 = similar(detJ_PL) # = -detJa_PL*dxi_dr\n Th_21 = similar(detJ_PL) # = detJa_PL*deta_dr\n # NxN = Array{Float64,2}(undef,3,3)\n # ang_dist = Array{Float64,2}(undef,3,nelblk)\n # VCOORD_th = similar(ang_dist)\n # VCOORD_r = similar(ang_dist)\n dNdx = Array{Float64,2}(undef,nelblk,size(dNds[1],2))\n dNdy = similar(dNdx)\n ω = Vector{Float64}(undef,Int(nelblk))\n invJx_double = Array{Float64,2}(undef,Int(nelblk),ndim) # storage for x-components of Jacobi matrix\n invJz_double = similar(invJx_double) # storage for z-components of Jacobi matrix \n # ==================================== STORAGE FOR DATA OF ELEMENTS IN BLOCK\n K_blk = fill(0.0, nelblk, Int(nUdofel*(nUdofel+1)/2))\n # symmetric stiffness matrix, dim=vel dofs, but only upper triangle\n M_blk = fill(0.0, nelblk, Int(nPdofel*(nPdofel+1)/2))\n # symmetric mass matrix, dim=pressure nodes, but only upper triangle\n G_blk = fill(0.0, nelblk, nPdofel*nUdofel)\n # asymmetric gradient matrix, vel dofs x pressure nodes\n Fb_blk = fill(0.0, nelblk, nUdofel)\n # storage for entries in bouyancy force vector \n invM_blk = fill(0.0, nelblk, nPdofel*nPdofel)\n invMG_blk = fill(0.0, nelblk, nPdofel*nUdofel)\n\n # ==================================== STORAGE FOR DATA OF ALL ELEMENT MATRICES/VECTORS\n K_all = Array{Float64,2}(undef, Int(nUdofel*(nUdofel+1)/2),nel)\n M_all = Array{Float64,2}(undef, Int(nPdofel*(nPdofel+1)/2),nel)\n G_all = Array{Float64,2}(undef, nUdofel*nPdofel,nel)\n Fb_all = Array{Float64,2}(undef, nUdofel,nel)\n invM_all = Array{Float64,2}(undef, nPdofel*nPdofel,nel)\n\n #=========================================================================\n BLOCK LOOP - MATRIX COMPUTATION\n =========================================================================#\n for ib in 1:nblk\n #===========================================================================\n CALCULATE JACOBIAN, ITS DETERMINANT AND INVERSE\n ===========================================================================#\n \"\"\"\n NOTE: For triangular elements with non-curved edges the Jacobian is\n the same for all integration points (i.e. calculated once\n before the integration loop). Further, linear 3-node shape are\n sufficient to calculate the Jacobian.\n \"\"\"\n # idx = @views EL2NOD[1:nvert,il:iu]\n # VCOORD_th = reshape(theta[idx],nvert,nelblk)\n # VCOORD_r = reshape(r[idx],nvert,nelblk)\n VCOORD_th = view(theta,:,il:iu)\n VCOORD_r = view(r,:,il:iu)\n\n J_th = (VCOORD_th'*dN3ds')\n J_r = (VCOORD_r'*dN3ds')\n\n _fill_R_J!(J_th,J_r,VCOORD_th,VCOORD_r,\n R_31,R_21,Th_31,Th_21,detJ_PL)\n\n # ------------------------ NUMERICAL INTEGRATION LOOP (GAUSS QUADRATURE) \n _ip_loop_penalty!(K_blk, M_blk, G_blk, Fb_blk, \n g, η, 𝓒, ρ, EL2NOD, PhaseID,il:iu,\n dNds, w_ip, nip, nnodel, nelblk, nPdofel,nUdofel,\n dNdx,dNdy,N,N3,NP,\n ω,invJx_double, invJz_double, detJ_PL,\n R_21,R_31,Th_21,Th_31,\n VCOORD_th,VCOORD_r)\n\n _invM!(invM_blk, M_blk, detJ_PL)\n\n _fill_invMxG!(invMG_blk, invM_blk, G_blk, nPdofel, nUdofel)\n\n _fill_KplusGxinvMxGt(K_blk, invMG_blk, G_blk, nPdofel, nUdofel, penalty)\n\n # --------------------------------------- WRITE DATA INTO GLOBAL STORAGE\n @views begin\n K_all[:,il:iu] .= K_blk'\n G_all[:,il:iu] .= G_blk'\n M_all[:,il:iu] .= M_blk'\n Fb_all[:,il:iu] .= Fb_blk'\n invM_all[:,il:iu] .= invM_blk'\n end\n \n # -------------------------------------------------- RESET BLOCK MATRICES\n fill!(K_blk,0.0)\n fill!(G_blk,0.0)\n fill!(M_blk,0.0)\n fill!(Fb_blk,0.0)\n fill!(invM_blk,0.0)\n fill!(invMG_blk,0.0)\n \n # -------------------------------- READJUST START, END AND SIZE OF BLOCK\n il += nelblk;\n if ib == nblk-1\n # ------------ Account for different number of elements in last block\n nelblk = nel - il + 1 # new block size\n # --------------------------------- Reallocate at blocks at the edge \n detJ_PL = Vector{Float64}(undef,nelblk)\n R_31 = similar(detJ_PL) \n R_21 = similar(detJ_PL) \n Th_31 = similar(detJ_PL) \n Th_21 = similar(detJ_PL) \n # ang_dist = Array{Float64,2}(undef,3,nelblk)\n dNdx = Array{Float64,2}(undef,nelblk,size(dNds[1],2))\n dNdy = similar(dNdx)\n K_blk = fill(0.0, nelblk, Int(nUdofel*(nUdofel+1)/2))\n M_blk = fill(0.0, nelblk, Int(nPdofel*(nPdofel+1)/2))\n G_blk = fill(0.0, nelblk, nPdofel*nUdofel) \n Fb_blk = fill(0.0, nelblk, nUdofel)\n ω = Vector{Float64}(undef,Int(nelblk))\n invJx_double = Array{Float64,2}(undef,Int(nelblk),ndim) \n invJz_double = similar(invJx_double) \n invM_blk = fill(0.0, nelblk, nPdofel*nPdofel)\n invMG_blk = fill(0.0, nelblk, nPdofel*nUdofel)\n end\n iu += nelblk\n\n end # end block loop\n \n # #===========================================================================\n # ASSEMBLY OF GLOBAL SPARSE MATRICES AND RHS-VECTOR\n # ===========================================================================#\n KK, GG, invMM, Fb = \n _create_stokes_matrices_penalty(EL2NOD, nUdofel, ndim,\n KKidx, GGidx, invMMidx,\n K_all, G_all, invM_all, Fb_all)\n\n return KK, GG, invMM, Fb\n \nend # END OF ASSEMBLY FUNCTION\n\nfunction _ip_loop_penalty!( K_blk, M_blk, G_blk, Fb_blk, \n g, η, 𝓒, ρ, EL2NOD, PhaseID,els,\n dNds, w_ip, nip, nnodel, nelblk, nPdofel,nUdofel,\n dNdx,dNdy,N,N3,NP,\n ω,invJx_double, invJz_double, detJ_PL,\n R_21,R_31,Th_21,Th_31,\n VCOORD_th,VCOORD_r)\n\n sin_ip = similar(detJ_PL)\n cos_ip = similar(detJ_PL)\n\n for ip=1:nip\n\n N_ip = N3[ip]\n # NP_blk = repeat(NP[ip],nelblk,1)\n NP_blk = NP[ip].*ones(nelblk)\n\n #=======================================================================\n PROPERTIES OF ELEMENTS AT ip-TH EVALUATION POINT\n =======================================================================#\n Dens_blk = _element_density(ρ,EL2NOD,PhaseID,els,NP[ip])\n Visc_blk = _element_viscosity(η,EL2NOD,PhaseID,els,NP[ip])\n # Gravitational force at ip-th integration point\n Fg_blk = g * Dens_blk \n\n #==========================================================================================================\n CALCULATE 2nd JACOBIAN (FROM CARTESIAN TO POLAR COORDINATES --> curved edges), ITS DETERMINANT AND INVERSE\n ===========================================================================================================\n NOTE: For triangular elements with curved edges the Jacobian needs to be computed at each integration\n point (inside the integration loop). =#\n th_ip = VCOORD_th'*N_ip'\n r_ip = VCOORD_r'*N_ip'\n\n _derivative_weights!(dNds[ip],ω,dNdx,dNdy,w_ip[ip],th_ip,r_ip,sin_ip,cos_ip,\n R_21,R_31,Th_21,Th_31,detJ_PL,invJx_double,invJz_double)\n \n _fill_Kblk!(K_blk, 𝓒, Visc_blk, Val(η), ω, dNdx, dNdy, nnodel, els, ip)\n\n _fill_Gblk!(G_blk, NP_blk, ω, dNdx, dNdy, nPdofel,nUdofel,nnodel)\n\n _fill_Mblk_penalty!(M_blk, NP_blk, ω, nPdofel)\n\n _fill_Fbblk!(Fb_blk,Fg_blk, N[ip],\n ω, sin_ip,cos_ip,nUdofel)\n\n end # end integration point loop\nend # ENF OF IP_LOOP FUNCTION\n\n@inline function _fill_Mblk_penalty!(M_blk, NP_blk, ω, nPdofel)\n # \"weight\" divided by viscosity at integration point in all elements\n indx = 1;\n for i in 1:nPdofel\n @inbounds @simd for j in i:nPdofel\n M_blk[:,indx] .+= ω.*view(NP_blk,:,i).*view(NP_blk,:,j)\n indx += 1\n end\n end\nend\n\n\nfunction _invM!(invM_blk, M_blk, detJ)\n TMP = 1.0./detJ\n M_blk = M_blk .* TMP\n # M_blk = M_blk .* TMP[:,ones[1,nPdofel*[nPdofel+1]/2]];\n\n # How to calculate the determinante of several symmetric 3x3 matrices:\n # det[M] = M11*M22*M33 + M12*M23*M31 + M13*M21*M32\n # - M13*M22*M31 - M12*M21*M33 - M11*M23*M32\n # written in 1-index notation:\n # = M1 *M5 *M9 + M4 *M8 *M3 + M7 *M2 *M6\n # - M7 *M5 *M3 - M4 *M2 *M9 - M1 *M8 *M6\n # considering symmetry and using lower triangular part only\n # [M4=M2, M7=M3, M8=M6]\n # = M1 *M5 *M9 + M2 *M6 *M3 + M3 *M2 *M6\n # - M3 *M5 *M3 - M2 *M2 *M9 - M1 *M6 *M6\n # and knowing where the 6 different values are stored in M_blk\n # [1-->M1, 2-->M2, 3-->M3, 4-->M5, 5-->M6, 6-->M9]\n # = M_blk1*M_blk4*M_blk6 + M_blk2*M_blk5*M_blk3 + M_blk3*M_blk2*M_blk5\n # - M_blk3*M_blk4*M_blk3 - M_blk2*M_blk2*M_blk6 - M_blk1*M_blk5*M_blk5\n # re-arranging\n # = M_blk1 * [M_blk4*M_blk6 - M_blk5*M_blk5] \n # + M_blk2 * [M_blk5*M_blk3 - M_blk2*M_blk6]\n # + M_blk3 * [M_blk2*M_blk5 - M_blk4*M_blk3]\n detM_blk = @. M_blk[:,1] * (M_blk[:,4]*M_blk[:,6] - M_blk[:,5]*M_blk[:,5]) + \n M_blk[:,2] * (M_blk[:,5]*M_blk[:,3] - M_blk[:,2]*M_blk[:,6]) + \n M_blk[:,3] * (M_blk[:,2]*M_blk[:,5] - M_blk[:,4]*M_blk[:,3])\n detM_blk ./=TMP\n\n # The determinante is used to calculate the inverse of the symmetric \n # 3x3 element mass matrices. The same logic as above is used.\n invM_blk[:,1] = @views @. (M_blk[:,4]*M_blk[:,6] - M_blk[:,5]*M_blk[:,5])/detM_blk;\n invM_blk[:,2] = @views @. (M_blk[:,5]*M_blk[:,3] - M_blk[:,2]*M_blk[:,6])/detM_blk;\n invM_blk[:,3] = @views @. (M_blk[:,2]*M_blk[:,5] - M_blk[:,4]*M_blk[:,3])/detM_blk;\n invM_blk[:,4] = @views invM_blk[:,2];\n invM_blk[:,5] = @views @. (M_blk[:,1]*M_blk[:,6] - M_blk[:,3]*M_blk[:,3])/detM_blk;\n invM_blk[:,6] = @views @. (M_blk[:,2]*M_blk[:,3] - M_blk[:,1]*M_blk[:,5])/detM_blk;\n invM_blk[:,7] = @views invM_blk[:,3];\n invM_blk[:,8] = @views invM_blk[:,6];\n invM_blk[:,9] = @views @. (M_blk[:,1]*M_blk[:,4] - M_blk[:,5]*M_blk[:,5])/detM_blk;\n\nend\n\n\nfunction _fill_invMxG!(invMG_blk, invM_blk, G_blk, nPdofel, nUdofel)\n # --------------------------invM*G'----------------------------\n for i=1:nPdofel\n for j=1:nUdofel\n for k=1:nPdofel\n invMG_blk[:,(i-1)*nUdofel+j] = @views invMG_blk[:,(i-1)*nUdofel+j] +\n invM_blk[:,(i-1)*nPdofel+k].*G_blk[:,(k-1)*nUdofel+j];\n end\n end\n end\nend\n\nfunction _fill_KplusGxinvMxGt(K_blk, invMG_blk, G_blk, nPdofel, nUdofel, penalty)\n # -----------------K = K + penalty*G*invM*G'-------------------\n indx = 1;\n for i=1:nUdofel\n for j=i:nUdofel\n for k=1:nPdofel\n K_blk[:,indx] = @views K_blk[:,indx] +\n penalty*G_blk[:,(k-1)*nUdofel+i].*invMG_blk[:,(k-1)*nUdofel+j];\n end\n indx += 1;\n end\n end\nend\n\n\n@inline function _create_stokes_matrices_penalty(EL2NOD,nUdofel,ndim,\n KKidx, GGidx, invMMidx,\n K_all, G_all, invM_all, Fb_all)\n\n nel = size(EL2NOD,2)\n \n #==========================================================================\n ASSEMBLY OF GLOBAL STIFFNESS MATRIX\n ==========================================================================#\n # convert triplet data to sparse global stiffness matrix (assembly)\n KK = sparse(KKidx._i ,KKidx._j, vec(K_all))\n\n #==========================================================================\n ASSEMBLY OF GLOBAL GRADIENT MATRIX\n ==========================================================================#\n # convert triplet data to sparse global gradient matrix (assembly)\n GG = sparse(GGidx._i ,GGidx._j ,vec(G_all))\n\n #==========================================================================\n ASSEMBLY OF GLOBAL FORCE VECTOR\n ==========================================================================#\n EL2DOF = Array{Int64}(undef,nUdofel, nel)\n @views EL2DOF[1:ndim:nUdofel,:] .= @. ndim*(EL2NOD-1)+1\n @views EL2DOF[2:ndim:nUdofel,:] .= @. ndim*(EL2NOD-1)+2\n Fb = accumarray(vec(EL2DOF),vec(Fb_all));\n\n #==========================================================================\n ASSEMBLY OF GLOBAL (1/VISCOSITY)-SCALED MASS MATRIX\n ==========================================================================#\n # convert triplet data to sparse global matrix\n invMM = sparse(invMMidx._i ,invMMidx._j , vec(invM_all))\n\n return KK, GG, invMM, Fb\n\nend\n\n# POWELL-HESTENESS SOLVER ================================================================\n@inline function PowellHesteness(U, P, KK, M⁻¹, GG, Rhs, ifree)\n \n itmax_PH = 50\n itmin_PH = 2\n # itnum = 0\n norm∇U = Vector{Float64}(undef, itmax_PH)\n\n Rhs .+= GG*P\n\n LL = factorize(KK[ifree, ifree])\n # LL = cholesky(KK[ifree, ifree])\n GGᵀ = GG'\n # Uifree = U[ifree]\n # Rhsifree = Rhs[ifree]\n penalty = 1e6\n\n for itPH = 1:itmax_PH\n @inbounds U[ifree] .= LL\\Rhs[ifree]\n ∇U = -GGᵀ*U\n # rm0space!(∇U)\n ΔP = penalty*M⁻¹*∇U\n Rhs .+= GG*ΔP\n P .+= ΔP\n # Check convergence -----------------------------------------------\n norm∇U[itPH] = mynorm(∇U)\n\n if (itPH > itmin_PH) && (norm∇U[itPH]/norm∇U[itPH-1] > 0.1)\n println(\"\\n\", itPH,\" Powell-Hesteness iterations\\n\")\n break\n end\n\n end\n\n # Ux = U[1:2:end]\n # Uz = U[2:2:end]\n # M = sum(mean(ρ[EL2NOD],dims=1)'.*area_el)\n # Ax = sum(mean(ρ[EL2NOD].*Ux[EL2NOD], dims=1)'.*area_el)\n # Az = sum(mean(ρ[EL2NOD].*Uz[EL2NOD], dims=1)'.*area_el)\n # A = @. (Ax+Az)/M\n # U .-=A \n \n return U, P\n\nend # END POWELL-HESTENESS SOLVER", "meta": {"hexsha": "bb12440bea774c4fad5697e9d9a8e1de61ca2c7a", "size": 16950, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Stokes/StokesPenalty.jl", "max_stars_repo_name": "albert-de-montserrat/Persephone", "max_stars_repo_head_hexsha": "ddd4a7029be0fa5d5cb9c9914023fe3a6fbb1907", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Stokes/StokesPenalty.jl", "max_issues_repo_name": "albert-de-montserrat/Persephone", "max_issues_repo_head_hexsha": "ddd4a7029be0fa5d5cb9c9914023fe3a6fbb1907", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Stokes/StokesPenalty.jl", "max_forks_repo_name": "albert-de-montserrat/Persephone", "max_forks_repo_head_hexsha": "ddd4a7029be0fa5d5cb9c9914023fe3a6fbb1907", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8518518519, "max_line_length": 139, "alphanum_fraction": 0.4978761062, "num_tokens": 5463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.17475744312321204}} {"text": "\"\"\"\nRepresents the processed spectral data necessary to efficiently filter-fit one or more unknown spectra.\nA `FilterFitPacket{S<:Detector, T<:AbstractFloat}` contains the data necessary to filter the unknown and to \napply pre-filtered references. The type `T <: AbstractFloat` allows you to specify the bit-depth used to\nperform subsequent calculations using this `FilterFitPacket`. `Float32` uses less memory and is a little\nfaster than `Float64`. If there are duplicate `FilteredReference` for an elemental ROI, the preference \nis for the first one. This allows you to fill in unavailable \"FilteredReference\" elemental ROIs with more \ngeneral ones.\n\"\"\"\nstruct FilterFitPacket{S<:Detector, T<:AbstractFloat}\n detector::S\n filter::TopHatFilter{T}\n references::Vector{FilteredReference{T}}\n\n function FilterFitPacket(det::S, filt::TopHatFilter{T}, refs::Vector{FilteredReference{T}}) where {S<:Detector, T<:AbstractFloat}\n # Only permit one FilteredReference for each type of label for a set of X-rays \n filtrefs = FilteredReference{T}[]\n for ref in refs\n exists = false\n for fr in filtrefs\n # If a reference already exists of this type for these X-rays reassign it\n if (typeof(fr.label) == typeof(ref.label)) && (fr.label.xrays==ref.label.xrays)\n # filtrefs[i] = ref\n exists = true\n break\n end\n end\n if !exists\n push!(filtrefs, ref)\n end\n end\n new{S,T}(det, filt, filtrefs)\n end\nend # struct\n\nfunction Base.show(io::IO, ffp::FilterFitPacket)\n xrays = join(map(r -> \"\\t$(r.label),\", ffp.references), \"\\n\")\n print(io, \"References[\\n\\t$(ffp.detector), \\n$xrays\\n]\")\nend\n\n\"\"\"\n NeXLUncertainties.asa(::Type{DataFrame}, ffp::FilterFitPacket)\n\nSummarize the `FilteredReference` structs within a `FilterFitPacket` as a `DataFrame`.\n\"\"\"\nfunction NeXLUncertainties.asa(::Type{DataFrame}, ffp::FilterFitPacket)\n function p2b(fref)\n # charonly over roi, data over ffroi\n croi = max(1,first(fref.roi)-first(fref.ffroi)+1):min(length(fref.data), last(fref.roi)-first(fref.ffroi)+1)\n @assert length(croi)==length(fref.roi)\n sum(fref.charonly) / (sum(fref.data[croi])-sum(fref.charonly))\n end \n function s2n(fref)\n croi = max(1,first(fref.roi)-first(fref.ffroi)+1):min(length(fref.data), last(fref.roi)-first(fref.ffroi)+1)\n @assert length(croi)==length(fref.roi)\n sum(fref.charonly) / sqrt(sum(fref.data[croi])-sum(fref.charonly))\n end \n DataFrame(\n :Spectrum => [ name(fr.label.spectrum) for fr in ffp.references ],\n Symbol(\"Beam Energy (keV)\") => [ get(fr.label.spectrum, :BeamEnergy, missing)/1000.0 for fr in ffp.references ],\n Symbol(\"Probe Current (nA)\") => [ get(fr.label.spectrum, :ProbeCurrent, missing) for fr in ffp.references ],\n Symbol(\"Live Time (s)\") => [ get(fr.label.spectrum, :LiveTime, missing) for fr in ffp.references ],\n :Material => [ get(fr.label.spectrum, :Composition, nothing) for fr in ffp.references],\n :Lines => [ fr.label.xrays for fr in ffp.references],\n :ROI => [ fr.roi for fr in ffp.references],\n # :FullROI => [ fr.ffroi for fr in ffp.references],\n Symbol(\"P-to-B\") => p2b.(ffp.references), \n Symbol(\"S-to-N\") => s2n.(ffp.references) \n )\nend\n\n\n\"\"\"\n missingReferences(ffp::FilterFitPacket, elms::Vector{Element}, e0::Float64, ampl=1.0e-5)\n\nReturns a `Vector{Tuple{Vector{CharXRay}, UnitRange{Int64}}}` containing the ROIs for which a \n`FilteredReference` is missing from the `FilterFitPacket`.\n\"\"\"\nfunction missingReferences(ffp::FilterFitPacket, elms::Vector{Element}, e0::Float64, ampl=1.0e-5)\n # Find all collections of X-rays for which we'll need references\n allXrays = mapreduce(elm->NeXLSpectrum.labeledextents(elm, ffp.detector, ampl, e0), append!, elms)\n # Remove those for which there are references\n filter(allXrays) do xr\n isnothing(findfirst(ref->ref.label.xrays == xr[1], ffp.references))\n end\nend\n\n\"\"\"\nReturns a tuple containing the unfiltered spectra associated with the references.\n\"\"\"\nspectra(ffp::FilterFitPacket) = (ref.label.spectrum for ref in ffp.references)\n\n\"\"\"\nA list of elements for which there are filtered references.\n\"\"\"\nNeXLCore.elms(ffp::FilterFitPacket) = union( [ element(ref.label) for ref in filter(r->r.label isa CharXRayLabel, ffp.references) ] )\n\nstruct ReferencePacket\n spectrum::Spectrum\n element::Element\n material::Material\nend\n\nBase.show(io::IO, rp::ReferencePacket) = print(io, \"ReferencePacket[$(symbol(rp.element)), $(name(rp.material)), $(name(rp.spectrum))]\")\n\n\"\"\"\n reference( elm::Element, spec::Spectrum, mat::Material=spec[:Composition]; pc = nothing, lt = nothing, e0 = nothing, coating = nothing)::ReferencePacket\n reference(els::AbstractVector{Element}, spec::Spectrum, mat::Material = spec[:Composition]; pc = nothing, lt = nothing, e0 = nothing, coating = nothing)::Vector{ReferencePacket}\n \nConstruct a `ReferencePacket` from a `Spectrum` collected from the specified `Material` for the specified `Element`.\nOften used with `references(...)` to build `FilterFitPacket`s.\n\nOptional named arguments `pc`, `lt`, `e0`, `coating` allow you to specify the probe current, live time, beam energy and\nsample coating.\n\"\"\"\nfunction reference(\n elm::Element,\n spec::Spectrum,\n mat::Material = spec[:Composition];\n pc = nothing,\n lt = nothing,\n e0 = nothing,\n coating = nothing,\n)::ReferencePacket\n if !isnothing(lt)\n @assert lt > 0.0 \"The live time must be larger than zero for $(spec[:Name]).\"\n spec[:LiveTime] = lt\n end\n if !isnothing(pc)\n @assert pc > 0.0 \"The probe current must be larger than zero for $(spec[:Name]).\"\n spec[:ProbeCurrent] = pc\n end\n if !isnothing(e0)\n @assert e0 >= 1.0e3 \"The beam energy ($(e0/1000.0)) keV is too low for $(spec[:Name]).\"\n spec[:BeamEnergy] = e0\n end\n if !isnothing(coating)\n @assert coating isa Film\n spec[:Coating] = coating\n end\n spec[:Composition] = mat\n @assert haskey(spec, :LiveTime) \"The :LiveTime property must be defined for $(spec[:Name]). (Use the `lt` keyword argument)\"\n @assert haskey(spec, :ProbeCurrent) \"The :ProbeCurrent property must be defined for $(spec[:Name]). (Use the `pc` keyword argument)\"\n @assert haskey(spec, :BeamEnergy) \"The :BeamEnergy property must be defined for $(spec[:Name]). (Use the `e0` keyword argument)\"\n @assert haskey(mat, elm) \"$(Symbol(elm)) is not present in $mat.\"\n return ReferencePacket(spec, elm, mat)\nend\n\nreference(elm::Element, filename::AbstractString, mat::Material; kwargs...) =\n reference(elm, loadspectrum(filename), mat; kwargs...)\n\nreference(elm::Element, filename::AbstractString; kwargs...) =\n reference(elm, loadspectrum(filename); kwargs...)\n\nfunction reference(\n els::AbstractVector{Element},\n spec::Spectrum,\n mat::Material = spec[:Composition];\n kwargs...)\n map(el->reference(el, spec, mat; kwargs...), els)\nend\nreference(elm::AbstractVector{Element}, filename::AbstractString, mat::Material; kwargs...) =\n reference(elm, loadspectrum(filename), mat; kwargs...)\n\n\n\"\"\"\n references(refs::AbstractVector{ReferencePacket}, det::EDSDetector)::FilterFitPacket\n references(refs::AbstractVector{ReferencePacket}, fwhm::Float64)::FilterFitPacket\n\nConstructs a FilterFitPacket from a vector of `ReferencePackets`. Each `ReferencePacket` represents a \nsingle ROI for an element. It is possible more than one `ReferencePacket` might be defined for an \nelemental ROI. In this case, the `ReferencePacket` with the lower index will take preference over\nlater ones. This allows you to fill in only the missing elemental ROIs using spectra collected from \nalternative materials. For example, a spectrum from F₂Fe is suitable for the Fe K-lines but not the \nFe L-lines. So we might specify F₂Fe first to specify the references for the Fe K-lines and then fill \nin the L-lines with a spectrum from pure Fe.\n\"\"\"\nfunction references(\n refs::AbstractVector{ReferencePacket},\n det::EDSDetector;\n ftype::Type{<:AbstractFloat} = Float64\n)::FilterFitPacket\n chcount = det.channelcount\n @assert all(length(r.spectrum) == chcount for r in refs) \"The number of spectrum channels must match the detector for all spectra.\"\n @assert length(refs) > 0 \"Please provide at least one ReferencePacket in references(...)\"\n # Build the top-hat filter for det\n ff = buildfilter(ftype, det)\n # Apply the top-hat filter to all refs. Trying to thread this fails. :-(\n frefs = mapreduce(append!, refs) do ref\n frefs = filterreference(ff, ref.spectrum, ref.element, ref.material)\n length(frefs)==0 && @warn \"Unable to create any filtered ROI references for $(ref.element) from $(name(ref.material)).\"\n frefs\n end\n return FilterFitPacket(det, ff, frefs)\nend\nreferences(refs::AbstractVector{ReferencePacket}, fwhm::Float64; ftype::Type{<:AbstractFloat}=Float64) =\n references(refs, matching(first(refs).spectrum, fwhm), ftype=ftype)\n\nfit_spectrum(spec::Spectrum, ffp::FilterFitPacket{S, T}) where { S<:Detector, T<: AbstractFloat } =\n fit_spectrum(FilteredUnknownW{T}, spec, ffp.filter, ffp.references)\n\nfit_spectrum(specs::AbstractVector{<:Spectrum}, ffp::FilterFitPacket{S, T}) where { S<:Detector, T<: AbstractFloat } =\n ThreadsX.map(spec -> fit_spectrum(FilteredUnknownW{T}, spec, ffp.filter, ffp.references), specs)\n\n\"\"\"\n fit_spectrum(spec::Spectrum, ffp::FilterFitPacket)::FilterFitResult\n fit_spectrum(specs::AbstractVector{<:Spectrum}, ffp::FilterFitPacket)::Vector{FilterFitResult}\n\nFit a `Spectrum` or a vector of `Spectrum` using the specified `FilterFitPacket`. The result is a\n`FilterFitResult` structure which contains k-ratios, residuals, etc. \n\n\n fit_spectrum(hs::HyperSpectrum, ffp::FilterFitPacket; mode::Symbol=:Fast, zero = x -> max(0.0, x))::Array{KRatios}\n\n * `mode = :Fast` - Uses precomputed, filtered \"vector\" fit method. No uncertainties are available.\n * `mode = :Intermediate` - Uses an optimized full fit without refits for negative k-ratios.\n * `mode = :Full` - Uses the full single spectrum fit algorithm including refitting when one or more k-ratio is less than zero.\n\nPerforms a filtered fit on a hyperspectrum returning an `Array{KRatios}`.\n\nSelecting a mode:\n :Fast is good for generating k-ratio maps or exploratory analysis of a k-ratio map. :Full is best when a\n quantitative map of a high count hyperspectrum is desired. Fit results for major elements are similar for\n all three but differ for minor and trace elements. Particularly when a k-ratio is slightly negative. This\n negative k-ratio can effect the other k-ratios. :Fast also works less well when many elements (>>10) (particularly\n interfering elements) are included in the fit. Unfortunately, :Intermediate and :Full slow down when many elements\n are fit - O(n(elements)²).\n\nThe following timing on a 512 x 512 x 2048 hyperspectrum fitting 21 elements with 33 distinct ROIs on a fast 6-core \nlaptop with 16 GiB memory give a relative feel for the speed of each algorithm. Yes, :Fast is approximately 30 × \nfaster than :Intermediate and used almost 80x less memory. (64-bit references, 32-bit references use about 1/2 \nthe memory and take about 4/5 the time.)\n\n| mode= | Threads |Run time (s) | Allocations | Allocated (GiB) | GC time |\n|---------------|----------|---------------|--------------|-----------------|----------|\n| :Fast | 6 | 11.4 | 2.11 M | 4.72 | 3.0% |\n| :Intermediate | 6 | 342.7 | 13.11 M | 364.4 | 4.2% |\n| :Full | 6 | 574.6 | 6.2 G | 862.9 | 5.5% |\n| :Fast | 1 | 25.5 | 2.1 M | 4.72 | 1.8% |\n| :Intermediate | 1 | 1064.6 | 13.1 M | 364.4 | 0.9% |\n| :Full | 1 | 2186.2 | 6.2 G | 862.1 | 2.8% |\n\"\"\"\nfunction fit_spectrum(\n hs::HyperSpectrum,\n ffp::FilterFitPacket{S, T};\n mode::Symbol = :Fast,\n zero = x -> max(Base.zero(T), x),\n sigma = Base.zero(T)\n)::Array{KRatios} where { S <: Detector, T <: AbstractFloat }\n @assert matches(hs[CartesianIndices(hs)[1]], ffp.detector) \"The detector for the hyper-spectrum must match the detector for the filtered references.\"\n @assert (mode==:Fast) || (mode==:Intermediate) || (mode==:Full) \"The mode argument must be :Fast, :Intermediate or :Full.\"\n if mode == :Fast\n vq = VectorQuant(ffp.references, ffp.filter)\n return fit_spectrum(hs, vq, zero)\n elseif mode == :Intermediate\n return fit_spectrum_int(hs, ffp, zero)\n elseif mode == :Full\n return fit_spectrum_full(hs, ffp, sigma)\n end\n # Should never get here...\n return Array{KRatio}[]\nend\n\nfunction fit_spectrum_int(\n hs::HyperSpectrum,\n ffp::FilterFitPacket{S, T},\n zero::Function\n)::Array{KRatios} where { S <: Detector, T <: AbstractFloat }\n unklabel = UnknownLabel(hs)\n function _tophatfilterhs(unklabel, data, thf, scale) \n @assert length(data) <= length(thf) \"The reference spectra must have more channels than the hyperspectrum data.\"\n filtered = [filtereddatum(thf, data, i) for i in eachindex(data)]\n dp = [max(x, one(T)) for x in data] # To ensure covariance isn't zero or infinite precision\n covar = [filteredcovar(thf, dp, i, i) for i in eachindex(data)]\n FilteredUnknownW{T}(unklabel, scale, 1:length(data), data, filtered, covar)\n end\n fitcontiguousx(unk, ffs, chs) = #\n _buildscale(unk, ffs) * pinv(_buildmodel(ffs, chs), rtol = convert(T, 1.0e-6)) * extract(unk,chs)\n function _filterfitx(unk, ffs, fitrois) \n Iterators.flatten(map(fitrois) do fr\n fitcontiguousx(\n unk,\n filter(ff -> length(intersect(fr, ff.ffroi)) > 0, ffs),\n fr,\n )\n end)\n end\n @assert matches(hs[CartesianIndices(hs)[1]], ffp.detector) \"The detector for the hyper-spectrum must match the detector for the filtered references.\"\n krs = zeros(Float32, length(ffp.references), size(hs)...)\n len = 1:min(depth(hs),length(ffp.filter))\n data = zeros(T, length(ffp.filter))\n fitrois = ascontiguous(map(fd -> fd.ffroi, ffp.references))\n cdata = counts(hs)\n ThreadsX.foreach(CartesianIndices(hs)) do ci\n data[len] .= T.(cdata[len,ci])\n unk = _tophatfilterhs(unklabel, data, ffp.filter, convert(T,1/dose(hs,ci)))\n krs[:, ci] .= zero.(_filterfitx(unk, ffp.references, fitrois))\n end\n return ThreadsX.map(filter(ii -> ffp.references[ii].label isa CharXRayLabel, eachindex(ffp.references))) do i\n lbl = ffp.references[i].label\n rprops = properties(spectrum(lbl))\n KRatios(xrays(lbl), properties(hs), rprops, rprops[:Composition], krs[i, :, :])\n end\nend\n\nfunction fit_spectrum_full(\n hs::HyperSpectrum,\n ffp::FilterFitPacket{S, T},\n sigma::T\n)::Array{KRatios} where { S <: Detector, T <: AbstractFloat }\n unklabel = UnknownLabel(hs)\n function _tophatfilterhs(unklabel, data, thf, scale) \n @assert length(data) <= length(thf) \"The reference spectra must have more channels than the hyperspectrum data.\"\n filtered = T[filtereddatum(thf, data, i) for i in eachindex(data)]\n dp = T[max(x, one(T)) for x in data] # To ensure covariance isn't zero or infinite precision\n covar = T[filteredcovar(thf, dp, i, i) for i in eachindex(data)]\n FilteredUnknownW{T}(unklabel, scale, 1:length(data), data, filtered, covar)\n end\n @assert matches(hs[CartesianIndices(hs)[1]], ffp.detector) \"The detector for the hyper-spectrum must match the detector for the filtered references.\"\n krs = zeros(Float32, length(ffp.references), size(hs)...)\n len = 1:depth(hs)\n data = zeros(T, length(ffp.filter))\n cdata = counts(hs)\n ThreadsX.foreach(CartesianIndices(hs)) do ci\n data[len] .= view(cdata, len, ci)\n unk = _tophatfilterhs(unklabel, data, ffp.filter, convert(T,1/dose(hs,ci)))\n uvs = _filterfit(unk, ffp.references, true)\n krs[:, ci] = map(ffp.references) do ref\n id = ref.label\n isnan(uvs, id) || (value(uvs, id) < sigma*σ(uvs, id)) ? Base.zero(eltype(krs)) : convert(eltype(krs), value(uvs, id))\n end\n end\n return ThreadsX.map(filter(ii -> ffp.references[ii].label isa CharXRayLabel, eachindex(ffp.references))) do i\n lbl = ffp.references[i].label\n rprops = properties(spectrum(lbl))\n KRatios( xrays(lbl), properties(hs), rprops, rprops[:Composition], krs[i, :, :])\n end\nend", "meta": {"hexsha": "d1864a4dc1dad39cdebbcd7ab6920cc23fbb9ce4", "size": 16838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reference.jl", "max_stars_repo_name": "NicholasWMRitchie/NeXLSpectrum", "max_stars_repo_head_hexsha": "e40990f68850fc2e732d0c6e13acdfbfbf5b1a31", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reference.jl", "max_issues_repo_name": "NicholasWMRitchie/NeXLSpectrum", "max_issues_repo_head_hexsha": "e40990f68850fc2e732d0c6e13acdfbfbf5b1a31", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reference.jl", "max_forks_repo_name": "NicholasWMRitchie/NeXLSpectrum", "max_forks_repo_head_hexsha": "e40990f68850fc2e732d0c6e13acdfbfbf5b1a31", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.8165680473, "max_line_length": 181, "alphanum_fraction": 0.6643900701, "num_tokens": 4598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.17460491136224213}} {"text": "#///////////////////////////////////////\n#// File Name: forward_backward_simulation.jl\n#// Author: Haruki Nishimura (hnishimura@stanford.edu)\n#// Date Created: 2021/01/29\n#// Description: Forward-backward simulation model for Risk Sensitive SAC\n#///////////////////////////////////////\n\nusing CUDA\nusing LinearAlgebra\nusing PyCall\nusing Random\nusing RobotOS\nimport StatsFuns: logsumexp\n\n# Simulation Parameter\nstruct SimulationParameter <: Parameter\n dtc::Float64 # Time Interval for Continuous-time Dynamics\n dto::Float64 # Time Interval for Discrete-time Dynamics\n prediction_steps::Int64 # Prediction steps for ado robots\n num_samples::Int64 # Number of samples (per ado) for ado simulation\n cost_param::CostParameter\nend\n\nfunction SimulationParameter(traj_scene_loader::TrajectronSceneLoader,\n traj_predictor::TrajectronPredictor,\n dtc::Float64, cost_param::CostParameter)\n dto = traj_scene_loader.dto;\n prediction_steps = traj_predictor.param.prediction_steps;\n num_samples = traj_predictor.param.num_samples;\n return SimulationParameter(dtc, dto, prediction_steps, num_samples,\n cost_param)\nend\n\nfunction SimulationParameter(traj_scene_loader::TrajectronSceneLoader,\n oracle_predictor::OraclePredictor,\n dtc::Float64, cost_param::CostParameter)\n dto = traj_scene_loader.dto;\n prediction_steps = oracle_predictor.param.prediction_steps;\n num_samples = 1;\n return SimulationParameter(dtc, dto, prediction_steps, num_samples,\n cost_param)\nend\n\nfunction SimulationParameter(gaussian_predictor::GaussianPredictor,\n dtc::Float64, cost_param::CostParameter)\n dto = gaussian_predictor.dto;\n prediction_steps = gaussian_predictor.param.prediction_steps;\n num_samples = gaussian_predictor.param.num_samples;\n return SimulationParameter(dtc, dto, prediction_steps, num_samples,\n cost_param)\nend\n\n# Simulated Cost Result\nmutable struct SimulationCostResult\n inst_cnt_cost_array_gpu::CuArray{Float32, 2} # instantaneous control costs: (num_controls, total_timesteps-1)\n inst_pos_cost_array_gpu::CuArray{Float32, 2} # instantaneous position costs: (num_controls, total_timesteps - 1)\n inst_col_cost_array_gpu::CuArray{Float32, 3} # instantaneous collision costs: (num_samples*num_controls, total_timesteps-1, num_ado_agents)\n\n term_pos_cost_array_gpu::CuArray{Float32, 2} # terminal position costs: (num_controls, 1)\n term_col_cost_array_gpu::CuArray{Float32, 3} # terminal collision costs: (num_samples*num_controls, 1, num_ado_agents)\nend\n\n# Simulated Cost Gradient Result\nmutable struct SimulationCostGradResult\n inst_pos_cost_grad_array_gpu::CuArray{Float32, 2} # instantaneous position cost gradients: (total_timesteps-1, 4)\n inst_col_cost_grad_array_gpu::CuArray{Float32, 4} # instantaneous collision cost gradients: (num_samples, total_timesteps-1, num_ado_agents, 4)\n\n term_pos_cost_grad_array_gpu::CuArray{Float32, 2} # terminal position cost gradients: (1, 4) array\n term_col_cost_grad_array_gpu::CuArray{Float32, 4} # terminal collision cost gradients: (num_samples, 1, num_ado_agents, 4)\nend\n\n# Simulation Result\nmutable struct SimulationResult\n u_nominal_array::Vector{Vector{Float64}} # best nominal control schedule to be used\n u_nominal_idx::Int64 # best nominal control idx\n e_state_array::Vector{RobotState} # simulation of ego robot states\n measurement_schedule::Vector{Time} # measurement schedule\n prediction_dict::Dict{String, Array{Float64, 3}} # predicted ado states (lower time resolution)\n ap_array_gpu::CuArray{Float32, 4} # predicted ado states (higher time resolution, concatenated)\n ado_ids_array::Vector{String} # correspondence between 1st dim of expanded_ap_array and ado agent id\n sampled_total_costs::Vector{Float64} # sampled total costs\n risk_val::Float64 # risk value (i.e. our objective)\n e_costate_array::Array{Float64, 3} # (4, total_timesteps, num_samples) array\n e_costate_array_constraint::Union{Nothing, Array{Float64, 3}} # nothing or (4, constraint_timesteps, num_samples) array\n sampled_total_costs_constraint::Union{Nothing, Vector{Float64}} # nothing or sampled total costs for constraint computation\n risk_constraint::Union{Nothing, Float64} # nothing or risk value for constraint computation\nend\n\n\n# Helper Functions\n# # convert array of u_array to 3-dimensional u_array\nfunction process_u_arrays(u_arrays::Vector{Vector{Vector{Float64}}})\n # u_arrays: array of length num_controls of arrays of length total_timesteps-1 of arrays of lenght 2\n num_controls = length(u_arrays)\n total_timesteps = length(u_arrays[1]) + 1\n @assert all([length(u_array) == total_timesteps - 1 for u_array in u_arrays])\n\n u_array = Array{Float64, 3}(undef, num_controls, total_timesteps - 1, 2)\n for ii = 1:num_controls\n @inbounds u_array[ii, :, :] = permutedims(hcat(u_arrays[ii]...), [2, 1]);\n end\n return u_array\nend\n\n# # Forward Simulation\nfunction simulate_forward(e_init::RobotState,\n u_array::Vector{Vector{Float64}},\n sim_param::SimulationParameter)\n e_state_array = Vector{RobotState}(undef, length(u_array) + 1);\n e_state_array[1] = e_init;\n for ii in eachindex(u_array)\n @inbounds e_state_array[ii + 1] = transition(e_state_array[ii],\n u_array[ii],\n sim_param.dtc)\n end\n return e_state_array\nend\n# # Forward Simulation (CUDA version)\nfunction simulate_forward(e_init::RobotState,\n u_array_gpu::CuArray{Float32, 3}, # multiple nominal control version\n sim_param::SimulationParameter)\n # ex_init: 4-length vector of initial ego state.\n # u_array_gpu: (num_controls, total_timesteps-1, 2) array of acceleration inputs\n out_vel = similar(u_array_gpu)\n dtc = Float32(sim_param.dtc);\n # compute velocity (Euler integration)\n CUDA.accumulate!(+, out_vel, u_array_gpu.*sim_param.dtc, dims=2);\n out_vel = cat(cu(zeros(size(u_array_gpu, 1), 1, 2)), out_vel, dims=2);\n ev_init = get_velocity(e_init);\n out_vel[:, :, 1] .+= Float32(ev_init[1]);\n out_vel[:, :, 2] .+= Float32(ev_init[2]);\n\n # compute position (Euler integration)\n out_pos = similar(u_array_gpu)\n CUDA.accumulate!(+, out_pos, out_vel[:, 1:end-1, :].*dtc, dims=2);\n out_pos = cat(cu(zeros(size(u_array_gpu, 1), 1, 2)), out_pos, dims=2);\n ep_init = get_position(e_init);\n out_pos[:, :, 1] .+= Float32(ep_init[1]);\n out_pos[:, :, 2] .+= Float32(ep_init[2]);\n\n # (num_controls, total_timesteps, 4) array\n return cat(out_pos, out_vel, dims=3)\nend\n\n# # Measurement Schedule Handler\nfunction get_measurement_schedule(w_init::WorldState, horizon::Float64,\n sim_param::SimulationParameter)\n measurement_schedule =\n Vector{Time}(undef, Int64(round(horizon/sim_param.dto, digits=6)));\n # If no measurement has been taken, assume the initial measurement time of\n # Time(a*dto) where a is the minimum integer so that a*dto > w_init.t\n if w_init.t_last_m == nothing\n a = 0;\n while a*sim_param.dto <= to_sec(w_init.t)\n a += 1;\n end\n measurement_schedule[1] = Time(a*sim_param.dto);\n else\n measurement_schedule[1] =\n w_init.t_last_m + Duration(sim_param.dto);\n end\n for ii = 2:length(measurement_schedule)\n measurement_schedule[ii] =\n measurement_schedule[ii - 1] + Duration(sim_param.dto);\n end\n return measurement_schedule\nend\nfunction get_measurement_schedule(w_init::WorldState,\n sim_param::SimulationParameter)\n measurement_schedule = Vector{Time}(undef, sim_param.prediction_steps);\n # If no measurement has been taken, assume the initial measurement time of\n # Time(a*dto) where a is the minimum integer so that a*dto > w_init.t\n if w_init.t_last_m == nothing\n a = 0;\n while a*sim_param.dto <= to_sec(w_init.t)\n a += 1;\n end\n measurement_schedule[1] = Time(a*sim_param.dto);\n else\n measurement_schedule[1] =\n w_init.t_last_m + Duration(sim_param.dto);\n end\n for ii = 2:length(measurement_schedule)\n measurement_schedule[ii] =\n measurement_schedule[ii - 1] + Duration(sim_param.dto);\n end\n return measurement_schedule\nend\n\nfunction get_target_pos_array(ex_array_gpu::AbstractArray{Float32, 3},\n w_init::WorldState,\n target_trajectory::Trajectory2D,\n sim_param::SimulationParameter)\n\n # target_pos_aray_gpu : (total_timesteps, 2)\n # ex_array_gpu : (num_controls, total_timesteps, 4)\n\n t_array = [w_init.t]\n for ii = 1:size(ex_array_gpu, 2) - 1\n push!(t_array, t_array[end] + Duration(sim_param.dtc))\n end\n\n target_pos_array = Array(transpose(hcat(map(t -> get_position(target_trajectory, t), t_array)...)));\n return target_pos_array # (total_timesteps, 2) array\nend\n\nfunction process_ap_dict(ex_array_gpu::CuArray{Float32, 3},\n w_init::WorldState,\n measurement_schedule::Vector{Time},\n prediction_dict::Dict{String, Array{Float64, 3}},\n sim_param::SimulationParameter)\n\n # prediction_dict : each value is (num_samples*num_controls, prediction_steps, 2) array\n # ap_array : (num_samples*num_controls, prediction_steps + 1, num_ado_agents, 2) array\n # time_idx_ap_array : (total_timesteps) array of time indices for referencing ap_array\n # control_idx_ex_array : (num_samples*num_controls) array of nominal control indices for referencing ex_array\n # ado_ids_array : (num_ado_agents) array of ado ids\n\n # ratio between dto and dtc\n expansion_factor = Int64(sim_param.dto/sim_param.dtc);\n # number of nominal control candidates\n num_controls = size(ex_array_gpu, 1);\n\n # total simulation timesteps\n total_timesteps = size(ex_array_gpu, 2);\n # timesteps between current and first measurement time\n init_timesteps =\n Int64(to_nsec(measurement_schedule[1] - w_init.t)/\n (sim_param.dtc*1e9));\n # timesteps between final measurement time and final e_state time\n remaining_timesteps = total_timesteps -\n (init_timesteps + expansion_factor*(sim_param.prediction_steps - 1));\n\n # time_idx_ap_array\n time_idx_ap_array = Vector{Int64}(undef, total_timesteps);\n time_idx_ap_array[1:init_timesteps] .= 1;\n time_idx_ap_array[init_timesteps+1:end-remaining_timesteps] = repeat(2:1:sim_param.prediction_steps,\n inner=expansion_factor);\n time_idx_ap_array[end-remaining_timesteps+1:end] .= sim_param.prediction_steps + 1;\n\n # control_idx_ex_array\n control_idx_ex_array = repeat(1:1:num_controls, inner=sim_param.num_samples)\n\n # ado ids\n ado_ids_array = collect(keys(prediction_dict));\n\n if length(ado_ids_array) == 0\n # if no pedestrian exists, return (num_samples*num_controls, prediction_steps + 1, 0, 2) array\n ap_array = Array{Float64, 4}(undef, sim_param.num_samples*num_controls, sim_param.prediction_steps + 1, 0, 2);\n return ap_array, time_idx_ap_array, control_idx_ex_array, ado_ids_array\n end\n\n ap_init_array = permutedims(cat([w_init.ap_dict[id] for id in ado_ids_array]..., dims=4),\n [2, 3, 4, 1]); # (1, 1, num_ado_agents, 2) array of initial ado positions\n ap_init_array = repeat(ap_init_array, inner=(sim_param.num_samples*num_controls, 1, 1, 1));\n\n ap_pred_array = permutedims(cat([prediction_dict[id] for id in ado_ids_array]..., dims=4),\n [1, 2, 4, 3]); # (num_samples*num_controls, prediction_steps, num_ado_agents, 2) array\n ap_array = cat(ap_init_array, ap_pred_array, dims=2) # (num_samples*num_controls, prediction_steps + 1, num_ado_agents, 2)\n\n return ap_array, time_idx_ap_array, control_idx_ex_array, ado_ids_array\nend\n\n# # Compute costs based on the forward simulation & predicted ado positions\nfunction compute_costs(ex_array_gpu::CuArray{Float32, 3},\n u_array_gpu::CuArray{Float32, 3},\n ap_array_gpu::CuArray{Float32, 4},\n time_idx_ap_array_gpu::CuArray{Int32, 1},\n control_idx_ex_array_gpu::CuArray{Int32, 1},\n target_pos_array_gpu::CuArray{Float32, 2},\n cost_param::CostParameter)\n if name(CuDevice(0)) == \"GeForce RTX 2080 Ti\"\n # Instataneous costs\n inst_cnt_cost_array_gpu = instant_control_cost(u_array_gpu, cost_param, threads=(16, 64));\n inst_pos_cost_array_gpu = instant_position_cost(ex_array_gpu, target_pos_array_gpu, cost_param, threads=(16, 64));\n inst_col_cost_array_gpu = instant_collision_cost(ex_array_gpu, ap_array_gpu,\n time_idx_ap_array_gpu, control_idx_ex_array_gpu,\n cost_param, threads=(64, 4, 4));\n # Terminal costs\n term_pos_cost_array_gpu = terminal_position_cost(ex_array_gpu, target_pos_array_gpu, cost_param, threads=(1024, 1));\n term_col_cost_array_gpu = terminal_collision_cost(ex_array_gpu, ap_array_gpu,\n time_idx_ap_array_gpu, control_idx_ex_array_gpu,\n cost_param, threads=(128, 1, 8));\n else\n # Instataneous costs\n inst_cnt_cost_array_gpu = instant_control_cost(u_array_gpu, cost_param);\n inst_pos_cost_array_gpu = instant_position_cost(ex_array_gpu, target_pos_array_gpu, cost_param);\n inst_col_cost_array_gpu = instant_collision_cost(ex_array_gpu, ap_array_gpu,\n time_idx_ap_array_gpu, control_idx_ex_array_gpu,\n cost_param);\n # Terminal costs\n term_pos_cost_array_gpu = terminal_position_cost(ex_array_gpu, target_pos_array_gpu, cost_param);\n term_col_cost_array_gpu = terminal_collision_cost(ex_array_gpu, ap_array_gpu,\n time_idx_ap_array_gpu, control_idx_ex_array_gpu,\n cost_param);\n end\n\n return SimulationCostResult(inst_cnt_cost_array_gpu, inst_pos_cost_array_gpu,\n inst_col_cost_array_gpu, term_pos_cost_array_gpu,\n term_col_cost_array_gpu)\nend\n\n# # Integrate all the costs over horizon, returning sampled total costs and the risk value\nfunction integrate_costs(cost_result::SimulationCostResult,\n sim_param::SimulationParameter,\n constraint_time::Union{Nothing, Float64}=nothing)\n if !isnothing(constraint_time)\n c_idx = Int64(round(constraint_time/sim_param.dtc, digits=5))\n @assert c_idx < size(cost_result.inst_pos_cost_array_gpu, 2);\n else\n c_idx = size(cost_result.inst_cnt_cost_array_gpu, 2);\n end\n # control cost\n cnt_cost_per_control = sum(cost_result.inst_cnt_cost_array_gpu[:, 1:c_idx], dims=2).*Float32(sim_param.dtc);\n\n # position cost\n pos_cost_per_control = sum(cost_result.inst_pos_cost_array_gpu[:, 1:c_idx], dims=2).*Float32(sim_param.dtc);\n if isnothing(constraint_time)\n pos_cost_per_control += cost_result.term_pos_cost_array_gpu;\n end\n\n # for collision cost, sum over all timesteps and ado agents but not over samples\n col_cost_per_sample_control = sum(cost_result.inst_col_cost_array_gpu[:, 1:c_idx, :], dims=(2, 3)).*Float32(sim_param.dtc);\n if isnothing(constraint_time)\n col_cost_per_sample_control += sum(cost_result.term_col_cost_array_gpu, dims=3);\n end\n # reshape collision cost into (num_controls, num_samples) array\n col_cost_per_control_sample = permutedims(reshape(col_cost_per_sample_control, sim_param.num_samples, :),\n [2, 1]);\n @assert isa(col_cost_per_control_sample, CuArray{Float32, 2});\n num_controls = size(col_cost_per_control_sample, 1);\n\n # (num_controls, num_samples) array of Float64\n total_cost_per_control_sample = Float64.(collect(col_cost_per_control_sample .+ (cnt_cost_per_control + pos_cost_per_control)));\n\n # compute risk value per control\n risk_per_control = Vector{Float64}(undef, num_controls);\n for ii = 1:num_controls\n if !(sim_param.cost_param.σ_risk == 0.0)\n risk_value = 1/sim_param.cost_param.σ_risk*\n logsumexp(sim_param.cost_param.σ_risk.*total_cost_per_control_sample[ii, :] .- log(sim_param.num_samples));\n else\n risk_value = sum(total_cost_per_control_sample[ii, :])./sim_param.num_samples\n end\n @inbounds risk_per_control[ii] = risk_value\n end\n return total_cost_per_control_sample, risk_per_control\nend\n\n# Choose best nominal control (i.e. with lowest risk value) for backward simulation\nfunction choose_best_nominal_control(total_cost_per_control_sample, risk_per_control, u_array_gpu)\n minimum_risk, best_control_idx = findmin(risk_per_control);\n sampled_total_costs = total_cost_per_control_sample[best_control_idx, :];\n\n best_u_array_tmp = Float64.(collect(u_array_gpu[best_control_idx, :, :]));\n best_u_array = [best_u_array_tmp[ii, :] for ii = 1:size(best_u_array_tmp, 1)];\n\n return sampled_total_costs, minimum_risk, best_control_idx, best_u_array\nend\n\n# # Compute cost gradients based on the forward simulation & predicted ado positions\nfunction compute_cost_gradients(best_ex_array_gpu::CuArray{Float32, 2},\n best_u_array_gpu::CuArray{Float32, 2},\n best_ap_array_gpu::CuArray{Float32, 4},\n time_idx_ap_array_gpu::CuArray{Int32, 1},\n target_pos_array_gpu::CuArray{Float32, 2},\n cost_param::CostParameter)\n if name(CuDevice(0)) == \"GeForce RTX 2080 Ti\"\n # Instantaneous costs\n inst_pos_cost_grad_array_gpu = instant_position_cost_gradient(best_ex_array_gpu, target_pos_array_gpu,\n cost_param, threads=256);\n inst_col_cost_grad_array_gpu = instant_collision_cost_gradient(best_ex_array_gpu, best_ap_array_gpu,\n time_idx_ap_array_gpu, cost_param,\n threads=(64, 4, 4));\n\n # Terminal costs\n term_pos_cost_grad_array_gpu = terminal_position_cost_gradient(best_ex_array_gpu, target_pos_array_gpu,\n cost_param);\n term_col_cost_grad_array_gpu = terminal_collision_cost_gradient(best_ex_array_gpu, best_ap_array_gpu,\n time_idx_ap_array_gpu, cost_param, threads=(128, 1, 8));\n else\n # Instantaneous costs\n inst_pos_cost_grad_array_gpu = instant_position_cost_gradient(best_ex_array_gpu, target_pos_array_gpu,\n cost_param);\n inst_col_cost_grad_array_gpu = instant_collision_cost_gradient(best_ex_array_gpu, best_ap_array_gpu,\n time_idx_ap_array_gpu, cost_param);\n\n # Terminal costs\n term_pos_cost_grad_array_gpu = terminal_position_cost_gradient(best_ex_array_gpu, target_pos_array_gpu,\n cost_param);\n term_col_cost_grad_array_gpu = terminal_collision_cost_gradient(best_ex_array_gpu, best_ap_array_gpu,\n time_idx_ap_array_gpu, cost_param);\n end\n return SimulationCostGradResult(inst_pos_cost_grad_array_gpu, inst_col_cost_grad_array_gpu,\n term_pos_cost_grad_array_gpu, term_col_cost_grad_array_gpu)\nend\n\n# # sum cost gradients per timestep and sample, reshaping them to (4, total_timesteps, num_samples) array\nfunction sum_cost_gradients(cost_grad_result::SimulationCostGradResult)\n num_samples = size(cost_grad_result.inst_col_cost_grad_array_gpu, 1);\n total_timesteps = size(cost_grad_result.inst_col_cost_grad_array_gpu, 2) + 1;\n\n cost_grad_array = Array{Float64, 3}(undef, 4, total_timesteps, num_samples);\n\n # sum over all ado agents\n inst_col_cost_grads_gpu = sum(cost_grad_result.inst_col_cost_grad_array_gpu, dims=3); # (num_samples, total_timesteps-1, 1, 4)\n term_col_cost_grads_gpu = sum(cost_grad_result.term_col_cost_grad_array_gpu, dims=3); # (num_samples, 1, 1, 4)\n\n cost_grad_array[:, 1:end-1, :] = collect(dropdims(permutedims(inst_col_cost_grads_gpu, [4, 3, 2, 1]), dims=2)); # (4, total_timesteps-1, num_samples)\n cost_grad_array[:, 1:end-1, :] .+= collect(permutedims(cost_grad_result.inst_pos_cost_grad_array_gpu, [2, 1])); # (4, total_timesteps-1, num_samples)\n cost_grad_array[:, end:end, :] = collect(dropdims(permutedims(term_col_cost_grads_gpu, [4, 3, 2, 1]), dims=2)); # (4, 1, num_samples)\n cost_grad_array[:, end:end, :] .+= collect(permutedims(cost_grad_result.term_pos_cost_grad_array_gpu, [2, 1])); # (4, 1, num_samples)\n\n return cost_grad_array\nend\n\n# # backward simulation of the costates.\nfunction simulate_backward(best_ex_array::Array{Float64, 2}, # (total_timesteps, 4) array\n best_u_array::Vector{Vector{Float64}},\n cost_grad_array::Array{Float64, 3},\n sim_param::SimulationParameter)\n e_costate_array = similar(cost_grad_array); # (4, total_timesteps, num_samples) array\n # boundary conditions\n e_costate_array[:, end, :] = cost_grad_array[:, end, :];\n\n for jj = Iterators.reverse(1:size(e_costate_array, 2) - 1)\n # backward euler integration\n @inbounds Jacobian =\n transition_jacobian(best_ex_array[jj + 1, :],\n best_u_array[jj]) # Note the index jj here\n @inbounds costate_vel =\n -cost_grad_array[:, jj, :] .- # Note the index jj here\n transpose(Jacobian)*e_costate_array[:, jj + 1, :];\n @inbounds e_costate_array[:, jj, :] =\n e_costate_array[:, jj + 1, :] .+\n costate_vel*(-sim_param.dtc);\n end\n return e_costate_array\nend\n\n# Main Simulation Function (forward-backward simulation)\n# Ado positions and predictions must be updated separately.\nfunction simulate(w_init::WorldState,\n u_arrays::Vector{Vector{Vector{Float64}}},\n target_trajectory::Trajectory2D,\n prediction_dict::Dict{String, Array{Float64, 3}},\n sim_param::SimulationParameter,\n constraint_time::Union{Nothing, Float64}=nothing)\n # process u_arrays\n u_array = process_u_arrays(u_arrays);\n u_array_gpu = cu(u_array);\n\n # ego state simulation\n ex_array_gpu = simulate_forward(w_init.e_state, u_array_gpu, sim_param);\n\n # get measurement schedule\n measurement_schedule = get_measurement_schedule(w_init, sim_param);\n\n # process prediction_dict for further computation\n # note that each value in prediction_dict has to be (num_samples*num_controls, prediction_steps, 2) array\n ap_array, time_idx_ap_array, control_idx_ex_array, ado_ids_array =\n process_ap_dict(ex_array_gpu, w_init, measurement_schedule, prediction_dict, sim_param);\n ap_array_gpu = cu(ap_array)\n time_idx_ap_array_gpu = CuArray{Int32}(time_idx_ap_array);\n control_idx_ex_array_gpu = CuArray{Int32}(control_idx_ex_array);\n\n # get target_pos array\n target_pos_array = get_target_pos_array(ex_array_gpu, w_init, target_trajectory, sim_param)\n target_pos_array_gpu = cu(target_pos_array);\n\n # compute costs\n cost_result = compute_costs(ex_array_gpu, u_array_gpu, ap_array_gpu,\n time_idx_ap_array_gpu, control_idx_ex_array_gpu,\n target_pos_array_gpu, sim_param.cost_param);\n\n # integrate costs\n total_cost_per_control_sample, risk_per_control = integrate_costs(cost_result, sim_param);\n\n # choose best nominal control\n sampled_total_costs, minimum_risk, best_control_idx, best_u_array =\n choose_best_nominal_control(total_cost_per_control_sample, risk_per_control, u_array_gpu);\n best_ex_array_gpu = ex_array_gpu[best_control_idx, :, :];\n best_ex_array = Float64.(collect(best_ex_array_gpu));\n best_u_array_gpu = u_array_gpu[best_control_idx, :, :];\n best_ap_array_sample_idx =\n sim_param.num_samples*(best_control_idx-1)+1:sim_param.num_samples*best_control_idx\n best_ap_array_gpu = ap_array_gpu[best_ap_array_sample_idx, :, :, :];\n # compute cost gradients using the best nominal control\n cost_grad_result = compute_cost_gradients(best_ex_array_gpu, best_u_array_gpu,\n best_ap_array_gpu, time_idx_ap_array_gpu,\n target_pos_array_gpu,\n sim_param.cost_param);\n\n # get cost gradient array for costate computation\n cost_grad_array = sum_cost_gradients(cost_grad_result);\n\n # backward simulation of ego costate\n e_costate_array = simulate_backward(best_ex_array, best_u_array, cost_grad_array, sim_param);\n\n if !isnothing(constraint_time)\n # compute indices to slice best_ex_array, best_u_array, cost_grad_array for constraint enforcement\n c_idx = Int64(round(constraint_time/sim_param.dtc, digits=5)) + 1;\n @assert c_idx < size(best_ex_array, 1)\n # compute adjoint for constraint enforcement\n cost_grad_array[:, c_idx, :] = zeros(size(cost_grad_array[:, c_idx, :])); # TODO: maybe we do not want to mutate cost_grad_array.\n e_costate_array_constraint = simulate_backward(best_ex_array[1:c_idx, :],\n best_u_array[1:c_idx],\n cost_grad_array[:, 1:c_idx, :],\n sim_param);\n total_cost_per_control_sample_constraint, risk_per_control_constraint =\n integrate_costs(cost_result, sim_param, constraint_time);\n sampled_total_costs_constraint =\n total_cost_per_control_sample_constraint[best_control_idx, :];\n risk_constraint = risk_per_control_constraint[best_control_idx];\n else\n e_costate_array_constraint = nothing;\n sampled_total_costs_constraint = nothing;\n risk_constraint = nothing;\n end\n\n sim_result = SimulationResult(best_u_array,\n best_control_idx,\n simulate_forward(w_init.e_state, best_u_array, sim_param),\n measurement_schedule, prediction_dict,\n best_ap_array_gpu,\n ado_ids_array, sampled_total_costs, minimum_risk,\n e_costate_array,\n e_costate_array_constraint,\n sampled_total_costs_constraint,\n risk_constraint)\n return sim_result, best_u_array\nend\n\n#=\n# Forward (re-)simulation and evaluation of risk (for potential line search which is not implemented yet)\nfunction evaluate_risk(w_init::WorldState,\n u_array::Vector{Vector{Float64}},\n target_trajectory::Trajectory2D,\n ap_array_gpu::CuArray{Float32, 4},\n sim_param::SimulationParameter)\n # ego state simulation\n e_state_array = simulate_forward(w_init.e_state, u_array, sim_param);\n # export to gpu\n ep_array_gpu = cu(hcat(get_position.(e_state_array)...));\n # compute costs\n cost_result = compute_costs(e_state_array, ep_array_gpu, u_array, ap_array_gpu,\n target_trajectory, sim_param.cost_param);\n ~, risk_val = integrate_costs(cost_result, sim_param);\n return risk_val\nend\n=#\n", "meta": {"hexsha": "1d77598aca03ceed59e785793f67d826a4b639da", "size": 28838, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/forward_backward_simulation.jl", "max_stars_repo_name": "StanfordMSL/RiskSensitiveSAC.jl", "max_stars_repo_head_hexsha": "64664b05ea160d5532643d24586176f8112b0c58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-02T04:20:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T17:33:57.000Z", "max_issues_repo_path": "src/forward_backward_simulation.jl", "max_issues_repo_name": "StanfordMSL/RiskSensitiveSAC.jl", "max_issues_repo_head_hexsha": "64664b05ea160d5532643d24586176f8112b0c58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-26T22:33:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T22:33:54.000Z", "max_forks_repo_path": "src/forward_backward_simulation.jl", "max_forks_repo_name": "StanfordMSL/RiskSensitiveSAC.jl", "max_forks_repo_head_hexsha": "64664b05ea160d5532643d24586176f8112b0c58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2427536232, "max_line_length": 153, "alphanum_fraction": 0.6611762258, "num_tokens": 6502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.173900672123696}} {"text": "\n\"\"\"\n`module JAC.Atomic` ... a submodel of JAC that contains all methods to set-up and process (simple) atomic and SCF computations as well as \n atomic cascade computations; it is using JAC, JAC.Radial, JAC.ManyElectron, JAC.Nuclear, JAC.Einstein, \n JAC.Hfs, JAC.IsotopeShift, JAC.PlasmaShift, JAC.LandeZeeman, JAC.PhotoEmission, JAC.PhotoIonization, JAC.AutoIonization.\n\"\"\"\nmodule Atomic\n\n using Interact\n using JAC.Basics, JAC.Radial, JAC.ManyElectron, JAC.Nuclear\n using JAC.Einstein, JAC.Hfs, JAC.IsotopeShift, JAC.PlasmaShift, JAC.LandeZeeman, JAC.AlphaVariation, JAC.FormFactor, JAC.DecayYield,\n JAC.GreenFunction, JAC.MultipolePolarizibility,\n JAC.PhotoEmission, JAC.PhotoIonization, JAC.PhotoExcitation, JAC.PhotoRecombination, \n JAC.AutoIonization, JAC.Dielectronic, JAC.ImpactExcitation, JAC.CoulombExcitation, JAC.CoulombIonization,\n JAC.PhotoExcitationFluores, JAC.PhotoExcitationAutoion, JAC.RayleighCompton, JAC.MultiPhotonDeExcitation,\n JAC.PhotoIonizationFluores, JAC.PhotoIonizationAutoion, JAC.ImpactExcitationAutoion, JAC.RadiativeAuger, \n JAC.MultiPhotonIonization, JAC.MultiPhotonDoubleIon, JAC.InternalConversion\n ##x , JAC.ElectricDipoleMoment\n\n\n \"\"\"\n `struct Atomic.CasStep` ... a type for defining an individual step of a (relativistic) complete active space computation for a specified \n set of levels. An instance of this struct provides all information to generate the atomic basis and to perform \n the associated SCF and multiplet computations for a selected No. of levels.\n\n + name ::String ... to assign a name to the given SCF step.\n + NoElectrons ::Int64 ... Number of electrons.\n + refConfigs ::Array{Configuration,1} ... List of references configurations, at least 1.\n + Sfrom ::Array{Shell,1} ... Single-excitations from shells [sh_1, sh_2, ...]\n + Sto ::Array{Shell,1} ... Single-excitations to shells [sh_1, sh_2, ...]\n + Dfrom ::Array{Shell,1} ... Double-excitations from shells [sh_1, sh_2, ...]\n + Dto ::Array{Shell,1} ... Double-excitations to shells [sh_1, sh_2, ...]\n + Tfrom ::Array{Shell,1} ... Triple-excitations from shells [sh_1, sh_2, ...]\n + Tto ::Array{Shell,1} ... Triple-excitations to shells [sh_1, sh_2, ...]\n + Qfrom ::Array{Shell,1} ... Quadrupole-excitations from shells [sh_1, sh_2, ...]\n + Qto ::Array{Shell,1} ... Quadrupole-excitations to shells [sh_1, sh_2, ...]\n + restrictions ::Array{String,1} ... List of Strings to define 'restrictions' to applied to the CSF basis.\n + NoIterations ::Int64 ... Number of SCf iterations to be applied in this step of computations.\n + frozenSubshells ::Array{Subshell,1} ... List of subshells that are kept 'frozen' in this step.\n + failureHandling ::Array{String,1} ... List of Strings to define subsequent steps in case of failure.\n \"\"\"\n struct CasStep\n name ::String \n NoElectrons ::Int64 \n refConfigs ::Array{Configuration,1}\n Sfrom ::Array{Shell,1}\n Sto ::Array{Shell,1}\n Dfrom ::Array{Shell,1}\n Dto ::Array{Shell,1} \n Tfrom ::Array{Shell,1}\n Tto ::Array{Shell,1}\n Qfrom ::Array{Shell,1}\n Qto ::Array{Shell,1}\n restrictions ::Array{String,1} \n NoIterations ::Int64 \n frozenShells ::Array{Subshell,1}\n failureHandling ::Array{String,1}\n end\n\n\n \"\"\"\n `JAC.Atomic.CasStep(name::String, NoElectrons::Int64)` ... constructor for an 'initial' instance of a variable::Atomic.CasStep with just \n a given name and No. of Electrons.\n \"\"\"\n function CasStep(name::String, NoElectrons::Int64)\n CasStep(name, NoElectrons, Configuration[], Shell[], Shell[], Shell[], Shell[], Shell[], Shell[], Shell[], Shell[], \n String[], 0, Subshell[], String[])\n end\n\n\n \"\"\"\n `JAC.Atomic.CasStep(\"interactive\"; refine::Atomic.CasStep=..)` ... constructor to generate a new instance of Atomic.CasStep\n interactively by replying to some detailed dialog. This constructor enables one to add, modify or\n refine an individual step in the complete active space computations. **Not yet implemented !**\n \"\"\"\n function CasStep(sa::String; refine::Atomic.CasStep = Atomic.CasStep())\n sa != \"interactive\" && error(\"Unsupported keystring = $sa.\")\n\n #= print(\"Enter the nuclear charge Z: \"); Zx = Base.parse(Float64, readline(STDIN) )\n\n yes = yesno(\"The ...; modify ? [N|y]\") \n while yes \n print(\"Enter a charge distribution model {point, Fermi, uniform}: \"); modelx = strip(readline(STDIN))\n !(modelx in [\"\"]) && println(\"Unsupported charge distribution model $modelx ... redo:\")\n end =#\n end\n\n\n # `Base.show(io::IO, step::Atomic.CasStep)` ... prepares a proper printout of the (individual step of computations) step::Atomic.CasStep.\n function Base.show(io::IO, step::Atomic.CasStep)\n sa = Base.string(step); print(io, sa, \"\\n\")\n sa = \"Reference configurations: \"; print(io, sa, \"\\n\") \n if length(step.refConfigs) > 0\n for conf in step.refConfigs print(io, conf ) end; print(io, \"\\n\")\n end\n if length(step.Sfrom) > 0\n sa = \"Singles from: { \"; for sh in step.Sfrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.Sto sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n if length(step.Dfrom) > 0\n sa = \"Doubles from: { \"; for sh in step.Dfrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.Dto sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n if length(step.Tfrom) > 0\n sa = \"Triples from: { \"; for sh in step.Tfrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.Tto sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n if length(step.Qfrom) > 0\n sa = \"Quadruples from: { \"; for sh in step.Qfrom sa = sa * string(sh) * \", \" end\n sa = sa[1:end-2] * \" } ... to { \"; for sh in step.Qto sa = sa * string(sh) * \", \" end; \n sa = sa[1:end-2] * \" }\"; print(io, sa, \"\\n\")\n end \n end\n\n\n # `Base.string(step::Atomic.CasStep)` ... provides a String notation for the variable step::Atomic.CasStep.\n function Base.string(step::Atomic.CasStep)\n sa = \"Step: Computational model for $(step.name) with $(step.NoElectrons) electrons and with (step.NoCoreShells) \"\n sa = sa * \"core shells:\"\n return( sa )\n end\n\n\n\n \"\"\"\n `struct Atomic.CasComputation` ... a struct for defining a series of complete active space computations for a specified set of levels. \n This type provides all information to generate the atomic basis and to perform the corresponding\n SCF and multiplet computations for a selected No. of levels.\n\n + name ::String ... to assign a name to the given model.\n + previousStep ::Int64 ... 0, if no previous steps was yet done in this series.\n + steps ::Array{Atomic.CasStep,1} ... List of SCF steps that are to be done in this model computation.\n \"\"\"\n struct CasComputation\n name ::String \n previousStep ::Int64 \n steps ::Array{Atomic.CasStep,1}\n end\n\n\n \"\"\"\n `JAC.Atomic.CasComputation()` ... constructor for an 'empty' instance of the a variable::Atomic.CasComputation\n \"\"\"\n function CasComputation()\n CasComputation(\"\", 0, Array{CasStep,1}[])\n end\n\n\n \"\"\"\n `JAC.Atomic.CasComputation(\"interactive\"; refine::Atomic.CasComputation=..)` ... constructor to generate a new instance of\n Atomic.CasComputation interactively by replying to some detailed dialog. This constructor enables one to add,\n modify or refine the model for a particular complete active space computations. **Not yet implemented !**\n \"\"\"\n function CasComputation(sa::String; refine::Atomic.CasComputation = Atomic.CasComputation())\n sa != \"interactive\" && error(\"Unsupported keystring = $sa.\")\n\n #= print(\"Enter the nuclear charge Z: \"); Zx = Base.parse(Float64, readline(STDIN) )\n\n yes = yesno(\"The ...; modify ? [N|y]\") \n while yes \n print(\"Enter a charge distribution model {point, Fermi, uniform}: \"); modelx = strip(readline(STDIN))\n !(modelx in [\"\"]) && println(\"Unsupported charge distribution model $modelx ... redo:\")\n end =#\n end\n\n\n # `Base.show(io::IO, model::CasComputation)` ... prepares a proper printout of the (individual step of computations) model::CasComputation.\n function Base.show(io::IO, model::CasComputation)\n sa = Base.string(model)\n print(io, sa)\n end\n\n\n # `Base.string(model::CasComputation)` ... provides a String notation for the variable model::CasComputation.\n function Base.string(model::CasComputation)\n sa = \"Model: $(model.name) includes $(length(model.steps)) steps and has been calculated up to the step $(model.previousStep).\"\n return( sa )\n end\n\n\n\n \"\"\"\n `struct Atomic.CasSettings` ... a struct for defining the settings for complete active space computations\n\n + generateScf ::Bool ... True, if a SCF need to be generated, and false if just the start orbitals should \n be applied.\n + startOrbitals ::String ... Specify how the start orbitals are obtained [\"fromNRorbitals\", \"fromGrasp\", \"hydrogenic\"].\n + rwfFilename ::String ... Filename of orbitals, if taken from Grasp.\n + levels ::Array{Int64,1} ... Levels on which the optimization need to be carried out.\n + includeBreit ::Bool ... True, if the Breit interaction is included into the SCF generation.\n + maxIterations ::Int64 ... maximum number of SCF iterations\n + scfAccuracy ::Float64 ... convergence criterion for the SCF field.\n + iterationSequence ::Array{Subshell,1} ... Sequence of subshells to be optimized.\n \"\"\"\n struct CasSettings\n generateScf ::Bool\n startOrbitals ::String\n rwfFilename ::String\n levels ::Array{Int64,1}\n includeBreit ::Bool\n maxIterations ::Int64\n scfAccuracy ::Float64\n iterationSequence ::Array{Subshell,1}\n end\n\n\n \"\"\"\n `JAC.Atomic.CasSettings()` ... constructor for setting the default values.\n \"\"\"\n function CasSettings()\n CasSettings(false, \"fromNRorbitals\", \"\", Int64[1], false, 24, 1.0e-8, Subshell[] )\n end\n\n\n # `Base.show(io::IO, settings::Atomic.CasSettings)` ... prepares a proper printout of the settings::Atomic.CasSettings.\n function Base.show(io::IO, settings::Atomic.CasSettings)\n println(io, \"generateScf: $(settings.generateScf) \")\n println(io, \"startOrbitals: $(settings.startOrbitals) \")\n println(io, \"rwfFilename: $(settings.rwfFilename) \")\n println(io, \"levels: $(settings.levels) \")\n println(io, \"includeBreit: $(settings.includeBreit) \")\n println(io, \"maxIterations: $(settings.maxIterations) \")\n println(io, \"scfAccuracy: $(settings.scfAccuracy) \")\n println(io, \"iterationSequence: $(settings.iterationSequence) \")\n end\n\n\n # `Base.string(settings::Atomic.CasSettings)` ... provides a String notation for the variable settings::Atomic.CasSettings.\n function Base.string(settings::Atomic.CasSettings)\n error(\"Not yet implemented.\")\n sa = \"Cas settings: maximum No. of iterations = $(settings.maxIterations), accuracy = (settings.scfAccuracy)\"\n return( sa )\n end\n\n\n \"\"\"\n `struct Computation` ... defines a type for defining (the model of simple) atomic computation of a single multiplet, \n including the SCF and CI as well as level properties and transition property calculations.\n\n + name ::String ... A name associated to the computation.\n + nuclearModel ::Nuclear.Model ... Model, charge and parameters of the nucleus.\n + grid ::Radial.Grid ... The radial grid to be used for the computation.\n ##x + calcLevelProperties ::Bool ... True, if level structures and properties are to be calculated\n + properties ::Array{AtomicLevelProperty,1} ... List of atomic properties to be calculated.\n + configs ::Array{Configuration,1} ... A list of non-relativistic configurations.\n + asfSettings ::AsfSettings ... Provides the settings for the SCF process and for the CI and QED calculations.\n + initialConfigs ::Array{Configuration,1} ... A list of initial-state configurations for some transition \n property calculation, such as radiative transition, Auger, etc. \n + initialAsfSettings ::AsfSettings ... Provides the SCF and CI settings for the initial-state multiplet.\n + intermediateConfigs ::Array{Configuration,1} ... A list of initial-state configurations.\n + intermediateAsfSettings ::AsfSettings ... Provides the SCF settings for the intermediate-state multiplet.\n + finalConfigs ::Array{Configuration,1} ... A list of final-state configurations.\n + finalAsfSettings ::AsfSettings ... Provides the SCF and CI settings for the final-state multiplet.\n + alphaSettings ::AlphaVariation.Settings ... Settings for alpha-variation parameter calculations.\n + einsteinSettings ::Einstein.Settings ... Settings for Einstein coefficient calculations.\n + formSettings ::FormFactor.Settings ... Settings for atomic form factor calculations.\n + greenSettings ::GreenFunction.Settings ... Settings for approximate Green function calculations.\n + hfsSettings ::Hfs.Settings ... Settings for hyperfine parameter calculations.\n + isotopeSettings ::IsotopeShift.Settings ... Settings for isotope shift parameter calculations.\n + plasmaSettings ::PlasmaShift.Settings ... Settings for plasma-shift calculations.\n + polaritySettings ::MultipolePolarizibility.Settings ... Settings for plasma-shift calculations.\n + yieldSettings ::DecayYield.Settings ... Settings for fluoresence and Auger yield calculations.\n + zeemanSettings ::LandeZeeman.Settings ... Settings for Lande-Zeeman coefficient calculations.\n + process ::JAC.AtomicProcess ... An (additional) process for which the properties are to be evaluated \n for the given initial- and final-state configurations.\n + processSettings ::Union{JAC.PhotoEmission.Settings, JAC.AutoIonization.Settings, JAC.PlasmaShift.AugerSettings, \n JAC.PhotoIonization.Settings, JAC.PlasmaShift.PhotoSettings, \n JAC.PhotoExcitation.Settings, JAC.PhotoExcitationAutoion.Settings, JAC.PhotoRecombination.Settings, \n JAC.ImpactExcitation.Settings, JAC.Dielectronic.Settings, RadiativeAuger.Settings,\n JAC.PairAnnihilation1Photon.Settings, JAC.ImpactExcitationAutoion.Settings, \n JAC.MultiPhotonDeExcitation.Settings, JAC.CoulombExcitation.Settings, \n JAC.CoulombIonization.Settings} ... Provides the settings for the selected process.\n \"\"\"\n struct Computation\n name ::String\n nuclearModel ::Nuclear.Model\n grid ::Radial.Grid\n ##x calcLevelProperties ::Bool\n properties ::Array{AtomicLevelProperty,1}\n configs ::Array{Configuration,1}\n asfSettings ::AsfSettings\n initialConfigs ::Array{Configuration,1} \n initialAsfSettings ::AsfSettings\n intermediateConfigs ::Array{Configuration,1} \n intermediateAsfSettings ::AsfSettings\n finalConfigs ::Array{Configuration,1}\n finalAsfSettings ::AsfSettings\n alphaSettings ::AlphaVariation.Settings\n einsteinSettings ::Einstein.Settings\n formSettings ::FormFactor.Settings\n greenSettings ::GreenFunction.Settings\n hfsSettings ::Hfs.Settings\n isotopeSettings ::IsotopeShift.Settings\n plasmaSettings ::PlasmaShift.Settings\n polaritySettings ::MultipolePolarizibility.Settings\n yieldSettings ::DecayYield.Settings\n zeemanSettings ::LandeZeeman.Settings\n process ::AtomicProcess\n processSettings ::Union{PhotoEmission.Settings, AutoIonization.Settings, PlasmaShift.AugerSettings, \n PhotoIonization.Settings, PlasmaShift.PhotoSettings,\n PhotoRecombination.Settings, Dielectronic.Settings, ImpactExcitation.Settings,\n CoulombExcitation.Settings, CoulombIonization.Settings, \n PhotoExcitation.Settings, PhotoExcitationFluores.Settings, \n PhotoExcitationAutoion.Settings, RayleighCompton.Settings, \n MultiPhotonDeExcitation.Settings, PhotoIonizationFluores.Settings, \n PhotoIonizationAutoion.Settings, ImpactExcitationAutoion.Settings,\n RadiativeAuger.Settings, MultiPhotonIonization.Settings,\n MultiPhotonDoubleIon.Settings, InternalConversion.Settings} #= , \n #\n PairAnnihilation1Photon.Settings } =#\n end \n\n\n \"\"\"\n `JAC.Atomic.Computation()` ... constructor for an 'empty' instance::Atomic.Computation.\n \"\"\"\n function Computation()\n Computation(\"\", Nuclear.Model(1.), Radial.Grid(), AtomicLevelProperty[], \n Configuration[], AsfSettings(),\n Configuration[], AsfSettings(),\n Configuration[], AsfSettings(),\n Configuration[], AsfSettings(),\n AlphaVariation.Settings(), Einstein.Settings(), FormFactor.Settings(), GreenFunction.Settings(), \n Hfs.Settings(), \n IsotopeShift.Settings(), PlasmaShift.Settings(), MultipolePolarizibility.Settings(), \n DecayYield.Settings(), LandeZeeman.Settings(), \n ##x NoAmplitude, ElectricDipoleMoment.Settings(), \n NoProcess, PhotoEmission.Settings() )\n end\n\n\n \"\"\"\n `JAC.Atomic.Computation(sa::String, nm::Nuclear.Model; grid::Radial.Grid = JAC.Radial.Grid('grid: exponential'), ##x calc::Bool = false,\n properties::Array{AtomicLevelProperty,1} = AtomicLevelProperty[], configs::Array{Configuration,1} = Configuration[],\n asfSettings::AsfSettings = AsfSettings(), \n initialConfigs::Array{Configuration,1} = Configuration[], initialAsfSettings::AsfSettings = AsfSettings(), \n intermediateConfigs::Array{Configuration,1} = Configuration[], intermediateAsfSettings::AsfSettings = AsfSettings(), \n finalConfigs::Array{Configuration,1} = Configuration[], finalAsfSettings::AsfSettings = AsfSettings(), \n alphaSettings::AlphaVariation.Settings = AlphaVariation.Settings(), einsteinSettings::Einstein.Settings = Einstein.Settings(), \n formSettings::FormFactor.Settings = FormFactor.Settings(), greenSettings::GreenFunction.Settings = GreenFunction.Settings(), \n hfsSettings::Hfs.Settings = Hfs.Settings(),\n isotopeSettings::IsotopeShift.Settings = IsotopeShift.Settings(), plasmaSettings::PlasmaShift.Settings = PlasmaShift.Settings(), \n polaritySettings::MultipolePolarizibility.Settings = MultipolePolarizibility.Settings(), \n yieldSettings::DecayYield.Settings = DecayYield.Settings(), zeemanSettings::LandeZeeman.Settings = LandeZeeman.Settings(), \n ##x amplitude::JAC.AtomicAmplitude = JAC.NoAmplitude, amplitudeSettings::Any = true, \n process::JAC.AtomicProcess = JAC.NoProcess, processSettings::Any = true)` ... constructor for an instance::Atomic.Computation for \n which all requested details are given by proper keyword specification. A few internal checks are made. \n \"\"\"\n function Computation(sa::String, nm::Nuclear.Model; grid::Radial.Grid = Radial.Grid(\"grid: exponential\"), ##x calc::Bool = false,\n properties::Array{AtomicLevelProperty,1} = [Basics.NoProperty], configs::Array{Configuration,1} = Configuration[],\n asfSettings::AsfSettings = AsfSettings(), \n initialConfigs::Array{Configuration,1} = Configuration[], initialAsfSettings::AsfSettings = AsfSettings(), \n intermediateConfigs::Array{Configuration,1} = Configuration[], intermediateAsfSettings::AsfSettings = AsfSettings(), \n finalConfigs::Array{Configuration,1} = Configuration[], finalAsfSettings::AsfSettings = AsfSettings(), \n alphaSettings::AlphaVariation.Settings = AlphaVariation.Settings(), \n einsteinSettings::Einstein.Settings = Einstein.Settings(), \n formSettings::FormFactor.Settings = FormFactor.Settings(), \n greenSettings::GreenFunction.Settings = GreenFunction.Settings(), \n hfsSettings::Hfs.Settings = Hfs.Settings(),\n isotopeSettings::IsotopeShift.Settings = IsotopeShift.Settings(), \n plasmaSettings::PlasmaShift.Settings = PlasmaShift.Settings(), \n polaritySettings::MultipolePolarizibility.Settings = MultipolePolarizibility.Settings(), \n yieldSettings::DecayYield.Settings = DecayYield.Settings(), \n zeemanSettings::LandeZeeman.Settings = LandeZeeman.Settings(), \n process::Basics.AtomicProcess = Basics.NoProcess, processSettings::Any = true)\n if process == Basics.NoProcess && typeof(processSettings) == Bool && processSettings procSettings = PhotoEmission.Settings()\n elseif process == Basics.Auger && typeof(processSettings) == Bool && processSettings procSettings = AutoIonization.Settings()\n elseif process == Basics.Auger && typeof(processSettings) == AutoIonization.Settings procSettings = processSettings \n elseif process == Basics.AugerInPlasma && typeof(processSettings) == Bool && processSettings procSettings = PlasmaShift.AugerSettings()\n elseif process == Basics.AugerInPlasma && typeof(processSettings) == PlasmaShift.AugerSettings procSettings = processSettings \n elseif process == Basics.Radiative && typeof(processSettings) == Bool && processSettings procSettings = PhotoEmission.Settings()\n elseif process == Basics.Radiative && typeof(processSettings) == PhotoEmission.Settings procSettings = processSettings \n elseif process == Basics.PhotoExc && typeof(processSettings) == Bool && processSettings procSettings = PhotoExcitation.Settings()\n elseif process == Basics.PhotoExc && typeof(processSettings) == PhotoExcitation.Settings procSettings = processSettings \n elseif process == Basics.Photo && typeof(processSettings) == Bool && processSettings procSettings = PhotoIonization.Settings()\n elseif process == Basics.Photo && typeof(processSettings) == PhotoIonization.Settings procSettings = processSettings \n elseif process == Basics.PhotoInPlasma && typeof(processSettings) == Bool && processSettings procSettings = PlasmaShift.PhotoSettings()\n elseif process == Basics.PhotoInPlasma && typeof(processSettings) == PlasmaShift.PhotoSettings procSettings = processSettings \n elseif process == Basics.Rec && typeof(processSettings) == Bool && processSettings procSettings = PhotoRecombination.Settings()\n elseif process == Basics.Rec && typeof(processSettings) == PhotoRecombination.Settings procSettings = processSettings \n elseif process == Basics.Dierec && typeof(processSettings) == Bool && processSettings procSettings = Dielectronic.Settings()\n elseif process == Basics.Dierec && typeof(processSettings) == Dielectronic.Settings procSettings = processSettings \n elseif process == Basics.PhotoExcFluor && typeof(processSettings) == Bool && processSettings procSettings = PhotoExcitationFluores.Settings()\n elseif process == Basics.PhotoExcFluor && typeof(processSettings) == PhotoExcitationFluores.Settings procSettings = processSettings \n elseif process == Basics.PhotoExcAuto && typeof(processSettings) == Bool && processSettings procSettings = PhotoExcitationAutoion.Settings()\n elseif process == Basics.PhotoExcAuto && typeof(processSettings) == PhotoExcitationAutoion.Settings procSettings = processSettings \n elseif process == Basics.PhotoIonFluor && typeof(processSettings) == Bool && processSettings procSettings = PhotoIonizationFluores.Settings()\n elseif process == Basics.PhotoIonFluor && typeof(processSettings) == PhotoIonizationFluores.Settings procSettings = processSettings \n elseif process == Basics.PhotoIonAuto && typeof(processSettings) == Bool && processSettings procSettings = PhotoIonizationAutoion.Settings()\n elseif process == Basics.PhotoIonAuto && typeof(processSettings) == PhotoIonizationAutoion.Settings procSettings = processSettings \n elseif process == Basics.MultiPhotonDE && typeof(processSettings) == Bool && processSettings procSettings = MultiPhotonDeExcitation.Settings()\n elseif process == Basics.MultiPhotonDE && typeof(processSettings) == MultiPhotonDeExcitation.Settings procSettings = processSettings \n elseif process == Basics.Compton && typeof(processSettings) == Bool && processSettings procSettings = RayleighCompton.Settings()\n elseif process == Basics.Compton && typeof(processSettings) == RayleighCompton.Settings procSettings = processSettings \n elseif process == Basics.Eimex && typeof(processSettings) == Bool && processSettings procSettings = ImpactExcitation.Settings()\n elseif process == Basics.Eimex && typeof(processSettings) == ImpactExcitation.Settings procSettings = processSettings \n elseif process == Basics.ImpactExcAuto && typeof(processSettings) == Bool && processSettings procSettings = ImpactExcitationAutoion.Settings()\n elseif process == Basics.ImpactExcAuto && typeof(processSettings) == ImpactExcitationAutoion.Settings procSettings = processSettings \n elseif process == Basics.RAuger && typeof(processSettings) == Bool && processSettings procSettings = RadiativeAuger.Settings()\n elseif process == Basics.RAuger && typeof(processSettings) == RadiativeAuger.Settings procSettings = processSettings \n elseif process == Basics.MultiPI && typeof(processSettings) == Bool && processSettings procSettings = MultiPhotonIonization.Settings()\n elseif process == Basics.MultiPI && typeof(processSettings) == MultiPhotonIonization.Settings procSettings = processSettings \n elseif process == Basics.MultiPDI && typeof(processSettings) == Bool && processSettings procSettings = MultiPhotonDoubleIon.Settings()\n elseif process == Basics.MultiPDI && typeof(processSettings) == MultiPhotonDoubleIon.Settings procSettings = processSettings \n elseif process == Basics.InternalConv && typeof(processSettings) == Bool && processSettings procSettings = InternalConversion.Settings()\n elseif process == Basics.InternalConv && typeof(processSettings) == InternalConversion.Settings procSettings = processSettings \n elseif process == Basics.Coulex && typeof(processSettings) == Bool && processSettings procSettings = CoulombExcitation.Settings()\n elseif process == Basics.Coulex && typeof(processSettings) == CoulombExcitation.Settings procSettings = processSettings \n elseif process == Basics.Coulion && typeof(processSettings) == Bool && processSettings procSettings = CoulombIonization.Settings()\n elseif process == Basics.Coulion && typeof(processSettings) == CoulombIonization.Settings procSettings = processSettings \n else error(\"The processSettings must fit to the given process or should not occur if NoProcess is to be calculated.\")\n end\n \n Computation(sa, nm, grid, properties, configs, asfSettings, \n initialConfigs, initialAsfSettings, \n intermediateConfigs, intermediateAsfSettings,\n finalConfigs, finalAsfSettings,\n alphaSettings, einsteinSettings, formSettings, greenSettings, hfsSettings, isotopeSettings, plasmaSettings, \n polaritySettings, yieldSettings, zeemanSettings, \n ##x amplitude, ampSettings, \n process, procSettings) \n end\n\n\n # `Base.show(io::IO, computation::Atomic.Computation)` ... prepares a proper printout of the variable computation::Atomic.Computation.\n function Base.show(io::IO, computation::Atomic.Computation) \n println(io, \"name: $(computation.name) \")\n println(io, \"nuclearModel: $(computation.nuclearModel) \")\n println(io, \"grid: $(computation.grid) \")\n ##x println(io, \"calcLevelProperties: $(computation.calcLevelProperties) \")\n println(io, \"properties: $(computation.properties) \")\n println(io, \"configs: $(computation.configs) \")\n println(io, \"asfSettings: computation.asfSettings \")\n println(io, \"initialConfigs: $(computation.initialConfigs) \")\n println(io, \"initialAsfSettings: computation.initialAsfSettings \")\n println(io, \"intermediateConfigs: $(computation.intermediateConfigs) \")\n println(io, \"intermediateAsfSettings: computation.intermediateAsfSettings \")\n println(io, \"finalConfigs: $(computation.finalConfigs) \")\n println(io, \"finalAsfSettings: computation.finalAsfSettings \")\n println(io, \"alphaSettings: computation.alphaSettings \")\n println(io, \"einsteinSettings: computation.einsteinSettings \")\n println(io, \"formSettings: computation.formSettings \")\n println(io, \"greenSettings: computation.greenSettings \")\n println(io, \"hfsSettings: computation.hfsSettings \")\n println(io, \"isotopeSettings: computation.isotopeSettings \")\n println(io, \"plasmaSettings: computation.plasmaSettings \")\n println(io, \"polaritySettings: computation.polaritySettings \")\n println(io, \"yieldSettings: computation.yieldSettings \")\n println(io, \"zeemanSettings: computation.zeemanSettings \")\n println(io, \"process: $(computation.process) \")\n println(io, \"processSettings: computation.processSettings \")\n end\n\n\n \"\"\"\n `JAC.Atomic.Computation(gui::Guint; comp::Atomic.Computation=Atomic.Computation())` ... constructor that is defined by a graphical user interface.\n \"\"\"\n function Computation(gui::Guint; comp::Atomic.Computation=Atomic.Computation())\n \n if gui == Gui\n println(\"aa\")\n output = Atomic.ComputationGui(comp)\n elseif gui == GuiSettings\n println(\"bb\")\n output = Atomic.ComputationGuiSettings(comp)\n else error(\"Unsupported Guint = $gui.\")\n end\n \n return( output )\n end\n\n\n \"\"\"\n `JAC.Atomic.ComputationGui(comp::Atomic.Computation)` ... constructor that defines the standard part of a computation by a graphical \n user interface apart from the setting and the configurations.\n \"\"\"\n function ComputationGui(comp::Atomic.Computation)\n nmd = comp.nuclearModel\n \n title = comp.name; nmd = comp.nuclearModel; grid = comp.grid; calcLevelProperties = comp.calcLevelProperties\n properties = comp.properties\n configs = comp.configs; asfSettings = comp.asfSettings\n initialConfigs = comp.initialConfigs; initialAsfSettings = comp.initialAsfSettings\n intermediateConfigs = comp.intermediateConfigs; intermediateAsfSettings = comp.intermediateAsfSettings\n finalConfigs = comp.finalConfigs; finalAsfSettings = comp.finalAsfSettings\n alphaSettings = comp.alphaSettings; einsteinSettings = comp.einsteinSettings\n formSettings = comp.formSettings; greenSettings = comp.greenSettings\n hfsSettings = comp.hfsSettings; isotopeSettings = comp.isotopeSettings\n plasmaSettings = comp.plasmaSettings; polaritySettings = comp.polaritySettings\n yieldSettings = comp.yieldSettings; zeemanSettings = comp.zeemanSettings \n process = comp.process; processSettings = comp.processSettings\n \n # Update the nuclear model\n tn1 = \"Update nuclear model: \"\n bn1 = slider(1:110, label = \"charge\", value = nmd.Z)\n bn2 = dropdown([nmd.model, \"Fermi\", \"point\", \"uniform\"])\n bn3 = spinbox(label=\"mass \"; value=nmd.mass)\n bn4 = spinbox(label=\"radius\"; value=nmd.radius)\n bn5 = spinbox(label=\"2*spin\"; value=nmd.spinI.num)\n bn6 = spinbox(label=\"mu \"; value=nmd.mu)\n bn7 = spinbox(label=\"Q \"; value=nmd.Q)\n #\n #\n update = button(\"Update all\")\n ui = vbox( hbox( pad(0em, tn1) ),\n hbox( pad(1em, bn1) ), \n hbox( pad(1em, bn2), pad(1em, bn3), pad(1em, bn4) ), \n hbox( pad(1em, bn5), pad(1em, bn6), pad(1em, bn7) ), \n hbox( pad(2em, update) )\n )\n #\n Interact.display(ui) \n output = Interact.@map (&update; Computation(title, \n Nuclear.Model( observe(bn1)[], observe(bn2)[], observe(bn3)[], observe(bn4)[], \n AngularJ64( Int64(observe(bn5)[])//2 ), observe(bn6)[], observe(bn7)[] ),\n grid, calcLevelProperties, properties, configs, asfSettings, \n initialConfigs, initialAsfSettings, \n intermediateConfigs, intermediateAsfSettings, \n finalConfigs, finalAsfSettings, \n alphaSettings, einsteinSettings, formSettings, greenSettings, hfsSettings, isotopeSettings, plasmaSettings, \n polaritySettings, yieldSettings, zeemanSettings, \n process, processSettings) )\n #\n return( output )\n end\n\n\n \"\"\"\n `JAC.Atomic.ComputationGuiSettings(comp::Atomic.Computation)` ... constructor that defines the settings and configurations of a computation \n by a graphical user interface.\n \"\"\"\n function ComputationGuiSettings(comp::Atomic.Computation)\n ac = comp; nmd = ac.nuclearModel\n \n t1 = \"A slider: \"\n b1 = slider(1:110, label = \"charge\", value = nmd.Z)\n update = button(\"Update\")\n ui = vbox( hbox( pad(0em, t1) ),\n hbox( pad(0em, b1) ),\n hbox( pad(1em, update) )\n )\n #\n Interact.display(ui) \n output = Interact.@map (&update; observe(b1)[] )\n return( output )\n end\n\nend # module\n", "meta": {"hexsha": "411983526c4c3cc8c2ff3162d649414669ac0d77", "size": 39619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-Atomic.jl", "max_stars_repo_name": "SanjiangYang/JAC.jl", "max_stars_repo_head_hexsha": "f5612dd0912d95da0a22efa1224381606f0012d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-15T11:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T11:27:51.000Z", "max_issues_repo_path": "src/module-Atomic.jl", "max_issues_repo_name": "Zstar95/JAC.jl", "max_issues_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-Atomic.jl", "max_forks_repo_name": "Zstar95/JAC.jl", "max_forks_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-30T13:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T13:09:52.000Z", "avg_line_length": 71.7735507246, "max_line_length": 167, "alphanum_fraction": 0.5834321916, "num_tokens": 8301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.31069439597968646, "lm_q1q2_score": 0.17346907283088847}} {"text": "#\n# Use git: git status ....; git add ; git commit -m \"..\"; git push; git rm \n# Use Jupyter notebooks: using IJulia; notebook()\n# Activation: ]; pkg> up; pkg> activate\n# Working with JAC: using Revise; using JAC; include(\"../src/jac.jl\"); pkg> test\n# \n# Copy to desktop scp -r JAC.jl/ fritzsch@10.140.119.236:~/fri/.\n\"\"\"\n`module JAC` \n ... Jena Atomic Calculator (JAC) provides tools for performing atomic (structure) calculations at various degrees of complexity \n and sophistication. It has been designed to not only calculate atomic level structures and properties [such as g-factors or\n hyperfine and isotope-shift parameters] but also transition amplitudes between bound-state levels [for the anapole moment, dipole \n operator, electron electric-dipole moment, parity non-conservation, etc.] and, in particular, (atomic) transition probabilities, \n Auger rates, photoionization cross sections, radiative and dielectronic recombination rates as well as cross sections for many \n other (elementary) processes. JAC also facilitates interactive computations, the simulation of atomic cascades, the time-evolution \n of statistical tensors, a few semi-empirical estimates of atomic properties as well as the simplification of symbolic expressions\n from Racah's algebra. -- In addition, the JAC module supports the display of level energies, electron and photon spectra, \n radial orbitals and other atomic data.\n\n\n**`Perform (atomic) computations of different complexity:`** \n JAC will eventually support **ten kinds** of computations which can be summarized as follows:\n\n + Atomic computations, based on explicitly specified electron configurations.\n + Restricted active-space computations (RAS).\n + Interactive computations.\n + Atomic cascade computations (partly implemented).\n + Atomic representations (Green and close-coupling functions, complex rotation; partly implemented).\n + Atomic responses (partly implemented).\n + Atomic descriptors for machine learning algorithms (not yet implemented).\n + Time-evolution of statistical tensors in (intense) light pusles (not yet implemented).\n + Semi-empirical estimates of cross sections, etc. (partly implemented).\n + Symbolic evaluation of expressions from Racah's algebra, etc.\n\n\n**`Further details and information`**\n\n + Kinds of atomic implementation [cf. ? Details.kindsOfComputation]\n + Atomic amplitudes (partly) implemented in JAC [cf. ? Details.amplitudes]\n + Atomic level properties (partly) implemented in JAC [cf. ? Details.properties]\n + Atomic processes (partly) implemented in JAC [cf. ? Details.processes]\n + Interactive use of JAC procedures [cf. ? Details.interactive]\n + Design principles and limitations of the JAC program [cf. ? Details.design]\n + Data types, structs and name conventions of the JAC module [cf. ? Details.datatypes]\n + Atomic cascade computations and approximations [cf. ? Details.decayCascades]\n + Use of (em) light pulses in the time evolution of statist. tensors [cf. ? Details.pulses]\n + Why Julia ? [cf. ? Details.whyJulia]\n\n\"\"\"\nmodule JAC\n\nusing Dates, Printf, LinearAlgebra, IJulia, SpecialFunctions, FortranFiles, QuadGK, GSL, JLD2, SymEngine, \n HypergeometricFunctions ## , Interact, GaussQuadrature\n\nexport AbstractConfigurationRestriction, AbstractEeInteraction, AbstractCImethod, AbstractPotential, AbstractQedModel, AbstractStartOrbitals,\n AbstractProcessSettings, AbstractPropertySettings, \n add, analyze, AlphaX, AlphaVariation, AnapoleMoment, \n AngularJ64, AngularM64, AngularJ, AngularMomentum, \n AsfSettings, Atomic, AtomicState, AtomicStructure, Auger, AugerInPlasma, AutoIonization, \n Basics, Basis, BreitInteraction, Bsplines,\n CartesianVector, CiSettings, CiExpansion, CloseCoupling, compute, convertUnits, Cascade, Compton, Configuration, ConfigurationR, \n Continuum, CsfR, Coulex, CoulombExcitation, Coulion, CoulombIonization, CoulombBreit, CoulombInteraction, ClebschGordan, \n CorePolarization,\n diagonalize, Defaults, DecayYield, Details, Dielectronic, Dierec, Djpq, DoubleAutoIonization, DoubleAuger,\n Eimex, ElectronCapture, ElecCapture, estimate, ElectricDipoleMoment, Einstein, EinsteinX, EmMultipole, evaluate, ExpStokes,\n E1, M1, E2, M2, E3, M3, E4, M4,\n FormFactor, FormF, FullCIeigen,\n generate, GreenSettings, GreenChannel, GreenExpansion, getDefaults, Green, Gui,\n Hfs, HighHarmonic, HFS, HydrogenicIon,\n interpolate, integrate, Integral, ImpactExcAuto, ImpactExcitation, ImpactExcitationAutoion, ImpactIonization, \n InternalConv, InternalConversion, Isotope, IsotopeShift, \n Kronecker,\n LandeZeeman, LandeJ, LandeF, Level, LevelSymmetry, LSjj, LSjjSettings, LevelSelection, LineSelection, \n ManyElectron, MeanFieldSettings, MeanFieldBasis, minus, Model, modify, MultiPhotonDE, MultiPhotonDeExcitation, MultiPhotonDoubleIon, \n MultiPI, MultiPDI, MultiPhotonIonization, MultipoleMoment, MultipolePolarizibility, Multiplet, \n NoAmplitude, NoProcess, Nuclear, NoneQed, NoProperty, \n OneElectronSettings, OneElectronSpectrum, Orbital, \n PathwaySelection, perform, provide, PairA1P, PairAnnihilation1Photon, PairAnnihilation2Photon, \n PairProduction, ParityNonConservation, PeriodicTable, Parity, plus,\n Photo, PhotoExc, PhotoExcAuto, PhotoExcFluor, PhotoEmission, PhotoExcitation, PhotoExcitationAutoion, PhotoExcitationFluores, \n PhotoIonAuto, PhotoIonFluor, PhotoDouble, PhotoIonization, PhotoDoubleIonization, PhotoIonizationFluores, PhotoIonizationAutoion, \n PhotoRecombination, PlasmaShift, Plasma, Polarity, Pulse,\n QedPetersburg, QedSydney,\n RacahAlgebra, RacahExpression, Radial, RadialIntegrals, Radiative, RadiativeAuger, RAuger, RasSettings, RasStep, \n RasExpansion, RayleighCompton, recast, Rec, REDA, READI, Representation, ReducedDensityMatrix, RadiativeOpacity,\n RestrictNoElectronsTo, RestrictParity, RestrictToShellDoubles, RequestMinimumOccupation, RequestMaximumOccupation,\n SchiffMoment, Semiempirical, setDefaults, Shell, SolidAngle, Spectroscopy, SpinAngular, SphericalTensor, \n StartFromHydrogenic, StartFromPrevious, StrongField, Subshell,\n tabulate, TestFrames, Triangle, tools,\n UseCoulomb, UseBabushkin, UseGauge,\n WeightedCartesian, W3j, W6j, W9j,\n Yields, Ylm, \n Zeeman\n \n# Basic data and data structures\ninclude(\"module-Basics.jl\"); using ..Basics\ninclude(\"module-Radial.jl\"); using ..Radial\ninclude(\"module-Math.jl\"); using ..Math\ninclude(\"module-Defaults.jl\"); using ..Defaults\ninclude(\"module-ManyElectron.jl\"); using ..ManyElectron\ninclude(\"module-Nuclear.jl\"); using ..Nuclear\ninclude(\"module-BiOrthogonal.jl\"); using ..BiOrthogonal\n\n# Specialized functions/methods to manipulate these data\ninclude(\"module-AngularMomentum.jl\")\n## include(\"module-AngularCoefficients-Ratip2013.jl\") ## keep for internal test purposes only\ninclude(\"module-SpinAngular.jl\"); using ..SpinAngular\ninclude(\"module-Bsplines.jl\")\ninclude(\"module-Continuum.jl\")\ninclude(\"module-Details.jl\")\ninclude(\"module-RadialIntegrals.jl\")\ninclude(\"module-HydrogenicIon.jl\")\ninclude(\"module-InteractionStrength.jl\")\ninclude(\"module-InteractionStrengthQED.jl\")\ninclude(\"module-PeriodicTable.jl\")\ninclude(\"module-TableStrings.jl\")\ninclude(\"module-Tools.jl\")\ninclude(\"module-AtomicState.jl\"); using ..AtomicState\ninclude(\"module-LSjj.jl\")\n\n# Functions/methods for atomic amplitudes\ninclude(\"module-MultipoleMoment.jl\")\ninclude(\"module-ParityNonConservation.jl\") \n\ninclude(\"module-PhotoEmission.jl\")\n\n# Functions/methods for atomic properties\ninclude(\"module-Einstein.jl\") \ninclude(\"module-Hfs.jl\")\ninclude(\"module-IsotopeShift.jl\")\ninclude(\"module-LandeZeeman.jl\")\ninclude(\"module-FormFactor.jl\")\ninclude(\"module-ReducedDensityMatrix.jl\")\ninclude(\"module-PlasmaShift.jl\")\ninclude(\"module-AlphaVariation.jl\")\ninclude(\"module-DecayYield.jl\")\ninclude(\"module-RadiativeOpacity.jl\")\n##x include(\"module-CloseCoupling.jl\")\ninclude(\"module-MultipolePolarizibility.jl\")\n\n# Functions/methods for atomic processes\ninclude(\"module-PhotoExcitation.jl\")\ninclude(\"module-PhotoIonization.jl\")\ninclude(\"module-PhotoRecombination.jl\")\ninclude(\"module-AutoIonization.jl\")\ninclude(\"module-ElectronCapture.jl\")\ninclude(\"module-Dielectronic.jl\")\ninclude(\"module-PhotoExcitationFluores.jl\")\ninclude(\"module-PhotoExcitationAutoion.jl\")\ninclude(\"module-RayleighCompton.jl\")\ninclude(\"module-MultiPhotonDeExcitation.jl\")\ninclude(\"module-DoubleAutoIonization.jl\")\ninclude(\"module-PhotoDoubleIonization.jl\")\ninclude(\"module-CoulombExcitation.jl\")\ninclude(\"module-PhotoIonizationFluores.jl\")\ninclude(\"module-PhotoIonizationAutoion.jl\")\ninclude(\"module-CoulombIonization.jl\")\ninclude(\"module-ImpactExcitation.jl\")\ninclude(\"module-ImpactExcitationAutoion.jl\")\ninclude(\"module-RadiativeAuger.jl\")\ninclude(\"module-MultiPhotonIonization.jl\")\ninclude(\"module-MultiPhotonDoubleIon.jl\")\ninclude(\"module-InternalConversion.jl\") \n#= Further processes, not yet included into the code\ninclude(\"module-REDA.jl\")\ninclude(\"module-READI.jl\")\ninclude(\"module-PairProduction.jl\")\ninclude(\"module-PairAnnihilation1Photon.jl\")\ninclude(\"module-PairAnnihilation2Photon.jl\") =#\n\n# Functions/methods for atomic responses and time evolutions\ninclude(\"module-Pulse.jl\")\n# include(\"module-Statistical.jl\")\n\n# Functions/methods for the computation of atomic responses\n## include(\"module-HighHarmonic.jl\")\ninclude(\"module-StrongField.jl\") \n\n# Functions/methods for semi-empirical estimations\n# include(\"module-ImpactIonization.jl\")\ninclude(\"module-Semiempirical.jl\")\n\n# Functions/methods for atomic and cascade computations\ninclude(\"module-Atomic.jl\"); using ..Atomic\ninclude(\"module-Cascade.jl\"); using ..Cascade\n\n# Functions/methods for symbolic computations\ninclude(\"module-RacahAlgebra.jl\"); using ..RacahAlgebra\ninclude(\"module-SphericalTensor.jl\"); using ..SphericalTensor\n\n# Basic functions/methods to manipulate these data\ninclude(\"module-BasicsAZ.jl\")\ninclude(\"module-ManyElectronAZ.jl\")\n\n# Specialized macros\n##x include(\"macro-racahsum.jl\")\n\n# All test functions/methods stay with the JAC root module\ninclude(\"module-TestFrames.jl\"); using ..TestFrames\n \nfunction __init__()\n # The following variables need to be initialized at runtime to enable precompilation\n global JAC_SUMMARY_IOSTREAM = stdout\n global JAC_TEST_IOSTREAM = stdout\nend\n\nprintln(\"\\nWelcome to JAC: A community approach to the computation of atomic structures, cascades and time evolutions \" * \n \"[(C) Copyright by Stephan Fritzsche, Jena (2018-2021)].\")\n\nend\n\n\n", "meta": {"hexsha": "5cb55fd94a1a24c9b67b1492fd67a80f6296f08e", "size": 11186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JAC.jl", "max_stars_repo_name": "Joseph-33/JACFork.jl", "max_stars_repo_head_hexsha": "e866abe256e9ae4dc5293a7efe9a24a5e6213f90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/JAC.jl", "max_issues_repo_name": "Joseph-33/JACFork.jl", "max_issues_repo_head_hexsha": "e866abe256e9ae4dc5293a7efe9a24a5e6213f90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JAC.jl", "max_forks_repo_name": "Joseph-33/JACFork.jl", "max_forks_repo_head_hexsha": "e866abe256e9ae4dc5293a7efe9a24a5e6213f90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.5164319249, "max_line_length": 141, "alphanum_fraction": 0.7352047202, "num_tokens": 2782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.1715082563509505}} {"text": "module NonMeansTestedBenefits\n#\n# This module provides routines for benefits which are (mostly) not means-tested benefits,\n# both current and historic. See [HistoricBenefits.jl] for the imputation routines used here.\n#\n using Base: has_tight_type\n using Dates\n using Dates: Date, now, TimeType, Year\n using ScottishTaxBenefitModel\n\n using .Definitions\n using .STBIncomes\n\n using .Utils: nearest\n\n using .ModelHousehold: \n BenefitUnit, \n Household, \n Person, \n get_benefit_units,\n has_income,\n num_children\n\n using .BenefitGenerosity: change_status\n\n using .Intermediate:\n has_limited_capactity_for_work_activity,\n has_limited_capactity_for_work,\n make_recipient\n \n using .STBParameters: \n AgeLimits, \n AttendanceAllowance, \n BereavementSupport, \n CarersAllowance, \n ChildBenefit, \n ContributoryESA,\n DisabilityLivingAllowance, \n HoursLimits,\n JobSeekersAllowance, \n MaternityAllowance,\n NonMeansTestedSys, \n PersonalIndependencePayment, \n RetirementPension, \n WidowsPensions, \n reached_state_pension_age\n \n using .Results: \n BenefitUnitResult, \n HouseholdResult, \n IndividualResult, \n LMTIncomes\n\n export \n calc_child_benefit!, \n calc_dla, \n calc_pip,\n calc_post_tax_non_means_tested!,\n calc_pre_tax_non_means_tested!, \n calc_state_pension, \n calc_widows_benefits\n \n \"\"\"\n Child Benefit - this has to be done *after* income tax, so we have\n income tax `total_income` for each adult in the `BenefitUnitResult` struct.\n \"\"\"\n function calc_child_benefit!( \n bures :: BenefitUnitResult,\n bu :: BenefitUnit, \n cb :: ChildBenefit{T} ) :: T where T\n c = zero(T)\n #= FIXME something to check the exact type of children - \n for now, assume the BU allocation has got this right.\n for pid in bu.children\n #\n end\n =#\n if cb.abolished \n return c\n end\n nc = num_children(bu)\n if nc == 0\n return 0.0\n end\n c += cb.first_child\n if nc > 1\n c += (nc-1)*cb.other_children\n end\n recipient = make_recipient( bu, CHILD_BENEFIT )\n # guardian's allowance\n bures.pers[recipient].income[GUARDIANS_ALLOWANCE] = 0.0\n\n # println( bu.people[bu.head].relationships)\n \n if c > 0 # fixme not quite right - qualify for CB for each child\n for cp in bu.children\n # this checks if anyone in the BU has a parent-like\n # relationship to the child\n is_guardian = true\n for pid in bu.adults\n if ! (bu.people[pid].relationships[cp] in [Grand_parent, Other_relative, Other_non_relative])\n is_guardian = false\n break;\n end\n end\n if is_guardian \n # FIXME we could also guess approx number of kids \n # qualifying for GA from receipt in HistoricBenefits || has_income( bu, guardians_allowance )\n bures.pers[recipient].income[GUARDIANS_ALLOWANCE] += \n cb.guardians_allowance\n end\n end\n end # guardian's allowance\n # cb but not guardians withdrawn with high incomes\n # high income thing - highest of the BU's *individual* income; see cpag ch.27\n max_inc = zero(T)\n for pid in bu.adults\n max_inc = max( max_inc, bures.pers[pid].it.total_income )\n if bu.people[pid].sex == Female\n recipient = pid\n end\n end\n if max_inc > cb.high_income_thresh\n # this should really be done in steps £1 for every £100, but since\n # everything is weekly here we'll just multiply\n withdrawn = cb.withdrawal*(max_inc - cb.high_income_thresh)\n c = max(0.0, c-withdrawn)\n end\n bures.pers[recipient].income[CHILD_BENEFIT] = c \n end\n\n function calc_widows_benefits(\n pers :: Person{T}, \n has_kids :: Bool, \n bp :: BereavementSupport{T},\n wp :: WidowsPensions{T}) :: T where T\n wid = zero(T)\n if wp.abolished || bp.abolished\n return wid\n end\n #\n # We don't know when someone was widowed\n # so we rely on this. FIXME Obviously this gets progressively worse as time goes on and\n # we keep using the old years of FRS.\n #\n # new-style: payable for 18 months at a flat rate\n # CHECK 2829 2017 why is that bereavment_support?\n if pers.bereavement_type in [bereavement_allowance,bereavement_support]\n # payable for 18 months so we'll allocate\n # 2/3rds of the weekly value of the lump-sum\n if has_kids\n wid = bp.higher + bp.lump_sum_higher*2/3\n else\n wid = bp.lower + bp.lump_sum_lower*2/3\n end\n elseif pers.bereavement_type == widowed_parents # At least 3 years ago so no \n # need to worry about lump-sums; just scale\n # the standard rate by the ratio of\n # their receipt to the standard rate at the time\n # of interview. CHECK hhld 477 2015 for an example\n # of someone with the lump sum but no standard benefit\n # so no ratio; for us, just assign the standard \n # rate in those cases.\n #\n # println( \"pers.benefit_ratios $(pers.benefit_ratios)\")\n if haskey( pers.benefit_ratios, bereavement_allowance_or_widowed_parents_allowance_or_bereavement )\n wid = pers.benefit_ratios[bereavement_allowance_or_widowed_parents_allowance_or_bereavement]*\n wp.standard_rate \n else\n wid = wp.standard_rate\n end\n else\n # check we're not missing anyone\n @assert ! haskey( pers.benefit_ratios, bereavement_allowance_or_widowed_parents_allowance_or_bereavement)\n end\n return wid\n end\n\n \"\"\"\n PIP and DLA (below) rely on all the types being sorted out earlier\n either in some kind of probit or by being inferred from receipts (see [HistoricBenefits.jl] for\n what we have so far).\n \"\"\"\n function calc_pip( \n pers :: Person{T},\n pip :: PersonalIndependencePayment{T}) :: Tuple{T,T} where T\n pl = zero(T)\n pm = zero(T)\n daily_type = pers.pip_daily_living_type\n mob_type = pers.pip_mobility_type\n if pip.abolished\n return (pl, pm )\n end\n daily_type = change_status( \n candidates=pip.dl_candidates, \n pid=pers.pid, \n change=pip.extra_people,\n choices=[standard_pip,enhanced_pip],\n current_value=daily_type, \n disqual_value=no_pip )\n mob_type = change_status( \n candidates=pip.mobility_candidates, \n pid=pers.pid, \n choices=[standard_pip,enhanced_pip],\n change=pip.extra_people,\n current_value=mob_type, \n disqual_value=no_pip )\n \n # fixme consistent names dl->daily living etc.\n if daily_type == standard_pip\n pl = pip.dl_standard \n elseif daily_type == enhanced_pip\n pl = pip.dl_enhanced \n end\n if mob_type == standard_pip\n pm = pip.mobility_standard \n elseif mob_type == enhanced_pip\n pm = pip.mobility_enhanced \n end\n return (pl, pm )\n end # pip calc\n\n function calc_attendance_allowance(\n pers :: Person{T},\n aa :: AttendanceAllowance{T},\n ) :: T where T\n a =zero(T)\n if aa.abolished\n return a\n end\n at = pers.attendance_allowance_type\n at = change_status( \n candidates=aa.candidates, \n pid=pers.pid, \n choices=[high,low],\n change=aa.extra_people,\n current_value=at, \n disqual_value=missing_lmh )\n if at == missing_lmh\n a = zero(T)\n elseif at == high\n a = aa.higher\n else\n a = aa.lower;\n end\n return a\n end\n\n function calc_dla(\n pers :: Person{T},\n dla :: DisabilityLivingAllowance{T} ) :: Tuple{T,T} where T\n dc = zero(T)\n dm = zero(T)\n if dla.abolished\n return (dc,dm)\n end\n dla_s = pers.dla_self_care_type\n dla_m = pers.dla_mobility_type\n # FIXME we use the same list for both mob and self\n # I think because of small sample size (kids only)\n dla_s = change_status( \n candidates=dla.candidates, \n pid=pers.pid, \n choices=[high,mid,low],\n change=dla.extra_people,\n current_value=dla_s, \n disqual_value=missing_lmh )\n dla_m = change_status( \n candidates=dla.candidates, \n pid=pers.pid, \n choices=[high,mid,low],\n change=dla.extra_people,\n current_value=dla_m, \n disqual_value=missing_lmh )\n # FIXME make all these names constisent (mid/middle,care->self_care etc.)\n if dla_s == high \n dc = dla.care_high\n elseif dla_s == mid\n dc = dla.care_middle\n elseif dla_s == low \n dc = dla.care_low\n end\n if dla_m == high \n dm = dla.mob_high\n elseif dla_m in (low,mid)\n dm = dla.mob_low\n end\n # println( \"setting DLA as $dc, $dm\")\n return (dc,dm);\n end # dla calc\n\n function calc_state_pension( \n pers :: Person{T}, \n rp :: RetirementPension{T},\n age_limits :: AgeLimits ) :: T where T\n pen = zero(T)\n if rp.abolished\n return pen\n end\n if reached_state_pension_age( \n age_limits, \n pers.age, \n pers.sex )\n # so, was someone over pension age *before* the new state pension?\n # if so, use the proportion of the `class_a` they seemed to be on at \n # the time, times the current `class_a`. \n if reached_state_pension_age(\n # old style \n age_limits, \n pers.age, \n pers.sex,\n age_limits.savings_credit_to_new_state_pension )\n # println( \"pers.benefit_ratios $(pers.benefit_ratios)\")\n if ! haskey( pers.benefit_ratios, state_pension ) \n ratio = pers.age < 70 ? 0.0 : 1.0 # kinda crude deferrment\n else\n ratio = pers.benefit_ratios[state_pension]\n end\n pen = ratio*rp.cat_a\n else\n # \n # new style\n pen = rp.new_state_pension\n end\n end\n return pen\n end\n\n \"\"\"\n FIXME Model this properly\n \"\"\"\n function calc_esa( \n pers :: Person{T}, \n esa :: ContributoryESA{T}) :: T where T\n e = zero(T)\n if esa.abolished\n return e\n end\n if pers.esa_type == contributory_jsa\n if pers.age < 25\n # FIXME not quite right since\n # could be past assessment stage;\n # maybe check time out of work?\n e = esa.assessment_u25\n else\n e = esa.main\n end\n if has_limited_capactity_for_work_activity( pers )\n e += esa.support\n end\n end\n return e\n end\n\n function calc_maternity_allowance( \n pers :: Person{T},\n ma :: MaternityAllowance ) :: T where T\n m = zero(T)\n if ma.abolished\n return m\n end\n # fixme the design means you should never have to check the incomes dict here\n if has_income( pers, maternity_allowance ) \n m = ma.rate\n end\n return m\n end\n\n function calc_carers_allowance( \n pers :: Person{T}, \n pres :: IndividualResult{T},\n carers :: CarersAllowance{T}) :: T where T\n c = zero(T)\n if carers.abolished\n return c\n end\n earnings :: T = isum(\n pres.income, \n carers.earnings;\n deducted=carers.deductions )\n # println( \"earnings=$earnings carers.gainful_employment_min=$(carers.gainful_employment_min)\")\n if pers.hours_of_care_given >= carers.hours && \n earnings < carers.gainful_employment_min\n c = carers.allowance\n end\n return c\n end\n\n function calc_jsa( \n pers :: Person{T}, \n jsa :: JobSeekersAllowance{T},\n hrs :: HoursLimits ) :: T where T\n j = zero(T) \n if jsa.abolished\n return j\n end\n if pers.jsa_type == contributory_jsa &&\n pers.usual_hours_worked <= hrs.med &&\n (! has_limited_capactity_for_work( pers ))\n j = pers.age < 25 ? jsa.u25 : jsa.o24\n end\n return j\n end\n\n \"\"\"\n Household level calculations for all nmt benefits that don't require knowlege\n of income tax/ni liabilties - not necessarily taxable benefits, just things\n that don't require any kind of net income calculation and so can be done\n before IT/NI.\n \"\"\"\n function calc_pre_tax_non_means_tested!( \n hhres :: HouseholdResult,\n hh :: Household,\n sys :: NonMeansTestedSys,\n hours_limits :: HoursLimits,\n age_limits :: AgeLimits ) \n ## maybe add a benefit unit allocator\n bus = get_benefit_units( hh )\n buno = 1 \n for bu in bus \n has_children = size( bu.children )[1] > 0\n bures = hhres.bus[buno]\n for adno in bu.adults\n pers = bu.people[adno]\n pres = bures.pers[adno]\n pres.income[STATE_PENSION] = calc_state_pension( \n pers,\n sys.pensions, age_limits );\n pres.income[WIDOWS_PAYMENT] = calc_widows_benefits(\n pers, has_children, sys.bereavement, sys.widows_pension )\n #\n # FIXME\n # pip/dla can only be claimed \n # if ! reached_state_pension_age( age_limits, pers.age, pers.sex )\n # but claims can run on indefinitely and for now we're just using \n # receipts, so ignore any upper age limits until we model these fully.\n #\n pres.income[sys.dla.care_slot],\n pres.income[sys.dla.mob_slot] = calc_dla( pers, sys.dla );\n pres.income[sys.pip.care_slot],\n pres.income[sys.pip.mob_slot] = calc_pip( pers, sys.pip )\n \n #\n # .. conversely, this age limit seems safe: a 62 yo female recieving\n # in the data should be disallowed now the pension age has increased.\n #\n if reached_state_pension_age( age_limits, pers.age, pers.sex )\n pres.income[sys.attendance_allowance.slot] = calc_attendance_allowance( pers, sys.attendance_allowance )\n else\n pres.income[CONTRIB_EMPLOYMENT_AND_SUPPORT_ALLOWANCE] = calc_esa( pers, sys.esa )\n pres.income[CONTRIB_JOBSEEKERS_ALLOWANCE] = calc_jsa( pers, sys.jsa, hours_limits )\n pres.income[MATERNITY_ALLOWANCE] = calc_maternity_allowance( pers, sys.maternity )\n end\n # NON-overlapping rules p1178 go here \n end # ad loop\n buno += 1\n end # bu loop\n end # calc_non_means_tested\n\n \"\"\"\n NMT Benefits that require knowlege of tax and NI liabilities and so have to be done\n after a tax calculation - not necessarily tax free as such (CB higher charge). Kinda-sorta\n means-tested bens, I suppose.\n \"\"\"\n function calc_post_tax_non_means_tested!( \n hhres :: HouseholdResult,\n hh :: Household,\n sys :: NonMeansTestedSys,\n age_limits :: AgeLimits ) \n ## maybe add a benefit unit allocator\n bus = get_benefit_units( hh )\n buno = 1 \n for bu in bus \n has_children = size( bu.children )[1] > 0\n bures = hhres.bus[buno]\n calc_child_benefit!( \n bures,\n bu, \n sys.child_benefit )\n for adno in bu.adults\n pers = bu.people[adno]\n pres = bures.pers[adno]\n pres.income[sys.carers.slot] = \n calc_carers_allowance( pers, pres, sys.carers )\n \n if hh.region == Scotland\n if pres.income[sys.carers.slot] > 0\n pres.income[SCOTTISH_CARERS_SUPPLEMENT] = sys.carers.scottish_supplement\n end\n end\n # NON-overlapping rules p1178 go here \n end # ad loop\n buno += 1\n end # bu loop\n end # calc_non_means_tested\n\nend # package non-means-tested", "meta": {"hexsha": "b4e2da28a8c75c18dddcf76d0d4d04739b252500", "size": 17473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NonMeansTestedBenefits.jl", "max_stars_repo_name": "grahamstark/ScottishTaxBenefitModel", "max_stars_repo_head_hexsha": "894f37c6debec271a0e4e4f09aa7b9599423d563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NonMeansTestedBenefits.jl", "max_issues_repo_name": "grahamstark/ScottishTaxBenefitModel", "max_issues_repo_head_hexsha": "894f37c6debec271a0e4e4f09aa7b9599423d563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NonMeansTestedBenefits.jl", "max_forks_repo_name": "grahamstark/ScottishTaxBenefitModel", "max_forks_repo_head_hexsha": "894f37c6debec271a0e4e4f09aa7b9599423d563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1569416499, "max_line_length": 124, "alphanum_fraction": 0.5515938877, "num_tokens": 4135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.1713806584178098}} {"text": "# Extend Zygote to work with static vectors and custom types on the GPU\n# Here be dragons\n\nusing ForwardDiff: Chunk, Dual, dualize, partials, value\nusing Zygote: unbroadcast\n\nZygote.accum(x::AbstractArray{<:SizedVector}, ys::AbstractArray{<:SVector}...) = Zygote.accum.(convert(typeof(ys[1]), x), ys...)\nZygote.accum(x::AbstractArray{<:SVector}, ys::AbstractArray{<:SizedVector}...) = Zygote.accum.(x, convert.(typeof(x), ys)...)\n\nBase.:+(x::Real, y::SizedVector) = x .+ y\nBase.:+(x::SizedVector, y::Real) = x .+ y\n\nBase.:+(x::Real, y::Zygote.OneElement) = x .+ y\nBase.:+(x::Zygote.OneElement, y::Real) = x .+ y\n\nfunction Base.:+(x::Atom{T, T, T, T}, y::Atom{T, T, T, T}) where T\n Atom{T, T, T, T}(0, x.charge + y.charge, x.mass + y.mass, x.σ + y.σ, x.ϵ + y.ϵ)\nend\n\nfunction Base.:-(x::Atom{T, T, T, T}, y::Atom{T, T, T, T}) where T\n Atom{T, T, T, T}(0, x.charge - y.charge, x.mass - y.mass, x.σ - y.σ, x.ϵ - y.ϵ)\nend\n\nfunction Zygote.accum(x::LennardJones{S, C, W, F, E}, y::LennardJones{S, C, W, F, E}) where {S, C, W, F, E}\n LennardJones{S, C, W, F, E}(x.cutoff, x.nl_only, x.lorentz_mixing, x.weight_14 + y.weight_14, x.force_units, x.energy_units)\nend\n\nfunction Zygote.accum(x::CoulombReactionField{D, S, W, T, F, E}, y::CoulombReactionField{D, S, W, T, F, E}) where {D, S, W, T, F, E}\n CoulombReactionField{D, S, W, T, F, E}(x.dist_cutoff + y.dist_cutoff, x.solvent_dielectric + y.solvent_dielectric, x.nl_only,\n x.weight_14 + y.weight_14, x.coulomb_const + y.coulomb_const, x.force_units, x.energy_units)\nend\n\nfunction Zygote.accum_sum(xs::AbstractArray{Tuple{LennardJones{S, C, W, F, E}, CoulombReactionField{D, SO, W, T, F, E}}}; dims=:) where {S, C, W, F, E, D, SO, T}\n reduce(Zygote.accum, xs, dims=dims; init=(\n LennardJones{S, C, W, F, E}(nothing, false, false, zero(W), NoUnits, NoUnits),\n CoulombReactionField{D, SO, W, T, F, E}(zero(D), zero(S), false, zero(W), zero(T), NoUnits, NoUnits),\n ))\nend\n\nfunction Zygote.accum(x::Tuple{NTuple{N, Int}, NTuple{N, T}, NTuple{N, E}},\n y::Tuple{NTuple{N, Int}, NTuple{N, T}, NTuple{N, E}}) where {N, T, E}\n ntuple(n -> 0, N), x[2] .+ y[2], x[3] .+ y[3]\nend\n\nBase.zero(::Type{Atom{T, T, T, T}}) where {T} = Atom(0, zero(T), zero(T), zero(T), zero(T))\natom_or_empty(at::Atom, T) = at\natom_or_empty(at::Nothing, T) = zero(Atom{T, T, T, T})\n\nZygote.z2d(dx::AbstractArray{Union{Nothing, Atom{T, T, T, T}}}, primal::AbstractArray{Atom{T, T, T, T}}) where {T} = atom_or_empty.(dx, T)\nZygote.z2d(dx::SVector{3, T}, primal::T) where {T} = sum(dx)\n\nZygote.unbroadcast(x::Tuple{Any}, x̄::Nothing) = nothing\n\nfunction Zygote.unbroadcast(x::AbstractArray{<:Real}, x̄::AbstractArray{<:StaticVector})\n if length(x) == length(x̄)\n Zygote._project(x, sum.(x̄))\n else\n dims = ntuple(d -> size(x, d) == 1 ? d : ndims(x̄) + 1, ndims(x̄))\n Zygote._project(x, accum_sum(x̄; dims=dims))\n end\nend\n\nZygote._zero(xs::AbstractArray{<:StaticVector}, T) = fill!(similar(xs, T), zero(T))\n\nfunction Zygote._zero(xs::AbstractArray{Atom{T, T, T, T}}, ::Type{Atom{T, T, T, T}}) where {T}\n fill!(similar(xs), Atom{T, T, T, T}(0, zero(T), zero(T), zero(T), zero(T)))\nend\n\nfunction Base.zero(::Type{Union{Nothing, SizedVector{D, T, Vector{T}}}}) where {D, T}\n zero(SizedVector{D, T, Vector{T}})\nend\n\n# Slower version than in Zygote but doesn't give wrong gradients on the GPU for repeated indices\n# Here we just move it to the CPU then move it back\n# See https://github.com/FluxML/Zygote.jl/pull/1131\nZygote.∇getindex(x::CuArray, inds::Tuple{AbstractArray{<:Integer}}) = dy -> begin\n inds1_cpu = Array(inds[1])\n dx = Zygote._zero(Array(x), eltype(dy))\n dxv = view(dx, inds1_cpu)\n dxv .= Zygote.accum.(dxv, Zygote._droplike(Array(dy), dxv))\n return Zygote._project(x, cu(dx)), nothing\nend\n\n# Extend to add extra empty partials before (B) and after (A) the SVector partials\n@generated function ForwardDiff.dualize(::Type{T}, x::StaticArray, ::Val{B}, ::Val{A}) where {T, B, A}\n N = length(x)\n dx = Expr(:tuple, [:(Dual{T}(x[$i], chunk, Val{$i + $B}())) for i in 1:N]...)\n V = StaticArrays.similar_type(x, Dual{T, eltype(x), N + B + A})\n return quote\n chunk = Chunk{$N + $B + $A}()\n $(Expr(:meta, :inline))\n return $V($(dx))\n end\nend\n\n# Dualize a value with extra partials\nmacro dualize(x, n_partials::Integer, active_partial::Integer)\n ps = [i == active_partial for i in 1:n_partials]\n return :(ForwardDiff.Dual($(esc(x)), $(ps...)))\nend\n\n# Space for 4 duals given to interactions though only one used in this case\n# No gradient for cutoff type\nfunction dualize_fb(inter::LennardJones{S, C, W, F, E}) where {S, C, W, F, E}\n w14 = inter.weight_14\n dual_weight_14 = @dualize(w14, 21, 1)\n return LennardJones{S, C, typeof(dual_weight_14), F, E}(inter.cutoff, inter.nl_only,\n inter.lorentz_mixing, dual_weight_14, inter.force_units, inter.energy_units)\nend\n\nfunction dualize_fb(inter::CoulombReactionField{D, S, W, T, F, E}) where {D, S, W, T, F, E}\n dc, sd, w14, cc = inter.dist_cutoff, inter.solvent_dielectric, inter.weight_14, inter.coulomb_const\n dual_dist_cutoff = @dualize(dc , 21, 1)\n dual_solvent_dielectric = @dualize(sd , 21, 2)\n dual_weight_14 = @dualize(w14, 21, 3)\n dual_coulomb_const = @dualize(cc , 21, 4)\n return CoulombReactionField{typeof(dual_dist_cutoff), typeof(dual_solvent_dielectric), typeof(dual_weight_14), typeof(dual_coulomb_const), F, E}(\n dual_dist_cutoff, dual_solvent_dielectric, inter.nl_only, dual_weight_14,\n dual_coulomb_const, inter.force_units, inter.energy_units)\nend\n\nfunction dualize_fb(inter::HarmonicBond{D, K}) where {D, K}\n b0, kb = inter.b0, inter.kb\n dual_b0 = @dualize(b0, 11, 1)\n dual_kb = @dualize(kb, 11, 2)\n return HarmonicBond{typeof(dual_b0), typeof(dual_kb)}(dual_b0, dual_kb)\nend\n\nfunction dualize_fb(inter::HarmonicAngle{D, K}) where {D, K}\n th0, cth = inter.th0, inter.cth\n dual_th0 = @dualize(th0, 14, 1)\n dual_cth = @dualize(cth, 14, 2)\n return HarmonicAngle{typeof(dual_th0), typeof(dual_cth)}(dual_th0, dual_cth)\nend\n\nfunction dualize_fb(inter::PeriodicTorsion{6, T, E}) where {T, E}\n p1, p2, p3, p4, p5, p6 = inter.phases\n k1, k2, k3, k4, k5, k6 = inter.ks\n dual_phases = (\n @dualize(p1, 27, 1), @dualize(p2, 27, 2), @dualize(p3, 27, 3),\n @dualize(p4, 27, 4), @dualize(p5, 27, 5), @dualize(p6, 27, 6),\n )\n dual_ks = (\n @dualize(k1, 27, 7), @dualize(k2, 27, 8), @dualize(k3, 27, 9),\n @dualize(k4, 27, 10), @dualize(k5, 27, 11), @dualize(k6, 27, 12),\n )\n return PeriodicTorsion{6, eltype(dual_phases), eltype(dual_ks)}(inter.periodicities,\n dual_phases, dual_ks)\nend\n\nfunction dualize_atom_fb1(at::Atom)\n charge, mass, σ, ϵ = at.charge, at.mass, at.σ, at.ϵ\n dual_charge = @dualize(charge, 21, 11)\n dual_mass = @dualize(mass, 21, 12)\n dual_σ = @dualize(σ, 21, 13)\n dual_ϵ = @dualize(ϵ, 21, 14)\n return Atom{typeof(dual_charge), typeof(dual_mass), typeof(dual_σ), typeof(dual_ϵ)}(\n at.index, dual_charge, dual_mass, dual_σ, dual_ϵ)\nend\n\nfunction dualize_atom_fb2(at::Atom)\n charge, mass, σ, ϵ = at.charge, at.mass, at.σ, at.ϵ\n dual_charge = @dualize(charge, 21, 15)\n dual_mass = @dualize(mass, 21, 16)\n dual_σ = @dualize(σ, 21, 17)\n dual_ϵ = @dualize(ϵ, 21, 18)\n return Atom{typeof(dual_charge), typeof(dual_mass), typeof(dual_σ), typeof(dual_ϵ)}(\n at.index, dual_charge, dual_mass, dual_σ, dual_ϵ)\nend\n\nfunction dual_function_svec(f::F) where F\n function (arg1)\n ds1 = dualize(Nothing, arg1, Val(0), Val(0))\n return f(ds1)\n end\nend\n\nfunction dual_function_svec_real(f::F) where F\n function (arg1::SVector{D, T}, arg2) where {D, T}\n ds1 = dualize(Nothing, arg1, Val(0), Val(1))\n # Leaving the integer type in here results in Float32 -> Float64 conversion\n ds2 = Zygote.dual(isa(arg2, Int) ? T(arg2) : arg2, (false, false, false, true))\n return f(ds1, ds2)\n end\nend\n\nfunction dual_function_svec_svec(f::F) where F\n function (arg1, arg2)\n ds1 = dualize(Nothing, arg1, Val(0), Val(3))\n ds2 = dualize(Nothing, arg2, Val(3), Val(0))\n return f(ds1, ds2)\n end\nend\n\nfunction dual_function_atom(f::F) where F\n function (arg1)\n charge, mass, σ, ϵ = arg1.charge, arg1.mass, arg1.σ, arg1.ϵ\n ds1 = Atom(arg1.index, @dualize(charge, 4, 1), @dualize(mass, 4, 2),\n @dualize(σ, 4, 3), @dualize(ϵ, 4, 4))\n return f(ds1)\n end\nend\n\nfunction dual_function_force_broadcast(f::F) where F\n function (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)\n ds1 = (dualize_fb(arg1[1]), dualize_fb(arg1[2])) # Only works for this case\n ds2 = dualize(Nothing, arg2, Val(4), Val(14))\n ds3 = dualize(Nothing, arg3, Val(7), Val(11))\n ds4 = dualize_atom_fb1(arg4)\n ds5 = dualize_atom_fb2(arg5)\n ds6 = dualize(Nothing, arg6, Val(18), Val(0))\n ds7 = arg7\n ds8 = arg8\n return f(ds1, ds2, ds3, ds4, ds5, ds6, ds7, ds8)\n end\nend\n\nfunction dual_function_specific_2_atoms(f::F) where F\n function (arg1, arg2, arg3, arg4)\n ds1 = dualize_fb(arg1)\n ds2 = dualize(Nothing, arg2, Val(2), Val(6))\n ds3 = dualize(Nothing, arg3, Val(5), Val(3))\n ds4 = dualize(Nothing, arg4, Val(8), Val(0))\n return f(ds1, ds2, ds3, ds4)\n end\nend\n\nfunction dual_function_specific_3_atoms(f::F) where F\n function (arg1, arg2, arg3, arg4, arg5)\n ds1 = dualize_fb(arg1)\n ds2 = dualize(Nothing, arg2, Val( 2), Val(9))\n ds3 = dualize(Nothing, arg3, Val( 5), Val(6))\n ds4 = dualize(Nothing, arg4, Val( 8), Val(3))\n ds5 = dualize(Nothing, arg5, Val(11), Val(0))\n return f(ds1, ds2, ds3, ds4, ds5)\n end\nend\n\nfunction dual_function_specific_4_atoms(f::F) where F\n function (arg1, arg2, arg3, arg4, arg5, arg6)\n ds1 = dualize_fb(arg1)\n ds2 = dualize(Nothing, arg2, Val(12), Val(12))\n ds3 = dualize(Nothing, arg3, Val(15), Val( 9))\n ds4 = dualize(Nothing, arg4, Val(18), Val( 6))\n ds5 = dualize(Nothing, arg5, Val(21), Val( 3))\n ds6 = dualize(Nothing, arg6, Val(24), Val( 0))\n return f(ds1, ds2, ds3, ds4, ds5, ds6)\n end\nend\n\n@inline function sum_partials(sv::SVector{3, Dual{Nothing, T, P}}, y1, i::Integer) where {T, P}\n partials(sv[1], i) * y1[1] + partials(sv[2], i) * y1[2] + partials(sv[3], i) * y1[3]\nend\n\n@inline function Zygote.broadcast_forward(f, arg1::AbstractArray{SVector{D, T}}) where {D, T}\n out = dual_function_svec(f).(arg1)\n y = map(x -> value.(x), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg1 isa CuArray ? cu(ȳ_in) : ȳ_in\n barg1 = broadcast(ȳ, out) do y1, o1\n if length(y1) == 1\n y1 .* SVector{D, T}(partials(o1))\n else\n SVector{D, T}(sum_partials(o1, y1, 1), sum_partials(o1, y1, 2), sum_partials(o1, y1, 3))\n end\n end\n darg1 = unbroadcast(arg1, barg1)\n (nothing, nothing, darg1)\n end\n return y, bc_fwd_back\nend\n\n@inline function Zygote.broadcast_forward(f, arg1::AbstractArray{SVector{D, T}}, arg2) where {D, T}\n out = dual_function_svec_real(f).(arg1, arg2)\n y = map(x -> value.(x), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg1 isa CuArray ? cu(ȳ_in) : ȳ_in\n barg1 = broadcast(ȳ, out) do y1, o1\n if length(y1) == 1\n y1 .* SVector{D, T}(partials.((o1,), (1, 2, 3)))\n else\n SVector{D, T}(sum_partials(o1, y1, 1), sum_partials(o1, y1, 2), sum_partials(o1, y1, 3))\n end\n end\n darg1 = unbroadcast(arg1, barg1)\n darg2 = unbroadcast(arg2, broadcast((y1, o1) -> y1 .* partials.(o1, 4), ȳ, out))\n (nothing, nothing, darg1, darg2)\n end\n return y, bc_fwd_back\nend\n\n@inline function Zygote.broadcast_forward(f, arg1::AbstractArray{SVector{D, T}}, arg2::AbstractArray{SVector{D, T}}) where {D, T}\n out = dual_function_svec_svec(f).(arg1, arg2)\n y = map(x -> value.(x), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg1 isa CuArray ? cu(ȳ_in) : ȳ_in\n barg1 = broadcast(ȳ, out) do y1, o1\n if length(y1) == 1\n y1 .* SVector{D, T}(partials.((o1,), (1, 2, 3)))\n else\n SVector{D, T}(sum_partials(o1, y1, 1), sum_partials(o1, y1, 2), sum_partials(o1, y1, 3))\n end\n end\n darg1 = unbroadcast(arg1, barg1)\n barg2 = broadcast(ȳ, out) do y1, o1\n if length(y1) == 1\n y1 .* SVector{D, T}(partials.((o1,), (4, 5, 6)))\n else\n SVector{D, T}(sum_partials(o1, y1, 4), sum_partials(o1, y1, 5), sum_partials(o1, y1, 6))\n end\n end\n darg2 = unbroadcast(arg2, barg2)\n (nothing, nothing, darg1, darg2)\n end\n return y, bc_fwd_back\nend\n\n@inline function Zygote.broadcast_forward(f, arg1::AbstractArray{<:Atom})\n out = dual_function_atom(f).(arg1)\n y = map(x -> value.(x), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg1 isa CuArray ? cu(ȳ_in) : ȳ_in\n barg1 = broadcast(ȳ, out) do y1, o1\n ps = partials(o1)\n Atom(0, y1 * ps[1], y1 * ps[2], y1 * ps[3], y1 * ps[4])\n end\n darg1 = unbroadcast(arg1, barg1)\n (nothing, nothing, darg1)\n end\n return y, bc_fwd_back\nend\n\nfunction combine_dual_GeneralInteraction(y1::SVector{3, T}, o1::SVector{3, Dual{Nothing, T, P}}, i::Integer) where {T, P}\n (\n LennardJones{false, Nothing, T, typeof(NoUnits), typeof(NoUnits)}(\n nothing, false, false,\n y1[1] * partials(o1[1], i) + y1[2] * partials(o1[2], i) + y1[3] * partials(o1[3], i),\n NoUnits, NoUnits,\n ),\n CoulombReactionField{T, T, T, T, typeof(NoUnits), typeof(NoUnits)}(\n y1[1] * partials(o1[1], i ) + y1[2] * partials(o1[2], i ) + y1[3] * partials(o1[3], i ),\n y1[1] * partials(o1[1], i + 1) + y1[2] * partials(o1[2], i + 1) + y1[3] * partials(o1[3], i + 1),\n false,\n y1[1] * partials(o1[1], i + 2) + y1[2] * partials(o1[2], i + 2) + y1[3] * partials(o1[3], i + 2),\n y1[1] * partials(o1[1], i + 3) + y1[2] * partials(o1[2], i + 3) + y1[3] * partials(o1[3], i + 3),\n NoUnits, NoUnits,\n ),\n )\nend\n\nfunction combine_dual_SpecificInteraction(inter::HarmonicBond, y1, o1, i::Integer)\n (y1.f1[1] * partials(o1.f1[1], i ) + y1.f1[2] * partials(o1.f1[2], i ) + y1.f1[3] * partials(o1.f1[3], i ) + y1.f2[1] * partials(o1.f2[1], i ) + y1.f2[2] * partials(o1.f2[2], i ) + y1.f2[3] * partials(o1.f2[3], i ),\n y1.f1[1] * partials(o1.f1[1], i + 1) + y1.f1[2] * partials(o1.f1[2], i + 1) + y1.f1[3] * partials(o1.f1[3], i + 1) + y1.f2[1] * partials(o1.f2[1], i + 1) + y1.f2[2] * partials(o1.f2[2], i + 1) + y1.f2[3] * partials(o1.f2[3], i + 1))\nend\n\nfunction combine_dual_SpecificInteraction(inter::HarmonicAngle, y1, o1, i::Integer)\n (y1.f1[1] * partials(o1.f1[1], i ) + y1.f1[2] * partials(o1.f1[2], i ) + y1.f1[3] * partials(o1.f1[3], i ) + y1.f2[1] * partials(o1.f2[1], i ) + y1.f2[2] * partials(o1.f2[2], i ) + y1.f2[3] * partials(o1.f2[3], i ) + y1.f3[1] * partials(o1.f3[1], i ) + y1.f3[2] * partials(o1.f3[2], i ) + y1.f3[3] * partials(o1.f3[3], i ),\n y1.f1[1] * partials(o1.f1[1], i + 1) + y1.f1[2] * partials(o1.f1[2], i + 1) + y1.f1[3] * partials(o1.f1[3], i + 1) + y1.f2[1] * partials(o1.f2[1], i + 1) + y1.f2[2] * partials(o1.f2[2], i + 1) + y1.f2[3] * partials(o1.f2[3], i + 1) + y1.f3[1] * partials(o1.f3[1], i + 1) + y1.f3[2] * partials(o1.f3[2], i + 1) + y1.f3[3] * partials(o1.f3[3], i + 1))\nend\n\nfunction combine_dual_SpecificInteraction(inter::PeriodicTorsion{6}, y1, o1, i::Integer)\n (\n (0, 0, 0, 0, 0, 0),\n (\n y1.f1[1] * partials(o1.f1[1], i ) + y1.f1[2] * partials(o1.f1[2], i ) + y1.f1[3] * partials(o1.f1[3], i ) + y1.f2[1] * partials(o1.f2[1], i ) + y1.f2[2] * partials(o1.f2[2], i ) + y1.f2[3] * partials(o1.f2[3], i ) + y1.f3[1] * partials(o1.f3[1], i ) + y1.f3[2] * partials(o1.f3[2], i ) + y1.f3[3] * partials(o1.f3[3], i ) + y1.f4[1] * partials(o1.f4[1], i ) + y1.f4[2] * partials(o1.f4[2], i ) + y1.f4[3] * partials(o1.f4[3], i ),\n y1.f1[1] * partials(o1.f1[1], i + 1) + y1.f1[2] * partials(o1.f1[2], i + 1) + y1.f1[3] * partials(o1.f1[3], i + 1) + y1.f2[1] * partials(o1.f2[1], i + 1) + y1.f2[2] * partials(o1.f2[2], i + 1) + y1.f2[3] * partials(o1.f2[3], i + 1) + y1.f3[1] * partials(o1.f3[1], i + 1) + y1.f3[2] * partials(o1.f3[2], i + 1) + y1.f3[3] * partials(o1.f3[3], i + 1) + y1.f4[1] * partials(o1.f4[1], i + 1) + y1.f4[2] * partials(o1.f4[2], i + 1) + y1.f4[3] * partials(o1.f4[3], i + 1),\n y1.f1[1] * partials(o1.f1[1], i + 2) + y1.f1[2] * partials(o1.f1[2], i + 2) + y1.f1[3] * partials(o1.f1[3], i + 2) + y1.f2[1] * partials(o1.f2[1], i + 2) + y1.f2[2] * partials(o1.f2[2], i + 2) + y1.f2[3] * partials(o1.f2[3], i + 2) + y1.f3[1] * partials(o1.f3[1], i + 2) + y1.f3[2] * partials(o1.f3[2], i + 2) + y1.f3[3] * partials(o1.f3[3], i + 2) + y1.f4[1] * partials(o1.f4[1], i + 2) + y1.f4[2] * partials(o1.f4[2], i + 2) + y1.f4[3] * partials(o1.f4[3], i + 2),\n y1.f1[1] * partials(o1.f1[1], i + 3) + y1.f1[2] * partials(o1.f1[2], i + 3) + y1.f1[3] * partials(o1.f1[3], i + 3) + y1.f2[1] * partials(o1.f2[1], i + 3) + y1.f2[2] * partials(o1.f2[2], i + 3) + y1.f2[3] * partials(o1.f2[3], i + 3) + y1.f3[1] * partials(o1.f3[1], i + 3) + y1.f3[2] * partials(o1.f3[2], i + 3) + y1.f3[3] * partials(o1.f3[3], i + 3) + y1.f4[1] * partials(o1.f4[1], i + 3) + y1.f4[2] * partials(o1.f4[2], i + 3) + y1.f4[3] * partials(o1.f4[3], i + 3),\n y1.f1[1] * partials(o1.f1[1], i + 4) + y1.f1[2] * partials(o1.f1[2], i + 4) + y1.f1[3] * partials(o1.f1[3], i + 4) + y1.f2[1] * partials(o1.f2[1], i + 4) + y1.f2[2] * partials(o1.f2[2], i + 4) + y1.f2[3] * partials(o1.f2[3], i + 4) + y1.f3[1] * partials(o1.f3[1], i + 4) + y1.f3[2] * partials(o1.f3[2], i + 4) + y1.f3[3] * partials(o1.f3[3], i + 4) + y1.f4[1] * partials(o1.f4[1], i + 4) + y1.f4[2] * partials(o1.f4[2], i + 4) + y1.f4[3] * partials(o1.f4[3], i + 4),\n y1.f1[1] * partials(o1.f1[1], i + 5) + y1.f1[2] * partials(o1.f1[2], i + 5) + y1.f1[3] * partials(o1.f1[3], i + 5) + y1.f2[1] * partials(o1.f2[1], i + 5) + y1.f2[2] * partials(o1.f2[2], i + 5) + y1.f2[3] * partials(o1.f2[3], i + 5) + y1.f3[1] * partials(o1.f3[1], i + 5) + y1.f3[2] * partials(o1.f3[2], i + 5) + y1.f3[3] * partials(o1.f3[3], i + 5) + y1.f4[1] * partials(o1.f4[1], i + 5) + y1.f4[2] * partials(o1.f4[2], i + 5) + y1.f4[3] * partials(o1.f4[3], i + 5),\n ),\n (\n y1.f1[1] * partials(o1.f1[1], i + 6) + y1.f1[2] * partials(o1.f1[2], i + 6) + y1.f1[3] * partials(o1.f1[3], i + 6) + y1.f2[1] * partials(o1.f2[1], i + 6) + y1.f2[2] * partials(o1.f2[2], i + 6) + y1.f2[3] * partials(o1.f2[3], i + 6) + y1.f3[1] * partials(o1.f3[1], i + 6) + y1.f3[2] * partials(o1.f3[2], i + 6) + y1.f3[3] * partials(o1.f3[3], i + 6) + y1.f4[1] * partials(o1.f4[1], i + 6) + y1.f4[2] * partials(o1.f4[2], i + 6) + y1.f4[3] * partials(o1.f4[3], i + 6),\n y1.f1[1] * partials(o1.f1[1], i + 7) + y1.f1[2] * partials(o1.f1[2], i + 7) + y1.f1[3] * partials(o1.f1[3], i + 7) + y1.f2[1] * partials(o1.f2[1], i + 7) + y1.f2[2] * partials(o1.f2[2], i + 7) + y1.f2[3] * partials(o1.f2[3], i + 7) + y1.f3[1] * partials(o1.f3[1], i + 7) + y1.f3[2] * partials(o1.f3[2], i + 7) + y1.f3[3] * partials(o1.f3[3], i + 7) + y1.f4[1] * partials(o1.f4[1], i + 7) + y1.f4[2] * partials(o1.f4[2], i + 7) + y1.f4[3] * partials(o1.f4[3], i + 7),\n y1.f1[1] * partials(o1.f1[1], i + 8) + y1.f1[2] * partials(o1.f1[2], i + 8) + y1.f1[3] * partials(o1.f1[3], i + 8) + y1.f2[1] * partials(o1.f2[1], i + 8) + y1.f2[2] * partials(o1.f2[2], i + 8) + y1.f2[3] * partials(o1.f2[3], i + 8) + y1.f3[1] * partials(o1.f3[1], i + 8) + y1.f3[2] * partials(o1.f3[2], i + 8) + y1.f3[3] * partials(o1.f3[3], i + 8) + y1.f4[1] * partials(o1.f4[1], i + 8) + y1.f4[2] * partials(o1.f4[2], i + 8) + y1.f4[3] * partials(o1.f4[3], i + 8),\n y1.f1[1] * partials(o1.f1[1], i + 9) + y1.f1[2] * partials(o1.f1[2], i + 9) + y1.f1[3] * partials(o1.f1[3], i + 9) + y1.f2[1] * partials(o1.f2[1], i + 9) + y1.f2[2] * partials(o1.f2[2], i + 9) + y1.f2[3] * partials(o1.f2[3], i + 9) + y1.f3[1] * partials(o1.f3[1], i + 9) + y1.f3[2] * partials(o1.f3[2], i + 9) + y1.f3[3] * partials(o1.f3[3], i + 9) + y1.f4[1] * partials(o1.f4[1], i + 9) + y1.f4[2] * partials(o1.f4[2], i + 9) + y1.f4[3] * partials(o1.f4[3], i + 9),\n y1.f1[1] * partials(o1.f1[1], i + 10) + y1.f1[2] * partials(o1.f1[2], i + 10) + y1.f1[3] * partials(o1.f1[3], i + 10) + y1.f2[1] * partials(o1.f2[1], i + 10) + y1.f2[2] * partials(o1.f2[2], i + 10) + y1.f2[3] * partials(o1.f2[3], i + 10) + y1.f3[1] * partials(o1.f3[1], i + 10) + y1.f3[2] * partials(o1.f3[2], i + 10) + y1.f3[3] * partials(o1.f3[3], i + 10) + y1.f4[1] * partials(o1.f4[1], i + 10) + y1.f4[2] * partials(o1.f4[2], i + 10) + y1.f4[3] * partials(o1.f4[3], i + 10),\n y1.f1[1] * partials(o1.f1[1], i + 11) + y1.f1[2] * partials(o1.f1[2], i + 11) + y1.f1[3] * partials(o1.f1[3], i + 11) + y1.f2[1] * partials(o1.f2[1], i + 11) + y1.f2[2] * partials(o1.f2[2], i + 11) + y1.f2[3] * partials(o1.f2[3], i + 11) + y1.f3[1] * partials(o1.f3[1], i + 11) + y1.f3[2] * partials(o1.f3[2], i + 11) + y1.f3[3] * partials(o1.f3[3], i + 11) + y1.f4[1] * partials(o1.f4[1], i + 11) + y1.f4[2] * partials(o1.f4[2], i + 11) + y1.f4[3] * partials(o1.f4[3], i + 11),\n ),\n )\nend\n\nfunction combine_dual_Atom(y1::SVector{3, T}, o1::SVector{3, Dual{Nothing, T, P}}, i::Integer, j::Integer, k::Integer, l::Integer) where {T, P}\n ps1, ps2, ps3 = partials(o1[1]), partials(o1[2]), partials(o1[3])\n Atom(\n 0,\n y1[1] * ps1[i] + y1[2] * ps2[i] + y1[3] * ps3[i],\n y1[1] * ps1[j] + y1[2] * ps2[j] + y1[3] * ps3[j],\n y1[1] * ps1[k] + y1[2] * ps2[k] + y1[3] * ps3[k],\n y1[1] * ps1[l] + y1[2] * ps2[l] + y1[3] * ps3[l],\n )\nend\n\n@inline function Zygote.broadcast_forward(f,\n arg1,\n arg2::AbstractArray{SVector{D, T}},\n arg3::AbstractArray{SVector{D, T}},\n arg4::AbstractArray{<:Atom},\n arg5::AbstractArray{<:Atom},\n arg6::Tuple{SVector{D, T}},\n arg7::Base.RefValue{<:Unitful.FreeUnits},\n arg8) where {D, T}\n out = dual_function_force_broadcast(f).(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)\n y = map(x -> value.(x), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg2 isa CuArray ? cu(ȳ_in) : ȳ_in\n darg1 = unbroadcast(arg1, broadcast(combine_dual_GeneralInteraction, ȳ, out, 1))\n darg2 = unbroadcast(arg2, broadcast((y1, o1) -> SVector{D, T}(sum_partials(o1, y1, 5),\n sum_partials(o1, y1, 6), sum_partials(o1, y1, 7)), ȳ, out))\n darg3 = unbroadcast(arg3, broadcast((y1, o1) -> SVector{D, T}(sum_partials(o1, y1, 8),\n sum_partials(o1, y1, 9), sum_partials(o1, y1, 10)), ȳ, out))\n darg4 = unbroadcast(arg4, broadcast(combine_dual_Atom, ȳ, out, 11, 12, 13, 14))\n darg5 = unbroadcast(arg5, broadcast(combine_dual_Atom, ȳ, out, 15, 16, 17, 18))\n darg6 = unbroadcast(arg6, broadcast((y1, o1) -> SVector{D, T}(sum_partials(o1, y1, 19),\n sum_partials(o1, y1, 20), sum_partials(o1, y1, 21)), ȳ, out))\n darg7 = nothing\n darg8 = nothing\n return (nothing, nothing, darg1, darg2, darg3, darg4, darg5, darg6, darg7, darg8)\n end\n return y, bc_fwd_back\nend\n\n@inline function Zygote.broadcast_forward(f,\n arg1::AbstractArray{<:SpecificInteraction},\n arg2::AbstractArray{SVector{D, T}},\n arg3::AbstractArray{SVector{D, T}},\n arg4::Tuple{SVector{D, T}}) where {D, T}\n out = dual_function_specific_2_atoms(f).(arg1, arg2, arg3, arg4)\n y = broadcast(o1 -> SpecificForce2Atoms{D, T}(value.(o1.f1), value.(o1.f2)), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg1 isa CuArray ? cu(ȳ_in) : ȳ_in\n darg1 = unbroadcast(arg1, broadcast(combine_dual_SpecificInteraction, arg1, ȳ, out, 1))\n darg2 = unbroadcast(arg2, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 3) + sum_partials(o1.f2, y1.f2, 3),\n sum_partials(o1.f1, y1.f1, 4) + sum_partials(o1.f2, y1.f2, 4),\n sum_partials(o1.f1, y1.f1, 5) + sum_partials(o1.f2, y1.f2, 5)),\n ȳ, out))\n darg3 = unbroadcast(arg3, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 6) + sum_partials(o1.f2, y1.f2, 6),\n sum_partials(o1.f1, y1.f1, 7) + sum_partials(o1.f2, y1.f2, 7),\n sum_partials(o1.f1, y1.f1, 8) + sum_partials(o1.f2, y1.f2, 8)),\n ȳ, out))\n darg4 = unbroadcast(arg4, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 9) + sum_partials(o1.f2, y1.f2, 9),\n sum_partials(o1.f1, y1.f1, 10) + sum_partials(o1.f2, y1.f2, 10),\n sum_partials(o1.f1, y1.f1, 11) + sum_partials(o1.f2, y1.f2, 11)),\n ȳ, out))\n return (nothing, nothing, darg1, darg2, darg3, darg4)\n end\n return y, bc_fwd_back\nend\n\n@inline function Zygote.broadcast_forward(f,\n arg1::AbstractArray{<:SpecificInteraction},\n arg2::AbstractArray{SVector{D, T}},\n arg3::AbstractArray{SVector{D, T}},\n arg4::AbstractArray{SVector{D, T}},\n arg5::Tuple{SVector{D, T}}) where {D, T}\n out = dual_function_specific_3_atoms(f).(arg1, arg2, arg3, arg4, arg5)\n y = broadcast(o1 -> SpecificForce3Atoms{D, T}(value.(o1.f1), value.(o1.f2), value.(o1.f3)), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg1 isa CuArray ? cu(ȳ_in) : ȳ_in\n darg1 = unbroadcast(arg1, broadcast(combine_dual_SpecificInteraction, arg1, ȳ, out, 1))\n darg2 = unbroadcast(arg2, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 3) + sum_partials(o1.f2, y1.f2, 3) + sum_partials(o1.f3, y1.f3, 3),\n sum_partials(o1.f1, y1.f1, 4) + sum_partials(o1.f2, y1.f2, 4) + sum_partials(o1.f3, y1.f3, 4),\n sum_partials(o1.f1, y1.f1, 5) + sum_partials(o1.f2, y1.f2, 5) + sum_partials(o1.f3, y1.f3, 5)),\n ȳ, out))\n darg3 = unbroadcast(arg3, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 6) + sum_partials(o1.f2, y1.f2, 6) + sum_partials(o1.f3, y1.f3, 6),\n sum_partials(o1.f1, y1.f1, 7) + sum_partials(o1.f2, y1.f2, 7) + sum_partials(o1.f3, y1.f3, 7),\n sum_partials(o1.f1, y1.f1, 8) + sum_partials(o1.f2, y1.f2, 8) + sum_partials(o1.f3, y1.f3, 8)),\n ȳ, out))\n darg4 = unbroadcast(arg4, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 9) + sum_partials(o1.f2, y1.f2, 9) + sum_partials(o1.f3, y1.f3, 9),\n sum_partials(o1.f1, y1.f1, 10) + sum_partials(o1.f2, y1.f2, 10) + sum_partials(o1.f3, y1.f3, 10),\n sum_partials(o1.f1, y1.f1, 11) + sum_partials(o1.f2, y1.f2, 11) + sum_partials(o1.f3, y1.f3, 11)),\n ȳ, out))\n darg5 = unbroadcast(arg5, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 12) + sum_partials(o1.f2, y1.f2, 12) + sum_partials(o1.f3, y1.f3, 12),\n sum_partials(o1.f1, y1.f1, 13) + sum_partials(o1.f2, y1.f2, 13) + sum_partials(o1.f3, y1.f3, 13),\n sum_partials(o1.f1, y1.f1, 14) + sum_partials(o1.f2, y1.f2, 14) + sum_partials(o1.f3, y1.f3, 14)),\n ȳ, out))\n return (nothing, nothing, darg1, darg2, darg3, darg4, darg5)\n end\n return y, bc_fwd_back\nend\n\n@inline function Zygote.broadcast_forward(f,\n arg1::AbstractArray{<:SpecificInteraction},\n arg2::AbstractArray{SVector{D, T}},\n arg3::AbstractArray{SVector{D, T}},\n arg4::AbstractArray{SVector{D, T}},\n arg5::AbstractArray{SVector{D, T}},\n arg6::Tuple{SVector{D, T}}) where {D, T}\n out = dual_function_specific_4_atoms(f).(arg1, arg2, arg3, arg4, arg5, arg6)\n y = broadcast(o1 -> SpecificForce4Atoms{D, T}(value.(o1.f1), value.(o1.f2), value.(o1.f3), value.(o1.f4)), out)\n function bc_fwd_back(ȳ_in)\n ȳ = arg1 isa CuArray ? cu(ȳ_in) : ȳ_in\n darg1 = unbroadcast(arg1, broadcast(combine_dual_SpecificInteraction, arg1, ȳ, out, 1))\n darg2 = unbroadcast(arg2, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 13) + sum_partials(o1.f2, y1.f2, 13) + sum_partials(o1.f3, y1.f3, 13) + sum_partials(o1.f4, y1.f4, 13),\n sum_partials(o1.f1, y1.f1, 14) + sum_partials(o1.f2, y1.f2, 14) + sum_partials(o1.f3, y1.f3, 14) + sum_partials(o1.f4, y1.f4, 14),\n sum_partials(o1.f1, y1.f1, 15) + sum_partials(o1.f2, y1.f2, 15) + sum_partials(o1.f3, y1.f3, 15) + sum_partials(o1.f4, y1.f4, 15)),\n ȳ, out))\n darg3 = unbroadcast(arg3, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 16) + sum_partials(o1.f2, y1.f2, 16) + sum_partials(o1.f3, y1.f3, 16) + sum_partials(o1.f4, y1.f4, 16),\n sum_partials(o1.f1, y1.f1, 17) + sum_partials(o1.f2, y1.f2, 17) + sum_partials(o1.f3, y1.f3, 17) + sum_partials(o1.f4, y1.f4, 17),\n sum_partials(o1.f1, y1.f1, 18) + sum_partials(o1.f2, y1.f2, 18) + sum_partials(o1.f3, y1.f3, 18) + sum_partials(o1.f4, y1.f4, 18)),\n ȳ, out))\n darg4 = unbroadcast(arg4, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 19) + sum_partials(o1.f2, y1.f2, 19) + sum_partials(o1.f3, y1.f3, 19) + sum_partials(o1.f4, y1.f4, 19),\n sum_partials(o1.f1, y1.f1, 20) + sum_partials(o1.f2, y1.f2, 20) + sum_partials(o1.f3, y1.f3, 20) + sum_partials(o1.f4, y1.f4, 20),\n sum_partials(o1.f1, y1.f1, 21) + sum_partials(o1.f2, y1.f2, 21) + sum_partials(o1.f3, y1.f3, 21) + sum_partials(o1.f4, y1.f4, 21)),\n ȳ, out))\n darg5 = unbroadcast(arg5, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 22) + sum_partials(o1.f2, y1.f2, 22) + sum_partials(o1.f3, y1.f3, 22) + sum_partials(o1.f4, y1.f4, 22),\n sum_partials(o1.f1, y1.f1, 23) + sum_partials(o1.f2, y1.f2, 23) + sum_partials(o1.f3, y1.f3, 23) + sum_partials(o1.f4, y1.f4, 23),\n sum_partials(o1.f1, y1.f1, 24) + sum_partials(o1.f2, y1.f2, 24) + sum_partials(o1.f3, y1.f3, 24) + sum_partials(o1.f4, y1.f4, 24)),\n ȳ, out))\n darg6 = unbroadcast(arg6, broadcast((y1, o1) -> SVector{D, T}(\n sum_partials(o1.f1, y1.f1, 25) + sum_partials(o1.f2, y1.f2, 25) + sum_partials(o1.f3, y1.f3, 25) + sum_partials(o1.f4, y1.f4, 25),\n sum_partials(o1.f1, y1.f1, 26) + sum_partials(o1.f2, y1.f2, 26) + sum_partials(o1.f3, y1.f3, 26) + sum_partials(o1.f4, y1.f4, 26),\n sum_partials(o1.f1, y1.f1, 27) + sum_partials(o1.f2, y1.f2, 27) + sum_partials(o1.f3, y1.f3, 27) + sum_partials(o1.f4, y1.f4, 27)),\n ȳ, out))\n return (nothing, nothing, darg1, darg2, darg3, darg4, darg5, darg6)\n end\n return y, bc_fwd_back\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf1),\n arg1::AbstractArray{<:SpecificForce2Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=y1, f2=zero(y1)), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf1),\n arg1::AbstractArray{<:SpecificForce3Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=y1, f2=zero(y1), f3=zero(y1)), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf1),\n arg1::AbstractArray{<:SpecificForce4Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=y1, f2=zero(y1), f3=zero(y1), f4=zero(y1)), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf2),\n arg1::AbstractArray{<:SpecificForce2Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=zero(y1), f2=y1), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf2),\n arg1::AbstractArray{<:SpecificForce3Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=zero(y1), f2=y1, f3=zero(y1)), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf2),\n arg1::AbstractArray{<:SpecificForce4Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=zero(y1), f2=y1, f3=zero(y1), f4=zero(y1)), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf3),\n arg1::AbstractArray{<:SpecificForce3Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=zero(y1), f2=zero(y1), f3=y1), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf3),\n arg1::AbstractArray{<:SpecificForce4Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=zero(y1), f2=zero(y1), f3=y1, f4=zero(y1)), ȳ)))\nend\n\n@inline function Zygote.broadcast_forward(f::typeof(getf4),\n arg1::AbstractArray{<:SpecificForce4Atoms}) where {D, T}\n return f.(arg1), ȳ -> (nothing, nothing, unbroadcast(arg1, broadcast(y1 -> (f1=zero(y1), f2=zero(y1), f3=zero(y1), f4=y1), ȳ)))\nend\n\n# Use fast broadcast path on CPU\nfor op in (:+, :-, :*, :/, :force, :force_nounit, :mass, :remove_molar, :ustrip,\n :ustrip_vec, :wrap_coords_vec, :getf1, :getf2, :getf3, :getf4)\n @eval Zygote.@adjoint Broadcast.broadcasted(::Broadcast.AbstractArrayStyle, f::typeof($op), args...) = Zygote.broadcast_forward(f, args...)\n # Avoid ambiguous dispatch\n @eval Zygote.@adjoint Broadcast.broadcasted(::CUDA.AbstractGPUArrayStyle , f::typeof($op), args...) = Zygote.broadcast_forward(f, args...)\nend\n", "meta": {"hexsha": "5781bb7dea0906304fec967d26ec10c9d62c7e0e", "size": 35721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/zygote.jl", "max_stars_repo_name": "moradza/Molly.jl", "max_stars_repo_head_hexsha": "ec74875569b40e28125f944025cf9992a46dc7f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zygote.jl", "max_issues_repo_name": "moradza/Molly.jl", "max_issues_repo_head_hexsha": "ec74875569b40e28125f944025cf9992a46dc7f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zygote.jl", "max_forks_repo_name": "moradza/Molly.jl", "max_forks_repo_head_hexsha": "ec74875569b40e28125f944025cf9992a46dc7f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.2710120069, "max_line_length": 490, "alphanum_fraction": 0.5567033398, "num_tokens": 14358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.17097467990390294}} {"text": "module SrtmKgb20\n sfluxref = [9.34081 , 8.93720 , 8.19346 , 7.39196 ,6.12127 , 5.23956 , 4.24941 , 3.20013 ,2.16047 , 0.234509 , 0.194593 , 0.151512 ,0.110315, 7.09959e-02, 2.70573e-02, 3.36042e-03]\n \n absch4 = [ \n 1.01381e-03,6.33692e-03,1.94185e-02,4.83210e-02,2.36574e-03,6.61973e-04,5.64552e-04,2.83183e-04,7.43623e-05,8.90159e-07,6.98728e-07,6.51832e-08,2.96619e-08, 0., 0., 0.]\n\n # Rayleigh extinction coefficient at v = 5670 cm-1.\n rayl = 4.12e-09\n\n layreffr = 3\n\n # ------------------------------------------------------------------\n\n # The array KA contains absorption coefs at the 16 chosen g-values \n # for a range of pressure levels> ~100mb:and binary:temperatures\n # species parameters (see taumol.f for definition). The first \n # index in the array, JS, runs from 1 to 9, and corresponds to \n # different values of the binary species parameter. For instance, \n # JS=1 refers to dry air, JS = 2 corresponds to the paramter value 1/8, \n # JS = 3 corresponds to the parameter value 2/8, etc. The second index\n # in the array, JT, which runs from 1 to 5, corresponds to different\n # temperatures. More specifically, JT = 3 means that the data are for\n # the reference temperature TREF for this pressure level:JT = 2 refers\n # to TREF-15, JT = 1 is for TREF-30:and JT = 5:JT = 4 is for TREF+15\n # is for TREF+30. The third index:runs from 1 to 13 and refers:JP\n # to the JPth reference pressure level (see taumol.f for these levels\n # in mb). The fourth index, IG, goes from 1 to 16, and indicates\n # which g-interval the absorption coefficients are for.\n # -----------------------------------------------------------------\n ka = zeros(5,13,16)\n ka[:, 1, 1] = [0.78383e-06,0.86220e-06,0.95359e-06,0.10590e-05,0.11782e-05]\n ka[:, 2, 1] = [0.65040e-06,0.72510e-06,0.81318e-06,0.90059e-06,0.99786e-06]\n ka[:, 3, 1] = [0.58072e-06,0.65888e-06,0.74265e-06,0.81854e-06,0.90645e-06]\n ka[:, 4, 1] = [0.53601e-06,0.60765e-06,0.68088e-06,0.75741e-06,0.83801e-06]\n ka[:, 5, 1] = [0.50142e-06,0.56951e-06,0.64028e-06,0.71944e-06,0.79813e-06]\n ka[:, 6, 1] = [0.47164e-06,0.54008e-06,0.61040e-06,0.68006e-06,0.75034e-06]\n ka[:, 7, 1] = [0.49337e-06,0.56178e-06,0.62215e-06,0.69127e-06,0.76060e-06]\n ka[:, 8, 1] = [0.61581e-06,0.70117e-06,0.78942e-06,0.87145e-06,0.94647e-06]\n ka[:, 9, 1] = [0.14154e-05,0.15754e-05,0.17261e-05,0.18739e-05,0.19774e-05]\n ka[:,10, 1] = [0.34186e-05,0.37012e-05,0.39602e-05,0.42235e-05,0.44256e-05]\n ka[:,11, 1] = [0.38574e-05,0.42080e-05,0.44701e-05,0.47454e-05,0.50002e-05]\n ka[:,12, 1] = [0.35794e-05,0.38686e-05,0.41443e-05,0.43939e-05,0.46500e-05]\n ka[:,13, 1] = [0.29586e-05,0.31938e-05,0.34167e-05,0.36253e-05,0.38250e-05]\n ka[:, 1, 2] = [0.57098e-05,0.64630e-05,0.73117e-05,0.82436e-05,0.91947e-05]\n ka[:, 2, 2] = [0.46384e-05,0.53125e-05,0.60301e-05,0.68028e-05,0.75824e-05]\n ka[:, 3, 2] = [0.40657e-05,0.46486e-05,0.52459e-05,0.58955e-05,0.65546e-05]\n ka[:, 4, 2] = [0.38895e-05,0.44258e-05,0.49759e-05,0.55663e-05,0.61702e-05]\n ka[:, 5, 2] = [0.38971e-05,0.44359e-05,0.49933e-05,0.55523e-05,0.61234e-05]\n ka[:, 6, 2] = [0.39532e-05,0.44644e-05,0.49734e-05,0.54875e-05,0.60102e-05]\n ka[:, 7, 2] = [0.41068e-05,0.45832e-05,0.50698e-05,0.55521e-05,0.60175e-05]\n ka[:, 8, 2] = [0.47922e-05,0.52156e-05,0.56817e-05,0.61576e-05,0.66313e-05]\n ka[:, 9, 2] = [0.83199e-05,0.88317e-05,0.93688e-05,0.99754e-05,0.10620e-04]\n ka[:,10, 2] = [0.16836e-04,0.18526e-04,0.19887e-04,0.21168e-04,0.22104e-04]\n ka[:,11, 2] = [0.18882e-04,0.21005e-04,0.22896e-04,0.24777e-04,0.26115e-04]\n ka[:,12, 2] = [0.17744e-04,0.19780e-04,0.21600e-04,0.23523e-04,0.25128e-04]\n ka[:,13, 2] = [0.14736e-04,0.16356e-04,0.17955e-04,0.19533e-04,0.20861e-04]\n ka[:, 1, 3] = [0.41776e-04,0.48150e-04,0.55097e-04,0.62661e-04,0.70920e-04]\n ka[:, 2, 3] = [0.33909e-04,0.39176e-04,0.44622e-04,0.50754e-04,0.57336e-04]\n ka[:, 3, 3] = [0.27438e-04,0.31473e-04,0.36122e-04,0.41134e-04,0.46456e-04]\n ka[:, 4, 3] = [0.23222e-04,0.26535e-04,0.30141e-04,0.34099e-04,0.38416e-04]\n ka[:, 5, 3] = [0.21114e-04,0.23888e-04,0.26883e-04,0.30340e-04,0.33785e-04]\n ka[:, 6, 3] = [0.20750e-04,0.22926e-04,0.25536e-04,0.28492e-04,0.31676e-04]\n ka[:, 7, 3] = [0.21584e-04,0.24112e-04,0.26872e-04,0.29794e-04,0.32940e-04]\n ka[:, 8, 3] = [0.24194e-04,0.26981e-04,0.30137e-04,0.33546e-04,0.37182e-04]\n ka[:, 9, 3] = [0.37461e-04,0.42158e-04,0.46718e-04,0.51048e-04,0.55154e-04]\n ka[:,10, 3] = [0.72391e-04,0.77164e-04,0.84016e-04,0.89658e-04,0.95511e-04]\n ka[:,11, 3] = [0.91736e-04,0.99107e-04,0.10463e-03,0.10952e-03,0.11549e-03]\n ka[:,12, 3] = [0.91200e-04,0.98812e-04,0.10432e-03,0.10893e-03,0.11349e-03]\n ka[:,13, 3] = [0.76217e-04,0.82702e-04,0.87500e-04,0.91349e-04,0.95349e-04]\n ka[:, 1, 4] = [0.71705e-03,0.82743e-03,0.94700e-03,0.10670e-02,0.11902e-02]\n ka[:, 2, 4] = [0.57909e-03,0.67096e-03,0.76724e-03,0.86582e-03,0.97167e-03]\n ka[:, 3, 4] = [0.44771e-03,0.51997e-03,0.59861e-03,0.67967e-03,0.76676e-03]\n ka[:, 4, 4] = [0.34085e-03,0.39833e-03,0.46226e-03,0.52889e-03,0.60008e-03]\n ka[:, 5, 4] = [0.26678e-03,0.31234e-03,0.36341e-03,0.41663e-03,0.47418e-03]\n ka[:, 6, 4] = [0.20903e-03,0.24718e-03,0.28922e-03,0.33353e-03,0.38176e-03]\n ka[:, 7, 4] = [0.17173e-03,0.20330e-03,0.23711e-03,0.27401e-03,0.31445e-03]\n ka[:, 8, 4] = [0.16722e-03,0.19396e-03,0.22307e-03,0.25347e-03,0.28561e-03]\n ka[:, 9, 4] = [0.25043e-03,0.28824e-03,0.32547e-03,0.36193e-03,0.39806e-03]\n ka[:,10, 4] = [0.43323e-03,0.48667e-03,0.53462e-03,0.57879e-03,0.62040e-03]\n ka[:,11, 4] = [0.47719e-03,0.52271e-03,0.56402e-03,0.60388e-03,0.63520e-03]\n ka[:,12, 4] = [0.45061e-03,0.49014e-03,0.52391e-03,0.55276e-03,0.57760e-03]\n ka[:,13, 4] = [0.37664e-03,0.40952e-03,0.43690e-03,0.46055e-03,0.48018e-03]\n ka[:, 1, 5] = [0.66466e-02,0.68686e-02,0.70897e-02,0.73019e-02,0.74914e-02]\n ka[:, 2, 5] = [0.54023e-02,0.56010e-02,0.58008e-02,0.59987e-02,0.61685e-02]\n ka[:, 3, 5] = [0.43218e-02,0.45127e-02,0.46848e-02,0.48647e-02,0.50267e-02]\n ka[:, 4, 5] = [0.34639e-02,0.36473e-02,0.37951e-02,0.39570e-02,0.41049e-02]\n ka[:, 5, 5] = [0.27745e-02,0.29370e-02,0.30754e-02,0.32148e-02,0.33492e-02]\n ka[:, 6, 5] = [0.22020e-02,0.23520e-02,0.24836e-02,0.25965e-02,0.27119e-02]\n ka[:, 7, 5] = [0.17624e-02,0.18963e-02,0.20161e-02,0.21153e-02,0.22116e-02]\n ka[:, 8, 5] = [0.14169e-02,0.15332e-02,0.16350e-02,0.17231e-02,0.18121e-02]\n ka[:, 9, 5] = [0.13030e-02,0.13904e-02,0.14690e-02,0.15500e-02,0.16275e-02]\n ka[:,10, 5] = [0.17155e-02,0.18169e-02,0.18943e-02,0.19620e-02,0.20215e-02]\n ka[:,11, 5] = [0.17156e-02,0.17808e-02,0.18419e-02,0.18925e-02,0.19313e-02]\n ka[:,12, 5] = [0.15269e-02,0.15811e-02,0.16283e-02,0.16686e-02,0.17061e-02]\n ka[:,13, 5] = [0.12768e-02,0.13207e-02,0.13555e-02,0.13924e-02,0.14234e-02]\n ka[:, 1, 6] = [0.19191e-01,0.19463e-01,0.19692e-01,0.19900e-01,0.20112e-01]\n ka[:, 2, 6] = [0.15967e-01,0.16219e-01,0.16426e-01,0.16613e-01,0.16805e-01]\n ka[:, 3, 6] = [0.13186e-01,0.13411e-01,0.13614e-01,0.13785e-01,0.13944e-01]\n ka[:, 4, 6] = [0.10935e-01,0.11131e-01,0.11318e-01,0.11475e-01,0.11620e-01]\n ka[:, 5, 6] = [0.90541e-02,0.92344e-02,0.94035e-02,0.95537e-02,0.96862e-02]\n ka[:, 6, 6] = [0.74724e-02,0.76320e-02,0.77794e-02,0.79294e-02,0.80528e-02]\n ka[:, 7, 6] = [0.61183e-02,0.62644e-02,0.63961e-02,0.65303e-02,0.66478e-02]\n ka[:, 8, 6] = [0.50638e-02,0.51984e-02,0.53222e-02,0.54412e-02,0.55465e-02]\n ka[:, 9, 6] = [0.42870e-02,0.44009e-02,0.45109e-02,0.45976e-02,0.46796e-02]\n ka[:,10, 6] = [0.45239e-02,0.46073e-02,0.46968e-02,0.47979e-02,0.48956e-02]\n ka[:,11, 6] = [0.44089e-02,0.45006e-02,0.45881e-02,0.46721e-02,0.48015e-02]\n ka[:,12, 6] = [0.39598e-02,0.40290e-02,0.41108e-02,0.41899e-02,0.42672e-02]\n ka[:,13, 6] = [0.33425e-02,0.34148e-02,0.34808e-02,0.35405e-02,0.35983e-02]\n ka[:, 1, 7] = [0.50165e-01,0.50343e-01,0.50452e-01,0.50424e-01,0.50329e-01]\n ka[:, 2, 7] = [0.42723e-01,0.42880e-01,0.42939e-01,0.42910e-01,0.42861e-01]\n ka[:, 3, 7] = [0.36117e-01,0.36255e-01,0.36301e-01,0.36294e-01,0.36288e-01]\n ka[:, 4, 7] = [0.30585e-01,0.30720e-01,0.30787e-01,0.30816e-01,0.30842e-01]\n ka[:, 5, 7] = [0.25879e-01,0.26029e-01,0.26116e-01,0.26179e-01,0.26225e-01]\n ka[:, 6, 7] = [0.21822e-01,0.21978e-01,0.22094e-01,0.22178e-01,0.22244e-01]\n ka[:, 7, 7] = [0.18304e-01,0.18476e-01,0.18606e-01,0.18705e-01,0.18780e-01]\n ka[:, 8, 7] = [0.15224e-01,0.15394e-01,0.15519e-01,0.15619e-01,0.15690e-01]\n ka[:, 9, 7] = [0.12835e-01,0.13029e-01,0.13169e-01,0.13281e-01,0.13369e-01]\n ka[:,10, 7] = [0.11632e-01,0.11714e-01,0.11760e-01,0.11776e-01,0.11806e-01]\n ka[:,11, 7] = [0.11170e-01,0.11252e-01,0.11288e-01,0.11357e-01,0.11397e-01]\n ka[:,12, 7] = [0.10404e-01,0.10533e-01,0.10705e-01,0.10833e-01,0.10947e-01]\n ka[:,13, 7] = [0.91041e-02,0.92674e-02,0.94068e-02,0.95412e-02,0.96769e-02]\n ka[:, 1, 8] = [0.14527e+00,0.14483e+00,0.14432e+00,0.14389e+00,0.14349e+00]\n ka[:, 2, 8] = [0.12739e+00,0.12702e+00,0.12661e+00,0.12624e+00,0.12584e+00]\n ka[:, 3, 8] = [0.11091e+00,0.11058e+00,0.11024e+00,0.10990e+00,0.10953e+00]\n ka[:, 4, 8] = [0.96590e-01,0.96335e-01,0.96105e-01,0.95818e-01,0.95530e-01]\n ka[:, 5, 8] = [0.83799e-01,0.83708e-01,0.83572e-01,0.83347e-01,0.83126e-01]\n ka[:, 6, 8] = [0.72369e-01,0.72388e-01,0.72289e-01,0.72143e-01,0.71981e-01]\n ka[:, 7, 8] = [0.62158e-01,0.62247e-01,0.62185e-01,0.62111e-01,0.62007e-01]\n ka[:, 8, 8] = [0.52998e-01,0.53142e-01,0.53162e-01,0.53154e-01,0.53101e-01]\n ka[:, 9, 8] = [0.44776e-01,0.44873e-01,0.44920e-01,0.44946e-01,0.44885e-01]\n ka[:,10, 8] = [0.38237e-01,0.38514e-01,0.38716e-01,0.38877e-01,0.38966e-01]\n ka[:,11, 8] = [0.33511e-01,0.33721e-01,0.33843e-01,0.33840e-01,0.33839e-01]\n ka[:,12, 8] = [0.29704e-01,0.29825e-01,0.29808e-01,0.29787e-01,0.29794e-01]\n ka[:,13, 8] = [0.25973e-01,0.26004e-01,0.26032e-01,0.26023e-01,0.26107e-01]\n ka[:, 1, 9] = [0.56699e+00,0.56615e+00,0.56479e+00,0.56318e+00,0.56135e+00]\n ka[:, 2, 9] = [0.53130e+00,0.53096e+00,0.53038e+00,0.52953e+00,0.52828e+00]\n ka[:, 3, 9] = [0.48947e+00,0.48989e+00,0.48991e+00,0.48970e+00,0.48916e+00]\n ka[:, 4, 9] = [0.44646e+00,0.44756e+00,0.44841e+00,0.44893e+00,0.44859e+00]\n ka[:, 5, 9] = [0.40428e+00,0.40594e+00,0.40746e+00,0.40811e+00,0.40825e+00]\n ka[:, 6, 9] = [0.36305e+00,0.36545e+00,0.36730e+00,0.36814e+00,0.36854e+00]\n ka[:, 7, 9] = [0.32383e+00,0.32659e+00,0.32849e+00,0.32954e+00,0.33028e+00]\n ka[:, 8, 9] = [0.28691e+00,0.28966e+00,0.29156e+00,0.29286e+00,0.29379e+00]\n ka[:, 9, 9] = [0.25109e+00,0.25404e+00,0.25607e+00,0.25752e+00,0.25870e+00]\n ka[:,10, 9] = [0.21600e+00,0.21860e+00,0.22047e+00,0.22164e+00,0.22251e+00]\n ka[:,11, 9] = [0.19149e+00,0.19387e+00,0.19567e+00,0.19725e+00,0.19809e+00]\n ka[:,12, 9] = [0.16914e+00,0.17134e+00,0.17303e+00,0.17407e+00,0.17494e+00]\n ka[:,13, 9] = [0.14841e+00,0.15027e+00,0.15244e+00,0.15403e+00,0.15523e+00]\n ka[:, 1,10] = [0.14885e+01,0.14756e+01,0.14663e+01,0.14567e+01,0.14479e+01]\n ka[:, 2,10] = [0.14911e+01,0.14850e+01,0.14762e+01,0.14677e+01,0.14597e+01]\n ka[:, 3,10] = [0.14749e+01,0.14716e+01,0.14663e+01,0.14579e+01,0.14502e+01]\n ka[:, 4,10] = [0.14314e+01,0.14303e+01,0.14232e+01,0.14150e+01,0.14115e+01]\n ka[:, 5,10] = [0.13616e+01,0.13604e+01,0.13539e+01,0.13506e+01,0.13501e+01]\n ka[:, 6,10] = [0.12710e+01,0.12700e+01,0.12670e+01,0.12702e+01,0.12745e+01]\n ka[:, 7,10] = [0.11674e+01,0.11690e+01,0.11727e+01,0.11812e+01,0.11854e+01]\n ka[:, 8,10] = [0.10584e+01,0.10652e+01,0.10757e+01,0.10857e+01,0.10906e+01]\n ka[:, 9,10] = [0.95450e+00,0.96414e+00,0.97673e+00,0.98621e+00,0.99187e+00]\n ka[:,10,10] = [0.83626e+00,0.84690e+00,0.85901e+00,0.86824e+00,0.87535e+00]\n ka[:,11,10] = [0.73738e+00,0.74729e+00,0.75610e+00,0.75994e+00,0.76481e+00]\n ka[:,12,10] = [0.66891e+00,0.67622e+00,0.68092e+00,0.68498e+00,0.68877e+00]\n ka[:,13,10] = [0.58616e+00,0.59614e+00,0.59749e+00,0.60310e+00,0.60445e+00]\n ka[:, 1,11] = [0.20080e+01,0.19998e+01,0.19844e+01,0.19679e+01,0.19504e+01]\n ka[:, 2,11] = [0.20896e+01,0.20752e+01,0.20596e+01,0.20445e+01,0.20293e+01]\n ka[:, 3,11] = [0.21262e+01,0.21143e+01,0.21043e+01,0.20968e+01,0.20862e+01]\n ka[:, 4,11] = [0.21310e+01,0.21263e+01,0.21243e+01,0.21203e+01,0.21144e+01]\n ka[:, 5,11] = [0.21041e+01,0.21063e+01,0.21071e+01,0.21077e+01,0.21021e+01]\n ka[:, 6,11] = [0.20447e+01,0.20491e+01,0.20534e+01,0.20532e+01,0.20477e+01]\n ka[:, 7,11] = [0.19487e+01,0.19563e+01,0.19608e+01,0.19593e+01,0.19591e+01]\n ka[:, 8,11] = [0.18239e+01,0.18317e+01,0.18359e+01,0.18391e+01,0.18451e+01]\n ka[:, 9,11] = [0.16772e+01,0.16879e+01,0.16955e+01,0.17047e+01,0.17179e+01]\n ka[:,10,11] = [0.15007e+01,0.15184e+01,0.15343e+01,0.15540e+01,0.15756e+01]\n ka[:,11,11] = [0.13041e+01,0.13245e+01,0.13445e+01,0.13685e+01,0.13888e+01]\n ka[:,12,11] = [0.11590e+01,0.11749e+01,0.11906e+01,0.12046e+01,0.12212e+01]\n ka[:,13,11] = [0.10681e+01,0.10905e+01,0.11017e+01,0.10997e+01,0.11116e+01]\n ka[:, 1,12] = [0.26762e+01,0.26701e+01,0.26710e+01,0.26742e+01,0.26733e+01]\n ka[:, 2,12] = [0.28804e+01,0.28775e+01,0.28798e+01,0.28773e+01,0.28700e+01]\n ka[:, 3,12] = [0.30825e+01,0.30790e+01,0.30757e+01,0.30631e+01,0.30471e+01]\n ka[:, 4,12] = [0.32355e+01,0.32278e+01,0.32144e+01,0.31959e+01,0.31753e+01]\n ka[:, 5,12] = [0.33271e+01,0.33191e+01,0.33073e+01,0.32879e+01,0.32714e+01]\n ka[:, 6,12] = [0.33604e+01,0.33571e+01,0.33478e+01,0.33355e+01,0.33272e+01]\n ka[:, 7,12] = [0.33406e+01,0.33436e+01,0.33436e+01,0.33435e+01,0.33409e+01]\n ka[:, 8,12] = [0.32648e+01,0.32808e+01,0.32919e+01,0.32976e+01,0.32999e+01]\n ka[:, 9,12] = [0.31373e+01,0.31630e+01,0.31816e+01,0.31936e+01,0.31991e+01]\n ka[:,10,12] = [0.29678e+01,0.29982e+01,0.30244e+01,0.30412e+01,0.30500e+01]\n ka[:,11,12] = [0.27380e+01,0.27731e+01,0.28013e+01,0.28227e+01,0.28455e+01]\n ka[:,12,12] = [0.24616e+01,0.24905e+01,0.25348e+01,0.25805e+01,0.26155e+01]\n ka[:,13,12] = [0.22251e+01,0.22562e+01,0.22966e+01,0.23312e+01,0.23811e+01]\n ka[:, 1,13] = [0.38031e+01,0.37992e+01,0.37926e+01,0.37822e+01,0.37755e+01]\n ka[:, 2,13] = [0.41542e+01,0.41473e+01,0.41391e+01,0.41329e+01,0.41296e+01]\n ka[:, 3,13] = [0.44998e+01,0.44963e+01,0.44896e+01,0.44914e+01,0.44937e+01]\n ka[:, 4,13] = [0.48464e+01,0.48445e+01,0.48485e+01,0.48565e+01,0.48598e+01]\n ka[:, 5,13] = [0.52074e+01,0.52112e+01,0.52168e+01,0.52231e+01,0.52210e+01]\n ka[:, 6,13] = [0.55492e+01,0.55575e+01,0.55655e+01,0.55693e+01,0.55642e+01]\n ka[:, 7,13] = [0.58380e+01,0.58479e+01,0.58509e+01,0.58482e+01,0.58453e+01]\n ka[:, 8,13] = [0.60377e+01,0.60538e+01,0.60594e+01,0.60647e+01,0.60640e+01]\n ka[:, 9,13] = [0.61268e+01,0.61532e+01,0.61730e+01,0.61888e+01,0.61993e+01]\n ka[:,10,13] = [0.61216e+01,0.61612e+01,0.61936e+01,0.62230e+01,0.62454e+01]\n ka[:,11,13] = [0.60409e+01,0.60960e+01,0.61462e+01,0.61882e+01,0.62219e+01]\n ka[:,12,13] = [0.58645e+01,0.59597e+01,0.60234e+01,0.60826e+01,0.61390e+01]\n ka[:,13,13] = [0.56001e+01,0.57009e+01,0.58017e+01,0.59181e+01,0.59860e+01]\n ka[:, 1,14] = [0.53647e+01,0.53127e+01,0.52736e+01,0.52471e+01,0.52264e+01]\n ka[:, 2,14] = [0.62359e+01,0.61753e+01,0.61253e+01,0.60847e+01,0.60573e+01]\n ka[:, 3,14] = [0.72065e+01,0.71249e+01,0.70556e+01,0.69965e+01,0.69559e+01]\n ka[:, 4,14] = [0.81631e+01,0.80714e+01,0.79828e+01,0.79081e+01,0.78545e+01]\n ka[:, 5,14] = [0.90691e+01,0.89602e+01,0.88621e+01,0.87858e+01,0.87314e+01]\n ka[:, 6,14] = [0.99707e+01,0.98474e+01,0.97395e+01,0.96541e+01,0.95904e+01]\n ka[:, 7,14] = [0.10852e+02,0.10724e+02,0.10620e+02,0.10536e+02,0.10469e+02]\n ka[:, 8,14] = [0.11716e+02,0.11588e+02,0.11487e+02,0.11403e+02,0.11337e+02]\n ka[:, 9,14] = [0.12572e+02,0.12448e+02,0.12341e+02,0.12260e+02,0.12188e+02]\n ka[:,10,14] = [0.13374e+02,0.13256e+02,0.13159e+02,0.13080e+02,0.13010e+02]\n ka[:,11,14] = [0.14046e+02,0.13957e+02,0.13888e+02,0.13824e+02,0.13769e+02]\n ka[:,12,14] = [0.14644e+02,0.14592e+02,0.14548e+02,0.14504e+02,0.14461e+02]\n ka[:,13,14] = [0.15144e+02,0.15129e+02,0.15111e+02,0.15095e+02,0.15074e+02]\n ka[:, 1,15] = [0.72019e+01,0.71097e+01,0.70236e+01,0.69449e+01,0.68844e+01]\n ka[:, 2,15] = [0.87604e+01,0.86468e+01,0.85349e+01,0.84375e+01,0.83491e+01]\n ka[:, 3,15] = [0.10615e+02,0.10469e+02,0.10333e+02,0.10214e+02,0.10099e+02]\n ka[:, 4,15] = [0.12669e+02,0.12473e+02,0.12305e+02,0.12161e+02,0.12026e+02]\n ka[:, 5,15] = [0.14978e+02,0.14741e+02,0.14530e+02,0.14329e+02,0.14143e+02]\n ka[:, 6,15] = [0.17562e+02,0.17282e+02,0.17031e+02,0.16791e+02,0.16552e+02]\n ka[:, 7,15] = [0.20480e+02,0.20136e+02,0.19827e+02,0.19524e+02,0.19223e+02]\n ka[:, 8,15] = [0.23734e+02,0.23307e+02,0.22908e+02,0.22521e+02,0.22160e+02]\n ka[:, 9,15] = [0.27249e+02,0.26733e+02,0.26255e+02,0.25787e+02,0.25354e+02]\n ka[:,10,15] = [0.30889e+02,0.30311e+02,0.29740e+02,0.29192e+02,0.28690e+02]\n ka[:,11,15] = [0.34366e+02,0.33687e+02,0.33035e+02,0.32430e+02,0.31843e+02]\n ka[:,12,15] = [0.37839e+02,0.37085e+02,0.36360e+02,0.35655e+02,0.34957e+02]\n ka[:,13,15] = [0.41323e+02,0.40503e+02,0.39673e+02,0.38847e+02,0.38049e+02]\n ka[:, 1,16] = [0.82631e+01,0.81761e+01,0.80809e+01,0.79778e+01,0.79010e+01]\n ka[:, 2,16] = [0.10258e+02,0.10128e+02,0.10005e+02,0.98803e+01,0.97700e+01]\n ka[:, 3,16] = [0.12786e+02,0.12614e+02,0.12441e+02,0.12267e+02,0.12120e+02]\n ka[:, 4,16] = [0.15843e+02,0.15549e+02,0.15326e+02,0.15095e+02,0.14871e+02]\n ka[:, 5,16] = [0.19543e+02,0.19089e+02,0.18733e+02,0.18430e+02,0.18134e+02]\n ka[:, 6,16] = [0.24038e+02,0.23415e+02,0.22893e+02,0.22427e+02,0.22005e+02]\n ka[:, 7,16] = [0.29445e+02,0.28630e+02,0.27921e+02,0.27268e+02,0.26654e+02]\n ka[:, 8,16] = [0.35889e+02,0.34849e+02,0.33913e+02,0.33036e+02,0.32194e+02]\n ka[:, 9,16] = [0.43512e+02,0.42175e+02,0.40956e+02,0.39809e+02,0.38685e+02]\n ka[:,10,16] = [0.52253e+02,0.50582e+02,0.49011e+02,0.47508e+02,0.46037e+02]\n ka[:,11,16] = [0.61290e+02,0.59240e+02,0.57269e+02,0.55343e+02,0.53572e+02]\n ka[:,12,16] = [0.71193e+02,0.68607e+02,0.66135e+02,0.63828e+02,0.61720e+02]\n ka[:,13,16] = [0.81988e+02,0.78665e+02,0.75707e+02,0.72932e+02,0.70347e+02]\n \n # -----------------------------------------------------------------\n # The array KB contains absorption coefs at the 16 chosen g-values \n # for a range of pressure levels < ~100mb and temperatures. The first \n # index in the array, JT, which runs from 1 to 5, corresponds to \n # different temperatures. More specifically, JT = 3 means that the \n # data are for the reference temperature TREF for this pressure \n # level, JT = 2 refers to the temperature TREF-15, JT = 1 is for\n # TREF-30, JT = 4 is for TREF+15:and JT = 5 is for TREF+30.\n # The second index, JP, runs from 13 to 59 and refers to the JPth\n # reference pressure level (see taumol.f for the value of these\n # pressure levels in mb). The third index, IG, goes from 1 to 16,\n # and tells us which g-interval the absorption coefficients are for.\n # -----------------------------------------------------------------\n kb = zeros(5,47,16)\n kb[:,13-12, 1] = [0.29597e-05,0.31929e-05,0.34159e-05,0.36256e-05,0.38264e-05]\n kb[:,14-12, 1] = [0.24233e-05,0.26151e-05,0.27866e-05,0.29502e-05,0.31170e-05]\n kb[:,15-12, 1] = [0.19206e-05,0.20789e-05,0.22099e-05,0.23383e-05,0.24505e-05]\n kb[:,16-12, 1] = [0.14933e-05,0.16071e-05,0.17039e-05,0.17994e-05,0.18816e-05]\n kb[:,17-12, 1] = [0.11429e-05,0.12144e-05,0.12895e-05,0.13503e-05,0.14174e-05]\n kb[:,18-12, 1] = [0.84134e-06,0.89264e-06,0.94260e-06,0.99003e-06,0.10391e-05]\n kb[:,19-12, 1] = [0.60683e-06,0.64142e-06,0.68018e-06,0.72042e-06,0.75479e-06]\n kb[:,20-12, 1] = [0.45809e-06,0.48813e-06,0.51934e-06,0.54823e-06,0.57261e-06]\n kb[:,21-12, 1] = [0.35219e-06,0.37835e-06,0.40322e-06,0.42772e-06,0.44736e-06]\n kb[:,22-12, 1] = [0.27419e-06,0.29542e-06,0.31617e-06,0.33398e-06,0.34932e-06]\n kb[:,23-12, 1] = [0.21385e-06,0.23127e-06,0.24670e-06,0.25951e-06,0.26952e-06]\n kb[:,24-12, 1] = [0.16767e-06,0.18179e-06,0.19282e-06,0.20136e-06,0.21113e-06]\n kb[:,25-12, 1] = [0.13361e-06,0.14301e-06,0.14980e-06,0.15778e-06,0.16615e-06]\n kb[:,26-12, 1] = [0.10615e-06,0.11218e-06,0.11889e-06,0.12574e-06,0.13111e-06]\n kb[:,27-12, 1] = [0.83660e-07,0.89296e-07,0.95019e-07,0.10007e-06,0.10397e-06]\n kb[:,28-12, 1] = [0.66667e-07,0.71217e-07,0.75615e-07,0.79237e-07,0.82239e-07]\n kb[:,29-12, 1] = [0.52776e-07,0.56086e-07,0.59828e-07,0.62513e-07,0.64218e-07]\n kb[:,30-12, 1] = [0.41429e-07,0.44370e-07,0.46731e-07,0.48553e-07,0.50143e-07]\n kb[:,31-12, 1] = [0.32437e-07,0.34523e-07,0.36208e-07,0.37500e-07,0.38571e-07]\n kb[:,32-12, 1] = [0.25237e-07,0.26730e-07,0.27868e-07,0.28829e-07,0.29943e-07]\n kb[:,33-12, 1] = [0.19545e-07,0.20614e-07,0.21467e-07,0.22280e-07,0.23141e-07]\n kb[:,34-12, 1] = [0.15146e-07,0.15869e-07,0.16509e-07,0.17179e-07,0.17980e-07]\n kb[:,35-12, 1] = [0.11482e-07,0.12039e-07,0.12547e-07,0.13255e-07,0.13874e-07]\n kb[:,36-12, 1] = [0.86172e-08,0.90023e-08,0.95607e-08,0.10106e-07,0.10595e-07]\n kb[:,37-12, 1] = [0.67411e-08,0.70781e-08,0.75553e-08,0.79739e-08,0.84011e-08]\n kb[:,38-12, 1] = [0.52604e-08,0.55743e-08,0.59410e-08,0.63031e-08,0.66516e-08]\n kb[:,39-12, 1] = [0.41129e-08,0.43854e-08,0.46851e-08,0.49771e-08,0.52463e-08]\n kb[:,40-12, 1] = [0.33089e-08,0.35289e-08,0.37702e-08,0.40125e-08,0.42415e-08]\n kb[:,41-12, 1] = [0.26794e-08,0.28488e-08,0.30428e-08,0.32437e-08,0.34420e-08]\n kb[:,42-12, 1] = [0.21670e-08,0.23030e-08,0.24589e-08,0.26252e-08,0.27867e-08]\n kb[:,43-12, 1] = [0.17699e-08,0.18853e-08,0.20001e-08,0.21330e-08,0.22657e-08]\n kb[:,44-12, 1] = [0.14446e-08,0.15471e-08,0.16397e-08,0.17423e-08,0.18526e-08]\n kb[:,45-12, 1] = [0.11734e-08,0.12754e-08,0.13542e-08,0.14242e-08,0.15193e-08]\n kb[:,46-12, 1] = [0.95743e-09,0.10470e-08,0.11183e-08,0.11726e-08,0.12389e-08]\n kb[:,47-12, 1] = [0.77345e-09,0.85197e-09,0.92184e-09,0.97368e-09,0.10149e-08]\n kb[:,48-12, 1] = [0.62500e-09,0.69288e-09,0.75548e-09,0.80446e-09,0.84428e-09]\n kb[:,49-12, 1] = [0.50095e-09,0.55967e-09,0.61904e-09,0.66441e-09,0.70339e-09]\n kb[:,50-12, 1] = [0.40806e-09,0.45712e-09,0.50530e-09,0.54974e-09,0.58246e-09]\n kb[:,51-12, 1] = [0.33102e-09,0.37130e-09,0.41121e-09,0.45024e-09,0.48436e-09]\n kb[:,52-12, 1] = [0.26906e-09,0.30739e-09,0.33845e-09,0.36884e-09,0.40024e-09]\n kb[:,53-12, 1] = [0.22202e-09,0.25108e-09,0.27937e-09,0.30592e-09,0.33012e-09]\n kb[:,54-12, 1] = [0.18662e-09,0.20761e-09,0.23072e-09,0.25342e-09,0.27445e-09]\n kb[:,55-12, 1] = [0.15741e-09,0.17147e-09,0.19146e-09,0.21029e-09,0.22857e-09]\n kb[:,56-12, 1] = [0.13151e-09,0.14637e-09,0.15977e-09,0.17547e-09,0.18974e-09]\n kb[:,57-12, 1] = [0.10874e-09,0.12447e-09,0.13634e-09,0.14752e-09,0.16022e-09]\n kb[:,58-12, 1] = [0.90206e-10,0.10484e-09,0.11617e-09,0.12545e-09,0.13474e-09]\n kb[:,59-12, 1] = [0.76759e-10,0.88866e-10,0.99340e-10,0.10706e-09,0.11444e-09]\n kb[:,13-12, 2] = [0.14727e-04,0.16357e-04,0.17961e-04,0.19530e-04,0.20852e-04]\n kb[:,14-12, 2] = [0.12148e-04,0.13478e-04,0.14818e-04,0.16049e-04,0.17100e-04]\n kb[:,15-12, 2] = [0.96902e-05,0.10787e-04,0.11835e-04,0.12770e-04,0.13515e-04]\n kb[:,16-12, 2] = [0.76235e-05,0.84575e-05,0.92217e-05,0.98526e-05,0.10449e-04]\n kb[:,17-12, 2] = [0.58049e-05,0.64239e-05,0.69733e-05,0.74131e-05,0.78082e-05]\n kb[:,18-12, 2] = [0.43204e-05,0.47510e-05,0.51165e-05,0.54579e-05,0.57434e-05]\n kb[:,19-12, 2] = [0.32211e-05,0.35327e-05,0.38175e-05,0.40535e-05,0.42245e-05]\n kb[:,20-12, 2] = [0.25265e-05,0.27652e-05,0.29644e-05,0.31331e-05,0.32730e-05]\n kb[:,21-12, 2] = [0.19921e-05,0.21749e-05,0.23343e-05,0.24377e-05,0.25458e-05]\n kb[:,22-12, 2] = [0.15859e-05,0.17259e-05,0.18236e-05,0.19124e-05,0.19942e-05]\n kb[:,23-12, 2] = [0.12591e-05,0.13565e-05,0.14309e-05,0.15032e-05,0.15642e-05]\n kb[:,24-12, 2] = [0.10012e-05,0.10701e-05,0.11246e-05,0.11819e-05,0.12279e-05]\n kb[:,25-12, 2] = [0.78985e-06,0.84074e-06,0.89029e-06,0.93145e-06,0.97085e-06]\n kb[:,26-12, 2] = [0.62996e-06,0.66847e-06,0.70637e-06,0.73513e-06,0.77135e-06]\n kb[:,27-12, 2] = [0.50283e-06,0.53111e-06,0.55653e-06,0.58306e-06,0.61799e-06]\n kb[:,28-12, 2] = [0.39962e-06,0.42320e-06,0.44265e-06,0.46715e-06,0.49516e-06]\n kb[:,29-12, 2] = [0.31810e-06,0.33597e-06,0.35191e-06,0.37448e-06,0.39768e-06]\n kb[:,30-12, 2] = [0.25242e-06,0.26447e-06,0.28109e-06,0.30089e-06,0.31543e-06]\n kb[:,31-12, 2] = [0.19837e-06,0.20954e-06,0.22442e-06,0.23762e-06,0.25183e-06]\n kb[:,32-12, 2] = [0.15599e-06,0.16701e-06,0.17789e-06,0.18880e-06,0.20030e-06]\n kb[:,33-12, 2] = [0.12307e-06,0.13211e-06,0.14046e-06,0.15111e-06,0.15988e-06]\n kb[:,34-12, 2] = [0.98429e-07,0.10498e-06,0.11326e-06,0.12074e-06,0.12779e-06]\n kb[:,35-12, 2] = [0.77743e-07,0.83951e-07,0.90473e-07,0.96277e-07,0.10204e-06]\n kb[:,36-12, 2] = [0.61220e-07,0.66399e-07,0.71102e-07,0.75946e-07,0.80803e-07]\n kb[:,37-12, 2] = [0.48819e-07,0.52962e-07,0.56669e-07,0.60817e-07,0.64709e-07]\n kb[:,38-12, 2] = [0.38871e-07,0.42226e-07,0.45376e-07,0.48641e-07,0.51855e-07]\n kb[:,39-12, 2] = [0.30869e-07,0.33485e-07,0.36233e-07,0.38868e-07,0.41523e-07]\n kb[:,40-12, 2] = [0.24798e-07,0.26983e-07,0.29180e-07,0.31437e-07,0.33600e-07]\n kb[:,41-12, 2] = [0.19951e-07,0.21784e-07,0.23518e-07,0.25460e-07,0.27219e-07]\n kb[:,42-12, 2] = [0.16098e-07,0.17542e-07,0.18979e-07,0.20547e-07,0.22016e-07]\n kb[:,43-12, 2] = [0.13020e-07,0.14144e-07,0.15414e-07,0.16610e-07,0.17870e-07]\n kb[:,44-12, 2] = [0.10548e-07,0.11500e-07,0.12492e-07,0.13520e-07,0.14524e-07]\n kb[:,45-12, 2] = [0.85602e-08,0.93245e-08,0.10096e-07,0.10978e-07,0.11819e-07]\n kb[:,46-12, 2] = [0.69149e-08,0.75653e-08,0.82154e-08,0.88822e-08,0.96002e-08]\n kb[:,47-12, 2] = [0.55708e-08,0.61164e-08,0.66678e-08,0.71922e-08,0.77633e-08]\n kb[:,48-12, 2] = [0.44804e-08,0.49312e-08,0.53967e-08,0.58662e-08,0.62780e-08]\n kb[:,49-12, 2] = [0.36467e-08,0.39866e-08,0.43628e-08,0.47589e-08,0.51208e-08]\n kb[:,50-12, 2] = [0.29524e-08,0.32540e-08,0.35471e-08,0.38638e-08,0.41887e-08]\n kb[:,51-12, 2] = [0.23887e-08,0.26526e-08,0.28959e-08,0.31504e-08,0.34112e-08]\n kb[:,52-12, 2] = [0.19321e-08,0.21648e-08,0.23625e-08,0.25839e-08,0.28173e-08]\n kb[:,53-12, 2] = [0.15684e-08,0.17725e-08,0.19476e-08,0.21240e-08,0.23118e-08]\n kb[:,54-12, 2] = [0.12799e-08,0.14467e-08,0.16073e-08,0.17494e-08,0.19160e-08]\n kb[:,55-12, 2] = [0.10442e-08,0.11911e-08,0.13216e-08,0.14537e-08,0.15771e-08]\n kb[:,56-12, 2] = [0.85741e-09,0.97937e-09,0.10936e-08,0.12056e-08,0.13167e-08]\n kb[:,57-12, 2] = [0.70358e-09,0.80334e-09,0.90824e-09,0.10056e-08,0.11010e-08]\n kb[:,58-12, 2] = [0.57428e-09,0.66441e-09,0.75420e-09,0.83627e-09,0.92485e-09]\n kb[:,59-12, 2] = [0.47922e-09,0.55592e-09,0.63499e-09,0.70731e-09,0.78678e-09]\n kb[:,13-12, 3] = [0.76201e-04,0.82699e-04,0.87499e-04,0.91352e-04,0.95348e-04]\n kb[:,14-12, 3] = [0.62821e-04,0.67861e-04,0.71868e-04,0.75108e-04,0.78557e-04]\n kb[:,15-12, 3] = [0.49775e-04,0.53367e-04,0.56639e-04,0.59001e-04,0.62303e-04]\n kb[:,16-12, 3] = [0.38005e-04,0.40883e-04,0.43269e-04,0.45403e-04,0.48139e-04]\n kb[:,17-12, 3] = [0.28550e-04,0.30750e-04,0.32331e-04,0.34489e-04,0.36687e-04]\n kb[:,18-12, 3] = [0.20976e-04,0.22322e-04,0.23743e-04,0.25554e-04,0.27223e-04]\n kb[:,19-12, 3] = [0.15389e-04,0.16422e-04,0.17792e-04,0.19127e-04,0.20295e-04]\n kb[:,20-12, 3] = [0.11883e-04,0.12816e-04,0.13962e-04,0.14872e-04,0.15725e-04]\n kb[:,21-12, 3] = [0.92948e-05,0.10187e-04,0.10986e-04,0.11713e-04,0.12426e-04]\n kb[:,22-12, 3] = [0.73969e-05,0.80840e-05,0.87263e-05,0.93856e-05,0.99533e-05]\n kb[:,23-12, 3] = [0.58961e-05,0.64591e-05,0.69648e-05,0.74494e-05,0.79385e-05]\n kb[:,24-12, 3] = [0.47445e-05,0.51742e-05,0.56036e-05,0.59758e-05,0.63724e-05]\n kb[:,25-12, 3] = [0.38442e-05,0.41791e-05,0.44837e-05,0.48078e-05,0.51294e-05]\n kb[:,26-12, 3] = [0.31335e-05,0.33923e-05,0.36400e-05,0.38961e-05,0.41487e-05]\n kb[:,27-12, 3] = [0.25499e-05,0.27432e-05,0.29560e-05,0.31545e-05,0.33433e-05]\n kb[:,28-12, 3] = [0.20635e-05,0.22231e-05,0.23897e-05,0.25516e-05,0.26938e-05]\n kb[:,29-12, 3] = [0.16635e-05,0.18024e-05,0.19279e-05,0.20498e-05,0.21627e-05]\n kb[:,30-12, 3] = [0.13359e-05,0.14474e-05,0.15470e-05,0.16346e-05,0.17457e-05]\n kb[:,31-12, 3] = [0.10697e-05,0.11477e-05,0.12254e-05,0.13097e-05,0.13914e-05]\n kb[:,32-12, 3] = [0.84958e-06,0.91464e-06,0.98189e-06,0.10489e-05,0.11150e-05]\n kb[:,33-12, 3] = [0.68178e-06,0.73356e-06,0.78905e-06,0.84226e-06,0.89476e-06]\n kb[:,34-12, 3] = [0.54737e-06,0.58995e-06,0.63374e-06,0.67732e-06,0.72182e-06]\n kb[:,35-12, 3] = [0.43680e-06,0.47086e-06,0.50771e-06,0.54209e-06,0.57687e-06]\n kb[:,36-12, 3] = [0.34612e-06,0.37466e-06,0.40370e-06,0.43073e-06,0.45979e-06]\n kb[:,37-12, 3] = [0.27725e-06,0.30048e-06,0.32451e-06,0.34638e-06,0.37105e-06]\n kb[:,38-12, 3] = [0.22228e-06,0.24114e-06,0.26049e-06,0.27871e-06,0.29935e-06]\n kb[:,39-12, 3] = [0.17797e-06,0.19317e-06,0.20878e-06,0.22411e-06,0.24102e-06]\n kb[:,40-12, 3] = [0.14346e-06,0.15601e-06,0.16913e-06,0.18197e-06,0.19566e-06]\n kb[:,41-12, 3] = [0.11559e-06,0.12615e-06,0.13697e-06,0.14785e-06,0.15874e-06]\n kb[:,42-12, 3] = [0.93358e-07,0.10214e-06,0.11089e-06,0.11998e-06,0.12904e-06]\n kb[:,43-12, 3] = [0.75599e-07,0.82690e-07,0.89808e-07,0.97524e-07,0.10511e-06]\n kb[:,44-12, 3] = [0.61285e-07,0.66786e-07,0.72937e-07,0.79087e-07,0.85525e-07]\n kb[:,45-12, 3] = [0.49725e-07,0.54294e-07,0.59263e-07,0.64213e-07,0.69583e-07]\n kb[:,46-12, 3] = [0.40336e-07,0.44186e-07,0.48034e-07,0.52184e-07,0.56534e-07]\n kb[:,47-12, 3] = [0.32904e-07,0.35633e-07,0.38959e-07,0.42402e-07,0.45883e-07]\n kb[:,48-12, 3] = [0.26725e-07,0.29104e-07,0.31693e-07,0.34312e-07,0.37304e-07]\n kb[:,49-12, 3] = [0.21751e-07,0.23849e-07,0.25803e-07,0.28024e-07,0.30356e-07]\n kb[:,50-12, 3] = [0.17587e-07,0.19609e-07,0.21216e-07,0.23022e-07,0.24942e-07]\n kb[:,51-12, 3] = [0.14376e-07,0.15990e-07,0.17493e-07,0.18872e-07,0.20463e-07]\n kb[:,52-12, 3] = [0.11811e-07,0.13106e-07,0.14489e-07,0.15615e-07,0.16832e-07]\n kb[:,53-12, 3] = [0.96001e-08,0.10788e-07,0.11921e-07,0.12985e-07,0.13904e-07]\n kb[:,54-12, 3] = [0.78243e-08,0.89178e-08,0.98430e-08,0.10840e-07,0.11619e-07]\n kb[:,55-12, 3] = [0.63638e-08,0.73678e-08,0.82214e-08,0.89997e-08,0.97565e-08]\n kb[:,56-12, 3] = [0.51753e-08,0.60497e-08,0.68419e-08,0.74560e-08,0.82362e-08]\n kb[:,57-12, 3] = [0.42164e-08,0.49916e-08,0.57066e-08,0.63308e-08,0.68950e-08]\n kb[:,58-12, 3] = [0.34618e-08,0.41424e-08,0.48054e-08,0.53757e-08,0.58095e-08]\n kb[:,59-12, 3] = [0.29083e-08,0.35291e-08,0.40932e-08,0.46285e-08,0.49865e-08]\n kb[:,13-12, 4] = [0.37674e-03,0.40953e-03,0.43690e-03,0.46059e-03,0.48007e-03]\n kb[:,14-12, 4] = [0.31202e-03,0.33906e-03,0.36066e-03,0.38003e-03,0.39627e-03]\n kb[:,15-12, 4] = [0.25135e-03,0.27271e-03,0.29069e-03,0.30661e-03,0.32005e-03]\n kb[:,16-12, 4] = [0.19797e-03,0.21527e-03,0.22955e-03,0.24328e-03,0.25456e-03]\n kb[:,17-12, 4] = [0.15354e-03,0.16679e-03,0.17933e-03,0.19101e-03,0.20041e-03]\n kb[:,18-12, 4] = [0.11742e-03,0.12797e-03,0.13923e-03,0.14836e-03,0.15654e-03]\n kb[:,19-12, 4] = [0.90519e-04,0.99386e-04,0.10819e-03,0.11601e-03,0.12319e-03]\n kb[:,20-12, 4] = [0.72579e-04,0.79910e-04,0.87075e-04,0.93728e-04,0.99656e-04]\n kb[:,21-12, 4] = [0.58866e-04,0.64805e-04,0.70705e-04,0.76153e-04,0.80996e-04]\n kb[:,22-12, 4] = [0.48157e-04,0.52883e-04,0.57740e-04,0.62130e-04,0.66100e-04]\n kb[:,23-12, 4] = [0.39337e-04,0.43289e-04,0.47275e-04,0.50906e-04,0.54161e-04]\n kb[:,24-12, 4] = [0.32289e-04,0.35577e-04,0.38808e-04,0.41814e-04,0.44433e-04]\n kb[:,25-12, 4] = [0.26615e-04,0.29301e-04,0.31984e-04,0.34396e-04,0.36509e-04]\n kb[:,26-12, 4] = [0.22060e-04,0.24270e-04,0.26460e-04,0.28450e-04,0.30203e-04]\n kb[:,27-12, 4] = [0.18344e-04,0.20177e-04,0.21948e-04,0.23595e-04,0.25001e-04]\n kb[:,28-12, 4] = [0.15256e-04,0.16787e-04,0.18242e-04,0.19561e-04,0.20696e-04]\n kb[:,29-12, 4] = [0.12679e-04,0.13952e-04,0.15170e-04,0.16211e-04,0.17163e-04]\n kb[:,30-12, 4] = [0.10550e-04,0.11605e-04,0.12579e-04,0.13451e-04,0.14210e-04]\n kb[:,31-12, 4] = [0.87512e-05,0.96322e-05,0.10433e-04,0.11133e-04,0.11762e-04]\n kb[:,32-12, 4] = [0.73001e-05,0.80203e-05,0.86745e-05,0.92292e-05,0.97295e-05]\n kb[:,33-12, 4] = [0.60958e-05,0.66862e-05,0.72006e-05,0.76359e-05,0.80576e-05]\n kb[:,34-12, 4] = [0.50855e-05,0.55671e-05,0.59670e-05,0.63392e-05,0.66869e-05]\n kb[:,35-12, 4] = [0.42033e-05,0.45905e-05,0.49250e-05,0.52384e-05,0.55369e-05]\n kb[:,36-12, 4] = [0.34384e-05,0.37618e-05,0.40430e-05,0.43060e-05,0.45577e-05]\n kb[:,37-12, 4] = [0.28039e-05,0.30749e-05,0.33135e-05,0.35344e-05,0.37458e-05]\n kb[:,38-12, 4] = [0.22842e-05,0.25104e-05,0.27126e-05,0.28966e-05,0.30768e-05]\n kb[:,39-12, 4] = [0.18585e-05,0.20510e-05,0.22194e-05,0.23731e-05,0.25249e-05]\n kb[:,40-12, 4] = [0.15041e-05,0.16676e-05,0.18097e-05,0.19402e-05,0.20681e-05]\n kb[:,41-12, 4] = [0.12154e-05,0.13541e-05,0.14749e-05,0.15852e-05,0.16934e-05]\n kb[:,42-12, 4] = [0.98033e-06,0.10975e-05,0.12011e-05,0.12945e-05,0.13859e-05]\n kb[:,43-12, 4] = [0.78724e-06,0.88625e-06,0.97486e-06,0.10554e-05,0.11307e-05]\n kb[:,44-12, 4] = [0.63059e-06,0.71382e-06,0.78948e-06,0.85755e-06,0.92044e-06]\n kb[:,45-12, 4] = [0.50426e-06,0.57391e-06,0.63808e-06,0.69718e-06,0.74972e-06]\n kb[:,46-12, 4] = [0.40133e-06,0.45858e-06,0.51414e-06,0.56400e-06,0.60964e-06]\n kb[:,47-12, 4] = [0.31580e-06,0.36440e-06,0.41120e-06,0.45433e-06,0.49348e-06]\n kb[:,48-12, 4] = [0.24847e-06,0.28907e-06,0.32879e-06,0.36537e-06,0.39903e-06]\n kb[:,49-12, 4] = [0.19530e-06,0.22858e-06,0.26247e-06,0.29331e-06,0.32217e-06]\n kb[:,50-12, 4] = [0.15364e-06,0.18113e-06,0.20911e-06,0.23589e-06,0.25994e-06]\n kb[:,51-12, 4] = [0.12072e-06,0.14413e-06,0.16656e-06,0.18952e-06,0.20983e-06]\n kb[:,52-12, 4] = [0.94925e-07,0.11397e-06,0.13255e-06,0.15193e-06,0.16960e-06]\n kb[:,53-12, 4] = [0.74473e-07,0.90197e-07,0.10574e-06,0.12153e-06,0.13661e-06]\n kb[:,54-12, 4] = [0.59009e-07,0.71594e-07,0.84781e-07,0.97758e-07,0.11018e-06]\n kb[:,55-12, 4] = [0.47008e-07,0.56997e-07,0.67838e-07,0.78753e-07,0.89116e-07]\n kb[:,56-12, 4] = [0.37415e-07,0.45642e-07,0.54420e-07,0.63466e-07,0.71910e-07]\n kb[:,57-12, 4] = [0.29896e-07,0.36635e-07,0.43697e-07,0.51036e-07,0.58267e-07]\n kb[:,58-12, 4] = [0.23946e-07,0.29523e-07,0.35316e-07,0.41183e-07,0.47391e-07]\n kb[:,59-12, 4] = [0.19881e-07,0.24642e-07,0.29390e-07,0.34099e-07,0.39234e-07]\n kb[:,13-12, 5] = [0.12771e-02,0.13202e-02,0.13557e-02,0.13927e-02,0.14233e-02]\n kb[:,14-12, 5] = [0.10608e-02,0.10951e-02,0.11249e-02,0.11549e-02,0.11788e-02]\n kb[:,15-12, 5] = [0.86750e-03,0.89679e-03,0.91986e-03,0.94399e-03,0.96405e-03]\n kb[:,16-12, 5] = [0.70073e-03,0.72504e-03,0.74630e-03,0.76495e-03,0.78165e-03]\n kb[:,17-12, 5] = [0.56280e-03,0.58321e-03,0.60153e-03,0.61544e-03,0.62885e-03]\n kb[:,18-12, 5] = [0.44940e-03,0.46598e-03,0.47887e-03,0.49058e-03,0.50223e-03]\n kb[:,19-12, 5] = [0.35753e-03,0.37064e-03,0.38290e-03,0.39390e-03,0.40387e-03]\n kb[:,20-12, 5] = [0.29013e-03,0.30099e-03,0.31179e-03,0.32117e-03,0.33011e-03]\n kb[:,21-12, 5] = [0.23657e-03,0.24602e-03,0.25504e-03,0.26340e-03,0.27145e-03]\n kb[:,22-12, 5] = [0.19423e-03,0.20224e-03,0.20987e-03,0.21711e-03,0.22439e-03]\n kb[:,23-12, 5] = [0.15963e-03,0.16643e-03,0.17308e-03,0.17949e-03,0.18580e-03]\n kb[:,24-12, 5] = [0.13166e-03,0.13745e-03,0.14332e-03,0.14871e-03,0.15428e-03]\n kb[:,25-12, 5] = [0.10885e-03,0.11394e-03,0.11896e-03,0.12371e-03,0.12846e-03]\n kb[:,26-12, 5] = [0.90403e-04,0.94914e-04,0.99157e-04,0.10310e-03,0.10729e-03]\n kb[:,27-12, 5] = [0.75265e-04,0.79166e-04,0.82648e-04,0.86209e-04,0.89882e-04]\n kb[:,28-12, 5] = [0.62870e-04,0.66050e-04,0.69111e-04,0.72289e-04,0.75451e-04]\n kb[:,29-12, 5] = [0.52465e-04,0.55192e-04,0.57887e-04,0.60660e-04,0.63367e-04]\n kb[:,30-12, 5] = [0.43887e-04,0.46191e-04,0.48588e-04,0.50910e-04,0.53278e-04]\n kb[:,31-12, 5] = [0.36760e-04,0.38766e-04,0.40783e-04,0.42783e-04,0.44780e-04]\n kb[:,32-12, 5] = [0.30831e-04,0.32561e-04,0.34267e-04,0.36000e-04,0.37594e-04]\n kb[:,33-12, 5] = [0.25908e-04,0.27389e-04,0.28832e-04,0.30290e-04,0.31581e-04]\n kb[:,34-12, 5] = [0.21776e-04,0.23026e-04,0.24266e-04,0.25444e-04,0.26510e-04]\n kb[:,35-12, 5] = [0.18233e-04,0.19280e-04,0.20324e-04,0.21266e-04,0.22141e-04]\n kb[:,36-12, 5] = [0.15160e-04,0.16042e-04,0.16918e-04,0.17686e-04,0.18406e-04]\n kb[:,37-12, 5] = [0.12538e-04,0.13285e-04,0.14015e-04,0.14657e-04,0.15269e-04]\n kb[:,38-12, 5] = [0.10357e-04,0.10990e-04,0.11595e-04,0.12148e-04,0.12651e-04]\n kb[:,39-12, 5] = [0.85566e-05,0.90856e-05,0.95986e-05,0.10057e-04,0.10478e-04]\n kb[:,40-12, 5] = [0.70390e-05,0.74826e-05,0.79200e-05,0.83061e-05,0.86634e-05]\n kb[:,41-12, 5] = [0.57827e-05,0.61572e-05,0.65269e-05,0.68528e-05,0.71595e-05]\n kb[:,42-12, 5] = [0.47477e-05,0.50656e-05,0.53705e-05,0.56486e-05,0.59100e-05]\n kb[:,43-12, 5] = [0.38802e-05,0.41533e-05,0.44089e-05,0.46515e-05,0.48719e-05]\n kb[:,44-12, 5] = [0.31658e-05,0.33971e-05,0.36177e-05,0.38205e-05,0.40089e-05]\n kb[:,45-12, 5] = [0.25796e-05,0.27740e-05,0.29635e-05,0.31336e-05,0.32986e-05]\n kb[:,46-12, 5] = [0.20945e-05,0.22636e-05,0.24214e-05,0.25698e-05,0.27077e-05]\n kb[:,47-12, 5] = [0.16931e-05,0.18383e-05,0.19729e-05,0.20996e-05,0.22172e-05]\n kb[:,48-12, 5] = [0.13650e-05,0.14889e-05,0.16043e-05,0.17139e-05,0.18136e-05]\n kb[:,49-12, 5] = [0.10981e-05,0.12042e-05,0.13028e-05,0.13963e-05,0.14824e-05]\n kb[:,50-12, 5] = [0.88407e-06,0.97370e-06,0.10589e-05,0.11383e-05,0.12124e-05]\n kb[:,51-12, 5] = [0.71150e-06,0.78682e-06,0.86048e-06,0.92711e-06,0.99128e-06]\n kb[:,52-12, 5] = [0.57140e-06,0.63513e-06,0.69790e-06,0.75466e-06,0.80946e-06]\n kb[:,53-12, 5] = [0.45871e-06,0.51183e-06,0.56494e-06,0.61376e-06,0.66022e-06]\n kb[:,54-12, 5] = [0.36889e-06,0.41319e-06,0.45759e-06,0.49973e-06,0.53933e-06]\n kb[:,55-12, 5] = [0.29683e-06,0.33396e-06,0.37110e-06,0.40671e-06,0.44026e-06]\n kb[:,56-12, 5] = [0.23828e-06,0.26973e-06,0.30048e-06,0.33099e-06,0.35949e-06]\n kb[:,57-12, 5] = [0.19083e-06,0.21782e-06,0.24350e-06,0.26883e-06,0.29309e-06]\n kb[:,58-12, 5] = [0.15334e-06,0.17592e-06,0.19753e-06,0.21869e-06,0.23903e-06]\n kb[:,59-12, 5] = [0.12635e-06,0.14504e-06,0.16321e-06,0.18074e-06,0.19759e-06]\n kb[:,13-12, 6] = [0.33433e-02,0.34159e-02,0.34798e-02,0.35397e-02,0.35995e-02]\n kb[:,14-12, 6] = [0.28039e-02,0.28589e-02,0.29090e-02,0.29595e-02,0.30108e-02]\n kb[:,15-12, 6] = [0.23135e-02,0.23579e-02,0.24012e-02,0.24470e-02,0.24900e-02]\n kb[:,16-12, 6] = [0.18925e-02,0.19281e-02,0.19671e-02,0.20090e-02,0.20445e-02]\n kb[:,17-12, 6] = [0.15365e-02,0.15703e-02,0.16039e-02,0.16424e-02,0.16760e-02]\n kb[:,18-12, 6] = [0.12424e-02,0.12746e-02,0.13067e-02,0.13397e-02,0.13687e-02]\n kb[:,19-12, 6] = [0.10113e-02,0.10417e-02,0.10664e-02,0.10958e-02,0.11231e-02]\n kb[:,20-12, 6] = [0.83375e-03,0.85863e-03,0.88098e-03,0.90680e-03,0.93093e-03]\n kb[:,21-12, 6] = [0.68849e-03,0.71056e-03,0.73161e-03,0.75402e-03,0.77432e-03]\n kb[:,22-12, 6] = [0.57076e-03,0.59001e-03,0.60925e-03,0.62816e-03,0.64531e-03]\n kb[:,23-12, 6] = [0.47462e-03,0.49138e-03,0.50818e-03,0.52421e-03,0.53930e-03]\n kb[:,24-12, 6] = [0.39552e-03,0.41011e-03,0.42460e-03,0.43865e-03,0.45206e-03]\n kb[:,25-12, 6] = [0.33041e-03,0.34317e-03,0.35573e-03,0.36800e-03,0.38005e-03]\n kb[:,26-12, 6] = [0.27699e-03,0.28806e-03,0.29892e-03,0.30983e-03,0.32038e-03]\n kb[:,27-12, 6] = [0.23253e-03,0.24229e-03,0.25208e-03,0.26144e-03,0.27039e-03]\n kb[:,28-12, 6] = [0.19573e-03,0.20442e-03,0.21276e-03,0.22087e-03,0.22869e-03]\n kb[:,29-12, 6] = [0.16528e-03,0.17271e-03,0.17974e-03,0.18681e-03,0.19373e-03]\n kb[:,30-12, 6] = [0.13949e-03,0.14599e-03,0.15214e-03,0.15834e-03,0.16448e-03]\n kb[:,31-12, 6] = [0.11793e-03,0.12345e-03,0.12891e-03,0.13432e-03,0.13975e-03]\n kb[:,32-12, 6] = [0.99845e-04,0.10464e-03,0.10941e-03,0.11425e-03,0.11896e-03]\n kb[:,33-12, 6] = [0.84723e-04,0.88808e-04,0.93054e-04,0.97257e-04,0.10144e-03]\n kb[:,34-12, 6] = [0.71857e-04,0.75478e-04,0.79245e-04,0.82878e-04,0.86527e-04]\n kb[:,35-12, 6] = [0.60741e-04,0.63987e-04,0.67190e-04,0.70445e-04,0.73634e-04]\n kb[:,36-12, 6] = [0.51094e-04,0.53953e-04,0.56787e-04,0.59644e-04,0.62421e-04]\n kb[:,37-12, 6] = [0.42809e-04,0.45324e-04,0.47805e-04,0.50314e-04,0.52797e-04]\n kb[:,38-12, 6] = [0.35862e-04,0.38082e-04,0.40249e-04,0.42459e-04,0.44691e-04]\n kb[:,39-12, 6] = [0.30047e-04,0.31970e-04,0.33877e-04,0.35841e-04,0.37792e-04]\n kb[:,40-12, 6] = [0.25051e-04,0.26734e-04,0.28429e-04,0.30177e-04,0.31859e-04]\n kb[:,41-12, 6] = [0.20858e-04,0.22337e-04,0.23837e-04,0.25348e-04,0.26845e-04]\n kb[:,42-12, 6] = [0.17358e-04,0.18653e-04,0.19947e-04,0.21279e-04,0.22614e-04]\n kb[:,43-12, 6] = [0.14382e-04,0.15507e-04,0.16637e-04,0.17808e-04,0.18975e-04]\n kb[:,44-12, 6] = [0.11875e-04,0.12851e-04,0.13847e-04,0.14865e-04,0.15886e-04]\n kb[:,45-12, 6] = [0.97824e-05,0.10641e-04,0.11497e-04,0.12386e-04,0.13288e-04]\n kb[:,46-12, 6] = [0.80305e-05,0.87712e-05,0.95170e-05,0.10282e-04,0.11073e-04]\n kb[:,47-12, 6] = [0.65554e-05,0.71881e-05,0.78331e-05,0.85022e-05,0.91799e-05]\n kb[:,48-12, 6] = [0.53399e-05,0.58818e-05,0.64364e-05,0.70093e-05,0.75992e-05]\n kb[:,49-12, 6] = [0.43396e-05,0.47990e-05,0.52727e-05,0.57633e-05,0.62785e-05]\n kb[:,50-12, 6] = [0.35272e-05,0.39139e-05,0.43230e-05,0.47423e-05,0.51819e-05]\n kb[:,51-12, 6] = [0.28624e-05,0.31913e-05,0.35379e-05,0.38979e-05,0.42744e-05]\n kb[:,52-12, 6] = [0.23189e-05,0.25961e-05,0.28907e-05,0.31976e-05,0.35200e-05]\n kb[:,53-12, 6] = [0.18736e-05,0.21072e-05,0.23576e-05,0.26179e-05,0.28943e-05]\n kb[:,54-12, 6] = [0.15155e-05,0.17135e-05,0.19245e-05,0.21451e-05,0.23808e-05]\n kb[:,55-12, 6] = [0.12250e-05,0.13923e-05,0.15714e-05,0.17578e-05,0.19597e-05]\n kb[:,56-12, 6] = [0.99012e-06,0.11296e-05,0.12801e-05,0.14395e-05,0.16107e-05]\n kb[:,57-12, 6] = [0.79875e-06,0.91418e-06,0.10408e-05,0.11777e-05,0.13212e-05]\n kb[:,58-12, 6] = [0.64474e-06,0.74109e-06,0.84664e-06,0.96328e-06,0.10849e-05]\n kb[:,59-12, 6] = [0.53296e-06,0.61427e-06,0.70385e-06,0.80375e-06,0.90863e-06]\n kb[:,13-12, 7] = [0.91063e-02,0.92681e-02,0.94045e-02,0.95388e-02,0.96735e-02]\n kb[:,14-12, 7] = [0.78483e-02,0.79806e-02,0.81238e-02,0.82528e-02,0.83603e-02]\n kb[:,15-12, 7] = [0.66269e-02,0.67445e-02,0.68845e-02,0.69911e-02,0.70854e-02]\n kb[:,16-12, 7] = [0.55183e-02,0.56414e-02,0.57574e-02,0.58487e-02,0.59407e-02]\n kb[:,17-12, 7] = [0.45693e-02,0.46780e-02,0.47743e-02,0.48625e-02,0.49467e-02]\n kb[:,18-12, 7] = [0.37611e-02,0.38535e-02,0.39408e-02,0.40234e-02,0.41007e-02]\n kb[:,19-12, 7] = [0.30991e-02,0.31809e-02,0.32647e-02,0.33388e-02,0.34042e-02]\n kb[:,20-12, 7] = [0.25858e-02,0.26585e-02,0.27347e-02,0.27990e-02,0.28579e-02]\n kb[:,21-12, 7] = [0.21672e-02,0.22326e-02,0.22973e-02,0.23547e-02,0.24058e-02]\n kb[:,22-12, 7] = [0.18211e-02,0.18809e-02,0.19364e-02,0.19859e-02,0.20352e-02]\n kb[:,23-12, 7] = [0.15314e-02,0.15844e-02,0.16332e-02,0.16760e-02,0.17243e-02]\n kb[:,24-12, 7] = [0.12924e-02,0.13385e-02,0.13793e-02,0.14209e-02,0.14659e-02]\n kb[:,25-12, 7] = [0.10926e-02,0.11322e-02,0.11689e-02,0.12081e-02,0.12493e-02]\n kb[:,26-12, 7] = [0.92756e-03,0.96136e-03,0.99601e-03,0.10324e-02,0.10695e-02]\n kb[:,27-12, 7] = [0.78832e-03,0.81893e-03,0.85137e-03,0.88465e-03,0.91885e-03]\n kb[:,28-12, 7] = [0.67097e-03,0.69979e-03,0.72985e-03,0.76038e-03,0.79213e-03]\n kb[:,29-12, 7] = [0.57231e-03,0.59934e-03,0.62727e-03,0.65471e-03,0.68389e-03]\n kb[:,30-12, 7] = [0.48996e-03,0.51441e-03,0.53945e-03,0.56564e-03,0.59164e-03]\n kb[:,31-12, 7] = [0.41998e-03,0.44237e-03,0.46551e-03,0.48924e-03,0.51322e-03]\n kb[:,32-12, 7] = [0.36133e-03,0.38168e-03,0.40297e-03,0.42441e-03,0.44722e-03]\n kb[:,33-12, 7] = [0.31153e-03,0.33055e-03,0.34980e-03,0.36972e-03,0.39086e-03]\n kb[:,34-12, 7] = [0.26941e-03,0.28657e-03,0.30436e-03,0.32295e-03,0.34256e-03]\n kb[:,35-12, 7] = [0.23210e-03,0.24782e-03,0.26411e-03,0.28121e-03,0.29930e-03]\n kb[:,36-12, 7] = [0.19904e-03,0.21311e-03,0.22797e-03,0.24380e-03,0.26030e-03]\n kb[:,37-12, 7] = [0.17000e-03,0.18300e-03,0.19666e-03,0.21128e-03,0.22641e-03]\n kb[:,38-12, 7] = [0.14528e-03,0.15704e-03,0.16975e-03,0.18320e-03,0.19735e-03]\n kb[:,39-12, 7] = [0.12414e-03,0.13496e-03,0.14654e-03,0.15899e-03,0.17211e-03]\n kb[:,40-12, 7] = [0.10567e-03,0.11547e-03,0.12618e-03,0.13765e-03,0.14994e-03]\n kb[:,41-12, 7] = [0.89774e-04,0.98751e-04,0.10852e-03,0.11918e-03,0.13057e-03]\n kb[:,42-12, 7] = [0.76232e-04,0.84383e-04,0.93336e-04,0.10314e-03,0.11381e-03]\n kb[:,43-12, 7] = [0.64370e-04,0.71684e-04,0.79797e-04,0.88850e-04,0.98733e-04]\n kb[:,44-12, 7] = [0.54125e-04,0.60680e-04,0.68042e-04,0.76313e-04,0.85432e-04]\n kb[:,45-12, 7] = [0.45374e-04,0.51280e-04,0.57932e-04,0.65429e-04,0.73852e-04]\n kb[:,46-12, 7] = [0.37861e-04,0.43078e-04,0.49016e-04,0.55844e-04,0.63538e-04]\n kb[:,47-12, 7] = [0.31342e-04,0.35879e-04,0.41175e-04,0.47252e-04,0.54286e-04]\n kb[:,48-12, 7] = [0.25821e-04,0.29777e-04,0.34458e-04,0.39880e-04,0.46218e-04]\n kb[:,49-12, 7] = [0.21180e-04,0.24617e-04,0.28719e-04,0.33507e-04,0.39184e-04]\n kb[:,50-12, 7] = [0.17377e-04,0.20345e-04,0.23916e-04,0.28177e-04,0.33237e-04]\n kb[:,51-12, 7] = [0.14223e-04,0.16790e-04,0.19868e-04,0.23656e-04,0.28163e-04]\n kb[:,52-12, 7] = [0.11593e-04,0.13788e-04,0.16479e-04,0.19773e-04,0.23765e-04]\n kb[:,53-12, 7] = [0.94141e-05,0.11279e-04,0.13591e-04,0.16447e-04,0.19969e-04]\n kb[:,54-12, 7] = [0.76622e-05,0.92417e-05,0.11233e-04,0.13709e-04,0.16819e-04]\n kb[:,55-12, 7] = [0.62315e-05,0.75671e-05,0.92699e-05,0.11429e-04,0.14186e-04]\n kb[:,56-12, 7] = [0.50473e-05,0.61766e-05,0.76316e-05,0.94979e-05,0.11890e-04]\n kb[:,57-12, 7] = [0.40773e-05,0.50242e-05,0.62540e-05,0.78594e-05,0.99378e-05]\n kb[:,58-12, 7] = [0.32937e-05,0.40862e-05,0.51228e-05,0.64992e-05,0.83112e-05]\n kb[:,59-12, 7] = [0.27593e-05,0.34505e-05,0.43716e-05,0.56035e-05,0.72609e-05]\n kb[:,13-12, 8] = [0.25990e-01,0.25997e-01,0.26024e-01,0.26038e-01,0.26132e-01]\n kb[:,14-12, 8] = [0.22648e-01,0.22731e-01,0.22803e-01,0.22861e-01,0.23020e-01]\n kb[:,15-12, 8] = [0.19641e-01,0.19812e-01,0.19880e-01,0.19998e-01,0.20141e-01]\n kb[:,16-12, 8] = [0.16909e-01,0.17030e-01,0.17148e-01,0.17296e-01,0.17502e-01]\n kb[:,17-12, 8] = [0.14365e-01,0.14504e-01,0.14643e-01,0.14808e-01,0.14996e-01]\n kb[:,18-12, 8] = [0.12072e-01,0.12207e-01,0.12346e-01,0.12513e-01,0.12742e-01]\n kb[:,19-12, 8] = [0.10135e-01,0.10263e-01,0.10402e-01,0.10602e-01,0.10794e-01]\n kb[:,20-12, 8] = [0.86508e-02,0.87951e-02,0.89765e-02,0.91530e-02,0.93447e-02]\n kb[:,21-12, 8] = [0.74228e-02,0.75964e-02,0.77805e-02,0.79441e-02,0.81266e-02]\n kb[:,22-12, 8] = [0.63949e-02,0.65920e-02,0.67584e-02,0.69298e-02,0.70968e-02]\n kb[:,23-12, 8] = [0.55389e-02,0.57165e-02,0.58834e-02,0.60490e-02,0.62163e-02]\n kb[:,24-12, 8] = [0.47980e-02,0.49696e-02,0.51333e-02,0.53055e-02,0.54695e-02]\n kb[:,25-12, 8] = [0.41676e-02,0.43357e-02,0.44999e-02,0.46749e-02,0.48179e-02]\n kb[:,26-12, 8] = [0.36391e-02,0.38079e-02,0.39834e-02,0.41374e-02,0.42754e-02]\n kb[:,27-12, 8] = [0.31917e-02,0.33580e-02,0.35237e-02,0.36737e-02,0.37982e-02]\n kb[:,28-12, 8] = [0.28096e-02,0.29709e-02,0.31242e-02,0.32613e-02,0.33829e-02]\n kb[:,29-12, 8] = [0.24786e-02,0.26272e-02,0.27706e-02,0.28986e-02,0.30130e-02]\n kb[:,30-12, 8] = [0.21907e-02,0.23282e-02,0.24574e-02,0.25778e-02,0.26806e-02]\n kb[:,31-12, 8] = [0.19346e-02,0.20569e-02,0.21757e-02,0.22805e-02,0.23742e-02]\n kb[:,32-12, 8] = [0.17101e-02,0.18247e-02,0.19308e-02,0.20256e-02,0.21176e-02]\n kb[:,33-12, 8] = [0.15171e-02,0.16168e-02,0.17121e-02,0.18035e-02,0.18911e-02]\n kb[:,34-12, 8] = [0.13466e-02,0.14390e-02,0.15246e-02,0.16083e-02,0.16921e-02]\n kb[:,35-12, 8] = [0.11871e-02,0.12698e-02,0.13534e-02,0.14320e-02,0.15071e-02]\n kb[:,36-12, 8] = [0.10388e-02,0.11179e-02,0.11934e-02,0.12647e-02,0.13391e-02]\n kb[:,37-12, 8] = [0.92233e-03,0.99854e-03,0.10722e-02,0.11426e-02,0.12118e-02]\n kb[:,38-12, 8] = [0.81843e-03,0.89236e-03,0.96605e-03,0.10340e-02,0.11003e-02]\n kb[:,39-12, 8] = [0.72738e-03,0.79777e-03,0.86997e-03,0.93496e-03,0.99852e-03]\n kb[:,40-12, 8] = [0.65149e-03,0.72098e-03,0.79235e-03,0.86116e-03,0.92474e-03]\n kb[:,41-12, 8] = [0.58318e-03,0.65154e-03,0.72160e-03,0.79400e-03,0.85973e-03]\n kb[:,42-12, 8] = [0.52127e-03,0.58770e-03,0.65781e-03,0.73110e-03,0.80165e-03]\n kb[:,43-12, 8] = [0.46404e-03,0.52960e-03,0.59886e-03,0.67366e-03,0.74727e-03]\n kb[:,44-12, 8] = [0.41229e-03,0.47609e-03,0.54424e-03,0.61918e-03,0.69366e-03]\n kb[:,45-12, 8] = [0.36534e-03,0.42624e-03,0.49374e-03,0.56668e-03,0.64364e-03]\n kb[:,46-12, 8] = [0.32134e-03,0.37987e-03,0.44597e-03,0.51669e-03,0.59469e-03]\n kb[:,47-12, 8] = [0.27855e-03,0.33531e-03,0.39855e-03,0.46832e-03,0.54562e-03]\n kb[:,48-12, 8] = [0.24094e-03,0.29440e-03,0.35477e-03,0.42284e-03,0.49767e-03]\n kb[:,49-12, 8] = [0.20710e-03,0.25712e-03,0.31425e-03,0.38098e-03,0.45465e-03]\n kb[:,50-12, 8] = [0.17757e-03,0.22422e-03,0.27906e-03,0.34231e-03,0.41419e-03]\n kb[:,51-12, 8] = [0.15198e-03,0.19538e-03,0.24758e-03,0.30796e-03,0.37765e-03]\n kb[:,52-12, 8] = [0.12943e-03,0.16907e-03,0.21812e-03,0.27585e-03,0.34284e-03]\n kb[:,53-12, 8] = [0.10946e-03,0.14560e-03,0.19103e-03,0.24633e-03,0.31049e-03]\n kb[:,54-12, 8] = [0.92950e-04,0.12599e-03,0.16848e-03,0.22109e-03,0.28266e-03]\n kb[:,55-12, 8] = [0.78722e-04,0.10883e-03,0.14831e-03,0.19790e-03,0.25770e-03]\n kb[:,56-12, 8] = [0.66323e-04,0.93651e-04,0.12983e-03,0.17638e-03,0.23393e-03]\n kb[:,57-12, 8] = [0.55644e-04,0.80085e-04,0.11349e-03,0.15741e-03,0.21274e-03]\n kb[:,58-12, 8] = [0.46537e-04,0.68442e-04,0.99190e-04,0.14045e-03,0.19327e-03]\n kb[:,59-12, 8] = [0.41558e-04,0.62503e-04,0.92377e-04,0.13258e-03,0.18528e-03]\n kb[:,13-12, 9] = [0.14836e+00,0.15039e+00,0.15239e+00,0.15389e+00,0.15517e+00]\n kb[:,14-12, 9] = [0.12935e+00,0.13183e+00,0.13366e+00,0.13551e+00,0.13674e+00]\n kb[:,15-12, 9] = [0.11269e+00,0.11456e+00,0.11672e+00,0.11824e+00,0.11951e+00]\n kb[:,16-12, 9] = [0.97577e-01,0.99647e-01,0.10140e+00,0.10272e+00,0.10390e+00]\n kb[:,17-12, 9] = [0.84601e-01,0.86370e-01,0.87860e-01,0.89144e-01,0.90341e-01]\n kb[:,18-12, 9] = [0.72851e-01,0.74498e-01,0.75924e-01,0.77220e-01,0.78434e-01]\n kb[:,19-12, 9] = [0.62688e-01,0.64121e-01,0.65574e-01,0.66965e-01,0.68243e-01]\n kb[:,20-12, 9] = [0.54382e-01,0.55704e-01,0.57013e-01,0.58303e-01,0.59763e-01]\n kb[:,21-12, 9] = [0.47190e-01,0.48469e-01,0.49752e-01,0.51138e-01,0.52452e-01]\n kb[:,22-12, 9] = [0.41104e-01,0.42378e-01,0.43684e-01,0.45035e-01,0.46495e-01]\n kb[:,23-12, 9] = [0.35910e-01,0.37220e-01,0.38484e-01,0.39789e-01,0.41443e-01]\n kb[:,24-12, 9] = [0.31558e-01,0.32836e-01,0.34085e-01,0.35462e-01,0.37160e-01]\n kb[:,25-12, 9] = [0.27861e-01,0.29090e-01,0.30363e-01,0.31857e-01,0.33566e-01]\n kb[:,26-12, 9] = [0.24743e-01,0.26003e-01,0.27311e-01,0.28788e-01,0.30553e-01]\n kb[:,27-12, 9] = [0.22141e-01,0.23397e-01,0.24754e-01,0.26282e-01,0.28040e-01]\n kb[:,28-12, 9] = [0.19941e-01,0.21165e-01,0.22565e-01,0.24131e-01,0.25980e-01]\n kb[:,29-12, 9] = [0.18046e-01,0.19353e-01,0.20736e-01,0.22375e-01,0.24248e-01]\n kb[:,30-12, 9] = [0.16429e-01,0.17775e-01,0.19238e-01,0.20907e-01,0.22847e-01]\n kb[:,31-12, 9] = [0.15094e-01,0.16450e-01,0.17992e-01,0.19741e-01,0.21608e-01]\n kb[:,32-12, 9] = [0.13975e-01,0.15315e-01,0.16950e-01,0.18741e-01,0.20564e-01]\n kb[:,33-12, 9] = [0.13026e-01,0.14475e-01,0.16113e-01,0.17903e-01,0.19794e-01]\n kb[:,34-12, 9] = [0.12248e-01,0.13747e-01,0.15391e-01,0.17142e-01,0.19155e-01]\n kb[:,35-12, 9] = [0.11491e-01,0.12979e-01,0.14611e-01,0.16423e-01,0.18475e-01]\n kb[:,36-12, 9] = [0.10695e-01,0.12142e-01,0.13822e-01,0.15678e-01,0.17729e-01]\n kb[:,37-12, 9] = [0.98761e-02,0.11300e-01,0.13000e-01,0.14808e-01,0.16848e-01]\n kb[:,38-12, 9] = [0.91358e-02,0.10538e-01,0.12200e-01,0.13999e-01,0.16082e-01]\n kb[:,39-12, 9] = [0.84558e-02,0.98580e-02,0.11508e-01,0.13321e-01,0.15372e-01]\n kb[:,40-12, 9] = [0.78020e-02,0.91740e-02,0.10778e-01,0.12588e-01,0.14594e-01]\n kb[:,41-12, 9] = [0.72028e-02,0.85294e-02,0.10093e-01,0.11887e-01,0.13872e-01]\n kb[:,42-12, 9] = [0.66335e-02,0.79299e-02,0.94524e-02,0.11233e-01,0.13162e-01]\n kb[:,43-12, 9] = [0.60936e-02,0.73819e-02,0.88361e-02,0.10555e-01,0.12456e-01]\n kb[:,44-12, 9] = [0.55851e-02,0.68018e-02,0.82487e-02,0.98836e-02,0.11744e-01]\n kb[:,45-12, 9] = [0.51361e-02,0.62783e-02,0.76910e-02,0.92631e-02,0.11096e-01]\n kb[:,46-12, 9] = [0.46789e-02,0.57877e-02,0.71257e-02,0.86688e-02,0.10399e-01]\n kb[:,47-12, 9] = [0.42434e-02,0.53043e-02,0.65448e-02,0.80300e-02,0.97286e-02]\n kb[:,48-12, 9] = [0.38917e-02,0.48269e-02,0.60283e-02,0.74378e-02,0.90783e-02]\n kb[:,49-12, 9] = [0.35823e-02,0.43988e-02,0.55409e-02,0.68845e-02,0.84495e-02]\n kb[:,50-12, 9] = [0.33116e-02,0.40852e-02,0.51044e-02,0.63885e-02,0.78773e-02]\n kb[:,51-12, 9] = [0.30752e-02,0.38103e-02,0.47346e-02,0.59580e-02,0.73779e-02]\n kb[:,52-12, 9] = [0.28626e-02,0.35553e-02,0.44430e-02,0.55409e-02,0.69343e-02]\n kb[:,53-12, 9] = [0.26485e-02,0.33392e-02,0.41695e-02,0.51739e-02,0.64753e-02]\n kb[:,54-12, 9] = [0.24736e-02,0.31489e-02,0.39367e-02,0.48954e-02,0.61401e-02]\n kb[:,55-12, 9] = [0.23362e-02,0.29819e-02,0.37593e-02,0.46985e-02,0.58363e-02]\n kb[:,56-12, 9] = [0.22243e-02,0.28447e-02,0.35827e-02,0.44762e-02,0.55720e-02]\n kb[:,57-12, 9] = [0.21389e-02,0.27081e-02,0.34315e-02,0.43182e-02,0.53898e-02]\n kb[:,58-12, 9] = [0.20428e-02,0.25997e-02,0.33047e-02,0.41726e-02,0.52071e-02]\n kb[:,59-12, 9] = [0.20538e-02,0.26323e-02,0.33247e-02,0.41770e-02,0.52496e-02]\n kb[:,13-12,10] = [0.58637e+00,0.59481e+00,0.59811e+00,0.60451e+00,0.60418e+00]\n kb[:,14-12,10] = [0.53191e+00,0.53363e+00,0.53861e+00,0.53976e+00,0.53933e+00]\n kb[:,15-12,10] = [0.47845e+00,0.48447e+00,0.48498e+00,0.48691e+00,0.48935e+00]\n kb[:,16-12,10] = [0.42695e+00,0.43265e+00,0.43442e+00,0.43949e+00,0.44244e+00]\n kb[:,17-12,10] = [0.37796e+00,0.38437e+00,0.38958e+00,0.39367e+00,0.39802e+00]\n kb[:,18-12,10] = [0.33399e+00,0.33971e+00,0.34517e+00,0.35032e+00,0.35265e+00]\n kb[:,19-12,10] = [0.29538e+00,0.30247e+00,0.30713e+00,0.30943e+00,0.31544e+00]\n kb[:,20-12,10] = [0.26154e+00,0.26955e+00,0.27264e+00,0.27778e+00,0.28167e+00]\n kb[:,21-12,10] = [0.23200e+00,0.23896e+00,0.24468e+00,0.24838e+00,0.25453e+00]\n kb[:,22-12,10] = [0.20714e+00,0.21368e+00,0.21959e+00,0.22402e+00,0.22934e+00]\n kb[:,23-12,10] = [0.18514e+00,0.19070e+00,0.19771e+00,0.20426e+00,0.20794e+00]\n kb[:,24-12,10] = [0.16629e+00,0.17247e+00,0.17943e+00,0.18543e+00,0.19044e+00]\n kb[:,25-12,10] = [0.15103e+00,0.15758e+00,0.16440e+00,0.16947e+00,0.17504e+00]\n kb[:,26-12,10] = [0.13782e+00,0.14448e+00,0.15050e+00,0.15723e+00,0.16403e+00]\n kb[:,27-12,10] = [0.12675e+00,0.13284e+00,0.13902e+00,0.14547e+00,0.15299e+00]\n kb[:,28-12,10] = [0.11700e+00,0.12400e+00,0.13029e+00,0.13779e+00,0.14535e+00]\n kb[:,29-12,10] = [0.10975e+00,0.11580e+00,0.12300e+00,0.13106e+00,0.13981e+00]\n kb[:,30-12,10] = [0.10326e+00,0.10877e+00,0.11694e+00,0.12523e+00,0.13409e+00]\n kb[:,31-12,10] = [0.97072e-01,0.10392e+00,0.11191e+00,0.12092e+00,0.13156e+00]\n kb[:,32-12,10] = [0.92483e-01,0.10003e+00,0.10847e+00,0.11777e+00,0.12978e+00]\n kb[:,33-12,10] = [0.89436e-01,0.96549e-01,0.10550e+00,0.11582e+00,0.12938e+00]\n kb[:,34-12,10] = [0.86605e-01,0.93852e-01,0.10437e+00,0.11565e+00,0.13025e+00]\n kb[:,35-12,10] = [0.83755e-01,0.92443e-01,0.10318e+00,0.11569e+00,0.13035e+00]\n kb[:,36-12,10] = [0.80159e-01,0.90106e-01,0.10185e+00,0.11331e+00,0.13105e+00]\n kb[:,37-12,10] = [0.76863e-01,0.86981e-01,0.98816e-01,0.11094e+00,0.12837e+00]\n kb[:,38-12,10] = [0.73911e-01,0.84640e-01,0.95988e-01,0.10951e+00,0.12524e+00]\n kb[:,39-12,10] = [0.71484e-01,0.82465e-01,0.93807e-01,0.10732e+00,0.12288e+00]\n kb[:,40-12,10] = [0.68367e-01,0.78553e-01,0.90288e-01,0.10290e+00,0.11884e+00]\n kb[:,41-12,10] = [0.65972e-01,0.75367e-01,0.87331e-01,0.98979e-01,0.11479e+00]\n kb[:,42-12,10] = [0.63899e-01,0.72995e-01,0.84392e-01,0.96170e-01,0.11066e+00]\n kb[:,43-12,10] = [0.61601e-01,0.69361e-01,0.80265e-01,0.92296e-01,0.10575e+00]\n kb[:,44-12,10] = [0.58053e-01,0.67236e-01,0.77057e-01,0.88848e-01,0.10118e+00]\n kb[:,45-12,10] = [0.55041e-01,0.64788e-01,0.73479e-01,0.85189e-01,0.97294e-01]\n kb[:,46-12,10] = [0.51538e-01,0.61359e-01,0.70493e-01,0.81342e-01,0.93711e-01]\n kb[:,47-12,10] = [0.48229e-01,0.57754e-01,0.67703e-01,0.77712e-01,0.88779e-01]\n kb[:,48-12,10] = [0.44328e-01,0.53953e-01,0.64327e-01,0.74186e-01,0.85354e-01]\n kb[:,49-12,10] = [0.40181e-01,0.50939e-01,0.60544e-01,0.71079e-01,0.81883e-01]\n kb[:,50-12,10] = [0.36327e-01,0.47243e-01,0.57625e-01,0.67925e-01,0.78806e-01]\n kb[:,51-12,10] = [0.33026e-01,0.43278e-01,0.54464e-01,0.64411e-01,0.75916e-01]\n kb[:,52-12,10] = [0.29600e-01,0.39888e-01,0.50913e-01,0.61457e-01,0.72719e-01]\n kb[:,53-12,10] = [0.26994e-01,0.36264e-01,0.46926e-01,0.58631e-01,0.68972e-01]\n kb[:,54-12,10] = [0.24928e-01,0.33245e-01,0.43870e-01,0.55481e-01,0.66121e-01]\n kb[:,55-12,10] = [0.23329e-01,0.30647e-01,0.40729e-01,0.52051e-01,0.63960e-01]\n kb[:,56-12,10] = [0.21581e-01,0.28578e-01,0.37651e-01,0.48828e-01,0.60673e-01]\n kb[:,57-12,10] = [0.20121e-01,0.27060e-01,0.35152e-01,0.45854e-01,0.57152e-01]\n kb[:,58-12,10] = [0.18692e-01,0.25639e-01,0.32995e-01,0.42657e-01,0.54655e-01]\n kb[:,59-12,10] = [0.18277e-01,0.25273e-01,0.32791e-01,0.42508e-01,0.53680e-01]\n kb[:,13-12,11] = [0.10693e+01,0.10902e+01,0.11032e+01,0.10991e+01,0.11118e+01]\n kb[:,14-12,11] = [0.95953e+00,0.97384e+00,0.98577e+00,0.99728e+00,0.10070e+01]\n kb[:,15-12,11] = [0.85940e+00,0.86781e+00,0.87766e+00,0.88834e+00,0.89855e+00]\n kb[:,16-12,11] = [0.76187e+00,0.76651e+00,0.78116e+00,0.79605e+00,0.80429e+00]\n kb[:,17-12,11] = [0.67627e+00,0.68377e+00,0.69734e+00,0.70867e+00,0.71758e+00]\n kb[:,18-12,11] = [0.60442e+00,0.61462e+00,0.62319e+00,0.63477e+00,0.64696e+00]\n kb[:,19-12,11] = [0.54250e+00,0.55180e+00,0.56132e+00,0.57649e+00,0.58604e+00]\n kb[:,20-12,11] = [0.49000e+00,0.49922e+00,0.51229e+00,0.52536e+00,0.53903e+00]\n kb[:,21-12,11] = [0.44362e+00,0.45018e+00,0.46523e+00,0.48212e+00,0.49590e+00]\n kb[:,22-12,11] = [0.40390e+00,0.41136e+00,0.42554e+00,0.44299e+00,0.45956e+00]\n kb[:,23-12,11] = [0.36600e+00,0.37646e+00,0.39144e+00,0.40936e+00,0.42622e+00]\n kb[:,24-12,11] = [0.33488e+00,0.34802e+00,0.36259e+00,0.38089e+00,0.39832e+00]\n kb[:,25-12,11] = [0.30569e+00,0.32099e+00,0.33730e+00,0.35716e+00,0.37447e+00]\n kb[:,26-12,11] = [0.28345e+00,0.29933e+00,0.31861e+00,0.33716e+00,0.35400e+00]\n kb[:,27-12,11] = [0.26524e+00,0.28116e+00,0.30310e+00,0.32398e+00,0.34341e+00]\n kb[:,28-12,11] = [0.25036e+00,0.26748e+00,0.29040e+00,0.31038e+00,0.33527e+00]\n kb[:,29-12,11] = [0.23678e+00,0.25759e+00,0.27958e+00,0.30373e+00,0.33097e+00]\n kb[:,30-12,11] = [0.22835e+00,0.25043e+00,0.27298e+00,0.30247e+00,0.33069e+00]\n kb[:,31-12,11] = [0.22381e+00,0.24448e+00,0.27386e+00,0.30198e+00,0.33135e+00]\n kb[:,32-12,11] = [0.21945e+00,0.24581e+00,0.27557e+00,0.30488e+00,0.33817e+00]\n kb[:,33-12,11] = [0.22020e+00,0.24997e+00,0.27933e+00,0.31199e+00,0.34537e+00]\n kb[:,34-12,11] = [0.22328e+00,0.25315e+00,0.28560e+00,0.31999e+00,0.35204e+00]\n kb[:,35-12,11] = [0.22463e+00,0.25599e+00,0.29016e+00,0.32472e+00,0.35705e+00]\n kb[:,36-12,11] = [0.22454e+00,0.25719e+00,0.29064e+00,0.32676e+00,0.35643e+00]\n kb[:,37-12,11] = [0.21917e+00,0.25146e+00,0.28533e+00,0.32018e+00,0.35207e+00]\n kb[:,38-12,11] = [0.21431e+00,0.24593e+00,0.28070e+00,0.31440e+00,0.34740e+00]\n kb[:,39-12,11] = [0.20995e+00,0.24107e+00,0.27540e+00,0.30795e+00,0.34247e+00]\n kb[:,40-12,11] = [0.20148e+00,0.23319e+00,0.26577e+00,0.30086e+00,0.33366e+00]\n kb[:,41-12,11] = [0.19132e+00,0.22478e+00,0.25632e+00,0.29251e+00,0.32436e+00]\n kb[:,42-12,11] = [0.18231e+00,0.21584e+00,0.24724e+00,0.28164e+00,0.31641e+00]\n kb[:,43-12,11] = [0.17273e+00,0.20475e+00,0.23702e+00,0.26984e+00,0.30535e+00]\n kb[:,44-12,11] = [0.16365e+00,0.19313e+00,0.22566e+00,0.25812e+00,0.29340e+00]\n kb[:,45-12,11] = [0.15471e+00,0.18278e+00,0.21464e+00,0.24686e+00,0.28060e+00]\n kb[:,46-12,11] = [0.14477e+00,0.17256e+00,0.20328e+00,0.23515e+00,0.26753e+00]\n kb[:,47-12,11] = [0.13513e+00,0.16209e+00,0.19092e+00,0.22162e+00,0.25481e+00]\n kb[:,48-12,11] = [0.12632e+00,0.15056e+00,0.17900e+00,0.20905e+00,0.24085e+00]\n kb[:,49-12,11] = [0.11846e+00,0.14059e+00,0.16812e+00,0.19759e+00,0.22701e+00]\n kb[:,50-12,11] = [0.11278e+00,0.13341e+00,0.15756e+00,0.18662e+00,0.21629e+00]\n kb[:,51-12,11] = [0.10711e+00,0.12752e+00,0.14951e+00,0.17651e+00,0.20555e+00]\n kb[:,52-12,11] = [0.10062e+00,0.12140e+00,0.14273e+00,0.16677e+00,0.19594e+00]\n kb[:,53-12,11] = [0.93686e-01,0.11587e+00,0.13705e+00,0.15900e+00,0.18673e+00]\n kb[:,54-12,11] = [0.88183e-01,0.10986e+00,0.13159e+00,0.15362e+00,0.17808e+00]\n kb[:,55-12,11] = [0.81924e-01,0.10428e+00,0.12662e+00,0.14862e+00,0.17143e+00]\n kb[:,56-12,11] = [0.75991e-01,0.98633e-01,0.12219e+00,0.14408e+00,0.16698e+00]\n kb[:,57-12,11] = [0.69399e-01,0.92760e-01,0.11664e+00,0.14040e+00,0.16308e+00]\n kb[:,58-12,11] = [0.64018e-01,0.88343e-01,0.11169e+00,0.13686e+00,0.15969e+00]\n kb[:,59-12,11] = [0.63145e-01,0.86273e-01,0.11143e+00,0.13565e+00,0.16187e+00]\n kb[:,13-12,12] = [0.22241e+01,0.22556e+01,0.22932e+01,0.23316e+01,0.23817e+01]\n kb[:,14-12,12] = [0.20015e+01,0.20535e+01,0.20976e+01,0.21411e+01,0.21895e+01]\n kb[:,15-12,12] = [0.18111e+01,0.18671e+01,0.19196e+01,0.19734e+01,0.20226e+01]\n kb[:,16-12,12] = [0.16513e+01,0.17114e+01,0.17632e+01,0.18132e+01,0.18623e+01]\n kb[:,17-12,12] = [0.15041e+01,0.15648e+01,0.16197e+01,0.16720e+01,0.17169e+01]\n kb[:,18-12,12] = [0.13731e+01,0.14345e+01,0.14937e+01,0.15386e+01,0.16052e+01]\n kb[:,19-12,12] = [0.12478e+01,0.13115e+01,0.13641e+01,0.14279e+01,0.14977e+01]\n kb[:,20-12,12] = [0.11298e+01,0.11910e+01,0.12495e+01,0.13186e+01,0.13914e+01]\n kb[:,21-12,12] = [0.10266e+01,0.10915e+01,0.11508e+01,0.12227e+01,0.13004e+01]\n kb[:,22-12,12] = [0.93959e+00,0.10027e+01,0.10735e+01,0.11507e+01,0.12312e+01]\n kb[:,23-12,12] = [0.87016e+00,0.93486e+00,0.10125e+01,0.10930e+01,0.11794e+01]\n kb[:,24-12,12] = [0.81213e+00,0.88017e+00,0.96483e+00,0.10508e+01,0.11396e+01]\n kb[:,25-12,12] = [0.77134e+00,0.84295e+00,0.93081e+00,0.10201e+01,0.11152e+01]\n kb[:,26-12,12] = [0.73832e+00,0.81743e+00,0.90746e+00,0.10024e+01,0.11020e+01]\n kb[:,27-12,12] = [0.71831e+00,0.80328e+00,0.89505e+00,0.99247e+00,0.10943e+01]\n kb[:,28-12,12] = [0.70848e+00,0.79592e+00,0.89143e+00,0.99432e+00,0.10940e+01]\n kb[:,29-12,12] = [0.70725e+00,0.79781e+00,0.89906e+00,0.10007e+01,0.11009e+01]\n kb[:,30-12,12] = [0.71125e+00,0.80824e+00,0.91144e+00,0.10109e+01,0.11144e+01]\n kb[:,31-12,12] = [0.72057e+00,0.82548e+00,0.92423e+00,0.10285e+01,0.11338e+01]\n kb[:,32-12,12] = [0.73855e+00,0.84223e+00,0.94322e+00,0.10495e+01,0.11523e+01]\n kb[:,33-12,12] = [0.75860e+00,0.86137e+00,0.96653e+00,0.10709e+01,0.11736e+01]\n kb[:,34-12,12] = [0.77584e+00,0.88104e+00,0.98358e+00,0.10881e+01,0.11928e+01]\n kb[:,35-12,12] = [0.78526e+00,0.88915e+00,0.99181e+00,0.10955e+01,0.12024e+01]\n kb[:,36-12,12] = [0.78420e+00,0.88679e+00,0.98962e+00,0.10938e+01,0.12013e+01]\n kb[:,37-12,12] = [0.76619e+00,0.86975e+00,0.97162e+00,0.10774e+01,0.11823e+01]\n kb[:,38-12,12] = [0.74778e+00,0.85168e+00,0.95355e+00,0.10588e+01,0.11642e+01]\n kb[:,39-12,12] = [0.73003e+00,0.83397e+00,0.93638e+00,0.10427e+01,0.11461e+01]\n kb[:,40-12,12] = [0.70694e+00,0.80603e+00,0.90951e+00,0.10129e+01,0.11179e+01]\n kb[:,41-12,12] = [0.68380e+00,0.77629e+00,0.88021e+00,0.98263e+00,0.10876e+01]\n kb[:,42-12,12] = [0.66231e+00,0.74849e+00,0.85130e+00,0.95458e+00,0.10576e+01]\n kb[:,43-12,12] = [0.63688e+00,0.72048e+00,0.81634e+00,0.92017e+00,0.10227e+01]\n kb[:,44-12,12] = [0.60858e+00,0.69178e+00,0.77940e+00,0.88149e+00,0.98460e+00]\n kb[:,45-12,12] = [0.58153e+00,0.66520e+00,0.74925e+00,0.84319e+00,0.94694e+00]\n kb[:,46-12,12] = [0.55197e+00,0.63412e+00,0.71872e+00,0.80664e+00,0.90684e+00]\n kb[:,47-12,12] = [0.51844e+00,0.60273e+00,0.68769e+00,0.77076e+00,0.86117e+00]\n kb[:,48-12,12] = [0.48120e+00,0.57148e+00,0.65491e+00,0.74197e+00,0.82485e+00]\n kb[:,49-12,12] = [0.44584e+00,0.53846e+00,0.62079e+00,0.70603e+00,0.79220e+00]\n kb[:,50-12,12] = [0.41289e+00,0.50133e+00,0.59314e+00,0.67773e+00,0.76297e+00]\n kb[:,51-12,12] = [0.38263e+00,0.46808e+00,0.55994e+00,0.64654e+00,0.73545e+00]\n kb[:,52-12,12] = [0.35216e+00,0.43713e+00,0.52781e+00,0.61897e+00,0.70212e+00]\n kb[:,53-12,12] = [0.33102e+00,0.40477e+00,0.49059e+00,0.58472e+00,0.67270e+00]\n kb[:,54-12,12] = [0.31146e+00,0.37834e+00,0.46271e+00,0.55353e+00,0.64596e+00]\n kb[:,55-12,12] = [0.29087e+00,0.35982e+00,0.43598e+00,0.52416e+00,0.61765e+00]\n kb[:,56-12,12] = [0.27304e+00,0.34098e+00,0.41224e+00,0.49775e+00,0.58771e+00]\n kb[:,57-12,12] = [0.25824e+00,0.32066e+00,0.39085e+00,0.46641e+00,0.55829e+00]\n kb[:,58-12,12] = [0.24548e+00,0.30081e+00,0.37338e+00,0.44708e+00,0.53062e+00]\n kb[:,59-12,12] = [0.24212e+00,0.29858e+00,0.36550e+00,0.44064e+00,0.51789e+00]\n kb[:,13-12,13] = [0.55998e+01,0.57039e+01,0.58049e+01,0.59180e+01,0.59854e+01]\n kb[:,14-12,13] = [0.53275e+01,0.54387e+01,0.55543e+01,0.56621e+01,0.57635e+01]\n kb[:,15-12,13] = [0.50203e+01,0.51578e+01,0.52898e+01,0.54130e+01,0.55373e+01]\n kb[:,16-12,13] = [0.47246e+01,0.48786e+01,0.50266e+01,0.51689e+01,0.53242e+01]\n kb[:,17-12,13] = [0.44403e+01,0.46027e+01,0.47680e+01,0.49455e+01,0.51299e+01]\n kb[:,18-12,13] = [0.41648e+01,0.43473e+01,0.45415e+01,0.47508e+01,0.49298e+01]\n kb[:,19-12,13] = [0.39134e+01,0.41196e+01,0.43493e+01,0.45520e+01,0.47522e+01]\n kb[:,20-12,13] = [0.36873e+01,0.39195e+01,0.41603e+01,0.43826e+01,0.46005e+01]\n kb[:,21-12,13] = [0.34974e+01,0.37507e+01,0.40010e+01,0.42413e+01,0.44759e+01]\n kb[:,22-12,13] = [0.33605e+01,0.36305e+01,0.38873e+01,0.41404e+01,0.43929e+01]\n kb[:,23-12,13] = [0.32571e+01,0.35388e+01,0.38042e+01,0.40702e+01,0.43353e+01]\n kb[:,24-12,13] = [0.31836e+01,0.34721e+01,0.37495e+01,0.40277e+01,0.43044e+01]\n kb[:,25-12,13] = [0.31346e+01,0.34329e+01,0.37222e+01,0.40107e+01,0.42953e+01]\n kb[:,26-12,13] = [0.31155e+01,0.34221e+01,0.37222e+01,0.40178e+01,0.43079e+01]\n kb[:,27-12,13] = [0.31157e+01,0.34328e+01,0.37392e+01,0.40396e+01,0.43346e+01]\n kb[:,28-12,13] = [0.31335e+01,0.34580e+01,0.37695e+01,0.40734e+01,0.43720e+01]\n kb[:,29-12,13] = [0.31697e+01,0.34978e+01,0.38120e+01,0.41186e+01,0.44189e+01]\n kb[:,30-12,13] = [0.32194e+01,0.35475e+01,0.38638e+01,0.41720e+01,0.44722e+01]\n kb[:,31-12,13] = [0.32811e+01,0.36069e+01,0.39241e+01,0.42325e+01,0.45314e+01]\n kb[:,32-12,13] = [0.33484e+01,0.36727e+01,0.39897e+01,0.42974e+01,0.45949e+01]\n kb[:,33-12,13] = [0.34186e+01,0.37430e+01,0.40586e+01,0.43658e+01,0.46602e+01]\n kb[:,34-12,13] = [0.34801e+01,0.38048e+01,0.41197e+01,0.44255e+01,0.47156e+01]\n kb[:,35-12,13] = [0.35126e+01,0.38375e+01,0.41525e+01,0.44577e+01,0.47454e+01]\n kb[:,36-12,13] = [0.35115e+01,0.38370e+01,0.41529e+01,0.44584e+01,0.47449e+01]\n kb[:,37-12,13] = [0.34620e+01,0.37892e+01,0.41066e+01,0.44144e+01,0.47052e+01]\n kb[:,38-12,13] = [0.34108e+01,0.37391e+01,0.40587e+01,0.43685e+01,0.46624e+01]\n kb[:,39-12,13] = [0.33603e+01,0.36896e+01,0.40114e+01,0.43229e+01,0.46208e+01]\n kb[:,40-12,13] = [0.32696e+01,0.36068e+01,0.39317e+01,0.42460e+01,0.45479e+01]\n kb[:,41-12,13] = [0.31746e+01,0.35197e+01,0.38475e+01,0.41644e+01,0.44716e+01]\n kb[:,42-12,13] = [0.30768e+01,0.34312e+01,0.37630e+01,0.40826e+01,0.43924e+01]\n kb[:,43-12,13] = [0.29558e+01,0.33178e+01,0.36587e+01,0.39822e+01,0.42959e+01]\n kb[:,44-12,13] = [0.28280e+01,0.31906e+01,0.35435e+01,0.38727e+01,0.41899e+01]\n kb[:,45-12,13] = [0.26988e+01,0.30597e+01,0.34201e+01,0.37628e+01,0.40831e+01]\n kb[:,46-12,13] = [0.25661e+01,0.29262e+01,0.32865e+01,0.36383e+01,0.39682e+01]\n kb[:,47-12,13] = [0.24176e+01,0.27716e+01,0.31308e+01,0.34925e+01,0.38381e+01]\n kb[:,48-12,13] = [0.22754e+01,0.26218e+01,0.29793e+01,0.33363e+01,0.36948e+01]\n kb[:,49-12,13] = [0.21329e+01,0.24724e+01,0.28302e+01,0.31874e+01,0.35454e+01]\n kb[:,50-12,13] = [0.20005e+01,0.23398e+01,0.26856e+01,0.30422e+01,0.34002e+01]\n kb[:,51-12,13] = [0.18713e+01,0.22087e+01,0.25515e+01,0.29067e+01,0.32588e+01]\n kb[:,52-12,13] = [0.17459e+01,0.20772e+01,0.24169e+01,0.27666e+01,0.31241e+01]\n kb[:,53-12,13] = [0.16095e+01,0.19502e+01,0.22895e+01,0.26325e+01,0.29855e+01]\n kb[:,54-12,13] = [0.15066e+01,0.18320e+01,0.21659e+01,0.25081e+01,0.28569e+01]\n kb[:,55-12,13] = [0.14318e+01,0.17117e+01,0.20491e+01,0.23896e+01,0.27343e+01]\n kb[:,56-12,13] = [0.13449e+01,0.16235e+01,0.19309e+01,0.22682e+01,0.26139e+01]\n kb[:,57-12,13] = [0.12667e+01,0.15514e+01,0.18274e+01,0.21528e+01,0.24919e+01]\n kb[:,58-12,13] = [0.11763e+01,0.14696e+01,0.17445e+01,0.20345e+01,0.23757e+01]\n kb[:,59-12,13] = [0.11472e+01,0.14428e+01,0.17312e+01,0.20031e+01,0.23234e+01]\n kb[:,13-12,14] = [0.15147e+02,0.15130e+02,0.15113e+02,0.15099e+02,0.15078e+02]\n kb[:,14-12,14] = [0.15510e+02,0.15546e+02,0.15567e+02,0.15587e+02,0.15585e+02]\n kb[:,15-12,14] = [0.15739e+02,0.15841e+02,0.15930e+02,0.15986e+02,0.16004e+02]\n kb[:,16-12,14] = [0.15858e+02,0.16042e+02,0.16196e+02,0.16295e+02,0.16347e+02]\n kb[:,17-12,14] = [0.15892e+02,0.16168e+02,0.16375e+02,0.16519e+02,0.16620e+02]\n kb[:,18-12,14] = [0.15890e+02,0.16233e+02,0.16495e+02,0.16687e+02,0.16843e+02]\n kb[:,19-12,14] = [0.15860e+02,0.16260e+02,0.16572e+02,0.16822e+02,0.17016e+02]\n kb[:,20-12,14] = [0.15821e+02,0.16274e+02,0.16642e+02,0.16937e+02,0.17165e+02]\n kb[:,21-12,14] = [0.15778e+02,0.16284e+02,0.16705e+02,0.17036e+02,0.17293e+02]\n kb[:,22-12,14] = [0.15777e+02,0.16337e+02,0.16794e+02,0.17151e+02,0.17417e+02]\n kb[:,23-12,14] = [0.15815e+02,0.16408e+02,0.16883e+02,0.17258e+02,0.17537e+02]\n kb[:,24-12,14] = [0.15884e+02,0.16493e+02,0.16982e+02,0.17365e+02,0.17648e+02]\n kb[:,25-12,14] = [0.15973e+02,0.16594e+02,0.17087e+02,0.17470e+02,0.17753e+02]\n kb[:,26-12,14] = [0.16098e+02,0.16711e+02,0.17198e+02,0.17574e+02,0.17853e+02]\n kb[:,27-12,14] = [0.16232e+02,0.16836e+02,0.17310e+02,0.17676e+02,0.17946e+02]\n kb[:,28-12,14] = [0.16376e+02,0.16966e+02,0.17425e+02,0.17775e+02,0.18032e+02]\n kb[:,29-12,14] = [0.16527e+02,0.17096e+02,0.17538e+02,0.17871e+02,0.18111e+02]\n kb[:,30-12,14] = [0.16681e+02,0.17223e+02,0.17646e+02,0.17959e+02,0.18183e+02]\n kb[:,31-12,14] = [0.16832e+02,0.17348e+02,0.17747e+02,0.18041e+02,0.18247e+02]\n kb[:,32-12,14] = [0.16982e+02,0.17470e+02,0.17844e+02,0.18116e+02,0.18304e+02]\n kb[:,33-12,14] = [0.17125e+02,0.17586e+02,0.17935e+02,0.18187e+02,0.18356e+02]\n kb[:,34-12,14] = [0.17243e+02,0.17681e+02,0.18009e+02,0.18243e+02,0.18396e+02]\n kb[:,35-12,14] = [0.17308e+02,0.17736e+02,0.18053e+02,0.18277e+02,0.18422e+02]\n kb[:,36-12,14] = [0.17321e+02,0.17747e+02,0.18064e+02,0.18289e+02,0.18431e+02]\n kb[:,37-12,14] = [0.17259e+02,0.17701e+02,0.18033e+02,0.18270e+02,0.18425e+02]\n kb[:,38-12,14] = [0.17190e+02,0.17649e+02,0.17997e+02,0.18247e+02,0.18415e+02]\n kb[:,39-12,14] = [0.17116e+02,0.17594e+02,0.17957e+02,0.18221e+02,0.18401e+02]\n kb[:,40-12,14] = [0.16981e+02,0.17491e+02,0.17882e+02,0.18168e+02,0.18367e+02]\n kb[:,41-12,14] = [0.16829e+02,0.17375e+02,0.17795e+02,0.18107e+02,0.18328e+02]\n kb[:,42-12,14] = [0.16667e+02,0.17250e+02,0.17700e+02,0.18038e+02,0.18281e+02]\n kb[:,43-12,14] = [0.16452e+02,0.17082e+02,0.17573e+02,0.17944e+02,0.18214e+02]\n kb[:,44-12,14] = [0.16203e+02,0.16887e+02,0.17421e+02,0.17833e+02,0.18135e+02]\n kb[:,45-12,14] = [0.15935e+02,0.16673e+02,0.17257e+02,0.17708e+02,0.18046e+02]\n kb[:,46-12,14] = [0.15628e+02,0.16427e+02,0.17064e+02,0.17560e+02,0.17936e+02]\n kb[:,47-12,14] = [0.15258e+02,0.16126e+02,0.16827e+02,0.17377e+02,0.17799e+02]\n kb[:,48-12,14] = [0.14864e+02,0.15798e+02,0.16564e+02,0.17174e+02,0.17643e+02]\n kb[:,49-12,14] = [0.14439e+02,0.15441e+02,0.16276e+02,0.16946e+02,0.17469e+02]\n kb[:,50-12,14] = [0.14012e+02,0.15084e+02,0.15980e+02,0.16711e+02,0.17289e+02]\n kb[:,51-12,14] = [0.13576e+02,0.14715e+02,0.15671e+02,0.16463e+02,0.17096e+02]\n kb[:,52-12,14] = [0.13120e+02,0.14320e+02,0.15341e+02,0.16194e+02,0.16882e+02]\n kb[:,53-12,14] = [0.12642e+02,0.13899e+02,0.14988e+02,0.15902e+02,0.16649e+02]\n kb[:,54-12,14] = [0.12147e+02,0.13496e+02,0.14645e+02,0.15614e+02,0.16418e+02]\n kb[:,55-12,14] = [0.11626e+02,0.13090e+02,0.14295e+02,0.15320e+02,0.16178e+02]\n kb[:,56-12,14] = [0.11110e+02,0.12619e+02,0.13926e+02,0.15012e+02,0.15922e+02]\n kb[:,57-12,14] = [0.10565e+02,0.12110e+02,0.13518e+02,0.14685e+02,0.15649e+02]\n kb[:,58-12,14] = [0.10061e+02,0.11633e+02,0.13084e+02,0.14356e+02,0.15374e+02]\n kb[:,59-12,14] = [0.98377e+01,0.11416e+02,0.12868e+02,0.14184e+02,0.15259e+02]\n kb[:,13-12,15] = [0.41304e+02,0.40483e+02,0.39654e+02,0.38829e+02,0.38029e+02]\n kb[:,14-12,15] = [0.44686e+02,0.43762e+02,0.42836e+02,0.41888e+02,0.41004e+02]\n kb[:,15-12,15] = [0.48004e+02,0.46942e+02,0.45864e+02,0.44813e+02,0.43844e+02]\n kb[:,16-12,15] = [0.51150e+02,0.49938e+02,0.48734e+02,0.47591e+02,0.46512e+02]\n kb[:,17-12,15] = [0.54100e+02,0.52729e+02,0.51435e+02,0.50180e+02,0.48962e+02]\n kb[:,18-12,15] = [0.56777e+02,0.55306e+02,0.53894e+02,0.52525e+02,0.51164e+02]\n kb[:,19-12,15] = [0.59186e+02,0.57635e+02,0.56100e+02,0.54603e+02,0.53129e+02]\n kb[:,20-12,15] = [0.61293e+02,0.59648e+02,0.58005e+02,0.56388e+02,0.54798e+02]\n kb[:,21-12,15] = [0.63124e+02,0.61368e+02,0.59613e+02,0.57895e+02,0.56204e+02]\n kb[:,22-12,15] = [0.64562e+02,0.62695e+02,0.60841e+02,0.59040e+02,0.57268e+02]\n kb[:,23-12,15] = [0.65690e+02,0.63742e+02,0.61820e+02,0.59937e+02,0.58087e+02]\n kb[:,24-12,15] = [0.66548e+02,0.64535e+02,0.62550e+02,0.60597e+02,0.58690e+02]\n kb[:,25-12,15] = [0.67194e+02,0.65115e+02,0.63062e+02,0.61050e+02,0.59091e+02]\n kb[:,26-12,15] = [0.67597e+02,0.65466e+02,0.63369e+02,0.61312e+02,0.59309e+02]\n kb[:,27-12,15] = [0.67831e+02,0.65647e+02,0.63518e+02,0.61430e+02,0.59393e+02]\n kb[:,28-12,15] = [0.67908e+02,0.65687e+02,0.63527e+02,0.61427e+02,0.59357e+02]\n kb[:,29-12,15] = [0.67845e+02,0.65603e+02,0.63419e+02,0.61304e+02,0.59222e+02]\n kb[:,30-12,15] = [0.67682e+02,0.65422e+02,0.63225e+02,0.61094e+02,0.59010e+02]\n kb[:,31-12,15] = [0.67415e+02,0.65154e+02,0.62953e+02,0.60816e+02,0.58721e+02]\n kb[:,32-12,15] = [0.67084e+02,0.64817e+02,0.62622e+02,0.60477e+02,0.58393e+02]\n kb[:,33-12,15] = [0.66692e+02,0.64428e+02,0.62242e+02,0.60092e+02,0.58024e+02]\n kb[:,34-12,15] = [0.66346e+02,0.64077e+02,0.61890e+02,0.59745e+02,0.57700e+02]\n kb[:,35-12,15] = [0.66188e+02,0.63920e+02,0.61727e+02,0.59582e+02,0.57542e+02]\n kb[:,36-12,15] = [0.66248e+02,0.63978e+02,0.61782e+02,0.59625e+02,0.57587e+02]\n kb[:,37-12,15] = [0.66642e+02,0.64358e+02,0.62144e+02,0.59978e+02,0.57911e+02]\n kb[:,38-12,15] = [0.67048e+02,0.64747e+02,0.62516e+02,0.60340e+02,0.58249e+02]\n kb[:,39-12,15] = [0.67435e+02,0.65122e+02,0.62879e+02,0.60689e+02,0.58578e+02]\n kb[:,40-12,15] = [0.68061e+02,0.65724e+02,0.63462e+02,0.61257e+02,0.59113e+02]\n kb[:,41-12,15] = [0.68702e+02,0.66354e+02,0.64067e+02,0.61847e+02,0.59682e+02]\n kb[:,42-12,15] = [0.69355e+02,0.66983e+02,0.64678e+02,0.62437e+02,0.60259e+02]\n kb[:,43-12,15] = [0.70142e+02,0.67744e+02,0.65416e+02,0.63159e+02,0.60959e+02]\n kb[:,44-12,15] = [0.70991e+02,0.68567e+02,0.66218e+02,0.63930e+02,0.61713e+02]\n kb[:,45-12,15] = [0.71837e+02,0.69401e+02,0.67026e+02,0.64713e+02,0.62473e+02]\n kb[:,46-12,15] = [0.72733e+02,0.70287e+02,0.67885e+02,0.65552e+02,0.63292e+02]\n kb[:,47-12,15] = [0.73741e+02,0.71285e+02,0.68859e+02,0.66493e+02,0.64198e+02]\n kb[:,48-12,15] = [0.74725e+02,0.72283e+02,0.69840e+02,0.67442e+02,0.65125e+02]\n kb[:,49-12,15] = [0.75665e+02,0.73280e+02,0.70828e+02,0.68404e+02,0.66060e+02]\n kb[:,50-12,15] = [0.76534e+02,0.74218e+02,0.71764e+02,0.69323e+02,0.66942e+02]\n kb[:,51-12,15] = [0.77333e+02,0.75093e+02,0.72664e+02,0.70214e+02,0.67806e+02]\n kb[:,52-12,15] = [0.78102e+02,0.75935e+02,0.73563e+02,0.71111e+02,0.68683e+02]\n kb[:,53-12,15] = [0.78815e+02,0.76761e+02,0.74462e+02,0.72010e+02,0.69568e+02]\n kb[:,54-12,15] = [0.79431e+02,0.77488e+02,0.75258e+02,0.72840e+02,0.70386e+02]\n kb[:,55-12,15] = [0.79987e+02,0.78156e+02,0.75999e+02,0.73628e+02,0.71177e+02]\n kb[:,56-12,15] = [0.80478e+02,0.78776e+02,0.76714e+02,0.74415e+02,0.71963e+02]\n kb[:,57-12,15] = [0.80898e+02,0.79365e+02,0.77410e+02,0.75181e+02,0.72750e+02]\n kb[:,58-12,15] = [0.81210e+02,0.79894e+02,0.78053e+02,0.75880e+02,0.73498e+02]\n kb[:,59-12,15] = [0.81312e+02,0.80086e+02,0.78299e+02,0.76156e+02,0.73801e+02]\n kb[:,13-12,16] = [0.81866e+02,0.78569e+02,0.75624e+02,0.72854e+02,0.70288e+02]\n kb[:,14-12,16] = [0.93095e+02,0.88986e+02,0.85351e+02,0.82051e+02,0.78936e+02]\n kb[:,15-12,16] = [0.10470e+03,0.99738e+02,0.95227e+02,0.91249e+02,0.87478e+02]\n kb[:,16-12,16] = [0.11635e+03,0.11037e+03,0.10495e+03,0.10011e+03,0.95646e+02]\n kb[:,17-12,16] = [0.12769e+03,0.12074e+03,0.11431e+03,0.10856e+03,0.10332e+03]\n kb[:,18-12,16] = [0.13851e+03,0.13038e+03,0.12299e+03,0.11635e+03,0.11033e+03]\n kb[:,19-12,16] = [0.14848e+03,0.13912e+03,0.13084e+03,0.12336e+03,0.11656e+03]\n kb[:,20-12,16] = [0.15718e+03,0.14679e+03,0.13761e+03,0.12934e+03,0.12188e+03]\n kb[:,21-12,16] = [0.16462e+03,0.15341e+03,0.14345e+03,0.13443e+03,0.12636e+03]\n kb[:,22-12,16] = [0.17012e+03,0.15822e+03,0.14760e+03,0.13801e+03,0.12950e+03]\n kb[:,23-12,16] = [0.17437e+03,0.16184e+03,0.15069e+03,0.14069e+03,0.13184e+03]\n kb[:,24-12,16] = [0.17733e+03,0.16436e+03,0.15282e+03,0.14251e+03,0.13340e+03]\n kb[:,25-12,16] = [0.17910e+03,0.16583e+03,0.15401e+03,0.14354e+03,0.13426e+03]\n kb[:,26-12,16] = [0.17968e+03,0.16627e+03,0.15433e+03,0.14378e+03,0.13445e+03]\n kb[:,27-12,16] = [0.17946e+03,0.16602e+03,0.15406e+03,0.14351e+03,0.13417e+03]\n kb[:,28-12,16] = [0.17860e+03,0.16522e+03,0.15334e+03,0.14282e+03,0.13355e+03]\n kb[:,29-12,16] = [0.17717e+03,0.16389e+03,0.15216e+03,0.14174e+03,0.13260e+03]\n kb[:,30-12,16] = [0.17533e+03,0.16225e+03,0.15066e+03,0.14043e+03,0.13143e+03]\n kb[:,31-12,16] = [0.17313e+03,0.16029e+03,0.14890e+03,0.13886e+03,0.13004e+03]\n kb[:,32-12,16] = [0.17069e+03,0.15811e+03,0.14694e+03,0.13716e+03,0.12847e+03]\n kb[:,33-12,16] = [0.16804e+03,0.15577e+03,0.14487e+03,0.13533e+03,0.12682e+03]\n kb[:,34-12,16] = [0.16580e+03,0.15376e+03,0.14309e+03,0.13376e+03,0.12539e+03]\n kb[:,35-12,16] = [0.16467e+03,0.15275e+03,0.14221e+03,0.13298e+03,0.12468e+03]\n kb[:,36-12,16] = [0.16486e+03,0.15289e+03,0.14233e+03,0.13308e+03,0.12477e+03]\n kb[:,37-12,16] = [0.16688e+03,0.15469e+03,0.14392e+03,0.13446e+03,0.12602e+03]\n kb[:,38-12,16] = [0.16902e+03,0.15657e+03,0.14555e+03,0.13592e+03,0.12732e+03]\n kb[:,39-12,16] = [0.17110e+03,0.15844e+03,0.14718e+03,0.13734e+03,0.12861e+03]\n kb[:,40-12,16] = [0.17468e+03,0.16155e+03,0.14992e+03,0.13976e+03,0.13077e+03]\n kb[:,41-12,16] = [0.17848e+03,0.16489e+03,0.15289e+03,0.14236e+03,0.13307e+03]\n kb[:,42-12,16] = [0.18237e+03,0.16833e+03,0.15592e+03,0.14501e+03,0.13541e+03]\n kb[:,43-12,16] = [0.18726e+03,0.17263e+03,0.15975e+03,0.14834e+03,0.13835e+03]\n kb[:,44-12,16] = [0.19275e+03,0.17748e+03,0.16403e+03,0.15210e+03,0.14166e+03]\n kb[:,45-12,16] = [0.19851e+03,0.18250e+03,0.16844e+03,0.15602e+03,0.14507e+03]\n kb[:,46-12,16] = [0.20490e+03,0.18806e+03,0.17333e+03,0.16038e+03,0.14888e+03]\n kb[:,47-12,16] = [0.21238e+03,0.19462e+03,0.17910e+03,0.16545e+03,0.15337e+03]\n kb[:,48-12,16] = [0.22029e+03,0.20156e+03,0.18514e+03,0.17074e+03,0.15806e+03]\n kb[:,49-12,16] = [0.22889e+03,0.20882e+03,0.19150e+03,0.17637e+03,0.16304e+03]\n kb[:,50-12,16] = [0.23745e+03,0.21596e+03,0.19782e+03,0.18187e+03,0.16787e+03]\n kb[:,51-12,16] = [0.24629e+03,0.22340e+03,0.20422e+03,0.18747e+03,0.17280e+03]\n kb[:,52-12,16] = [0.25553e+03,0.23136e+03,0.21090e+03,0.19335e+03,0.17798e+03]\n kb[:,53-12,16] = [0.26553e+03,0.23980e+03,0.21793e+03,0.19951e+03,0.18336e+03]\n kb[:,54-12,16] = [0.27524e+03,0.24799e+03,0.22485e+03,0.20544e+03,0.18854e+03]\n kb[:,55-12,16] = [0.28502e+03,0.25615e+03,0.23188e+03,0.21133e+03,0.19372e+03]\n kb[:,56-12,16] = [0.29529e+03,0.26491e+03,0.23927e+03,0.21749e+03,0.19913e+03]\n kb[:,57-12,16] = [0.30624e+03,0.27413e+03,0.24703e+03,0.22404e+03,0.20478e+03]\n kb[:,58-12,16] = [0.31727e+03,0.28329e+03,0.25471e+03,0.23065e+03,0.21031e+03]\n kb[:,59-12,16] = [0.32188e+03,0.28710e+03,0.25796e+03,0.23341e+03,0.21261e+03]\n\n # -----------------------------------------------------------------\n forref = zeros(4,16)\n forref[:, 1] = [ 0.214504e-06, 0.460418e-06, 0.357608e-05, 0.192037e-05 ]\n forref[:, 2] = [ 0.142576e-05, 0.364463e-05, 0.117033e-04, 0.112085e-04 ]\n forref[:, 3] = [ 0.101536e-04, 0.124096e-04, 0.509190e-04, 0.565282e-04 ]\n forref[:, 4] = [ 0.143394e-03, 0.154700e-03, 0.466498e-03, 0.918829e-03 ]\n forref[:, 5] = [ 0.251631e-02, 0.241729e-02, 0.240057e-02, 0.350408e-02 ]\n forref[:, 6] = [ 0.410309e-02, 0.416851e-02, 0.390925e-02, 0.383694e-02 ]\n forref[:, 7] = [ 0.445387e-02, 0.448657e-02, 0.432310e-02, 0.370739e-02 ]\n forref[:, 8] = [ 0.458150e-02, 0.460014e-02, 0.450245e-02, 0.336718e-02 ]\n forref[:, 9] = [ 0.465423e-02, 0.465595e-02, 0.467006e-02, 0.368061e-02 ]\n forref[:,10] = [ 0.493955e-02, 0.490181e-02, 0.481941e-02, 0.367577e-02 ]\n forref[:,11] = [ 0.511876e-02, 0.490981e-02, 0.493303e-02, 0.357423e-02 ]\n forref[:,12] = [ 0.509845e-02, 0.511556e-02, 0.504031e-02, 0.355915e-02 ]\n forref[:,13] = [ 0.523822e-02, 0.530473e-02, 0.523811e-02, 0.414259e-02 ]\n forref[:,14] = [ 0.551133e-02, 0.535831e-02, 0.546702e-02, 0.473875e-02 ]\n forref[:,15] = [ 0.609781e-02, 0.589859e-02, 0.561187e-02, 0.528981e-02 ]\n forref[:,16] = [ 0.644958e-02, 0.631718e-02, 0.625201e-02, 0.600448e-02 ]\n\n # -----------------------------------------------------------------\n # The array SELFREF contains the coefficient of the water vapor\n # self-continuum (including the energy term). The first index\n # refers to temperature in 7.2 degree increments. For instance,\n # JT = 1 refers to a temperature of 245.6, JT = 2 refers to 252.8,\n # etc. The second index runs over the g-channel (1 to 16).\n selfref = zeros(10,16)\n selfref[:, 1] = [0.217058e-03, 0.176391e-03, 0.143342e-03, 0.116486e-03, 0.946614e-04,0.769257e-04, 0.625131e-04, 0.508007e-04, 0.412828e-04, 0.335481e-04]\n selfref[:, 2] = [0.598055e-03, 0.484805e-03, 0.393000e-03, 0.318580e-03, 0.258252e-03,0.209348e-03, 0.169705e-03, 0.137569e-03, 0.111518e-03, 0.904008e-04]\n selfref[:, 3] = [0.102691e-02, 0.930281e-03, 0.842740e-03, 0.763437e-03, 0.691596e-03,0.626516e-03, 0.567560e-03, 0.514152e-03, 0.465769e-03, 0.421940e-03]\n selfref[:, 4] = [0.388569e-02, 0.365098e-02, 0.343045e-02, 0.322324e-02, 0.302854e-02,0.284561e-02, 0.267372e-02, 0.251222e-02, 0.236047e-02, 0.221789e-02]\n selfref[:, 5] = [0.349845e-01, 0.326678e-01, 0.305045e-01, 0.284845e-01, 0.265982e-01,0.248369e-01, 0.231921e-01, 0.216563e-01, 0.202222e-01, 0.188831e-01]\n selfref[:, 6] = [0.613705e-01, 0.562676e-01, 0.515890e-01, 0.472994e-01, 0.433665e-01,0.397606e-01, 0.364545e-01, 0.334233e-01, 0.306442e-01, 0.280961e-01]\n selfref[:, 7] = [0.656981e-01, 0.602660e-01, 0.552830e-01, 0.507120e-01, 0.465190e-01,0.426726e-01, 0.391443e-01, 0.359077e-01, 0.329387e-01, 0.302153e-01]\n selfref[:, 8] = [0.671782e-01, 0.616461e-01, 0.565695e-01, 0.519110e-01, 0.476361e-01,0.437132e-01, 0.401134e-01, 0.368100e-01, 0.337787e-01, 0.309970e-01]\n selfref[:, 9] = [0.675902e-01, 0.620888e-01, 0.570351e-01, 0.523928e-01, 0.481284e-01,0.442110e-01, 0.406125e-01, 0.373069e-01, 0.342703e-01, 0.314809e-01]\n selfref[:,10] = [0.708308e-01, 0.651419e-01, 0.599099e-01, 0.550981e-01, 0.506728e-01,0.466030e-01, 0.428600e-01, 0.394176e-01, 0.362517e-01, 0.333401e-01]\n selfref[:,11] = [0.698445e-01, 0.646584e-01, 0.598573e-01, 0.554128e-01, 0.512982e-01,0.474892e-01, 0.439630e-01, 0.406986e-01, 0.376766e-01, 0.348791e-01]\n selfref[:,12] = [0.743921e-01, 0.682057e-01, 0.625337e-01, 0.573334e-01, 0.525655e-01,0.481942e-01, 0.441863e-01, 0.405118e-01, 0.371428e-01, 0.340540e-01]\n selfref[:,13] = [0.775758e-01, 0.709818e-01, 0.649484e-01, 0.594277e-01, 0.543764e-01,0.497544e-01, 0.455253e-01, 0.416556e-01, 0.381149e-01, 0.348751e-01]\n selfref[:,14] = [0.776545e-01, 0.714761e-01, 0.657894e-01, 0.605550e-01, 0.557372e-01,0.513026e-01, 0.472209e-01, 0.434639e-01, 0.400058e-01, 0.368229e-01]\n selfref[:,15] = [0.855675e-01, 0.787337e-01, 0.724456e-01, 0.666598e-01, 0.613360e-01,0.564374e-01, 0.519301e-01, 0.477827e-01, 0.439666e-01, 0.404552e-01]\n selfref[:,16] = [0.934781e-01, 0.855190e-01, 0.782376e-01, 0.715761e-01, 0.654819e-01,0.599065e-01, 0.548058e-01, 0.501394e-01, 0.458704e-01, 0.419648e-01]\nend", "meta": {"hexsha": "40d168aa2a7878948af923234d34a5b20ea1a428", "size": 84209, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "srtm_kgbs/srtm_kgb20.jl", "max_stars_repo_name": "jsbj/RRTM.jl", "max_stars_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-05-25T03:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T12:05:50.000Z", "max_issues_repo_path": "srtm_kgbs/srtm_kgb20.jl", "max_issues_repo_name": "jsbj/RRTM.jl", "max_issues_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srtm_kgbs/srtm_kgb20.jl", "max_forks_repo_name": "jsbj/RRTM.jl", "max_forks_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.2755004766, "max_line_length": 206, "alphanum_fraction": 0.6432447838, "num_tokens": 52503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.2254166158350767, "lm_q1q2_score": 0.17017038406876595}} {"text": "SEED_Char(io::IO, BUF::SeisIOBuf, nb::UInt16) = replace(String(read(io, nb)),\n ['\\r', '\\0'] =>\"\")\n\n# This gets special handling as Float64 arrays are assumed in S.x[c]\nfunction SEED_Float64!(io::IO, S::SeisData, c::Int64, xi::Int64, nb::UInt16)\n buf = getfield(BUF, :buf)\n x = getindex(getfield(S, :x), c)\n readbytes!(io, buf, nb)\n nx = div(nb, 8)\n if getfield(BUF, :xs) == true\n j = xi\n @inbounds for i = 1:nx\n j += 1\n y = UInt32(buf[8*i-7]) << 56\n y |= UInt32(buf[8*i-6]) << 48\n y |= UInt32(buf[8*i-5]) << 40\n y |= UInt32(buf[8*i-4]) << 32\n y |= UInt32(buf[8*i-3]) << 24\n y |= UInt32(buf[8*i-2]) << 16\n y |= UInt32(buf[8*i-1]) << 8\n y |= UInt32(buf[8*i])\n x[j] = y\n end\n else\n xr = reinterpret(Float64, buf)\n copyto!(x, xi+1, xr, 1, nx)\n end\n setfield!(BUF, :k, Int64(nx))\n return nothing\nend\n\nfunction SEED_Unenc!(io::IO, S::SeisData, c::Int64, xi::Int64, nb::UInt16, nx::UInt16)\n buf = getfield(BUF, :buf)\n checkbuf_8!(buf, xi)\n x = getindex(getfield(S, :x), c)\n readbytes!(io, buf, nb)\n T::Type = if BUF.fmt == 0x01\n Int16\n elseif BUF.fmt == 0x03\n Int32\n elseif BUF.fmt == 0x04\n Float32\n end\n if getfield(BUF, :swap) == true\n xr = bswap.(reinterpret(T, buf))\n else\n xr = reinterpret(T, buf)\n end\n copyto!(x, xi+1, xr, 1, nx)\n setfield!(BUF, :k, Int64(nx))\n return nothing\nend\n\nfunction SEED_Geoscope!(io::IO, BUF::SeisIOBuf)\n mm = 0x0fff\n gm = BUF.fmt == 0x0d ? 0x7000 : 0xf000\n for i = 0x0001:BUF.n\n x = BUF.swap ? bswap(read(io, UInt16)) : read(io, UInt16)\n m = Int32(x & mm)\n g = Int32((x & gm) >> 12)\n ex = -1*g\n setindex!(BUF.x, ldexp(Float64(m-2048), ex), i)\n end\n BUF.k = BUF.n\n return nothing\nend\n\nfunction SEED_CDSN!(io::IO, BUF::SeisIOBuf)\n for i = 0x0001:BUF.n\n x = BUF.swap ? bswap(read(io, UInt16)) : read(io, UInt16)\n m = Int32(x & 0x3fff)\n g = Int32((x & 0xc000) >> 14)\n mult = 4^g * g==3 ? 2 : 1\n m -= 0x1fff\n setindex!(BUF.x, m*mult, i)\n end\n BUF.k = BUF.n\n return nothing\nend\n\nfunction SEED_SRO!(io::IO, BUF::SeisIOBuf)\n for i = 0x0001:BUF.n\n x = BUF.swap ? bswap(read(io, UInt16)) : read(io, UInt16)\n m = Int32(x & 0x0fff)\n g = Int32((x & 0xf000) >> 12)\n if m > 0x07ff\n m -= 0x1000\n end\n ex = -1*g + 10\n setindex!(BUF.x, ldexp(Float64(m), ex), i)\n end\n BUF.k = BUF.n\n return nothing\nend\n\nfunction SEED_DWWSSN!(io::IO, BUF::SeisIOBuf)\n for i = 0x0001:BUF.n\n x = signed(UInt32(BUF.swap ? bswap(read(io, UInt16)) : read(io, UInt16)))\n BUF.x[i] = x > 32767 ? x - 65536 : x\n end\n BUF.k = BUF.n\n return nothing\nend\n\n# Steim1 or Steim2\nfunction SEED_Steim!(io::IO, BUF::SeisIOBuf, nb::UInt16)\n x = getfield(BUF, :x)\n buf = getfield(BUF, :buf)\n ff = getfield(BUF, :x32)\n nc = Int64(div(nb, 0x0040))\n ni = div(nb, 0x0004)\n readbytes!(io, buf, nb)\n\n # Parse buf as UInt32s\n if ni > lastindex(ff)\n resize!(ff, ni)\n end\n yy = zero(UInt32)\n if getfield(BUF, :xs) == true\n @inbounds for ib = 1:ni\n yy = UInt32(buf[4*ib-3]) << 24\n yy |= UInt32(buf[4*ib-2]) << 16\n yy |= UInt32(buf[4*ib-1]) << 8\n yy |= UInt32(buf[4*ib])\n ff[ib] = yy\n end\n else\n @inbounds for il = 1:ni\n yy = UInt32(buf[4*il]) << 24\n yy |= UInt32(buf[4*il-1]) << 16\n yy |= UInt32(buf[4*il-2]) << 8\n yy |= UInt32(buf[4*il-3])\n ff[il] = yy\n end\n end\n\n k = zero(Int64)\n x0 = zero(Float32)\n xn = zero(Float32)\n a = zero(UInt8)\n b = zero(UInt8)\n c = zero(UInt8)\n d = zero(UInt8)\n fq = zero(Float32)\n m = zero(UInt8)\n p = zero(UInt32)\n q = zero(Int32)\n u = zero(UInt32)\n y = zero(UInt32)\n z = zero(UInt32)\n χ = zero(UInt32)\n r = zero(Int64)\n for i = 1:nc\n z = getindex(ff, 1+r)\n for j = 1:16\n χ = getindex(ff, j+r)\n y = (z >> steim[j]) & 0x00000003\n if y == 0x00000001\n a = 0x00\n b = 0x08\n c = 0x04\n elseif BUF.fmt == 0x0a\n a = 0x00\n if y == 0x00000002\n b = 0x10\n c = 0x02\n elseif y == 0x00000003\n b = 0x20\n c = 0x01\n end\n else\n p = χ >> 0x0000001e\n if y == 0x00000002\n a = 0x02\n if p == 0x00000001\n b = 0x1e\n c = 0x01\n elseif p == 0x00000002\n b = 0x0f\n c = 0x02\n elseif p == 0x00000003\n b = 0x0a\n c = 0x03\n end\n elseif y == 0x00000003\n if p == 0x00000000\n a = 0x02\n b = 0x06\n c = 0x05\n elseif p == 0x00000001\n a = 0x02\n b = 0x05\n c = 0x06\n else\n a = 0x04\n b = 0x04\n c = 0x07\n end\n end\n end\n if y != 0x00000000\n u = χ << a\n m = zero(UInt8)\n d = 0x20 - b\n while m < c\n k = k + 1\n q = signed(u)\n q >>= d\n fq = Float32(q)\n setindex!(x, fq, k)\n m = m + 0x01\n u <<= b\n end\n end\n if i == 1\n if j == 2\n x0 = Float32(signed(χ))\n elseif j == 3\n xn = Float32(signed(χ))\n end\n end\n end\n r = r+16\n end\n\n if BUF.wo != 0x01\n vx = view(getfield(BUF, :x), 1:k)\n reverse!(vx)\n end\n setindex!(x, x0, 1)\n\n # Cumsum by hand\n xa = copy(x0)\n @inbounds for i1 = 2:k\n xa = xa + getindex(x, i1)\n setindex!(x, xa, i1)\n end\n\n # Check data values\n if isapprox(getindex(x, k), xn) == false\n println(stdout, string(\"RDMSEED: data integrity -- Steim-\",\n getfield(BUF, :fmt) - 0x09, \" sequence #\",\n String(copy(getfield(BUF, :seq))),\n \" integrity check failed, last_data=\",\n getindex(getfield(BUF, :x), k),\n \", should be xn=\", xn))\n end\n setfield!(BUF, :k, k)\n return nothing\nend\n", "meta": {"hexsha": "ba41356e1e037105bf3f95d6b855108f83a539a4", "size": 5977, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Submodules/SEED/1_mSEEDdec.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SeisIO.jl-b372bb87-02dd-52bb-bcf6-c30dd83fd342", "max_stars_repo_head_hexsha": "ae4ddd969c4c42281f36e218d5d3039af6c3146a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Submodules/SEED/1_mSEEDdec.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SeisIO.jl-b372bb87-02dd-52bb-bcf6-c30dd83fd342", "max_issues_repo_head_hexsha": "ae4ddd969c4c42281f36e218d5d3039af6c3146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Submodules/SEED/1_mSEEDdec.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SeisIO.jl-b372bb87-02dd-52bb-bcf6-c30dd83fd342", "max_forks_repo_head_hexsha": "ae4ddd969c4c42281f36e218d5d3039af6c3146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.812749004, "max_line_length": 86, "alphanum_fraction": 0.4945624895, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.1698684764003171}} {"text": "function sample_data_and_build_tree!(trnidx::Vector{Int}, validx::Vector{Int}, fitted_values_all_data_this_vector_is_modified_by_build_tree::Vector{Float64}, candMatWOMaxValues::Array{Array{Float64,1},1}, mappings::Array{Array{String,1},1}, settings::ModelSettings, numerator::Array{Float64,1}, denominator::Array{Float64,1}, weight::Array{Float64,1}, features, sampleSizeCanBeNEGATIVE, abssampleSize, sampleVector, T_Uint8_or_UInt16)\n# NOTE: this function will call build_tree!()\n\t# fitted_values_all_data_this_vector_is_modified_by_build_tree=zeros(numerator)\n\tif abs(settings.subsampling_prop) >= 1.0\n\t\tn = build_tree!(trnidx, validx, candMatWOMaxValues, mappings, settings, numerator, denominator, weight, features, fitted_values_all_data_this_vector_is_modified_by_build_tree, T_Uint8_or_UInt16)\n\t\treturn n \n\telse\n reused_fitted_leafnr_vector = zeros(Int, length(weight))\n\t\t# do subsampling\n\t\t# sampleSizeCanBeNEGATIVE=convert(Int,round(settings.subsampling_prop*length(denominator)))\n\t\t# note: this can probably be done more efficiently (see also bagging)\n\t\t# abssampleSize,sampleVector,num,denom,w,numf,charf,ooBagnum,ooBagdenom,ooBagw,ooBagnumf,ooBagcharf,ooBagsize=initBoostrapSample(sampleSizeCanBeNEGATIVE,numerator,denominator,weight,charfeatures,numfeatures)\n\t\tunusedSamplePart = sampleData!(trnidx, sampleSizeCanBeNEGATIVE, sampleVector)\n\t\t# build tree\ton subsample of data\n\t\t\tthistree = build_tree!(sampleVector, validx, candMatWOMaxValues, mappings, deepcopy(settings), numerator, denominator, weight, features, fitted_values_all_data_this_vector_is_modified_by_build_tree, T_Uint8_or_UInt16)\n\t# apply tree to ooBagSample\n\t\t\tleaves_of_tree = create_leaves_array(thistree.rootnode)\t\t\t\n apply_tree_by_leaf!(fitted_values_all_data_this_vector_is_modified_by_build_tree, reused_fitted_leafnr_vector, unusedSamplePart, thistree.rootnode, features)\n\t\t# Determine Goodness of Fit\n\t\t\t# I think it is best to consider the goodness of fit per leaf here\n\t\t\t# out of bag performance should be measured here, however this is not coded yet (see also bagging!)\n\t\t\t\t# ooBagEstNumerator=ooBagEstimates.*ooBagdenom\n\t\t\t\t# fittedPerLeaf=Float64[x.fitted for x in leaves_of_tree]\n\t\t\t\t# ooBagcntperLeaf,ooBagsumnumeratorEST,ooBagsumnumerator,ooBagsumdenominator,ooBagsumweight=aggregateByLeafNr(leafNrooBag,ooBagEstNumerator,ooBagnum,ooBagdenom,ooBagw)\n\t\t\t\t# todo tbd check this!\n\t\t\t\t# thisError=calcErrorStats(fittedPerLeaf,ooBagsumnumerator./ooBagsumdenominator,ooBagsumweight)\n\t\t\t\t# thisError=goodnessOfFit(ooBagEstimates,ooBagnum,ooBagdenom,ooBagw,meanobservedvalue,ngroupsInput)\n\t\tthisError = ErrorStats() # Empty/Default Error Stats .\n\t\treturn thistree\n\tend\nend\n\nfunction build_tree!(trnidx::Vector{Int}, validx::Vector{Int}, candMatWOMaxValues::Array{Array{Float64,1},1}, mappings::Array{Array{String,1},1}, settings::ModelSettings, numerator::Array{Float64,1}, denominator::Array{Float64,1}, weight::Array{Float64,1}, features, fitted_values::Vector{Float64}, T_Uint8_or_UInt16)\n\tintVarsUsed, inds, minweightcalculated = some_tree_settings(trnidx, validx, settings.fixedinds, candMatWOMaxValues, mappings, settings.minWeight, weight, settings.subsampling_features_prop, size(features, 2))\n\tsettings.minWeight = minweightcalculated # update minWeight\n\tif !(length(inds) > 0)\n throw(ErrorException(string(\"Error: no features were selected length(inds)=\", length(inds))))\n end\n # if (typeof(settings.crit) == mseSplit)||(typeof(settings.crit) == NormalDevianceDifferenceToMeanFitWEIGHTEDSplit)\n # pointwiseRatio=numerator./denominator\n # else \n # pointwiseRatio=zeros(length(numerator)) #this vector should not be used in this case (also we want to allow for zero deonominators in certain cases and thus refrain from calcuating the pointwise ratio)\n # end\n pointwiseRatio = Vector{Float64}(undef, length(numerator)) # this should not be used by any of the algorithms, hence it is not computed (it is filled with trash(undefined data))\n \n\tempty_xl_data = ExcelData(Array{ExcelSheet}(undef, 0), Array{Chart}(undef, 0))\n\tfp = get_feature_pools(features)\n thisEmptyNode = T_Uint8_or_UInt16 == UInt8 ? UInt8emptyNode : UInt16emptyNode\n\tresultingTree = Tree(thisEmptyNode, intVarsUsed, candMatWOMaxValues, mappings, inds, settings, empty_xl_data, fp)\n\tresultingTree.rootnode = build_tree_iteration!(trnidx, validx, settings, resultingTree, numerator, denominator, pointwiseRatio, weight, features, 0, settings.randomw, Array{Rulepath{T_Uint8_or_UInt16}}(undef, 0), Distributed.myid(), fitted_values, T_Uint8_or_UInt16)\n\t# set Leaf Numbers\n\tset_leaf_numbers!(resultingTree)\n\treturn resultingTree\nend\n\nfunction build_tree_iteration!(trnidx::Vector{Int},validx::Vector{Int},settings::ModelSettings,thisTree::Tree,numerator::Array{Float64,1},denominator::Array{Float64,1},pointwiseRatio::Array{Float64,1},weight::Array{Float64,1},features::DataFrame,\n\t\t\t\t\t\t\t\t\tdepth::Int,randomweight::Float64,parent_rp::Array{Rulepath{RPType},1},parentid::Int,fitted_values::Vector{Float64},T_Uint8_or_UInt16) where RPType\n\t# !!!! the current concept foresees that features is always the FULL DataFrame\n\tboolRandomizeOnlySplitAtTopNode = settings.boolRandomizeOnlySplitAtTopNode\n\tlocal inds\n\t# if fixedinds are provided we never change the selection of features for the whole tree! (bagged boosting model)\n\tif boolRandomizeOnlySplitAtTopNode || (length(settings.fixedinds) > 0)\n\t\t# these settings are randomly chosen by some_tree_settings in this case\n\t\tinds = thisTree.inds_considered\n\telse\n\t\t# inds need to be randomly picked for each iteration\n\t\tinds = randomFeatureSelection(size(features, 2), settings.subsampling_features_prop)\n\tend\n\tintVarsUsed = thisTree.intVarsUsed\n\n\tminweight = settings.minWeight\n\tcrit = settings.crit\n\tspawnsmaller = settings.spawnsmaller\n\tcatSortByThreshold = settings.catSortByThreshold\n\tcatSortBy = settings.catSortBy\n\n\tnobs = size(numerator, 1)\n\tfnames = propertynames(features)\n\t# @code_warntype _split(settings.number_of_num_features,trnidx,validx,numerator,denominator,pointwiseRatio,weight,fnames,features, minweight, depth,randomweight,crit,parallel_level_threshold,parallel_weight_threshold,inds,catSortByThreshold,catSortBy)\n\t# T_Uint8_or_UInt16=T_Uint8_or_UInt16 #T_Uint8_or_UInt16=find_max_type(features)::DataType #Union{UInt8,UInt16}\n\tbest_split = _split(one(T_Uint8_or_UInt16), settings.number_of_num_features, trnidx, validx, numerator, denominator, pointwiseRatio, weight, fnames, features, minweight, depth, randomweight, crit, inds, catSortByThreshold, catSortBy)\n\tid = best_split.featid\n\tsubset = best_split.subset\n\tfname = best_split.featurename\n\tid2 = best_split.featid_new_positive\n\t\n\ttmpsn = sum(view(numerator, trnidx))\n tmpsd = sum(view(denominator, trnidx))\n # todo/tbd check if this \"sort!(subset)\" is necessary and find out why.... is it intended?\n\tsort!(subset)\n\n\t# check if no split was found\n # this can happen (EVEN AT THE TOP NODE) if subsampling (of data and or features) is enabled: it may be that there is in fact no split possible (e.g. if all variables are constant)\n # @show id,nobs,size(trnidx),subset\n # @show sum(view(weight,trnidx))\n # @show sum(view(weight,validx))\n if id == 0\n\tif (depth == 0)\n\t\t@warn(\"DTM: No split was found at the top node. This is generally not expected.\")\n\tend\n\t\ttrnsumn = sum(view(numerator, trnidx))\n\t\ttrnsumd = sum(view(denominator, trnidx))\n mean_observed = trnsumn / trnsumd;this_leaf_size = sum(view(weight, trnidx))\n\t\tfitted_increment = mean_observed\n return Leaf(length(trnidx), mean_observed, fitted_increment, this_leaf_size, depth, parent_rp, trnsumn, trnsumd, -1)::Leaf\n end;\n# Rulepath\n\t\tthis_left_rp = deepcopy(parent_rp);\n\t\tthis_right_rp = deepcopy(parent_rp);\n\t\tpush!(this_left_rp, Rulepath(id, subset, true));\n\t\tpush!(this_right_rp, Rulepath(id, subset, false));\n\t\tif id < 0 # (id<0 == !isa(features[!,id2].pool[1],Number)) #pool cannot be empty here, thus accessing the first element should be fine alternatively eltype(x)<:Number might be faster..\n\t\t\t# split by character variable \n for u in subset\n intVarsUsed[-id + settings.number_of_num_features][u] += 1\n end\n else\n # split by numeric variable\n # todo check performance of this and improve\n intVarsUsed[id][subset[end]] += 1 # set this value to true to indicate, that is is used by the tree\n end\n l, r = lrIndices(trnidx, features[!,id2], subset)\n\n # needs review: are these checks meaningful (June18 2020 ) \n length(r), length(l), length(trnidx)\n @assert length(l) < length(trnidx)\n @assert length(r) < length(trnidx)\n \n countl = size(l, 1)\n countr = size(r, 1)\n sumwl = sum(view(weight, l))\n sumwr = sum(view(weight, r))\n\n\tleftchildwillbefurthersplit = sumwl < 2 * minweight\n\trightchildwillbefurthersplit = sumwr < 2 * minweight\n\t(sumwr > sumwl) ? boolSpawnLeft = false : boolSpawnLeft = true\n if spawnsmaller;boolSpawnLeft = !boolSpawnLeft;end;\n \n boolRandomizeOnlySplitAtTopNode ? newrandomweight = copy(randomweight) : newrandomweight = 0.0\n\n # todo/tbd check the different if/then here, I think a few things are not quite accurate\n\t# Also, we probably do not need any parallelization for the construction of a single tree-> we should disable this functionality\n\ttrnsumnl = sum(view(numerator, l))\n\ttrnsumdl = sum(view(denominator, l))\n\ttrnsumnr = sum(view(numerator, r))\n\ttrnsumdr = sum(view(denominator, r))\n\tmean_observedl = trnsumnl / trnsumdl\t\n\tmean_observedr = trnsumnr / trnsumdr\n\tfitted_labelsl = mean_observedl;\n\tfitted_labelsr = mean_observedr;\n\tif (max(sumwr, sumwl) < minweight)\n\t\t\t\t\tif leftchildwillbefurthersplit\t\t\t\n\t\t\t\t\t\tfill_some_elements!(fitted_values, l, mean_observedl)\n\t\t\t\t\t\t\tremote_ref_build_tree_leftchild = Leaf(length(l), mean_observedl, fitted_labelsl, sumwl, depth + 1, this_left_rp, trnsumnl, trnsumdl, -1)\n else\n remote_ref_build_tree_leftchild = build_tree_iteration!(l, validx, settings, thisTree, numerator, denominator, pointwiseRatio, weight, features, depth + 1, newrandomweight, this_left_rp, Distributed.myid(), fitted_values, T_Uint8_or_UInt16)\n\t\t end\n\t\t\t\t\tif rightchildwillbefurthersplit\t\t\t \n\t\t\t\t\t\tfill_some_elements!(fitted_values, r, mean_observedr)\n remote_ref_build_tree_rightchild = Leaf(length(r), mean_observedr, fitted_labelsr, sumwr, depth + 1, this_right_rp, trnsumnr, trnsumdr, -1)\n else\n remote_ref_build_tree_rightchild = build_tree_iteration!(r, validx, settings, thisTree, numerator, denominator, pointwiseRatio, weight, features, depth + 1, newrandomweight, this_right_rp, Distributed.myid(), fitted_values, T_Uint8_or_UInt16)\n end\n else\n # here we spawn a process for the smaller \"child\"\n if (!boolSpawnLeft)\n # here it is important that the @spawn is executed before the build_tree_iteration! call!\n\t\t\t\t\t\tif rightchildwillbefurthersplit\n\t\t\t\t\t\t\tfill_some_elements!(fitted_values, r, mean_observedr)\n \t remote_ref_build_tree_rightchild = Leaf(length(r), mean_observedr, fitted_labelsr, sumwr, depth + 1, this_right_rp, trnsumnr, trnsumdr, -1)\n else\n remote_ref_build_tree_rightchild = Distributed.@spawn build_tree_iteration!(r, validx, settings, thisTree, numerator, denominator, pointwiseRatio, weight, features, depth + 1, newrandomweight, this_right_rp, Distributed.myid(), fitted_values, T_Uint8_or_UInt16)\n end\n\t\t\t\t\t\tif leftchildwillbefurthersplit\n\t\t\t\t\t\t\tfill_some_elements!(fitted_values, l, mean_observedl)\n\t\t\t\t\t\t remote_ref_build_tree_leftchild = Leaf(length(l), mean_observedl, fitted_labelsl, sumwl, depth + 1, this_left_rp, trnsumnl, trnsumdl, -1)\n else\n remote_ref_build_tree_leftchild = build_tree_iteration!(l, validx, settings, thisTree, numerator, denominator, pointwiseRatio, weight, features, depth + 1, newrandomweight, this_left_rp, Distributed.myid(), fitted_values, T_Uint8_or_UInt16)\n end\n else\n\t\t\t\t\t\tif leftchildwillbefurthersplit\n\t\t\t\t\t\t\tfill_some_elements!(fitted_values, l, mean_observedl)\n\t\t\t\t\t\t remote_ref_build_tree_leftchild = Leaf(length(l), mean_observedl, fitted_labelsl, sumwl, depth + 1, this_left_rp, trnsumnl, trnsumdl, -1)\n else\n remote_ref_build_tree_leftchild = Distributed.@spawn build_tree_iteration!(l, validx, settings, thisTree, numerator, denominator, pointwiseRatio, weight, features, depth + 1, newrandomweight, this_left_rp, Distributed.myid(), fitted_values, T_Uint8_or_UInt16)\n end\n\t\t\t\t\t\tif rightchildwillbefurthersplit\n\t\t\t\t\t\t\tfill_some_elements!(fitted_values, r, mean_observedr)\n remote_ref_build_tree_rightchild = Leaf(length(r), mean_observedr, fitted_labelsr, sumwr, depth + 1, this_right_rp, trnsumnr, trnsumdr, -1)\n else \n remote_ref_build_tree_rightchild = build_tree_iteration!(r, validx, settings, thisTree, numerator, denominator, pointwiseRatio, weight, features, depth + 1, newrandomweight, this_right_rp, Distributed.myid(), fitted_values, T_Uint8_or_UInt16)\n end\n end\n end\n\n fetched_left = fetch(remote_ref_build_tree_leftchild)\n fetched_right = fetch(remote_ref_build_tree_rightchild)\n # fitted_values=mergeLeftAndRightFittedValues(fitted_valuesl,fitted_valuesr,left)\n\tif !((id < 0) || (maximum(subset) == subset[end])) # for numeric variables subset should generally be of the form [1:n], if not this means that the data was split in a way such that several candidates collapsed as there was no more data between to (or more) candidates.\n throw(ErrorException(string(\"Internal DTM Error. Subset had unexpected layout. You may want to report this as an issue\")))\n end\n id2 = id < 0 ? abs(id) + settings.number_of_num_features : id\n return Node(id, id2, subset, fetched_left, fetched_right, parent_rp)::Node\nend\n\nfunction _split(val_of_some_UInt_type::T, number_of_num_features::Int, trnidx::Vector{Int}, validx::Vector{Int}, numerator::Array{Float64,1}, denominator::Array{Float64,1}, pointwiseRatio::Array{Float64,1}, weight::Array{Float64,1}, fnames::Vector{Symbol}, features, minweight::Float64, depth::Int, randomweight::Float64, crit::SplittingCriterion, inds::Array{Int,1}=Array{Int}(undef, 0), catSortByThreshold::Int=8, catSortBy::SortBy=SORTBYMEAN) where T <: Unsigned # ,RT<:Union{Splitdef{UInt16},Splitdef{UInt8}}\n\t# This function selects the maximal possible split defined by crit (thus depending on the impurity function, we need to put a minus sign in front of it)\n\t\ttmpsz::Int = 0\n\t\tif sum(view(weight, trnidx)) < 2 * minweight;\n if T == UInt8\n return UInt8emptySplitDef\n else\n return UInt16emptySplitDef\n end\n\t\tend\n\t\ttmp_splitlist = Vector{Splitdef{T}}(undef, 0)\n\t\tfor i in inds\n\t\t\t# ATTENTION: for char variables we pass the variable i with a negative sing!!\n\t\t\t# this allows us to distinguish whether we are working on a char or num variable later on\n\t\t\tmodified_i = eltype(features[!,i]) <: AbstractString ? number_of_num_features - i : i \n\t\t\ttmplist = _split_feature(val_of_some_UInt_type, number_of_num_features, trnidx, validx, numerator, denominator, pointwiseRatio, weight, fnames[i], features[!,i], minweight, crit, modified_i, randomweight, catSortByThreshold, catSortBy)::Vector{Splitdef{T}}\n\t\t\tappend!(tmp_splitlist, tmplist)\n\t\tend\n\n\t\t# pick best \"valid\" (minweight feasible) split\n\t\tif !(size(tmp_splitlist, 1) > 0)\n\t\t\tif T == UInt8\n return UInt8emptySplitDef\n else\n return UInt16emptySplitDef\n end\n\t\telse \n\t\t\t\ttmp_splitlist = subset_splitlist(tmp_splitlist, minweight)\n\t\t\t\tif !(size(tmp_splitlist, 1) > 0)\n\t\t\t\t\tif T == UInt8\n return UInt8emptySplitDef\n else\n return UInt16emptySplitDef\n end\n\t\t\t\telse\n splitlist_sorted::Vector{Splitdef{T}} = sort_splitlist(tmp_splitlist)::Vector{Splitdef{T}}\n\t\t\t\t\t\ttmpsz = size(splitlist_sorted, 1)::Int\n\t\t\t\t\t\tif tmpsz > 0 # can it be that splitlist_sorted is empty even though tmp_splitlist was not? I think so!\n\t\t\t\t\t\t\t# randomize choice\n\t\t\t\t\t\t\tspl::Splitdef{T} = splitlist_sorted[1]\n\t\t\t\t\t\t\tif randomweight > 0 # ((depth==0) && (randomweight>0))\n\t\t\t\t\t\t\t\trnd = Int(max(1, min(tmpsz, ceil(rand() * randomweight * tmpsz)))) # I am not sure if it can happen that rnd becomes 0 if we do not impose the max(1,...) condition. But it seems safe to enforce it in case an incredibly small random number is generated\n\t\t\t\t\t\t\t\tspl = splitlist_sorted[rnd]::Splitdef{T}\n\t\t\t\t\t\t\telse # randomweight<=0\n\t\t\t\t\t\t\t\t# deterministic choice (greedy)\n\t\t\t\t\t\t\t\tspl = splitlist_sorted[1]::Splitdef{T}\n\t\t\t\t\t\t\tend # \"if condition randomweight>0\"\n\t\t\t\t\t\t\tif isfinite(spl.splitvalue) && (spl.featid < 0)\t\t\t\t\n\t\t\t\t\t\t\t\t# For Character variables: The split can be defined by the subset or its complement, We choose to define it via the subset which defines the smaller child node such that when new values arrive (in out of sample testing) they will \"go with the larger child node\"\n\t\t\t\t\t\t\t\tif spl.weightl > spl.weightr\n\t\t\t\t\t\t\t\t\t\tlvls = unique(view(features[!,spl.featid_new_positive].refs, trnidx))\n\t\t\t\t\t\t\t\t\t\tspl = Splitdef(spl.featid, spl.featid_new_positive, spl.featurename, convert(Vector{T}, setdiff(lvls, spl.subset)), spl.splitvalue, spl.weightl, spl.weightr)::Splitdef{T}\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend # isfinite(best_value_split) && (best[1]<0)\n\t\t\t\t\t\tend # size(splitlist_sorted,1)>0\n end # size(tmp_splitlist,1)>0\n\t\tend # size(tmp_splitlist,1)>0\n return spl::Splitdef{T}\nend\n\n\n# new approach; first summarize by label, then iterate over the gray code such that only one category needs to switch classes and \"online\" update the metrics\nfunction _split_feature(ONE_return_type::T, number_of_num_features::Int, trnidx::Vector{Int}, validx::Vector{Int}, numerator::Array{Float64,1}, denominator::Array{Float64,1}, pointwiseRatio::Array{Float64,1}, weight::Array{Float64,1}, fname::Symbol, features, minweight::Float64, crit::SplittingCriterion, feature_column_id::Int, randomweight::Float64, catSortByThreshold::Int, catSortBy::SortBy) where T <: Unsigned\n crit_type = typeof(crit)\n# This function is now for numeric and character variables!\n# feature_column_id is negative in case of character variables\n best_value = -Inf\n best_thresh = best_wl = best_wr = NaN\n best_subset = Array{UInt8}(undef, 0)\n trnfeatures = view(features, trnidx)\n elt = T # eltype(trnfeatures.parent.refs) #not sure if this was really helping, let us determine elt through T\n labellist_sorted = collect(one(elt):convert(elt, length(trnfeatures.parent.pool))) # this used to be levels(features) #this also contains the val feature levels here! It is considerably faster than levels(view) \\factor 100 or so\n\n case1a = (crit_type == DifferenceSplit || crit_type == MaxValueSplit || crit_type == MaxMinusValueSplit || crit_type == MaxAbsValueSplit)\n case1b = (crit_type == GammaDevianceSplit) || (crit_type == PoissonDevianceSplit)\n case1 = (crit_type == DifferenceSplit || crit_type == GammaDevianceSplit || crit_type == PoissonDevianceSplit || crit_type == MaxValueSplit || crit_type == MaxMinusValueSplit || crit_type == MaxAbsValueSplit)\n case2 = (crit_type == msePointwiseSplit) || (crit_type == mseSplit) || (crit_type == sseSplit) \n\t# THIS IS CRITICAL\n\t# THE WAY A PooledArray IS CONSTRUCTED, WE WILL ALWAYS HAVE\n\t# pda.pool[2] == \"some string\" -> any pda.refs[x].==0x02 will be \"some string\" \n\t# todo/tbd countsort here might be obsolete: we should check if levels is always sorted by construction\n # also we will later sort the labels in a different order anyway (then again the list probably needs to be sorted in the natural manner such that build_listOfMeanResponse is working properly)\n if size(labellist_sorted, 1) <= 1\n if T == UInt8\n return UInt8VECTORemptySplitDef\n else\n return UInt16VECTORemptySplitDef # collect(Vector{Splitdef{T}}(undef,0))::Vector{Splitdef{T}}\n end\n else\t\n # this may need improvement:\n\tif case1\n \t\tlabellist, sumnumerator, sumdenominator, sumweight, countlistfloat = build_listOfMeanResponse(crit, trnidx, validx, numerator, denominator, weight, trnfeatures, labellist_sorted, minweight)\n\t elseif case2\n\t\t labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, moments_per_pdaclass = build_listOfMeanResponse(crit, numerator, denominator, weight, trnfeatures, labellist_sorted, minweight)\n # else #we catch this possibility earlier when checking the settings\n #\tthrow(ErrorException(string(\"Invalid Splitting criterion $(crit)\")))\n\tend\n # todo/tbd\n # here we can introduce the possiblity to sort the labellist (e.g. by meanobserved or median (to be calculated)).\n # then we could only loop through the \"increasing list\" of sorted labels (instead of doing the 2^ncategories exhaustive search (bitflip_graycode_subsets))\n if feature_column_id > 0 # id>0 -> we are working on a numeric column\n\t\t# only consider to split at the candidate split points \n\t\tsubs = increasing_subsets(labellist) \n else # id<0 -> we are working on a character column\n\t\t# distinguish between exhaustive and \"increasing\" search for split point\n\t if size(labellist_sorted, 1) > catSortByThreshold\n\t\t if case1 \n sortlists!(catSortBy, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat) # catSortBy::SortBy=SORTBYMEAN\n elseif case2\n\t\t\t sortlists!(catSortBy, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, moments_per_pdaclass)\n\t\t end\n\t\tsubs = increasing_subsets(labellist)\n\telse\n\t # perform exhaustive search\n subs = bitflip_graycode_subsetsHALF(labellist)\n end\n\tend\n\n\tif randomweight == 0.0\n if case1a\n tmp_result = calculateSplitValue(crit, fname, number_of_num_features, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, minweight, subs)\n elseif case2 \n tmp_result = calculateSplitValue(crit, fname, number_of_num_features, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, minweight, subs, moments_per_pdaclass)\n elseif case1b\n tmp_result = calculateSplitValue(crit, fname, number_of_num_features, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, minweight, subs, numerator, denominator, pointwiseRatio, weight, trnfeatures)\n end\n if isfinite(tmp_result[1])\n feature_column_id2 = feature_column_id < 0 ? abs(feature_column_id) + number_of_num_features : feature_column_id\n return [Splitdef(feature_column_id, feature_column_id2, fname, Vector{T}(tmp_result[2]), tmp_result[1], tmp_result[3], tmp_result[4])]::Vector{Splitdef{T}}\n else \n if T == UInt8\n return UInt8VECTORemptySplitDef\n else\n return UInt16VECTORemptySplitDef # collect(Vector{Splitdef{T}}(undef,0))::Vector{Splitdef{T}}\n end \n end\n else\n # randomweight>0\n if case1a\n tmpres = calculateSplitValue(crit, fname, number_of_num_features, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, minweight, subs, feature_column_id)\n elseif case2 \n tmpres = calculateSplitValue(crit, fname, number_of_num_features, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, minweight, subs, feature_column_id, moments_per_pdaclass)\n elseif case1b \n tmpres = calculateSplitValue(crit, fname, number_of_num_features, labellist, sumnumerator, sumdenominator, sumweight, countlistfloat, minweight, subs, numerator, denominator, pointwiseRatio, weight, trnfeatures, feature_column_id)\n end\n return tmpres::Vector{Splitdef{T}} \n end\n end\nend\n\n", "meta": {"hexsha": "0cdf92a75ed2d0b6275168b20825a0363784cec5", "size": 23830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/build_tree.jl", "max_stars_repo_name": "kafisatz/DecisionTrees.jl", "max_stars_repo_head_hexsha": "f36e55da257d3a58c6eb9ac4ba98e396ddb7e1bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-08-05T03:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T10:00:56.000Z", "max_issues_repo_path": "src/build_tree.jl", "max_issues_repo_name": "kafisatz/DecisionTrees.jl", "max_issues_repo_head_hexsha": "f36e55da257d3a58c6eb9ac4ba98e396ddb7e1bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2018-06-19T07:50:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T16:08:11.000Z", "max_forks_repo_path": "src/build_tree.jl", "max_forks_repo_name": "kafisatz/DecisionTrees.jl", "max_forks_repo_head_hexsha": "f36e55da257d3a58c6eb9ac4ba98e396ddb7e1bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.9382022472, "max_line_length": 512, "alphanum_fraction": 0.7402853546, "num_tokens": 6422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.16943946553583702}} {"text": "# sudo apt-get install python-dev\n# sudo apt-get install python-pip\n# sudo pip install biopython\n# sudo apt-get install numpy | unless you want to compile it..\n# julia: Pkg.add(\"PyCall\")\nmodule PDB\nexport get_structure, get_chains, structure_to_matrix, export_to_pdb, get_remote_pdb\n\nusing PyCall\nusing Formatting\n@pyimport Bio.PDB as pdb\n\n# get a structure from a PDB File\nfunction get_structure(filename::AbstractString)\n\t# using QUIET to supress discontinous chains warning\n\tpdbparser = pdb.PDBParser(QUIET = 1)\n\n\t# parse the file\n\tstructure = pdbparser[:get_structure](filename, filename)\n\treturn structure\nend\n\n# get chains from structure\nfunction get_chains(structure::PyObject)\n\tchains = structure[:get_chains]()\n\n\tchainMatrices = Any[]\n\n\tfor c in chains\n\t\tpush!(chainMatrices,structure_to_matrix(c))\n\tend\n\n\treturn chainMatrices\nend\n\n# Read in a PDB file and return a matrix of C_Alpha atom coordinates\nfunction structure_to_matrix(structure::PyObject)\n\tatoms = structure[:get_atoms]()\n\t# Filter out C_Alpha atoms\n\tatoms = filter(x -> x[:get_name]() == \"CA\", atoms) \n\t# Get the coordinates\n\tatoms = map(x -> x[:get_coord](), atoms)\n\n\tn = length(atoms)\n\n\t# initialize an empty Nx3 matrix\n\tmatrix = zeros(n,3)\n\n\t# fill it\n\tfor i in 1:n\n\t\tmatrix[i,:] = [atoms[i][1] atoms[i][2] atoms[i][3]]\n\tend\n\n\tmatrix = reshape(matrix,n,3)\n\n\treturn matrix\nend\n\n# Export a matrix of C_alpha atom coordinates to a PDB file\nfunction export_to_pdb(residueName::AbstractString,chainID::AbstractString,matrix::Array{Float64,2}, filename::AbstractString)\n\tlines = AbstractString[]\n\n\tatomExpr = FormatExpr(\"{: <6}{: >5} {: >4}{: <1}{: >3} {: <1}{: >4}{: <1} {: >8}{: >8}{: >8}{: >6}{: >6} {: <4}{: >2}{: <2}\\n\")\n\n\tfor i in 1:size(matrix)[1]\n\t\tline = format(atomExpr, \"ATOM\", i, \"CA\", \" \", residueName, chainID, \"1\", \" \", matrix[i,:][1], matrix[i,:][2], matrix[i,:][3], 1.0, 0.0, \"A1\", \"C\", \" \")\n\t\t\n\t\tpush!(lines, line)\n\tend\n\n\tf = open(filename, \"w\")\n\twrite(f,lines)\n\tclose(f)\n\n\treturn lines\nend\n\n# Get a PDB file by ID from rcsb.org\nfunction get_remote_pdb(id::AbstractString)\n\t# create cache if not present\n\tif !isdir(joinpath(dirname(@__FILE__), \"..\", \"..\", \".cache\")) \n\t\tmkdir(joinpath(dirname(@__FILE__), \"..\", \"..\", \".cache\"))\n\tend\n\tfilename = joinpath(dirname(@__FILE__), \"..\", \"..\", \".cache\", id)\n\t# check if PDB isn't already cached\n\tif !isreadable(filename)\n\t\tdata = get(\"http://www.rcsb.org/pdb/files/\" * id * \".pdb\")\n\t\tf = open(filename, \"w\")\n\t\twrite(f, data.data)\n\tend\t\n\treturn filename\nend\n\nend", "meta": {"hexsha": "a647ad64d1b7b153602e16621b470efff9098206", "size": 2497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PDB/pdb.jl", "max_stars_repo_name": "UnofficialJuliaMirror/BiomolecularStructures.jl-8710203e-1f21-525d-b237-938bdd24ee6a", "max_stars_repo_head_hexsha": "a8c8970f2cbbdf4ec05bd1245a61e3ddab2a6380", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-04-30T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T02:14:33.000Z", "max_issues_repo_path": "src/PDB/pdb.jl", "max_issues_repo_name": "UnofficialJuliaMirror/BiomolecularStructures.jl-8710203e-1f21-525d-b237-938bdd24ee6a", "max_issues_repo_head_hexsha": "a8c8970f2cbbdf4ec05bd1245a61e3ddab2a6380", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2015-03-13T21:52:53.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-01T21:46:01.000Z", "max_forks_repo_path": "src/PDB/pdb.jl", "max_forks_repo_name": "UnofficialJuliaMirror/BiomolecularStructures.jl-8710203e-1f21-525d-b237-938bdd24ee6a", "max_forks_repo_head_hexsha": "a8c8970f2cbbdf4ec05bd1245a61e3ddab2a6380", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-03-12T13:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:21:28.000Z", "avg_line_length": 26.5638297872, "max_line_length": 153, "alphanum_fraction": 0.676411694, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.16943946215819936}} {"text": "module HydrostaticBoussinesq\n\nexport HydrostaticBoussinesqModel, HydrostaticBoussinesqProblem, OceanDGModel\n\nusing StaticArrays\nusing LinearAlgebra: I, dot, Diagonal\nusing ..VariableTemplates\nusing ..MPIStateArrays\nusing ..DGmethods: init_ode_state\nusing ..PlanetParameters: grav\nusing ..Mesh.Filters: CutoffFilter, apply!, ExponentialFilter\nusing ..Mesh.Grids: polynomialorder, VerticalDirection\n\nusing ..DGmethods.NumericalFluxes: Rusanov, CentralGradPenalty,\n CentralNumericalFluxDiffusive,\n CentralNumericalFluxNonDiffusive\n\nimport ..DGmethods.NumericalFluxes: update_penalty!, numerical_flux_diffusive!,\n NumericalFluxNonDiffusive\n\nimport ..DGmethods: BalanceLaw, vars_aux, vars_state, vars_gradient,\n vars_diffusive, vars_integrals, flux_nondiffusive!,\n flux_diffusive!, source!, wavespeed,\n boundary_state!, update_aux!, update_aux_diffusive!,\n gradvariables!, init_aux!, init_state!,\n LocalGeometry, indefinite_stack_integral!,\n reverse_indefinite_stack_integral!, integrate_aux!,\n DGModel, nodal_update_aux!, diffusive!,\n copy_stack_field_down!, create_state\n\n×(a::SVector, b::SVector) = StaticArrays.cross(a, b)\n∘(a::SVector, b::SVector) = StaticArrays.dot(a, b)\n\nabstract type OceanBoundaryCondition end\nstruct CoastlineFreeSlip <: OceanBoundaryCondition end\nstruct CoastlineNoSlip <: OceanBoundaryCondition end\nstruct OceanFloorFreeSlip <: OceanBoundaryCondition end\nstruct OceanFloorNoSlip <: OceanBoundaryCondition end\nstruct OceanSurfaceNoStressNoForcing <: OceanBoundaryCondition end\nstruct OceanSurfaceStressNoForcing <: OceanBoundaryCondition end\nstruct OceanSurfaceNoStressForcing <: OceanBoundaryCondition end\nstruct OceanSurfaceStressForcing <: OceanBoundaryCondition end\n\nabstract type HydrostaticBoussinesqProblem end\n\nstruct HydrostaticBoussinesqModel{P,T} <: BalanceLaw\n problem::P\n c₁::T\n c₂::T\n c₃::T\n αᵀ::T\n νʰ::T\n νᶻ::T\n κʰ::T\n κᶻ::T\nend\n\nHBModel = HydrostaticBoussinesqModel\nHBProblem = HydrostaticBoussinesqProblem\n\nfunction OceanDGModel(bl::HBModel, grid, numfluxnondiff, numfluxdiff,\n gradnumflux; kwargs...)\n vert_filter = CutoffFilter(grid, polynomialorder(grid)-1)\n exp_filter = ExponentialFilter(grid, 1, 8)\n\n modeldata = (vert_filter = vert_filter, exp_filter=exp_filter)\n\n return DGModel(bl, grid, numfluxnondiff, numfluxdiff, gradnumflux;\n kwargs..., modeldata=modeldata)\nend\n\n# If this order is changed check the filter usage!\nfunction vars_state(m::HBModel, T)\n @vars begin\n u::SVector{2, T}\n η::T # real a 2-D variable TODO: should be 2D\n θ::T\n end\nend\n\n# If this order is changed check update_aux!\nfunction vars_aux(m::HBModel, T)\n @vars begin\n w::T\n pkin_reverse::T # ∫(-αᵀ θ) # TODO: remove me after better integral interface\n w_reverse::T # TODO: remove me after better integral interface\n pkin::T # ∫(-αᵀ θ)\n wz0::T # w at z=0\n θʳ::T # SST given # TODO: Should be 2D\n f::T # coriolis\n τ::T # wind stress # TODO: Should be 2D\n # κ::SMatrix{3, 3, T, 9} # diffusivity tensor (for convective adjustment)\n κᶻ::T\n end\nend\n\nfunction vars_gradient(m::HBModel, T)\n @vars begin\n u::SVector{2, T}\n θ::T\n end\nend\n\nfunction vars_diffusive(m::HBModel, T)\n @vars begin\n ∇u::SMatrix{3, 2, T, 6}\n ∇θ::SVector{3, T}\n end\nend\n\nfunction vars_integrals(m::HBModel, T)\n @vars begin\n ∇hu::T\n αᵀθ::T\n end\nend\n\n@inline function flux_nondiffusive!(m::HBModel, F::Grad, Q::Vars,\n A::Vars, t::Real)\n @inbounds begin\n u = Q.u # Horizontal components of velocity\n η = Q.η\n θ = Q.θ\n w = A.w # vertical velocity\n pkin = A.pkin\n v = @SVector [u[1], u[2], w]\n Ih = @SMatrix [ 1 -0;\n -0 1;\n -0 -0]\n\n # ∇ • (u θ)\n F.θ += v * θ\n\n # ∇h • (g η)\n F.u += grav * η * Ih\n\n # ∇h • (- ∫(αᵀ θ))\n F.u += grav * pkin * Ih\n\n # ∇h • (v ⊗ u)\n # F.u += v * u'\n\n end\n\n return nothing\nend\n\n@inline wavespeed(m::HBModel, n⁻, _...) = abs(SVector(m.c₁, m.c₂, m.c₃)' * n⁻)\n\n# We want not have jump penalties on η (since not a flux variable)\nfunction update_penalty!(::Rusanov, ::HBModel, n⁻, λ, ΔQ::Vars,\n Q⁻, A⁻, Q⁺, A⁺, t)\n ΔQ.η = -0\n\n #=\n θ⁻ = Q⁻.θ\n u⁻ = Q⁻.u\n w⁻ = A⁻.w\n @inbounds v⁻ = @SVector [u⁻[1], u⁻[2], w⁻]\n n̂_v⁻ = n⁻∘v⁻\n\n θ⁺ = Q⁺.θ\n u⁺ = Q⁺.u\n w⁺ = A⁺.w\n @inbounds v⁺ = @SVector [u⁺[1], u⁺[2], w⁺]\n n̂_v⁺ = n⁻∘v⁺\n\n # max velocity\n # n̂∘v = (abs(n̂∘v⁺) > abs(n̂∘v⁻) ? n̂∘v⁺ : n̂∘v⁻\n\n # average velocity\n n̂_v = (n̂_v⁻ + n̂_v⁺) / 2\n\n ΔQ.θ = ((n̂_v > 0) ? 1 : -1) * (n̂_v⁻ * θ⁻ - n̂_v⁺ * θ⁺)\n # ΔQ.θ = abs(n̂_v⁻) * θ⁻ - abs(n̂_v⁺) * θ⁺\n =#\n\n return nothing\nend\n\n@inline function flux_diffusive!(m::HBModel, F::Grad, Q::Vars, D::Vars,\n A::Vars, t::Real)\n ν = Diagonal(@SVector [m.νʰ, m.νʰ, m.νᶻ])\n F.u -= ν * D.∇u\n\n κ = Diagonal(@SVector [m.κʰ, m.κʰ, A.κᶻ])\n F.θ -= κ * D.∇θ\n\n return nothing\nend\n\n@inline function gradvariables!(m::HBModel, G::Vars, Q::Vars, A, t)\n G.u = Q.u\n G.θ = Q.θ\n\n return nothing\nend\n\n@inline function diffusive!(m::HBModel, D::Vars, G::Grad, Q::Vars,\n A::Vars, t)\n D.∇u = G.u\n D.∇θ = G.θ\n\n return nothing\nend\n\n@inline function source!(m::HBModel{P}, source::Vars, Q::Vars, A::Vars,\n t::Real) where P\n @inbounds begin\n u = Q.u # Horizontal components of velocity\n f = A.f\n wz0 = A.wz0\n\n # f × u\n source.u -= @SVector [-f * u[2], f * u[1]]\n\n source.η += wz0\n end\n\n return nothing\nend\n\n@inline function integrate_aux!(m::HBModel, integrand::Vars, Q::Vars, A::Vars)\n αᵀ = m.αᵀ\n integrand.αᵀθ = -αᵀ * Q.θ\n integrand.∇hu = A.w # borrow the w value from A...\n\n return nothing\nend\n\nfunction update_aux!(dg::DGModel, m::HBModel, Q::MPIStateArray, t::Real)\n MD = dg.modeldata\n\n # required to ensure that after integration velocity field is divergence free\n vert_filter = MD.vert_filter\n # Q[1] = u[1] = u, Q[2] = u[2] = v\n apply!(Q, (1, 2), dg.grid, vert_filter, VerticalDirection())\n\n exp_filter = MD.exp_filter\n # Q[4] = θ\n apply!(Q, (4,), dg.grid, exp_filter, VerticalDirection())\n\n return true\nend\n\nfunction update_aux_diffusive!(dg::DGModel, m::HBModel, Q::MPIStateArray, t::Real)\n A = dg.auxstate\n\n # store ∇ʰu as integrand for w\n # update vertical diffusivity for convective adjustment\n function f!(::HBModel, Q, A, D, t)\n @inbounds begin\n A.w = -(D.∇u[1,1] + D.∇u[2,2])\n\n # κʰ = m.κʰ\n # A.κ = @SMatrix [κʰ -0 -0; -0 κʰ -0; -0 -0 κᶻ]\n D.∇θ[3] < 0 ? A.κᶻ = 1000 * m.κᶻ : A.κᶻ = m.κᶻ\n end\n\n return nothing\n end\n nodal_update_aux!(f!, dg, m, Q, t; diffusive=true)\n\n # compute integrals for w and pkin\n indefinite_stack_integral!(dg, m, Q, A, t) # bottom -> top\n reverse_indefinite_stack_integral!(dg, m, A, t) # top -> bottom\n\n # project w(z=0) down the stack\n # Need to be consistent with vars_aux\n # A[1] = w, A[5] = wz0\n copy_stack_field_down!(dg, m, A, 1, 5)\n\n return true\nend\n\nfunction ocean_init_aux! end\nfunction init_aux!(m::HBModel, A::Vars, geom::LocalGeometry)\n return ocean_init_aux!(m, m.problem, A, geom)\nend\n\nfunction ocean_init_state! end\nfunction init_state!(m::HBModel, Q::Vars, A::Vars, coords, t)\n return ocean_init_state!(m.problem, Q, A, coords, t)\nend\n\n@inline function boundary_state!(nf, m::HBModel, Q⁺::Vars, A⁺::Vars, n⁻,\n Q⁻::Vars, A⁻::Vars, bctype, t, _...)\n return ocean_boundary_state!(m, bctype, nf, Q⁺, A⁺, n⁻, Q⁻, A⁻, t)\nend\n@inline function boundary_state!(nf, m::HBModel,\n Q⁺::Vars, D⁺::Vars, A⁺::Vars,\n n⁻,\n Q⁻::Vars, D⁻::Vars, A⁻::Vars,\n bctype, t, _...)\n return ocean_boundary_state!(m, bctype, nf, Q⁺, D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\nend\n\n@inline function ocean_boundary_state!(::HBModel, ::CoastlineFreeSlip,\n ::Union{Rusanov, CentralGradPenalty},\n Q⁺, A⁺, n⁻, Q⁻, A⁻, t)\n return nothing\nend\n\n\n@inline function ocean_boundary_state!(::HBModel, ::CoastlineFreeSlip,\n ::CentralNumericalFluxDiffusive, Q⁺,\n D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n D⁺.∇u = -D⁻.∇u\n\n D⁺.∇θ = -D⁻.∇θ\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(::HBModel, ::CoastlineNoSlip,\n ::Union{Rusanov, CentralGradPenalty},\n Q⁺, A⁺, n⁻, Q⁻, A⁻, t)\n Q⁺.u = -Q⁻.u\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(::HBModel, ::CoastlineNoSlip,\n ::CentralNumericalFluxDiffusive, Q⁺,\n D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n Q⁺.u = -Q⁻.u\n\n D⁺.∇θ = -D⁻.∇θ\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(m::HBModel, ::OceanFloorFreeSlip,\n ::Union{Rusanov, CentralGradPenalty},\n Q⁺, A⁺, n⁻, Q⁻, A⁻, t)\n A⁺.w = -A⁻.w\n\n return nothing\nend\n\n\n@inline function ocean_boundary_state!(m::HBModel, ::OceanFloorFreeSlip,\n ::CentralNumericalFluxDiffusive, Q⁺,\n D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n A⁺.w = -A⁻.w\n D⁺.∇u = -D⁻.∇u\n\n D⁺.∇θ = -D⁻.∇θ\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(m::HBModel, ::OceanFloorNoSlip,\n ::Union{Rusanov, CentralGradPenalty},\n Q⁺, A⁺, n⁻, Q⁻, A⁻, t)\n Q⁺.u = -Q⁻.u\n A⁺.w = -A⁻.w\n\n return nothing\nend\n\n\n@inline function ocean_boundary_state!(m::HBModel, ::OceanFloorNoSlip,\n ::CentralNumericalFluxDiffusive, Q⁺,\n D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n\n Q⁺.u = -Q⁻.u\n A⁺.w = -A⁻.w\n\n D⁺.∇θ = -D⁻.∇θ\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(m::HBModel, ::Union{\n OceanSurfaceNoStressNoForcing,\n OceanSurfaceStressNoForcing,\n OceanSurfaceNoStressForcing,\n OceanSurfaceStressForcing},\n ::Union{Rusanov, CentralGradPenalty},\n Q⁺, A⁺, n⁻, Q⁻, A⁻, t)\n return nothing\nend\n\n@inline function ocean_boundary_state!(m::HBModel,\n ::OceanSurfaceNoStressNoForcing,\n ::CentralNumericalFluxDiffusive,\n Q⁺, D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n D⁺.∇u = -D⁻.∇u\n\n D⁺.∇θ = -D⁻.∇θ\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(m::HBModel,\n ::OceanSurfaceStressNoForcing,\n ::CentralNumericalFluxDiffusive,\n Q⁺, D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n τ = A⁻.τ\n D⁺.∇u = -D⁻.∇u + 2 * @SMatrix [ -0 -0;\n -0 -0;\n τ / 1000 -0]\n\n D⁺.∇θ = -D⁻.∇θ\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(m::HBModel,\n ::OceanSurfaceNoStressForcing,\n ::CentralNumericalFluxDiffusive,\n Q⁺, D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n D⁺.∇u = -D⁻.∇u\n\n θ = Q⁻.θ\n θʳ = A⁻.θʳ\n λʳ = m.problem.λʳ\n D⁺.∇θ = -D⁻.∇θ + 2 * @SVector [-0, -0, λʳ * (θʳ - θ)]\n\n return nothing\nend\n\n@inline function ocean_boundary_state!(m::HBModel,\n ::OceanSurfaceStressForcing,\n ::CentralNumericalFluxDiffusive,\n Q⁺, D⁺, A⁺, n⁻, Q⁻, D⁻, A⁻, t)\n τ = A⁻.τ\n D⁺.∇u = -D⁻.∇u + 2 * @SMatrix [ -0 -0;\n -0 -0;\n τ / 1000 -0]\n\n θ = Q⁻.θ\n θʳ = A⁻.θʳ\n λʳ = m.problem.λʳ\n D⁺.∇θ = -D⁻.∇θ + 2 * @SVector [-0, -0, λʳ * (θʳ - θ)]\n\n return nothing\nend\n\nend\n", "meta": {"hexsha": "b3b2dfa27f2e5402625fa68f82c562a15f2df075", "size": 12495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Ocean/Model/HydrostaticBoussinesqModel.jl", "max_stars_repo_name": "emassoud/CLIMA", "max_stars_repo_head_hexsha": "7dcd4d6c86f01f9c27cf18f6e19f6b54d72a19ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Ocean/Model/HydrostaticBoussinesqModel.jl", "max_issues_repo_name": "emassoud/CLIMA", "max_issues_repo_head_hexsha": "7dcd4d6c86f01f9c27cf18f6e19f6b54d72a19ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Ocean/Model/HydrostaticBoussinesqModel.jl", "max_forks_repo_name": "emassoud/CLIMA", "max_forks_repo_head_hexsha": "7dcd4d6c86f01f9c27cf18f6e19f6b54d72a19ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2692307692, "max_line_length": 82, "alphanum_fraction": 0.5340536214, "num_tokens": 4340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.1686645718042868}} {"text": "export moveispseudo,\n pseudocaptures, pseudochecks, pseudoislegal, pseudomoves, pseudoquiets, pseudoevasions\n\n\nfunction is_attacked_after_move(b::Board, s::Square, m::Move)::Bool\n f = from(m)\n t = to(m)\n us = sidetomove(b)\n theirs = pieces(b, -us)\n\n # Remove captured piece, if any:\n if pieceon(b, t) != EMPTY\n theirs -= t\n elseif moveisep(b, m)\n theirs -= t - (us == WHITE ? DELTA_N : DELTA_S)\n end\n\n # Test for attacks by non-sliding pieces:\n if !isempty(pawnattacks(us, s) ∩ pawns(b) ∩ theirs)\n return true\n end\n if !isempty(knightattacks(s) ∩ knights(b) ∩ theirs)\n return true\n end\n if !isempty(kingattacks(s) ∩ kings(b) ∩ theirs)\n return true\n end\n\n # Test for attacks by sliding pieces:\n ours = pieces(b, us) - f + t\n occ = ours ∪ theirs\n\n if !isempty(bishopattacks(occ, s) ∩ bishoplike(b) ∩ theirs)\n return true\n end\n if !isempty(rookattacks(occ, s) ∩ rooklike(b) ∩ theirs)\n return true\n end\n\n # Square not attacked!\n return false\nend\n\n\n\"\"\"\n moveispseudo(b::Board, m::Move)\n\nTest whether the move `m` is pseudo-legal.\n\nThis means that the move `m` is legal except for possibly leaving the king in\ncheck.\n\n# Examples\n```julia-repl\njulia> b = @startboard e4 c5 Nf3 d6 Bb5;\n\njulia> moveispseudo(b, Move(SQ_G8, SQ_F6))\ntrue\n\njulia> moveispseudo(b, Move(SQ_B8, SQ_C6))\ntrue\n\njulia> moveispseudo(b, Move(SQ_G8, SQ_G6))\nfalse\n```\n\"\"\"\nfunction moveispseudo(b::Board, m::Move)::Bool\n f = from(m)\n t = to(m)\n us = sidetomove(b)\n them = -us\n\n # The piece on the source square must belong to the current side to move:\n pcolor(pieceon(b, f)) == us || return false\n\n # The piece on the destination square cannot belong to the current side to\n # move. TODO: Chess960 castling\n pcolor(pieceon(b, t)) ≠ us || return false\n\n p = pieceon(b, f)\n Δ = t - f\n\n if ptype(p) == PAWN\n # If the destination square is on the 1st or 8th rank, the move must be\n # a promotion:\n if t ∈ SS_RANK_1 ∪ SS_RANK_8 && !ispromotion(m)\n return false\n end\n\n # Is this a normal pawn push?\n push = us == WHITE ? DELTA_N : DELTA_S\n if Δ == push\n return pieceon(b, t) == EMPTY\n end\n\n # Is this a double pawn push?\n if Δ == 2 * push && f ∈ SS_RANK_2 ∪ SS_RANK_7\n return pieceon(b, t) == EMPTY && pieceon(b, f + push) == EMPTY\n end\n\n # Is this a capture?\n if t ∈ pawnattacks(us, f)\n return pcolor(pieceon(b, t)) == them || t == epsquare(b)\n end\n\n # Neither a pawn push nor a pawn capture -- cannot be a legal move:\n return false\n else # Non-pawn move\n # Non-pawn moves cannot be promotions:\n ispromotion(m) && return false\n\n pt = ptype(p)\n\n if pt == KNIGHT\n return t ∈ knightattacks(f)\n elseif pt == BISHOP\n return t ∈ bishopattacks(b, f)\n elseif pt == ROOK\n return t ∈ rookattacks(b, f)\n elseif pt == QUEEN\n return t ∈ queenattacks(b, f)\n elseif pt == KING\n if t ∈ kingattacks(f)\n return true\n elseif Δ == 2 * DELTA_E\n # Kingside castling\n return cancastlekingside(b, us) &&\n !ischeck(b) &&\n pieceon(b, f + DELTA_E) == EMPTY &&\n pieceon(b, t) == EMPTY\n elseif Δ == 2 * DELTA_W\n # Queenside castling\n return cancastlequeenside(b, us) &&\n !ischeck(b) &&\n pieceon(b, f + DELTA_W) == EMPTY &&\n pieceon(b, t) == EMPTY &&\n pieceon(b, f + 3 * DELTA_W) == EMPTY\n else\n return false\n end\n else\n return false\n end\n end\nend\n\n\n\"\"\"\n pseudoislegal(b::Board, m::Move)::Bool\n\nTests whether the pseudo-legal move `m` is legal.\n\n# Examples\n```julia-repl\njulia> b = @startboard e4 c5 Nf3 d6 Bb5;\n\njulia> pseudoislegal(b, Move(SQ_C8, SQ_D7))\ntrue\n\njulia> pseudoislegal(b, Move(SQ_G8, SQ_F6))\nfalse\n```\n\"\"\"\nfunction pseudoislegal(b::Board, m::Move)::Bool\n f = from(m)\n t = to(m)\n us = sidetomove(b)\n them = -us\n ksq = kingsquare(b, us)\n check = ischeck(b)\n\n # If we're not in check, any non-king, non-en-passant move of a non-pinned\n # piece is legal:\n if !check && f ∉ pinned(b) && f ≠ ksq && !moveisep(b, m)\n return true\n end\n\n # Castling moves are legal if we're not in check and both the destination\n # square and the square we're passing over are not under attack by the\n # opponent:\n if moveisshortcastle(b, m)\n return !check && !isattacked(b, f + DELTA_E, them) && !isattacked(b, t, them)\n end\n if moveislongcastle(b, m)\n return !check && !isattacked(b, f + DELTA_W, them) && !isattacked(b, t, them)\n end\n\n # For king moves, make sure the king is not under attack on the new square:\n if f == ksq\n return !is_attacked_after_move(b, t, m)\n end\n\n # When in check or when making an en passant capture, check in a slow way\n # that the move does not leave the king in check:\n if check || moveisep(b, m)\n return !is_attacked_after_move(b, ksq, m)\n end\n\n # If we are here, we are not in check, and we're moving a pinned piece. The\n # move is legal if it's moving along the ray towards/away from the friendly\n # king.\n return t ∈ squaresbetween(ksq, f) || f ∈ squaresbetween(ksq, t)\nend\n\n\nfunction addmove!(list::MoveList, f::Square, t::Square)\n push!(list, Move(f, t))\nend\n\nfunction addpromotions!(list::MoveList, f::Square, t::Square)\n for p ∈ [QUEEN, ROOK, BISHOP, KNIGHT]\n push!(list, Move(f, t, p))\n end\nend\n\nfunction addpawnmoves!(list::MoveList, target::SquareSet, Δ::SquareDelta)\n for t ∈ target\n addmove!(list, t - Δ, t)\n end\nend\n\nfunction addpawnpromotions!(list::MoveList, target::SquareSet, Δ::SquareDelta)\n for t ∈ target\n addpromotions!(list, t - Δ, t)\n end\nend\n\nfunction knight_pseudomoves(b::Board, list::MoveList, src::SquareSet, target::SquareSet)\n for f ∈ src\n for t ∈ knightattacks(f) ∩ target\n addmove!(list, f, t)\n end\n end\nend\n\nfunction bishop_pseudomoves(b::Board, list::MoveList, src::SquareSet, target::SquareSet)\n for f ∈ src\n for t ∈ bishopattacks(b, f) ∩ target\n addmove!(list, f, t)\n end\n end\nend\n\nfunction rook_pseudomoves(b::Board, list::MoveList, src::SquareSet, target::SquareSet)\n for f ∈ src\n for t ∈ rookattacks(b, f) ∩ target\n addmove!(list, f, t)\n end\n end\nend\n\nfunction queen_pseudomoves(b::Board, list::MoveList, src::SquareSet, target::SquareSet)\n for f ∈ src\n for t ∈ queenattacks(b, f) ∩ target\n addmove!(list, f, t)\n end\n end\nend\n\nfunction king_pseudomoves(b::Board, list::MoveList, src::SquareSet, target::SquareSet)\n for f ∈ src\n for t ∈ kingattacks(f) ∩ target\n addmove!(list, f, t)\n end\n end\nend\n\nfunction pawn_pseudocaptures(b::Board, list::MoveList)\n us = sidetomove(b)\n them = -us\n ps = pawns(b, us)\n\n if us == WHITE\n # Promotions (captures and non-captures)\n source1 = ps ∩ SS_RANK_7\n addpawnpromotions!(list, pawnshift_ne(source1) ∩ pieces(b, them), DELTA_NE)\n addpawnpromotions!(list, pawnshift_nw(source1) ∩ pieces(b, them), DELTA_NW)\n addpawnpromotions!(list, pawnshift_n(source1) ∩ emptysquares(b), DELTA_N)\n\n # Non-promotion captures\n source2 = ps ∩ -SS_RANK_7\n addpawnmoves!(list, pawnshift_ne(source2) ∩ pieces(b, them), DELTA_NE)\n addpawnmoves!(list, pawnshift_nw(source2) ∩ pieces(b, them), DELTA_NW)\n else\n # Promotions (captures and non-captures)\n source1 = ps ∩ SS_RANK_2\n addpawnpromotions!(list, pawnshift_se(source1) ∩ pieces(b, them), DELTA_SE)\n addpawnpromotions!(list, pawnshift_sw(source1) ∩ pieces(b, them), DELTA_SW)\n addpawnpromotions!(list, pawnshift_s(source1) ∩ emptysquares(b), DELTA_S)\n\n # Non-promotion captures\n source2 = ps ∩ -SS_RANK_2\n addpawnmoves!(list, pawnshift_se(source2) ∩ pieces(b, them), DELTA_SE)\n addpawnmoves!(list, pawnshift_sw(source2) ∩ pieces(b, them), DELTA_SW)\n end\nend\n\nfunction pawn_pseudopushes(b::Board, list::MoveList, target::SquareSet)\n us = sidetomove(b)\n ps = pawns(b, us)\n if us == WHITE\n source1 = ps ∩ -SS_RANK_7\n source2 = ps ∩ SS_RANK_2\n target1 = pawnshift_n(source1) ∩ emptysquares(b) ∩ target\n target2 =\n pawnshift_n(pawnshift_n(source2) ∩ emptysquares(b)) ∩ emptysquares(b) ∩ target\n addpawnmoves!(list, target1, DELTA_N)\n addpawnmoves!(list, target2, 2 * DELTA_N)\n else\n source1 = ps ∩ -SS_RANK_2\n source2 = ps ∩ SS_RANK_7\n target1 = pawnshift_s(source1) ∩ emptysquares(b) ∩ target\n target2 =\n pawnshift_s(pawnshift_s(source2) ∩ emptysquares(b)) ∩ emptysquares(b) ∩ target\n addpawnmoves!(list, target1, DELTA_S)\n addpawnmoves!(list, target2, 2 * DELTA_S)\n end\nend\n\n\nfunction pawn_promotion_pseudopushes(b::Board, list::MoveList, target::SquareSet)\n us = sidetomove(b)\n ps = pawns(b, us)\n if us == WHITE\n source = ps ∩ SS_RANK_7\n target = pawnshift_n(source) ∩ emptysquares(b) ∩ target\n addpawnpromotions!(list, target, DELTA_N)\n else\n source = ps ∩ SS_RANK_2\n target = pawnshift_s(source) ∩ emptysquares(b) ∩ target\n addpawnpromotions!(list, target, DELTA_N)\n end\nend\n\n\nfunction pseudo_ep_captures(b::Board, list::MoveList)\n us = sidetomove(b)\n if epsquare(b) != SQ_NONE\n for f ∈ pawnattacks(-us, epsquare(b)) ∩ pawns(b, us)\n addmove!(list, f, epsquare(b))\n end\n end\nend\n\n\nfunction pseudo_castles(b::Board, list::MoveList)\n us = sidetomove(b)\n ksq = kingsquare(b, us)\n if cancastlekingside(b, us)\n if isempty(squaresbetween(ksq, ksq + 3 * DELTA_E) ∩ occupiedsquares(b))\n addmove!(list, ksq, ksq + 2 * DELTA_E)\n end\n end\n if cancastlequeenside(b, us)\n if isempty(squaresbetween(ksq, ksq + 4 * DELTA_W) ∩ occupiedsquares(b))\n addmove!(list, ksq, ksq + 2 * DELTA_W)\n end\n end\nend\n\nfunction non_pawn_moves_to_target(b::Board, list::MoveList, target::SquareSet)\n us = sidetomove(b)\n knight_pseudomoves(b, list, knights(b, us) ∩ -pinned(b), target)\n bishop_pseudomoves(b, list, bishops(b, us), target)\n rook_pseudomoves(b, list, rooks(b, us), target)\n queen_pseudomoves(b, list, queens(b, us), target)\n king_pseudomoves(b, list, kings(b, us), target)\nend\n\nfunction pawn_discovered_checks(b::Board, list::MoveList, src::SquareSet)\n us = sidetomove(b)\n source = src ∩ pawns(b, us) ∩ -filesquares(file(kingsquare(b, -us)))\n push = us == WHITE ? DELTA_N : DELTA_S\n for f ∈ source\n if f + push ∉ (SS_RANK_1 ∪ SS_RANK_8) && pieceon(b, f + push) == EMPTY\n addmove!(list, f, f + push)\n if f ∈ SS_RANK_2 ∪ SS_RANK_7 && pieceon(b, f + 2 * push) == EMPTY\n addmove!(list, f, f + 2 * push)\n end\n end\n end\nend\n\nfunction pawn_plain_checks(b::Board, list::MoveList, src::SquareSet)\n us = sidetomove(b)\n ksq = kingsquare(b, -us)\n source = src ∩ pawns(b, us) ∩ adjacentfilesquares(ksq)\n push = us == WHITE ? DELTA_N : DELTA_S\n\n for f ∈ source\n if f + push ∉ (SS_RANK_1 ∪ SS_RANK_8) && pieceon(b, f + push) == EMPTY\n if ksq ∈ pawnattacks(us, f + push)\n addmove!(list, f, f + push)\n end\n if f ∈ (SS_RANK_2 ∪ SS_RANK_7) && pieceon(b, f + 2 * push) == EMPTY\n if ksq ∈ pawnattacks(us, f + 2 * push)\n addmove!(list, f, f + 2 * push)\n end\n end\n end\n end\nend\n\nfunction discovered_checks(b::Board, list::MoveList, source::SquareSet)\n us = sidetomove(b)\n them = -us\n ksq = kingsquare(b, them)\n target = emptysquares(b)\n\n knight_pseudomoves(b, list, knights(b, us) ∩ source, target)\n bishop_pseudomoves(b, list, bishops(b, us) ∩ source, target)\n rook_pseudomoves(b, list, rooks(b, us) ∩ source, target)\n pawn_discovered_checks(b, list, source)\n for f ∈ kings(b, us) ∩ source\n for t ∈ kingattacks(f) ∩ target\n if t ∉ squaresbetween(f, ksq) && f ∉ squaresbetween(t, ksq)\n addmove!(list, f, t)\n end\n end\n end\nend\n\nfunction plain_checks(b::Board, list::MoveList, source::SquareSet)\n us = sidetomove(b)\n them = -us\n ksq = kingsquare(b, them)\n target = emptysquares(b)\n b_check_sqs = bishopattacks(b, ksq) ∩ target\n r_check_sqs = rookattacks(b, ksq) ∩ target\n q_check_sqs = b_check_sqs ∪ r_check_sqs\n\n knight_pseudomoves(b, list, knights(b, us) ∩ source, knightattacks(ksq) ∩ target)\n bishop_pseudomoves(b, list, bishops(b, us) ∩ source, b_check_sqs)\n rook_pseudomoves(b, list, rooks(b, us) ∩ source, r_check_sqs)\n queen_pseudomoves(b, list, queens(b, us) ∩ source, q_check_sqs)\n pawn_plain_checks(b, list, source)\nend\n\n\n\"\"\"\n pseudocaptures(b::Board, list::MoveList)\n\nGenerates all pseudo-legal captures and promotions.\n\"\"\"\nfunction pseudocaptures(b::Board, list::MoveList)\n target = pieces(b, -sidetomove(b))\n pawn_pseudocaptures(b, list)\n non_pawn_moves_to_target(b, list, target)\n pseudo_ep_captures(b, list)\nend\n\n\n\"\"\"\n pseudoquiets(b::Board, list::MoveList)\n\nGenerates all pseudo-legal quiet moves.\n\nCaptures and promotions will not be included.\n\"\"\"\nfunction pseudoquiets(b::Board, list::MoveList)\n target = emptysquares(b)\n pawn_pseudopushes(b, list, target)\n non_pawn_moves_to_target(b, list, target)\n pseudo_castles(b, list)\nend\n\n\n\"\"\"\n pseudomoves(b::Board, list::MoveList)\n\nGenerates all pseudo-legal moves.\n\"\"\"\nfunction pseudomoves(b::Board, list::MoveList)\n pseudocaptures(b, list)\n pseudoquiets(b, list)\nend\n\n\n\"\"\"\n pseudoevasions(b::Board, list::MoveList)\n\nGenerates pseudo-legal moves when in check.\n\nMost obviously illegal moves are excluded.\n\"\"\"\nfunction pseudoevasions(b::Board, list::MoveList)\n us = sidetomove(b)\n\n # Generate all pseudo-legal moves for the king.\n king_pseudomoves(b, list, kings(b, us), -pieces(b, us))\n\n # Other moves are only possible if this is not a double check:\n if issingleton(b.checkers)\n ksq = kingsquare(b, us)\n chsq = first(b.checkers)\n target = squaresbetween(ksq, chsq) + chsq\n\n # Blocking pawn pushes:\n pawn_pseudopushes(b, list, target)\n pawn_promotion_pseudopushes(b, list, target)\n\n # Pawn captures of checking piece:\n for f ∈ pawnattacks(-us, chsq) ∩ pawns(b, us) ∩ -pinned(b)\n if chsq ∈ (SS_RANK_8 ∪ SS_RANK_1)\n addpromotions!(list, f, chsq)\n else\n addmove!(list, f, chsq)\n end\n end\n if chsq == epsquare(b) - (us == WHITE ? DELTA_N : DELTA_S)\n pseudo_ep_captures(b, list)\n end\n\n # Remaining pieces: Generate moves to target for non-pinned pieces.\n knight_pseudomoves(b, list, knights(b, us) ∩ -pinned(b), target)\n bishop_pseudomoves(b, list, bishops(b, us) ∩ -pinned(b), target)\n rook_pseudomoves(b, list, rooks(b, us) ∩ -pinned(b), target)\n queen_pseudomoves(b, list, queens(b, us) ∩ -pinned(b), target)\n end\nend\n\n\n\"\"\"\n pseudochecks(b::Board, list::MoveList)\n\nGenerates all pseudo-legal non-capturing checking moves.\n\"\"\"\nfunction pseudochecks(b::Board, list::MoveList)\n dc = discovered_check_candidates(b)\n discovered_checks(b, list, dc)\n plain_checks(b, list, pieces(b, sidetomove(b)) ∩ -dc)\nend\n", "meta": {"hexsha": "6f210be09fbb067eb5dfa1e4075cdb090dcba546", "size": 15874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/movegen.jl", "max_stars_repo_name": "NateSolon/Chess.jl", "max_stars_repo_head_hexsha": "f626fade5a8720aabdb6817ab20044bc13cad506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96, "max_stars_repo_stars_event_min_datetime": "2019-09-27T09:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:17:19.000Z", "max_issues_repo_path": "src/movegen.jl", "max_issues_repo_name": "NateSolon/Chess.jl", "max_issues_repo_head_hexsha": "f626fade5a8720aabdb6817ab20044bc13cad506", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2019-09-27T10:26:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:00:13.000Z", "max_forks_repo_path": "src/movegen.jl", "max_forks_repo_name": "NateSolon/Chess.jl", "max_forks_repo_head_hexsha": "f626fade5a8720aabdb6817ab20044bc13cad506", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2020-03-27T02:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T00:09:09.000Z", "avg_line_length": 29.7823639775, "max_line_length": 90, "alphanum_fraction": 0.6074083407, "num_tokens": 4831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.16858212986626178}} {"text": "#=\n# Mandelbrot Set\nIn the last tutorial we got a brief overview of the architecture of a GPU. In this tutorial We will elborate a bit more on Grid configuration and compute the mandelbrot set on the GPU.\n\n\n## Grid configuration\n\nWhen we launch a CUDA kernel we use the syntax `@cuda blocks=x threads=y f(a, b, c...)` where `f` is the function and `a, b, c...` are its arguments.\n\nThe `blocks` and `threads` options to `@cuda` are used to specify the **grid** configuration of the kernel which is being launched. \n\n`blocks` specifies the dimension and the size of the grid of blocks. This can be one, two or three dimensional. The reason for having multiple dimensions is to make it easier to express algorithms which index over two or three dimensional spaces. \n\n`threads` specifies the *cooperative thread array* (CTA). Threads in the same CTA have access to better coordination and communication utilities. CTA's can also two or three dimensional for convenient indexing.\n\nThere are restrictions related to the grid given below.\n* Maximum x-dimension of a grid of thread blocks : $2^{31} - 1$\n* Maximum y-, or z-dimension of a grid of thread blocks : $65535 (2^{16} - 1)$\n* Maximum x- or y-dimension of a CTA: $1024$\n* Maximum z-dimension of a CTA: $64$\n* Maximum number of threads per block: $1024$ \n\nNow let's go back to our SAXPY example and verify the flexibility in choosing grid configurations.\n=#\n\nusing CUDA, BenchmarkTools\n\nfunction gpu_axpy!(A, X, Y)\n ## set tid to thread rank\n tid = (blockIdx().x - 1) * blockDim().x + threadIdx().x\n tid > length(X) && return \n Y[tid] = A*X[tid] + Y[tid]\n return\nend\n\nN = 2^20\ngpu_v1 = CUDA.rand(N)\ngpu_v2 = CUDA.rand(N)\ngpu_v3 = copy(gpu_v2)\n\nα = 0.48\ngpu_v2 .+= α * gpu_v1\n\nfunction verify_grid(args, result, numthreads, numblocks = cld(N, numthreads))\n u = copy(args[3])\n\n @cuda threads=numthreads blocks=numblocks gpu_axpy!(args...)\n println(\"Explicit kernel launch with threads=$numthreads and blocks=$numblocks is correct: \"\n ,result == args[3])\n\n args[3] = u\n return \nend\n\nargs = [α, gpu_v1, gpu_v3]\n\nverify_grid(args, gpu_v2, 1024)\nverify_grid(args, gpu_v2, 1)\nverify_grid(args, gpu_v2, 33)\n\n#=\n## Occupancy\n\nThe above exercise shows the flexibility in deciding grid configuration. However this raises an important question of how the configuration affects performance. The best way to determine is to actually measure what works best in a given scenario however that may prove to be cumbersome for most workflows. Expecially while developing an application it may not be worth our time to find the optimal configuration.\n\nWhile each SM(streaming multiprocessor) might be executing 100's of threads from the perspective of the programmer, the GPU Hardware deals with `warps`. Each warp is a set of fixed number of threads(32 on NVIDIA hardware). Scheduling and issuing instructions is done at a per warp basis rather than a per thread basis. There is atleast one *warp scheduler* inside each SM whose job it is to keep the SM as busy as possible. Switching between warps(context switch) is extremely fast and essential to hide latencies such as global memory access. Whenever a warp stalls another warp is immediately switched to.\n\nComing back to out original question of how to determine the optimal grid configuration. One possible solution is to use the occupancy heurestic. $\\mbox{occupancy} = \\frac{\\mbox{active warps}}{\\mbox{maximum number of active warps}}$.\nSince each SM has a finite amount of resources. As the number of resources per thread increases, fewer of them can be concurrently executed. Occupancy can limited by register usage, shared memory and block size.\n\nThe `launch_configuration` function analyses the kernel's resource usage and suggests a configuration that maximises occupancy.\n=#\n\n@show kernel_args = cudaconvert((α, gpu_v1, gpu_v3)) # Convert to GPU friendly types\n@show kernel_tt = Tuple{Core.Typeof.(kernel_args)...}\nkernel = cufunction(gpu_axpy!, kernel_tt)\nkernel_config = launch_configuration(kernel.fun, shmem = 0)\n\n#=\nFor our example the configurator returns 20 blocks and 1024 threads. The occupancy API does not understand what our kernel is doing, it can only see the input types and the function definition. It's our job to figure out if the suggested configuration will work or not. It's best to keep the suggested block size in account while deciding the launch config.\n\nFor this example it's perhaps best to set the block size to 1024 and determine the grid size based on that.\n\n# Mandelbrot Set\n\nA popular example of mathematical visualization is the Mandelbrot set. Mathematically it is defined as the set of [complex numbers](https://simple.wikipedia.org/wiki/Complex_number) $c$ such $f_c(z) = z^2 + c$ is bounded.\n\nIn other words:\n* ‎‎$Z_0 = 0$‎\n* $Z_{n + 1} = {Z_n}^2 + c$\n* $c$ is in the mandelbrot set if the value of $Z_{n}$ is bounded.\n\nIt can be mathematically shown $|Z_n| \\leq 2.0 $ for bounded points.\n=#\n\nusing Images\n\nimg = rand(Bool, 10, 10)\nGray.(img)\n\n#-\n\ndims = (3000, 3000)\n\nmset = Array{Bool, 2}(undef, dims)\n\nfunction mandelbrot_cpu(mset::AbstractArray, dims, iterations)\n origin = CartesianIndex(div.(dims, (2, 2), RoundUp))\n for ind in CartesianIndices(mset)\n ## Compute coordinates for true canvas\n coordinates = Tuple(ind - origin) ./ 1000.\n c = ComplexF32(coordinates[1]im + coordinates[2])\n mset[ind] = mandelbrot(c, iterations)\n end\nend\n\nfunction mandelbrot(c, iterations)\n z = ComplexF32(0, 0)\n for i in 1:iterations\n z = z^2 + c\n abs(z) > 2.0 && return false\n end\n return true\nend\n\n#-\n\nmandelbrot_cpu(mset, dims, 32)\nGray.(mset)\n\n# This black and white image is no fun. To add color let's map a color to the number iterations it took $z$ to become greater than two.\n\nmset_color = Array{UInt8}(undef, dims)\nfunction mandelbrot(c, iterations)\n z = ComplexF32(0, 0)\n for i in 1:iterations\n z = z^2 + c\n abs2(z) > 4.0 && return i % UInt8\n end\n return zero(UInt8) \nend\nmandelbrot_cpu(mset_color, dims, 32)\n\n#-\n\ncmap = colormap(\"RdBu\", 32 + 1)\n\n#-\n\nmap(x -> cmap[x + 1], mset_color)\n\n#=\nOur task is to move this computation to the GPU. The tricky part with moving to the GPU is that the idexing gets tricky. We can use 1-D indexing then figure out inside the kernel what our 2-D index is or use 2-D index from the get go. \n=#\n\nmset_gpu = CuArray{UInt8}(undef, dims)\nfunction mandelbrot_gpu(mset::AbstractArray, dims, iterations)\n ind = CartesianIndex((blockIdx().y - 1)*blockDim().y + threadIdx().y,\n (blockIdx().x - 1)*blockDim().x + threadIdx().x)\n ## Check if index is valid, if not then exit\n !(ind in CartesianIndices(dims)) && return\n origin = CartesianIndex(div.(dims, (2, 2), RoundUp))\n \n ## Scale the 3000x3000 image to -1.5 to 1.5\n coordinates = Tuple(ind - origin) ./ 1000.\n c = ComplexF32(coordinates[1]im + coordinates[2]) # x + yi\n mset[ind] = mandelbrot(c, iterations)\n return\nend\n\n#-\n\nblkdim = (16, 16)\n@cuda blocks=cld.(dims, blkdim) threads=blkdim mandelbrot_gpu(mset_gpu, dims, 32)\n\n#-\n\n## copy back to host and display the same image\nmap(x -> cmap[x + 1], Array(mset_gpu))\n\n#=\n## Thread Divergence\n\nWe mentioned in the last tutorial that threads in a warp execute the same instruction. This was not the entire picture as you can guess from the mandelbrot set example. Inside the `mandelbrot` inner loop we have consecutive threads exiting at different points during iteration.\n\n\n```julia\n for i in 1:iterations\n z = z^2 + c\n abs2(z) > 4.0 && return i % UInt8\n end\n```\n\nWhen threads of the same warp are following different execution paths we call it thread divergence. Even when 1 thread out of 32 follows takes a different branch there is thread divergence.\n\nFor example\n\n```julia\nif threadIdx().x % 2 == 0\n # Do something\nelse\n # Do something else\nend\n```\n\nIn the above example threads with an even index will follow the first path and the odd indexed ones will follow the second path. Inside the GPU when a branching condition is evaluated a 32-bit mask is generated for that warp (1-bit for each lane). All lanes whose corresponding mask bit is true will be active and the remaining lanes will be idle. When execution reaches a convergence point, the mask is inverted so that all lanes which were idle become active and vice versa. This kind of an IF-ELSE branch has 50% efficiency. Even if a single thread had diverged (say condition was `threadIdx().x % 32 == 0`) we would still be at 50% efficiency. However, nesting IF-ELSE will further reduce efficiency.\n\nIn our mandelbrot example while we definitely had a lot of thread divergence it was still beneficial because threads in a warp represented physically close pixels which diverge less. \n\nAlso, note that thread divergence refers to intra-warp divergence rather than inter-warp divergence which does not matter to performance. Because doing work efficiently at the warp level is extremely important for performance we will consider it while writing algorithms. In addition there are a number of functions that work at the warp-level such as `sync_warp()`and `shfl_up_sync()`. We will explore these in the `reduction` and `prefix scan` tutorials.\n=#", "meta": {"hexsha": "debf0f4d03c21c7a2bd900ec58cc48bb3ac4df14", "size": 9258, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tutorials/introduction/02-Mandelbrot_Set.jl", "max_stars_repo_name": "Ellipse0934/CUDATutorials.jl", "max_stars_repo_head_hexsha": "c351844b7af300d2b7a7fce60738d94e166c03bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-12T14:02:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-12T14:02:20.000Z", "max_issues_repo_path": "src/tutorials/introduction/02-Mandelbrot_Set.jl", "max_issues_repo_name": "Ellipse0934/CUDATutorials.jl", "max_issues_repo_head_hexsha": "c351844b7af300d2b7a7fce60738d94e166c03bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-09-03T12:40:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-03T15:59:10.000Z", "max_forks_repo_path": "src/tutorials/introduction/02-Mandelbrot_Set.jl", "max_forks_repo_name": "Ellipse0934/CUDATutorials.jl", "max_forks_repo_head_hexsha": "c351844b7af300d2b7a7fce60738d94e166c03bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-23T04:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T19:54:03.000Z", "avg_line_length": 43.8767772512, "max_line_length": 704, "alphanum_fraction": 0.7312594513, "num_tokens": 2408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.16812285359339496}} {"text": "# MIT license\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# See LICENSE in the project root for full license information.\n\nexport CARGILLE, EYE\n\n# all other glasses should follow the format below, new glasses must be added to OTHER_GLASSES and OTHER_GLASS_NAMES where the index in the array matches the numeric part of the GlassID\n\nmodule CARGILLE\nusing ..AGFFileReader: Glass, GlassID, OTHER\n\nconst OG0608 = Glass(GlassID(OTHER, 1), -2, 1.4451400, 0.0043176, -1.80659e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.0009083144750540808, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.008, -1.0, -1.0, 800.0, -1.0, 0, -1.0, [(0.32, 0.03, 10.0), (0.365, 0.16, 100.0), (0.4047, 0.40, 100.0), (0.480, 0.71, 100.0), (0.4861, 0.72, 100.0), (0.5461, 0.80, 100.0), (0.5893, 0.90, 100.0), (0.6328, 0.92, 100.0), (0.6439, 0.95, 100.0), (0.6563, 0.96, 100.0), (0.6943, 0.99, 100.0), (0.840, 0.99, 100.0), (0.10648, 0.74, 100.0), (0.1300, 0.39, 100.0), (0.1550, 0.16, 100.0)], 1.457518, -1.0, -1.0, 0, 57.18978, 0, 0.878, -1)\nconst OG0607 = Glass(GlassID(OTHER, 2), -2, 1.44503, 0.0044096, -2.85878e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.0009083144750540808, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.008, -1.0, -1.0, 700.0, -1.0, 0, -1.0, [(0.32, 0.15, 10.0), (0.365, 0.12, 100.0), (0.4047, 0.42, 100.0), (0.480, 0.78, 100.0), (0.4861, 0.79, 100.0), (0.5461, 0.86, 100.0), (0.5893, 0.90, 100.0), (0.6328, 0.92, 100.0), (0.6439, 0.90, 100.0), (0.6563, 0.92, 100.0), (0.6943, 0.98, 100.0), (0.840, 0.99, 100.0), (0.10648, 0.61, 100.0), (0.1300, 0.39, 100.0), (0.1550, 0.11, 100.0)], 1.457587, -1.0, -1.0, 0, 57.19833, 0, 0.878, -1)\nconst OG081160 = Glass(GlassID(OTHER, 3), -2, 1.49614, 0.00692199, -8.07052e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.000885983052189022, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.014, -1.0, -1.0, 700.0, -1.0, 0, -1.0, [(0.32, 0.04, 100.0), (0.365, 0.13, 100.0), (0.4047, 0.26, 100.0), (0.480, 0.48, 100.0), (0.4861, 0.49, 100.0), (0.5461, 0.60, 100.0), (0.5893, 0.68, 100.0), (0.6328, 0.71, 100.0), (0.6439, 0.73, 100.0), (0.6563, 0.74, 100.0), (0.6943, 0.76, 100.0), (0.840, 0.83, 100.0), (0.10648, 0.86, 100.0), (0.1300, 0.89, 100.0), (0.1550, 0.90, 100.0)], 1.515549, -1.0, -1.0, 0, 36.82493, 0, 1.11, -1)\n\nend\n\nmodule EYE\nusing ..AGFFileReader: Glass, GlassID, OTHER\n\n\"\"\" EYE.AQUEOUS\n```\nID: OTHER:4\nRI @ 587nm: 1.336981\nAbbe Number: 52.658991\nΔPgF: 0.0\nTCE (÷1e-6): 0.0\nDensity: 1.0g/m³\nValid wavelengths: 0.38μm to 0.78μm\nReference Temp: 20.0°C\n```\n\"\"\"\nconst AQUEOUS = Glass(GlassID(OTHER, 4), 5, 1.32107278, 0.00847113739, 0.000231825063, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.336981, -1.0, -1.0, 0, 52.658991, 0, 1.0, 0)\n\"\"\" EYE.LENS\n```\nID: OTHER:5\nRI @ 587nm: 1.419976\nAbbe Number: 51.226142\nΔPgF: 0.0\nTCE (÷1e-6): 0.0\nDensity: 1.0g/m³\nValid wavelengths: 0.38μm to 0.78μm\nReference Temp: 20.0°C\n```\n\"\"\"\nconst LENS = Glass(GlassID(OTHER, 5), 5, 1.4014679, 0.00938901135, 0.000393175776, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.419976, -1.0, -1.0, 0, 51.226142, 0, 1.0, 0)\n\"\"\" EYE.CORNEA\n```\nID: OTHER:6\nRI @ 587nm: 1.376981\nAbbe Number: 56.279936\nΔPgF: 0.0\nTCE (÷1e-6): 0.0\nDensity: 1.0g/m³\nValid wavelengths: 0.38μm to 0.78μm\nReference Temp: 20.0°C\n```\n\"\"\"\nconst CORNEA = Glass(GlassID(OTHER, 6), 5, 1.36313817, 0.00667127181, 0.000386916734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.376981, -1.0, -1.0, 0, 56.279936, 0, 1.0, 0)\n\"\"\" EYE.VITREOUS\n```\nID: OTHER:7\nRI @ 587nm: 1.335982\nAbbe Number: 53.342173\nΔPgF: 0.0\nTCE (÷1e-6): 0.0\nDensity: 1.0g/m³\nValid wavelengths: 0.38μm to 0.78μm\nReference Temp: 20.0°C\n```\n\"\"\"\nconst VITREOUS = Glass(GlassID(OTHER, 7), 5, 1.32238376, 0.00672767909, 0.000333967702, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.38, 0.78, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 0.0, -1.0, -1.0, 0.0, -1.0, 0, -1.0, [(0.32, 0.16, 25.0), (0.334, 0.42, 25.0), (0.35, 0.7, 25.0), (0.365, 0.85, 25.0), (0.37, 0.88, 25.0), (0.38, 0.92, 25.0), (0.39, 0.95, 25.0), (0.4, 0.963, 25.0), (0.42, 0.977, 25.0), (0.46, 0.988, 25.0), (0.5, 0.993, 25.0), (0.66, 0.996, 25.0), (1.06, 0.996, 25.0), (1.529, 0.975, 25.0), (1.9701, 0.93, 25.0), (2.325, 0.66, 25.0)], 1.335982, -1.0, -1.0, 0, 53.342173, 0, 1.0, 0)\n\nend\n\nconst OTHER_GLASSES = [CARGILLE.OG0607, CARGILLE.OG0608, CARGILLE.OG081160, EYE.AQUEOUS, EYE.LENS, EYE.CORNEA, EYE.VITREOUS]\nconst OTHER_GLASS_NAMES = [\"CARGILLE.OG0607\", \"CARGILLE.OG0608\", \"CARGILLE.OG081160\", \"EYE.AQUEOUS\", \"EYE.LENS\", \"EYE.CORNEA\", \"EYE.VITREOUS\"]\n", "meta": {"hexsha": "8a3ae8ad0544814f883357322fa7ec0a0109d257", "size": 6113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/data/jl/OTHER.jl", "max_stars_repo_name": "rambunctiousapple/GlassCat", "max_stars_repo_head_hexsha": "5e10affbed57311088f78f461e8f83f6f5874c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/data/jl/OTHER.jl", "max_issues_repo_name": "rambunctiousapple/GlassCat", "max_issues_repo_head_hexsha": "5e10affbed57311088f78f461e8f83f6f5874c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-12T17:20:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-12T17:20:35.000Z", "max_forks_repo_path": "src/data/jl/OTHER.jl", "max_forks_repo_name": "rambunctiousapple/GlassCat", "max_forks_repo_head_hexsha": "5e10affbed57311088f78f461e8f83f6f5874c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-29T23:16:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T23:16:46.000Z", "avg_line_length": 78.3717948718, "max_line_length": 612, "alphanum_fraction": 0.5218387044, "num_tokens": 3691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.16803640406268974}} {"text": "module SrtmKgb29\n # KURUCZ\n sfluxref = [1.32880 , 2.14018 , 1.97612 , 1.79000 ,1.51242 , 1.22977 , 1.06052 , 0.800996 ,0.748053 , 8.64369e-02, 7.10675e-02, 5.62425e-02,4.46988e-02, 3.07441e-02, 1.16728e-02, 1.65573e-03]\n\n absco2 = [2.90073e-06, 2.12382e-05, 1.03032e-04, 1.86481e-04,4.31997e-04, 6.08238e-04, 2.17603e-03, 4.64479e-02,2.96956 , 14.9569 , 28.4831 , 61.3998 ,164.129 , 832.282 , 4995.02 , 12678.1 ]\n \n absh2o = [2.99508e-04, 3.95012e-03, 1.49316e-02, 3.24384e-02,6.92879e-02, 0.123523 , 0.360985 , 1.86434 ,10.38157 , 0.214129 , 0.213914 , 0.212781 ,0.215562 , 0.218087 , 0.220918 , 0.218546 ]\n \n # Rayleigh extinction coefficient at v = 2200 cm-1.\n rayl = 9.30e-11\n\n layreffr = 49\n\n # ------------------------------------------------------------------\n\n # The array KA contains absorption coefs at the 16 chosen g-values \n # for a range of pressure levels> ~100mb:and binary:temperatures\n # species parameters (see taumol.f for definition). The first \n # index in the array, JS, runs from 1 to 9, and corresponds to \n # different values of the binary species parameter. For instance, \n # JS=1 refers to dry air, JS = 2 corresponds to the paramter value 1/8, \n # JS = 3 corresponds to the parameter value 2/8, etc. The second index\n # in the array, JT, which runs from 1 to 5, corresponds to different\n # temperatures. More specifically, JT = 3 means that the data are for\n # the reference temperature TREF for this pressure level:JT = 2 refers\n # to TREF-15, JT = 1 is for TREF-30:and JT = 5:JT = 4 is for TREF+15\n # is for TREF+30. The third index:runs from 1 to 13 and refers:JP\n # to the JPth reference pressure level (see taumol.f for these levels\n # in mb). The fourth index, IG, goes from 1 to 16, and indicates\n # which g-interval the absorption coefficients are for.\n # -----------------------------------------------------------------\n ka = zeros(5,13,16)\n ka[:, 1, 1] = [0.11565e-03,0.10123e-03,0.90804e-04,0.82282e-04,0.71083e-04]\n ka[:, 2, 1] = [0.96434e-04,0.82830e-04,0.72366e-04,0.61803e-04,0.52497e-04]\n ka[:, 3, 1] = [0.64539e-04,0.56659e-04,0.46605e-04,0.39815e-04,0.37118e-04]\n ka[:, 4, 1] = [0.34417e-04,0.27113e-04,0.25362e-04,0.30345e-04,0.36275e-04]\n ka[:, 5, 1] = [0.12260e-04,0.15856e-04,0.20834e-04,0.27363e-04,0.36114e-04]\n ka[:, 6, 1] = [0.10221e-04,0.14598e-04,0.19695e-04,0.25976e-04,0.33702e-04]\n ka[:, 7, 1] = [0.97563e-05,0.13809e-04,0.20231e-04,0.27238e-04,0.36110e-04]\n ka[:, 8, 1] = [0.14062e-04,0.19587e-04,0.27069e-04,0.36937e-04,0.49415e-04]\n ka[:, 9, 1] = [0.36371e-04,0.48122e-04,0.61586e-04,0.77647e-04,0.99897e-04]\n ka[:,10, 1] = [0.99203e-04,0.12842e-03,0.16588e-03,0.20834e-03,0.26000e-03]\n ka[:,11, 1] = [0.13233e-03,0.17318e-03,0.22059e-03,0.28904e-03,0.36062e-03]\n ka[:,12, 1] = [0.13379e-03,0.17484e-03,0.23687e-03,0.30286e-03,0.37504e-03]\n ka[:,13, 1] = [0.11740e-03,0.15667e-03,0.20962e-03,0.26768e-03,0.33485e-03]\n ka[:, 1, 2] = [0.10246e-03,0.10450e-03,0.97383e-04,0.96398e-04,0.10549e-03]\n ka[:, 2, 2] = [0.10589e-03,0.10240e-03,0.95801e-04,0.98509e-04,0.11993e-03]\n ka[:, 3, 2] = [0.94054e-04,0.87009e-04,0.10941e-03,0.13486e-03,0.15918e-03]\n ka[:, 4, 2] = [0.11883e-03,0.14236e-03,0.16636e-03,0.18235e-03,0.19785e-03]\n ka[:, 5, 2] = [0.17800e-03,0.19347e-03,0.20977e-03,0.22730e-03,0.25111e-03]\n ka[:, 6, 2] = [0.22243e-03,0.24157e-03,0.26567e-03,0.28549e-03,0.30723e-03]\n ka[:, 7, 2] = [0.29248e-03,0.32242e-03,0.34635e-03,0.37915e-03,0.40803e-03]\n ka[:, 8, 2] = [0.43386e-03,0.48611e-03,0.52681e-03,0.56812e-03,0.60642e-03]\n ka[:, 9, 2] = [0.89109e-03,0.10345e-02,0.11794e-02,0.13045e-02,0.14303e-02]\n ka[:,10, 2] = [0.21538e-02,0.24459e-02,0.27329e-02,0.30932e-02,0.35253e-02]\n ka[:,11, 2] = [0.29272e-02,0.32676e-02,0.36353e-02,0.40062e-02,0.45441e-02]\n ka[:,12, 2] = [0.30762e-02,0.34365e-02,0.38146e-02,0.41556e-02,0.47164e-02]\n ka[:,13, 2] = [0.27808e-02,0.31114e-02,0.34383e-02,0.37954e-02,0.42576e-02]\n ka[:, 1, 3] = [0.24042e-03,0.32719e-03,0.44370e-03,0.56836e-03,0.70357e-03]\n ka[:, 2, 3] = [0.23303e-03,0.31901e-03,0.41926e-03,0.52400e-03,0.62365e-03]\n ka[:, 3, 3] = [0.35050e-03,0.42158e-03,0.47490e-03,0.53390e-03,0.60411e-03]\n ka[:, 4, 3] = [0.49954e-03,0.53067e-03,0.56338e-03,0.60859e-03,0.66569e-03]\n ka[:, 5, 3] = [0.66908e-03,0.69727e-03,0.72898e-03,0.76756e-03,0.80358e-03]\n ka[:, 6, 3] = [0.88634e-03,0.92853e-03,0.96856e-03,0.10101e-02,0.10556e-02]\n ka[:, 7, 3] = [0.11659e-02,0.12355e-02,0.13238e-02,0.13889e-02,0.14491e-02]\n ka[:, 8, 3] = [0.17485e-02,0.18223e-02,0.19411e-02,0.20705e-02,0.22025e-02]\n ka[:, 9, 3] = [0.42442e-02,0.43561e-02,0.45061e-02,0.47505e-02,0.50358e-02]\n ka[:,10, 3] = [0.10940e-01,0.11499e-01,0.11906e-01,0.12570e-01,0.12803e-01]\n ka[:,11, 3] = [0.14287e-01,0.15010e-01,0.15581e-01,0.16054e-01,0.16609e-01]\n ka[:,12, 3] = [0.14856e-01,0.15546e-01,0.16074e-01,0.16478e-01,0.17057e-01]\n ka[:,13, 3] = [0.13257e-01,0.13834e-01,0.14155e-01,0.14723e-01,0.15095e-01]\n ka[:, 1, 4] = [0.24391e-02,0.28720e-02,0.33497e-02,0.38926e-02,0.45054e-02]\n ka[:, 2, 4] = [0.22506e-02,0.26004e-02,0.30002e-02,0.34490e-02,0.39579e-02]\n ka[:, 3, 4] = [0.22153e-02,0.25711e-02,0.29320e-02,0.33330e-02,0.37728e-02]\n ka[:, 4, 4] = [0.22483e-02,0.25445e-02,0.28745e-02,0.32484e-02,0.36554e-02]\n ka[:, 5, 4] = [0.23388e-02,0.25985e-02,0.28914e-02,0.32377e-02,0.36113e-02]\n ka[:, 6, 4] = [0.24669e-02,0.26579e-02,0.28834e-02,0.31538e-02,0.34593e-02]\n ka[:, 7, 4] = [0.32536e-02,0.33413e-02,0.34375e-02,0.35905e-02,0.38010e-02]\n ka[:, 8, 4] = [0.51228e-02,0.51967e-02,0.52820e-02,0.53446e-02,0.53797e-02]\n ka[:, 9, 4] = [0.13029e-01,0.13065e-01,0.12891e-01,0.12848e-01,0.12777e-01]\n ka[:,10, 4] = [0.29911e-01,0.30117e-01,0.28340e-01,0.27321e-01,0.27485e-01]\n ka[:,11, 4] = [0.36663e-01,0.36877e-01,0.34688e-01,0.33004e-01,0.32437e-01]\n ka[:,12, 4] = [0.37282e-01,0.37775e-01,0.34910e-01,0.33463e-01,0.33074e-01]\n ka[:,13, 4] = [0.33412e-01,0.32961e-01,0.30323e-01,0.29437e-01,0.29572e-01]\n ka[:, 1, 5] = [0.20792e-01,0.22727e-01,0.25207e-01,0.27650e-01,0.29866e-01]\n ka[:, 2, 5] = [0.17515e-01,0.19421e-01,0.21509e-01,0.23389e-01,0.25418e-01]\n ka[:, 3, 5] = [0.14912e-01,0.16535e-01,0.18159e-01,0.19873e-01,0.21718e-01]\n ka[:, 4, 5] = [0.13498e-01,0.14786e-01,0.16253e-01,0.17812e-01,0.19494e-01]\n ka[:, 5, 5] = [0.12840e-01,0.13983e-01,0.15257e-01,0.16617e-01,0.18015e-01]\n ka[:, 6, 5] = [0.12557e-01,0.13714e-01,0.14939e-01,0.16145e-01,0.17356e-01]\n ka[:, 7, 5] = [0.11839e-01,0.12951e-01,0.14090e-01,0.15237e-01,0.16396e-01]\n ka[:, 8, 5] = [0.13190e-01,0.13998e-01,0.14783e-01,0.15641e-01,0.16632e-01]\n ka[:, 9, 5] = [0.24479e-01,0.24660e-01,0.25206e-01,0.25571e-01,0.26098e-01]\n ka[:,10, 5] = [0.62373e-01,0.60241e-01,0.61372e-01,0.61530e-01,0.60978e-01]\n ka[:,11, 5] = [0.76394e-01,0.73727e-01,0.74701e-01,0.75649e-01,0.75608e-01]\n ka[:,12, 5] = [0.76656e-01,0.73608e-01,0.75610e-01,0.76362e-01,0.76033e-01]\n ka[:,13, 5] = [0.66025e-01,0.64890e-01,0.66873e-01,0.66992e-01,0.66685e-01]\n ka[:, 1, 6] = [0.99799e-01,0.10479e+00,0.10918e+00,0.11347e+00,0.11767e+00]\n ka[:, 2, 6] = [0.87946e-01,0.91820e-01,0.95208e-01,0.99071e-01,0.10286e+00]\n ka[:, 3, 6] = [0.76753e-01,0.80377e-01,0.84204e-01,0.87924e-01,0.91370e-01]\n ka[:, 4, 6] = [0.67002e-01,0.70630e-01,0.73736e-01,0.76764e-01,0.79671e-01]\n ka[:, 5, 6] = [0.58933e-01,0.61857e-01,0.64756e-01,0.67323e-01,0.69871e-01]\n ka[:, 6, 6] = [0.53143e-01,0.55386e-01,0.57507e-01,0.59715e-01,0.62263e-01]\n ka[:, 7, 6] = [0.50856e-01,0.52603e-01,0.54414e-01,0.56230e-01,0.58483e-01]\n ka[:, 8, 6] = [0.50528e-01,0.52598e-01,0.54634e-01,0.56710e-01,0.58872e-01]\n ka[:, 9, 6] = [0.64616e-01,0.65915e-01,0.67210e-01,0.68742e-01,0.70092e-01]\n ka[:,10, 6] = [0.11509e+00,0.11448e+00,0.11368e+00,0.11348e+00,0.11401e+00]\n ka[:,11, 6] = [0.14266e+00,0.13997e+00,0.13810e+00,0.13688e+00,0.13622e+00]\n ka[:,12, 6] = [0.14464e+00,0.14198e+00,0.13915e+00,0.13789e+00,0.13781e+00]\n ka[:,13, 6] = [0.12550e+00,0.12328e+00,0.12173e+00,0.12127e+00,0.12078e+00]\n ka[:, 1, 7] = [0.30825e+00,0.31119e+00,0.31335e+00,0.31641e+00,0.32024e+00]\n ka[:, 2, 7] = [0.28100e+00,0.28660e+00,0.29192e+00,0.29680e+00,0.30014e+00]\n ka[:, 3, 7] = [0.26374e+00,0.27129e+00,0.27887e+00,0.28626e+00,0.29478e+00]\n ka[:, 4, 7] = [0.24539e+00,0.25325e+00,0.26070e+00,0.26955e+00,0.27794e+00]\n ka[:, 5, 7] = [0.21737e+00,0.22642e+00,0.23531e+00,0.24408e+00,0.25322e+00]\n ka[:, 6, 7] = [0.19066e+00,0.19913e+00,0.20834e+00,0.21782e+00,0.22698e+00]\n ka[:, 7, 7] = [0.17386e+00,0.18325e+00,0.19211e+00,0.20024e+00,0.20881e+00]\n ka[:, 8, 7] = [0.17625e+00,0.18236e+00,0.18905e+00,0.19574e+00,0.20193e+00]\n ka[:, 9, 7] = [0.21820e+00,0.22416e+00,0.22986e+00,0.23737e+00,0.24518e+00]\n ka[:,10, 7] = [0.33529e+00,0.34302e+00,0.35397e+00,0.36397e+00,0.37339e+00]\n ka[:,11, 7] = [0.38474e+00,0.39863e+00,0.41168e+00,0.42115e+00,0.42917e+00]\n ka[:,12, 7] = [0.38499e+00,0.39580e+00,0.40497e+00,0.41279e+00,0.42045e+00]\n ka[:,13, 7] = [0.34291e+00,0.35180e+00,0.35970e+00,0.36697e+00,0.37460e+00]\n ka[:, 1, 8] = [0.87131e+00,0.87876e+00,0.88509e+00,0.89061e+00,0.89432e+00]\n ka[:, 2, 8] = [0.78963e+00,0.79236e+00,0.79978e+00,0.80959e+00,0.82163e+00]\n ka[:, 3, 8] = [0.82479e+00,0.82842e+00,0.83069e+00,0.83679e+00,0.84334e+00]\n ka[:, 4, 8] = [0.90877e+00,0.91962e+00,0.92466e+00,0.93139e+00,0.93904e+00]\n ka[:, 5, 8] = [0.97131e+00,0.99301e+00,0.10095e+01,0.10270e+01,0.10371e+01]\n ka[:, 6, 8] = [0.96984e+00,0.10040e+01,0.10393e+01,0.10670e+01,0.10990e+01]\n ka[:, 7, 8] = [0.95686e+00,0.10029e+01,0.10449e+01,0.10923e+01,0.11334e+01]\n ka[:, 8, 8] = [0.97227e+00,0.10380e+01,0.11014e+01,0.11624e+01,0.12218e+01]\n ka[:, 9, 8] = [0.12290e+01,0.13071e+01,0.14005e+01,0.15005e+01,0.15980e+01]\n ka[:,10, 8] = [0.17996e+01,0.19304e+01,0.20752e+01,0.22219e+01,0.23814e+01]\n ka[:,11, 8] = [0.19289e+01,0.20656e+01,0.22166e+01,0.23715e+01,0.25386e+01]\n ka[:,12, 8] = [0.18429e+01,0.19765e+01,0.21175e+01,0.22722e+01,0.24239e+01]\n ka[:,13, 8] = [0.16420e+01,0.17464e+01,0.18635e+01,0.19773e+01,0.21012e+01]\n ka[:, 1, 9] = [0.39892e+01,0.40153e+01,0.40324e+01,0.40465e+01,0.40524e+01]\n ka[:, 2, 9] = [0.38871e+01,0.39035e+01,0.39123e+01,0.39056e+01,0.38966e+01]\n ka[:, 3, 9] = [0.37883e+01,0.37950e+01,0.38080e+01,0.37991e+01,0.37826e+01]\n ka[:, 4, 9] = [0.37778e+01,0.37663e+01,0.37745e+01,0.37709e+01,0.37556e+01]\n ka[:, 5, 9] = [0.38757e+01,0.38404e+01,0.38539e+01,0.39228e+01,0.39777e+01]\n ka[:, 6, 9] = [0.40990e+01,0.41407e+01,0.41745e+01,0.42258e+01,0.42574e+01]\n ka[:, 7, 9] = [0.46288e+01,0.46726e+01,0.47096e+01,0.47165e+01,0.47374e+01]\n ka[:, 8, 9] = [0.58432e+01,0.58474e+01,0.58608e+01,0.58935e+01,0.59261e+01]\n ka[:, 9, 9] = [0.88685e+01,0.88567e+01,0.88137e+01,0.87653e+01,0.87262e+01]\n ka[:,10, 9] = [0.10455e+02,0.10242e+02,0.10004e+02,0.97643e+01,0.95067e+01]\n ka[:,11, 9] = [0.10240e+02,0.99968e+01,0.97347e+01,0.94750e+01,0.92006e+01]\n ka[:,12, 9] = [0.10401e+02,0.10165e+02,0.99240e+01,0.96656e+01,0.94112e+01]\n ka[:,13, 9] = [0.10764e+02,0.10580e+02,0.10381e+02,0.10188e+02,0.99802e+01]\n ka[:, 1,10] = [0.10712e+02,0.10575e+02,0.10581e+02,0.10556e+02,0.10575e+02]\n ka[:, 2,10] = [0.11144e+02,0.11109e+02,0.11034e+02,0.11107e+02,0.11138e+02]\n ka[:, 3,10] = [0.12257e+02,0.12112e+02,0.11992e+02,0.11951e+02,0.12031e+02]\n ka[:, 4,10] = [0.13040e+02,0.13085e+02,0.12882e+02,0.12756e+02,0.12737e+02]\n ka[:, 5,10] = [0.13809e+02,0.13771e+02,0.13452e+02,0.12567e+02,0.12086e+02]\n ka[:, 6,10] = [0.14608e+02,0.13942e+02,0.13365e+02,0.13494e+02,0.13762e+02]\n ka[:, 7,10] = [0.14665e+02,0.14685e+02,0.15121e+02,0.15602e+02,0.15768e+02]\n ka[:, 8,10] = [0.15612e+02,0.16507e+02,0.16644e+02,0.16706e+02,0.16696e+02]\n ka[:, 9,10] = [0.15405e+02,0.15874e+02,0.16716e+02,0.17957e+02,0.17859e+02]\n ka[:,10,10] = [0.19406e+00,0.17932e+00,0.16660e+00,0.15558e+00,0.14589e+00]\n ka[:,11,10] = [0.27650e+00,0.25556e+00,0.23727e+00,0.22182e+00,0.20805e+00]\n ka[:,12,10] = [0.29298e+00,0.27044e+00,0.25162e+00,0.23497e+00,0.22076e+00]\n ka[:,13,10] = [0.24883e+00,0.22985e+00,0.21413e+00,0.20012e+00,0.18795e+00]\n ka[:, 1,11] = [0.13650e+02,0.13767e+02,0.13771e+02,0.13650e+02,0.13663e+02]\n ka[:, 2,11] = [0.15146e+02,0.15253e+02,0.15272e+02,0.15152e+02,0.15138e+02]\n ka[:, 3,11] = [0.16834e+02,0.17107e+02,0.17158e+02,0.17187e+02,0.17057e+02]\n ka[:, 4,11] = [0.19191e+02,0.19144e+02,0.19155e+02,0.19247e+02,0.19292e+02]\n ka[:, 5,11] = [0.20953e+02,0.21248e+02,0.21186e+02,0.21027e+02,0.20703e+02]\n ka[:, 6,11] = [0.22592e+02,0.22192e+02,0.22056e+02,0.20972e+02,0.19910e+02]\n ka[:, 7,11] = [0.24652e+02,0.23679e+02,0.22339e+02,0.21302e+02,0.21697e+02]\n ka[:, 8,11] = [0.22508e+02,0.20438e+02,0.20163e+02,0.20628e+02,0.20954e+02]\n ka[:, 9,11] = [0.10264e+02,0.85820e+01,0.65270e+01,0.38883e+01,0.27974e+01]\n ka[:,10,11] = [0.19324e+00,0.17913e+00,0.16619e+00,0.15516e+00,0.14524e+00]\n ka[:,11,11] = [0.27573e+00,0.25425e+00,0.23627e+00,0.22036e+00,0.20639e+00]\n ka[:,12,11] = [0.29224e+00,0.26998e+00,0.25055e+00,0.23380e+00,0.21908e+00]\n ka[:,13,11] = [0.24964e+00,0.23056e+00,0.21391e+00,0.19980e+00,0.18698e+00]\n ka[:, 1,12] = [0.17721e+02,0.17805e+02,0.17752e+02,0.17857e+02,0.17872e+02]\n ka[:, 2,12] = [0.20222e+02,0.20161e+02,0.20267e+02,0.20335e+02,0.20254e+02]\n ka[:, 3,12] = [0.23717e+02,0.23414e+02,0.23571e+02,0.23552e+02,0.23687e+02]\n ka[:, 4,12] = [0.26876e+02,0.26972e+02,0.27155e+02,0.26947e+02,0.27025e+02]\n ka[:, 5,12] = [0.30213e+02,0.29978e+02,0.30226e+02,0.30477e+02,0.30329e+02]\n ka[:, 6,12] = [0.33660e+02,0.33482e+02,0.33159e+02,0.32959e+02,0.32299e+02]\n ka[:, 7,12] = [0.35893e+02,0.35649e+02,0.35067e+02,0.34565e+02,0.32437e+02]\n ka[:, 8,12] = [0.33426e+02,0.33323e+02,0.31984e+02,0.29587e+02,0.27505e+02]\n ka[:, 9,12] = [0.46633e-01,0.43205e-01,0.40562e-01,0.38133e-01,0.35900e-01]\n ka[:,10,12] = [0.19421e+00,0.18024e+00,0.16872e+00,0.15815e+00,0.14837e+00]\n ka[:,11,12] = [0.27315e+00,0.25480e+00,0.23771e+00,0.22191e+00,0.20780e+00]\n ka[:,12,12] = [0.29027e+00,0.26969e+00,0.25017e+00,0.23314e+00,0.21774e+00]\n ka[:,13,12] = [0.24833e+00,0.22943e+00,0.21278e+00,0.19800e+00,0.18543e+00]\n ka[:, 1,13] = [0.29672e+02,0.29291e+02,0.29191e+02,0.29170e+02,0.29116e+02]\n ka[:, 2,13] = [0.24713e+02,0.24965e+02,0.25039e+02,0.25355e+02,0.25650e+02]\n ka[:, 3,13] = [0.30510e+02,0.31166e+02,0.30663e+02,0.31021e+02,0.30901e+02]\n ka[:, 4,13] = [0.38695e+02,0.38922e+02,0.38741e+02,0.39204e+02,0.38826e+02]\n ka[:, 5,13] = [0.45118e+02,0.44337e+02,0.43664e+02,0.43267e+02,0.43524e+02]\n ka[:, 6,13] = [0.34652e+02,0.35182e+02,0.35339e+02,0.35340e+02,0.35899e+02]\n ka[:, 7,13] = [0.18801e+02,0.18598e+02,0.18855e+02,0.18819e+02,0.19052e+02]\n ka[:, 8,13] = [0.12297e-01,0.11425e-01,0.10670e-01,0.99994e-02,0.94139e-02]\n ka[:, 9,13] = [0.46821e-01,0.43361e-01,0.40368e-01,0.37752e-01,0.35493e-01]\n ka[:,10,13] = [0.19817e+00,0.18303e+00,0.17002e+00,0.15883e+00,0.14933e+00]\n ka[:,11,13] = [0.28145e+00,0.25995e+00,0.24181e+00,0.22660e+00,0.21326e+00]\n ka[:,12,13] = [0.29510e+00,0.27294e+00,0.25519e+00,0.23947e+00,0.22551e+00]\n ka[:,13,13] = [0.24830e+00,0.23074e+00,0.21556e+00,0.20226e+00,0.19029e+00]\n ka[:, 1,14] = [0.47168e+02,0.46890e+02,0.46612e+02,0.46353e+02,0.46088e+02]\n ka[:, 2,14] = [0.47771e+02,0.46980e+02,0.46445e+02,0.45828e+02,0.45437e+02]\n ka[:, 3,14] = [0.42946e+02,0.42652e+02,0.43791e+02,0.43237e+02,0.44104e+02]\n ka[:, 4,14] = [0.30957e+02,0.30098e+02,0.30055e+02,0.29555e+02,0.29902e+02]\n ka[:, 5,14] = [0.28397e+01,0.38572e+01,0.42906e+01,0.47091e+01,0.48135e+01]\n ka[:, 6,14] = [0.36978e-02,0.34591e-02,0.32524e-02,0.30649e-02,0.29018e-02]\n ka[:, 7,14] = [0.61733e-02,0.57589e-02,0.53925e-02,0.50742e-02,0.47835e-02]\n ka[:, 8,14] = [0.12390e-01,0.11526e-01,0.10766e-01,0.10096e-01,0.95010e-02]\n ka[:, 9,14] = [0.47105e-01,0.43648e-01,0.40665e-01,0.38054e-01,0.35722e-01]\n ka[:,10,14] = [0.19915e+00,0.18412e+00,0.17099e+00,0.15957e+00,0.14948e+00]\n ka[:,11,14] = [0.28280e+00,0.26124e+00,0.24266e+00,0.22645e+00,0.21214e+00]\n ka[:,12,14] = [0.29891e+00,0.27613e+00,0.25648e+00,0.23927e+00,0.22423e+00]\n ka[:,13,14] = [0.25421e+00,0.23484e+00,0.21809e+00,0.20347e+00,0.19057e+00]\n ka[:, 1,15] = [0.64994e+02,0.64283e+02,0.63755e+02,0.63407e+02,0.63287e+02]\n ka[:, 2,15] = [0.78266e+02,0.77364e+02,0.76722e+02,0.76285e+02,0.75992e+02]\n ka[:, 3,15] = [0.41710e+02,0.38379e+02,0.35076e+02,0.35418e+02,0.33306e+02]\n ka[:, 4,15] = [0.14170e-02,0.13401e-02,0.12716e-02,0.12073e-02,0.11535e-02]\n ka[:, 5,15] = [0.23659e-02,0.22261e-02,0.21042e-02,0.19950e-02,0.18970e-02]\n ka[:, 6,15] = [0.37432e-02,0.35105e-02,0.33006e-02,0.31222e-02,0.29521e-02]\n ka[:, 7,15] = [0.62408e-02,0.58258e-02,0.54782e-02,0.51594e-02,0.48767e-02]\n ka[:, 8,15] = [0.12522e-01,0.11652e-01,0.10922e-01,0.10265e-01,0.96672e-02]\n ka[:, 9,15] = [0.47545e-01,0.44152e-01,0.41251e-01,0.38666e-01,0.36358e-01]\n ka[:,10,15] = [0.20097e+00,0.18592e+00,0.17341e+00,0.16203e+00,0.15235e+00]\n ka[:,11,15] = [0.28499e+00,0.26428e+00,0.24585e+00,0.22980e+00,0.21575e+00]\n ka[:,12,15] = [0.30172e+00,0.27929e+00,0.25980e+00,0.24306e+00,0.22789e+00]\n ka[:,13,15] = [0.25655e+00,0.23731e+00,0.22092e+00,0.20639e+00,0.19367e+00]\n ka[:, 1,16] = [0.80810e+02,0.81099e+02,0.81190e+02,0.81107e+02,0.80989e+02]\n ka[:, 2,16] = [0.99319e+02,0.99708e+02,0.99822e+02,0.99871e+02,0.99993e+02]\n ka[:, 3,16] = [0.46927e+02,0.54316e+02,0.57355e+02,0.53715e+02,0.52802e+02]\n ka[:, 4,16] = [0.12802e-02,0.12027e-02,0.11386e-02,0.10866e-02,0.10525e-02]\n ka[:, 5,16] = [0.21675e-02,0.20715e-02,0.19422e-02,0.18402e-02,0.17681e-02]\n ka[:, 6,16] = [0.34707e-02,0.32796e-02,0.30986e-02,0.29246e-02,0.28034e-02]\n ka[:, 7,16] = [0.58659e-02,0.55310e-02,0.51820e-02,0.48829e-02,0.46784e-02]\n ka[:, 8,16] = [0.11875e-01,0.11183e-01,0.10438e-01,0.98038e-02,0.93665e-02]\n ka[:, 9,16] = [0.45519e-01,0.42850e-01,0.39715e-01,0.37447e-01,0.35369e-01]\n ka[:,10,16] = [0.19392e+00,0.18108e+00,0.16817e+00,0.15883e+00,0.14864e+00]\n ka[:,11,16] = [0.27830e+00,0.25715e+00,0.24100e+00,0.22595e+00,0.21321e+00]\n ka[:,12,16] = [0.29533e+00,0.27422e+00,0.25636e+00,0.23936e+00,0.22658e+00]\n ka[:,13,16] = [0.25310e+00,0.23535e+00,0.21855e+00,0.20552e+00,0.19293e+00]\n \n # -----------------------------------------------------------------\n # The array KB contains absorption coefs at the 16 chosen g-values \n # for a range of pressure levels < ~100mb and temperatures. The first \n # index in the array, JT, which runs from 1 to 5, corresponds to \n # different temperatures. More specifically, JT = 3 means that the \n # data are for the reference temperature TREF for this pressure \n # level, JT = 2 refers to the temperature TREF-15, JT = 1 is for\n # TREF-30, JT = 4 is for TREF+15:and JT = 5 is for TREF+30.\n # The second index, JP, runs from 13 to 59 and refers to the JPth\n # reference pressure level (see taumol.f for the value of these\n # pressure levels in mb). The third index, IG, goes from 1 to 16,\n # and tells us which g-interval the absorption coefficients are for.\n # -----------------------------------------------------------------\n kb = zeros(5,47,16)\n kb[:,13-12, 1] = [0.18379e-05,0.23296e-05,0.29007e-05,0.35902e-05,0.43437e-05]\n kb[:,14-12, 1] = [0.15919e-05,0.19832e-05,0.24720e-05,0.30683e-05,0.37253e-05]\n kb[:,15-12, 1] = [0.13850e-05,0.17115e-05,0.21225e-05,0.26292e-05,0.31945e-05]\n kb[:,16-12, 1] = [0.11896e-05,0.14680e-05,0.18142e-05,0.22537e-05,0.27284e-05]\n kb[:,17-12, 1] = [0.10228e-05,0.12597e-05,0.15532e-05,0.19272e-05,0.23163e-05]\n kb[:,18-12, 1] = [0.88243e-06,0.10835e-05,0.13316e-05,0.16603e-05,0.19808e-05]\n kb[:,19-12, 1] = [0.75677e-06,0.92925e-06,0.11401e-05,0.14107e-05,0.16901e-05]\n kb[:,20-12, 1] = [0.64614e-06,0.79361e-06,0.97353e-06,0.11964e-05,0.14414e-05]\n kb[:,21-12, 1] = [0.55323e-06,0.67580e-06,0.82647e-06,0.10137e-05,0.12318e-05]\n kb[:,22-12, 1] = [0.47719e-06,0.58149e-06,0.71060e-06,0.87005e-06,0.10605e-05]\n kb[:,23-12, 1] = [0.41128e-06,0.50080e-06,0.61104e-06,0.75347e-06,0.91200e-06]\n kb[:,24-12, 1] = [0.35306e-06,0.42860e-06,0.52320e-06,0.65156e-06,0.78122e-06]\n kb[:,25-12, 1] = [0.30363e-06,0.36731e-06,0.44673e-06,0.56097e-06,0.66791e-06]\n kb[:,26-12, 1] = [0.26073e-06,0.31537e-06,0.38738e-06,0.48210e-06,0.57382e-06]\n kb[:,27-12, 1] = [0.22303e-06,0.26986e-06,0.33628e-06,0.41161e-06,0.48722e-06]\n kb[:,28-12, 1] = [0.18954e-06,0.22952e-06,0.28797e-06,0.35166e-06,0.41440e-06]\n kb[:,29-12, 1] = [0.16106e-06,0.19430e-06,0.24661e-06,0.29815e-06,0.35151e-06]\n kb[:,30-12, 1] = [0.13630e-06,0.16528e-06,0.20922e-06,0.25193e-06,0.29913e-06]\n kb[:,31-12, 1] = [0.11504e-06,0.14276e-06,0.17807e-06,0.21482e-06,0.25451e-06]\n kb[:,32-12, 1] = [0.96980e-07,0.12215e-06,0.15159e-06,0.18179e-06,0.21515e-06]\n kb[:,33-12, 1] = [0.81598e-07,0.10315e-06,0.12730e-06,0.15190e-06,0.18093e-06]\n kb[:,34-12, 1] = [0.67700e-07,0.85970e-07,0.10559e-06,0.12608e-06,0.15006e-06]\n kb[:,35-12, 1] = [0.55177e-07,0.69519e-07,0.85967e-07,0.10223e-06,0.12147e-06]\n kb[:,36-12, 1] = [0.43924e-07,0.54395e-07,0.67998e-07,0.81142e-07,0.95717e-07]\n kb[:,37-12, 1] = [0.34469e-07,0.41036e-07,0.52575e-07,0.63117e-07,0.74301e-07]\n kb[:,38-12, 1] = [0.26777e-07,0.31734e-07,0.40555e-07,0.49032e-07,0.57653e-07]\n kb[:,39-12, 1] = [0.20670e-07,0.24721e-07,0.30685e-07,0.37873e-07,0.44555e-07]\n kb[:,40-12, 1] = [0.15860e-07,0.19032e-07,0.22612e-07,0.28845e-07,0.34246e-07]\n kb[:,41-12, 1] = [0.12129e-07,0.14603e-07,0.17357e-07,0.21851e-07,0.26346e-07]\n kb[:,42-12, 1] = [0.92319e-08,0.11199e-07,0.13365e-07,0.16174e-07,0.20019e-07]\n kb[:,43-12, 1] = [0.69289e-08,0.84537e-08,0.10159e-07,0.11992e-07,0.14940e-07]\n kb[:,44-12, 1] = [0.51546e-08,0.63380e-08,0.76593e-08,0.90562e-08,0.10716e-07]\n kb[:,45-12, 1] = [0.38335e-08,0.47085e-08,0.57219e-08,0.68148e-08,0.79518e-08]\n kb[:,46-12, 1] = [0.28583e-08,0.34724e-08,0.42447e-08,0.50888e-08,0.59494e-08]\n kb[:,47-12, 1] = [0.20945e-08,0.25418e-08,0.31058e-08,0.37494e-08,0.44274e-08]\n kb[:,48-12, 1] = [0.15164e-08,0.18560e-08,0.22628e-08,0.27371e-08,0.32773e-08]\n kb[:,49-12, 1] = [0.10916e-08,0.13465e-08,0.16387e-08,0.19740e-08,0.23865e-08]\n kb[:,50-12, 1] = [0.78324e-09,0.98361e-09,0.11977e-08,0.14517e-08,0.17457e-08]\n kb[:,51-12, 1] = [0.57263e-09,0.71786e-09,0.87689e-09,0.10705e-08,0.12881e-08]\n kb[:,52-12, 1] = [0.41574e-09,0.51264e-09,0.64152e-09,0.78315e-09,0.94705e-09]\n kb[:,53-12, 1] = [0.29940e-09,0.36836e-09,0.45886e-09,0.56405e-09,0.69166e-09]\n kb[:,54-12, 1] = [0.22617e-09,0.27395e-09,0.33754e-09,0.42095e-09,0.51544e-09]\n kb[:,55-12, 1] = [0.17483e-09,0.20845e-09,0.25546e-09,0.31817e-09,0.39119e-09]\n kb[:,56-12, 1] = [0.13496e-09,0.15930e-09,0.19380e-09,0.23861e-09,0.29770e-09]\n kb[:,57-12, 1] = [0.10406e-09,0.12247e-09,0.14749e-09,0.18078e-09,0.22597e-09]\n kb[:,58-12, 1] = [0.81345e-10,0.94816e-10,0.11329e-09,0.13832e-09,0.17161e-09]\n kb[:,59-12, 1] = [0.67159e-10,0.78312e-10,0.94745e-10,0.11544e-09,0.14442e-09]\n kb[:,13-12, 2] = [0.16654e-04,0.18728e-04,0.21238e-04,0.24491e-04,0.29038e-04]\n kb[:,14-12, 2] = [0.15636e-04,0.17574e-04,0.19918e-04,0.23671e-04,0.27237e-04]\n kb[:,15-12, 2] = [0.14853e-04,0.16629e-04,0.19700e-04,0.22604e-04,0.25586e-04]\n kb[:,16-12, 2] = [0.13519e-04,0.15923e-04,0.18289e-04,0.20530e-04,0.22799e-04]\n kb[:,17-12, 2] = [0.12411e-04,0.14439e-04,0.16431e-04,0.18235e-04,0.20109e-04]\n kb[:,18-12, 2] = [0.11267e-04,0.12880e-04,0.14429e-04,0.16005e-04,0.17538e-04]\n kb[:,19-12, 2] = [0.10025e-04,0.11332e-04,0.12550e-04,0.13853e-04,0.15103e-04]\n kb[:,20-12, 2] = [0.86342e-05,0.97455e-05,0.10778e-04,0.11898e-04,0.12789e-04]\n kb[:,21-12, 2] = [0.74004e-05,0.83107e-05,0.91633e-05,0.10071e-04,0.10674e-04]\n kb[:,22-12, 2] = [0.63700e-05,0.70549e-05,0.78271e-05,0.85170e-05,0.90022e-05]\n kb[:,23-12, 2] = [0.54404e-05,0.60156e-05,0.66393e-05,0.71320e-05,0.75007e-05]\n kb[:,24-12, 2] = [0.45997e-05,0.50718e-05,0.55713e-05,0.59455e-05,0.62118e-05]\n kb[:,25-12, 2] = [0.38745e-05,0.42617e-05,0.46479e-05,0.49297e-05,0.51638e-05]\n kb[:,26-12, 2] = [0.32488e-05,0.35592e-05,0.38685e-05,0.40759e-05,0.43092e-05]\n kb[:,27-12, 2] = [0.26995e-05,0.29601e-05,0.32065e-05,0.33666e-05,0.35609e-05]\n kb[:,28-12, 2] = [0.22359e-05,0.24429e-05,0.26408e-05,0.27752e-05,0.29293e-05]\n kb[:,29-12, 2] = [0.18487e-05,0.20089e-05,0.21668e-05,0.22793e-05,0.24029e-05]\n kb[:,30-12, 2] = [0.15291e-05,0.16589e-05,0.17733e-05,0.18706e-05,0.19584e-05]\n kb[:,31-12, 2] = [0.12554e-05,0.13589e-05,0.14436e-05,0.15195e-05,0.15928e-05]\n kb[:,32-12, 2] = [0.10248e-05,0.11046e-05,0.11716e-05,0.12288e-05,0.12916e-05]\n kb[:,33-12, 2] = [0.83272e-06,0.89120e-06,0.95036e-06,0.99040e-06,0.10409e-05]\n kb[:,34-12, 2] = [0.67518e-06,0.72097e-06,0.76854e-06,0.80246e-06,0.83912e-06]\n kb[:,35-12, 2] = [0.53577e-06,0.57870e-06,0.61715e-06,0.64987e-06,0.67220e-06]\n kb[:,36-12, 2] = [0.42402e-06,0.45825e-06,0.49307e-06,0.52005e-06,0.54029e-06]\n kb[:,37-12, 2] = [0.33419e-06,0.36213e-06,0.38911e-06,0.41359e-06,0.43177e-06]\n kb[:,38-12, 2] = [0.26240e-06,0.28355e-06,0.30530e-06,0.32881e-06,0.34617e-06]\n kb[:,39-12, 2] = [0.20468e-06,0.22245e-06,0.23980e-06,0.25776e-06,0.27424e-06]\n kb[:,40-12, 2] = [0.16070e-06,0.17478e-06,0.18856e-06,0.20230e-06,0.21801e-06]\n kb[:,41-12, 2] = [0.12583e-06,0.13680e-06,0.14851e-06,0.15917e-06,0.17184e-06]\n kb[:,42-12, 2] = [0.98494e-07,0.10639e-06,0.11634e-06,0.12500e-06,0.13490e-06]\n kb[:,43-12, 2] = [0.75196e-07,0.82809e-07,0.90095e-07,0.97952e-07,0.10509e-06]\n kb[:,44-12, 2] = [0.57305e-07,0.63787e-07,0.69227e-07,0.75635e-07,0.81687e-07]\n kb[:,45-12, 2] = [0.42965e-07,0.48245e-07,0.53346e-07,0.58061e-07,0.63120e-07]\n kb[:,46-12, 2] = [0.31048e-07,0.36457e-07,0.40514e-07,0.44557e-07,0.48550e-07]\n kb[:,47-12, 2] = [0.23094e-07,0.26356e-07,0.30443e-07,0.33954e-07,0.36789e-07]\n kb[:,48-12, 2] = [0.16858e-07,0.19402e-07,0.22449e-07,0.25401e-07,0.28254e-07]\n kb[:,49-12, 2] = [0.11413e-07,0.14055e-07,0.16046e-07,0.18927e-07,0.21080e-07]\n kb[:,50-12, 2] = [0.78650e-08,0.99879e-08,0.11846e-07,0.13654e-07,0.15871e-07]\n kb[:,51-12, 2] = [0.55417e-08,0.68977e-08,0.87006e-08,0.10108e-07,0.11829e-07]\n kb[:,52-12, 2] = [0.39143e-08,0.48025e-08,0.60180e-08,0.73762e-08,0.85851e-08]\n kb[:,53-12, 2] = [0.27637e-08,0.33397e-08,0.41996e-08,0.52787e-08,0.62923e-08]\n kb[:,54-12, 2] = [0.19691e-08,0.24529e-08,0.30071e-08,0.38041e-08,0.46981e-08]\n kb[:,55-12, 2] = [0.13034e-08,0.18257e-08,0.22359e-08,0.28210e-08,0.35386e-08]\n kb[:,56-12, 2] = [0.10026e-08,0.13422e-08,0.16687e-08,0.20793e-08,0.26054e-08]\n kb[:,57-12, 2] = [0.77730e-09,0.91190e-09,0.12468e-08,0.15302e-08,0.19418e-08]\n kb[:,58-12, 2] = [0.60359e-09,0.67848e-09,0.92414e-09,0.11511e-08,0.14401e-08]\n kb[:,59-12, 2] = [0.50441e-09,0.56797e-09,0.77369e-09,0.95612e-09,0.11957e-08]\n kb[:,13-12, 3] = [0.98124e-04,0.10149e-03,0.10303e-03,0.10669e-03,0.10870e-03]\n kb[:,14-12, 3] = [0.88110e-04,0.89730e-04,0.90679e-04,0.91892e-04,0.91413e-04]\n kb[:,15-12, 3] = [0.78555e-04,0.78633e-04,0.79145e-04,0.77689e-04,0.77791e-04]\n kb[:,16-12, 3] = [0.67245e-04,0.67743e-04,0.66690e-04,0.65765e-04,0.65950e-04]\n kb[:,17-12, 3] = [0.57553e-04,0.57490e-04,0.56012e-04,0.55634e-04,0.56016e-04]\n kb[:,18-12, 3] = [0.49729e-04,0.48302e-04,0.47418e-04,0.47262e-04,0.47732e-04]\n kb[:,19-12, 3] = [0.42101e-04,0.40906e-04,0.40541e-04,0.40229e-04,0.40671e-04]\n kb[:,20-12, 3] = [0.35046e-04,0.34193e-04,0.34032e-04,0.33881e-04,0.34691e-04]\n kb[:,21-12, 3] = [0.29192e-04,0.28813e-04,0.28525e-04,0.28485e-04,0.29764e-04]\n kb[:,22-12, 3] = [0.24212e-04,0.23970e-04,0.23804e-04,0.23947e-04,0.24310e-04]\n kb[:,23-12, 3] = [0.20167e-04,0.19961e-04,0.19837e-04,0.20528e-04,0.19887e-04]\n kb[:,24-12, 3] = [0.16817e-04,0.16624e-04,0.16525e-04,0.17263e-04,0.16481e-04]\n kb[:,25-12, 3] = [0.13896e-04,0.13806e-04,0.13810e-04,0.14348e-04,0.13634e-04]\n kb[:,26-12, 3] = [0.11515e-04,0.11474e-04,0.11553e-04,0.11705e-04,0.11167e-04]\n kb[:,27-12, 3] = [0.95004e-05,0.94543e-05,0.95650e-05,0.95316e-05,0.91651e-05]\n kb[:,28-12, 3] = [0.78135e-05,0.77862e-05,0.78715e-05,0.77825e-05,0.74877e-05]\n kb[:,29-12, 3] = [0.63615e-05,0.63601e-05,0.64198e-05,0.63507e-05,0.61200e-05]\n kb[:,30-12, 3] = [0.51738e-05,0.51781e-05,0.52250e-05,0.51709e-05,0.50243e-05]\n kb[:,31-12, 3] = [0.41825e-05,0.42240e-05,0.42510e-05,0.42241e-05,0.41058e-05]\n kb[:,32-12, 3] = [0.34024e-05,0.34302e-05,0.34514e-05,0.34436e-05,0.33474e-05]\n kb[:,33-12, 3] = [0.27510e-05,0.27828e-05,0.28059e-05,0.28125e-05,0.27394e-05]\n kb[:,34-12, 3] = [0.22195e-05,0.22517e-05,0.22743e-05,0.22728e-05,0.22254e-05]\n kb[:,35-12, 3] = [0.18029e-05,0.18238e-05,0.18432e-05,0.18461e-05,0.18241e-05]\n kb[:,36-12, 3] = [0.14477e-05,0.14734e-05,0.14936e-05,0.15116e-05,0.14874e-05]\n kb[:,37-12, 3] = [0.11637e-05,0.11929e-05,0.12098e-05,0.12265e-05,0.12076e-05]\n kb[:,38-12, 3] = [0.93292e-06,0.96246e-06,0.98169e-06,0.99435e-06,0.98749e-06]\n kb[:,39-12, 3] = [0.74927e-06,0.76742e-06,0.79020e-06,0.80604e-06,0.81415e-06]\n kb[:,40-12, 3] = [0.60479e-06,0.61743e-06,0.63973e-06,0.65295e-06,0.66261e-06]\n kb[:,41-12, 3] = [0.48450e-06,0.49742e-06,0.51366e-06,0.52876e-06,0.53813e-06]\n kb[:,42-12, 3] = [0.38298e-06,0.40088e-06,0.41192e-06,0.42651e-06,0.43595e-06]\n kb[:,43-12, 3] = [0.30310e-06,0.31905e-06,0.32907e-06,0.34154e-06,0.35007e-06]\n kb[:,44-12, 3] = [0.23745e-06,0.25035e-06,0.26224e-06,0.27145e-06,0.28146e-06]\n kb[:,45-12, 3] = [0.18653e-06,0.19510e-06,0.20644e-06,0.21510e-06,0.22354e-06]\n kb[:,46-12, 3] = [0.14759e-06,0.15322e-06,0.16145e-06,0.17034e-06,0.17744e-06]\n kb[:,47-12, 3] = [0.11410e-06,0.12007e-06,0.12507e-06,0.13237e-06,0.13995e-06]\n kb[:,48-12, 3] = [0.88327e-07,0.93967e-07,0.97683e-07,0.10257e-06,0.10921e-06]\n kb[:,49-12, 3] = [0.66715e-07,0.72172e-07,0.76442e-07,0.79214e-07,0.84006e-07]\n kb[:,50-12, 3] = [0.51458e-07,0.55761e-07,0.59239e-07,0.62292e-07,0.64470e-07]\n kb[:,51-12, 3] = [0.39957e-07,0.42400e-07,0.45870e-07,0.48592e-07,0.50287e-07]\n kb[:,52-12, 3] = [0.31150e-07,0.32725e-07,0.35598e-07,0.37633e-07,0.39607e-07]\n kb[:,53-12, 3] = [0.23783e-07,0.25415e-07,0.26634e-07,0.28885e-07,0.30620e-07]\n kb[:,54-12, 3] = [0.18531e-07,0.19938e-07,0.20988e-07,0.22678e-07,0.23867e-07]\n kb[:,55-12, 3] = [0.14810e-07,0.15772e-07,0.16651e-07,0.17727e-07,0.18861e-07]\n kb[:,56-12, 3] = [0.11652e-07,0.12557e-07,0.13319e-07,0.13930e-07,0.15077e-07]\n kb[:,57-12, 3] = [0.91523e-08,0.99835e-08,0.10603e-07,0.11081e-07,0.11999e-07]\n kb[:,58-12, 3] = [0.72383e-08,0.79060e-08,0.84489e-08,0.88615e-08,0.94456e-08]\n kb[:,59-12, 3] = [0.60315e-08,0.65931e-08,0.71001e-08,0.74012e-08,0.78761e-08]\n kb[:,13-12, 4] = [0.21882e-03,0.20968e-03,0.18648e-03,0.17505e-03,0.17320e-03]\n kb[:,14-12, 4] = [0.19140e-03,0.17026e-03,0.15903e-03,0.15552e-03,0.16009e-03]\n kb[:,15-12, 4] = [0.16003e-03,0.14531e-03,0.14007e-03,0.14511e-03,0.14619e-03]\n kb[:,16-12, 4] = [0.13387e-03,0.12423e-03,0.12444e-03,0.12743e-03,0.12749e-03]\n kb[:,17-12, 4] = [0.11266e-03,0.10780e-03,0.11110e-03,0.11051e-03,0.11075e-03]\n kb[:,18-12, 4] = [0.96156e-04,0.95617e-04,0.96775e-04,0.96220e-04,0.96078e-04]\n kb[:,19-12, 4] = [0.82712e-04,0.82946e-04,0.83265e-04,0.82827e-04,0.82044e-04]\n kb[:,20-12, 4] = [0.71080e-04,0.71167e-04,0.71040e-04,0.70443e-04,0.69069e-04]\n kb[:,21-12, 4] = [0.60110e-04,0.60836e-04,0.59994e-04,0.58992e-04,0.57237e-04]\n kb[:,22-12, 4] = [0.50688e-04,0.51296e-04,0.50271e-04,0.48889e-04,0.48471e-04]\n kb[:,23-12, 4] = [0.42706e-04,0.42628e-04,0.41764e-04,0.39999e-04,0.40893e-04]\n kb[:,24-12, 4] = [0.35803e-04,0.35316e-04,0.34535e-04,0.33229e-04,0.34127e-04]\n kb[:,25-12, 4] = [0.29906e-04,0.29201e-04,0.28336e-04,0.27455e-04,0.28044e-04]\n kb[:,26-12, 4] = [0.24659e-04,0.23926e-04,0.23159e-04,0.22827e-04,0.23266e-04]\n kb[:,27-12, 4] = [0.20221e-04,0.19578e-04,0.18838e-04,0.18853e-04,0.19067e-04]\n kb[:,28-12, 4] = [0.16345e-04,0.15913e-04,0.15327e-04,0.15412e-04,0.15560e-04]\n kb[:,29-12, 4] = [0.13195e-04,0.12870e-04,0.12430e-04,0.12518e-04,0.12639e-04]\n kb[:,30-12, 4] = [0.10622e-04,0.10384e-04,0.10068e-04,0.10151e-04,0.10256e-04]\n kb[:,31-12, 4] = [0.85785e-05,0.83523e-05,0.81227e-05,0.81998e-05,0.83313e-05]\n kb[:,32-12, 4] = [0.69114e-05,0.67093e-05,0.65758e-05,0.66222e-05,0.67679e-05]\n kb[:,33-12, 4] = [0.55456e-05,0.54342e-05,0.53229e-05,0.53610e-05,0.54819e-05]\n kb[:,34-12, 4] = [0.44461e-05,0.43891e-05,0.43112e-05,0.43632e-05,0.44560e-05]\n kb[:,35-12, 4] = [0.35725e-05,0.35192e-05,0.34703e-05,0.35075e-05,0.35919e-05]\n kb[:,36-12, 4] = [0.28842e-05,0.28362e-05,0.28143e-05,0.28097e-05,0.29057e-05]\n kb[:,37-12, 4] = [0.23374e-05,0.22987e-05,0.22934e-05,0.22812e-05,0.23451e-05]\n kb[:,38-12, 4] = [0.18966e-05,0.18679e-05,0.18613e-05,0.18437e-05,0.18894e-05]\n kb[:,39-12, 4] = [0.15300e-05,0.15180e-05,0.15096e-05,0.14915e-05,0.15107e-05]\n kb[:,40-12, 4] = [0.12426e-05,0.12357e-05,0.12171e-05,0.12170e-05,0.12227e-05]\n kb[:,41-12, 4] = [0.10102e-05,0.10077e-05,0.98593e-06,0.98478e-06,0.99213e-06]\n kb[:,42-12, 4] = [0.82201e-06,0.81050e-06,0.80313e-06,0.80181e-06,0.80361e-06]\n kb[:,43-12, 4] = [0.67318e-06,0.65347e-06,0.65478e-06,0.64360e-06,0.64722e-06]\n kb[:,44-12, 4] = [0.55598e-06,0.53355e-06,0.52778e-06,0.52097e-06,0.51997e-06]\n kb[:,45-12, 4] = [0.46157e-06,0.43457e-06,0.42412e-06,0.42137e-06,0.41750e-06]\n kb[:,46-12, 4] = [0.39156e-06,0.35690e-06,0.34498e-06,0.33995e-06,0.33614e-06]\n kb[:,47-12, 4] = [0.33392e-06,0.29746e-06,0.28074e-06,0.27344e-06,0.27079e-06]\n kb[:,48-12, 4] = [0.27066e-06,0.25369e-06,0.23115e-06,0.22213e-06,0.21766e-06]\n kb[:,49-12, 4] = [0.22198e-06,0.21395e-06,0.19274e-06,0.18040e-06,0.17542e-06]\n kb[:,50-12, 4] = [0.18070e-06,0.17367e-06,0.16473e-06,0.14916e-06,0.14306e-06]\n kb[:,51-12, 4] = [0.14595e-06,0.14287e-06,0.13847e-06,0.12418e-06,0.11697e-06]\n kb[:,52-12, 4] = [0.11819e-06,0.11588e-06,0.11225e-06,0.10604e-06,0.96269e-07]\n kb[:,53-12, 4] = [0.95028e-07,0.93094e-07,0.91303e-07,0.88900e-07,0.80262e-07]\n kb[:,54-12, 4] = [0.77005e-07,0.76238e-07,0.74228e-07,0.72526e-07,0.67965e-07]\n kb[:,55-12, 4] = [0.62979e-07,0.62692e-07,0.60930e-07,0.59579e-07,0.57700e-07]\n kb[:,56-12, 4] = [0.51571e-07,0.51196e-07,0.50031e-07,0.48916e-07,0.48127e-07]\n kb[:,57-12, 4] = [0.42602e-07,0.41678e-07,0.41006e-07,0.39709e-07,0.39283e-07]\n kb[:,58-12, 4] = [0.35155e-07,0.34052e-07,0.33561e-07,0.32395e-07,0.32057e-07]\n kb[:,59-12, 4] = [0.29318e-07,0.28516e-07,0.28097e-07,0.26888e-07,0.26840e-07]\n kb[:,13-12, 5] = [0.43718e-03,0.42279e-03,0.43200e-03,0.42910e-03,0.42775e-03]\n kb[:,14-12, 5] = [0.37902e-03,0.38090e-03,0.38058e-03,0.37637e-03,0.36798e-03]\n kb[:,15-12, 5] = [0.33222e-03,0.33597e-03,0.33205e-03,0.32000e-03,0.31310e-03]\n kb[:,16-12, 5] = [0.28736e-03,0.28700e-03,0.27853e-03,0.26891e-03,0.26391e-03]\n kb[:,17-12, 5] = [0.24534e-03,0.24098e-03,0.23072e-03,0.22519e-03,0.22013e-03]\n kb[:,18-12, 5] = [0.20645e-03,0.20019e-03,0.19266e-03,0.18716e-03,0.18139e-03]\n kb[:,19-12, 5] = [0.17271e-03,0.16642e-03,0.16064e-03,0.15556e-03,0.14951e-03]\n kb[:,20-12, 5] = [0.14266e-03,0.13766e-03,0.13239e-03,0.12767e-03,0.12305e-03]\n kb[:,21-12, 5] = [0.11797e-03,0.11256e-03,0.10880e-03,0.10424e-03,0.10062e-03]\n kb[:,22-12, 5] = [0.97085e-04,0.92101e-04,0.88420e-04,0.85535e-04,0.82201e-04]\n kb[:,23-12, 5] = [0.79380e-04,0.75312e-04,0.72177e-04,0.69710e-04,0.66966e-04]\n kb[:,24-12, 5] = [0.64591e-04,0.61520e-04,0.58891e-04,0.56626e-04,0.54603e-04]\n kb[:,25-12, 5] = [0.52423e-04,0.49934e-04,0.48122e-04,0.46331e-04,0.44875e-04]\n kb[:,26-12, 5] = [0.42528e-04,0.40739e-04,0.39218e-04,0.37806e-04,0.36631e-04]\n kb[:,27-12, 5] = [0.34453e-04,0.33104e-04,0.32009e-04,0.30764e-04,0.30000e-04]\n kb[:,28-12, 5] = [0.28076e-04,0.26948e-04,0.26097e-04,0.25065e-04,0.24596e-04]\n kb[:,29-12, 5] = [0.22814e-04,0.21902e-04,0.21222e-04,0.20350e-04,0.20152e-04]\n kb[:,30-12, 5] = [0.18551e-04,0.17731e-04,0.17162e-04,0.16614e-04,0.16461e-04]\n kb[:,31-12, 5] = [0.15020e-04,0.14383e-04,0.13922e-04,0.13548e-04,0.13388e-04]\n kb[:,32-12, 5] = [0.12091e-04,0.11653e-04,0.11308e-04,0.11033e-04,0.10954e-04]\n kb[:,33-12, 5] = [0.97901e-05,0.93570e-05,0.91428e-05,0.89594e-05,0.89614e-05]\n kb[:,34-12, 5] = [0.79439e-05,0.76095e-05,0.74365e-05,0.73099e-05,0.73269e-05]\n kb[:,35-12, 5] = [0.64505e-05,0.62326e-05,0.60921e-05,0.59939e-05,0.59799e-05]\n kb[:,36-12, 5] = [0.52745e-05,0.51017e-05,0.49658e-05,0.48988e-05,0.48773e-05]\n kb[:,37-12, 5] = [0.43522e-05,0.42053e-05,0.40681e-05,0.40176e-05,0.40058e-05]\n kb[:,38-12, 5] = [0.35676e-05,0.34559e-05,0.33446e-05,0.33017e-05,0.32771e-05]\n kb[:,39-12, 5] = [0.29238e-05,0.28445e-05,0.27512e-05,0.27095e-05,0.26825e-05]\n kb[:,40-12, 5] = [0.23985e-05,0.23437e-05,0.22756e-05,0.22251e-05,0.22009e-05]\n kb[:,41-12, 5] = [0.19763e-05,0.19311e-05,0.18886e-05,0.18370e-05,0.18072e-05]\n kb[:,42-12, 5] = [0.16256e-05,0.15918e-05,0.15558e-05,0.15108e-05,0.14861e-05]\n kb[:,43-12, 5] = [0.13290e-05,0.13116e-05,0.12833e-05,0.12550e-05,0.12262e-05]\n kb[:,44-12, 5] = [0.10777e-05,0.10760e-05,0.10566e-05,0.10365e-05,0.10136e-05]\n kb[:,45-12, 5] = [0.86690e-06,0.87981e-06,0.87044e-06,0.85428e-06,0.83627e-06]\n kb[:,46-12, 5] = [0.68706e-06,0.71088e-06,0.70939e-06,0.70110e-06,0.69032e-06]\n kb[:,47-12, 5] = [0.54665e-06,0.56934e-06,0.58033e-06,0.57830e-06,0.57105e-06]\n kb[:,48-12, 5] = [0.44874e-06,0.44653e-06,0.46650e-06,0.47090e-06,0.46732e-06]\n kb[:,49-12, 5] = [0.36869e-06,0.35456e-06,0.36842e-06,0.37978e-06,0.38217e-06]\n kb[:,50-12, 5] = [0.30489e-06,0.29229e-06,0.29104e-06,0.30430e-06,0.31068e-06]\n kb[:,51-12, 5] = [0.25290e-06,0.24012e-06,0.23271e-06,0.24366e-06,0.25149e-06]\n kb[:,52-12, 5] = [0.21148e-06,0.19715e-06,0.19121e-06,0.19177e-06,0.20148e-06]\n kb[:,53-12, 5] = [0.17334e-06,0.16335e-06,0.15574e-06,0.15266e-06,0.15921e-06]\n kb[:,54-12, 5] = [0.14189e-06,0.13650e-06,0.12781e-06,0.12535e-06,0.12749e-06]\n kb[:,55-12, 5] = [0.11763e-06,0.11398e-06,0.10627e-06,0.10373e-06,0.10268e-06]\n kb[:,56-12, 5] = [0.98316e-07,0.94892e-07,0.88799e-07,0.85036e-07,0.83393e-07]\n kb[:,57-12, 5] = [0.83049e-07,0.78499e-07,0.74140e-07,0.70137e-07,0.68774e-07]\n kb[:,58-12, 5] = [0.71768e-07,0.64682e-07,0.62012e-07,0.58149e-07,0.57037e-07]\n kb[:,59-12, 5] = [0.60166e-07,0.54824e-07,0.52042e-07,0.49198e-07,0.47862e-07]\n kb[:,13-12, 6] = [0.71254e-03,0.65708e-03,0.60824e-03,0.57965e-03,0.55389e-03]\n kb[:,14-12, 6] = [0.58852e-03,0.54811e-03,0.51125e-03,0.48557e-03,0.47730e-03]\n kb[:,15-12, 6] = [0.50599e-03,0.46869e-03,0.44362e-03,0.43503e-03,0.43705e-03]\n kb[:,16-12, 6] = [0.43493e-03,0.40996e-03,0.39680e-03,0.39623e-03,0.40784e-03]\n kb[:,17-12, 6] = [0.38028e-03,0.36175e-03,0.35696e-03,0.36547e-03,0.38127e-03]\n kb[:,18-12, 6] = [0.33113e-03,0.32205e-03,0.32458e-03,0.33502e-03,0.35577e-03]\n kb[:,19-12, 6] = [0.28886e-03,0.29134e-03,0.29799e-03,0.31134e-03,0.33676e-03]\n kb[:,20-12, 6] = [0.25113e-03,0.25555e-03,0.26535e-03,0.28470e-03,0.30677e-03]\n kb[:,21-12, 6] = [0.21640e-03,0.22152e-03,0.23323e-03,0.25467e-03,0.27764e-03]\n kb[:,22-12, 6] = [0.18601e-03,0.19217e-03,0.20696e-03,0.22593e-03,0.24729e-03]\n kb[:,23-12, 6] = [0.15978e-03,0.16833e-03,0.18229e-03,0.19994e-03,0.21913e-03]\n kb[:,24-12, 6] = [0.13748e-03,0.14696e-03,0.16025e-03,0.17620e-03,0.19459e-03]\n kb[:,25-12, 6] = [0.11841e-03,0.12828e-03,0.13998e-03,0.15487e-03,0.17174e-03]\n kb[:,26-12, 6] = [0.10209e-03,0.11175e-03,0.12193e-03,0.13590e-03,0.15125e-03]\n kb[:,27-12, 6] = [0.87003e-04,0.95681e-04,0.10499e-03,0.11744e-03,0.13086e-03]\n kb[:,28-12, 6] = [0.73110e-04,0.80653e-04,0.89103e-04,0.99988e-04,0.11120e-03]\n kb[:,29-12, 6] = [0.60620e-04,0.66736e-04,0.74222e-04,0.82863e-04,0.92471e-04]\n kb[:,30-12, 6] = [0.49831e-04,0.54602e-04,0.61288e-04,0.68281e-04,0.75599e-04]\n kb[:,31-12, 6] = [0.40315e-04,0.44435e-04,0.49703e-04,0.55140e-04,0.60140e-04]\n kb[:,32-12, 6] = [0.32490e-04,0.36020e-04,0.39894e-04,0.44068e-04,0.48080e-04]\n kb[:,33-12, 6] = [0.26085e-04,0.29063e-04,0.32003e-04,0.35074e-04,0.38662e-04]\n kb[:,34-12, 6] = [0.21201e-04,0.23256e-04,0.25636e-04,0.28140e-04,0.31273e-04]\n kb[:,35-12, 6] = [0.17022e-04,0.18534e-04,0.20322e-04,0.22464e-04,0.25109e-04]\n kb[:,36-12, 6] = [0.13427e-04,0.14606e-04,0.16055e-04,0.17783e-04,0.19877e-04]\n kb[:,37-12, 6] = [0.10630e-04,0.11559e-04,0.12731e-04,0.14118e-04,0.15831e-04]\n kb[:,38-12, 6] = [0.84365e-05,0.91300e-05,0.10077e-04,0.11171e-04,0.12568e-04]\n kb[:,39-12, 6] = [0.66762e-05,0.71770e-05,0.79359e-05,0.88044e-05,0.99043e-05]\n kb[:,40-12, 6] = [0.53561e-05,0.57216e-05,0.63210e-05,0.70080e-05,0.79213e-05]\n kb[:,41-12, 6] = [0.42954e-05,0.45692e-05,0.50356e-05,0.56102e-05,0.63394e-05]\n kb[:,42-12, 6] = [0.34409e-05,0.36788e-05,0.40124e-05,0.44898e-05,0.50645e-05]\n kb[:,43-12, 6] = [0.27453e-05,0.29361e-05,0.31651e-05,0.35498e-05,0.40058e-05]\n kb[:,44-12, 6] = [0.21863e-05,0.23320e-05,0.24965e-05,0.27915e-05,0.31593e-05]\n kb[:,45-12, 6] = [0.17409e-05,0.18472e-05,0.19801e-05,0.21812e-05,0.24741e-05]\n kb[:,46-12, 6] = [0.13903e-05,0.14639e-05,0.15660e-05,0.17042e-05,0.19243e-05]\n kb[:,47-12, 6] = [0.11229e-05,0.11661e-05,0.12377e-05,0.13335e-05,0.14898e-05]\n kb[:,48-12, 6] = [0.90528e-06,0.92962e-06,0.97799e-06,0.10483e-05,0.11575e-05]\n kb[:,49-12, 6] = [0.72877e-06,0.74278e-06,0.77380e-06,0.82564e-06,0.89736e-06]\n kb[:,50-12, 6] = [0.59358e-06,0.59955e-06,0.62170e-06,0.65720e-06,0.70771e-06]\n kb[:,51-12, 6] = [0.48783e-06,0.48769e-06,0.50300e-06,0.52655e-06,0.56377e-06]\n kb[:,52-12, 6] = [0.39834e-06,0.39922e-06,0.40604e-06,0.42316e-06,0.45057e-06]\n kb[:,53-12, 6] = [0.33019e-06,0.32505e-06,0.33011e-06,0.33917e-06,0.35858e-06]\n kb[:,54-12, 6] = [0.27829e-06,0.26763e-06,0.27219e-06,0.27714e-06,0.29159e-06]\n kb[:,55-12, 6] = [0.23259e-06,0.22250e-06,0.22510e-06,0.22855e-06,0.23937e-06]\n kb[:,56-12, 6] = [0.19401e-06,0.18605e-06,0.18566e-06,0.18937e-06,0.19605e-06]\n kb[:,57-12, 6] = [0.15908e-06,0.15649e-06,0.15396e-06,0.15754e-06,0.16039e-06]\n kb[:,58-12, 6] = [0.12892e-06,0.13132e-06,0.12793e-06,0.13093e-06,0.13273e-06]\n kb[:,59-12, 6] = [0.11177e-06,0.11165e-06,0.10875e-06,0.11132e-06,0.11431e-06]\n kb[:,13-12, 7] = [0.19357e-02,0.20341e-02,0.21760e-02,0.22982e-02,0.24550e-02]\n kb[:,14-12, 7] = [0.20343e-02,0.21709e-02,0.23192e-02,0.24854e-02,0.27026e-02]\n kb[:,15-12, 7] = [0.21108e-02,0.23009e-02,0.25488e-02,0.28048e-02,0.30159e-02]\n kb[:,16-12, 7] = [0.21016e-02,0.23581e-02,0.25958e-02,0.28093e-02,0.29839e-02]\n kb[:,17-12, 7] = [0.21350e-02,0.23722e-02,0.25718e-02,0.27703e-02,0.30036e-02]\n kb[:,18-12, 7] = [0.21493e-02,0.23550e-02,0.25593e-02,0.27827e-02,0.29722e-02]\n kb[:,19-12, 7] = [0.21677e-02,0.23602e-02,0.25446e-02,0.27267e-02,0.29542e-02]\n kb[:,20-12, 7] = [0.21009e-02,0.22669e-02,0.24261e-02,0.26095e-02,0.28436e-02]\n kb[:,21-12, 7] = [0.19811e-02,0.21249e-02,0.22790e-02,0.24716e-02,0.26844e-02]\n kb[:,22-12, 7] = [0.18393e-02,0.19585e-02,0.21127e-02,0.22962e-02,0.25211e-02]\n kb[:,23-12, 7] = [0.16905e-02,0.18032e-02,0.19594e-02,0.21280e-02,0.23466e-02]\n kb[:,24-12, 7] = [0.15327e-02,0.16542e-02,0.18047e-02,0.19642e-02,0.21591e-02]\n kb[:,25-12, 7] = [0.13831e-02,0.14932e-02,0.16391e-02,0.17921e-02,0.19606e-02]\n kb[:,26-12, 7] = [0.12298e-02,0.13325e-02,0.14676e-02,0.16086e-02,0.17628e-02]\n kb[:,27-12, 7] = [0.10692e-02,0.11652e-02,0.12858e-02,0.14124e-02,0.15514e-02]\n kb[:,28-12, 7] = [0.91706e-03,0.10034e-02,0.11100e-02,0.12231e-02,0.13481e-02]\n kb[:,29-12, 7] = [0.76824e-03,0.84492e-03,0.93654e-03,0.10377e-02,0.11448e-02]\n kb[:,30-12, 7] = [0.63841e-03,0.70573e-03,0.78553e-03,0.87197e-03,0.96607e-03]\n kb[:,31-12, 7] = [0.51979e-03,0.58056e-03,0.64728e-03,0.71891e-03,0.80875e-03]\n kb[:,32-12, 7] = [0.42659e-03,0.47686e-03,0.53347e-03,0.60016e-03,0.67592e-03]\n kb[:,33-12, 7] = [0.34820e-03,0.39030e-03,0.44004e-03,0.49875e-03,0.56492e-03]\n kb[:,34-12, 7] = [0.28753e-03,0.32477e-03,0.36831e-03,0.41989e-03,0.47708e-03]\n kb[:,35-12, 7] = [0.23568e-03,0.26716e-03,0.30618e-03,0.35062e-03,0.39934e-03]\n kb[:,36-12, 7] = [0.19116e-03,0.21863e-03,0.25180e-03,0.28983e-03,0.33082e-03]\n kb[:,37-12, 7] = [0.15437e-03,0.17829e-03,0.20646e-03,0.23900e-03,0.27320e-03]\n kb[:,38-12, 7] = [0.12397e-03,0.14462e-03,0.16847e-03,0.19621e-03,0.22528e-03]\n kb[:,39-12, 7] = [0.98930e-04,0.11647e-03,0.13711e-03,0.16057e-03,0.18549e-03]\n kb[:,40-12, 7] = [0.79845e-04,0.94437e-04,0.11202e-03,0.13217e-03,0.15346e-03]\n kb[:,41-12, 7] = [0.64260e-04,0.76439e-04,0.91253e-04,0.10837e-03,0.12691e-03]\n kb[:,42-12, 7] = [0.51561e-04,0.61686e-04,0.74044e-04,0.88504e-04,0.10431e-03]\n kb[:,43-12, 7] = [0.40906e-04,0.49267e-04,0.59361e-04,0.71417e-04,0.84751e-04]\n kb[:,44-12, 7] = [0.32247e-04,0.38955e-04,0.47246e-04,0.57199e-04,0.68540e-04]\n kb[:,45-12, 7] = [0.25243e-04,0.30790e-04,0.37490e-04,0.45754e-04,0.55394e-04]\n kb[:,46-12, 7] = [0.19604e-04,0.24131e-04,0.29598e-04,0.36431e-04,0.44419e-04]\n kb[:,47-12, 7] = [0.15116e-04,0.18785e-04,0.23180e-04,0.28780e-04,0.35381e-04]\n kb[:,48-12, 7] = [0.11550e-04,0.14451e-04,0.18039e-04,0.22545e-04,0.28005e-04]\n kb[:,49-12, 7] = [0.87452e-05,0.10992e-04,0.13863e-04,0.17498e-04,0.21949e-04]\n kb[:,50-12, 7] = [0.66768e-05,0.84974e-05,0.10835e-04,0.13777e-04,0.17448e-04]\n kb[:,51-12, 7] = [0.51359e-05,0.66277e-05,0.85196e-05,0.10905e-04,0.13933e-04]\n kb[:,52-12, 7] = [0.38737e-05,0.51001e-05,0.66347e-05,0.85842e-05,0.11033e-04]\n kb[:,53-12, 7] = [0.28793e-05,0.38820e-05,0.50987e-05,0.66800e-05,0.86846e-05]\n kb[:,54-12, 7] = [0.22250e-05,0.30528e-05,0.40721e-05,0.53813e-05,0.70529e-05]\n kb[:,55-12, 7] = [0.17548e-05,0.24455e-05,0.32962e-05,0.43877e-05,0.58071e-05]\n kb[:,56-12, 7] = [0.13740e-05,0.19413e-05,0.26523e-05,0.35566e-05,0.47512e-05]\n kb[:,57-12, 7] = [0.10745e-05,0.15242e-05,0.21190e-05,0.28679e-05,0.38612e-05]\n kb[:,58-12, 7] = [0.84271e-06,0.12117e-05,0.17039e-05,0.23246e-05,0.31564e-05]\n kb[:,59-12, 7] = [0.75625e-06,0.11002e-05,0.15376e-05,0.20855e-05,0.28548e-05]\n kb[:,13-12, 8] = [0.41133e-01,0.43585e-01,0.46448e-01,0.50156e-01,0.54607e-01]\n kb[:,14-12, 8] = [0.39162e-01,0.41636e-01,0.44649e-01,0.48118e-01,0.52078e-01]\n kb[:,15-12, 8] = [0.37770e-01,0.40048e-01,0.43090e-01,0.46524e-01,0.50698e-01]\n kb[:,16-12, 8] = [0.35235e-01,0.37712e-01,0.40429e-01,0.44092e-01,0.48470e-01]\n kb[:,17-12, 8] = [0.32748e-01,0.35232e-01,0.38049e-01,0.41536e-01,0.45596e-01]\n kb[:,18-12, 8] = [0.30656e-01,0.33078e-01,0.36084e-01,0.39403e-01,0.43319e-01]\n kb[:,19-12, 8] = [0.28887e-01,0.31462e-01,0.34348e-01,0.37660e-01,0.41532e-01]\n kb[:,20-12, 8] = [0.26521e-01,0.29153e-01,0.32006e-01,0.35368e-01,0.39083e-01]\n kb[:,21-12, 8] = [0.23988e-01,0.26537e-01,0.29508e-01,0.32666e-01,0.36356e-01]\n kb[:,22-12, 8] = [0.21655e-01,0.24205e-01,0.27193e-01,0.30346e-01,0.33820e-01]\n kb[:,23-12, 8] = [0.19724e-01,0.22257e-01,0.25021e-01,0.27997e-01,0.31309e-01]\n kb[:,24-12, 8] = [0.18094e-01,0.20464e-01,0.23167e-01,0.26069e-01,0.29357e-01]\n kb[:,25-12, 8] = [0.16666e-01,0.18896e-01,0.21422e-01,0.24282e-01,0.27401e-01]\n kb[:,26-12, 8] = [0.15252e-01,0.17451e-01,0.19828e-01,0.22565e-01,0.25604e-01]\n kb[:,27-12, 8] = [0.13902e-01,0.15940e-01,0.18143e-01,0.20720e-01,0.23727e-01]\n kb[:,28-12, 8] = [0.12642e-01,0.14401e-01,0.16467e-01,0.18975e-01,0.21740e-01]\n kb[:,29-12, 8] = [0.11177e-01,0.12765e-01,0.14750e-01,0.16957e-01,0.19575e-01]\n kb[:,30-12, 8] = [0.97810e-02,0.11281e-01,0.13066e-01,0.15112e-01,0.17581e-01]\n kb[:,31-12, 8] = [0.84562e-02,0.98553e-02,0.11427e-01,0.13312e-01,0.15536e-01]\n kb[:,32-12, 8] = [0.73434e-02,0.85939e-02,0.10020e-01,0.11770e-01,0.13758e-01]\n kb[:,33-12, 8] = [0.63801e-02,0.74957e-02,0.87874e-02,0.10375e-01,0.12145e-01]\n kb[:,34-12, 8] = [0.56002e-02,0.65926e-02,0.77964e-02,0.92186e-02,0.10768e-01]\n kb[:,35-12, 8] = [0.48489e-02,0.57164e-02,0.68333e-02,0.80886e-02,0.94500e-02]\n kb[:,36-12, 8] = [0.41428e-02,0.49220e-02,0.58884e-02,0.69905e-02,0.81862e-02]\n kb[:,37-12, 8] = [0.34967e-02,0.41841e-02,0.50244e-02,0.59657e-02,0.70167e-02]\n kb[:,38-12, 8] = [0.29333e-02,0.35364e-02,0.42644e-02,0.50719e-02,0.59938e-02]\n kb[:,39-12, 8] = [0.24443e-02,0.29647e-02,0.35953e-02,0.42898e-02,0.50972e-02]\n kb[:,40-12, 8] = [0.20439e-02,0.25046e-02,0.30512e-02,0.36459e-02,0.43466e-02]\n kb[:,41-12, 8] = [0.17068e-02,0.21107e-02,0.25838e-02,0.30959e-02,0.36971e-02]\n kb[:,42-12, 8] = [0.14199e-02,0.17705e-02,0.21755e-02,0.26204e-02,0.31356e-02]\n kb[:,43-12, 8] = [0.11616e-02,0.14584e-02,0.18069e-02,0.21876e-02,0.26286e-02]\n kb[:,44-12, 8] = [0.93807e-03,0.11864e-02,0.14851e-02,0.18080e-02,0.21849e-02]\n kb[:,45-12, 8] = [0.75026e-03,0.95460e-03,0.12092e-02,0.14831e-02,0.18037e-02]\n kb[:,46-12, 8] = [0.59319e-03,0.76134e-03,0.97292e-03,0.12059e-02,0.14787e-02]\n kb[:,47-12, 8] = [0.46546e-03,0.60113e-03,0.77762e-03,0.97379e-03,0.12030e-02]\n kb[:,48-12, 8] = [0.36131e-03,0.46999e-03,0.61292e-03,0.77778e-03,0.96667e-03]\n kb[:,49-12, 8] = [0.27490e-03,0.36153e-03,0.47561e-03,0.61173e-03,0.76634e-03]\n kb[:,50-12, 8] = [0.21403e-03,0.28416e-03,0.37592e-03,0.48994e-03,0.61812e-03]\n kb[:,51-12, 8] = [0.16745e-03,0.22425e-03,0.29943e-03,0.39474e-03,0.50310e-03]\n kb[:,52-12, 8] = [0.12927e-03,0.17496e-03,0.23541e-03,0.31434e-03,0.40442e-03]\n kb[:,53-12, 8] = [0.98512e-04,0.13503e-03,0.18276e-03,0.24681e-03,0.32086e-03]\n kb[:,54-12, 8] = [0.78150e-04,0.10819e-03,0.14843e-03,0.20243e-03,0.26646e-03]\n kb[:,55-12, 8] = [0.63455e-04,0.88570e-04,0.12297e-03,0.17015e-03,0.22626e-03]\n kb[:,56-12, 8] = [0.51095e-04,0.72223e-04,0.10144e-03,0.14188e-03,0.19132e-03]\n kb[:,57-12, 8] = [0.40866e-04,0.58631e-04,0.83096e-04,0.11753e-03,0.16055e-03]\n kb[:,58-12, 8] = [0.32890e-04,0.47893e-04,0.68644e-04,0.98156e-04,0.13564e-03]\n kb[:,59-12, 8] = [0.29702e-04,0.43928e-04,0.64217e-04,0.92621e-04,0.12965e-03]\n kb[:,13-12, 9] = [0.27690e+01,0.28644e+01,0.29696e+01,0.30850e+01,0.32162e+01]\n kb[:,14-12, 9] = [0.23162e+01,0.23973e+01,0.24876e+01,0.25913e+01,0.27107e+01]\n kb[:,15-12, 9] = [0.19377e+01,0.20096e+01,0.20909e+01,0.21846e+01,0.22904e+01]\n kb[:,16-12, 9] = [0.16221e+01,0.16854e+01,0.17596e+01,0.18440e+01,0.19374e+01]\n kb[:,17-12, 9] = [0.13581e+01,0.14147e+01,0.14813e+01,0.15562e+01,0.16364e+01]\n kb[:,18-12, 9] = [0.11494e+01,0.11995e+01,0.12558e+01,0.13168e+01,0.13828e+01]\n kb[:,19-12, 9] = [0.99857e+00,0.10422e+01,0.10890e+01,0.11391e+01,0.11917e+01]\n kb[:,20-12, 9] = [0.86585e+00,0.90292e+00,0.94341e+00,0.98616e+00,0.10332e+01]\n kb[:,21-12, 9] = [0.74752e+00,0.77983e+00,0.81433e+00,0.85283e+00,0.89462e+00]\n kb[:,22-12, 9] = [0.64494e+00,0.67286e+00,0.70277e+00,0.73658e+00,0.77352e+00]\n kb[:,23-12, 9] = [0.55485e+00,0.57897e+00,0.60654e+00,0.63699e+00,0.66979e+00]\n kb[:,24-12, 9] = [0.47664e+00,0.49869e+00,0.52329e+00,0.54973e+00,0.57955e+00]\n kb[:,25-12, 9] = [0.41114e+00,0.42988e+00,0.45044e+00,0.47447e+00,0.50163e+00]\n kb[:,26-12, 9] = [0.35513e+00,0.37142e+00,0.38942e+00,0.41045e+00,0.43493e+00]\n kb[:,27-12, 9] = [0.30546e+00,0.31995e+00,0.33673e+00,0.35597e+00,0.37742e+00]\n kb[:,28-12, 9] = [0.26188e+00,0.27552e+00,0.29117e+00,0.30879e+00,0.32839e+00]\n kb[:,29-12, 9] = [0.22377e+00,0.23654e+00,0.25102e+00,0.26735e+00,0.28587e+00]\n kb[:,30-12, 9] = [0.19129e+00,0.20332e+00,0.21691e+00,0.23233e+00,0.24924e+00]\n kb[:,31-12, 9] = [0.16347e+00,0.17463e+00,0.18745e+00,0.20165e+00,0.21712e+00]\n kb[:,32-12, 9] = [0.14037e+00,0.15075e+00,0.16282e+00,0.17567e+00,0.18973e+00]\n kb[:,33-12, 9] = [0.12095e+00,0.13081e+00,0.14161e+00,0.15337e+00,0.16632e+00]\n kb[:,34-12, 9] = [0.10468e+00,0.11371e+00,0.12351e+00,0.13423e+00,0.14632e+00]\n kb[:,35-12, 9] = [0.90259e-01,0.98421e-01,0.10717e+00,0.11695e+00,0.12831e+00]\n kb[:,36-12, 9] = [0.77272e-01,0.84599e-01,0.92464e-01,0.10140e+00,0.11193e+00]\n kb[:,37-12, 9] = [0.65606e-01,0.72029e-01,0.79063e-01,0.87174e-01,0.96643e-01]\n kb[:,38-12, 9] = [0.55528e-01,0.61268e-01,0.67613e-01,0.74898e-01,0.83456e-01]\n kb[:,39-12, 9] = [0.46985e-01,0.52085e-01,0.57765e-01,0.64303e-01,0.72021e-01]\n kb[:,40-12, 9] = [0.39626e-01,0.44094e-01,0.49150e-01,0.55005e-01,0.61884e-01]\n kb[:,41-12, 9] = [0.33376e-01,0.37326e-01,0.41783e-01,0.46997e-01,0.53158e-01]\n kb[:,42-12, 9] = [0.28074e-01,0.31535e-01,0.35493e-01,0.40112e-01,0.45645e-01]\n kb[:,43-12, 9] = [0.23419e-01,0.26419e-01,0.29889e-01,0.33982e-01,0.38867e-01]\n kb[:,44-12, 9] = [0.19437e-01,0.22035e-01,0.25042e-01,0.28622e-01,0.32930e-01]\n kb[:,45-12, 9] = [0.16083e-01,0.18329e-01,0.20937e-01,0.24027e-01,0.27786e-01]\n kb[:,46-12, 9] = [0.13236e-01,0.15146e-01,0.17420e-01,0.20094e-01,0.23328e-01]\n kb[:,47-12, 9] = [0.10820e-01,0.12455e-01,0.14377e-01,0.16656e-01,0.19464e-01]\n kb[:,48-12, 9] = [0.88043e-02,0.10190e-01,0.11813e-01,0.13745e-01,0.16141e-01]\n kb[:,49-12, 9] = [0.71234e-02,0.82775e-02,0.96453e-02,0.11284e-01,0.13310e-01]\n kb[:,50-12, 9] = [0.58127e-02,0.67802e-02,0.79379e-02,0.93254e-02,0.11078e-01]\n kb[:,51-12, 9] = [0.47494e-02,0.55659e-02,0.65602e-02,0.77407e-02,0.92288e-02]\n kb[:,52-12, 9] = [0.38618e-02,0.45424e-02,0.53925e-02,0.64011e-02,0.76645e-02]\n kb[:,53-12, 9] = [0.31264e-02,0.36823e-02,0.43952e-02,0.52615e-02,0.63311e-02]\n kb[:,54-12, 9] = [0.25794e-02,0.30481e-02,0.36548e-02,0.44037e-02,0.53380e-02]\n kb[:,55-12, 9] = [0.21508e-02,0.25472e-02,0.30665e-02,0.37188e-02,0.45472e-02]\n kb[:,56-12, 9] = [0.17938e-02,0.21263e-02,0.25713e-02,0.31411e-02,0.38667e-02]\n kb[:,57-12, 9] = [0.14949e-02,0.17755e-02,0.21510e-02,0.26439e-02,0.32830e-02]\n kb[:,58-12, 9] = [0.12521e-02,0.14938e-02,0.18137e-02,0.22426e-02,0.28028e-02]\n kb[:,59-12, 9] = [0.11302e-02,0.13552e-02,0.16582e-02,0.20691e-02,0.26051e-02]\n kb[:,13-12,10] = [0.14370e+02,0.14649e+02,0.14957e+02,0.15296e+02,0.15663e+02]\n kb[:,14-12,10] = [0.12178e+02,0.12411e+02,0.12682e+02,0.12978e+02,0.13316e+02]\n kb[:,15-12,10] = [0.10211e+02,0.10402e+02,0.10625e+02,0.10894e+02,0.11239e+02]\n kb[:,16-12,10] = [0.85974e+01,0.87539e+01,0.89410e+01,0.91849e+01,0.95108e+01]\n kb[:,17-12,10] = [0.72440e+01,0.73858e+01,0.75683e+01,0.78199e+01,0.81516e+01]\n kb[:,18-12,10] = [0.59680e+01,0.61054e+01,0.63108e+01,0.66074e+01,0.69367e+01]\n kb[:,19-12,10] = [0.47759e+01,0.49000e+01,0.51125e+01,0.53858e+01,0.56972e+01]\n kb[:,20-12,10] = [0.40682e+01,0.42060e+01,0.43988e+01,0.46035e+01,0.48052e+01]\n kb[:,21-12,10] = [0.35226e+01,0.36715e+01,0.38357e+01,0.40017e+01,0.41636e+01]\n kb[:,22-12,10] = [0.30730e+01,0.32059e+01,0.33607e+01,0.35055e+01,0.36621e+01]\n kb[:,23-12,10] = [0.26688e+01,0.27999e+01,0.29296e+01,0.30668e+01,0.32115e+01]\n kb[:,24-12,10] = [0.23228e+01,0.24338e+01,0.25510e+01,0.26866e+01,0.28223e+01]\n kb[:,25-12,10] = [0.19964e+01,0.21083e+01,0.22332e+01,0.23566e+01,0.24845e+01]\n kb[:,26-12,10] = [0.17097e+01,0.18190e+01,0.19420e+01,0.20663e+01,0.21952e+01]\n kb[:,27-12,10] = [0.14729e+01,0.15741e+01,0.16825e+01,0.17963e+01,0.19295e+01]\n kb[:,28-12,10] = [0.12788e+01,0.13609e+01,0.14562e+01,0.15668e+01,0.17032e+01]\n kb[:,29-12,10] = [0.11113e+01,0.11813e+01,0.12669e+01,0.13763e+01,0.15012e+01]\n kb[:,30-12,10] = [0.96661e+00,0.10287e+01,0.11081e+01,0.12093e+01,0.13273e+01]\n kb[:,31-12,10] = [0.83795e+00,0.89792e+00,0.97327e+00,0.10727e+01,0.11828e+01]\n kb[:,32-12,10] = [0.72634e+00,0.78480e+00,0.86071e+00,0.95503e+00,0.10615e+01]\n kb[:,33-12,10] = [0.63134e+00,0.68789e+00,0.76628e+00,0.85854e+00,0.96370e+00]\n kb[:,34-12,10] = [0.55172e+00,0.60863e+00,0.68672e+00,0.77637e+00,0.87664e+00]\n kb[:,35-12,10] = [0.48039e+00,0.53701e+00,0.61125e+00,0.69795e+00,0.79084e+00]\n kb[:,36-12,10] = [0.41819e+00,0.47188e+00,0.54096e+00,0.62096e+00,0.70693e+00]\n kb[:,37-12,10] = [0.36050e+00,0.40906e+00,0.47069e+00,0.54184e+00,0.62144e+00]\n kb[:,38-12,10] = [0.31156e+00,0.35409e+00,0.40958e+00,0.47371e+00,0.54611e+00]\n kb[:,39-12,10] = [0.26782e+00,0.30677e+00,0.35645e+00,0.41535e+00,0.48073e+00]\n kb[:,40-12,10] = [0.23006e+00,0.26273e+00,0.30670e+00,0.35934e+00,0.41871e+00]\n kb[:,41-12,10] = [0.19681e+00,0.22601e+00,0.26383e+00,0.31041e+00,0.36443e+00]\n kb[:,42-12,10] = [0.16794e+00,0.19457e+00,0.22757e+00,0.26875e+00,0.31708e+00]\n kb[:,43-12,10] = [0.14222e+00,0.16606e+00,0.19480e+00,0.23049e+00,0.27422e+00]\n kb[:,44-12,10] = [0.11907e+00,0.14059e+00,0.16567e+00,0.19741e+00,0.23557e+00]\n kb[:,45-12,10] = [0.99508e-01,0.11792e+00,0.14029e+00,0.16912e+00,0.20294e+00]\n kb[:,46-12,10] = [0.82787e-01,0.98729e-01,0.11783e+00,0.14344e+00,0.17433e+00]\n kb[:,47-12,10] = [0.68205e-01,0.81739e-01,0.98558e-01,0.12017e+00,0.14798e+00]\n kb[:,48-12,10] = [0.55907e-01,0.67050e-01,0.81465e-01,0.10030e+00,0.12506e+00]\n kb[:,49-12,10] = [0.45682e-01,0.54871e-01,0.66950e-01,0.83270e-01,0.10500e+00]\n kb[:,50-12,10] = [0.37515e-01,0.45259e-01,0.55584e-01,0.69475e-01,0.88432e-01]\n kb[:,51-12,10] = [0.31052e-01,0.37347e-01,0.46136e-01,0.58029e-01,0.74379e-01]\n kb[:,52-12,10] = [0.25697e-01,0.30758e-01,0.38027e-01,0.48169e-01,0.62340e-01]\n kb[:,53-12,10] = [0.21053e-01,0.25282e-01,0.31221e-01,0.39765e-01,0.52061e-01]\n kb[:,54-12,10] = [0.17506e-01,0.21171e-01,0.26181e-01,0.33450e-01,0.43837e-01]\n kb[:,55-12,10] = [0.14733e-01,0.17912e-01,0.22352e-01,0.28517e-01,0.37310e-01]\n kb[:,56-12,10] = [0.12382e-01,0.15138e-01,0.19031e-01,0.24337e-01,0.31780e-01]\n kb[:,57-12,10] = [0.10363e-01,0.12802e-01,0.16188e-01,0.20731e-01,0.27252e-01]\n kb[:,58-12,10] = [0.87632e-02,0.10863e-01,0.13823e-01,0.17907e-01,0.23570e-01]\n kb[:,59-12,10] = [0.79477e-02,0.99708e-02,0.12797e-01,0.16832e-01,0.22384e-01]\n kb[:,13-12,11] = [0.27028e+02,0.27753e+02,0.28483e+02,0.29219e+02,0.29909e+02]\n kb[:,14-12,11] = [0.23419e+02,0.24025e+02,0.24638e+02,0.25228e+02,0.25789e+02]\n kb[:,15-12,11] = [0.20150e+02,0.20660e+02,0.21151e+02,0.21642e+02,0.22118e+02]\n kb[:,16-12,11] = [0.17107e+02,0.17510e+02,0.17925e+02,0.18355e+02,0.18823e+02]\n kb[:,17-12,11] = [0.14361e+02,0.14686e+02,0.15035e+02,0.15422e+02,0.15903e+02]\n kb[:,18-12,11] = [0.12138e+02,0.12397e+02,0.12696e+02,0.13058e+02,0.13553e+02]\n kb[:,19-12,11] = [0.10135e+02,0.10395e+02,0.10708e+02,0.11115e+02,0.11638e+02]\n kb[:,20-12,11] = [0.81786e+01,0.84190e+01,0.87492e+01,0.92221e+01,0.97673e+01]\n kb[:,21-12,11] = [0.68203e+01,0.70074e+01,0.73249e+01,0.77062e+01,0.81227e+01]\n kb[:,22-12,11] = [0.58880e+01,0.61142e+01,0.64089e+01,0.67273e+01,0.70540e+01]\n kb[:,23-12,11] = [0.51482e+01,0.53972e+01,0.56613e+01,0.59190e+01,0.62039e+01]\n kb[:,24-12,11] = [0.45460e+01,0.47798e+01,0.50055e+01,0.52340e+01,0.54793e+01]\n kb[:,25-12,11] = [0.40038e+01,0.42162e+01,0.44356e+01,0.46519e+01,0.48861e+01]\n kb[:,26-12,11] = [0.35330e+01,0.37282e+01,0.39261e+01,0.41342e+01,0.43614e+01]\n kb[:,27-12,11] = [0.30918e+01,0.32790e+01,0.34783e+01,0.36774e+01,0.38933e+01]\n kb[:,28-12,11] = [0.27019e+01,0.28880e+01,0.30842e+01,0.32755e+01,0.34826e+01]\n kb[:,29-12,11] = [0.23567e+01,0.25399e+01,0.27237e+01,0.29118e+01,0.31184e+01]\n kb[:,30-12,11] = [0.20673e+01,0.22421e+01,0.24146e+01,0.26001e+01,0.28136e+01]\n kb[:,31-12,11] = [0.18233e+01,0.19796e+01,0.21491e+01,0.23275e+01,0.25391e+01]\n kb[:,32-12,11] = [0.16164e+01,0.17629e+01,0.19137e+01,0.20921e+01,0.23020e+01]\n kb[:,33-12,11] = [0.14325e+01,0.15691e+01,0.17171e+01,0.18965e+01,0.20991e+01]\n kb[:,34-12,11] = [0.12711e+01,0.14025e+01,0.15514e+01,0.17231e+01,0.19204e+01]\n kb[:,35-12,11] = [0.11251e+01,0.12478e+01,0.13948e+01,0.15591e+01,0.17428e+01]\n kb[:,36-12,11] = [0.98734e+00,0.11026e+01,0.12425e+01,0.13991e+01,0.15730e+01]\n kb[:,37-12,11] = [0.85152e+00,0.96327e+00,0.10911e+01,0.12398e+01,0.14045e+01]\n kb[:,38-12,11] = [0.73399e+00,0.83942e+00,0.95984e+00,0.10967e+01,0.12526e+01]\n kb[:,39-12,11] = [0.63468e+00,0.73175e+00,0.84488e+00,0.97279e+00,0.11163e+01]\n kb[:,40-12,11] = [0.54166e+00,0.63099e+00,0.73459e+00,0.85525e+00,0.98986e+00]\n kb[:,41-12,11] = [0.46341e+00,0.54185e+00,0.63786e+00,0.75041e+00,0.87557e+00]\n kb[:,42-12,11] = [0.39710e+00,0.46604e+00,0.55335e+00,0.65788e+00,0.77518e+00]\n kb[:,43-12,11] = [0.33809e+00,0.39845e+00,0.47656e+00,0.56991e+00,0.67763e+00]\n kb[:,44-12,11] = [0.28738e+00,0.33811e+00,0.40783e+00,0.49238e+00,0.58805e+00]\n kb[:,45-12,11] = [0.24372e+00,0.28787e+00,0.34858e+00,0.42338e+00,0.51131e+00]\n kb[:,46-12,11] = [0.20655e+00,0.24407e+00,0.29751e+00,0.36239e+00,0.44206e+00]\n kb[:,47-12,11] = [0.17359e+00,0.20653e+00,0.25158e+00,0.30900e+00,0.37888e+00]\n kb[:,48-12,11] = [0.14508e+00,0.17395e+00,0.21335e+00,0.26232e+00,0.32328e+00]\n kb[:,49-12,11] = [0.12016e+00,0.14523e+00,0.17928e+00,0.22128e+00,0.27412e+00]\n kb[:,50-12,11] = [0.99920e-01,0.12218e+00,0.15097e+00,0.18907e+00,0.23575e+00]\n kb[:,51-12,11] = [0.82909e-01,0.10226e+00,0.12737e+00,0.16132e+00,0.20378e+00]\n kb[:,52-12,11] = [0.68577e-01,0.85131e-01,0.10673e+00,0.13644e+00,0.17453e+00]\n kb[:,53-12,11] = [0.56302e-01,0.70491e-01,0.88684e-01,0.11469e+00,0.14786e+00]\n kb[:,54-12,11] = [0.47171e-01,0.59185e-01,0.74877e-01,0.97387e-01,0.12762e+00]\n kb[:,55-12,11] = [0.40028e-01,0.50199e-01,0.63960e-01,0.83211e-01,0.11104e+00]\n kb[:,56-12,11] = [0.33854e-01,0.42508e-01,0.54649e-01,0.71262e-01,0.95596e-01]\n kb[:,57-12,11] = [0.28590e-01,0.36142e-01,0.46409e-01,0.61269e-01,0.82012e-01]\n kb[:,58-12,11] = [0.24352e-01,0.30934e-01,0.39697e-01,0.52483e-01,0.71167e-01]\n kb[:,59-12,11] = [0.22598e-01,0.29152e-01,0.37468e-01,0.48573e-01,0.66434e-01]\n kb[:,13-12,12] = [0.57172e+02,0.59297e+02,0.61400e+02,0.63512e+02,0.65627e+02]\n kb[:,14-12,12] = [0.50361e+02,0.52086e+02,0.53828e+02,0.55595e+02,0.57346e+02]\n kb[:,15-12,12] = [0.44078e+02,0.45453e+02,0.46902e+02,0.48347e+02,0.49789e+02]\n kb[:,16-12,12] = [0.38395e+02,0.39554e+02,0.40754e+02,0.41955e+02,0.43150e+02]\n kb[:,17-12,12] = [0.33363e+02,0.34355e+02,0.35352e+02,0.36337e+02,0.37312e+02]\n kb[:,18-12,12] = [0.28599e+02,0.29463e+02,0.30307e+02,0.31155e+02,0.32043e+02]\n kb[:,19-12,12] = [0.24284e+02,0.24982e+02,0.25685e+02,0.26424e+02,0.27289e+02]\n kb[:,20-12,12] = [0.20576e+02,0.21117e+02,0.21693e+02,0.22370e+02,0.23304e+02]\n kb[:,21-12,12] = [0.17126e+02,0.17629e+02,0.18193e+02,0.18968e+02,0.20012e+02]\n kb[:,22-12,12] = [0.14084e+02,0.14526e+02,0.15112e+02,0.15986e+02,0.17086e+02]\n kb[:,23-12,12] = [0.11727e+02,0.12073e+02,0.12663e+02,0.13546e+02,0.14594e+02]\n kb[:,24-12,12] = [0.10116e+02,0.10483e+02,0.11087e+02,0.11839e+02,0.12630e+02]\n kb[:,25-12,12] = [0.89362e+01,0.93748e+01,0.99578e+01,0.10576e+02,0.11263e+02]\n kb[:,26-12,12] = [0.79574e+01,0.84325e+01,0.89960e+01,0.95862e+01,0.10135e+02]\n kb[:,27-12,12] = [0.71290e+01,0.76343e+01,0.81343e+01,0.86609e+01,0.91441e+01]\n kb[:,28-12,12] = [0.64441e+01,0.69081e+01,0.73340e+01,0.77892e+01,0.82579e+01]\n kb[:,29-12,12] = [0.57859e+01,0.61904e+01,0.65762e+01,0.69937e+01,0.74255e+01]\n kb[:,30-12,12] = [0.51602e+01,0.55338e+01,0.58953e+01,0.62766e+01,0.66823e+01]\n kb[:,31-12,12] = [0.45943e+01,0.49270e+01,0.52739e+01,0.56298e+01,0.60118e+01]\n kb[:,32-12,12] = [0.40881e+01,0.44095e+01,0.47450e+01,0.50839e+01,0.54488e+01]\n kb[:,33-12,12] = [0.36534e+01,0.39549e+01,0.42670e+01,0.46043e+01,0.49743e+01]\n kb[:,34-12,12] = [0.32874e+01,0.35667e+01,0.38571e+01,0.41872e+01,0.45862e+01]\n kb[:,35-12,12] = [0.29379e+01,0.31963e+01,0.34845e+01,0.38151e+01,0.42290e+01]\n kb[:,36-12,12] = [0.26101e+01,0.28628e+01,0.31405e+01,0.34760e+01,0.38927e+01]\n kb[:,37-12,12] = [0.23047e+01,0.25368e+01,0.28124e+01,0.31292e+01,0.35310e+01]\n kb[:,38-12,12] = [0.20413e+01,0.22603e+01,0.25129e+01,0.28252e+01,0.32149e+01]\n kb[:,39-12,12] = [0.18040e+01,0.20133e+01,0.22565e+01,0.25571e+01,0.29423e+01]\n kb[:,40-12,12] = [0.15898e+01,0.17862e+01,0.20189e+01,0.22992e+01,0.26576e+01]\n kb[:,41-12,12] = [0.14002e+01,0.15861e+01,0.18008e+01,0.20620e+01,0.24028e+01]\n kb[:,42-12,12] = [0.12302e+01,0.14049e+01,0.16015e+01,0.18444e+01,0.21658e+01]\n kb[:,43-12,12] = [0.10668e+01,0.12258e+01,0.14101e+01,0.16347e+01,0.19297e+01]\n kb[:,44-12,12] = [0.91800e+00,0.10642e+01,0.12324e+01,0.14347e+01,0.17074e+01]\n kb[:,45-12,12] = [0.78687e+00,0.91967e+00,0.10737e+01,0.12598e+01,0.15049e+01]\n kb[:,46-12,12] = [0.67148e+00,0.79041e+00,0.92761e+00,0.10973e+01,0.13177e+01]\n kb[:,47-12,12] = [0.57045e+00,0.67640e+00,0.80034e+00,0.94779e+00,0.11432e+01]\n kb[:,48-12,12] = [0.48142e+00,0.57646e+00,0.68676e+00,0.82116e+00,0.98898e+00]\n kb[:,49-12,12] = [0.40194e+00,0.48757e+00,0.58498e+00,0.70838e+00,0.85881e+00]\n kb[:,50-12,12] = [0.34095e+00,0.41499e+00,0.50425e+00,0.61464e+00,0.75451e+00]\n kb[:,51-12,12] = [0.29038e+00,0.35608e+00,0.43553e+00,0.53422e+00,0.66315e+00]\n kb[:,52-12,12] = [0.24615e+00,0.30360e+00,0.37359e+00,0.46378e+00,0.57808e+00]\n kb[:,53-12,12] = [0.20660e+00,0.25764e+00,0.31993e+00,0.39869e+00,0.50232e+00]\n kb[:,54-12,12] = [0.17518e+00,0.22280e+00,0.27852e+00,0.34881e+00,0.44243e+00]\n kb[:,55-12,12] = [0.14906e+00,0.19392e+00,0.24538e+00,0.31045e+00,0.39204e+00]\n kb[:,56-12,12] = [0.12564e+00,0.16748e+00,0.21535e+00,0.27386e+00,0.34816e+00]\n kb[:,57-12,12] = [0.10489e+00,0.14334e+00,0.18902e+00,0.24147e+00,0.30976e+00]\n kb[:,58-12,12] = [0.88415e-01,0.12250e+00,0.16566e+00,0.21499e+00,0.27515e+00]\n kb[:,59-12,12] = [0.80710e-01,0.11375e+00,0.15629e+00,0.20737e+00,0.26838e+00]\n kb[:,13-12,13] = [0.16465e+03,0.16298e+03,0.16413e+03,0.16796e+03,0.17425e+03]\n kb[:,14-12,13] = [0.14134e+03,0.14223e+03,0.14584e+03,0.15183e+03,0.15823e+03]\n kb[:,15-12,13] = [0.12334e+03,0.12642e+03,0.13170e+03,0.13719e+03,0.14248e+03]\n kb[:,16-12,13] = [0.10903e+03,0.11350e+03,0.11825e+03,0.12284e+03,0.12720e+03]\n kb[:,17-12,13] = [0.96744e+02,0.10077e+03,0.10473e+03,0.10856e+03,0.11225e+03]\n kb[:,18-12,13] = [0.85368e+02,0.88669e+02,0.91934e+02,0.95127e+02,0.98216e+02]\n kb[:,19-12,13] = [0.74865e+02,0.77560e+02,0.80263e+02,0.82912e+02,0.85499e+02]\n kb[:,20-12,13] = [0.65304e+02,0.67588e+02,0.69849e+02,0.72099e+02,0.74316e+02]\n kb[:,21-12,13] = [0.56704e+02,0.58616e+02,0.60541e+02,0.62457e+02,0.64444e+02]\n kb[:,22-12,13] = [0.49099e+02,0.50788e+02,0.52451e+02,0.54119e+02,0.55970e+02]\n kb[:,23-12,13] = [0.42076e+02,0.43646e+02,0.45230e+02,0.46888e+02,0.48798e+02]\n kb[:,24-12,13] = [0.35457e+02,0.36904e+02,0.38447e+02,0.40262e+02,0.42565e+02]\n kb[:,25-12,13] = [0.29832e+02,0.31036e+02,0.32508e+02,0.34502e+02,0.36979e+02]\n kb[:,26-12,13] = [0.25205e+02,0.26348e+02,0.27792e+02,0.29788e+02,0.32459e+02]\n kb[:,27-12,13] = [0.21486e+02,0.22586e+02,0.24162e+02,0.26260e+02,0.28944e+02]\n kb[:,28-12,13] = [0.18712e+02,0.19693e+02,0.21370e+02,0.23591e+02,0.26158e+02]\n kb[:,29-12,13] = [0.16630e+02,0.17716e+02,0.19369e+02,0.21565e+02,0.24102e+02]\n kb[:,30-12,13] = [0.14923e+02,0.16119e+02,0.17783e+02,0.19989e+02,0.22379e+02]\n kb[:,31-12,13] = [0.13532e+02,0.14853e+02,0.16576e+02,0.18745e+02,0.21084e+02]\n kb[:,32-12,13] = [0.12453e+02,0.13784e+02,0.15587e+02,0.17718e+02,0.20022e+02]\n kb[:,33-12,13] = [0.11580e+02,0.13038e+02,0.14851e+02,0.16892e+02,0.19192e+02]\n kb[:,34-12,13] = [0.10820e+02,0.12376e+02,0.14134e+02,0.16152e+02,0.18402e+02]\n kb[:,35-12,13] = [0.10116e+02,0.11686e+02,0.13402e+02,0.15346e+02,0.17556e+02]\n kb[:,36-12,13] = [0.93933e+01,0.10910e+02,0.12572e+02,0.14432e+02,0.16536e+02]\n kb[:,37-12,13] = [0.85160e+01,0.99755e+01,0.11554e+02,0.13358e+02,0.15350e+02]\n kb[:,38-12,13] = [0.77505e+01,0.91225e+01,0.10670e+02,0.12380e+02,0.14273e+02]\n kb[:,39-12,13] = [0.70897e+01,0.83885e+01,0.98694e+01,0.11502e+02,0.13343e+02]\n kb[:,40-12,13] = [0.63295e+01,0.75506e+01,0.89466e+01,0.10495e+02,0.12287e+02]\n kb[:,41-12,13] = [0.56302e+01,0.67988e+01,0.80957e+01,0.96013e+01,0.11280e+02]\n kb[:,42-12,13] = [0.50234e+01,0.61071e+01,0.73389e+01,0.87816e+01,0.10380e+02]\n kb[:,43-12,13] = [0.44225e+01,0.54282e+01,0.65963e+01,0.79433e+01,0.94666e+01]\n kb[:,44-12,13] = [0.38558e+01,0.47912e+01,0.58905e+01,0.71478e+01,0.86145e+01]\n kb[:,45-12,13] = [0.33575e+01,0.42351e+01,0.52475e+01,0.64292e+01,0.78296e+01]\n kb[:,46-12,13] = [0.29053e+01,0.37074e+01,0.46432e+01,0.57484e+01,0.70674e+01]\n kb[:,47-12,13] = [0.24706e+01,0.31851e+01,0.40524e+01,0.50837e+01,0.62990e+01]\n kb[:,48-12,13] = [0.20907e+01,0.27320e+01,0.35232e+01,0.44689e+01,0.55998e+01]\n kb[:,49-12,13] = [0.17652e+01,0.23397e+01,0.30525e+01,0.39130e+01,0.49641e+01]\n kb[:,50-12,13] = [0.14980e+01,0.19995e+01,0.26386e+01,0.34309e+01,0.43930e+01]\n kb[:,51-12,13] = [0.12883e+01,0.17229e+01,0.22808e+01,0.30058e+01,0.38921e+01]\n kb[:,52-12,13] = [0.11032e+01,0.14878e+01,0.19945e+01,0.26225e+01,0.34327e+01]\n kb[:,53-12,13] = [0.94256e+00,0.12803e+01,0.17436e+01,0.23095e+01,0.30258e+01]\n kb[:,54-12,13] = [0.80847e+00,0.11045e+01,0.15250e+01,0.20573e+01,0.27048e+01]\n kb[:,55-12,13] = [0.69972e+00,0.95008e+00,0.13215e+01,0.18178e+01,0.24326e+01]\n kb[:,56-12,13] = [0.60659e+00,0.81298e+00,0.11430e+01,0.15925e+01,0.21783e+01]\n kb[:,57-12,13] = [0.52664e+00,0.69670e+00,0.97998e+00,0.13891e+01,0.19333e+01]\n kb[:,58-12,13] = [0.45985e+00,0.60682e+00,0.84337e+00,0.12113e+01,0.17188e+01]\n kb[:,59-12,13] = [0.43853e+00,0.57879e+00,0.79018e+00,0.11130e+01,0.16039e+01]\n kb[:,13-12,14] = [0.86016e+03,0.84626e+03,0.83228e+03,0.81817e+03,0.80450e+03]\n kb[:,14-12,14] = [0.75981e+03,0.74663e+03,0.73345e+03,0.72104e+03,0.71224e+03]\n kb[:,15-12,14] = [0.66201e+03,0.64993e+03,0.63891e+03,0.63210e+03,0.62978e+03]\n kb[:,16-12,14] = [0.57014e+03,0.56027e+03,0.55466e+03,0.55378e+03,0.55721e+03]\n kb[:,17-12,14] = [0.48861e+03,0.48354e+03,0.48324e+03,0.48760e+03,0.49602e+03]\n kb[:,18-12,14] = [0.41987e+03,0.41964e+03,0.42411e+03,0.43291e+03,0.44575e+03]\n kb[:,19-12,14] = [0.36303e+03,0.36702e+03,0.37556e+03,0.38834e+03,0.40471e+03]\n kb[:,20-12,14] = [0.31651e+03,0.32421e+03,0.33627e+03,0.35219e+03,0.37072e+03]\n kb[:,21-12,14] = [0.27867e+03,0.28947e+03,0.30434e+03,0.32131e+03,0.33823e+03]\n kb[:,22-12,14] = [0.24916e+03,0.26251e+03,0.27768e+03,0.29296e+03,0.30844e+03]\n kb[:,23-12,14] = [0.22571e+03,0.23932e+03,0.25291e+03,0.26670e+03,0.28069e+03]\n kb[:,24-12,14] = [0.20503e+03,0.21765e+03,0.23029e+03,0.24291e+03,0.25575e+03]\n kb[:,25-12,14] = [0.18574e+03,0.19763e+03,0.20960e+03,0.22151e+03,0.23356e+03]\n kb[:,26-12,14] = [0.16825e+03,0.17945e+03,0.19085e+03,0.20242e+03,0.21406e+03]\n kb[:,27-12,14] = [0.15254e+03,0.16311e+03,0.17402e+03,0.18521e+03,0.19696e+03]\n kb[:,28-12,14] = [0.13815e+03,0.14857e+03,0.15913e+03,0.17022e+03,0.18238e+03]\n kb[:,29-12,14] = [0.12560e+03,0.13571e+03,0.14630e+03,0.15763e+03,0.17019e+03]\n kb[:,30-12,14] = [0.11497e+03,0.12476e+03,0.13550e+03,0.14719e+03,0.16044e+03]\n kb[:,31-12,14] = [0.10602e+03,0.11577e+03,0.12671e+03,0.13889e+03,0.15289e+03]\n kb[:,32-12,14] = [0.98519e+02,0.10855e+03,0.11978e+03,0.13265e+03,0.14744e+03]\n kb[:,33-12,14] = [0.92517e+02,0.10274e+03,0.11452e+03,0.12822e+03,0.14389e+03]\n kb[:,34-12,14] = [0.87441e+02,0.97936e+02,0.11044e+03,0.12495e+03,0.14148e+03]\n kb[:,35-12,14] = [0.82499e+02,0.93333e+02,0.10635e+03,0.12151e+03,0.13874e+03]\n kb[:,36-12,14] = [0.77442e+02,0.88493e+02,0.10184e+03,0.11740e+03,0.13513e+03]\n kb[:,37-12,14] = [0.71771e+02,0.82731e+02,0.96032e+02,0.11158e+03,0.12941e+03]\n kb[:,38-12,14] = [0.66727e+02,0.77610e+02,0.90795e+02,0.10632e+03,0.12415e+03]\n kb[:,39-12,14] = [0.62339e+02,0.73113e+02,0.86200e+02,0.10167e+03,0.11942e+03]\n kb[:,40-12,14] = [0.57601e+02,0.67999e+02,0.80724e+02,0.95858e+02,0.11323e+03]\n kb[:,41-12,14] = [0.53285e+02,0.63203e+02,0.75577e+02,0.90242e+02,0.10726e+03]\n kb[:,42-12,14] = [0.49392e+02,0.58908e+02,0.70834e+02,0.85045e+02,0.10163e+03]\n kb[:,43-12,14] = [0.45446e+02,0.54452e+02,0.65751e+02,0.79402e+02,0.95397e+02]\n kb[:,44-12,14] = [0.41620e+02,0.50184e+02,0.60777e+02,0.73786e+02,0.89076e+02]\n kb[:,45-12,14] = [0.38059e+02,0.46282e+02,0.56226e+02,0.68539e+02,0.83136e+02]\n kb[:,46-12,14] = [0.34554e+02,0.42501e+02,0.51829e+02,0.63383e+02,0.77220e+02]\n kb[:,47-12,14] = [0.31009e+02,0.38610e+02,0.47385e+02,0.58058e+02,0.71080e+02]\n kb[:,48-12,14] = [0.27715e+02,0.34934e+02,0.43319e+02,0.53190e+02,0.65347e+02]\n kb[:,49-12,14] = [0.24658e+02,0.31478e+02,0.39500e+02,0.48743e+02,0.59997e+02]\n kb[:,50-12,14] = [0.22034e+02,0.28437e+02,0.36093e+02,0.44894e+02,0.55346e+02]\n kb[:,51-12,14] = [0.19684e+02,0.25626e+02,0.32937e+02,0.41385e+02,0.51154e+02]\n kb[:,52-12,14] = [0.17504e+02,0.22995e+02,0.29925e+02,0.38057e+02,0.47307e+02]\n kb[:,53-12,14] = [0.15552e+02,0.20544e+02,0.27079e+02,0.34832e+02,0.43722e+02]\n kb[:,54-12,14] = [0.13886e+02,0.18476e+02,0.24607e+02,0.31966e+02,0.40540e+02]\n kb[:,55-12,14] = [0.12396e+02,0.16681e+02,0.22385e+02,0.29384e+02,0.37592e+02]\n kb[:,56-12,14] = [0.11028e+02,0.15006e+02,0.20297e+02,0.26955e+02,0.34780e+02]\n kb[:,57-12,14] = [0.97493e+01,0.13452e+02,0.18354e+02,0.24644e+02,0.32099e+02]\n kb[:,58-12,14] = [0.86411e+01,0.12068e+02,0.16627e+02,0.22569e+02,0.29684e+02]\n kb[:,59-12,14] = [0.80894e+01,0.11449e+02,0.15905e+02,0.21753e+02,0.28728e+02]\n kb[:,13-12,15] = [0.50046e+04,0.50034e+04,0.49950e+04,0.49781e+04,0.49542e+04]\n kb[:,14-12,15] = [0.51812e+04,0.51738e+04,0.51582e+04,0.51357e+04,0.51054e+04]\n kb[:,15-12,15] = [0.52793e+04,0.52645e+04,0.52450e+04,0.52172e+04,0.51836e+04]\n kb[:,16-12,15] = [0.53001e+04,0.52818e+04,0.52568e+04,0.52274e+04,0.51924e+04]\n kb[:,17-12,15] = [0.52448e+04,0.52242e+04,0.52004e+04,0.51715e+04,0.51377e+04]\n kb[:,18-12,15] = [0.51200e+04,0.51031e+04,0.50817e+04,0.50571e+04,0.50308e+04]\n kb[:,19-12,15] = [0.49389e+04,0.49284e+04,0.49153e+04,0.49007e+04,0.48819e+04]\n kb[:,20-12,15] = [0.47181e+04,0.47168e+04,0.47163e+04,0.47129e+04,0.47111e+04]\n kb[:,21-12,15] = [0.44718e+04,0.44865e+04,0.44990e+04,0.45153e+04,0.45403e+04]\n kb[:,22-12,15] = [0.42192e+04,0.42497e+04,0.42861e+04,0.43316e+04,0.43809e+04]\n kb[:,23-12,15] = [0.39727e+04,0.40275e+04,0.40936e+04,0.41646e+04,0.42404e+04]\n kb[:,24-12,15] = [0.37507e+04,0.38336e+04,0.39239e+04,0.40206e+04,0.41209e+04]\n kb[:,25-12,15] = [0.35606e+04,0.36694e+04,0.37826e+04,0.39026e+04,0.40244e+04]\n kb[:,26-12,15] = [0.34043e+04,0.35364e+04,0.36731e+04,0.38130e+04,0.39519e+04]\n kb[:,27-12,15] = [0.32803e+04,0.34346e+04,0.35912e+04,0.37476e+04,0.39014e+04]\n kb[:,28-12,15] = [0.31876e+04,0.33610e+04,0.35344e+04,0.37042e+04,0.38699e+04]\n kb[:,29-12,15] = [0.31239e+04,0.33137e+04,0.34995e+04,0.36813e+04,0.38573e+04]\n kb[:,30-12,15] = [0.30850e+04,0.32872e+04,0.34837e+04,0.36745e+04,0.38591e+04]\n kb[:,31-12,15] = [0.30674e+04,0.32795e+04,0.34848e+04,0.36826e+04,0.38724e+04]\n kb[:,32-12,15] = [0.30683e+04,0.32879e+04,0.34990e+04,0.37022e+04,0.38953e+04]\n kb[:,33-12,15] = [0.30831e+04,0.33087e+04,0.35243e+04,0.37303e+04,0.39250e+04]\n kb[:,34-12,15] = [0.31017e+04,0.33308e+04,0.35496e+04,0.37580e+04,0.39527e+04]\n kb[:,35-12,15] = [0.31057e+04,0.33387e+04,0.35601e+04,0.37700e+04,0.39654e+04]\n kb[:,36-12,15] = [0.30895e+04,0.33260e+04,0.35504e+04,0.37630e+04,0.39606e+04]\n kb[:,37-12,15] = [0.30400e+04,0.32811e+04,0.35096e+04,0.37263e+04,0.39277e+04]\n kb[:,38-12,15] = [0.29913e+04,0.32361e+04,0.34690e+04,0.36890e+04,0.38942e+04]\n kb[:,39-12,15] = [0.29441e+04,0.31926e+04,0.34294e+04,0.36526e+04,0.38612e+04]\n kb[:,40-12,15] = [0.28722e+04,0.31254e+04,0.33667e+04,0.35943e+04,0.38073e+04]\n kb[:,41-12,15] = [0.27971e+04,0.30548e+04,0.33004e+04,0.35326e+04,0.37505e+04]\n kb[:,42-12,15] = [0.27226e+04,0.29837e+04,0.32336e+04,0.34701e+04,0.36925e+04]\n kb[:,43-12,15] = [0.26332e+04,0.28981e+04,0.31525e+04,0.33944e+04,0.36223e+04]\n kb[:,44-12,15] = [0.25372e+04,0.28050e+04,0.30643e+04,0.33114e+04,0.35441e+04]\n kb[:,45-12,15] = [0.24417e+04,0.27113e+04,0.29748e+04,0.32268e+04,0.34651e+04]\n kb[:,46-12,15] = [0.23395e+04,0.26115e+04,0.28783e+04,0.31351e+04,0.33792e+04]\n kb[:,47-12,15] = [0.22243e+04,0.24998e+04,0.27694e+04,0.30313e+04,0.32810e+04]\n kb[:,48-12,15] = [0.21083e+04,0.23877e+04,0.26592e+04,0.29257e+04,0.31803e+04]\n kb[:,49-12,15] = [0.19925e+04,0.22741e+04,0.25488e+04,0.28180e+04,0.30783e+04]\n kb[:,50-12,15] = [0.18841e+04,0.21666e+04,0.24447e+04,0.27159e+04,0.29806e+04]\n kb[:,51-12,15] = [0.17798e+04,0.20618e+04,0.23428e+04,0.26160e+04,0.28839e+04]\n kb[:,52-12,15] = [0.16762e+04,0.19574e+04,0.22398e+04,0.25156e+04,0.27862e+04]\n kb[:,53-12,15] = [0.15731e+04,0.18530e+04,0.21358e+04,0.24152e+04,0.26872e+04]\n kb[:,54-12,15] = [0.14802e+04,0.17581e+04,0.20401e+04,0.23219e+04,0.25956e+04]\n kb[:,55-12,15] = [0.13915e+04,0.16675e+04,0.19488e+04,0.22318e+04,0.25080e+04]\n kb[:,56-12,15] = [0.13039e+04,0.15778e+04,0.18577e+04,0.21406e+04,0.24200e+04]\n kb[:,57-12,15] = [0.12167e+04,0.14890e+04,0.17672e+04,0.20493e+04,0.23313e+04]\n kb[:,58-12,15] = [0.11349e+04,0.14057e+04,0.16818e+04,0.19631e+04,0.22464e+04]\n kb[:,59-12,15] = [0.11025e+04,0.13721e+04,0.16476e+04,0.19283e+04,0.22117e+04]\n kb[:,13-12,16] = [0.12492e+05,0.12602e+05,0.12678e+05,0.12730e+05,0.12749e+05]\n kb[:,14-12,16] = [0.14696e+05,0.14792e+05,0.14862e+05,0.14890e+05,0.14889e+05]\n kb[:,15-12,16] = [0.17153e+05,0.17242e+05,0.17275e+05,0.17274e+05,0.17231e+05]\n kb[:,16-12,16] = [0.19843e+05,0.19894e+05,0.19898e+05,0.19845e+05,0.19747e+05]\n kb[:,17-12,16] = [0.22727e+05,0.22731e+05,0.22667e+05,0.22551e+05,0.22386e+05]\n kb[:,18-12,16] = [0.25761e+05,0.25684e+05,0.25544e+05,0.25342e+05,0.25070e+05]\n kb[:,19-12,16] = [0.28878e+05,0.28701e+05,0.28454e+05,0.28131e+05,0.27759e+05]\n kb[:,20-12,16] = [0.31981e+05,0.31695e+05,0.31314e+05,0.30871e+05,0.30360e+05]\n kb[:,21-12,16] = [0.35017e+05,0.34575e+05,0.34064e+05,0.33480e+05,0.32821e+05]\n kb[:,22-12,16] = [0.37854e+05,0.37264e+05,0.36589e+05,0.35840e+05,0.35046e+05]\n kb[:,23-12,16] = [0.40473e+05,0.39710e+05,0.38862e+05,0.37967e+05,0.37023e+05]\n kb[:,24-12,16] = [0.42796e+05,0.41864e+05,0.40869e+05,0.39817e+05,0.38718e+05]\n kb[:,25-12,16] = [0.44813e+05,0.43719e+05,0.42578e+05,0.41380e+05,0.40143e+05]\n kb[:,26-12,16] = [0.46504e+05,0.45263e+05,0.43973e+05,0.42641e+05,0.41294e+05]\n kb[:,27-12,16] = [0.47893e+05,0.46507e+05,0.45087e+05,0.43647e+05,0.42197e+05]\n kb[:,28-12,16] = [0.48993e+05,0.47480e+05,0.45952e+05,0.44417e+05,0.42878e+05]\n kb[:,29-12,16] = [0.49823e+05,0.48206e+05,0.46588e+05,0.44969e+05,0.43353e+05]\n kb[:,30-12,16] = [0.50415e+05,0.48716e+05,0.47025e+05,0.45339e+05,0.43659e+05]\n kb[:,31-12,16] = [0.50811e+05,0.49042e+05,0.47288e+05,0.45543e+05,0.43813e+05]\n kb[:,32-12,16] = [0.51032e+05,0.49203e+05,0.47400e+05,0.45610e+05,0.43841e+05]\n kb[:,33-12,16] = [0.51107e+05,0.49234e+05,0.47393e+05,0.45565e+05,0.43775e+05]\n kb[:,34-12,16] = [0.51130e+05,0.49228e+05,0.47350e+05,0.45497e+05,0.43688e+05]\n kb[:,35-12,16] = [0.51256e+05,0.49316e+05,0.47413e+05,0.45540e+05,0.43711e+05]\n kb[:,36-12,16] = [0.51519e+05,0.49555e+05,0.47626e+05,0.45731e+05,0.43885e+05]\n kb[:,37-12,16] = [0.52034e+05,0.50041e+05,0.48090e+05,0.46168e+05,0.44302e+05]\n kb[:,38-12,16] = [0.52529e+05,0.50511e+05,0.48535e+05,0.46595e+05,0.44706e+05]\n kb[:,39-12,16] = [0.52985e+05,0.50952e+05,0.48954e+05,0.46996e+05,0.45085e+05]\n kb[:,40-12,16] = [0.53633e+05,0.51575e+05,0.49556e+05,0.47578e+05,0.45648e+05]\n kb[:,41-12,16] = [0.54289e+05,0.52211e+05,0.50171e+05,0.48171e+05,0.46220e+05]\n kb[:,42-12,16] = [0.54932e+05,0.52836e+05,0.50778e+05,0.48759e+05,0.46785e+05]\n kb[:,43-12,16] = [0.55673e+05,0.53569e+05,0.51488e+05,0.49449e+05,0.47456e+05]\n kb[:,44-12,16] = [0.56461e+05,0.54346e+05,0.52247e+05,0.50190e+05,0.48178e+05]\n kb[:,45-12,16] = [0.57241e+05,0.55121e+05,0.53007e+05,0.50929e+05,0.48897e+05]\n kb[:,46-12,16] = [0.58063e+05,0.55933e+05,0.53806e+05,0.51710e+05,0.49656e+05]\n kb[:,47-12,16] = [0.58978e+05,0.56828e+05,0.54697e+05,0.52582e+05,0.50505e+05]\n kb[:,48-12,16] = [0.59891e+05,0.57720e+05,0.55586e+05,0.53459e+05,0.51367e+05]\n kb[:,49-12,16] = [0.60795e+05,0.58621e+05,0.56472e+05,0.54336e+05,0.52224e+05]\n kb[:,50-12,16] = [0.61639e+05,0.59466e+05,0.57298e+05,0.55162e+05,0.53034e+05]\n kb[:,51-12,16] = [0.62447e+05,0.60284e+05,0.58110e+05,0.55961e+05,0.53824e+05]\n kb[:,52-12,16] = [0.63240e+05,0.61098e+05,0.58916e+05,0.56760e+05,0.54612e+05]\n kb[:,53-12,16] = [0.64030e+05,0.61903e+05,0.59727e+05,0.57558e+05,0.55411e+05]\n kb[:,54-12,16] = [0.64735e+05,0.62637e+05,0.60471e+05,0.58287e+05,0.56138e+05]\n kb[:,55-12,16] = [0.65407e+05,0.63332e+05,0.61181e+05,0.59003e+05,0.56834e+05]\n kb[:,56-12,16] = [0.66069e+05,0.64015e+05,0.61881e+05,0.59702e+05,0.57529e+05]\n kb[:,57-12,16] = [0.66725e+05,0.64683e+05,0.62576e+05,0.60411e+05,0.58225e+05]\n kb[:,58-12,16] = [0.67327e+05,0.65315e+05,0.63232e+05,0.61078e+05,0.58891e+05]\n kb[:,59-12,16] = [0.67577e+05,0.65572e+05,0.63496e+05,0.61349e+05,0.59161e+05]\n\n # -----------------------------------------------------------------\n forref = zeros(4,16)\n forref[:, 1] = [ 0.299818e-05, 0.209282e-05, 0.988353e-04, 0.632178e-03 ]\n forref[:, 2] = [ 0.633648e-05, 0.509214e-04, 0.650535e-03, 0.264019e-02 ]\n forref[:, 3] = [ 0.636782e-04, 0.136577e-03, 0.166500e-02, 0.750821e-02 ]\n forref[:, 4] = [ 0.472314e-03, 0.988296e-03, 0.585751e-02, 0.187352e-01 ]\n forref[:, 5] = [ 0.558635e-02, 0.856489e-02, 0.157438e-01, 0.181471e-01 ]\n forref[:, 6] = [ 0.217395e-01, 0.229156e-01, 0.230125e-01, 0.143821e-01 ]\n forref[:, 7] = [ 0.277222e-01, 0.299252e-01, 0.208929e-01, 0.826748e-02 ]\n forref[:, 8] = [ 0.252119e-01, 0.262911e-01, 0.187663e-01, 0.417110e-02 ]\n forref[:, 9] = [ 0.304941e-01, 0.175545e-01, 0.971224e-02, 0.142023e-02 ]\n forref[:,10] = [ 0.327200e-01, 0.215788e-01, 0.346831e-02, 0.157989e-02 ]\n forref[:,11] = [ 0.324955e-01, 0.228571e-01, 0.171749e-02, 0.226853e-02 ]\n forref[:,12] = [ 0.326588e-01, 0.198544e-01, 0.532339e-06, 0.279086e-02 ]\n forref[:,13] = [ 0.345157e-01, 0.168679e-01, 0.505361e-06, 0.276647e-02 ]\n forref[:,14] = [ 0.448765e-01, 0.123791e-02, 0.488367e-06, 0.122245e-02 ]\n forref[:,15] = [ 0.486925e-01, 0.464371e-06, 0.464241e-06, 0.753846e-06 ]\n forref[:,16] = [ 0.530511e-01, 0.376234e-06, 0.409824e-06, 0.470650e-06 ]\n\n # -----------------------------------------------------------------\n # The array SELFREF contains the coefficient of the water vapor\n # self-continuum (including the energy term). The first index\n # refers to temperature in 7.2 degree increments. For instance,\n # JT = 1 refers to a temperature of 245.6, JT = 2 refers to 252.8,\n # etc. The second index runs over the g-channel (1 to 16).\n selfref = zeros(10,16)\n selfref[:, 1] = [0.118069e+00, 0.713523e-01, 0.431199e-01, 0.260584e-01, 0.157477e-01,0.951675e-02, 0.575121e-02, 0.347560e-02, 0.210039e-02, 0.126932e-02]\n selfref[:, 2] = [0.137081e-01, 0.139046e-01, 0.141040e-01, 0.143061e-01, 0.145112e-01,0.147193e-01, 0.149303e-01, 0.151443e-01, 0.153614e-01, 0.155816e-01]\n selfref[:, 3] = [0.166575e-01, 0.164916e-01, 0.163273e-01, 0.161647e-01, 0.160037e-01,0.158443e-01, 0.156864e-01, 0.155302e-01, 0.153755e-01, 0.152224e-01]\n selfref[:, 4] = [0.597379e-01, 0.509517e-01, 0.434579e-01, 0.370662e-01, 0.316145e-01,0.269647e-01, 0.229988e-01, 0.196162e-01, 0.167311e-01, 0.142703e-01]\n selfref[:, 5] = [0.227517e+00, 0.198401e+00, 0.173011e+00, 0.150870e+00, 0.131563e+00,0.114726e+00, 0.100044e+00, 0.872415e-01, 0.760769e-01, 0.663411e-01]\n selfref[:, 6] = [0.453235e+00, 0.414848e+00, 0.379712e+00, 0.347552e+00, 0.318116e+00,0.291173e+00, 0.266512e+00, 0.243940e+00, 0.223279e+00, 0.204368e+00]\n selfref[:, 7] = [0.569263e+00, 0.516415e+00, 0.468473e+00, 0.424982e+00, 0.385528e+00,0.349737e+00, 0.317269e+00, 0.287815e+00, 0.261095e+00, 0.236856e+00]\n selfref[:, 8] = [0.490314e+00, 0.448042e+00, 0.409413e+00, 0.374116e+00, 0.341861e+00,0.312387e+00, 0.285455e+00, 0.260844e+00, 0.238355e+00, 0.217805e+00]\n selfref[:, 9] = [0.258162e+00, 0.265085e+00, 0.272193e+00, 0.279493e+00, 0.286988e+00,0.294684e+00, 0.302586e+00, 0.310701e+00, 0.319033e+00, 0.327588e+00]\n selfref[:,10] = [0.332019e+00, 0.331902e+00, 0.331784e+00, 0.331666e+00, 0.331549e+00,0.331431e+00, 0.331314e+00, 0.331197e+00, 0.331079e+00, 0.330962e+00]\n selfref[:,11] = [0.357523e+00, 0.353154e+00, 0.348839e+00, 0.344576e+00, 0.340366e+00,0.336207e+00, 0.332099e+00, 0.328041e+00, 0.324032e+00, 0.320073e+00]\n selfref[:,12] = [0.294662e+00, 0.299043e+00, 0.303488e+00, 0.308000e+00, 0.312579e+00,0.317226e+00, 0.321941e+00, 0.326727e+00, 0.331585e+00, 0.336514e+00]\n selfref[:,13] = [0.227445e+00, 0.241545e+00, 0.256519e+00, 0.272422e+00, 0.289311e+00,0.307247e+00, 0.326294e+00, 0.346523e+00, 0.368005e+00, 0.390820e+00]\n selfref[:,14] = [0.616203e-02, 0.113523e-01, 0.209144e-01, 0.385307e-01, 0.709852e-01,0.130776e+00, 0.240929e+00, 0.443865e+00, 0.817733e+00, 0.150651e+01]\n selfref[:,15] = [0.279552e-03, 0.808472e-03, 0.233812e-02, 0.676192e-02, 0.195557e-01,0.565555e-01, 0.163560e+00, 0.473020e+00, 0.136799e+01, 0.395626e+01]\n selfref[:,16] = [0.261006e-03, 0.771043e-03, 0.227776e-02, 0.672879e-02, 0.198777e-01,0.587212e-01, 0.173470e+00, 0.512452e+00, 0.151385e+01, 0.447209e+01]\nend", "meta": {"hexsha": "2da489efd12720de0fe024d71ca5aecb60b263fd", "size": 84463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "srtm_kgbs/srtm_kgb29.jl", "max_stars_repo_name": "jsbj/RRTM.jl", "max_stars_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-05-25T03:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T12:05:50.000Z", "max_issues_repo_path": "srtm_kgbs/srtm_kgb29.jl", "max_issues_repo_name": "jsbj/RRTM.jl", "max_issues_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srtm_kgbs/srtm_kgb29.jl", "max_forks_repo_name": "jsbj/RRTM.jl", "max_forks_repo_head_hexsha": "58dcc7b76d5706dffccec10815144224cd2c94f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.364414843, "max_line_length": 218, "alphanum_fraction": 0.6430152848, "num_tokens": 52651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.22000708951749934, "lm_q1q2_score": 0.16797184071344654}} {"text": "function _extract_reaction_phrase_table(phrase::String)::Dict{String,Float64}\n\n # initialize -\n reaction_phrase_table = Dict{String,Float64}()\n\n # compnents -\n if (occursin(\"+\",phrase) == true)\n\n # ok, so we have some +'s\n component_array = split(phrase,\"+\")\n for component in component_array\n\n # split around the * -\n inner_component_array = split(component,\"*\")\n\n # if len(inner_component_array) == 1, then no *\n # if len(inner_component_array) == 2, then we have a st coeff -\n if (length(inner_component_array) == 1)\n\n # we have a single species -\n key = string(last(inner_component_array))\n value = 1.0\n reaction_phrase_table[key] = value\n\n elseif (length(inner_component_array) == 2)\n\n # we have a species w/a coefficient -\n key = string(last(inner_component_array))\n value = parse(Float64, first(inner_component_array))\n reaction_phrase_table[key] = value\n else\n # error state -\n throw(DimensionMismatch(\"component array larger than 2\"))\n end\n end\n else\n\n # single species, possibly w/*\n # split around the * -\n phrase_component_array = split(phrase,\"*\")\n if (length(phrase_component_array) == 1)\n\n # we have a single species -\n key = string(last(phrase_component_array))\n value = 1.0\n reaction_phrase_table[key] = value\n\n elseif (length(phrase_component_array) == 2)\n\n # we have a species w/a coefficient -\n key = string(last(phrase_component_array))\n value = parse(Float64, first(phrase_component_array))\n reaction_phrase_table[key] = value\n\n else\n # error state -\n throw(DimensionMismatch(\"phrase component array larger than 2\"))\n end\n end\n\n # return -\n return reaction_phrase_table\nend\n\nfunction _extract_stoichiometric_coefficient(phrase::String, speciesSymbol::String)::Float64\n\n # initialize -\n stoichiometric_coefficient = 0.0 # default is 0, species in NOT involved\n\n # get the reaction phrase table -\n reaction_phrase_table = _extract_reaction_phrase_table(phrase)\n\n # ok, look up the species in the phrase table, if its there we have a match - no = 0\n if (haskey(reaction_phrase_table,speciesSymbol) == true)\n return reaction_phrase_table[speciesSymbol]\n end\n\n # return -\n return stoichiometric_coefficient\nend\n\n# == PUBLIC METHODS BELOW HERE ======================================================================================== #\n\n\"\"\"\n generate_stoichiometric_matrix(intermediate_dictionary::Dict{String,Any})::VLResult\n\nGenerate a stoichiometric matrix based on the biochemical model reaction network.\n\nInput arguments:\n`intermediate_dictionary::Dict{String,Any}` - data dictionary containing the master reaction table and molecular species participating in the reactions.\n\nOutput arguments:\n`VLResult::VLResult` - concrete data type holding the generated stoichiometric matrix.\n\n\"\"\"\nfunction generate_stoichiometric_matrix(intermediate_dictionary::Dict{String,Any})::VLResult\n\n # initialize -\n\n\n try\n\n # check: do we have the ir_master_reaction_table_key?\n if (haskey(intermediate_dictionary, ir_master_reaction_table_key) == false)\n throw(ArgumentError(\"intermediate_dictionary is missing the ir_master_reaction_table_key\"))\n end\n\n # check: do we have the ir_list_of_molecular_species_key?\n if (haskey(intermediate_dictionary, ir_list_of_molecular_species_key) == false)\n throw(ArgumentError(\"intermediate_dictionary is missing the ir_list_of_molecular_species_key\"))\n end\n\n # get reaction data frame, and species list -\n reaction_data_frame = intermediate_dictionary[ir_master_reaction_table_key]\n list_of_species = intermediate_dictionary[ir_list_of_molecular_species_key]\n\n # ok, so we need to initialize some space for the stm -\n number_of_species = length(list_of_species)\n number_of_reactions = size(reaction_data_frame,1)\n stoichiometric_matrix = Array{Float64,2}(undef, number_of_species, number_of_reactions)\n\n # process each species -\n for (species_index,species_symbol) in enumerate(list_of_species)\n\n # process each reaction -\n for reaction_index = 1:number_of_reactions\n\n # get the left and right phrases -\n left_phrase = reaction_data_frame[reaction_index,:left_phrase]\n right_phrase = reaction_data_frame[reaction_index,:right_phrase]\n\n # check: is this species symbol in the left or right phrase?\n left_st_coeff = _extract_stoichiometric_coefficient(left_phrase, species_symbol)\n right_st_coeff = _extract_stoichiometric_coefficient(right_phrase, species_symbol)\n\n # overall coeff -\n overall_st_coeff = right_st_coeff - left_st_coeff\n\n # grab -\n stoichiometric_matrix[species_index,reaction_index] = overall_st_coeff\n end\n end\n\n # return -\n return VLResult(stoichiometric_matrix)\n catch error\n return VLResult(error)\n end\nend\n\n# == PUBLIC METHODS ABOVE HERE ======================================================================================== #\n", "meta": {"hexsha": "fcfac8192796ba6d89a70f1bfd2955c7542b57ad", "size": 5525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/strategy/General.jl", "max_stars_repo_name": "varnerlab/CellFreeModelGenerationKit", "max_stars_repo_head_hexsha": "7106243229a4df170887202d695fe3db87bc9aa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/strategy/General.jl", "max_issues_repo_name": "varnerlab/CellFreeModelGenerationKit", "max_issues_repo_head_hexsha": "7106243229a4df170887202d695fe3db87bc9aa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-05T23:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-19T22:29:46.000Z", "max_forks_repo_path": "src/strategy/General.jl", "max_forks_repo_name": "varnerlab/CellFreeModelGenerationKit", "max_forks_repo_head_hexsha": "7106243229a4df170887202d695fe3db87bc9aa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-21T01:15:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T01:15:13.000Z", "avg_line_length": 36.3486842105, "max_line_length": 152, "alphanum_fraction": 0.6392760181, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.16685327665694719}} {"text": "module SurfaceReactions\nusing LightXML\nusing DifferentialEquations\ninclude(\"Constants.jl\")\ninclude(\"Reactions.jl\")\ninclude(\"Utils.jl\")\ninclude(\"IdealGas.jl\")\n\n\"\"\"\nFunction to create composite type of SurfaceMechanism and\nSpeciesRxnMap. In general the application programs shall only\ncall the compile_mech function and not directly the create_mech\nand species_rxn_map function\n# Usage\n compile_mech(file_path,gas_species)\n- file_path::String : path to the mechanism xml file\n- gas_species::Array{String,1} : list of gasphase species\n\"\"\"\nfunction compile_mech(file_path::T, thermo_obj::IdealGas.SpeciesThermoObj, gas_species::Array{T,1}) where T <: AbstractString\n sm = create_mech(file_path,gas_species,thermo_obj.molwt)\n rxn_map = species_rxn_map(gas_species,sm)\n return MechanismDefinition(sm,rxn_map)\nend\n\n\"\"\"\nFunction to read a surface reaction mechanism file\n# Usage:\n create_mech(file_path,gas_species)\n- file_path::String : file name including the relative path \n- gas_species::Array{String,1} : gasphase species list \n\"\"\"\nfunction create_mech(file_path::String, gas_species::Array{String,1},molwt::Array{Float64,1})\n xmldoc = parse_file(file_path)\n mech_root = root(xmldoc) \n mech_unit = attribute(mech_root,\"unit\") \n energy_factor = convert2si(mech_unit)\n\n #get the surface species\n surface_species = map(x->uppercase(x) ,split(content(get_elements_by_tagname(mech_root,\"species\")[1])))\n\n #default initial values\n site_coordination_vector = ones(length(surface_species))\n covg_vec = zeros(length(surface_species))\n site_density = 1.0\n site_name = \"\"\n #read the site node\n site_node = get_elements_by_tagname(mech_root,\"site\")\n for elements in site_node\n site_name = attribute(elements,\"name\")\n #get the site coordination\n coordination = get_elements_by_tagname(elements,\"coordination\")[1]\n if is_elementnode(coordination)\n site_coord_species = split(content(coordination),\",\")\n for items in site_coord_species\n sp,val = split(items,\"=\")\n sp_id = get_index(String(sp),surface_species)\n site_coordination_vector[sp_id] = parse(Float64,String(val))\n end\n end \n #get the site density\n density = get_elements_by_tagname(elements,\"density\")[1]\n if is_elementnode(density)\n unit = strip(attribute(density,\"unit\"))\n site_density = parse(Float64, content(density))\n if uppercase(unit) == \"MOL/M2\"\n site_density *= 1e4\n end\n else\n throw(error(\"Surface site density not specified\\n\"))\n end\n \n #get the intitial coverages\n covg_node = get_elements_by_tagname(elements,\"initial\")[1]\n if is_elementnode(covg_node)\n ini_covg = split(content(covg_node),\",\")\n for items in ini_covg\n sp,val = split(items,\"=\")\n sp_id = get_index(String(sp),surface_species)\n covg_vec[sp_id] = parse(Float64,String(val))\n end\n else\n throw(error(\"Initial coverage not specified\\n\"))\n end\n \n end\n\n site_info = SiteInfo(site_name,site_density,site_coordination_vector,covg_vec)\n\n #Read the coverage dependencies if any. This must be read before reading the reactions\n covg_nodes = get_elements_by_tagname(mech_root,\"coverage\")\n cov_dep_rxns = Dict{Int64,Dict{Int,Float64}}() #rxn_id=>{species_id=>cov_act_energy}\n for covg in covg_nodes\n rxn_ids = split(attribute(covg,\"id\"))\n sp,val = split(content(covg),\"=\")\n sp_id = get_index(String(sp),surface_species)\n cov_dict = Dict(sp_id=>parse(Float64,val))\n\n for rxn in rxn_ids\n cov_dep_rxns[parse(Int64,rxn)] = cov_dict\n end \n end\n #Read the order dependencies if any. This must be read before reading the reactions\n order_nodes = get_elements_by_tagname(mech_root,\"order\")\n order_dep_rxns = Dict{Int64,Dict{Int,Float64}}() #rxn_id=>{species_id=>order}\n for order in order_nodes\n rxn_ids = split(attribute(order,\"id\"))\n sp,val = split(content(order),\"=\")\n sp_id = get_index(String(sp),surface_species)\n order_dict = Dict(sp_id=>parse(Float64,val))\n for rxn in rxn_ids\n order_dep_rxns[parse(Int64,rxn)] = order_dict\n end\n end\n \n\n #Read Motz-Wise Correction\n mwc_node = get_elements_by_tagname(mech_root,\"mwc\")\n mwc_rxns = Array{Int64,1}()\n if length(mwc_node) > 0\n if is_elementnode(mwc_node[1])\n mwc_rxns = [ parse(Int64,rxn) for rxn in split(content(mwc_node[1]))]\n end \n end\n \n #Define the reaction array to be returned\n rxn_array= Array{ElementaryReactions,1}()\n\n rct_ids = Array{Int64,1}()\n prdt_ids = Array{Int64,1}()\n all_species = Array{String,1}()\n all_species = copy(gas_species)\n append!(all_species,surface_species)\n \n #Read sticking reactions\n site_index = get_index(site_name,all_species)\n\n stick_node = get_elements_by_tagname(mech_root,\"stick\")[1]\n if is_elementnode(stick_node)\n stick_rxns = get_elements_by_tagname(stick_node,\"rxn\")\n for rxn in stick_rxns\n rxn_id = parse(Int64,strip(attribute(rxn,\"id\")))\n stoic, params = split(content(rxn),\"@\")\n reversible, r_species, p_species = parase_rxn_string(String(stoic)) \n rct_ids = [get_index(sp,all_species) for sp in r_species] \n prdt_ids = [get_index(sp,all_species) for sp in p_species]\n s,β,E = parse_rxn_params(String(params)) \n #Check for coverage, order and mwc dependency\n cov,ord,mwc = get_dependencies(cov_dep_rxns,order_dep_rxns,mwc_rxns,rxn_id)\n #convert sticking coefficient to rate constant\n n_site = count(x->x==site_index, rct_ids)\n gas_species_id = filter(x->x != site_index, rct_ids)[1]\n sqrt_term = 100*sqrt(R/(2*π*molwt[gas_species_id]))\n s_by_gamma = s/site_density^n_site \n k = sqrt_term*s_by_gamma #rate constant\n #Apply the MWC\n if mwc\n k /= (1-0.5*s)\n end\n p = Parameters(s,k,β,E)\n\n stoic = Stoichiometry(reversible,rct_ids,prdt_ids,cov,ord)\n elm_rxn = ElementaryReactions(rxn_id,stick,p,mwc,stoic)\n push!(rxn_array,elm_rxn)\n \n end\n end\n \n #Read Arrhenius reactions\n arrhenius_node = get_elements_by_tagname(mech_root,\"arrhenius\")[1]\n if is_elementnode(arrhenius_node)\n arrhenius_rxns = get_elements_by_tagname(arrhenius_node,\"rxn\")\n for rxn in arrhenius_rxns\n rxn_id = parse(Int64,strip(attribute(rxn,\"id\")))\n stoic,params = split(content(rxn),\"@\")\n reversible, r_species, p_species = parase_rxn_string(String(stoic))\n rct_ids = [get_index(sp,all_species) for sp in r_species]\n prdt_ids = [get_index(sp,all_species) for sp in p_species]\n k,β,E = parse_rxn_params(String(params))\n p = Parameters(0.0,k,β,E)\n #Check for coverage, order and mwc dependency. MWC not applicable to Arrhenius type\n cov,ord,mwc = get_dependencies(cov_dep_rxns,order_dep_rxns,mwc_rxns,rxn_id) \n stoic = Stoichiometry(reversible,rct_ids,prdt_ids,cov,ord)\n elm_rxn = ElementaryReactions(rxn_id,arrhenius,p,mwc,stoic) \n push!(rxn_array,elm_rxn) \n end\n end\n \n return SurfaceMechanism(energy_factor,site_info,surface_species,rxn_array)\nend\n\n\n\"\"\"\nCreate array of structures of SpeciesRxnMap. The SpeciesRxnMap is a \ncomposit structure of species_id in participating reactions and the\nstoichiometric coefficients\n# Usage\n species_rxn_map(gas_species,sm)\n- gas_species::Array{String,1} : list of gas phase species\n- sm::SurfaceMechanism : SurfaceMechanism composite type\n\"\"\"\nfunction species_rxn_map(gas_species::Array{String,1},sm::SurfaceMechanism)\n #Array of SpeciesRxnMap\n srm_array = Array{SpeciesRxnMap,1}()\n #create list of all species\n all_species = Array{String,1}()\n all_species = copy(gas_species)\n append!(all_species,sm.species)\n #loop over all species\n for sp in all_species\n sp_id = get_index(sp,all_species)\n #check if the species is present in the reactant_ids of a reaction\n rxns = Array{Int64,1}()\n stc = Array{Int64,1}()\n for rxn in sm.reactions\n #count the number of occurances of species in reactants list (using ids)\n n = count(x->x==sp_id,rxn.rxn_stoic.reactant_ids)\n if n > 0\n push!(rxns,rxn.id)\n push!(stc,-n)\n end \n #count the number of occurances of species in the products list (using ids)\n n = count(x->x==sp_id,rxn.rxn_stoic.product_ids)\n if n > 0\n push!(rxns,rxn.id)\n push!(stc,n)\n end\n end\n push!(srm_array,SpeciesRxnMap(sp_id,rxns,stc))\n end\n return srm_array\nend\n\n\n\n\"\"\"\nFunction to calculate the molar production rate of gas-phase and \nsurface species based on the surface reaction mechanism. The function\nwill alter the field s_rate after the calculation.\n# Usage:\n calculate_molar_production_rate!(state,md)\n- state::State : state of the reaction, which is of the composite type State\n- thermo_obj::SpeciesThermoObj : Composite type SpeciesThermoObj. Required in case of reversible reactions\n- md::MechanismDefinition : the mechanism, which is of the composite type MechanismDefinition\n\"\"\"\nfunction calculate_molar_production_rates!(state::ReactionState, thermo_obj::IdealGas.SpeciesThermoObj,md::SurfaceMechDefinition)\n #get the mole fractions from state\n mf = state.mole_frac\n #convert mole fractions to concentrations\n all_conc = (state.p/R/state.T) .* mf \n all_conc *= 1e-6 # convert to mol/cm3\n #get the surface coverages from state\n coverage = state.covg\n #convert coverages to surface concentrations mol/cm2 \n surf_conc = (md.sm.si.density .* coverage) ./ md.sm.si.site_coordination\n #merge the concentrations\n append!(all_conc,surf_conc) \n rxn_rate = Array{Float64,1}()\n \n #calcuate the rate of individual reactions\n for rxn in md.sm.reactions \n local prdt_conc = prod(all_conc[rxn.rxn_stoic.reactant_ids]) \n #check for coverage dependency of the reaction\n local cov_act_E = 0\n #cov_act_E = sum(coverage[collect(keys(rxn.rxn_stoic.cov_dep))] .* collect(values(rxn.rxn_stoic.cov_dep)))\n if !isempty(rxn.rxn_stoic.cov_dep)\n #calculate coverage dependent activation energy\n for (sp_id,cov_e) in rxn.rxn_stoic.cov_dep\n cov_act_E += coverage[sp_id]*cov_e\n end \n end\n #check for order dependency\n local m_order = 1.0\n if !isempty(rxn.rxn_stoic.order_dep)\n #calculate order change\n for (sp_id,order) in rxn.rxn_stoic.order_dep\n m_order *= coverage[sp_id]^order\n end\n end\n #calculate the forward reaction rate \n E = (rxn.params.E + cov_act_E)*md.sm.energy_factor \n k = rxn.params.k0 * state.T^rxn.params.β * exp(-E/R/state.T)\n if rxn.type == stick\n k *= sqrt(state.T)\n end \n push!(rxn_rate,k*prdt_conc*m_order*1e4)#e4 is to convert the units to mol/m2\n\n if rxn.rxn_stoic.reversible\n throw(error(\"Reverse reaction not implemented\\n\"))\n end\n \n end\n #calculate the species molar production rates\n for srm in md.srm_array \n state.s_rate[srm.species_id] = sum(rxn_rate[srm.rxns] .* srm.stoic_coeff)\n end\nend\n\n\"\"\"\nFunction to calculate the molar production rate of gas-phase species.\nThis function integrates the rate equations so that \\frac{d\\theta}{dt}=0\n# Usage:\n calculate_molar_production_rate!(state,md)\n- state::State : state of the reaction, which is of the composite type State\n- thermo_obj::SpeciesThermoObj : Composite type SpeciesThermoObj. Required in case of reversible reactions\n- md::MechanismDefinition : the mechanism, which is of the composite type MechanismDefinition\n\"\"\"\nfunction calculate_ss_molar_production_rates!(state::ReactionState, thermo_obj::IdealGas.SpeciesThermoObj,md::SurfaceMechDefinition, time =1.0)\n t_span = (0,time) \n coverage = state.covg\n p = (state,thermo_obj,md)\n prob = ODEProblem(covg_integration!,coverage,t_span,p)\n sol = solve(prob, alg_hints=[:stiff] , reltol=1e-6, abstol=1e-10, save_everystep=false,save_start=false) \n state.covg = sol.u[lastindex(sol.u)]\n return sol.t, state\nend\n\n\nfunction covg_integration!(du, u, p, t)\n state, thermo_obj,md = p\n state.covg = u \n ng = length(state.mole_frac)\n calculate_molar_production_rates!(state,thermo_obj,md) \n @inbounds for i in eachindex(u)\n du[i] = (md.sm.si.site_coordination[i]*state.s_rate[ng+i])/(md.sm.si.density*1e4)\n end\nend\n\n\n\"\"\"\nFunction to update the rate parameters. This function is only used for\nsensitivity analysis\n# Usage\n update_params(rate_params,md)\n- rate_params::Array : One dimentional array of floating point variables\n- md:SurfaceMechDefinition : SurfaceMechDefinition struct\n\"\"\"\nfunction update_params(rate_params::Array{Float64,1},md::SurfaceMechDefinition)\n #assign the new parameters to SurfaceMechDefinition object \n for i in eachindex(rate_params)\n if Int(md.sm.reactions[i].type) == Int(stick)\n k = md.sm.reactions[i].params.k0 #This is the current value of converted rate constant including MWC\n if md.sm.reactions[i].mwc == true\n #take out the MWC factor\n k *= (1-0.5*md.sm.reactions[i].s)\n end\n #new k value for the purturbed sticking coefficient\n k = (k/md.sm.reactions[i].params.s)*rate_params[i]\n md.sm.reactions[i].params.s = rate_params[i]\n if md.sm.reactions[i].mwc == true\n #Apply the MWC back\n k /= (1-0.5*rate_params[i])\n end\n md.sm.reactions[i].params.k0 = k\n else\n md.sm.reactions[i].params.k0 = rate_params[i]\n end \n end\n\nend\n\n\"\"\"\nA function for use in global sensitivity analysis. The function updates the parameters with the \n supplied rate_params \n# Usage\n update_params!(md, rate_params,rxn_ids, constraint_ids)\n- md : SurfaceMechDefinition structure\n- rate_params : parameters to that needs to be set to the mechanism object \n- rxn_ids : id of the reactions considered in the sensitivity analysis \n- constraint_ids : id of the reverse reaction ids considered\n\"\"\"\nfunction update_params!(md, rate_params::Array{Float64,1},rxn_ids::Array{Int64,1}, constraint_ids::Array{Int64,1}, pratio::Array{Float64,1})\n for id in eachindex(rxn_ids)\n if Int(md.sm.reactions[rxn_ids[id]].type) == Int(stick)\n # The current value of sticking coefficient converted to rate constant including MWC\n k = md.sm.reactions[rxn_ids[id]].params.k0 \n if md.sm.reactions[rxn_ids[id]].mwc == true\n #take out the MWC factor\n k *= (1-0.5*md.sm.reactions[rxn_ids[id]].params.s)\n end\n # multiplication factor used to convert sticking coefficient to rate constant \n m_factor = k/md.sm.reactions[rxn_ids[id]].params.s\n # new sticking coefficient \n md.sm.reactions[rxn_ids[id]].params.s = rate_params[id]\n #new k value for the purturbed sticking coefficient\n k = md.sm.reactions[rxn_ids[id]].params.s * m_factor\n #Apply the MWC back\n if md.sm.reactions[id].mwc == true \n k /= (1-0.5*rate_params[id])\n end\n md.sm.reactions[rxn_ids[id]].params.k0 = k \n \n # Now if there is a constraint, i.e. if a reverse reaction present, then the \n # parameter for that reaction needs to be changed accordingly. \n if constraint_ids[id] != 0 \n md.sm.reactions[constraint_ids[id]].params.k0 = k/pratio[id] \n end\n else \n md.sm.reactions[rxn_ids[id]].params.k0 = rate_params[id] \n if constraint_ids[id] != 0 \n md.sm.reactions[constraint_ids[id]].params.k0 = rate_params[id]/pratio[id] \n end\n end\n end \nend\n\n\n\n#end of module\nend", "meta": {"hexsha": "1e719d8cb0a0d67be18046ff7be7e0d6b7d4f4a4", "size": 16852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SurfaceReactions.jl", "max_stars_repo_name": "vinodjanardhanan/ReactionEngine.jl", "max_stars_repo_head_hexsha": "4526a68c550abdfd4f2546f358ab171d4c7c54ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SurfaceReactions.jl", "max_issues_repo_name": "vinodjanardhanan/ReactionEngine.jl", "max_issues_repo_head_hexsha": "4526a68c550abdfd4f2546f358ab171d4c7c54ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SurfaceReactions.jl", "max_forks_repo_name": "vinodjanardhanan/ReactionEngine.jl", "max_forks_repo_head_hexsha": "4526a68c550abdfd4f2546f358ab171d4c7c54ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2029339853, "max_line_length": 143, "alphanum_fraction": 0.6432470923, "num_tokens": 4286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.1666734995674789}} {"text": "using Pkg;Pkg.activate(@__DIR__)\nusing Comrade\nusing PyCall\nusing Plots\n\nusing ComradeAHMC\n\nload_ehtim()\n@pyimport eht_dmc as ed\n\n# To download the data visit https://doi.org/10.25739/g85n-f134\nobs = ehtim.obsdata.load_uvfits(joinpath(@__DIR__, \"SR1_M87_2017_096_hi_hops_netcal_StokesI.uvfits\"))\nobs.add_scans()\n\nobsavg = obs.avg_coherent(0.0, scan_avg=true)\n\nimg = ehtim.image.make_empty(512, μas2rad(250.0), obs.ra, obs.dec, obs.rf, obs.source)\nimg = img.add_gauss(1.0, [μas2rad(40.0), μas2rad(30.0), π/3, 0.0, 0.0])\n\nobslist = obsavg.split_obs()\n\ngainoff = 0.0\ngainp = Dict(\"AA\"=> 0.01,\n \"AP\" => 0.1,\n \"AZ\" => 0.1,\n \"JC\" => 0.1,\n \"LM\" => 0.2,\n \"PV\" => 0.1,\n \"SM\" => 0.1,\n \"SR\" => 0.1)\nobsim = img.observe_same(ehtim.obsdata.merge_obs(obslist), ttype=\"fast\", gainp=gainp, gain_offset=gainoff, ampcal=false, phasecal=false, stabilize_scan_phase=true, stabilize_scan_amp=true)\n# now get cal table\nctable = ehtim.calibrating.self_cal.self_cal(obsim, img, caltable=true)\nehtim.caltable.save_caltable(ctable, obsim, datadir=joinpath(@__DIR__ ,\"CaltableTest\"))\n\n\ndvis = extract_vis(obsim)\ndlcamp = extract_lcamp(obsim)\ndcphase = extract_cphase(obsim)\ndamp = extract_amp(obsim)\nst = scantable(dvis)\n\ngcache = Comrade.GainCache(st)\n\nstruct Test{G}\n gcache::G\nend\n\nfunction Test(st::Comrade.ScanTable)\n gcache = Comrade.GainCache(st)\n return Test{typeof(gcache)}(gcache)\nend\n\nfunction (mod::Test)(θ)\n (;f, σ, τ, ξ, gamp, gphase) = θ\n g = exp.(gamp).*cis.(gphase)\n m = f*rotated(stretched(Gaussian(), σ*τ, σ), ξ)\n return GainModel(mod.gcache, g, m)\nend\n\n# define the priors\ndistamp = (AA = Normal(0.0, 0.1),\n AP = Normal(0.0, 0.1),\n LM = Normal(0.0, 0.2),\n AZ = Normal(0.0, 0.1),\n JC = Normal(0.0, 0.1),\n PV = Normal(0.0, 0.1),\n #SM = LogNormal(0.0, 0.1)\n )\ndistphase = (AA = Normal(0.0, 1e-4),\n AP = Normal(0.0, π),\n LM = Normal(0.0, π),\n AZ = Normal(0.0, 1.0*π),\n JC = Normal(0.0, 1.0*π),\n PV = Normal(0.0, π),\n #SM = Normal(0.0, 1.0*π),\n )\nprior = (\n f = Uniform(0.9, 1.1),\n σ = Uniform(μas2rad(10.0), μas2rad(30.0)),\n τ = Uniform(0.1, 1.0),\n ξ = Uniform(-π/2, π/2),\n gamp = Comrade.GainPrior(distamp, st),\n gphase = Comrade.GainPrior(distphase, st)\n )\n# Now form the posterior\n\nmms = Test(st)\n\ncllklhd = RadioLikelihood(dlcamp, dcphase)\nclpost = Posterior(cllklhd, prior, mms)\n\nlklhd = RadioLikelihood(dvis)#damp, dcphase)\npost = Posterior(lklhd, prior, mms)\ntpost = asflat(post)\n# We will use HMC to sample the posterior.\n# First to reduce burn in we use pathfinder\n\nndim = dimension(tpost)\nf = OptimizationFunction(tpost, GalacticOptim.AutoForwardDiff())\nx0 = Comrade.HypercubeTransform.inverse(tpost, rand(post.prior))\n\nprob = OptimizationProblem(f, x0, nothing, lb=fill(-5.0, ndim), ub=fill(5.0, ndim))\nsol = solve(prob, BBO_adaptive_de_rand_1_bin_radiuslimited(); maxiters=1_000_000)\n\nprob = GalacticOptim.OptimizationProblem(f, 0.1*randn(ndim), nothing)\nsol = solve(prob, LBFGS(); g_tol=1e-2, maxiters=2_000)\n\n@info sol.minimum\n\nxopt = transform(tpost, sol)\n\nresidual(mms(xopt), dvis)\n\n\nmetric = DenseEuclideanMetric(ndim)\nchain, stats = sample(post, AHMC(;metric), 7_000; nadapts=5_000, init_params=xopt)\n", "meta": {"hexsha": "e5d0ba410684b4575a270cc509cd1313147feaf1", "size": 3429, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gaintest.jl", "max_stars_repo_name": "ptiede/ROSEx.jl", "max_stars_repo_head_hexsha": "505da52dc047057673ed8cf9fe35b2ef2db3ede3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-08T18:38:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:38:39.000Z", "max_issues_repo_path": "examples/gaintest.jl", "max_issues_repo_name": "ptiede/ROSEx.jl", "max_issues_repo_head_hexsha": "505da52dc047057673ed8cf9fe35b2ef2db3ede3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/gaintest.jl", "max_forks_repo_name": "ptiede/ROSEx.jl", "max_forks_repo_head_hexsha": "505da52dc047057673ed8cf9fe35b2ef2db3ede3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0593220339, "max_line_length": 189, "alphanum_fraction": 0.6302128901, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.16566081383421943}} {"text": "# November, 2020\n# Kevin Dorma\n# module for common hydraulic calculations\n# rev 0\n\n# I need to make some decisions about how to interace with these functions\n# I assume that I use dataframes to store information about sizing lines and general hydraulics\n# then I will execute a function and it will return a result, but not change the raw information\n# size lines\n # Input dataframe for describing the lines\n # Output line descriptor, pipe schedule, size criteria DP/100 and C, IDmm for each criteria and the chosen IDmm\n# pick NPS will return the next size larger for NPS.This will be the chosen size.\n# we will have utility functions for increasing or decreasing the NPS by 1. \n\n\nmodule Hydraulics\n\nusing DataFrames\nusing CSV\n#using ExcelFiles\n\nexport calcMoodyF\nexport addPipeProperties, addFluidProperties, getReynolds, getSegmentDP\nexport getLineSize, getListLargerNPS, getLargerNPS\n\n\n\n# these are the reference data.\n# and this needs to be loaded correctly when we use the code in a module\ninclude(\"npsList.jl\")\ninclude(\"schedList.jl\")\ninclude(\"pipeRoughnessList.jl\")\ninclude(\"fitting3K.jl\")\ninclude(\"pipeIDlist.jl\")\n\n#schedList = CSV.File(\"schedList.csv\") |> DataFrame\n#pipeRoughness = CSV.File(\"pipeRoughness.csv\") |> DataFrame\n#fitting3K = CSV.File(\"fitting3K.csv\") |> DataFrame\n#IDmm = CSV.File(\"pipeIDlist.csv\") |> DataFrame\n## not used\n#pipeTable = CSV.read(\"pipeIDtable.csv\");\n\n\nfunction packageInfo()\n # return information about the package as a string\n return(\"Hydraulics package, Kevin Dorma. Written in Julia, December 2020.\")\nend\n\n# need function to append piping data\n# later\n\n\nfunction calcMoodyF(Reynolds,eD)\n # Moody friction factor, this is Halaand\n # eD is e/D relative roughness\n # Reynolds is Reynolds number\n invSqrtF = -1.8 .* log10.((eD ./ 3.70) .^ 1.11 + 6.9 ./ Reynolds)\n moodyF = (1 ./ (invSqrtF .^2) )\n return (moodyF)\nend\n\nfunction checkFittingList(fittingList)\n # fittingList is our list of fittings, fittingReference is the generic data\n # go through the list of fittings (fittingList) and compare with the reference list (possibly our fitting3K global list)\n # return items that are not found\n errorList = DataFrame(message = String[], entry=Int64[], Segment=String[], fittingType=String[])\n for i = 1:(size(fittingList)[1])\n thisFitting = fittingList[i,:fittingType]\n match = fitting3K[fitting3K.fittingType .== thisFitting,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"Fitting not found in row\", i, fittingList[i,:Segment], fittingList[i,:fittingType] ))\n end\n end\n return (errorList)\nend\n\n\n\nfunction checkLineList(lines,fluidList)\n # go through our list of lines and compare with our reference lists\n # return the line items that are not found\n errorList = DataFrame(message = String[], entry=Int64[], Segment=String[], NPS=Float64[], Schedule=String[], material=String[], fluidName=String[])\n for i = 1:(size(lines)[1])\n # NPS\n thisItem = lines[i,:NPS]\n match = npsList[npsList.NPS .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"NPS not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ))\n end\n # schedule\n thisItem = lines[i,:Schedule]\n match = schedList[schedList.Schedule .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"Schedule not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ))\n end\n # roughness material\n thisItem = lines[i,:Material]\n match = pipeRoughness[pipeRoughness.Material .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"Material not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ))\n end\n # fluid\n thisItem = lines[i,:fluidName]\n match = fluidList[fluidList.fluidName .== thisItem,:]\n if ((size(match)[1]) == 0)\n push!(errorList, (\"FluidName not found in row\", i, lines[i,:Segment], lines[i,:NPS], lines[i,:Schedule], lines[i,:Material], lines[i,:fluidName] ))\n end\n end\n return (errorList)\nend\n\n\nfunction addPipeProperties(df)\n # roughness, IDmm, eD ratio\n # this appends columns to df\n # used either line sizing or hydraulic calculations\n\n df[:,:roughnessMM] .= 0.0\n df[:,:IDmm] .= 0.0\n\n for i = 1:(size(df)[1])\n df[i,:roughnessMM]=pipeRoughness[df[i,:Material] .== pipeRoughness[:,:Material],:roughnessMM][1]\n df[i,:IDmm]= IDmm[(df[i,:NPS] .== IDmm[:,:NPS]) .& (df[i,:Schedule] .== IDmm[:,:Schedule]),:Idmm][1]\n end\n\n return (0.0)\nend\n\nfunction addFluidProperties(df,fluidList)\n # extract the density, viscosity and whatever else is needed from the fluidList\n # Add this to the df\n # used either line sizing or hydraulic calculations\n\n \n\n df[:,:rho_kgm3] .= 0.0\n df[:,:mu_mPas] .= 0.0\n df[:,:roughnessMM] .= 0.0\n\n\n for i = 1:(size(df)[1])\n df[i,:rho_kgm3] = fluidList[df[i,:fluidName] .== fluidList[:,:fluidName], :rho_kgm3][1]\n df[i,:mu_mPas] = fluidList[df[i,:fluidName] .== fluidList[:,:fluidName], :mu_mPas][1]\n df[i,:roughnessMM] = pipeRoughness[df[i,:Material] .== pipeRoughness[:,:Material], :roughnessMM][1]\n end\n\n return (0.0)\nend\n\n\n\nfunction lineSizeDP(df)\n # this is for sizing lines based on pressure drop kPa per 100 m, return the ID in mm\n # very convenient form straight out of Perrys handbook\n # uses friction factor correlation from Chen\n # Do not modify the original data in df\n\n g = 9.80665\n Sf = df.kPaPer100m*1000 ./ (df.rho_kgm3*g*100)\n q = df.massFlow .* df.margin ./(df.rho_kgm3*3600)\n eps = (df.roughnessMM/1000)\n kinVisc = (df.mu_mPas/1000) ./ df.rho_kgm3\n termA = ((eps.^5)*g .* Sf ./ (q.^2)).^0.25\n termB = ((kinVisc .^ 5)./((q.^3) .* Sf * g )).^0.2\n termC = 0.125*(termA .+ termB).^0.2\n returnValue = (1000*(termC .* (q.^2) ./ (g*Sf)).^0.2)\n return (returnValue)\nend\n\nfunction lineSizeErosion(df)\n # df is the dataframe with hydraulic information\n # this is the erosion C factor method\n # C = v/sqrt(rho), with v in m/s and rho in kg/m3\n # for most service, C = 120, this is similar to C = 100 for imperial units\n # return the ID in mm\n\n g = 9.80665\n maxVeloc = df.frictionCsi ./ sqrt.(df.rho_kgm3)\n q = df.massFlow .* df.margin ./(df.rho_kgm3*3600)\n area = q ./ maxVeloc\n returnValue = (sqrt.(4*area ./ pi )*1000.0)\n return (returnValue)\nend\n\nfunction getLineSize(df,fluidList)\n # from the calculated line size for the two different methods, determine the required line size\n \n addFluidProperties(df,fluidList)\n \n theSchedule = df[:,:Schedule]\n\n theSegment = df[:,:Segment]\n\n tempDP100 = lineSizeDP(df)\n tempErosion = lineSizeErosion(df)\n tempNeeded = tempErosion[:] + tempDP100[:]\n for j in 1:size(tempDP100)[1]\n tempNeeded[j] =max(tempDP100[j], tempErosion[j])\n end\n returnValue = DataFrame(Segment = theSegment, mmDP100 = tempDP100, mmErosion = tempErosion, mmNeeded = tempNeeded, Schedule = theSchedule)\n return (returnValue)\nend\n\n# I need a function to pick the next larger line size given the pipe schedule\n\n\nfunction getLargerNPS(ourIDmm, ourSchedule)\n # from the common list of line sizes, pick the pipe size that matches the required schedule\n # and is the next larger that the required ID\n # this works for a single line size\n ourScheduleList = IDmm[IDmm[:,:Schedule] .== ourSchedule, :];\n refinedList = ourScheduleList[(ourScheduleList[:,:Idmm] .- ourIDmm) .> 0.0,:];\n theMinID = minimum(refinedList[:,:Idmm])\n ourNPS = refinedList[(refinedList[:,:Idmm] .== theMinID), :NPS]\n\n return (ourNPS)\nend\n\n\nfunction getListLargerNPS(lineSizeDF)\n # we will use the required line size and schedule and return the NPS and actual ID\n diamList = DataFrame(Segment=String[], NPS=Float64[], Schedule=String[], IDmm=Float64[])\n for i = 1:(size(lineSizeDF)[1])\n ourSchedule = lineSizeDF[i,:Schedule];\n ourIDmm = lineSizeDF[i,:mmNeeded]\n ourScheduleList = IDmm[IDmm[:,:Schedule] .== ourSchedule, :];\n refinedList = ourScheduleList[(ourScheduleList[:,:Idmm] .- ourIDmm) .> 0.0,:];\n theMinID = minimum(refinedList[:,:Idmm])\n ourNPS = refinedList[(refinedList[:,:Idmm] .== theMinID), :NPS][1]\n\n push!(diamList, (lineSizeDF[i,:Segment], ourNPS, ourSchedule, theMinID))\n end\n return (diamList)\nend\n\nfunction sizing2hydraulics(sizingDF, chosenLineSizeDF)\n # given the line sizing DF, copy the info into hydraulics dataframe\n # chosenSizeDF contains the NPS and Schedule\n # return the hydraulics DF\n # we also need a simple fittingDF, but this is done with a separate function\n hydraulicsDF = DataFrame(Segment=String[], Description=String[], LineTag=String[], PnID=String[], NPS=Float64[], Schedule=String[],\n\t\tMaterial=String[],\tfluidName=[],\tinletP_kPaa=[],\tmassFlow=Float64[],\tmargin=Float64[])\n for i = 1:(size(sizingDF)[1])\n push!(hydraulicsDF, (sizingDF[i,:Segment], sizingDF[i,:Description],\n sizingDF[i,:LineTag], sizingDF[i,:PnID], chosenLineSizeDF[i,:NPS],\n chosenLineSizeDF[i,:Schedule], sizingDF[i,:Material], sizingDF[i,:fluidName],\n 100.0, sizingDF[i,:massFlow], sizingDF[i,:margin]))\n end\n return(hydraulicsDF)\nend\n\nfunction sizing2fittingList(sizingDF, chosenLineSizeDF)\n # given the line sizing DF, copy the info into the fitting list\n # chosenSizeDF contains the NPS and Schedule\n # return the pre-populsted fittign list DF\n fittingListDF = DataFrame(Segment=String[], fittingType=String[], num_length_m=Float64[], comment=String[], revision=String[])\n \n for i = 1:(size(sizingDF)[1])\n push!(fittingListDF, (sizingDF[i,:Segment], \"PIPE\", 100.0, \"from line sizing\", \"A\"))\n end\n return(fittingListDF)\nend\n\n\n\n\nfunction incrementLineSize(rowNum, lineSizeDF, increment)\n # increment the specified row number needed line size by +1 or -1\n # not the cleanest function, but it works\n \n neededDF = DataFrame(Segment=String[], mmNeeded=Float64[], Schedule=String[])\n \n i = rowNum\n push!(neededDF, (lineSizeDF[i,:Segment], lineSizeDF[i,:IDmm] + increment, lineSizeDF[i,:Schedule]))\n\n incrementedLines = getListLargerNPS(neededDF)\n\n lineSizeDF[i,:NPS] = incrementedLines[1,:NPS]\n lineSizeDF[i,:IDmm] = incrementedLines[1,:IDmm]\n\n return (3.14)\nend\n\nfunction getReynolds(df)\n # preliminary calculations for pipe hydraulics\n # return the velocity, Reynolds, friction factor, density, diameterMM, diameterInch\n\n theSegment = df.Segment\n diamMM = df.IDmm\n diamInch = diamMM / 25.4\n rho = df.rho_kgm3\n volFlow = df.massFlow .* df.margin ./ df.rho_kgm3\n area = 0.25 * pi * (df.IDmm / 1000.0).^2\n velocity = volFlow ./ area / 3600\n Reynolds = df.rho_kgm3 .* velocity .* (df.IDmm / 1000.0) ./ (df.mu_mPas/1000.0)\n eD = df.roughnessMM ./ df.IDmm\n moodyF = calcMoodyF(Reynolds, eD)\n returnValue = DataFrame(Segment = theSegment, velocity_ms = velocity, rho_kgm3 = rho, Re = Reynolds, frictF = moodyF, IDmm = diamMM, IDinch = diamInch)\n return (returnValue)\nend\n\n\nfunction elementDP(lines, fittingList)\n # given the hydraulic elements in df (long list of pipe and fittings)\n # and the preliminary values in prelim\n # calculate the DP in each element\n # dp = rho.f. (L/D) v2/2\n # dp = rho K v2/2\n # where I need to calculate K = K1/Re + Kinf*(1 + Kd/Dinch^0.3)\n # can I get all of the pipe segments and use K = Kp * f L/D, where Kp = 1 for pipe\n # return the value for Kp (1 for pipe, 0 for fitting) and the pressure drop in the item\n returnValue = DataFrame(Segment = String[], Kp = Float64[], fittingK=Float64[], pipeK=Float64[], elementK = Float64[], DPkpa = Float64[])\n \n # start with getting Reynolds and other important things\n prelim = getReynolds(lines)\n\n for i = 1:(size(fittingList)[1])\n theSegment = fittingList[i,:Segment]\n\n # first we get all of the K values\n valK1 = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:K1][1]\n valKinf = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kinf][1]\n valKd = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kd][1]\n valKp = fitting3K[fitting3K[:,:fittingType] .== fittingList[i,:fittingType],:Kp][1]\n\n # now we get the hydraulic properties\n ff = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:frictF][1]\n rho = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:rho_kgm3][1]\n idInch = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:IDinch][1]\n idMM = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:IDmm][1]\n veloc = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:velocity_ms][1]\n Re = prelim[prelim[:,:Segment] .== fittingList[i,:Segment],:Re][1]\n \n Kfitting = valK1/Re + valKinf*(1.0 + valKd/(idInch^0.3))\n\n # pressure drop in kPa\n thisKfitting = fittingList[i,:num_length_m] * Kfitting\n thisKpipe = valKp * ff * fittingList[i,:num_length_m] /(idMM/1000.0) \n thisK = thisKfitting + thisKpipe\n thisDP = thisK * (0.001 * rho * 0.5 * (veloc)^ 2)\n\n push!(returnValue, (theSegment, valKp, thisKfitting, thisKpipe, thisK, thisDP))\n end\n return (returnValue)\nend\n\nfunction compileDP(lines, fittingDP)\n # for each entry in lines, sum all of the fittingDP\n returnValue = DataFrame(Segment = String[], segmentK = Float64[], DPkpa = Float64[], inletP = Float64[], outletP = Float64[])\n\n for i = 1:(size(lines)[1])\n theSegment = lines[i,:Segment]\n theSumK = sum(fittingDP[fittingDP[:,:Segment] .== theSegment,:elementK])\n theSumDP = sum(fittingDP[fittingDP[:,:Segment] .== theSegment,:DPkpa])\n theInletP = lines[i,:inletP_kPaa]\n theOutletP = theInletP - theSumDP\n push!(returnValue, (theSegment, theSumK, theSumDP, theInletP, theOutletP))\n end\n return (returnValue)\nend\n\nfunction getSegmentDP(lines, fittingList, fluidList)\n # lines describes the hydraulics, fittingList has the piping details, fluidList is the fluid\n\n addFluidProperties(lines,fluidList)\n addPipeProperties(lines)\n fittingDP = elementDP(lines, fittingList)\n returnValue = compileDP(lines, fittingDP)\n return (returnValue)\nend\n\nend # module\n", "meta": {"hexsha": "366134fd13b98f053f1561dff7e258bc438bad5b", "size": 14610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/.~Hydraulics_1.jl", "max_stars_repo_name": "kevindorma/Hydraulics2.jl", "max_stars_repo_head_hexsha": "331009cc9417b560eb9442fdf8e1e85d1c5d416f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-30T16:20:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T16:20:28.000Z", "max_issues_repo_path": "src/.~Hydraulics_1.jl", "max_issues_repo_name": "kevindorma/Hydraulics2.jl", "max_issues_repo_head_hexsha": "331009cc9417b560eb9442fdf8e1e85d1c5d416f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/.~Hydraulics_1.jl", "max_forks_repo_name": "kevindorma/Hydraulics2.jl", "max_forks_repo_head_hexsha": "331009cc9417b560eb9442fdf8e1e85d1c5d416f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1689008043, "max_line_length": 159, "alphanum_fraction": 0.6639972621, "num_tokens": 4312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.16559273781891592}} {"text": "export Bellhop\n\n\"\"\"\n$(TYPEDEF)\nA propagation model based on an external FORTRAN Bellhop executable.\n\"\"\"\nstruct Bellhop{T} <: PropagationModel{T}\n env::T\n nbeams::Int\n minangle::Float32\n maxangle::Float32\n gaussian::Bool\n debug::Bool\n function Bellhop(env, nbeams, minangle, maxangle, gaussian, debug)\n nbeams < 0 && (nbeams = 0)\n -π/2 ≤ minangle ≤ π/2 || throw(ArgumentError(\"minangle should be between -π/2 and π/2\"))\n -π/2 ≤ maxangle ≤ π/2 || throw(ArgumentError(\"maxangle should be between -π/2 and π/2\"))\n minangle < maxangle || throw(ArgumentError(\"maxangle should be more than minangle\"))\n new{typeof(env)}(check(Bellhop, env), nbeams, Float32(minangle), Float32(maxangle), gaussian, debug)\n end\nend\n\n\"\"\"\n Bellhop(env; gaussian=false, debug=false)\n Bellhop(env, nbeams, minangle, maxangle, gaussian, debug)\n\nCreate a Bellhop propagation model.\n\"\"\"\nBellhop(env; gaussian=false, debug=false) = Bellhop(env, 0, -80°, 80°, gaussian, debug)\n\n### interface functions\n\nfunction check(::Type{Bellhop}, env::Union{<:UnderwaterEnvironment,Missing})\n if env === missing\n mktempdir(prefix=\"bellhop_\") do dirname\n try\n bellhop(dirname, false)\n catch e\n e isa BellhopError && e.details == [\"Unable to execute bellhop.exe\"] && throw(e)\n end\n end\n else\n seabed(env) isa RayleighReflectionCoef || throw(ArgumentError(\"Seabed type not supported\"))\n seasurface(env) === Vacuum || throw(ArgumentError(\"Only vacuum seasurface supported\"))\n end\n env\nend\n\nfunction arrivals(model::Bellhop, tx1::AcousticSource, rx1::AcousticReceiver)\n mktempdir(prefix=\"bellhop_\") do dirname\n writeenv(model, [tx1], [rx1], \"A\", dirname)\n bellhop(dirname, model.debug)\n readarrivals(joinpath(dirname, \"model.arr\"))\n end\nend\n\nfunction transfercoef(model::Bellhop, tx1::AcousticSource, rx::AcousticReceiverGrid2D; mode=:coherent)\n if mode === :coherent\n taskcode = \"C\"\n elseif mode === :incoherent\n taskcode = \"I\"\n elseif mode === :semicoherent\n taskcode = \"S\"\n else\n throw(ArgumentError(\"Unknown mode :\" * string(mode)))\n end\n mktempdir(prefix=\"bellhop_\") do dirname\n writeenv(model, [tx1], rx, taskcode, dirname)\n bellhop(dirname, model.debug)\n readshd(joinpath(dirname, \"model.shd\"))\n end\nend\n\nfunction transfercoef(model::Bellhop, tx1::AcousticSource, rx1::AcousticReceiver; mode=:coherent)\n if mode === :coherent\n taskcode = \"C\"\n elseif mode === :incoherent\n taskcode = \"I\"\n elseif mode === :semicoherent\n taskcode = \"S\"\n else\n throw(ArgumentError(\"Unknown mode :\" * string(mode)))\n end\n mktempdir(prefix=\"bellhop_\") do dirname\n writeenv(model, [tx1], [rx1], taskcode, dirname)\n bellhop(dirname, model.debug)\n readshd(joinpath(dirname, \"model.shd\"))[1]\n end\nend\n\nfunction eigenrays(model::Bellhop, tx1::AcousticSource, rx1::AcousticReceiver)\n mktempdir(prefix=\"bellhop_\") do dirname\n writeenv(model, [tx1], [rx1], \"E\", dirname)\n bellhop(dirname, model.debug)\n readrays(joinpath(dirname, \"model.ray\"))\n end\nend\n\nfunction rays(model::Bellhop, tx1::AcousticSource, θ::AbstractArray, rmax)\n θ isa AbstractRange || length(θ) == 1 || throw(ArgumentError(\"Bellhop only supports uniformly spaced angles\"))\n all(-π/2 .< θ .< π/2) || throw(ArgumentError(\"θ must be between -π/2 and π/2\"))\n mktempdir(prefix=\"bellhop_\") do dirname\n writeenv(model, [tx1], [AcousticReceiver(rmax, 0.0)], \"R\", dirname; minangle=minimum(θ), maxangle=maximum(θ), nbeams=length(θ))\n bellhop(dirname, model.debug)\n readrays(joinpath(dirname, \"model.ray\"))\n end\nend\n\nrays(model::Bellhop, tx1::AcousticSource, θ, rmax) = rays(model, tx1, [θ], rmax)[1]\n\n### helper functions\n\nstruct BellhopError <: Exception\n details::Vector{String}\nend\n\nfunction Base.show(io::IO, e::BellhopError)\n if length(e.details) == 1\n println(io, e.details[1])\n else\n println(io, \"Bellhop said:\")\n for s ∈ e.details\n println(io, \" \", s)\n end\n end\nend\n\nfunction bellhop(dirname, debug)\n infilebase = joinpath(dirname, \"model\")\n outfilename = joinpath(dirname, \"output.txt\")\n try\n run(pipeline(ignorestatus(`bellhop.exe $infilebase`); stdout=outfilename, stderr=outfilename))\n if debug\n @info \"Bellhop run completed in $dirname, press ENTER to delete intermediate files...\"\n readline()\n end\n catch\n throw(BellhopError([\"Unable to execute bellhop.exe\"]))\n end\n err = String[]\n checkerr!(err, outfilename)\n checkerr!(err, joinpath(dirname, \"model.prt\"))\n if length(err) > 0\n throw(BellhopError(err))\n end\nend\n\nfunction checkerr!(err, filename)\n output = false\n open(filename) do f\n for s in eachline(f)\n if output || occursin(\"ERROR\", uppercase(s))\n push!(err, s)\n output = true\n end\n end\n end\nend\n\nfunction writeenv(model::Bellhop, tx::Vector{<:AcousticSource}, rx::AbstractArray{<:AcousticReceiver}, taskcode, dirname; minangle=model.minangle, maxangle=model.maxangle, nbeams=model.nbeams)\n all(location(tx1)[1] == 0.0 for tx1 ∈ tx) || throw(ArgumentError(\"Bellhop requires transmitters at (0, 0, z)\"))\n all(location(tx1)[2] == 0.0 for tx1 ∈ tx) || throw(ArgumentError(\"Bellhop 2D requires transmitters in the x-z plane\"))\n all(location(rx1)[1] >= 0.0 for rx1 ∈ rx) || throw(ArgumentError(\"Bellhop requires receivers to be in the +x halfspace\"))\n all(location(rx1)[2] == 0.0 for rx1 ∈ rx) || throw(ArgumentError(\"Bellhop 2D requires receivers in the x-z plane\"))\n env = model.env\n name = split(basename(dirname), \"_\")[end]\n filename = joinpath(dirname, \"model.env\")\n open(filename, \"w\") do io\n println(io, \"'\", name, \"'\")\n flist = [nominalfrequency(tx1) for tx1 ∈ tx]\n f = sum(flist) / length(flist)\n maximum(abs.(flist .- f))/f > 0.2 && @warn(\"Source frequency varies by more than 20% from nominal frequency\")\n @printf(io, \"%0.6f\\n\", f)\n println(io, \"1\")\n if length(rx) == 1\n maxr = location(rx[1])[1]\n elseif rx isa AcousticReceiverGrid2D\n maxr = maximum(rx.xrange)\n else\n throw(ArgumentError(\"Receivers must be on a 2D grid\"))\n end\n ss = ssp(env)\n sspi = \"S\"\n ss isa SampledSSP1D && ss.interp === :linear && (sspi = \"C\")\n print(io, \"'\", sspi, \"VWT\")\n alt = altimetry(env)\n if !(alt isa FlatSurface)\n print(io, \"*\")\n createadfile(joinpath(dirname, \"model.ati\"), alt, (p...) -> -altitude(p...), maxr, f)\n end\n println(io, \"'\")\n bathy = bathymetry(env)\n waterdepth = maxdepth(bathy)\n @printf(io, \"1 0.0 %0.6f\\n\", waterdepth)\n if ss isa IsoSSP\n @printf(io, \"0.0 %0.6f /\\n\", soundspeed(ss, 0.0, 0.0, 0.0), )\n @printf(io, \"%0.6f %0.6f /\\n\", waterdepth, soundspeed(ss, 0.0, 0.0, 0.0))\n elseif ss isa SampledSSP1D\n for i ∈ 1:length(ss.z)\n @printf(io, \"%0.6f %0.6f /\\n\", -ss.z[i], ss.c[i])\n end\n else\n for d ∈ range(0.0, waterdepth; length=recommendlength(waterdepth, f))\n @printf(io, \"%0.6f %0.6f /\\n\", d, soundspeed(ss, 0.0, 0.0, -d))\n end\n floor(waterdepth) != waterdepth && @printf(io, \"%0.6f %0.6f /\\n\", waterdepth, soundspeed(ss, 0.0, 0.0, -waterdepth))\n end\n print(io, \"'A\")\n if !(bathy isa ConstantDepth)\n print(io, \"*\")\n createadfile(joinpath(dirname, \"model.bty\"), bathy, depth, maxr, f)\n end\n println(io, \"' 0.0\") # bottom roughness = 0\n bed = seabed(env)\n c2 = soundspeed(ss, 0.0, 0.0, -waterdepth) * bed.cᵣ\n α = bed.δ * 40π / log(10) # based on APL-UW TR 9407 (1994), IV-9 equation (4)\n @printf(io, \"%0.6f %0.6f 0.0 %0.6f %0.6f /\\n\", waterdepth, c2, bed.ρᵣ, α)\n printarray(io, [-location(tx1)[3] for tx1 ∈ tx])\n if length(rx) == 1\n printarray(io, [-location(rx[1])[3]])\n printarray(io, [maxr / 1000.0])\n elseif rx isa AcousticReceiverGrid2D\n printarray(io, reverse(-rx.zrange))\n printarray(io, rx.xrange ./ 1000.0)\n end\n println(io, \"'\", taskcode, model.gaussian ? \"B'\" : \"'\")\n @printf(io, \"%d\\n\", nbeams)\n @printf(io, \"%0.6f %0.6f /\\n\", rad2deg(minangle), rad2deg(maxangle))\n @printf(io, \"0.0 %0.6f %0.6f\\n\", 1.01*waterdepth, 1.01 * maxr / 1000.0)\n end\nend\n\nfunction printarray(io, a::AbstractVector)\n println(io, length(a))\n for a1 ∈ a\n @printf(io, \"%0.6f \", a1)\n end\n println(io, \"/\")\nend\n\nfunction recommendlength(x, f)\n # recommendation based on nominal half-wavelength spacing\n λ = 1500.0 / f\n clamp(round(Int, 2x / λ) + 1, 25, 1000)\nend\n\nfunction createadfile(filename, data, func, maxr, f)\n open(filename, \"w\") do io\n interp = \"L\"\n if data isa SampledDepth || data isa SampledAltitude\n x = data.x\n data.interp !== :linear && (interp = \"C\")\n else\n x = range(0.0, maxr; length=recommendlength(maxr, f))\n end\n println(io, \"'\", interp, \"'\")\n println(io, length(x))\n for i ∈ 1:length(x)\n @printf(io, \"%0.6f %0.6f\\n\", x[i]/1000.0, func(data, x[i], 0.0))\n end\n end\nend\n\nfunction readrays(filename)\n rays = RayArrival{Float64,Float64}[]\n open(filename, \"r\") do io\n [readline(io) for i ∈ 1:7]\n while !eof(io)\n s = strip(readline(io))\n length(s) == 0 && break\n aod = parse(Float64, s)\n pts, sb, bb = parse.(Int, split(strip(readline(io)) ,r\" +\"))\n raypath = Array{NTuple{3,Float64}}(undef, pts)\n for k ∈ 1:pts\n x, d = parse.(Float64, split(strip(readline(io)) ,r\" +\"))\n raypath[k] = (x, 0.0, -d)\n end\n push!(rays, RayArrival(NaN64, NaN64, sb, bb, -deg2rad(aod), NaN64, raypath))\n end\n end\n rays\nend\n\nfunction readarrivals(filename)\n arrivals = RayArrival{Float64,Missing}[]\n open(filename, \"r\") do io\n s = strip(readline(io))\n if occursin(\"2D\", s)\n f = parse(Float64, strip(readline(io)))\n v = split(strip(readline(io)) ,r\" +\")\n n = parse(Int, v[1])\n txdepth = parse.(Float64, v[2:end])\n n == length(txdepth) || error(\"Wrong number of txdepth entries in arrivals\")\n v = split(strip(readline(io)) ,r\" +\")\n n = parse(Int, v[1])\n rxdepth = parse.(Float64, v[2:end])\n n == length(rxdepth) || error(\"Wrong number of rxdepth entries in arrivals\")\n v = split(strip(readline(io)) ,r\" +\")\n n = parse(Int, v[1])\n rxrange = parse.(Float64, v[2:end])\n n == length(rxrange) || error(\"Wrong number of rxrange entries in arrivals\")\n else\n v = split(s ,r\" +\")\n f = parse(Float64, v[1])\n n1, n2, n3 = parse.(Int, v[2:4])\n txdepth = parse.(Float64, split(strip(readline(io)) ,r\" +\"))\n rxdepth = parse.(Float64, split(strip(readline(io)) ,r\" +\"))\n rxrange = parse.(Float64, split(strip(readline(io)) ,r\" +\"))\n n1 == length(txdepth) || error(\"Wrong number of txdepth entries in arrivals\")\n n2 == length(rxdepth) || error(\"Wrong number of rxdepth entries in arrivals\")\n n3 == length(rxrange) || error(\"Wrong number of rxrange entries in arrivals\")\n end\n for j ∈ 1:length(txdepth)\n readline(io)\n for k ∈ 1:length(rxdepth)\n for m ∈ 1:length(rxrange)\n count = parse(Int, strip(readline(io)))\n for n ∈ 1:count\n v = split(strip(readline(io)) ,r\" +\")\n length(v) == 8 || error(\"Wrong number of data entries in arrivals\")\n A, ph, t, _, aod, aoa = parse.(Float64, v[1:6])\n sb, bb = parse.(Int, v[7:8])\n push!(arrivals, RayArrival(t, A * cis(deg2rad(ph)), sb, bb, -deg2rad(aod), deg2rad(aoa)))\n end\n end\n end\n end\n end\n sort(arrivals; by = a -> a.time)\nend\n\nfunction readshd(filename)\n open(filename, \"r\") do io\n r = read(io, UInt32)\n seek(io, 4r)\n b = Array{UInt8}(undef, 10)\n read!(io, b)\n strip(String(b)) == \"rectilin\" || error(\"Bad shd file format: incorrect ptype\")\n seek(io, 8r)\n nfreq = read(io, UInt32)\n nfreq == 1 || error(\"Bad shd file format: incorrect nfreq\")\n nθ = read(io, UInt32)\n nθ == 1 || error(\"Bad shd file format: incorrect nθ\")\n nsx = read(io, UInt32)\n nsy = read(io, UInt32)\n nsd = read(io, UInt32)\n nsd == 1 || error(\"Bad shd file format: incorrect nsd\")\n nrd = read(io, UInt32)\n nrr = read(io, UInt32)\n pressure = Array{ComplexF32}(undef, nrr, nrd)\n for ird ∈ 0:nrd-1\n recnum = 10 + ird\n seek(io, recnum * 4r)\n temp = Array{ComplexF32}(undef, nrr)\n read!(io, temp)\n pressure[:,ird+1] .= -temp # negative because Bellhop seems to have a 180° phase inversion\n end\n reverse(pressure; dims=2)\n end\nend\n", "meta": {"hexsha": "ca6276c4b345ac98b792dd3ca6ae2b3de7a05eda", "size": 12355, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pm_bellhop.jl", "max_stars_repo_name": "apatlpo/UnderwaterAcoustics.jl", "max_stars_repo_head_hexsha": "3ac5a080bf066a9ab4d389e70488fc93bffbf2c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pm_bellhop.jl", "max_issues_repo_name": "apatlpo/UnderwaterAcoustics.jl", "max_issues_repo_head_hexsha": "3ac5a080bf066a9ab4d389e70488fc93bffbf2c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pm_bellhop.jl", "max_forks_repo_name": "apatlpo/UnderwaterAcoustics.jl", "max_forks_repo_head_hexsha": "3ac5a080bf066a9ab4d389e70488fc93bffbf2c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2243767313, "max_line_length": 192, "alphanum_fraction": 0.624524484, "num_tokens": 3993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16504377200862794}} {"text": "\"\"\"\nINI method:\n\n run_omniscape(path::String)\n\nIn-memory method:\n\n run_omniscape(\n cfg::Dict{String, String}\n resistance::Array{Union{Float64, Missing}, 2};\n reclass_table = Array{Union{Float64, Missing}, 2}(undef, 1, 2),\n source_strength = source_from_resistance(resistance, cfg, reclass_table),\n condition1 = Array{Union{Float64, Missing}, 2}(undef, 1, 1),\n condition2 = Array{Union{Float64, Missing}, 2}(undef, 1, 1),\n condition1_future = Array{Union{Float64, Missing}, 2}(undef, 1, 1),\n condition2_future = Array{Union{Float64, Missing}, 2}(undef, 1, 1),\n wkt = \"\",\n geotransform = [0.0, 1.0, 0.0, 0.0, 0.0, -1.0],\n write_outputs = false\n )\n\nCompute omnidirectional current flow. All array inputs for the in-memory method\nshould be of type `Array{Union{T, Missing}, 2} where T <: Number`, with\n`missing` used for NoData pixels.\n\n# Parameters\n**`path`**: The path to an INI file containing run parameters. See the\n[Settings and Options](@ref) section of the User Guide for descriptions of the run\nparameters.\n\n**`cfg`**: A dictionary of Omniscape run parameters. See the [Settings and Options](@ref)\nsection of the User Guide for descriptions of the run parameters and their\ndefault values. The in-memory method of `run_omniscape` ignores the following\nkeys: `resistance_file`, `source_file`, `reclass_table`, `condition1_file`,\n`condition2_file`, `condition1_future_file`, and `condition2_future_file`. These\nall specify file paths, so they do not apply to the in-memory method\nof `run_omniscape`.\n\n**`resistance`**: A 2D, north-oriented array of resistance values. Use\n`missing` for NoData (infinite resistance). `resistance` cannot contain zeros or\nnegative values.\n\n# Keyword Arguments\n\n**`reclass_table`**: A two column array. The first column contains the original\nresistance values in the resistance surface, and the second column specifies\nwhat those values should be changed to. You can reclassify values to `missing`\nto replace them with infinite resistance (NoData).\n\n**`source_strength`**: A 2D, north-oriented array (with size equal to\n`size(resistance)`) of source strength values. `source_strength` is only\nrequired if `source_from_resistance` in `cfg` is set to \"false\"\n(the default value).\n\n**`condition1`**: Optional. Required if `conditional` in`cfg` is set to \"true\".\nA 2D, north-oriented array (with size equal to `size(resistance)`). See\n[Climate Connectivity](@ref) and [Conditional Connectivity Options](@ref) for\nmore information.\n\n**`condition2`**: Optional. Required if `conditional` in`cfg` is set to \"true\"\nand `n_conditions` in `cfg` is set to \"2\". A 2D, north-oriented array (with size\nequal to `size(resistance)`). See [Climate Connectivity](@ref) and\n[Conditional Connectivity Options](@ref) for more information.\n\n**`condition1_future`**: Optional. Required if `conditional` in `cfg` is set\nto \"true\" and `compare_to_future` in `cfg` is set to \"1\" or \"both\".\nA 2D, north-oriented array (with size equal to `size(resistance)`). See\n[Climate Connectivity](@ref) and [Conditional Connectivity Options](@ref) for\nmore information.\n\n**`condition2_future`**: Optional. A 2D, north-oriented array (with size equal to\n`size(resistance)`). See [Climate Connectivity](@ref) and\n[Conditional Connectivity Options](@ref) for more information. Required if\n`conditional` in`cfg` is set to \"true\", `n_conditions` in `cfg` is set to \"2\",\nand `compare_to_future` in `cfg` is set to \"2\" or \"both\".\n\n**`wkt`**: Optionally specify a Well Known Text representation of the projection\nused for your spatial data inputs. Only used if Omniscape writes raster\noutputs to disk.\n\n**`geotransform`**: In addition to `wkt`, optionally specify a geotransform.\nThe geotransform is a 6-element vector with elements as follows for a north up\noriented image: `[, ,\n, ,\n, ]`.\nOnly used when writing raster outputs to disk.\n\n**`write_outputs`**: Boolean specifying if outputs should be written to disk.\nDefaults to `false`. If `true`, `cfg` must contain a value for the `project_name`\nkey.\n\n\"\"\"\nfunction run_omniscape(\n cfg::Dict{String, String},\n resistance::Array{Union{T, Missing}, 2} where T <: Number;\n reclass_table::Array{Union{T, Missing}, 2} where T <: Number = Array{Union{Float64, Missing}, 2}(undef, 1, 2),\n source_strength::Array{Union{T, Missing}, 2} where T <: Number = source_from_resistance(resistance, cfg, reclass_table),\n condition1::Array{Union{T, Missing}, 2} where T <: Number = Array{Union{Float64, Missing}, 2}(undef, 1, 1),\n condition2::Array{Union{T, Missing}, 2} where T <: Number = Array{Union{Float64, Missing}, 2}(undef, 1, 1),\n condition1_future::Array{Union{T, Missing}, 2} where T <: Number = condition1,\n condition2_future::Array{Union{T, Missing}, 2} where T <: Number = condition2,\n wkt::String = \"\",\n geotransform::Array{Float64, 1} = [0., 1., 0., 0., 0., -1.0],\n write_outputs::Bool = false)\n\n start_time = time()\n n_threads = nthreads()\n cfg_user = cfg\n\n # Check for unsupported or missing arguments\n check_unsupported_args(cfg)\n check_missing_args_dict(cfg_user) && return\n\n cfg = init_cfg()\n update_cfg!(cfg, cfg_user)\n\n ## Parse commonly called integer arguments\n int_arguments = Dict{String, Int64}()\n\n int_arguments[\"block_size\"] = Int64(round(parse(Float64,\n cfg[\"block_size\"])))\n\n check_block_size!(int_arguments)\n\n int_arguments[\"block_radius\"] = Int64((int_arguments[\"block_size\"] - 1) / 2)\n int_arguments[\"radius\"] = Int64(round(parse(Float64, cfg[\"radius\"])))\n int_arguments[\"buffer\"] = Int64(round(parse(Float64, cfg[\"buffer\"])))\n int_arguments[\"n_conditions\"] = Int64(round(parse(Float64, cfg[\"n_conditions\"])))\n\n ## Parse other arguments\n compare_to_future = lowercase(cfg[\"compare_to_future\"])\n precision = cfg[\"precision\"] in SINGLE ? Float32 : Float64\n\n # flags\n os_flags = get_omniscape_flags(cfg)\n\n # other\n source_threshold = parse(Float64, cfg[\"source_threshold\"])\n project_name = cfg[\"project_name\"]\n file_format = os_flags.write_as_tif ? \"tif\" : \"asc\"\n\n check_solver!(cfg)\n solver = cfg[\"solver\"]\n\n ## Set number of BLAS threads to 1 when parallel processing\n if os_flags.parallelize && nthreads() != 1\n BLAS.set_num_threads(1)\n end\n\n check_resistance_values(resistance) && return\n\n # Reclassify resistance layer\n if os_flags.reclassify\n reclassify_resistance!(resistance, reclass_table)\n end\n\n int_arguments[\"nrows\"] = size(source_strength, 1)\n int_arguments[\"ncols\"] = size(source_strength, 2)\n\n # Set up conditional connctivity stuff\n conditions = Conditions(cfg[\"comparison1\"],\n cfg[\"comparison2\"],\n parse(Float64, cfg[\"condition1_lower\"]),\n parse(Float64, cfg[\"condition1_upper\"]),\n parse(Float64, cfg[\"condition2_lower\"]),\n parse(Float64, cfg[\"condition2_upper\"]))\n\n condition_layers = ConditionLayers(condition1, condition1_future, condition2, condition2_future)\n\n ## Setup Circuitscape configuration\n cs_cfg_dict = init_csdict(cfg)\n cs_cfg_dict[\"solver\"] = solver\n cs_cfg = Circuitscape.init_config()\n Circuitscape.update!(cs_cfg, cs_cfg_dict)\n\n ## Calculate targets\n targets = get_targets(source_strength,\n int_arguments,\n precision)\n\n ## Circuitscape calls in loop over targets\n n_targets = size(targets, 1)\n\n # Permute targets randomly (to get better estimate of ProgressMeter ETA)\n targets = targets[randperm(n_targets), :]\n\n ## Define parameters for cs\n # Get flags\n o = Circuitscape.OutputFlags(false, false,\n false, false,\n false, false,\n false, false)\n\n precision_name = precision == Float64 ? \"double\" : \"single\"\n ## Add parallel workers\n if os_flags.parallelize\n @info(\"Starting up Omniscape with $(n_threads) workers and $(precision_name) precision\")\n @info(\"Using Circuitscape with the $(uppercase(solver)) solver...\")\n\n cum_currmap = fill(convert(precision, 0.),\n int_arguments[\"nrows\"],\n int_arguments[\"ncols\"],\n n_threads)\n\n if os_flags.calc_flow_potential || os_flags.calc_normalized_current\n fp_cum_currmap = fill(convert(precision, 0.),\n int_arguments[\"nrows\"],\n int_arguments[\"ncols\"],\n n_threads)\n else\n # Hacky fix -- a later function needs fp_cum_currmap to be an array\n fp_cum_currmap = Array{precision, 3}(undef, 1, 1, 1)\n end\n else\n @info(\"Starting up Omniscape with 1 worker and $(precision_name) precision\")\n @info(\"Using Circuitscape with the $(uppercase(solver)) solver...\")\n cum_currmap = fill(convert(precision, 0.),\n int_arguments[\"nrows\"],\n int_arguments[\"ncols\"],\n 1)\n\n if os_flags.calc_flow_potential || os_flags.calc_normalized_current\n fp_cum_currmap = fill(convert(precision, 0.),\n int_arguments[\"nrows\"],\n int_arguments[\"ncols\"],\n 1)\n else\n fp_cum_currmap = Array{precision, 3}(undef, 1, 1, 1)\n end\n end\n\n cs_flags = Circuitscape.RasterFlags(true, false, true,\n false, false,\n false, Symbol(\"rmvsrc\"),\n cfg[\"connect_four_neighbors_only\"] in TRUELIST,\n false, solver, o)\n\n if os_flags.correct_artifacts && !(int_arguments[\"block_size\"] == 1)\n @info(\"Calculating block artifact correction array...\")\n correction_array = calc_correction(int_arguments,\n os_flags,\n cs_cfg,\n cs_flags,\n condition_layers,\n conditions,\n precision)\n\n else\n correction_array = Array{precision, 2}(undef, 1, 1)\n end\n\n ## Calculate and accumulate currents on each worker\n @info(\"Solving moving window targets...\")\n\n ## Create progress object\n p = Progress(n_targets; dt = 0.25, barlen = min(50, displaysize(stdout)[2] - length(\"Progress: 100% Time: 00:00:00\")))\n\n if os_flags.parallelize\n parallel_batch_size = Int64(round(parse(Float64, cfg[\"parallel_batch_size\"])))\n n_batches = Int(ceil(n_targets / parallel_batch_size))\n\n @threads for i in 0:(n_batches - 1)\n start_ind = parallel_batch_size * i + 1\n end_ind = min(n_targets, start_ind + parallel_batch_size - 1)\n \n for j in start_ind:end_ind\n target = Target(Int64(targets[j, 1]), Int64(targets[j, 2]), float(targets[j, 3]))\n try \n solve_target!(target,\n int_arguments,\n source_strength,\n resistance,\n os_flags,\n cs_cfg,\n cs_flags,\n condition_layers,\n conditions,\n correction_array,\n cum_currmap,\n fp_cum_currmap,\n precision)\n catch error\n println(\"Omniscape failed on the moving window centered on row $(target.y_coord) column $(target.x_coord)\")\n throw(error)\n end\n next!(p)\n end\n end\n else\n for i in 1:n_targets\n target = Target(Int64(targets[i, 1]), Int64(targets[i, 2]), float(targets[i, 3]))\n try\n solve_target!(target,\n int_arguments,\n source_strength,\n resistance,\n os_flags,\n cs_cfg,\n cs_flags,\n condition_layers,\n conditions,\n correction_array,\n cum_currmap,\n fp_cum_currmap,\n precision)\n catch error\n println(\"Omniscape failed on the moving window centered on row $(target.y_coord) column $(target.x_coord)\")\n throw(error)\n end\n next!(p)\n end\n end\n\n ## Set some objects to nothing to free up memory\n source_strength = nothing\n condition1 = nothing\n condition1_future = nothing\n condition2 = nothing\n condition2_future = nothing\n GC.gc()\n\n ## Collapse 3-dim cum current arrays to 2-dim via sum\n cum_currmap = dropdims(sum(cum_currmap, dims = 3), dims = 3)\n\n if os_flags.calc_flow_potential || os_flags.calc_normalized_current\n fp_cum_currmap = dropdims(sum(fp_cum_currmap, dims = 3), dims = 3)\n end\n\n ## Normalize by flow potential\n if os_flags.calc_normalized_current\n normalized_cum_currmap = cum_currmap ./ fp_cum_currmap\n # replace NaNs with 0's\n normalized_cum_currmap[isnan.(normalized_cum_currmap)] .= 0\n end\n\n if write_outputs\n ## create new directory if project_name already exists\n dir_suffix = 1\n while isdir(string(project_name, \"_$(dir_suffix)\"))\n dir_suffix+=1\n end\n isdir(project_name) && (project_name = string(project_name, \"_$(dir_suffix)\"))\n mkpath(project_name)\n end\n\n ## Overwrite no data\n if os_flags.mask_nodata\n if os_flags.calc_normalized_current\n normalized_cum_currmap[ismissing.(resistance)] .= -9999\n end\n if os_flags.calc_flow_potential\n fp_cum_currmap[ismissing.(resistance)] .= -9999\n end\n cum_currmap[ismissing.(resistance)] .= -9999\n end\n\n GC.gc()\n\n ## Write outputs\n if write_outputs\n write_cfg(cfg_user, project_name)\n\n if os_flags.reclassify && os_flags.write_reclassified_resistance\n resistance[ismissing.(resistance)] .= -9999\n write_raster(\"$(project_name)/classified_resistance\",\n convert(Array{precision, 2}, resistance),\n wkt,\n geotransform,\n file_format)\n end\n\n if os_flags.write_raw_currmap\n write_raster(\"$(project_name)/cum_currmap\",\n cum_currmap,\n wkt,\n geotransform,\n file_format)\n end\n\n if os_flags.calc_flow_potential\n write_raster(\"$(project_name)/flow_potential\",\n fp_cum_currmap,\n wkt,\n geotransform,\n file_format)\n end\n\n if os_flags.calc_normalized_current\n write_raster(\"$(project_name)/normalized_cum_currmap\",\n normalized_cum_currmap,\n wkt,\n geotransform,\n file_format)\n end\n end\n\n resistance = nothing\n\n @info(\"Time taken to complete job: $(round(time() - start_time; digits = 4)) seconds\")\n\n if write_outputs\n @info(\"Outputs written to $(string(pwd(),\"/\",project_name))\")\n end\n ## Return outputs, depending on user options\n # convert arrays, replace -9999's with missing\n cum_currmap = convert_and_fill_missing(cum_currmap, precision)\n\n if os_flags.calc_normalized_current && !os_flags.calc_flow_potential\n normalized_cum_currmap = convert_and_fill_missing(normalized_cum_currmap, precision)\n return cum_currmap, normalized_cum_currmap\n elseif !os_flags.calc_normalized_current && os_flags.calc_flow_potential\n fp_cum_currmap = convert_and_fill_missing(fp_cum_currmap, precision)\n return cum_currmap, fp_cum_currmap\n elseif os_flags.calc_normalized_current && os_flags.calc_flow_potential\n fp_cum_currmap = convert_and_fill_missing(fp_cum_currmap, precision)\n normalized_cum_currmap = convert_and_fill_missing(normalized_cum_currmap, precision)\n return cum_currmap, fp_cum_currmap, normalized_cum_currmap\n else\n return cum_currmap\n end\nend\n\nfunction run_omniscape(path::String)\n cfg_user = parse_cfg(path)\n check_missing_args_ini(cfg_user) && return\n\n cfg = init_cfg()\n update_cfg!(cfg, cfg_user)\n\n ## flags and other cfg args\n os_flags = get_omniscape_flags(cfg)\n compare_to_future = lowercase(cfg[\"compare_to_future\"])\n precision = cfg[\"precision\"] in SINGLE ? Float32 : Float64\n n_conditions = Int64(round(parse(Float64, cfg[\"n_conditions\"])))\n allow_different_projections = cfg[\"allow_different_projections\"] in TRUELIST\n source_threshold = parse(precision, cfg[\"source_threshold\"])\n\n ## Load resistance\n resistance_raster = read_raster(\"$(cfg[\"resistance_file\"])\", precision)\n resistance = resistance_raster[1]\n\n wkt = resistance_raster[2]\n geotransform = resistance_raster[3]\n\n check_resistance_values(resistance) && return\n\n ## Load reclass table if applicable\n if os_flags.reclassify\n reclass_table = read_reclass_table(\"$(cfg[\"reclass_table\"])\", precision)\n else\n reclass_table = Array{Union{precision, Missing}, 2}(undef, 1, 2)\n end\n\n ## Load source strengths\n if !os_flags.source_from_resistance\n sources_raster = read_raster(\"$(cfg[\"source_file\"])\", precision)\n source_strength = sources_raster[1]\n\n # Check for raster alignment\n check_raster_alignment(resistance_raster, sources_raster,\n \"resistance_file\", \"source_file\",\n allow_different_projections) && return\n\n # get rid of unneeded raster to save memory\n sources_raster = nothing\n\n # overwrite nodata with 0\n source_strength[ismissing.(source_strength)] .= 0.0\n\n # Set values < user-specified threshold to 0\n source_strength[source_strength .< source_threshold] .= 0.0\n else\n source_strength = source_from_resistance(resistance, cfg, reclass_table)\n end\n\n ## Load condition rasters\n if os_flags.conditional\n condition1_raster = read_raster(\"$(cfg[\"condition1_file\"])\", precision)\n condition1 = condition1_raster[1]\n\n # Check for raster alignment\n check_raster_alignment(resistance_raster, condition1_raster,\n \"resistance_file\", \"condition1_file\",\n allow_different_projections) && return\n\n # get rid of unneedecheck_rasterd raster to save memory\n condition1_raster = nothing\n\n if compare_to_future == \"1\" || compare_to_future == \"both\"\n condition1_future_raster = read_raster(\"$(cfg[\"condition1_future_file\"])\", precision)\n condition1_future = condition1_future_raster[1]\n\n # Check for raster alignment\n check_raster_alignment(resistance_raster, condition1_future_raster,\n \"resistance_file\", \"condition1_future_file\",\n allow_different_projections) && return\n\n # get rid of unneeded raster to save memory\n condition1_future_raster = nothing\n else\n condition1_future = condition1\n end\n\n if n_conditions == 2\n condition2_raster = read_raster(\"$(cfg[\"condition2_file\"])\", precision)\n condition2 = condition2_raster[1]\n\n # Check for raster alignment\n check_raster_alignment(resistance_raster, condition2_raster,\n \"resistance_file\", \"condition2_file\",\n allow_different_projections) && return\n\n # get rid of unneeded raster to save memory\n condition2_raster = nothing\n\n if compare_to_future == \"2\" || compare_to_future == \"both\"\n condition2_future_raster = read_raster(\"$(cfg[\"condition2_future_file\"])\", precision)\n condition2_future = condition2_future_raster[1]\n\n # Check for raster alignment\n check_raster_alignment(resistance_raster, condition2_future_raster,\n \"resistance_file\", \"condition2_future_file\",\n allow_different_projections) && return\n\n # get rid of unneeded raster to save memory\n condition2_future_raster = nothing\n else\n condition2_future = condition2\n end\n\n else\n condition2 = Array{Union{Missing, precision}, 2}(undef, 1, 1)\n condition2_future = condition2\n end\n else\n condition1 = Array{Union{Missing, precision}, 2}(undef, 1, 1)\n condition2 = Array{Union{Missing, precision}, 2}(undef, 1, 1)\n condition1_future = condition1\n condition2_future = condition2\n end\n\n resistance_raster = nothing\n\n run_omniscape(\n cfg,\n resistance;\n source_strength = source_strength,\n condition1 = condition1,\n condition2 = condition2,\n condition1_future = condition1_future,\n condition2_future = condition2_future,\n geotransform = geotransform,\n wkt = wkt,\n reclass_table = reclass_table,\n write_outputs = true\n )\nend\n", "meta": {"hexsha": "6540130419e0b60e7fdae648d5b0480b4d8e7433", "size": 22354, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/main.jl", "max_stars_repo_name": "Circuitscape/Omniscape.jl", "max_stars_repo_head_hexsha": "1746c980ab1b75f1ab68bfa8416b8583a5c653c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2019-06-29T04:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:24:01.000Z", "max_issues_repo_path": "src/main.jl", "max_issues_repo_name": "Circuitscape/Omniscape.jl", "max_issues_repo_head_hexsha": "1746c980ab1b75f1ab68bfa8416b8583a5c653c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 84, "max_issues_repo_issues_event_min_datetime": "2019-07-11T16:54:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:56:56.000Z", "max_forks_repo_path": "src/main.jl", "max_forks_repo_name": "Circuitscape/Omniscape.jl", "max_forks_repo_head_hexsha": "1746c980ab1b75f1ab68bfa8416b8583a5c653c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T22:10:25.000Z", "avg_line_length": 40.0609318996, "max_line_length": 128, "alphanum_fraction": 0.6056634159, "num_tokens": 4983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.31069437044942166, "lm_q1q2_score": 0.165043761837191}} {"text": "\n# This file is part of UnitSystems.jl. It is licensed under the MIT license\n# UnitSystems Copyright (C) 2021 Michael Reed\n\nexport Universe, coupling, finestructure, electronunit, protonunit, protonelectron\n#const Mu,Ru,SB,hh,cc,m0,e0,ke,me,mp,mu,ee,FF,Z0,G0,Eh,a0,re,g0,lP,ϵ₀,mB = Mᵤ,Rᵤ,σ,𝘩,𝘤,μ₀,ε₀,kₑ,mₑ,mₚ,mᵤ,𝘦,𝔉,Z₀,G₀,Eₕ,a₀,rₑ,g₀,ℓP,ε₀,μB\nexport slug, ft, KJ1990, KJ2014, RK1990, RK2014, mₑ1990, mₑ2014, temp, units\nexport slugs, kilograms, lbm, meters, feet, rankine, kelvin, moles, molecules\nexport UnitSystem, US, SI, MKS, CGS, CGS2019, CGSm, CGSe, HLU, FFF\n\n# == Metric is different\nconst κ = einstein(SI2019)\nconst σ = stefan(SI2019) #\nconst μB = magneton(SI2019) #\nconst ε₀ = permittivity(SI2019) #\nconst kₑ = coulomb(SI2019) #\nconst mₚ = protonmass(SI2019)\nconst mᵤ = atomicmass(SI2019)\nconst Mᵤ = molarmass(SI2019)\nconst 𝔉 = faraday(SI2019) #\nconst Φ₀ = magneticflux(SI2019) #\nconst Z₀ = impedance(SI2019) #\nconst G₀ = conductance(SI2019) #\nconst Eₕ = hartree(SI2019)\nconst a₀ = bohr(SI2019)\nconst rₑ = electronradius(SI2019)\nconst RK = klitzing(SI2019) #\nconst KJ = josephson(SI2019) #\nconst RH,Ry = R∞*mₚ/(mₑ+mₚ),𝘩*𝘤*R∞\n\nconst ℓP = length(PlanckGauss,SI2019)\nconst tP = time(PlanckGauss,SI2019)\nconst TP = temperature(PlanckGauss,SI2019)\n\nconst lS = length(Stoney,SI2019)\nconst tS = time(Stoney,SI2019)\nconst mS = mass(Stoney,SI2019)\nconst qS = charge(Stoney,SI2019)\n\nconst lA = length(Hartree,SI2019)\nconst tA = time(Hartree,SI2019)\nconst mA = mass(Hartree,SI2019)\nconst qA = charge(Hartree,SI2019)\n\nconst lQCD = length(QCD,SI2019)\nconst tQCD = time(QCD,SI2019)\nconst mQCD = mass(QCD,SI2019)\n\n# non standard units\n\nconst BTUftlb = 3600/0.5778thermalconductivity(English) # BTU⋅ft⁻¹⋅lb⁻¹\nconst BTUJ = energy(English)*BTUftlb # BTU⋅J⁻¹\n\n# constant aliases\n\nconst mpe, meu, mpu, ainv, aG = μₚₑ, μₑᵤ, μₚᵤ, αinv, αG\nconst Mu,Ru,SB,hh,cc,m0,e0,ke,me,mp,mu,ee,FF,Z0,G0,Eh,a0,re,g0,lP,aL,ϵ₀ = Mᵤ,Rᵤ,σ,𝘩,𝘤,μ₀,ε₀,kₑ,mₑ,mₚ,mᵤ,𝘦,𝔉,Z₀,G₀,Eₕ,a₀,rₑ,g₀,ℓP,αL,ε₀\nexport κ, GG, NA, kB, Rᵤ, σ, 𝘩, ħ, 𝘤, μ₀, ε₀, kₑ, mₑ, mₚ, mᵤ, 𝘦, 𝔉, Φ₀, Z₀, G₀, Eₕ, R∞, a₀, rₑ, KJ, RK, Ru, SB, hh, cc, m0, e0, ke, me, mp, mu, ee, FF, Z0, G0, Eh, a0, re, μB\nexport αG, αinv, μₚₑ, μₑᵤ, μₚᵤ, mpe, meu, mpu, mP, δμ₀, Mᵤ, Mu, RH, Ry, ΔνCs, Kcd, ainv\nexport cal, kcal, calₜₕ, kcalₜₕ, calᵢₜ, kcalᵢₜ, ℓP, g₀, g0, atm, lbm, BTUJ, BTUftlb, aG\nexport lP, tP, TP, lS, tS, mS, qS, lA, tA, mA, qA, lQCD, tQCD, mQCD, ϵ₀, αL, aL\n\n# engineering unit systems docs\n\ncgstext(US,AMP,cgs=eval(US)) = \"\"\"\n```Julia\njulia> boltzmann($US) # erg⋅K⁻¹\n$(boltzmann(cgs))\n\njulia> planckreduced($US) # erg⋅s⋅rad⁻¹\n$(planckreduced(cgs))\n\njulia> lightspeed($US) # cm⋅s⁻¹\n$(lightspeed(cgs))\n\njulia> permeability($US) # statH⋅cm⁻¹\n$(permeability(cgs))\n\njulia> electronmass($US) # g\n$(electronmass(cgs))\n\njulia> rationalization($US)\n$(rationalization(cgs))\n```\n\"\"\"\n\nfor U ∈ (:CGSm,:CGSe,:EMU,:ESU)\n (EU,AMP) = QuoteNode.(U ∉ (:CGSe,:ESU) ? (:EMU,:Bi) : (:ESU,:statA))\n@eval @doc \"\"\"\n $($(QuoteNode(U)))::UnitSystem{1e10*Rᵤ*mₑ/μₑᵤ,1e7*ħ,100𝘤,$($EU≠:EMU ? \"(100𝘤)^-2\" : 1),1000mₑ,4π}\n\nCentimetre-gram-second `UnitSystem` variant based on `$($EU)` (non-rationalized).\n\n$(cgstext($(QuoteNode(U)),$AMP))\n\"\"\" $U\n\nU ∉ (:CGSm,:CGSe) && @eval @doc \"\"\"\n $(Symbol($(QuoteNode(U)),:2019))::UnitSystem{1e7*kB,1e7*ħ,100𝘤,$($EU≠:EMU ? \"1e3*μ₀/𝘤^2\" : \"1e7*μ₀\"),1000mₑ}\n\nCentimetre-gram-second `UnitSystem` variant of tuned `SI2019` based on `$($EU)` (rationalized).\n\n$(cgstext(Symbol($(QuoteNode(U)),:2019),$AMP))\n\"\"\" $(Symbol(U,:2019))\nend\n\n@doc \"\"\"\n Thomson::UnitSystem{1e10*Rᵤ*mₑ/μₑᵤ,1e7*ħ,100𝘤,1,1000mₑ,4π,1/2}\n\nCentimetre-gram-second `UnitSystem` variant `Thomson` (EMU-Lorentz, non-rationalized).\n\n```Julia\njulia> boltzmann(Thomson) # erg⋅K⁻¹\n$(boltzmann(Thomson))\n\njulia> planckreduced(Thomson) # erg⋅s⋅rad⁻¹\n$(planckreduced(Thomson))\n\njulia> lightspeed(Thomson) # cm⋅s⁻¹\n$(lightspeed(Thomson))\n\njulia> permeability(Thomson) # abH⋅cm⁻¹\n$(permeability(Thomson))\n\njulia> electronmass(Thomson) # g\n$(electronmass(Thomson))\n\njulia> rationalization(Thomson)\n$(rationalization(Thomson))\n\njulia> lorentz(Thomson)\n$(lorentz(Thomson))\n```\n\"\"\" Thomson\n\n@doc \"\"\"\n Gauss::UnitSystem{1e10*Rᵤ*mₑ/μₑᵤ,1e7*ħ,100𝘤,1,1000mₑ,4π,0.01/𝘤}\n\nCentimetre-gram-second `UnitSystem` variant `CGS` (Gauss-Lorentz, non-rationalized).\n\n```Julia\njulia> boltzmann(Gauss) # erg⋅K⁻¹\n$(boltzmann(Gauss))\n\njulia> planckreduced(Gauss) # erg⋅s⋅rad⁻¹\n$(planckreduced(Gauss))\n\njulia> lightspeed(Gauss) # cm⋅s⁻¹\n$(lightspeed(Gauss))\n\njulia> permeability(Gauss) # statH⋅cm⁻¹\n$(permeability(Gauss))\n\njulia> electronmass(Gauss) # g\n$(electronmass(Gauss))\n\njulia> rationalization(Gauss)\n$(rationalization(Gauss))\n\njulia> lorentz(Gauss)\n$(lorentz(Gauss))\n```\n\"\"\" Gauss, CGS\n\n@doc \"\"\"\n LorentzHeaviside::UnitSystem{1e10*Rᵤ*mₑ/μₑᵤ,1e7*ħ,100𝘤,1,1000mₑ,1,0.01/𝘤}\n\nCentimetre-gram-second `UnitSystem` variant `HLU` (Heaviside-Lorentz, rationalized).\n\n```Julia\njulia> boltzmann(LorentzHeaviside) # erg⋅K⁻¹\n$(boltzmann(LorentzHeaviside))\n\njulia> planckreduced(LorentzHeaviside) # erg⋅s⋅rad⁻¹\n$(planckreduced(LorentzHeaviside))\n\njulia> lightspeed(LorentzHeaviside) # cm⋅s⁻¹\n$(lightspeed(LorentzHeaviside))\n\njulia> permeability(HLU) # hlH⋅cm⁻¹\n$(permeability(LorentzHeaviside))\n\njulia> electronmass(LorentzHeaviside) # g\n$(electronmass(LorentzHeaviside))\n\njulia> rationalization(LorentzHeaviside)\n$(rationalization(LorentzHeaviside))\n\njulia> lorentz(LorentzHeaviside)\n$(lorentz(LorentzHeaviside))\n```\n\"\"\" LorentzHeaviside, HLU\n\n@doc \"\"\"\n MTS::UnitSystem{1e6*Rᵤ*mₑ/μₑᵤ,1000ħ,𝘤,4π/1e4,mₑ/1000}\n\nMetre-tonne-second `UnitSystem` variant of `Metric` system.\n\n```Julia\njulia> boltzmann(MTS) # kJ⋅K⁻¹\n$(boltzmann(MTS))\n\njulia> planckreduced(MTS) # kJ⋅s⋅rad⁻¹\n$(planckreduced(MTS))\n\njulia> lightspeed(MTS) # m⋅s⁻¹\n$(lightspeed(MTS))\n\njulia> permeability(MTS) # kH⋅m⁻¹\n$(permeability(MTS))\n\njulia> electronmass(MTS) # t\n$(electronmass(MTS))\n```\n\"\"\" MTS\n\n@doc \"\"\"\n Metric::UnitSystem{Rᵤ*mₑ/μₑᵤ/0.001,ħ,𝘤,4π*1e-7,mₑ}\n\nSysteme International d'Unites (the SI units) adopted as the preferred `UnitSystem`.\n\n```Julia\njulia> boltzmann(Metric) # J⋅K⁻¹\n$(boltzmann(Metric))\n\njulia> planckreduced(Metric) # J⋅s⋅rad⁻¹\n$(planckreduced(Metric))\n\njulia> lightspeed(Metric) # m⋅s⁻¹\n$(lightspeed(Metric))\n\njulia> permeability(Metric) # H⋅m⁻¹\n$(permeability(Metric))\n\njulia> electronmass(Metric) # kg\n$(electronmass(Metric))\n```\n\"\"\" Metric\n\n@doc \"\"\"\n SI2019::UnitSystem{kB,ħ,𝘤,μ₀,mₑ}\n\nSysteme International d'Unites (the SI units) with `μ₀` for a tuned `charge` exactly.\n\n```Julia\njulia> boltzmann(SI2019) # J⋅K⁻¹\n$(boltzmann(SI2019))\n\njulia> planckreduced(SI2019) # J⋅s⋅rad⁻¹\n$(planckreduced(SI2019))\n\njulia> lightspeed(SI2019) # m⋅s⁻¹\n$(lightspeed(SI2019))\n\njulia> permeability(SI2019) # H⋅m⁻¹\n$(permeability(SI2019))\n\njulia> electronmass(SI2019) # kg\n$(electronmass(SI2019))\n```\n\"\"\" SI2019, SI\n\n@doc \"\"\"\n CODATA::UnitSystem{Rᵤ*mₑ2014/μₑᵤ/0.001,2/RK2014/KJ2014^2/π,𝘤,2RK2014/𝘤/αinv,mₑ2014}\n\nMetric `UnitSystem` based on Committee on Data of the International Science Council.\n\n```Julia\njulia> boltzmann(CODATA) # J⋅K⁻¹\n$(boltzmann(CODATA))\n\njulia> planckreduced(CODATA) # J⋅s⋅rad⁻¹\n$(planckreduced(CODATA))\n\njulia> lightspeed(CODATA) # m⋅s⁻¹\n$(lightspeed(CODATA))\n\njulia> permeability(CODATA) # H⋅m⁻¹\n$(permeability(CODATA))\n\njulia> electronmass(CODATA) # kg\n$(electronmass(CODATA))\n```\n\"\"\" CODATA\n\n@doc \"\"\"\n Conventional::UnitSystem{Rᵤ*mₑ1990/μₑᵤ/0.001,2/RK1990/KJ1990^2/π,𝘤,2RK1990/𝘤/αinv,mₑ1990}\n\nConventional electronic `UnitSystem` with 1990 tuned `josephson` and `klitzing` constants.\n\n```Julia\njulia> boltzmann(Conventional) # J⋅K⁻¹\n$(boltzmann(Conventional))\n\njulia> planckreduced(Conventional) # J⋅s⋅rad⁻¹\n$(planckreduced(Conventional))\n\njulia> lightspeed(Conventional) # m⋅s⁻¹\n$(lightspeed(Conventional))\n\njulia> permeability(Conventional) # H⋅m⁻¹\n$(permeability(Conventional))\n\njulia> electronmass(Conventional) # kg\n$(electronmass(Conventional))\n```\n\"\"\" Conventional\n\n@doc \"\"\"\n IAU::UnitSystem{Rᵤ*mₑ/μₑᵤ/0.001/Jₛ,ħ*day/Jₛ,day*𝘤/au,4π*1e-7*day^2/Jₛ,mₑ/mₛ}\n\nAstronomical (solar) `UnitSystem` defined by International Astronomical Union.\n\n```Julia\njulia> boltzmann(IAU) # M⊙⋅au²⋅D⁻²⋅K⁻¹\n$(boltzmann(IAU))\n\njulia> planckreduced(IAU) # M⊙⋅au²⋅D⁻¹⋅rad⁻¹\n$(planckreduced(IAU))\n\njulia> lightspeed(IAU) # au⋅D⁻¹\n$(lightspeed(IAU))\n\njulia> permeability(IAU) # M⊙⋅au²⋅C⁻²\n$(permeability(IAU))\n\njulia> electronmass(IAU) # M⊙\n$(electronmass(IAU))\n```\n\"\"\" IAU\n\n@doc \"\"\"\n English::UnitSystem{kB*rankine/slug/ft^2,ħ/slug/ft^2,𝘤/ft,4π,mₑ/slug}\n\nEngineering `UnitSystem` historically used by Britain and United States.\n\n```Julia\njulia> boltzmann(English) # ft⋅lb⋅°R⁻¹\n$(boltzmann(English))\n\njulia> planckreduced(English) # ft⋅lb⋅s⋅rad⁻¹\n$(planckreduced(English))\n\njulia> lightspeed(English) # ft⋅s⁻¹\n$(lightspeed(English))\n\njulia> permeability(English) # slug⋅ft²⋅?⁻²\n$(permeability(English))\n\njulia> electronmass(English) # slugs\n$(electronmass(English))\n```\n\"\"\" English\n\n@doc \"\"\"\n EnglishUS::UnitSystem{1000Rᵤ*mₑ/μₑᵤ*rankine/slug/ftUS^2,ħ/slug/ftUS^2,𝘤/ftUS,4π,mₑ/slug}\n\nEngineering `UnitSystem` based on the geophysical US survey foot (1200/3937).\n\n```Julia\njulia> boltzmann(EnglishUS) # ftUS⋅lb⋅°R⁻¹\n$(boltzmann(EnglishUS))\n\njulia> planckreduced(EnglishUS) # ftUS⋅lb⋅s⋅rad⁻¹\n$(planckreduced(EnglishUS))\n\njulia> lightspeed(EnglishUS) # ftUS⋅s⁻¹\n$(lightspeed(EnglishUS))\n\njulia> permeability(EnglishUS) # slug⋅ftUS²⋅?⁻²\n$(permeability(EnglishUS))\n\njulia> electronmass(EnglishUS) # slugs\n$(electronmass(EnglishUS))\n```\n\"\"\" EnglishUS\n\n@doc \"\"\"\n FFF::UnitSystem{Rᵤ*mₑ/μₑᵤ/0.001*rankine/Jf,ħ/14day/Jf,14day*𝘤/201.168,0,mₑ/mf}\n\nFurlong–firkin–fortnight `FFF` is a humorous `UnitSystem` based on unusal impractical units.\n\n```Julia\njulia> boltzmann(FFF) # fir⋅fur²⋅ftn⁻²⋅F⁻¹\n$(boltzmann(FFF))\n\njulia> planckreduced(FFF) # fir⋅fur²⋅ftn⁻¹⋅rad⁻¹\n$(planckreduced(FFF))\n\njulia> lightspeed(FFF) # fur⋅ftn⁻¹\n$(lightspeed(FFF))\n\njulia> permeability(FFF) # fir⋅fur²⋅Inf⁻²\n$(permeability(FFF))\n\njulia> electronmass(FFF) # fir\n$(electronmass(FFF))\n```\n\"\"\" FFF\n\n@doc \"\"\"\n Kennelly::UnitSystem{Rᵤ*mₑ/μₑᵤ/0.001,ħ,𝘤,1e-7,mₑ,4π}\n\nKennelly ? variant `UnitSystem` of the standard `Metric` units ???\n\n```Julia\njulia> boltzmann(Kennelly) # J⋅K⁻¹\n$(boltzmann(Kennelly))\n\njulia> planckreduced(Kennelly) # J⋅s⋅rad⁻¹\n$(planckreduced(Kennelly))\n\njulia> lightspeed(Kennelly) # m⋅s⁻¹\n$(lightspeed(Kennelly))\n\njulia> permeability(Kennelly) # H⋅m⁻¹\n$(permeability(Kennelly))\n\njulia> electronmass(Kennelly) # kg\n$(electronmass(Kennelly))\n\njulia> rationalization(Kennelly)\n$(rationalization(Kennelly))\n```\n\"\"\" Kennelly\n\n# natural unit system docs\n\ntextunits(U,S) = \"\"\"\n```Julia\njulia> boltzmann($S)\n$(boltzmann(U))\n\njulia> planckreduced($S)\n$(planckreduced(U))\n\njulia> lightspeed($S)\n$(lightspeed(U))\n\njulia> permeability($S)\n$(permeability(U))\n\njulia> electronmass($S)\n$(electronmass(U))\n```\n\"\"\"\n\n@doc \"\"\"\n Planck::UnitSystem{1,1,1,1,√(4π*αG)}\n\nPlanck `UnitSystem` with the `electronmass` value `√(4π*αG)` using gravitational coupling.\n\n$(textunits(Planck,:Planck))\n\"\"\" Planck\n\n@doc \"\"\"\n PlanckGauss::UnitSystem{1,1,1,4π,√αG}\n\nPlanck (Gauss) `UnitSystem` with `permeability` of `4π` and `electronmass` coupling `√αG`.\n\n$(textunits(PlanckGauss,:PlanckGauss))\n\nThe well known `PlanckGauss` values for `length`, `time`, `mass`, and `temperature` are:\n```Julia\njulia> length(PlanckGauss,Metric) # ℓP\n$(length(PlanckGauss,Metric))\n\njulia> time(PlanckGauss,Metric) # tP\n$(time(PlanckGauss,Metric))\n\njulia> mass(PlanckGauss,Metric) # mP\n$(mass(PlanckGauss,Metric))\n\njulia> temperature(PlanckGauss,Metric) # TP\n$(temperature(PlanckGauss,Metric))\n```\n\"\"\" PlanckGauss\n\n@doc \"\"\"\n Stoney::UnitSystem{1,αinv,1,4π,√(αG*αinv)}\n\nStoney `UnitSystem` with `permeability` of `4π` and `electronmass` coupling `√(αG*αinv)`.\n\n$(textunits(Stoney,:Stoney))\n\nThe well known `Stoney` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(Stoney,Metric) # lS\n$(length(Stoney,Metric))\n\njulia> time(Stoney,Metric) # tS\n$(time(Stoney,Metric))\n\njulia> mass(Stoney,Metric) # mS\n$(mass(Stoney,Metric))\n\njulia> charge(Stoney,Metric) # qS\n$(charge(Stoney,Metric))\n```\n\"\"\" Stoney\n\n@doc \"\"\"\n Hartree::UnitSystem{1,1,αinv,4π/αinv^2,1}\n\nHartree atomic `UnitSystem` with `lightspeed` of `αinv` and `permeability` of `4π/αinv^2`.\n\n$(textunits(Hartree,:Hartree))\n\nThe well known `Hartree` atomic unit values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(Hartree,Metric) # lA\n$(length(Hartree,Metric))\n\njulia> time(Hartree,Metric) # tA\n$(time(Hartree,Metric))\n\njulia> mass(Hartree,Metric) # mA\n$(mass(Hartree,Metric))\n\njulia> charge(Hartree,Metric) # qA\n$(charge(Hartree,Metric))\n```\n\"\"\" Hartree\n\n@doc \"\"\"\n Rydberg::UnitSystem{1,1,2αinv,π/αinv^2,1/2}\n\nRydberg `UnitSystem` with `lightspeed` of `2αinv` and `permeability` of `π/αinv^2`.\n\n$(textunits(Rydberg,:Rydberg))\n\"\"\" Rydberg\n\n@doc \"\"\"\n Schrodinger::UnitSystem{1,1,αinv,4π/αinv^2,√(αG*αinv)}\n\nSchrodinger `UnitSystem` with `permeability` of `4π/αinv^2` and `electronmass` of `√(αG*αinv)`.\n\n$(textunits(Schrodinger,:Schrodinger))\n\"\"\" Schrodinger\n\n@doc \"\"\"\n Electronic::UnitSystem{1,αinv,1,4π,1}\n\nElectronic `UnitSystem` with `planckreduced` of `αinv` and `permeability` of `4π`.\n\n$(textunits(Electronic,:Electronic))\n\"\"\" Electronic\n\n@doc \"\"\"\n Natural::UnitSystem{1,1,1,1,1}\n\nNatural `UnitSystem` with all primary constants having unit value.\n\n$(textunits(Natural,:Natural))\n\nThe well known `Natural` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(Natural,Metric)\n$(length(Natural,Metric))\n\njulia> time(Natural,Metric)\n$(time(Natural,Metric))\n\njulia> mass(Natural,Metric)\n$(mass(Natural,Metric))\n\njulia> charge(Natural,Metric)\n$(charge(Natural,Metric))\n```\n\"\"\" Natural\n\n@doc \"\"\"\n NaturalGauss::UnitSystem{1,1,1,4π,1}\n\nNatural (Gauss) `UnitSystem` with the Gaussian `permeability` value of `4π`.\n\n$(textunits(NaturalGauss,:NaturalGauss))\n\"\"\" NaturalGauss\n\n@doc \"\"\"\n QCD::UnitSystem{1,1,1,1,1/μₚₑ}\n\nQunatum chromodynamics `UnitSystem` with `electronmass` of `1/μₚₑ` or `1/$μₚₑ`.\n\n$(textunits(QCD,:QCD))\n\nThe well known `QCD` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(QCD,Metric) # lQCD\n$(length(QCD,Metric))\n\njulia> time(QCD,Metric) # tQCD\n$(time(QCD,Metric))\n\njulia> mass(QCD,Metric) # mQCD\n$(mass(QCD,Metric))\n\njulia> charge(QCD,Metric)\n$(charge(QCD,Metric))\n```\n\"\"\" QCD\n\n@doc \"\"\"\n QCDGauss::UnitSystem{1,1,1,4π,1/μₚₑ}\n\nQunatum chromodynamics (Gauss) `UnitSystem` with `electronmass` of `1/μₚₑ`.\n\n$(textunits(QCDGauss,:QCDGauss))\n\nThe well known `QCDGauss` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(QCDGauss,Metric) # lQCD\n$(length(QCDGauss,Metric))\n\njulia> time(QCDGauss,Metric) # tQCD\n$(time(QCDGauss,Metric))\n\njulia> mass(QCDGauss,Metric) # mQCD\n$(mass(QCDGauss,Metric))\n\njulia> charge(QCDGauss,Metric)\n$(charge(QCDGauss,Metric))\n```\n\"\"\" QCDGauss\n\n@doc \"\"\"\n QCDoriginal::UnitSystem{1,1,1,4π/αinv,1/μₚₑ}\n\nQunatum chromodynamics (original) `UnitSystem` with `permeability` of `4π/αinv`.\n\n$(textunits(QCDoriginal,:QCDoriginal))\n\nThe well known `QCDoriginal` values for `length`, `time`, `mass`, and `charge` are:\n```Julia\njulia> length(QCDoriginal,Metric) # lQCD\n$(length(QCDoriginal,Metric))\n\njulia> time(QCDoriginal,Metric) # tQCD\n$(time(QCDoriginal,Metric))\n\njulia> mass(QCDoriginal,Metric) # mQCD\n$(mass(QCDoriginal,Metric))\n\njulia> charge(QCDoriginal,Metric)\n$(charge(QCDoriginal,Metric))\n```\n\"\"\" QCDoriginal\n", "meta": {"hexsha": "28eb503e4823ba646ec50f4473831fe14d0d0b43", "size": 15375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems.jl", "max_stars_repo_name": "chakravala/UnitSystems.jl", "max_stars_repo_head_hexsha": "2685298452f7efc269262b67d9b66ef623637023", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-12-17T20:32:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:04:14.000Z", "max_issues_repo_path": "src/systems.jl", "max_issues_repo_name": "chakravala/UnitSystems.jl", "max_issues_repo_head_hexsha": "2685298452f7efc269262b67d9b66ef623637023", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/systems.jl", "max_forks_repo_name": "chakravala/UnitSystems.jl", "max_forks_repo_head_hexsha": "2685298452f7efc269262b67d9b66ef623637023", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-12T13:49:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T13:49:54.000Z", "avg_line_length": 23.7635239567, "max_line_length": 174, "alphanum_fraction": 0.7014634146, "num_tokens": 6581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1649097131204255}} {"text": "\n\"\"\"\n`module JAC.PhotoExcitationFluores` \n ... a submodel of JAC that contains all methods for computing photo-excitation-autoionization cross \n sections and rates.\n\"\"\"\nmodule PhotoExcitationFluores \n\n using Printf, ..AutoIonization, ..Basics, ..ManyElectron, ..Radial, ..PhotoEmission, ..TableStrings\n #x global JAC_counter = 0\n\n \"\"\"\n `struct PhotoExcitationFluores.Settings` \n ... defines a type for the details and parameters of computing photon-impact excitation-autoionization \n pathways |i(N)> --> |m(N)> --> |f(N-1)>.\n\n + multipoles ::Array{EmMultipole,1} ... Specifies the multipoles of the radiation field that are to be included.\n + gauges ::Array{UseGauge,1} ... Specifies the gauges to be included into the computations.\n + printBeforeComputation ::Bool ... True, if all energies and lines are printed before their evaluation.\n + selectPathways ::Bool ... True if particular pathways are selected for the computations.\n + selectedPathways ::Array{Tuple{Int64,Int64,Int64},1} ... List of list of pathways, given by tupels (inital, inmediate, final).\n \"\"\"\n struct Settings\n multipoles ::Array{EmMultipole,1}\n gauges ::Array{UseGauge,1} \n printBeforeComputation ::Bool\n selectPathways ::Bool\n selectedPathways ::Array{Tuple{Int64,Int64,Int64},1}\n end \n\n\n \"\"\"\n `PhotoExcitationFluores.Settings()` \n ... constructor for the default values of photon-impact excitation-autoionizaton settings.\n \"\"\"\n function Settings()\n Settings( Basics.EmMultipole[], UseGauge[], false, false, Tuple{Int64,Int64,Int64}[])\n end\n\n\n # `Base.show(io::IO, settings::PhotoExcitationFluores.Settings)` \n # \t ... prepares a proper printout of the variable settings::PhotoExcitationFluores.Settings. \n function Base.show(io::IO, settings::PhotoExcitationFluores.Settings) \n println(io, \"multipoles: $(settings.multipoles) \")\n println(io, \"gauges: $(settings.gauges) \")\n println(io, \"printBeforeComputation: $(settings.printBeforeComputation) \")\n println(io, \"selectPathways: $(settings.selectPathways) \")\n println(io, \"selectedPathways: $(settings.selectedPathways) \")\n end\n\n\n #==\n \"\"\"\n `struct PhotoExcitationFluores.Channel` \n ... defines a type for a photon-impact excitaton & autoionization channel that specifies \n all quantum numbers, phases and amplitudes.\n\n + excitationChannel ::PhotoEmission.Channel ... Channel that describes the photon-impact excitation process.\n + augerChannel ::AutoIonization.Channel ... Channel that describes the subsequent Auger/autoionization process.\n \"\"\"\n struct Channel\n excitationChannel ::PhotoEmission.Channel\n augerChannel ::AutoIonization.Channel\n end ==#\n\n\n \"\"\"\n `struct PhotoExcitationFluores.Pathway` ... defines a type for a photon-impact excitation pathway that may include the definition \n of different excitation and autoionization channels and their corresponding amplitudes.\n\n + initialLevel ::Level ... initial-(state) level\n + intermediateLevel ::Level ... intermediate-(state) level\n + finalLevel ::Level ... final-(state) level\n + excitEnergy ::Float64 ... photon excitation energy of this pathway\n + fluorEnergy ::Float64 ... photon fluorescence energy of this pathway\n + crossSection ::EmProperty ... total cross section of this pathway\n + hasChannels ::Bool ... Determines whether the individual excitation and fluorescence channels are defined \n in terms of their multipole, gauge as well as the amplitude, or not.\n + excitChannels ::Array{PhotoEmission.Channel,1} ... List of excitation channels of this pathway.\n + fluorChannels ::Array{PhotoEmission.Channel,1} ... List of fluorescence channels of this pathway.\n \"\"\"\n struct Pathway\n initialLevel ::Level\n intermediateLevel ::Level\n finalLevel ::Level\n excitEnergy ::Float64\n fluorEnergy ::Float64\n crossSection ::EmProperty\n hasChannels ::Bool\n excitChannels ::Array{PhotoEmission.Channel,1}\n fluorChannels ::Array{PhotoEmission.Channel,1}\n end \n\n\n \"\"\"\n `PhotoExcitationFluores.Pathway()` \n ... 'empty' constructor for an photon-impact excitation-autoionization pathway between a specified initial, \n intermediate and final level.\n \"\"\"\n function Pathway()\n Pathway(Level(), Level(), Level(), 0., 0., 0., false, PhotoExcitationFluores.Channel[] )\n end\n\n\n # `Base.show(io::IO, pathway::PhotoExcitationFluores.Pathway)` \n #\t\t ... prepares a proper printout of the variable pathway::PhotoExcitationFluores.Pathway.\n function Base.show(io::IO, pathway::PhotoExcitationFluores.Pathway) \n println(io, \"initialLevel: $(pathway.initialLevel) \")\n println(io, \"intermediateLevel: $(pathway.intermediateLevel) \")\n println(io, \"finalLevel: $(pathway.finalLevel) \")\n println(io, \"excitEnergy $(pathway.excitEnergy) \") \n println(io, \"fluorEnergy $(pathway.fluorEnergy) \")\n println(io, \"crossSection: $(pathway.crossSection) \")\n println(io, \"hasChannels: $(pathway.hasChannels) \")\n println(io, \"excitChannels: $(pathway.excitChannels) \")\n println(io, \"fluorChannels: $(pathway.fluorChannels) \")\n end\n\n\n \"\"\"\n `PhotoExcitationFluores.computeAmplitudesProperties(pathway::PhotoExcitationFluores.Pathway, grid::Radial.Grid, \n settings::PhotoExcitationFluores.Settings)` \n ... to compute all amplitudes and properties of the given line; a pathway::PhotoExcitationFluores.Pathway is \n returned for which the amplitudes and properties have now been evaluated.\n \"\"\"\n function computeAmplitudesProperties(pathway::PhotoExcitationFluores.Pathway, grid::Radial.Grid, settings::PhotoExcitationFluores.Settings)\n # Compute all excitation channels\n neweChannels = PhotoEmission.Channel[]\n for eChannel in pathway.excitChannels\n amplitude = PhotoEmission.amplitude(\"absorption\", eChannel.multipole, eChannel.gauge, pathway.excitEnergy, \n pathway.intermediateLevel, pathway.initialLevel, grid)\n push!( neweChannels, PhotoEmission.Channel( eChannel.multipole, eChannel.gauge, amplitude))\n end\n # Compute all fluorescence channels\n newfChannels = PhotoEmission.Channel[]\n for fChannel in pathway.fluorChannels\n amplitude = PhotoEmission.amplitude(\"emission\", fChannel.multipole, fChannel.gauge, pathway.fluorEnergy, \n pathway.finalLevel, pathway.intermediateLevel, grid)\n push!( newfChannels, PhotoEmission.Channel( fChannel.multipole, fChannel.gauge, amplitude))\n end\n crossSection = EmProperty(-1., -1.)\n pathway = PhotoExcitationFluores.Pathway( pathway.initialLevel, pathway.intermediateLevel, pathway.finalLevel, pathway.excitEnergy, \n pathway.fluorEnergy, crossSection, true, neweChannels, newfChannels)\n return( pathway )\n end\n\n\n\n \"\"\"\n `PhotoExcitationFluores.computePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, \n grid::Radial.Grid, settings::PhotoExcitationFluores.Settings; output=true)` \n ... to compute the photo-excitation-fluorescence amplitudes and all properties as requested by the given settings. A list of\n lines::Array{PhotoExcitationFluores.Lines} is returned.\n \"\"\"\n function computePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, grid::Radial.Grid, \n settings::PhotoExcitationFluores.Settings; output=true)\n println(\"\")\n printstyled(\"PhotoExcitationFluores.computePathways(): The computation of photo-excitation-fluorescence amplitudes starts now ... \\n\", color=:light_green)\n printstyled(\"-------------------------------------------------------------------------------------------------------------------- \\n\", color=:light_green)\n println(\"\")\n pathways = PhotoExcitationFluores.determinePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, settings)\n # Display all selected pathways before the computations start\n if settings.printBeforeComputation PhotoExcitationFluores.displayPathways(pathways) end\n # Calculate all amplitudes and requested properties\n newPathways = PhotoExcitationFluores.Pathway[]\n ##x println(\"computePathways: NO-pathwayS = $(length(pathways)) \")\n for pathway in pathways\n ##x println(\"computePathways: pathway = $pathway \")\n newPathway = PhotoExcitationFluores.computeAmplitudesProperties(pathway, grid, settings) \n push!( newPathways, newPathway)\n end\n # Print all results to screen\n PhotoExcitationFluores.displayResults(stdout, pathways, settings)\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary PhotoExcitationFluores.displayResults(iostream, pathways, settings) end\n #\n if output return( pathways )\n else return( nothing )\n end\n end\n\n\n \"\"\"\n `PhotoExcitationFluores.determinePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, \n settings::PhotoExcitationFluores.Settings)` \n ... to determine a list of dielectronic-recombination pathways between the levels from the given initial-, intermediate- and \n final-state multiplets and by taking into account the particular selections and settings for this computation; \n an Array{PhotoExcitationFluores.Pathway,1} is returned. Apart from the level specification, all physical properties are \n set to zero during the initialization process. \n \"\"\"\n function determinePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, \n settings::PhotoExcitationFluores.Settings)\n if settings.selectPathways selectPathways = true; \n selectedPathways = Basics.determineSelectedPathways(settings.selectedPathways, initialMultiplet, intermediateMultiplet, finalMultiplet)\n else selectPathways = false\n end\n \n pathways = PhotoExcitationFluores.Pathway[]\n for i = 1:length(initialMultiplet.levels)\n for n = 1:length(intermediateMultiplet.levels)\n for f = 1:length(finalMultiplet.levels)\n if selectPathways && !((i,n,f) in selectedPathways ) continue end\n eEnergy = intermediateMultiplet.levels[n].energy - initialMultiplet.levels[i].energy\n fEnergy = intermediateMultiplet.levels[n].energy - finalMultiplet.levels[f].energy\n if eEnergy < 0. || fEnergy < 0. continue end\n\n rSettings = PhotoEmission.Settings( settings.multipoles, settings.gauges, false, false, false, Tuple{Int64,Int64}[], 0., 0., 0.)\n eChannels = PhotoEmission.determineChannels(intermediateMultiplet.levels[n], initialMultiplet.levels[i], rSettings) \n fChannels = PhotoEmission.determineChannels(finalMultiplet.levels[f], intermediateMultiplet.levels[n], rSettings) \n push!( pathways, PhotoExcitationFluores.Pathway(initialMultiplet.levels[i], intermediateMultiplet.levels[i], finalMultiplet.levels[f], \n eEnergy, fEnergy, EmProperty(0., 0.), true, eChannels, fChannels) )\n end\n end\n end\n return( pathways )\n end\n\n\n \"\"\"\n `PhotoExcitationFluores.displayResults(stream::IO, pathways::Array{PhotoExcitationFluores.Pathway,1}, \n settings::PhotoExcitationFluores.Settings)` \n ... to list all results, energies, cross sections, etc. of the selected lines. A neat table is printed but nothing \n is returned otherwise.\n \"\"\"\n function displayResults(stream::IO, pathways::Array{PhotoExcitationFluores.Pathway,1}, settings::PhotoExcitationFluores.Settings)\n println(stream, \" \")\n println(stream, \" Partial excitation & fluorescence cross sections:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(150))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(23, \"Levels\"; na=2); sb = sb * TableStrings.center(23, \"i -- e -- f\"; na=2); \n sa = sa * TableStrings.center(23, \"J^P symmetries\"; na=0); sb = sb * TableStrings.center(23, \"i -- e -- f\"; na=2);\n sa = sa * TableStrings.center(30, \"Energies \" * TableStrings.inUnits(\"energy\"); na=4); \n sb = sb * TableStrings.center(30, \"r--i r--f \"; na=4)\n sa = sa * TableStrings.center(30, \"Multipoles\"; na=4); \n sb = sb * TableStrings.center(38, \"i--r r--f \"; na=4)\n sa = sa * TableStrings.center(36, \"Cou -- cross sections -- Bab\"; na=2)\n sb = sb * TableStrings.center(36, TableStrings.inUnits(\"cross section\") * \" \" * \n TableStrings.inUnits(\"cross section\"); na=3)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(150)) \n # \n for pathway in pathways\n sa = \" \"; isym = LevelSymmetry( pathway.initialLevel.J, pathway.initialLevel.parity)\n msym = LevelSymmetry( pathway.intermediateLevel.J, pathway.intermediateLevel.parity)\n fsym = LevelSymmetry( pathway.finalLevel.J, pathway.finalLevel.parity)\n sa = sa * TableStrings.center(23, TableStrings.levels_imf(pathway.initialLevel.index, pathway.intermediateLevel.index, \n pathway.finalLevel.index); na=3)\n sa = sa * TableStrings.center(23, TableStrings.symmetries_imf(isym, msym, fsym); na=4)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", pathway.excitEnergy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", pathway.fluorEnergy)) * \" \"\n #\n multipoles = EmMultipole[]\n for ech in pathway.excitChannels\n multipoles = push!( multipoles, ech.multipole)\n end\n multipoles = unique(multipoles); mpString = TableStrings.multipoleList(multipoles) * \" \"\n sa = sa * TableStrings.flushleft(16, mpString[1:16]; na=2)\n #\n multipoles = EmMultipole[]\n for fch in pathway.fluorChannels\n multipoles = push!( multipoles, fch.multipole)\n end \n multipoles = unique(multipoles); mpString = TableStrings.multipoleList(multipoles) * \" \"\n sa = sa * TableStrings.flushleft(16, mpString[1:16]; na=2)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"cross section: from atomic\", pathway.crossSection.Coulomb)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"cross section: from atomic\", pathway.crossSection.Babushkin)) * \" \"\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(150))\n #\n return( nothing )\n end\n\nend # module\n", "meta": {"hexsha": "00c0f54a72f94c69a78da752a5e5f6cee38a2b2f", "size": 16680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-PhotoExcitationFluores.jl", "max_stars_repo_name": "Zstar95/JAC.jl", "max_stars_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-15T11:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T11:27:51.000Z", "max_issues_repo_path": "src/module-PhotoExcitationFluores.jl", "max_issues_repo_name": "Zstar95/JAC.jl", "max_issues_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-PhotoExcitationFluores.jl", "max_forks_repo_name": "Zstar95/JAC.jl", "max_forks_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.6545454545, "max_line_length": 162, "alphanum_fraction": 0.6072541966, "num_tokens": 3717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.16442907519466857}} {"text": "\"\"\"\n update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = :bgk::Symbol,\n bc = :fix::Symbol,\n ) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D1F,1},\n Z<:AbstractArray{Interface1D1F,1},\n }\n\n update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = :bgk::Symbol,\n bc = :extra::Symbol,\n ) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D2F,1},\n Z<:AbstractArray{Interface1D2F,1},\n }\n\n update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = :bgk::Symbol,\n bc = :extra::Symbol,\n isMHD = true::Bool,\n ) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D3F,1},\n Z<:AbstractArray{Interface1D3F,1},\n }\n\n update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = :bgk::Symbol,\n bc = :extra::Symbol,\n isMHD = true::Bool,\n ) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D4F,1},\n Z<:AbstractArray{Interface1D4F,1},\n }\n\n update!(\n KS::X,\n ctr::Y,\n a1face::Z,\n a2face::Z,\n dt,\n residual; # 1D / 2D\n coll = :bgk::Symbol,\n bc = :fix::Symbol,\n ) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume2D2F,2},\n Z<:AbstractArray{Interface2D2F,2},\n }\n\nUpdate flow variables over control volumes\n\n\"\"\"\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual::T; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D,1},\n Z<:AbstractArray{Interface1D,1},\n T<:AbstractFloat,\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n @inbounds Threads.@threads for i = 1:KS.pSpace.nx\n ctr[i].w, sumRes, sumAvg = step!(\n face[i].fw,\n ctr[i].w,\n ctr[i].prim,\n face[i+1].fw,\n KS.gas.a,\n KS.ps.dx[i],\n sumRes,\n sumAvg,\n )\n end\n\n residual = sqrt(sumRes * KS.pSpace.nx) / (sumAvg + 1.e-7)\n\n if bc[1] == :period\n ctr[0].w = ctr[KS.pSpace.nx].w\n ctr[0].sw = ctr[KS.pSpace.nx].sw\n ctr[KS.pSpace.nx+1].w = ctr[1].w\n ctr[KS.pSpace.nx+1].sw = ctr[1].sw\n elseif bc[1] == :extra\n ctr[0].w = ctr[1].w\n end\n\n if bc[2] == :extra\n ctr[KS.pSpace.nx+1].w = ctr[KS.pSpace.nx].w\n end\n\n return residual\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual::AbstractArray{T}; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D,1},\n Z<:AbstractArray{Interface1D,1},\n T<:AbstractFloat,\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n if ndims(sumRes) == 1\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(\n face[i].fw,\n ctr[i].w,\n ctr[i].prim,\n face[i+1].fw,\n KS.gas.γ,\n KS.ps.dx[i],\n sumRes,\n sumAvg,\n )\n end\n elseif ndims(sumRes) == 2\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(\n face[i].fw,\n ctr[i].w,\n ctr[i].prim,\n face[i+1].fw,\n KS.gas.γ,\n KS.gas.mi,\n KS.gas.ni,\n KS.gas.me,\n KS.gas.ne,\n KS.gas.Kn[1],\n KS.ps.dx[i],\n dt,\n sumRes,\n sumAvg,\n )\n end\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * KS.pSpace.nx) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(KS, ctr, face, dt, residual; bc = [bc, bc])\n else\n update_boundary!(KS, ctr, face, dt, residual; bc = bc)\n end\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D1F,1},\n Z<:AbstractArray{Interface1D1F,1},\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n phase = KS.set.space[3:end]\n if phase == \"1f1v\"\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(\n face[i].fw,\n face[i].ff,\n ctr[i].w,\n ctr[i].prim,\n ctr[i].f,\n face[i+1].fw,\n face[i+1].ff,\n KS.vSpace.u,\n KS.vSpace.weights,\n KS.gas.γ,\n KS.gas.μᵣ,\n KS.gas.ω,\n KS.gas.Pr,\n KS.ps.dx[i],\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n elseif phase == \"1f3v\"\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(\n face[i].fw,\n face[i].ff,\n ctr[i].w,\n ctr[i].prim,\n ctr[i].f,\n face[i+1].fw,\n face[i+1].ff,\n KS.vSpace.u,\n KS.vSpace.v,\n KS.vSpace.w,\n KS.vSpace.weights,\n KS.gas.γ,\n KS.gas.μᵣ,\n KS.gas.ω,\n KS.gas.Pr,\n KS.ps.dx[i],\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * KS.pSpace.nx) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = [bc, bc])\n else\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = bc)\n end\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D2F,1},\n Z<:AbstractArray{Interface1D2F,1},\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n if ndims(sumRes) == 1\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(\n face[i].fw,\n face[i].fh,\n face[i].fb,\n ctr[i].w,\n ctr[i].prim,\n ctr[i].h,\n ctr[i].b,\n face[i+1].fw,\n face[i+1].fh,\n face[i+1].fb,\n KS.vSpace.u,\n KS.vSpace.weights,\n KS.gas.K,\n KS.gas.γ,\n KS.gas.μᵣ,\n KS.gas.ω,\n KS.gas.Pr,\n KS.ps.dx[i],\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n elseif ndims(sumRes) == 2\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(\n face[i].fw,\n face[i].fh,\n face[i].fb,\n ctr[i].w,\n ctr[i].prim,\n ctr[i].h,\n ctr[i].b,\n face[i+1].fw,\n face[i+1].fh,\n face[i+1].fb,\n KS.vSpace.u,\n KS.vSpace.weights,\n KS.gas.K,\n KS.gas.γ,\n KS.gas.mi,\n KS.gas.ni,\n KS.gas.me,\n KS.gas.ne,\n KS.gas.Kn[1],\n KS.gas.Pr,\n KS.ps.dx[i],\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * KS.pSpace.nx) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = [bc, bc])\n else\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = bc)\n end\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n isMHD = true::Bool,\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D3F,1},\n Z<:AbstractArray{Interface1D3F,1},\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(KS, face[i], ctr[i], face[i+1], KS.ps.dx[i], dt, sumRes, sumAvg, coll, isMHD)\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * KS.pSpace.nx) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(\n KS,\n ctr,\n face,\n dt,\n residual;\n coll = coll,\n bc = [bc, bc],\n isMHD = isMHD,\n )\n else\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = bc, isMHD = isMHD)\n end\n\n #=\n ng = 1 - first(eachindex(KS.pSpace.x))\n if bc == :extra\n for i in 1:ng\n ctr[1-i].w .= ctr[1].w\n ctr[1-i].prim .= ctr[1].prim\n ctr[1-i].h0 .= ctr[1].h0\n ctr[1-i].h1 .= ctr[1].h1\n ctr[1-i].h2 .= ctr[1].h2\n ctr[1-i].E .= ctr[1].E\n ctr[1-i].B .= ctr[1].B\n ctr[1-i].ϕ = deepcopy(ctr[1].ϕ)\n ctr[1-i].ψ = deepcopy(ctr[1].ψ)\n ctr[1-i].lorenz .= ctr[1].lorenz\n\n ctr[KS.pSpace.nx+i].w .= ctr[KS.pSpace.nx].w\n ctr[KS.pSpace.nx+i].prim .= ctr[KS.pSpace.nx].prim\n ctr[KS.pSpace.nx+i].h0 .= ctr[KS.pSpace.nx].h0\n ctr[KS.pSpace.nx+i].h1 .= ctr[KS.pSpace.nx].h1\n ctr[KS.pSpace.nx+i].h2 .= ctr[KS.pSpace.nx].h2\n ctr[KS.pSpace.nx+i].E .= ctr[KS.pSpace.nx].E\n ctr[KS.pSpace.nx+i].B .= ctr[KS.pSpace.nx].B\n ctr[KS.pSpace.nx+i].ϕ = deepcopy(ctr[KS.pSpace.nx].ϕ)\n ctr[KS.pSpace.nx+i].ψ = deepcopy(ctr[KS.pSpace.nx].ψ)\n ctr[KS.pSpace.nx+i].lorenz .= ctr[KS.pSpace.nx].lorenz\n end\n elseif bc == :period\n for i in 1:ng\n ctr[1-i].w .= ctr[KS.pSpace.nx+1-i].w\n ctr[1-i].prim .= ctr[KS.pSpace.nx+1-i].prim\n ctr[1-i].h0 .= ctr[KS.pSpace.nx+1-i].h0\n ctr[1-i].h1 .= ctr[KS.pSpace.nx+1-i].h1\n ctr[1-i].h2 .= ctr[KS.pSpace.nx+1-i].h2\n ctr[1-i].E .= ctr[KS.pSpace.nx+1-i].E\n ctr[1-i].B .= ctr[KS.pSpace.nx+1-i].B\n ctr[1-i].ϕ = deepcopy(ctr[KS.pSpace.nx+1-i].ϕ)\n ctr[1-i].ψ = deepcopy(ctr[KS.pSpace.nx+1-i].ψ)\n ctr[1-i].lorenz .= ctr[KS.pSpace.nx+1-i].lorenz\n\n ctr[KS.pSpace.nx+i].w .= ctr[i].w\n ctr[KS.pSpace.nx+i].prim .= ctr[i].prim\n ctr[KS.pSpace.nx+i].h0 .= ctr[i].h0\n ctr[KS.pSpace.nx+i].h1 .= ctr[i].h1\n ctr[KS.pSpace.nx+i].h2 .= ctr[i].h2\n ctr[KS.pSpace.nx+i].E .= ctr[i].E\n ctr[KS.pSpace.nx+i].B .= ctr[i].B\n ctr[KS.pSpace.nx+i].ϕ = deepcopy(ctr[i].ϕ)\n ctr[KS.pSpace.nx+i].ψ = deepcopy(ctr[i].ψ)\n ctr[KS.pSpace.nx+i].lorenz .= ctr[i].lorenz\n end\n elseif bc == :balance\n @. ctr[0].w = 0.5 * (ctr[-1].w + ctr[1].w)\n @. ctr[0].prim = 0.5 * (ctr[-1].prim + ctr[1].prim)\n @. ctr[0].h0 = 0.5 * (ctr[-1].h0 + ctr[1].h0)\n @. ctr[0].h1 = 0.5 * (ctr[-1].h1 + ctr[1].h1)\n @. ctr[0].h2 = 0.5 * (ctr[-1].h2 + ctr[1].h2)\n @. ctr[0].E = 0.5 * (ctr[-1].E + ctr[1].E)\n @. ctr[0].B = 0.5 * (ctr[-1].B + ctr[1].B)\n ctr[0].ϕ = 0.5 * (ctr[-1].ϕ + ctr[1].ϕ)\n ctr[0].ψ = 0.5 * (ctr[-1].ψ + ctr[1].ψ)\n @. ctr[0].lorenz = 0.5 * (ctr[-1].lorenz + ctr[1].lorenz)\n\n @. ctr[KS.pSpace.nx+1].w = 0.5 * (ctr[KS.pSpace.nx].w + ctr[KS.pSpace.nx+2].w)\n @. ctr[KS.pSpace.nx+1].prim = 0.5 * (ctr[KS.pSpace.nx].prim + ctr[KS.pSpace.nx+2].prim)\n @. ctr[KS.pSpace.nx+1].h0 = 0.5 * (ctr[KS.pSpace.nx].h0 + ctr[KS.pSpace.nx+2].h0)\n @. ctr[KS.pSpace.nx+1].h1 = 0.5 * (ctr[KS.pSpace.nx].h1 + ctr[KS.pSpace.nx+2].h1)\n @. ctr[KS.pSpace.nx+1].h2 = 0.5 * (ctr[KS.pSpace.nx].h2 + ctr[KS.pSpace.nx+2].h2)\n @. ctr[KS.pSpace.nx+1].E = 0.5 * (ctr[KS.pSpace.nx].E + ctr[KS.pSpace.nx+2].E)\n @. ctr[KS.pSpace.nx+1].B = 0.5 * (ctr[KS.pSpace.nx].B + ctr[KS.pSpace.nx+2].B)\n ctr[KS.pSpace.nx+1].ϕ = 0.5 * (ctr[KS.pSpace.nx].ϕ + ctr[KS.pSpace.nx+2].ϕ)\n ctr[KS.pSpace.nx+1].ψ = 0.5 * (ctr[KS.pSpace.nx].ψ + ctr[KS.pSpace.nx+2].ψ)\n @. ctr[KS.pSpace.nx+1].lorenz = 0.5 * (ctr[KS.pSpace.nx].lorenz + ctr[KS.pSpace.nx+2].lorenz)\n else\n end\n =#\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n isMHD = true::Bool,\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume1D4F,1},\n Z<:AbstractArray{Interface1D4F,1},\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n @inbounds Threads.@threads for i = 2:KS.pSpace.nx-1\n step!(KS, face[i], ctr[i], face[i+1], KS.ps.dx[i], dt, sumRes, sumAvg, coll, isMHD)\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * KS.pSpace.nx) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(\n KS,\n ctr,\n face,\n dt,\n residual;\n coll = coll,\n bc = [bc, bc],\n isMHD = isMHD,\n )\n else\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = bc, isMHD = isMHD)\n end\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n a1face::Z,\n a2face::Z,\n dt,\n residual;\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume2D,2},\n Z<:AbstractArray{Interface2D,2},\n}\n\n nx, ny, dx, dy = begin\n if KS.ps isa CSpace2D\n KS.ps.nr, KS.ps.nθ, KS.ps.dr, KS.ps.darc\n else\n KS.ps.nx, KS.ps.ny, KS.ps.dx, KS.ps.dy\n end\n end\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n if ndims(sumRes) == 1\n\n @inbounds for j = 2:ny-1\n for i = 2:nx-1\n step!(\n ctr[i, j].w,\n ctr[i, j].prim,\n a1face[i, j].fw,\n a1face[i+1, j].fw,\n a2face[i, j].fw,\n a2face[i, j+1].fw,\n KS.gas.γ,\n dx[i, j] * dy[i, j],\n sumRes,\n sumAvg,\n coll,\n )\n end\n end\n\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * nx * ny) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(\n KS,\n ctr,\n a1face,\n a2face,\n dt,\n residual;\n coll = coll,\n bc = [bc, bc, bc, bc],\n )\n else\n update_boundary!(KS, ctr, a1face, a2face, dt, residual; coll = coll, bc = bc)\n end\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n a1face::Z,\n a2face::Z,\n dt,\n residual;\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume2D1F,2},\n Z<:AbstractArray{Interface2D1F,2},\n}\n\n nx, ny, dx, dy = begin\n if KS.ps isa CSpace2D\n KS.ps.nr, KS.ps.nθ, KS.ps.dr, KS.ps.darc\n else\n KS.ps.nx, KS.ps.ny, KS.ps.dx, KS.ps.dy\n end\n end\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n if ndims(sumRes) == 1\n\n @inbounds for j = 2:ny-1\n for i = 2:nx-1\n step!(\n ctr[i, j].w,\n ctr[i, j].prim,\n ctr[i, j].f,\n a1face[i, j].fw,\n a1face[i, j].ff,\n a1face[i+1, j].fw,\n a1face[i+1, j].ff,\n a2face[i, j].fw,\n a2face[i, j].ff,\n a2face[i, j+1].fw,\n a2face[i, j+1].ff,\n KS.vSpace.u,\n KS.vSpace.v,\n KS.vSpace.weights,\n KS.gas.γ,\n KS.gas.μᵣ,\n KS.gas.ω,\n KS.gas.Pr,\n dx[i, j] * dy[i, j],\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n end\n\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * nx * ny) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(\n KS,\n ctr,\n a1face,\n a2face,\n dt,\n residual;\n coll = coll,\n bc = [bc, bc, bc, bc],\n )\n else\n update_boundary!(KS, ctr, a1face, a2face, dt, residual; coll = coll, bc = bc)\n end\n\n return nothing\n\nend\n\n#--- 2d2f ---#\nfunction update!(\n KS::X,\n ctr::Y,\n a1face::Z,\n a2face::Z,\n dt,\n residual;\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolume2D2F,2},\n Z<:AbstractArray{Interface2D2F,2},\n}\n\n nx, ny, dx, dy = begin\n if KS.ps isa CSpace2D\n KS.ps.nr, KS.ps.nθ, KS.ps.dr, KS.ps.darc\n else\n KS.ps.nx, KS.ps.ny, KS.ps.dx, KS.ps.dy\n end\n end\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n if ndims(sumRes) == 1\n\n @inbounds for j = 2:ny-1\n for i = 2:nx-1\n step!(\n ctr[i, j].w,\n ctr[i, j].prim,\n ctr[i, j].h,\n ctr[i, j].b,\n a1face[i, j].fw,\n a1face[i, j].fh,\n a1face[i, j].fb,\n a1face[i+1, j].fw,\n a1face[i+1, j].fh,\n a1face[i+1, j].fb,\n a2face[i, j].fw,\n a2face[i, j].fh,\n a2face[i, j].fb,\n a2face[i, j+1].fw,\n a2face[i, j+1].fh,\n a2face[i, j+1].fb,\n KS.vSpace.u,\n KS.vSpace.v,\n KS.vSpace.weights,\n KS.gas.K,\n KS.gas.γ,\n KS.gas.μᵣ,\n KS.gas.ω,\n KS.gas.Pr,\n dx[i, j] * dy[i, j],\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n end\n\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * nx * ny) / (sumAvg[i] + 1.e-7)\n end\n\n if bc isa Symbol\n update_boundary!(\n KS,\n ctr,\n a1face,\n a2face,\n dt,\n residual;\n coll = coll,\n bc = [bc, bc, bc, bc],\n )\n else\n update_boundary!(KS, ctr, a1face, a2face, dt, residual; coll = coll, bc = bc)\n end\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolumeUS,1},\n Z<:AbstractArray{Interface2D,1},\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n @inbounds Threads.@threads for i in eachindex(ctr)\n if KS.ps.cellType[i] in (0, 2)\n dirc = [sign(dot(ctr[i].n[j], face[KS.ps.cellFaces[i, j]].n)) for j = 1:3]\n\n step!(\n ctr[i].w,\n ctr[i].prim,\n face[KS.ps.cellFaces[i, 1]].fw,\n face[KS.ps.cellFaces[i, 2]].fw,\n face[KS.ps.cellFaces[i, 3]].fw,\n KS.gas.γ,\n KS.pSpace.cellArea[i],\n dirc,\n sumRes,\n sumAvg,\n )\n end\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * size(KS.ps.cellid, 1)) / (sumAvg[i] + 1.e-7)\n end\n\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = bc)\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolumeUS1F,1},\n Z<:AbstractArray{Interface2D1F,1},\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n @inbounds Threads.@threads for i in eachindex(ctr)\n if KS.ps.cellType[i] in (0, 2)\n dirc = [sign(dot(ctr[i].n[j], face[KS.ps.cellFaces[i, j]].n)) for j = 1:3]\n\n step!(\n ctr[i].w,\n ctr[i].prim,\n ctr[i].f,\n face[KS.ps.cellFaces[i, 1]].fw,\n face[KS.ps.cellFaces[i, 1]].ff,\n face[KS.ps.cellFaces[i, 2]].fw,\n face[KS.ps.cellFaces[i, 2]].ff,\n face[KS.ps.cellFaces[i, 3]].fw,\n face[KS.ps.cellFaces[i, 3]].ff,\n KS.vSpace.u,\n KS.vSpace.v,\n KS.vSpace.weights,\n KS.gas.K,\n KS.gas.γ,\n KS.gas.μᵣ,\n KS.gas.ω,\n KS.gas.Pr,\n KS.pSpace.cellArea[i],\n dirc,\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * size(KS.ps.cellid, 1)) / (sumAvg[i] + 1.e-7)\n end\n\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = bc)\n\n return nothing\n\nend\n\nfunction update!(\n KS::X,\n ctr::Y,\n face::Z,\n dt,\n residual; # 1D / 2D\n coll = symbolize(KS.set.collision),\n bc = symbolize(KS.set.boundary),\n) where {\n X<:AbstractSolverSet,\n Y<:AbstractArray{ControlVolumeUS2F,1},\n Z<:AbstractArray{Interface2D2F,1},\n}\n\n sumRes = zero(ctr[1].w)\n sumAvg = zero(ctr[1].w)\n\n @inbounds Threads.@threads for i in eachindex(ctr)\n if KS.ps.cellType[i] in (0, 2)\n dirc = [sign(dot(ctr[i].n[j], face[KS.ps.cellFaces[i, j]].n)) for j = 1:3]\n\n step!(\n ctr[i].w,\n ctr[i].prim,\n ctr[i].h,\n ctr[i].b,\n face[KS.ps.cellFaces[i, 1]].fw,\n face[KS.ps.cellFaces[i, 1]].fh,\n face[KS.ps.cellFaces[i, 1]].fb,\n face[KS.ps.cellFaces[i, 2]].fw,\n face[KS.ps.cellFaces[i, 2]].fh,\n face[KS.ps.cellFaces[i, 2]].fb,\n face[KS.ps.cellFaces[i, 3]].fw,\n face[KS.ps.cellFaces[i, 3]].fh,\n face[KS.ps.cellFaces[i, 3]].fb,\n KS.vSpace.u,\n KS.vSpace.v,\n KS.vSpace.weights,\n KS.gas.K,\n KS.gas.γ,\n KS.gas.μᵣ,\n KS.gas.ω,\n KS.gas.Pr,\n KS.pSpace.cellArea[i],\n dirc,\n dt,\n sumRes,\n sumAvg,\n coll,\n )\n end\n end\n\n for i in eachindex(residual)\n residual[i] = sqrt(sumRes[i] * size(KS.ps.cellid, 1)) / (sumAvg[i] + 1.e-7)\n end\n\n update_boundary!(KS, ctr, face, dt, residual; coll = coll, bc = bc)\n\n return nothing\n\nend\n", "meta": {"hexsha": "e2577ddefae0bb92eeba6b664ab24c56ee16f4ba", "size": 24281, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Solver/solver_update.jl", "max_stars_repo_name": "vavrines/KitBase.jl", "max_stars_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-12-02T13:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T00:49:20.000Z", "max_issues_repo_path": "src/Solver/solver_update.jl", "max_issues_repo_name": "vavrines/KitBase.jl", "max_issues_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2020-12-02T21:20:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T00:35:04.000Z", "max_forks_repo_path": "src/Solver/solver_update.jl", "max_forks_repo_name": "vavrines/KitBase.jl", "max_forks_repo_head_hexsha": "c7b835e8151828c4065691c9882e42335a237ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-07T17:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T21:13:25.000Z", "avg_line_length": 25.7760084926, "max_line_length": 101, "alphanum_fraction": 0.4398089041, "num_tokens": 7681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16416958012879473}} {"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ ac87ced2-986f-4e6c-80b2-104b25c171c2\nbegin\n\tusing CSV, JLD2, FITSIO, FileIO# , HDF5\n\tusing DataFrames #, Query\n\tusing PyCall\n\tusing PlutoUI, PlutoTeachingTools\n\teval(Meta.parse(code_for_check_type_funcs))\nend\n\n# ╔═╡ e0e60e09-3808-4d6b-a773-6ba59c02f517\nmd\"\"\"\n# Astro 528, Lab 3, Exercise 2\n# Benchmarking File I/O\n# (no Python dependance)\n\"\"\"\n\n# ╔═╡ 8c1d81ab-d215-4972-afeb-7e00bf6063c2\nmd\"\"\"\nFor many applications, its important that we be able to read input data from a file and/or to write our outputes to files so they can be reused later. Disk access is typically much slower than accessing system memory. Therefore, disk access can easily become the limiting factor for a project. In this set of exercises, you'll see examples of how to perform basic file I/O. \n\nYou'll be provided with most of the code you need, so that you can focus on comparing how much disk space and time is required by different file formats. Near the end of the lab, you'll be asked to think about when each type of file format would be a good choice for you to use in your research projects.\n\"\"\"\n\n# ╔═╡ 1607eac9-e76f-4d1f-a9ce-981ce3be9bea\nmd\"\"\"\n### Download some data\nFirst, we're going to download some data from the web. Julia has a built in `download` function that can be handy for this. It relies on your system having some utilities already installed (e.g., `curl`, `wget` or `fetch`). If you run this on a local system and run into trouble, then you can leave the cell below, and manually download the file to the data subdirectory.\n\"\"\"\n\n# ╔═╡ f27e1e8f-15eb-4754-a94c-7f37c54b871e\nbegin \n\tpath = basename(pwd())==\"test\" ? \"../data/\" : \"data/\"\n\tif !isdir(path) mkdir(path) end # make sure there's a data directory\n\turl = \"https://personal.psu.edu/~ebf11/data/kplr_dr25_inj1_plti.csv\"\n\tfilename_csv = joinpath(path,basename(url)) # extract the filename and prepend \"data/\"\n\ttime_to_download = NaN\n\tif !isfile(filename_csv) # skip downloading if file already exists\n\t time_to_download = @elapsed download(url,filename_csv)\n\tend\nend\n\n# ╔═╡ 80f02c3a-6751-48df-92ec-13f5c7d8c71e\nif !isnan(time_to_download)\n\tmd\"Downloading the file took $time_to_download seconds.\"\nend\n\n# ╔═╡ 624c9038-3008-4e78-a149-60796dacf9c0\nmd\"\"\"\nPreviously, everything you needed for an assignment was included in a GitHub repository. So why did I make you download the file?\n\nNotice the size of the file. Git is great for tracking source code, but it wasn't really designed for working with large files (especially large _binary_ files). Since we're not going to be editing it, we'll simply download it once. \n\"\"\"\n\n# ╔═╡ c808d0e1-4829-432f-b91f-968d4be20ecf\nmd\"\"\"\n(We're skipping 2a-2d, since we're avoiding using Python in this notebook.)\n\"\"\"\n\n# ╔═╡ 191ba96e-2573-4bc1-a352-46a66e0a5c4f\nmd\"\"\"\n## CSV files\nLet's say that we'd like to read/write data as [CSV files](https://en.wikipedia.org/wiki/Comma-separated_values), so that it's easy for other programs to read in. Using the CSV package, we can read a CSV file into a DataFrame (or several other tabular data structures) and write CSV files from a DataFrame with code like the following.\n\"\"\"\n\n# ╔═╡ 82a757ad-566d-4c1d-8b3d-366ffd980fb4\nbegin\n\t# Read & write a small test file so compilation time not included below\n\tn_small_df = 1024\n\tsmall_csv_filename = \"random_numbers.csv\"\n\tsmall_df = DataFrame(a=rand(n_small_df),b=rand(n_small_df) ) \n\tCSV.write(joinpath(path,small_csv_filename),small_df) \n\tsmall_df_from_csv = CSV.read(joinpath(path,small_csv_filename),DataFrame,types=Dict(:TCE_ID=>String))\nend;\n\n# ╔═╡ 32124f8a-f5cf-41d1-97a9-ce1d05145fde\nmd\"\"\"\n2d. How long do you think it will take to read 146,294 rows and 25 columns of data data stored in CSV format?\n\"\"\"\n\n# ╔═╡ 507e1516-5433-49eb-831d-32426f30895e\nresponse_2d = missing\n\n# ╔═╡ eac67cc9-754b-4f7d-add8-93900a1b5b49\ndisplay_msg_if_fail(check_type_isa(:response_2d,response_2d,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 73c06bb1-be49-46bd-b7f1-c45cc56af7b4\nmd\"\"\"\nI'm ready to benchmark reading a CSV file. $(@bind ready_read_csv CheckBox()) \n$(@bind go_read_csv Button(\"Rerun the benchmarks.\"))\n\"\"\"\n\n# ╔═╡ ebfaa677-829b-4bf9-bdbb-19f3c87dd3a4\nif ready_read_csv\n\tgo_read_csv\n\ttime_read_csv = @elapsed df_csv = CSV.read(filename_csv, DataFrame)\n\talready_benchmarked_csv_read = true\n\tmd\"It took $time_read_csv seconds to read the CSV file.\"\nend\n\n# ╔═╡ b0c3875b-ef07-4e92-a0a8-55f42b266c6b\nif already_benchmarked_csv_read\n\tready_read_csv\n\tdf = CSV.read(filename_csv,DataFrame,types=Dict(:TCE_ID=>String),missingstring=\"NA\")\nend\n\n# ╔═╡ 945f5a55-3026-4497-9ece-8af878c87788\nmd\"\"\"\n2e. How did the time required to read the data in CSV format compare to your expectation? If you were suprsised, try to explain what happened.\n\"\"\"\n\n# ╔═╡ 57397ee4-9efc-48b3-b640-d2b7a10da633\nresponse_2e = missing\n\n# ╔═╡ 8059a6a3-384a-4344-8a23-650ee0be10c2\ndisplay_msg_if_fail(check_type_isa(:response_2e,response_2e,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 64224c6b-c5a0-44f2-b2a0-7f77759cb848\nmd\"\"\"\nNow, we'll try writing the same data out to a new CSV file. \n\"\"\"\n\n# ╔═╡ f5b93929-2c59-4360-8c41-97a1324ba455\nmd\"2f. How long do you think it will take to write the same data? Once you've made your prediction, mouse over the hint box. If you were suprsised, try to explain what happened.\"\n\n# ╔═╡ 122196fa-45ca-4031-85eb-4afd4782de9e\nresponse_2f = missing\n\n# ╔═╡ e9dc1456-616b-4e4b-b209-9f6ba4c48607\ndisplay_msg_if_fail(check_type_isa(:response_2f,response_2f,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 3e550b71-4750-460b-be18-911a848a8f49\nif ready_read_csv\n\tgo_read_csv\n\tfilename_csv_out = replace(filename_csv, \".csv\" => \"_2.csv\") \n\ttime_write_csv = @elapsed CSV.write(filename_csv_out, df)\nend;\n\n# ╔═╡ f15d37a7-d962-4da0-977f-76729a3313be\nhint(md\"It took $time_write_csv seconds to write the CSV file.\")\n\n# ╔═╡ 28f195c4-4f61-4873-85d6-b4e3aaa3660f\nmd\"\"\"\n## Binary formats: HDF5/JLD2\n\nThere are numerous binary file formats that one could use. Here, we'll try using JLD2 which is a subset of the [HDF5](https://www.hdfgroup.org/solutions/hdf5/) file format. This means that when [Julia's JLD2 package](https://github.com/JuliaIO/JLD2.jl) writes jld2 files, they can be read by other programs that can read HDF5 files. However, a generic HDF5 file is not a valid JLD2 file. If you want to read a HDF5 file, then you can use Julia's [HDF5.jl package](https://github.com/JuliaIO/HDF5.jl). The [FileIO.jl](https://github.com/JuliaIO/FileIO.jl) package provides a common interface for reading and writing from multiple file formats, including these and several others.\n\nAs before, we'll call each function once using a small DataFrame, just so they get compiled before we benchmark them.\n\"\"\"\n\n# ╔═╡ 3837e439-250b-4577-b0d7-93352ec19f6e\nbegin\n\tfilename_jld2_small = replace(small_csv_filename, \".csv\" => \".jld2\") \n\t@save joinpath(path,filename_jld2_small) small_df \n\tsmall_df_from_jld2 = load(joinpath(path,filename_jld2_small), \"small_df\")\nend;\n\n# ╔═╡ df9b701f-d314-4512-b2ea-1f6ae015166c\nresponse_2g = missing\n\n# ╔═╡ 377f7527-a338-4526-bb24-9766c635e719\ndisplay_msg_if_fail(check_type_isa(:response_2g,response_2g,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 25f24754-16d4-4343-b54a-cf8ea1358ce9\nbegin \n\tsmall_jld2_filesize = filesize(joinpath(path,filename_jld2_small))/1024\n\tsmall_csv_filesize = filesize(joinpath(path,small_csv_filename))/1024\n\thint(md\"For the small random data set, the JLD2 file's size is $small_jld2_filesize KB versus $small_csv_filesize KB for the CSV file.\")\nend\n\n# ╔═╡ 8255b5a9-cbe6-4604-bedd-0e366f311096\nmd\"\"\"\nLet's check the filesizes for the JLD2 file to the CSV file. \nThe small CSV file we created is $small_csv_filesize KB. \n\n2g. How large would you guess the JLD2 file will be? Once you've made your prediction, mouse over the hint box. If you were suprised, try to explain what happened.\n\"\"\"\n\n# ╔═╡ 570fd826-23fd-46ee-bdb4-58fb0c45719a\nmd\"\"\"\nNow let's time how long it takes to save the data from CSV into a JLD2 file.\n\"\"\"\n\n# ╔═╡ 691410bb-0472-4800-a90d-29ddf947de3e\nbegin\n\tfilename_jld2 = replace(filename_csv, \".csv\" => \".jld2\") \n\twith_terminal() do \n\t\t@time @save filename_jld2 df\n\tend\nend\n\n# ╔═╡ 8cbb1c90-bd94-44b5-80b6-81d38f3e6252\nmd\"2h. How long do you think it will take to load the data from the JLD2 file? \"\n\n# ╔═╡ c3065acf-6205-455f-ba74-ca51f3f6761b\nresponse_2h = missing\n\n# ╔═╡ 9c392be9-1505-40bc-a290-68085a1c2700\ndisplay_msg_if_fail(check_type_isa(:response_2h,response_2h,[AbstractString,Markdown.MD]))\n\n# ╔═╡ d738bdcc-5f83-4dfa-a17f-e9ea23db2986\nmd\"\"\"\nNow time how long it takes to load the data from the JLD2 file.\n\"\"\"\n\n# ╔═╡ d55ce157-099c-4c1b-94db-62918f04e5fe\nmd\"\"\"\nI'm ready to benchmark reading a JLD2 file. $(@bind ready_read_jld2 CheckBox()) \n$(@bind go_read_jld2 Button(\"Rerun the benchmarks.\"))\n\"\"\"\n\n# ╔═╡ 206f464b-55fe-46aa-85b7-8f0246a0aaad\nif ready_read_jld2\n\tgo_read_jld2\n\ttime_read_jld2 = @elapsed df_jld2_read_back_in = load(filename_jld2, \"df\")\n\tmd\"It took $time_read_jld2 seconds to read the JLD2 file.\"\nend\n\n# ╔═╡ 6f72d1b2-63f6-4301-8272-bb2d6d2d049e\nmd\"\"\"\n2i. How does the time required to read and write the JLD2 file compare to the time required to read the CSV formatted files? If you were suprised, try to explain what happend.\n\"\"\"\n\n# ╔═╡ 01201c37-0b79-46b1-a001-e716f5b3ba67\nresponse_2i = missing\n\n# ╔═╡ e3d37bc1-a119-4add-a111-899ee0caea05\ndisplay_msg_if_fail(check_type_isa(:response_2i,response_2i,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 39eff7cf-6f6c-4aac-91a7-b776e0a62c45\ncsv_filesize = filesize(filename_csv) / 1024^2;\n\n# ╔═╡ 6dff3f21-fac0-42e1-910a-f969a231374f\nmd\"\"\"\nNext, we'll compare the filesizes for the JLD2 file to the CSV file. The CSV file is $csv_filesize MB. \n\n2j. How large would you guess the JLD2 file will be? Once you've made your prediction, mouse over the hint box. If you were suprised, try to explain what happened.\n\"\"\"\n\n# ╔═╡ b26b8253-e6cd-49f4-81c5-2a3c2963a37c\nresponse_2j = missing\n\n# ╔═╡ e5dc123f-1596-4311-9398-f0cfe80a5342\ndisplay_msg_if_fail(check_type_isa(:response_2j,response_2j,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 7b9d26c2-899e-45e9-b664-39d5f1adfe3f\nbegin \n\tjld2_filesize = filesize(filename_jld2) / 1024^2;\n\thint(md\"The JLD2 file size is $jld2_filesize MB.\")\nend\n\n# ╔═╡ fc01d57f-c90b-4231-96be-ddd48656d55e\nmd\"\"\"\n## Flexible Format: FITS\n\nAstronomers often use the [FITS file format](https://en.wikipedia.org/wiki/FITS). Like [HDF\n5](https://www.hdfgroup.org/solutions/hdf5/), it's a very flexible (e.g., it can store both text and binary data) and thus complicated file\n format. \nTherefore, most languages call a common [FITSIO library written in C](https://heasarc.gsfc.nasa.gov/fitsio/), rather than implementing code themselves. Indeed, that's what [Julia's FITSIO.jl package](https://github.com/JuliaAstro/FITSIO.jl) does.\n\nUnfortunately, the FITSIO package isn't as polished as the others. It expects a `Dict` rather than a `DataFrame`, and it can't handle missing values. So I've provided some helper functions at the bottom of the notebook. Also, FITS files have complicated headers, so I'll provide a function to read all the tabular data from a simple FITS file. As usual, we'll use each function once, so that Julia compiles them before we start timing.\n\"\"\"\n\n# ╔═╡ 3b232365-f2fe-4edb-a39f-3e37c8cbb666\nmd\"Now we can time how long it takes to write and read the data as FITS files.\"\n\n# ╔═╡ 568862b3-6fce-426a-a9e2-e558adf3932a\nmd\"\"\"\nI'm ready to benchmark reading a FITS file. $(@bind ready_read_fits CheckBox()) \n$(@bind go_read_fits Button(\"Rerun the benchmarks.\"))\n\"\"\"\n\n# ╔═╡ ae79ee89-d788-4612-8b1d-fc22d85c7744\nmd\"2k. How do the read/write times and file sizes for FITS compare to CSV and JLD2?\"\n\n# ╔═╡ 3745c237-ba48-4f2c-959e-441484244764\nresponse_2k = missing\n\n# ╔═╡ 6d061411-6f19-4119-aefb-cc380198b0ce\ndisplay_msg_if_fail(check_type_isa(:response_2k,response_2k,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 8def87d2-f10b-4a82-b353-a6477eeead9b\nmd\"## Implications for your project\"\n\n# ╔═╡ c74b3105-f480-4688-b85f-3e7dff70da3b\nmd\"\"\"\n2l. How does the time required to read any of the above formats compare to the time required to download the files ($time_to_download seconds)? \nWill your project need to transfer large files over the internet? If so, very roughly how large do you expect they will be? \n\"\"\"\n\n# ╔═╡ 55438c09-1d94-4ff7-90c3-0cc6064a091e\nresponse_2l = missing\n\n# ╔═╡ bcc796c9-db11-4a09-a5f9-215127ac0938\ndisplay_msg_if_fail(check_type_isa(:response_2l,response_2l,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 92b2ecdd-9491-4f16-8cb9-bacbcf180280\nmd\"\"\"\n2m. Will your project need to read in any input files? If so, what format are they in? \n\nI assume everyone's project code will write at least some output files? Very roughly, how large do you expect that they'll be? What format(s) would be a good choice for your project?\"\"\"\n\n# ╔═╡ 83216915-cdcf-4f0f-829f-a5ff4c4b8da0\nresponse_2m = missing\n\n# ╔═╡ 452872f9-2009-4733-b2d3-28f262ae19b7\ndisplay_msg_if_fail(check_type_isa(:response_2m,response_2m,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 29415ddc-e002-4f56-a169-95f7b1c36be9\nmd\"# Helper Functions\"\n\n# ╔═╡ fb23d6c6-b812-4fe1-b224-0014bedbd43f\nChooseDisplayMode()\n\n# ╔═╡ 1e53aa10-dff6-40d5-89e2-da194ffc2052\nTableOfContents()\n\n# ╔═╡ 14cca8ce-cc61-4fae-b871-21c3fd23d0ea\n\"Convert a DataFrame to a Dict\"\nfunction convert_dataframe_to_dict_remove_missing(df::DataFrame)\n#=\n\t\"Convert a DataFrame to a Dict, replacing missing values with 0 or an empty string.\"\n\td = Dict(map(n->\"$n\"=> # create a dictionary\n ( any(ismissing.(df[!,n])) ? # if column contains a missing\n map(x-> !ismissing(x) ? # search for missings\n x : # leave non-missing values alone\n ( (eltype(df[!,n]) <: Number) ? zero(eltype(n)) : \"\")\n , df[!,n]) # but replace missing with 0 or \"\"\n : df[!,n] ), # if nothing is missing, just use column as is\n names(df) )) \n=#\n\td = Dict(zip(names(df),collect.(eachcol(df))))\nend\n\n# ╔═╡ 28fc8de4-749b-4093-b32f-c398f8d27d3d\n\"Write a DataFrame to a FITS file, replacing missing values with 0 or an empty string.\"\nfunction write_dataframe_as_fits(filename::String, df::DataFrame)\n try \n dict = convert_dataframe_to_dict_remove_missing(df) \n fits_file = FITS(filename,\"w\")\n write(fits_file, dict )\n close(fits_file)\n catch\n @warn(\"There was a problem writing a dataframe to \" * filename * \".\")\n end\nend\n\n\n# ╔═╡ 57b422e5-0ad0-4674-bdd3-a8358bc7aaeb\n\n\"Read the columns of the first table from a FITS file into a Dict\"\nfunction read_fits_tables(filename::String)\n dict = Dict{String,Any}()\n fits_file = FITS(filename,\"r\")\n # fits_file[1] is image data, we're interested in the table\n @assert length(fits_file) >= 2\n header = read_header(fits_file[2])\n for i in 1:length(header)\n c = get_comment(header,i)\n if !occursin(\"label for field\",c)\n continue\n end\n h = header[i]\n @assert typeof(h) == String\n try \n dict[h] = read(fits_file[2],h)\n catch\n @warn \"# Problem reading table column \" * h * \".\"\n end\n end\n close(fits_file)\n return dict\nend\n\n\n# ╔═╡ e05f16d6-eb50-49a9-bf14-95d63c9da7ff\nbegin\n\tfilename_fits_small = replace(small_csv_filename, \".csv\" => \".fits\") \n\twrite_dataframe_as_fits(joinpath(path,filename_fits_small),small_df)\n\tread_fits_tables(joinpath(path,filename_fits_small))\nend;\n\n# ╔═╡ 1992595f-9976-4b18-bf9c-df8a73d30dc8\nbegin\n\tfilename_fits_small # make sure have already compiled functions\n\tfilename_fits = replace(filename_csv, \".csv\" => \".fits\") \n\twith_terminal() do \n\t\t@time write_dataframe_as_fits(filename_fits,df)\n\tend\nend\n\n# ╔═╡ 90d5244e-17be-4601-b922-8c254f1248bf\nbegin\n\tfits_filesize = filesize(filename_fits) /1024^2\n\thint(md\"The FITS file size is $fits_filesize MB versus $jld2_filesize MB for the JLD2 and $csv_filesize MB for the CSV.\")\nend\n\n# ╔═╡ 52f9edd0-79b0-4a9a-9930-3a05d3aa2447\nif ready_read_fits\n\tgo_read_fits\n\ttime_read_fits = @elapsed read_fits_tables(filename_fits)\n\tmd\"It took $time_read_fits seconds to read the FITS file.\"\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nFITSIO = \"525bcba6-941b-5504-bd06-fd0dc1a4d2eb\"\nFileIO = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nJLD2 = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nPlutoTeachingTools = \"661c6b06-c737-4d37-b85c-46df65de6f69\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPyCall = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\n\n[compat]\nCSV = \"~0.8.5\"\nDataFrames = \"~1.2.2\"\nFITSIO = \"~0.16.7\"\nFileIO = \"~1.10.1\"\nJLD2 = \"~0.4.13\"\nPlutoTeachingTools = \"~0.1.3\"\nPlutoUI = \"~0.7.9\"\nPyCall = \"~1.92.3\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[CFITSIO]]\ndeps = [\"CFITSIO_jll\"]\ngit-tree-sha1 = \"c860f5545064216f86aa3365ec186ce7ced6a935\"\nuuid = \"3b1b4be9-1499-4b22-8d78-7db3344d1961\"\nversion = \"1.3.0\"\n\n[[CFITSIO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"LibCURL_jll\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"2fabb5fc48d185d104ca7ed7444b475705993447\"\nuuid = \"b3e40c51-02ae-5482-8a39-3ace5868dcf4\"\nversion = \"3.49.1+0\"\n\n[[CSV]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"PooledArrays\", \"SentinelArrays\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"b83aa3f513be680454437a0eee21001607e5d983\"\nuuid = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nversion = \"0.8.5\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"727e463cfebd0c7b999bbf3e9e7e16f254b94193\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.34.0\"\n\n[[Conda]]\ndeps = [\"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"299304989a5e6473d985212c28928899c74e9421\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.5.2\"\n\n[[Crayons]]\ngit-tree-sha1 = \"3f71217b538d7aaee0b69ab47d9b7724ca8afa0d\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.0.4\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"d785f42445b63fc86caa08bb9a9351008be9b765\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.2.2\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[FITSIO]]\ndeps = [\"CFITSIO\", \"Printf\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"85b66005c9d16d3d27c9d06fd3be5e25074128da\"\nuuid = \"525bcba6-941b-5504-bd06-fd0dc1a4d2eb\"\nversion = \"0.16.7\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"256d8e6188f3f1ebfa1a5d17e072a0efafa8c5bf\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.10.1\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InvertedIndices]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"15732c475062348b0165684ffe28e85ea8396afc\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.0.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLD2]]\ndeps = [\"DataStructures\", \"FileIO\", \"MacroTools\", \"Mmap\", \"Pkg\", \"Printf\", \"Reexport\", \"TranscodingStreams\", \"UUIDs\"]\ngit-tree-sha1 = \"59ee430ac5dc87bc3eec833cc2a37853425750b4\"\nuuid = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nversion = \"0.4.13\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"0fb723cd8c45858c22169b2e42269e53271a6df7\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.7\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"2ca267b08821e86c5ef4376cffed98a46c2cb205\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"bfd7d8c7fd87f04543810d9cbd3995972236ba1b\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.2\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlutoTeachingTools]]\ndeps = [\"LaTeXStrings\", \"Markdown\", \"PlutoUI\", \"Random\"]\ngit-tree-sha1 = \"e2b63ee022e0b20f43fcd15cda3a9047f449e3b4\"\nuuid = \"661c6b06-c737-4d37-b85c-46df65de6f69\"\nversion = \"0.1.4\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"cde4ce9d6f33219465b55162811d8de8139c0414\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.2.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"0d1245a357cc61c8cd61934c07447aa569ff22e6\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.1.0\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"169bb8ea6b1b143c5cf57df6d34d022a7b60c6db\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.92.3\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"54f37736d8934a12a200edea2f9206b03bdf3159\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.7\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"d0c690d37c73aeb5ca063056283fde5585a41710\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[VersionParsing]]\ngit-tree-sha1 = \"80229be1f670524750d905f8fc8148e5a8c4537f\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.2.0\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─e0e60e09-3808-4d6b-a773-6ba59c02f517\n# ╟─8c1d81ab-d215-4972-afeb-7e00bf6063c2\n# ╟─1607eac9-e76f-4d1f-a9ce-981ce3be9bea\n# ╠═f27e1e8f-15eb-4754-a94c-7f37c54b871e\n# ╠═80f02c3a-6751-48df-92ec-13f5c7d8c71e\n# ╟─624c9038-3008-4e78-a149-60796dacf9c0\n# ╟─c808d0e1-4829-432f-b91f-968d4be20ecf\n# ╟─191ba96e-2573-4bc1-a352-46a66e0a5c4f\n# ╠═82a757ad-566d-4c1d-8b3d-366ffd980fb4\n# ╟─32124f8a-f5cf-41d1-97a9-ce1d05145fde\n# ╠═507e1516-5433-49eb-831d-32426f30895e\n# ╟─eac67cc9-754b-4f7d-add8-93900a1b5b49\n# ╟─73c06bb1-be49-46bd-b7f1-c45cc56af7b4\n# ╟─ebfaa677-829b-4bf9-bdbb-19f3c87dd3a4\n# ╠═b0c3875b-ef07-4e92-a0a8-55f42b266c6b\n# ╟─945f5a55-3026-4497-9ece-8af878c87788\n# ╠═57397ee4-9efc-48b3-b640-d2b7a10da633\n# ╟─8059a6a3-384a-4344-8a23-650ee0be10c2\n# ╟─64224c6b-c5a0-44f2-b2a0-7f77759cb848\n# ╟─f5b93929-2c59-4360-8c41-97a1324ba455\n# ╠═122196fa-45ca-4031-85eb-4afd4782de9e\n# ╟─e9dc1456-616b-4e4b-b209-9f6ba4c48607\n# ╟─3e550b71-4750-460b-be18-911a848a8f49\n# ╟─f15d37a7-d962-4da0-977f-76729a3313be\n# ╟─28f195c4-4f61-4873-85d6-b4e3aaa3660f\n# ╠═3837e439-250b-4577-b0d7-93352ec19f6e\n# ╠═8255b5a9-cbe6-4604-bedd-0e366f311096\n# ╠═df9b701f-d314-4512-b2ea-1f6ae015166c\n# ╟─377f7527-a338-4526-bb24-9766c635e719\n# ╠═25f24754-16d4-4343-b54a-cf8ea1358ce9\n# ╟─570fd826-23fd-46ee-bdb4-58fb0c45719a\n# ╠═691410bb-0472-4800-a90d-29ddf947de3e\n# ╟─8cbb1c90-bd94-44b5-80b6-81d38f3e6252\n# ╠═c3065acf-6205-455f-ba74-ca51f3f6761b\n# ╟─9c392be9-1505-40bc-a290-68085a1c2700\n# ╟─d738bdcc-5f83-4dfa-a17f-e9ea23db2986\n# ╟─d55ce157-099c-4c1b-94db-62918f04e5fe\n# ╟─206f464b-55fe-46aa-85b7-8f0246a0aaad\n# ╟─6f72d1b2-63f6-4301-8272-bb2d6d2d049e\n# ╠═01201c37-0b79-46b1-a001-e716f5b3ba67\n# ╟─e3d37bc1-a119-4add-a111-899ee0caea05\n# ╟─39eff7cf-6f6c-4aac-91a7-b776e0a62c45\n# ╟─6dff3f21-fac0-42e1-910a-f969a231374f\n# ╠═b26b8253-e6cd-49f4-81c5-2a3c2963a37c\n# ╟─e5dc123f-1596-4311-9398-f0cfe80a5342\n# ╟─7b9d26c2-899e-45e9-b664-39d5f1adfe3f\n# ╟─fc01d57f-c90b-4231-96be-ddd48656d55e\n# ╠═e05f16d6-eb50-49a9-bf14-95d63c9da7ff\n# ╟─3b232365-f2fe-4edb-a39f-3e37c8cbb666\n# ╠═1992595f-9976-4b18-bf9c-df8a73d30dc8\n# ╟─568862b3-6fce-426a-a9e2-e558adf3932a\n# ╟─52f9edd0-79b0-4a9a-9930-3a05d3aa2447\n# ╟─90d5244e-17be-4601-b922-8c254f1248bf\n# ╟─ae79ee89-d788-4612-8b1d-fc22d85c7744\n# ╠═3745c237-ba48-4f2c-959e-441484244764\n# ╟─6d061411-6f19-4119-aefb-cc380198b0ce\n# ╟─8def87d2-f10b-4a82-b353-a6477eeead9b\n# ╟─c74b3105-f480-4688-b85f-3e7dff70da3b\n# ╠═55438c09-1d94-4ff7-90c3-0cc6064a091e\n# ╟─bcc796c9-db11-4a09-a5f9-215127ac0938\n# ╟─92b2ecdd-9491-4f16-8cb9-bacbcf180280\n# ╠═83216915-cdcf-4f0f-829f-a5ff4c4b8da0\n# ╟─452872f9-2009-4733-b2d3-28f262ae19b7\n# ╟─29415ddc-e002-4f56-a169-95f7b1c36be9\n# ╟─fb23d6c6-b812-4fe1-b224-0014bedbd43f\n# ╠═1e53aa10-dff6-40d5-89e2-da194ffc2052\n# ╠═ac87ced2-986f-4e6c-80b2-104b25c171c2\n# ╠═14cca8ce-cc61-4fae-b871-21c3fd23d0ea\n# ╠═28fc8de4-749b-4093-b32f-c398f8d27d3d\n# ╠═57b422e5-0ad0-4674-bdd3-a8358bc7aaeb\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "1c9e2b5a52b591d34263cc9faeaf26e527b0a00f", "size": 30933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ex2_nopycall.jl", "max_stars_repo_name": "PsuAstro528/lab3-start", "max_stars_repo_head_hexsha": "adc592c7a3d00a2402ebe1943ab4a09c8d8cabfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-20T16:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T16:12:26.000Z", "max_issues_repo_path": "ex2_nopycall.jl", "max_issues_repo_name": "PsuAstro528/lab3-start", "max_issues_repo_head_hexsha": "adc592c7a3d00a2402ebe1943ab4a09c8d8cabfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex2_nopycall.jl", "max_forks_repo_name": "PsuAstro528/lab3-start", "max_forks_repo_head_hexsha": "adc592c7a3d00a2402ebe1943ab4a09c8d8cabfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0317100793, "max_line_length": 683, "alphanum_fraction": 0.7375941551, "num_tokens": 12856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.1612371766117515}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\n## CHOLMOD\nconst TRUE = Int32(1)\nconst FALSE = Int32(0)\n\n## itype defines the types of integer used:\nconst INT = Int32(0) # all integer arrays are int\nconst INTLONG = Int32(1) # most are int, some are SuiteSparse_long\nconst LONG = Int32(2) # all integer arrays are SuiteSparse_long\n\n## dtype defines what the numerical type is (double or float):\nconst DOUBLE = Int32(0) # all numerical values are double\nconst SINGLE = Int32(1) # all numerical values are float\ndtyp(::Type{Float32}) = SINGLE\ndtyp(::Type{Float64}) = DOUBLE\ndtyp(::Type{ComplexF32}) = SINGLE\ndtyp(::Type{ComplexF64}) = DOUBLE\n\n## xtype defines the kind of numerical values used:\nconst PATTERN = Int32(0) # pattern only, no numerical values\nconst REAL = Int32(1) # a real matrix\nconst COMPLEX = Int32(2) # a complex matrix (ANSI C99 compatible)\nconst ZOMPLEX = Int32(3) # a complex matrix (MATLAB compatible)\nxtyp(::Type{Float32}) = REAL\nxtyp(::Type{Float64}) = REAL\nxtyp(::Type{ComplexF32}) = COMPLEX\nxtyp(::Type{ComplexF64}) = COMPLEX\n\n## Scaling modes, selected by the scale input parameter:\nconst SCALAR = Int32(0) # A = s*A\nconst ROW = Int32(1) # A = diag(s)*A\nconst COL = Int32(2) # A = A*diag(s)\nconst SYM = Int32(3) # A = diag(s)*A*diag(s)\n\n## Types of systems to solve\nconst CHOLMOD_A = Int32(0) # solve Ax=b\nconst CHOLMOD_LDLt = Int32(1) # solve LDL'x=b\nconst CHOLMOD_LD = Int32(2) # solve LDx=b\nconst CHOLMOD_DLt = Int32(3) # solve DL'x=b\nconst CHOLMOD_L = Int32(4) # solve Lx=b\nconst CHOLMOD_Lt = Int32(5) # solve L'x=b\nconst CHOLMOD_D = Int32(6) # solve Dx=b\nconst CHOLMOD_P = Int32(7) # permute x=Px\nconst CHOLMOD_Pt = Int32(8) # permute x=P'x\n\n# Symmetry types\nconst EMPTY =-1\nconst MM_RECTANGULAR = 1\nconst MM_UNSYMMETRIC = 2\nconst MM_SYMMETRIC = 3\nconst MM_HERMITIAN = 4\nconst MM_SKEW_SYMMETRIC = 5\nconst MM_SYMMETRIC_POSDIAG = 6\nconst MM_HERMITIAN_POSDIAG = 7\n\n# check the size of SuiteSparse_long\nif Int(ccall((:jl_cholmod_sizeof_long, :libsuitesparse_wrapper),Csize_t,())) == 4\n const SuiteSparse_long = Int32\n const IndexTypes = (:Int32,)\n const ITypes = Union{Int32}\nelse\n const SuiteSparse_long = Int64\n const IndexTypes = (:Int32, :Int64)\n const ITypes = Union{Int32, Int64}\nend\nityp(::Type{SuiteSparse_long}) = LONG\n\n\nconst VTypes = Union{ComplexF64, Float64}\nconst VRealTypes = Union{Float64}\n\nstruct CHOLMODException <: Exception\n msg::String\nend\n\nmacro isok(A)\n :($(esc(A)) == TRUE || throw(CHOLMODException(\"\")))\nend\n", "meta": {"hexsha": "08b8464238a599ea42ef7ac90fb789d2a38b4525", "size": 2762, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stdlib/SuiteSparse/src/cholmod_h.jl", "max_stars_repo_name": "sg-s/julia", "max_stars_repo_head_hexsha": "d7d2b0c692eb6ad409d7193ba8d9d42972cbf182", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stdlib/SuiteSparse/src/cholmod_h.jl", "max_issues_repo_name": "sg-s/julia", "max_issues_repo_head_hexsha": "d7d2b0c692eb6ad409d7193ba8d9d42972cbf182", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stdlib/SuiteSparse/src/cholmod_h.jl", "max_forks_repo_name": "sg-s/julia", "max_forks_repo_head_hexsha": "d7d2b0c692eb6ad409d7193ba8d9d42972cbf182", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.525, "max_line_length": 81, "alphanum_fraction": 0.651339609, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3073580041760868, "lm_q1q2_score": 0.16087743379421948}} {"text": "struct AddCostSpec\n variable_type::Type\n component_type::Type\n has_status_variable::Bool\n has_status_parameter::Bool\n sos_status::SOS_STATUS_VARIABLE\n multiplier::Float64\n variable_cost::Union{Nothing, Function}\n start_up_cost::Union{Nothing, Function}\n shut_down_cost::Union{Nothing, Function}\n fixed_cost::Union{Nothing, Function}\n addtional_linear_terms::Dict{String, Symbol}\nend\n\nfunction AddCostSpec(;\n variable_type,\n component_type,\n has_status_variable = false,\n has_status_parameter = false,\n sos_status = NO_VARIABLE,\n multiplier = OBJECTIVE_FUNCTION_POSITIVE,\n variable_cost = nothing,\n start_up_cost = nothing,\n shut_down_cost = nothing,\n fixed_cost = nothing,\n addtional_linear_terms = Dict{String, Symbol}(),\n)\n return AddCostSpec(\n variable_type,\n component_type,\n has_status_variable,\n has_status_parameter,\n sos_status,\n multiplier,\n variable_cost,\n start_up_cost,\n shut_down_cost,\n fixed_cost,\n addtional_linear_terms,\n )\nend\n\nfunction AddCostSpec(\n ::Type{<:T},\n ::Type{<:U},\n ::PSIContainer,\n) where {T <: PSY.Component, U <: AbstractDeviceFormulation}\n error(\"AddCostSpec is not implemented for $T / $U\")\nend\n\nset_addtional_linear_terms!(spec::AddCostSpec, key, value) =\n spec.addtional_linear_terms[key] = value\n\nfunction add_service_variables!(spec::AddCostSpec, services)\n for service in services\n name = PSY.get_name(service)\n set_addtional_linear_terms!(spec, name, make_variable_name(name, typeof(service)))\n end\n return\nend\n\n\"\"\"\nAdd variables to the PSIContainer for a service.\n\"\"\"\nfunction cost_function!(\n psi_container::PSIContainer,\n devices::IS.FlattenIteratorWrapper{T},\n ::DeviceModel{T, U},\n ::Type{<:PM.AbstractPowerModel},\n feedforward::Union{Nothing, AbstractAffectFeedForward} = nothing,\n) where {T <: PSY.Component, U <: AbstractDeviceFormulation}\n for d in devices\n spec = AddCostSpec(T, U, psi_container)\n @debug T, spec\n services = PSY.get_services(d)\n add_service_variables!(spec, services)\n add_to_cost!(psi_container, spec, PSY.get_operation_cost(d), d)\n end\n return\nend\n\nfunction add_to_cost_expression!(\n psi_container::PSIContainer,\n cost_expression::JuMP.AbstractJuMPScalar,\n)\n T_ce = typeof(cost_expression)\n T_cf = typeof(psi_container.cost_function)\n if T_cf <: JuMP.GenericAffExpr && T_ce <: JuMP.GenericQuadExpr\n psi_container.cost_function += cost_expression\n else\n JuMP.add_to_expression!(psi_container.cost_function, cost_expression)\n end\n return\nend\n\nfunction has_on_variable(\n psi_container::PSIContainer,\n ::Type{T};\n variable_type = OnVariable,\n) where {T <: PSY.Component}\n #get_variable can't be used because the default behavior is to error if variables is not present\n return !isnothing(get(\n psi_container.variables,\n make_variable_name(variable_type, T),\n nothing,\n ))\nend\n\nfunction has_on_parameter(psi_container::PSIContainer, ::Type{T}) where {T <: PSY.Component}\n if !model_has_parameters(psi_container)\n return false\n end\n return !isnothing(get(\n psi_container.parameters,\n encode_symbol(OnVariable, string(T)),\n nothing,\n ))\nend\n\nfunction _get_pwl_vars_container(psi_container::PSIContainer)\n if !haskey(psi_container.variables, :PWL_cost_vars)\n time_steps = model_time_steps(psi_container)\n contents = Dict{Tuple{String, Int, Int}, Any}()\n container = JuMP.Containers.SparseAxisArray(contents)\n assign_variable!(psi_container, :PWL_cost_vars, container)\n else\n container = get_variable(psi_container, :PWL_cost_vars)\n end\n return container\nend\n\nfunction slope_convexity_check(slopes::Vector{Float64})\n flag = true\n for ix in 1:(length(slopes) - 1)\n if slopes[ix] > slopes[ix + 1]\n @debug slopes\n return flag = false\n end\n end\n return flag\nend\n\n@doc raw\"\"\"\nReturns True/False depending on compatibility of the cost data with the linear implementation method\n\nReturns ```flag```\n\n# Arguments\n\n* cost_ : container for quadratic and linear factors\n\"\"\"\nfunction pwlparamcheck(cost_)\n slopes = PSY.get_slopes(cost_)\n # First element of the return is the average cost at P_min.\n # Shouldn't be passed for convexity check\n return slope_convexity_check(slopes[2:end])\nend\n\nfunction linear_gen_cost!(\n psi_container::PSIContainer,\n var_name::Symbol,\n component_name::String,\n linear_term::Float64,\n time_period::Int,\n)\n resolution = model_resolution(psi_container)\n dt = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n variable = get_variable(psi_container, var_name)[component_name, time_period]\n gen_cost = sum(variable) * linear_term\n add_to_cost_expression!(psi_container, gen_cost * dt)\n return\nend\n\n@doc raw\"\"\"\nReturns piecewise cost expression using SOS Type-2 implementation for psi_container model.\n\n# Equations\n\n``` variable = sum(sos_var[i]*cost_data[2][i])```\n\n``` gen_cost = sum(sos_var[i]*cost_data[1][i]) ```\n\n# LaTeX\n\n`` variable = (sum_{i\\in I} c_{2, i} sos_i) ``\n\n`` gen_cost = (sum_{i\\in I} c_{1, i} sos_i) ``\n\nReturns ```gen_cost```\n\n# Arguments\n\n* psi_container::PSIContainer : the psi_container model built in PowerSimulations\n* variable::JuMP.Containers.DenseAxisArray{JV} : variable array\n* cost_data::PSY.VariableCost{NTuple{2, Float64}} : container for quadratic and linear factors\n\"\"\"\nfunction pwl_gencost_sos!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component_name::String,\n cost_data::Vector{NTuple{2, Float64}},\n time_period::Int,\n)\n var_name = make_variable_name(spec.variable_type, spec.component_type)\n variable = get_variable(psi_container, var_name)[component_name, time_period]\n settings_ext = get_ext(get_settings(psi_container))\n export_pwl_vars = get_export_pwl_vars(psi_container.settings)\n @debug export_pwl_vars\n total_gen_cost = JuMP.AffExpr(0.0)\n\n if spec.sos_status == NO_VARIABLE\n bin = 1.0\n @debug(\"Using Piecewise Linear cost function but no variable/parameter ref for ON status is passed. Default status will be set to online (1.0)\")\n elseif spec.sos_status == PARAMETER\n param_key = encode_symbol(OnVariable, string(spec.component_type))\n bin =\n get_parameter_container(psi_container, param_key).parameter_array[component_name]\n @debug(\"Using Piecewise Linear cost function with parameter $(param_key)\")\n elseif spec.sos_status == VARIABLE\n var_key = make_variable_name(OnVariable, spec.component_type)\n bin = get_variable(psi_container, var_key)[component_name, time_period]\n @debug(\"Using Piecewise Linear cost function with variable $(var_key)\")\n else\n @assert false\n end\n\n gen_cost = JuMP.AffExpr(0.0)\n pwlvars = Array{JuMP.VariableRef}(undef, length(cost_data))\n for i in 1:length(cost_data)\n pwlvars[i] = JuMP.@variable(\n psi_container.JuMPmodel,\n base_name = \"{$(variable)}_{sos}\",\n start = 0.0,\n lower_bound = 0.0,\n upper_bound = 1.0\n )\n if export_pwl_vars\n container = _get_pwl_vars_container(psi_container)\n container[(component_name, time_period, i)] = pwlvars[i]\n end\n JuMP.add_to_expression!(gen_cost, cost_data[i][1] * pwlvars[i])\n end\n JuMP.@constraint(psi_container.JuMPmodel, sum(pwlvars) == bin)\n JuMP.@constraint(\n psi_container.JuMPmodel,\n pwlvars in MOI.SOS2(collect(1:length(pwlvars)))\n )\n JuMP.@constraint(\n psi_container.JuMPmodel,\n variable == sum([var_ * cost_data[ix][2] for (ix, var_) in enumerate(pwlvars)])\n )\n JuMP.add_to_expression!(total_gen_cost, gen_cost)\n\n return total_gen_cost\nend\n\n@doc raw\"\"\"\nReturns piecewise cost expression using linear implementation for psi_container model.\n\n# Equations\n\n``` 0 <= pwl_var[i] <= (cost_data[2][i] - cost_data[2][i-1])```\n\n``` variable = sum(pwl_var[i])```\n\n``` gen_cost = sum(pwl_var[i]*cost_data[1][i]/cost_data[2][i]) ```\n\n# LaTeX\n`` 0 <= pwl_i <= (c_{2, i} - c_{2, i-1})``\n\n`` variable = (sum_{i\\in I} pwl_i) ``\n\n`` gen_cost = (sum_{i\\in I} pwl_i) c_{1, i}/c_{2, i} ``\n\nReturns ```gen_cost```\n\n# Arguments\n\n* psi_container::PSIContainer : the psi_container model built in PowerSimulations\n* variable::JuMP.Containers.DenseAxisArray{JV} : variable array\n* cost_data::Vector{NTuple{2, Float64}} : container for quadratic and linear factors\n\"\"\"\nfunction pwl_gencost_linear!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component_name::String,\n cost_data::Vector{NTuple{2, Float64}},\n time_period::Int,\n)\n var_name = make_variable_name(spec.variable_type, spec.component_type)\n variable = get_variable(psi_container, var_name)[component_name, time_period]\n settings_ext = get_ext(get_settings(psi_container))\n export_pwl_vars = get_export_pwl_vars(psi_container.settings)\n @debug export_pwl_vars\n total_gen_cost = JuMP.AffExpr(0.0)\n\n gen_cost = JuMP.AffExpr(0.0)\n total_gen = JuMP.AffExpr(0.0)\n for i in 1:length(cost_data)\n pwlvar = JuMP.@variable(\n psi_container.JuMPmodel,\n base_name = \"{$(variable)}_{pwl}\",\n start = 0.0,\n lower_bound = 0.0,\n upper_bound = PSY.get_breakpoint_upperbounds(cost_data)[i]\n )\n if export_pwl_vars\n container = _get_pwl_vars_container(psi_container)\n container[(component_name, time_period, i)] = pwlvar\n end\n JuMP.add_to_expression!(gen_cost, PSY.get_slopes(cost_data)[i] * pwlvar)\n JuMP.add_to_expression!(total_gen, pwlvar)\n end\n JuMP.@constraint(psi_container.JuMPmodel, variable == total_gen)\n JuMP.add_to_expression!(total_gen_cost, gen_cost)\n return total_gen_cost\nend\n\n\"\"\"\nAdds to the models costs represented by PowerSystems TwoPart costs\n\"\"\"\nfunction add_to_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n cost_data::PSY.TwoPartCost,\n component::PSY.Component,\n)\n component_name = PSY.get_name(component)\n time_steps = model_time_steps(psi_container)\n @debug \"TwoPartCost\" component_name\n if !(spec.variable_cost === nothing)\n variable_cost = spec.variable_cost(cost_data)\n for t in time_steps\n variable_cost!(psi_container, spec, component_name, variable_cost, t)\n end\n else\n @warn \"No variable cost defined for $component_name\"\n end\n\n if !isnothing(spec.fixed_cost) && spec.has_status_variable\n @debug \"Fixed cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(OnVariable, spec.component_type),\n component_name,\n spec.fixed_cost,\n t,\n )\n end\n end\n return\nend\n\n\"\"\"\nAdds to the models costs represented by PowerSystems ThreePart costs\n\"\"\"\nfunction add_to_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n cost_data::PSY.ThreePartCost,\n component::PSY.Component,\n)\n component_name = PSY.get_name(component)\n @debug \"ThreePartCost\" component_name\n resolution = model_resolution(psi_container)\n dt = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n variable_cost = PSY.get_variable(cost_data)\n time_steps = model_time_steps(psi_container)\n for t in time_steps\n variable_cost!(psi_container, spec, component_name, variable_cost, t)\n end\n\n if !isnothing(spec.start_up_cost)\n @debug \"Start up cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(StartVariable, spec.component_type),\n component_name,\n spec.start_up_cost(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n if !isnothing(spec.shut_down_cost)\n @debug \"Shut down cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(StopVariable, spec.component_type),\n component_name,\n spec.shut_down_cost(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n if !isnothing(spec.fixed_cost) && spec.has_status_variable\n @debug \"Fixed cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(OnVariable, spec.component_type),\n component_name,\n spec.fixed_cost(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n return\nend\n\n\"\"\"\nAdds to the models costs represented by PowerSystems Multi-Start costs\n\"\"\"\nfunction add_to_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n cost_data::PSY.MultiStartCost,\n component::PSY.Component,\n)\n component_name = PSY.get_name(component)\n resolution = model_resolution(psi_container)\n dt = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n time_steps = model_time_steps(psi_container)\n\n if !isnothing(spec.fixed_cost) && spec.has_status_variable\n @debug \"Fixed cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(OnVariable, spec.component_type),\n component_name,\n spec.fixed_cost(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n if !isnothing(spec.shut_down_cost)\n @debug \"Shut down cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(StopVariable, spec.component_type),\n component_name,\n spec.shut_down_cost(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n # Original implementation had SOS by default\n variable_cost_data = PSY.get_cost(PSY.get_variable(cost_data))\n if !all(iszero.(last.(variable_cost_data)))\n for t in time_steps\n gen_cost =\n pwl_gencost_sos!(psi_container, spec, component_name, variable_cost_data, t)\n add_to_cost_expression!(psi_container, spec.multiplier * gen_cost * dt)\n end\n else\n @debug \"No Variable Cost associated with $(component_name)\"\n end\n\n # Start-up costs\n start_cost_data = PSY.get_start_up(cost_data)\n for (st, var_type) in\n enumerate((HotStartVariable, WarmStartVariable, ColdStartVariable))\n var_name = make_variable_name(var_type, spec.component_type)\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n var_name,\n component_name,\n start_cost_data[st] * spec.multiplier,\n t,\n )\n end\n end\n\n return\nend\n\n\"\"\"\nAdds to the models costs represented by PowerSystems Market-Bid costs\n\"\"\"\nfunction add_to_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n cost_data::PSY.MarketBidCost,\n component::PSY.Component,\n)\n component_name = PSY.get_name(component)\n @debug \"Market Bid\" component_name\n resolution = model_resolution(psi_container)\n dt = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n time_steps = model_time_steps(psi_container)\n initial_time = model_initial_time(psi_container)\n # TODO: Use mthods from PowerSystems to eliminate this step\n variable_cost_forecast = get_time_series(psi_container, component, \"variable_cost\")\n variable_cost_forecast = map(PSY.VariableCost, variable_cost_forecast)\n for t in time_steps\n variable_cost!(psi_container, spec, component_name, variable_cost_forecast[t], t)\n end\n\n if !isnothing(spec.start_up_cost)\n @debug \"Start up cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(StartVariable, spec.component_type),\n component_name,\n spec.start_up_cost(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n if spec.has_status_variable\n @debug \"no_load cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(OnVariable, spec.component_type),\n component_name,\n PSY.get_no_load(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n if !isnothing(spec.shut_down_cost)\n @debug \"Shut down cost\" component_name\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n make_variable_name(StopVariable, spec.component_type),\n component_name,\n spec.shut_down_cost(cost_data) * spec.multiplier,\n t,\n )\n end\n end\n\n #Service Cost Bid\n ancillary_services = PSY.get_ancillary_services(cost_data)\n for service in ancillary_services\n add_service_bid_cost!(psi_container, spec, component, service)\n end\n return\nend\n\nfunction add_service_bid_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component::PSY.Component,\n service::PSY.Service,\n)\n return\nend\n\nfunction add_service_bid_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component::PSY.Component,\n service::PSY.Reserve{T},\n) where {T <: PSY.ReserveDirection}\n # TODO: Use mthods from PowerSystems to eliminate this step\n forecast_data = get_time_series(psi_container, component, PSY.get_name(service))\n forecast_data = map(PSY.VariableCost, forecast_data)\n time_steps = model_time_steps(psi_container)\n if eltype(forecast_data) == PSY.VariableCost{Float64}\n for t in time_steps\n linear_gen_cost!(\n psi_container,\n spec.addtional_linear_terms[PSY.get_name(service)],\n PSY.get_name(component),\n forecast_data,\n t,\n )\n end\n else\n error(\"Current version only supports linear cost bid for services, please change the forecast data for $(PSY.get_name(service))\")\n end\n return\nend\n\nfunction add_service_bid_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component::PSY.Component,\n service::PSY.ReserveDemandCurve{T},\n) where {T <: PSY.ReserveDirection}\n error(\"Current version doesn't supports cost bid for ReserveDemandCurve services, please change the forecast data for $(PSY.get_name(service))\")\n return\nend\n\n@doc raw\"\"\"\nAdds to the cost function cost terms for sum of variables with common factor to be used for cost expression for psi_container model.\n\n # Arguments\n\n* psi_container::PSIContainer : the psi_container model built in PowerSimulations\n* var_name::Symbol: The variable name\n* component_name::String: The component_name of the variable container\n* cost_component::PSY.VariableCost{Float64} : container for cost to be associated with variable\n\"\"\"\nfunction variable_cost!(\n ::PSIContainer,\n ::AddCostSpec,\n component_name::String,\n ::Nothing,\n ::Int,\n)\n @debug \"Empty Variable Cost\" component_name\n return\nend\n\n@doc raw\"\"\"\nAdds to the cost function cost terms for sum of variables with common factor to be used for cost expression for psi_container model.\n\n # Arguments\n\n* psi_container::PSIContainer : the psi_container model built in PowerSimulations\n* var_name::Symbol: The variable name\n* component_name::String: The component_name of the variable container\n* cost_component::PSY.VariableCost{Float64} : container for cost to be associated with variable\n\"\"\"\nfunction variable_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component_name::String,\n cost_component::PSY.VariableCost{Float64},\n time_period::Int,\n)\n @debug \"Linear Variable Cost\" component_name\n var_name = make_variable_name(spec.variable_type, spec.component_type)\n cost_data = PSY.get_cost(cost_component)\n linear_gen_cost!(\n psi_container,\n var_name,\n component_name,\n cost_data * spec.multiplier,\n time_period,\n )\n return\nend\n\n@doc raw\"\"\"\nAdds to the cost function cost terms for sum of variables with common factor to be used for cost expression for psi_container model.\n\n# Equation\n\n``` gen_cost = dt*sign*(sum(variable.^2)*cost_data[1] + sum(variable)*cost_data[2]) ```\n\n# LaTeX\n\n`` cost = dt\\times sign (sum_{i\\in I} c_1 v_i^2 + sum_{i\\in I} c_2 v_i ) ``\n\nfor quadratic factor large enough. If the first term of the quadratic objective is 0.0, adds a\nlinear cost term `sum(variable)*cost_data[2]`\n\n# Arguments\n\n* psi_container::PSIContainer : the psi_container model built in PowerSimulations\n* var_name::Symbol: The variable name\n* component_name::String: The component_name of the variable container\n* cost_component::PSY.VariableCost{NTuple{2, Float64}} : container for quadratic and linear factors\n\"\"\"\nfunction variable_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component_name::String,\n cost_component::PSY.VariableCost{NTuple{2, Float64}},\n time_period::Int,\n)\n var_name = make_variable_name(spec.variable_type, spec.component_type)\n cost_data = PSY.get_cost(cost_component)\n if cost_data[1] >= eps()\n @debug \"Quadratic Variable Cost\" component_name\n resolution = model_resolution(psi_container)\n dt = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n variable = get_variable(psi_container, var_name)[component_name, time_period]\n gen_cost = sum(variable .^ 2) * cost_data[1] + sum(variable) * cost_data[2]\n add_to_cost_expression!(psi_container, spec.multiplier * gen_cost * dt)\n else\n @debug \"Quadratic Variable Cost with only linear term\" component_name\n linear_gen_cost!(\n psi_container,\n var_name,\n component_name,\n cost_data[2] * spec.multiplier,\n time_period,\n )\n end\n return\nend\n\n@doc raw\"\"\"\nCreates piecewise linear cost function using a sum of variables and expression with sign and time step included.\n\n# Expression\n\n```JuMP.add_to_expression!(gen_cost, c)```\n\nReturns sign*gen_cost*dt\n\n# LaTeX\n\n``cost = sign\\times dt \\sum_{v\\in V} c_v``\n\nwhere ``c_v`` is given by\n\n`` c_v = \\sum_{i\\in Ix} \\frac{y_i - y_{i-1}}{x_i - x_{i-1}} v^{p.w.}_i ``\n\n# Arguments\n\n* psi_container::PSIContainer : the psi_container model built in PowerSimulations\n* var_name::Symbol: The variable name\n* component_name::String: The component_name of the variable container\n* cost_component::PSY.VariableCost{Vector{NTuple{2, Float64}}}\n\"\"\"\nfunction variable_cost!(\n psi_container::PSIContainer,\n spec::AddCostSpec,\n component_name::String,\n cost_component::PSY.VariableCost{Vector{NTuple{2, Float64}}},\n time_period::Int,\n)\n @debug \"PWL Variable Cost\" component_name\n resolution = model_resolution(psi_container)\n dt = Dates.value(Dates.Second(resolution)) / SECONDS_IN_HOUR\n # If array is full of tuples with zeros return 0.0\n cost_data = PSY.get_cost(cost_component)\n if all(iszero.(last.(cost_data)))\n @debug \"All cost terms for component $(component_name) are 0.0\"\n return JuMP.AffExpr(0.0)\n end\n\n var_name = make_variable_name(spec.variable_type, spec.component_type)\n if !pwlparamcheck(cost_component)\n @warn(\"The cost function provided for $(var_name) device is not compatible with a linear PWL cost function.\n An SOS-2 formulation will be added to the model.\n This will result in additional binary variables added to the model.\")\n gen_cost =\n pwl_gencost_sos!(psi_container, spec, component_name, cost_data, time_period)\n else\n gen_cost =\n pwl_gencost_linear!(psi_container, spec, component_name, cost_data, time_period)\n end\n add_to_cost_expression!(psi_container, spec.multiplier * gen_cost * dt)\n return\nend\n", "meta": {"hexsha": "36cb43f65bf447afbb9114717751aaffbec9b387", "size": 24269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/devices_models/devices/common/cost_functions.jl", "max_stars_repo_name": "superdakun/PowerSimulations.jl", "max_stars_repo_head_hexsha": "9f9cc278455e8db83433b2d3f26ce7f7830561be", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-12T06:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T06:17:19.000Z", "max_issues_repo_path": "src/devices_models/devices/common/cost_functions.jl", "max_issues_repo_name": "superdakun/PowerSimulations.jl", "max_issues_repo_head_hexsha": "9f9cc278455e8db83433b2d3f26ce7f7830561be", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/devices_models/devices/common/cost_functions.jl", "max_forks_repo_name": "superdakun/PowerSimulations.jl", "max_forks_repo_head_hexsha": "9f9cc278455e8db83433b2d3f26ce7f7830561be", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0594451783, "max_line_length": 152, "alphanum_fraction": 0.6765420907, "num_tokens": 5836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.16085854678309305}} {"text": "\n # Functions and methods for cascade computation\n\n\n \"\"\"\n `Cascade.computeSteps(scheme::Cascade.StepwiseDecayScheme, comp::Cascade.Computation, stepList::Array{Cascade.Step,1})` \n ... computes in turn all the requested transition amplitudes as well as PhotoEmission.Line's, AutoIonization.Line's, \n etc. for all pre-specified decay steps of the cascade. When compared with standard computations of these atomic \n processes, however, the amount of output is largely reduced and often just printed into the summary file. \n A set of data::Cascade.DecayData is returned.\n \"\"\"\n function computeSteps(scheme::Cascade.StepwiseDecayScheme, comp::Cascade.Computation, stepList::Array{Cascade.Step,1})\n linesA = AutoIonization.Line[]; linesR = PhotoEmission.Line[]; cOrbitals = Dict{Subshell, Orbital}() \n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n nt = 0; st = 0; previousMeanEn = 0.\n for step in stepList\n st = st + 1\n nc = length(step.initialMultiplet.levels) * length(step.finalMultiplet.levels)\n println(\"\\n $st) Perform $(string(step.process)) amplitude computations for up to $nc decay lines (without selection rules): \")\n if printSummary println(iostream, \"\\n* $st) Perform $(string(step.process)) amplitude computations for \" *\n \"up to $nc decay lines (without selection rules): \") end \n \n if step.process == Basics.Auger() && comp.approach == Cascade.AverageSCA()\n # First determine the `mean' free-electron energy for this Auger block and calculate a common set of continuum orbital\n meanEn = 0.; NoEn = 0\n for p = 1:length(step.initialMultiplet.levels), q = 1:length(step.finalMultiplet.levels)\n en = step.initialMultiplet.levels[p].energy - step.finalMultiplet.levels[q].energy\n if en > 0.1 meanEn = meanEn + en; NoEn = NoEn + 1 end\n end\n if NoEn > 0 meanEn = meanEn/ NoEn else meanEn = 0.1 end\n if abs(meanEn - previousMeanEn) / meanEn < 0.15 # no new continuum orbitals\n println(\">> No new continum orbitals are generated for $(keys(cOrbitals)) and for the energy $meanEn \")\n else\n previousMeanEn = meanEn; cOrbitals = Dict{Subshell, Orbital}()\n for kappa = -step.settings.maxKappa-1:step.settings.maxKappa if kappa == 0 continue end\n sh = Subshell(101, kappa); nrContinuum = Continuum.gridConsistency(meanEn, comp.grid)\n contSettings = Continuum.Settings(false, nrContinuum); \n npot = Nuclear.nuclearPotential(comp.nuclearModel, comp.grid)\n ## wp1 = compute(\"radial potential: core-Hartree\", grid, wLevel)\n ## wp2 = compute(\"radial potential: Hartree-Slater\", grid, wLevel)\n ## wp3 = compute(\"radial potential: Kohn-Sham\", grid, wLevel)\n ## wp = Basics.compute(\"radial potential: Dirac-Fock-Slater\", comp.grid, step.finalMultiplet.levels[1].basis)\n wp = Basics.computePotentialDFS(comp.grid, step.finalMultiplet.levels[1])\n pot = Basics.add(npot, wp)\n cOrbital, phase, normF = Continuum.generateOrbitalLocalPotential(meanEn, sh, pot, contSettings)\n cOrbitals[sh] = cOrbital\n end\n println(\">> Generate continum orbitals in DFS potential for $(keys(cOrbitals)) and for the energy $meanEn \")\n end\n \n newLines = AutoIonization.computeLinesFromOrbitals(step.finalMultiplet, step.initialMultiplet, comp.nuclearModel, comp.grid, \n step.settings, cOrbitals, output=true, printout=false) \n append!(linesA, newLines); nt = length(linesA)\n elseif step.process == Basics.Auger() \n # Compute continuum orbitals independently for all transitions in the given block.\n newLines = AutoIonization.computeLinesCascade(step.finalMultiplet, step.initialMultiplet, comp.nuclearModel, comp.grid, \n step.settings, output=true, printout=false) \n append!(linesA, newLines); nt = length(linesA)\n elseif step.process == Basics.Radiative()\n newLines = PhotoEmission.computeLinesCascade(step.finalMultiplet, step.initialMultiplet, comp.grid, \n step.settings, output=true, printout=false) \n append!(linesR, newLines); nt = length(linesR)\n else error(\"Unsupported atomic process for cascade computations.\")\n end\n println(\" Step $st:: A total of $(length(newLines)) $(string(step.process)) lines are calculated, giving now rise \" *\n \"to a total of $nt $(string(step.process)) decay lines.\" )\n if printSummary println(iostream, \"\\n* Step $st:: A total of $(length(newLines)) $(string(step.process)) lines are calculated, \" *\n \"giving now rise to a total of $nt $(string(step.process)) decay lines.\" ) end \n end\n #\n data = Cascade.DecayData(linesR, linesA)\n end\n\n\n \"\"\"\n `Cascade.determineSteps(scheme::Cascade.StepwiseDecayScheme, comp::Cascade.Computation, blockList::Array{Cascade.Block,1})` \n ... determines all step::Cascade.Step's that need to be computed for this decay cascade. It cycles through all processes of the given\n decay scheme and selects all pairs of blocks due to the selected cascade approach. It is checked that the (averaged) energies \n each block or level supports a `decay' within the step. A stepList::Array{Cascade.Step,1} is returned, and for which subsequently\n all required transition amplitudes and rates are computed.\n \"\"\"\n function determineSteps(scheme::Cascade.StepwiseDecayScheme, comp::Cascade.Computation, blockList::Array{Cascade.Block,1})\n stepList = Cascade.Step[]\n if comp.approach in [Cascade.AverageSCA(), Cascade.SCA()]\n for a = 1:length(blockList)\n for b = 1:length(blockList)\n minEn = 100000.; maxEn = -100000.\n for p = 1:length(blockList[a].multiplet.levels), q = 1:length(blockList[b].multiplet.levels)\n minEn = min(minEn, blockList[a].multiplet.levels[p].energy - blockList[b].multiplet.levels[q].energy)\n maxEn = max(maxEn, blockList[a].multiplet.levels[p].energy - blockList[b].multiplet.levels[q].energy)\n end\n for process in comp.scheme.processes\n if process == Basics.Radiative() \n if a == b || minEn < 0. continue end\n if blockList[a].NoElectrons == blockList[b].NoElectrons\n settings = PhotoEmission.Settings([E1], [UseBabushkin], false, false, LineSelection(), 0., 0., 1.0e6)\n push!( stepList, Cascade.Step(process, settings, blockList[a].confs, blockList[b].confs, \n blockList[a].multiplet, blockList[b].multiplet) )\n end\n elseif process == Basics.Auger() \n if a == b || minEn < 0. continue end\n if blockList[a].NoElectrons == blockList[b].NoElectrons + 1\n settings = AutoIonization.Settings(false, false, LineSelection(), 0., 1.0e6, 3, CoulombInteraction())\n push!( stepList, Cascade.Step(process, settings, blockList[a].confs, blockList[b].confs, \n blockList[a].multiplet, blockList[b].multiplet) )\n end\n else error(\"stop a\")\n end\n end\n end\n end\n #\n else error(\"Unsupported cascade approach.\")\n end\n return( stepList )\n end\n\n\n \"\"\"\n `Cascade.perform(scheme::StepwiseDecayScheme, comp::Cascade.Computation)` \n ... to set-up and perform a cascade computation that starts from a given set of initial configurations and proceeds via \n various steps until a given number of electrons has been removed or the decay stops at some stable levels with regard \n to the given atomic processes. The results of all individual steps are printed to screen but nothing is returned \n otherwise.\n\n `Cascade.perform(scheme::StepwiseDecayScheme, comp::Cascade.Computation; output::Bool=false, outputToFile::Bool=true)` \n ... to perform the same but to return the complete output in a dictionary; the particular output depends on the type \n and specifications of the cascade but can easily accessed by the keys of this dictionary.\n \"\"\"\n function perform(scheme::StepwiseDecayScheme, comp::Cascade.Computation; output::Bool=false, outputToFile::Bool=true)\n if output results = Dict{String, Any}() else results = nothing end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n #\n # Perform the SCF and CI computation for the intial-state multiplets if initial configurations are given\n if comp.initialConfigs != Configuration[]\n basis = Basics.performSCF(comp.initialConfigs, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplet = Basics.performCI(basis, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplets = [Multiplet(\"initial states\", multiplet.levels)]\n else\n basis = comp.initialMultiplets[1].levels[1].basis\n multiplets = comp.initialMultiplets\n end\n # Print out initial configurations and levels \n Cascade.displayLevels(stdout, multiplets, sa=\"initial \")\n if printSummary Cascade.displayLevels(iostream, multiplets, sa=\"initial \") end\n #\n # Generate subsequent cascade configurations as well as display and group them together\n wa = Cascade.generateConfigurationList(multiplets, comp.scheme.maxElectronLoss, comp.scheme.NoShakeDisplacements)\n wb = Cascade.groupDisplayConfigurationList(comp.nuclearModel.Z, wa, sa=\"decay \")\n #\n # Determine first all configuration 'blocks' and from them the individual steps of the cascade\n wc = Cascade.generateBlocks(comp, wb, basis.orbitals, sa=\"for the decay cascade:\")\n Cascade.displayBlocks(stdout, wc, sa=\"for the decay cascade \")\n if printSummary Cascade.displayBlocks(iostream, wc, sa=\"for the decay cascade \") end \n gMultiplets = Multiplet[]; for block in wc push!(gMultiplets, block.multiplet) end\n # Determine, modify and compute the transition data for all steps, ie. the PhotoEmission.Line's, the AutoIonization.Line's, etc.\n wd = Cascade.determineSteps(scheme, comp, wc)\n Cascade.displaySteps(stdout, wd, sa=\"decay \")\n if printSummary Cascade.displaySteps(iostream, wd, sa=\"decay \") end \n we = Cascade.modifySteps(wd)\n @time data = Cascade.computeSteps(scheme, comp, we)\n if output \n results = Base.merge( results, Dict(\"name\" => comp.name) ) \n results = Base.merge( results, Dict(\"cascade scheme\" => comp.scheme) ) \n results = Base.merge( results, Dict(\"initial multiplets:\" => multiplets) ) \n results = Base.merge( results, Dict(\"generated multiplets:\" => gMultiplets) ) \n results = Base.merge( results, Dict(\"decay line data:\" => data) )\n #\n # Write out the result to file to later continue with simulations on the cascade data\n if outputToFile\n filename = \"zzz-cascade-decay-computations-\" * string(Dates.now())[1:13] * \".jld\"\n println(\"\\n* Write all results to disk; use:\\n JLD.save(''$filename'', results) \\n using JLD \" *\n \"\\n results = JLD.load(''$filename'') ... to load the results back from file.\")\n if printSummary println(iostream, \"\\n* Write all results to disk; use:\\n JLD.save(''$filename'', results) \\n using JLD \" *\n \"\\n results = JLD.load(''$filename'') ... to load the results back from file.\" ) end \n ## JLD.save(filename, results)\n JLD2.@save filename results\n end\n else results = nothing\n end\n \n return( results )\n end\n", "meta": {"hexsha": "726102e6b8379d6841d731304ddfce0dac67d869", "size": 13350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-Cascade-inc-stepwise-decay.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-Cascade-inc-stepwise-decay.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-Cascade-inc-stepwise-decay.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.5543478261, "max_line_length": 153, "alphanum_fraction": 0.5841947566, "num_tokens": 2909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.24798742624020279, "lm_q1q2_score": 0.16064581616534915}} {"text": "using LinearAlgebra: transpose!\nusing AstroBase: NAIFId, Epoch, TDBEpoch, from_naifid, julian_twopart, value, SECONDS_PER_DAY\n\nimport AstroBase.Ephemerides:\n AbstractEphemeris,\n position,\n position!,\n velocity,\n velocity!,\n state,\n state!\n\nexport SPK,\n segments,\n print_segments,\n position,\n position!,\n velocity,\n velocity!,\n state,\n state!\n\nconst SIZE_FLOAT64 = sizeof(Float64)\n\nstruct OutOfRangeError <: Exception\n date::Float64\n startdate::Float64\n finaldate::Float64\nend\n\nBase.showerror(io::IO, err::OutOfRangeError) = print(io,\n \"The requested date $(err.date) is outside the interval ($(err.startdate), $(err.finaldate)).\")\n\nmutable struct Segment\n name::String\n firstsec::Float64\n lastsec::Float64\n firstdate::Float64\n lastdate::Float64\n target::Int\n center::Int\n frame::Int\n spktype::Int\n firstaddr::Int\n lastaddr::Int\n firstword::Int\n lastword::Int\n initialsecond::Float64\n intlen::Float64\n rsize::Int\n n_records::Int\n order::Int\n cached_record::Int\n cache::Matrix{Float64}\n x::Vector{Float64}\n t::Vector{Float64}\nend\n\njd(sec) = 2451545.0 + sec / SECONDS_PER_DAY\nseconds(jd) = (jd - 2451545.0) * SECONDS_PER_DAY\n\nfunction Segment(daf, name, record)\n firstsec, lastsec = reinterpret_getindex(Float64, record, (1, 9), daf.little)\n target, center, frame, spktype, firstaddr, lastaddr =\n reinterpret_getindex(Int32, record, (17, 21, 25, 29, 33, 37), daf.little)\n if spktype != 2\n throw(ArgumentError(\"Type $spktype SPK file detected. Only Type 2 SPK files are supported.\"))\n end\n i0 = lastaddr * SIZE_FLOAT64 - 4 * SIZE_FLOAT64 + 1\n init, intlen, rsize, n_records =\n reinterpret_getindex(Float64, daf.array, (i0, i0 + 8, i0 + 16, i0 + 24), daf.little)\n n_records = round(Int32, n_records)\n order = Int((rsize - 2) ÷ 3)\n Segment(\n name,\n firstsec,\n lastsec,\n jd(firstsec),\n jd(lastsec),\n target,\n center,\n frame,\n spktype,\n firstaddr,\n lastaddr,\n firstaddr*SIZE_FLOAT64 - SIZE_FLOAT64 + 1,\n lastaddr*SIZE_FLOAT64 - SIZE_FLOAT64*4,\n init,\n intlen,\n round(Int32, rsize),\n n_records,\n order,\n -1,\n zeros(3, order),\n zeros(order),\n zeros(order),\n )\nend\n\nstruct SPK <: AbstractEphemeris\n daf::DAF\n segments::Dict{Int,Dict{Int,Segment}}\nend\n\nBase.show(io::IO, spk::SPK) = print(io, \"SPK($(spk.segments[0][1].name))\")\n\nfunction SPK(filename)\n daf = DAF(filename)\n segments = Dict{Int, Dict{Int, Segment}}()\n for (name, summary) in getsummaries(daf)\n seg = Segment(daf, name, summary)\n if haskey(segments, seg.center)\n merge!(segments[seg.center], Dict(seg.target=>seg))\n else\n merge!(segments, Dict(seg.center=>Dict(seg.target=>seg)))\n end\n end\n SPK(daf, segments)\nend\n\nsegments(spk::SPK) = spk.segments\n\nfunction list_segments(spk::SPK)\n s = String[]\n for (k,v) in spk.segments\n for l in keys(v)\n push!(s, \"$(from_naifid(k)) ($k) => $(from_naifid(l)) ($l)\")\n end\n end\n sort!(s, lt=segstrlt)\nend\n\nfunction print_segments(spk::SPK)\n s = list_segments(spk)\n println(join(s, \"\\n\"))\nend\n\nfunction segstrlt(a::String, b::String)\n rex = r\"\\([0-9]*\\)$\"\n ma = match(rex, a)\n mb = match(rex, b)\n ia = parse(Int, a[ma.offset+1:end-1])\n ib = parse(Int, b[mb.offset+1:end-1])\n ia < ib\nend\n\n@inline function checkdate(seg::Segment, tdb::Float64)\n if !(seg.firstdate <= tdb <= seg.lastdate)\n throw(OutOfRangeError(tdb, seg.firstdate, seg.lastdate))\n end\nend\n\n@inline function getrecordnum(seg, tdb, tdb2)\n checkdate(seg, tdb+tdb2)\n secs = (seconds(tdb) - seg.initialsecond) + tdb2 * SECONDS_PER_DAY\n recordnum, frac = divrem(secs, seg.intlen)\n recordnum = round(Int, recordnum)\n if recordnum == seg.n_records\n recordnum -= 1\n frac = seg.intlen\n end\n recordnum, frac\nend\n\n@inline function update_cache!(spk::SPK, seg::Segment, recordnum)\n components = 3\n seg.cached_record = recordnum\n # Drop the MID and RADIUS values\n first = seg.firstword + SIZE_FLOAT64 * seg.rsize * recordnum + SIZE_FLOAT64 * 2\n ptr = Ptr{Float64}(pointer(spk.daf.array, first))\n\n cache = unsafe_wrap(Array, Ptr{Float64}(ptr), (seg.order, components), own=false)\n if !spk.daf.little\n transpose!(seg.cache, ntoh.(copy(cache)))\n else\n transpose!(seg.cache, cache)\n end\nend\n\n@inline function chebyshev!(seg, frac)\n seg.x[1] = 1.0\n seg.x[2] = 2.0 * frac / seg.intlen - 1.0\n @inbounds for i = 3:seg.order\n seg.x[i] = 2.0 * seg.x[2] * seg.x[i-1] - seg.x[i-2]\n end\nend\n\n@inline function chebyshev_deriv!(seg)\n seg.t[2] = 1.0\n if seg.order > 2\n seg.t[3] = 4.0 * seg.x[2]\n @inbounds for i = 4:seg.order\n seg.t[i] = 2.0 * seg.x[2] * seg.t[i-1] - seg.t[i-2] +\n seg.x[i-1] + seg.x[i-1]\n end\n end\n seg.t .*= 2.0\n seg.t ./= seg.intlen\nend\n\n@inline function position!(r, seg::Segment, sign::Float64)\n @inbounds @simd for i = 1:3\n for j = 1:seg.order\n r[i] += sign * seg.cache[i, j] * seg.x[j]\n end\n end\n r\nend\n\n@inline function position!(r, spk::SPK, seg::Segment, sign::Float64, tdb::Float64, tdb2::Float64=0.0)\n recordnum, frac = getrecordnum(seg, tdb, tdb2)\n if recordnum != seg.cached_record\n update_cache!(spk, seg, recordnum)\n end\n chebyshev!(seg, frac)\n position!(r, seg, sign)\nend\n\n@inline function velocity!(v, seg::Segment, sign::Float64)\n chebyshev_deriv!(seg)\n @inbounds @simd for i = 1:3\n for j = 1:seg.order\n v[i] += sign * seg.cache[i, j] * seg.t[j]\n end\n end\n v\nend\n\n@inline function velocity!(v, spk::SPK, seg::Segment, sign::Float64, tdb::Float64, tdb2::Float64=0.0)\n recordnum, frac = getrecordnum(seg, tdb, tdb2)\n if recordnum != seg.cached_record\n update_cache!(spk, seg, recordnum)\n end\n chebyshev!(seg, frac)\n velocity!(v, seg, sign)\nend\n\n\n@inline function state!(pos,\n vel,\n spk::SPK,\n seg::Segment,\n sign::Float64,\n tdb::Float64,\n tdb2::Float64=0.0)\n recordnum, frac = getrecordnum(seg, tdb, tdb2)\n if recordnum != seg.cached_record\n update_cache!(spk, seg, recordnum)\n end\n chebyshev!(seg, frac)\n position!(pos, seg, sign)\n velocity!(vel, seg, sign)\n pos, vel\nend\n\n@inline function findsegment(segments, origin, target)\n if !(origin in keys(segments) || target in keys(segments))\n throw(ArgumentError(\"No segment '$origin'->'$target' available.\"))\n end\n sign = 1.0\n if target < origin\n origin, target = target, origin\n sign = -1.0\n end\n segments[origin][target], sign\nend\n\nfunction position!(pos, spk::SPK, ep::Epoch, from::NAIFId, to::NAIFId)\n seg, sign = findsegment(spk.segments, from, to)\n jd1, jd2 = value.(julian_twopart(TDBEpoch(ep)))\n position!(pos, spk, seg, sign, jd1, jd2)\nend\n\nfunction velocity!(vel, spk::SPK, ep::Epoch, from::NAIFId, to::NAIFId)\n seg, sign = findsegment(spk.segments, from, to)\n jd1, jd2 = value.(julian_twopart(TDBEpoch(ep)))\n velocity!(vel, spk, seg, sign, jd1, jd2)\nend\n\nfunction state!(pos, vel, spk::SPK, ep::Epoch, from::NAIFId, to::NAIFId)\n seg, sign = findsegment(spk.segments, from, to)\n jd1, jd2 = value.(julian_twopart(TDBEpoch(ep)))\n state!(pos, vel, spk, seg, sign, jd1, jd2)\nend\n\n", "meta": {"hexsha": "590babed392e54a96a188431ba2e352e0bf9a35a", "size": 7733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spk.jl", "max_stars_repo_name": "KosmosML/JPLEphemeris.jl", "max_stars_repo_head_hexsha": "53fa39c8f30bd235e7504dbbe061ff53ad24c996", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-07-29T03:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T16:03:39.000Z", "max_issues_repo_path": "src/spk.jl", "max_issues_repo_name": "KosmosML/JPLEphemeris.jl", "max_issues_repo_head_hexsha": "53fa39c8f30bd235e7504dbbe061ff53ad24c996", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-05-06T07:22:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T05:47:22.000Z", "max_forks_repo_path": "src/spk.jl", "max_forks_repo_name": "KosmosML/JPLEphemeris.jl", "max_forks_repo_head_hexsha": "53fa39c8f30bd235e7504dbbe061ff53ad24c996", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-05-06T06:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T17:40:27.000Z", "avg_line_length": 27.0384615385, "max_line_length": 101, "alphanum_fraction": 0.6006724428, "num_tokens": 2433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.15947859599039274}} {"text": "\n\"\"\"\n`module JAC.READI` ... a submodel of JAC that contains all methods for computing resonant-excitation Auger double-ionization cross \n sections and rates; it is using JAC, JAC.ManyElectron, JAC.DoubleAuger.\n\"\"\"\nmodule READI \n\n using JAC, JAC.ManyElectron, JAC.DoubleAuger\n\n\n \"\"\"\n `struct READI.Settings` ... defines a type for the details and parameters in computing resonant-excitation Auger double-ionization \n pathways |i(N)> --> |m(N+1)> --> |n(N-1)>.\n\n + electronEnergies ::Array{Float64,1} ... List of impact-energies of the incoming elecgtrons.\n + selectPathways ::Bool ... True if particular pathways are selected for the computations.\n + selectedPathways ::Array{Tuple{Int64,Int64,Int64},1} ... List of list of pathways, given by tupels (inital, inmediate, final).\n + maxKappa ::Int64 ... Maximum kappa value of partial waves to be included.\n \"\"\"\n struct Settings\n electronEnergies ::Array{Float64,1}\n selectPathways ::Bool\n selectedPathways ::Array{Tuple{Int64,Int64,Int64},1}\n maxKappa ::Int64 \n end \n\n\n \"\"\"\n `JAC.READI.Settings()` ... constructor for the default values of resonant-excitation Auger double-ionization settings.\n \"\"\"\n function Settings()\n Settings( Float64[], false, Tuple{Int64,Int64,Int64}[], 0)\n end\n\n\n # `Base.show(io::IO, settings::READI.Settings)` ... prepares a proper printout of the variable settings::READI.Settings. \n function Base.show(io::IO, settings::READI.Settings) \n println(io, \"electronEnergies: $(settings.electronEnergies) \")\n println(io, \"selectPathways: $(settings.selectPathways) \")\n println(io, \"selectedPathways: $(settings.selectedPathways) \")\n println(io, \"maxKappa: $(settings.maxKappa) \")\n end\n\n\n \"\"\"\n `struct READI.Channel` ... defines a type for a resonant-excitation Auger double-ionization channel that specifies \n all quantum numbers, phases and amplitudes.\n\n + excitationChannel ::JAC.ImpactExcitation.Channel ... Channel that describes the electron-impact excitation process.\n + augerChannel1 ::JAC.AutoIonization.Channel ... Channel that describes the first subsequent Auger/autoionization process.\n + augerChannel2 ::JAC.AutoIonization.Channel ... Channel that describes the second Auger/autoionization process.\n \"\"\"\n struct Channel\n excitationChannel ::JAC.ImpactExcitation.Channel\n channel ::JAC.DoubleAuger.Channel\n end \n\n\n \"\"\"\n `struct READI.Pathway` ... defines a type for a resonant-excitation Auger double-ionization pathway that may include\n the definition of different excitation and double Auger channels and their corresponding amplitudes.\n\n + initialLevel ::Level ... initial-(state, N-electron) level\n + intermediateLevel ::Level ... intermediate-(state, N+1 electron) level m\n + finalLevel ::Level ... final-(state, N-1 electron) level\n + electronInEnergy ::Float64 ... energy of the (incoming) electron\n + electronOutEnergy ::Float64 ... energy of the (outgoing, scattered) electron\n + electronAugerEnergy1 ::Float64 ... energy of the (first emitted Auger) electron\n + electronAugerEnergy2 ::Float64 ... energy of the (second emitted Auger) electron\n + crossSection ::Float64 ... total cross section of this pathway\n + hasChannels ::Bool ... Determines whether the indiv. excitation and double autoionization channels are defined in \n terms of their free-electron kappa's, phases and the total angular momentum/parity as well \n as the amplitude, or not.\n + channels ::Array{READI.Channel,1} ... List of channels of this pathway.\n \"\"\"\n struct Pathway\n initialLevel ::Level\n intermediateLevel ::Level\n finalLevel ::Level\n electronInEnergy ::Float64\n electronOutEnergy ::Float64\n electronAugerEnergy1 ::Float64\n electronAugerEnergy2 ::Float64\n crossSection ::Float64 \n hasChannels ::Bool\n channels ::Array{READI.Channel,1}\n end \n\n\n \"\"\"\n `JAC.READI.Pathway()` ... constructor for an electron-impact excitation Auger double ionization pathway between a specified \n initial, intermediate and final level.\n \"\"\"\n function Pathway()\n Pathway(Level(), Level(), Level(), 0., 0., 0., 0., 0., false, READI.Channel[] )\n end\n\n\n # `Base.show(io::IO, pathway::READI.Pathway)` ... prepares a proper printout of the variable pathway::READI.Pathway.\n function Base.show(io::IO, pathway::READI.Pathway) \n println(io, \"initialLevel: $(pathway.initialLevel) \")\n println(io, \"intermediateLevel: $(pathway.intermediateLevel) \")\n println(io, \"finalLevel: $(pathway.finalLevel) \")\n println(io, \"electronInEnergy: $(pathway.electronInEnergy) \")\n println(io, \"electronOutEnergy: $(pathway.electronOutEnergy) \")\n println(io, \"electronAugerEnergy1: $(pathway.electronAugerEnergy1) \")\n println(io, \"electronAugerEnergy2: $(pathway.electronAugerEnergy2) \")\n println(io, \"crossSection: $(pathway.crossSection) \")\n println(io, \"hasChannels: $(pathway.hasChannels) \")\n println(io, \"channels: $(pathway.channels) \")\n end\n\nend # module\n", "meta": {"hexsha": "ff692d38ce0af495a3730f6b4b18d73d32db4bcc", "size": 6055, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-READI.jl", "max_stars_repo_name": "SanjiangYang/JAC.jl", "max_stars_repo_head_hexsha": "f5612dd0912d95da0a22efa1224381606f0012d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-15T11:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T11:27:51.000Z", "max_issues_repo_path": "src/module-READI.jl", "max_issues_repo_name": "Zstar95/JAC.jl", "max_issues_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-READI.jl", "max_forks_repo_name": "Zstar95/JAC.jl", "max_forks_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-30T13:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T13:09:52.000Z", "avg_line_length": 53.1140350877, "max_line_length": 144, "alphanum_fraction": 0.5895953757, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.1593925943174445}} {"text": "\n\"\"\"\n`module JAC.Atomic` \n ... a submodel of JAC that contains all methods to set-up and process (simple) atomic and SCF computations as well as \n atomic representations.\n\"\"\"\nmodule Atomic\n\n ## using Interact\n using ..Basics, ..Radial, ..ManyElectron, ..Nuclear\n using ..Einstein, ..Hfs, ..IsotopeShift, ..PlasmaShift, ..LandeZeeman, ..AlphaVariation, ..FormFactor, ..DecayYield,\n ..MultipolePolarizibility, ..PhotoEmission, ..PhotoIonization, ..PhotoExcitation, ..PhotoRecombination, \n ..AutoIonization, ..DoubleAutoIonization, ..Dielectronic, ..ImpactExcitation, ..CoulombExcitation, ..CoulombIonization,\n ..PhotoDoubleIonization, ..PhotoExcitationFluores, ..PhotoExcitationAutoion, ..RayleighCompton, ..MultiPhotonDeExcitation,\n ..PhotoIonizationFluores, ..PhotoIonizationAutoion, ..ImpactExcitationAutoion, ..RadiativeAuger, \n ..MultiPhotonIonization, ..MultiPhotonDoubleIon, ..InternalConversion\n\n \n \"\"\"\n `struct Computation` \n ... defines a type for defining (the model of simple) atomic computation of a single multiplet, \n including the SCF and CI as well as level properties and transition property calculations.\n\n + name ::String ... A name associated to the computation.\n + nuclearModel ::Nuclear.Model ... Model, charge and parameters of the nucleus.\n + grid ::Radial.Grid ... The radial grid to be used for the computation.\n + properties ::Array{AbstractLevelProperty,1} ... List of atomic properties to be calculated.\n + configs ::Array{Configuration,1} ... A list of non-relativistic configurations.\n + asfSettings ::AsfSettings \n ... Provides the settings for the SCF process and for the CI and QED calculations.\n + initialConfigs ::Array{Configuration,1} \n ... A list of initial-state configurations for some transition property calculation, such as radiative transition, Auger, etc. \n + initialAsfSettings ::AsfSettings ... Provides the SCF and CI settings for the initial-state multiplet.\n + intermediateConfigs ::Array{Configuration,1} ... A list of initial-state configurations.\n + intermediateAsfSettings ::AsfSettings ... Provides the SCF settings for the intermediate-state multiplet.\n + finalConfigs ::Array{Configuration,1} ... A list of final-state configurations.\n + finalAsfSettings ::AsfSettings ... Provides the SCF and CI settings for the final-state multiplet.\n + alphaSettings ::AlphaVariation.Settings ... Settings for alpha-variation parameter calculations.\n + einsteinSettings ::Einstein.Settings ... Settings for Einstein coefficient calculations.\n + formSettings ::FormFactor.Settings ... Settings for atomic form factor calculations.\n + hfsSettings ::Hfs.Settings ... Settings for hyperfine parameter calculations.\n + isotopeSettings ::IsotopeShift.Settings ... Settings for isotope shift parameter calculations.\n + plasmaSettings ::PlasmaShift.Settings ... Settings for plasma-shift calculations.\n + polaritySettings ::MultipolePolarizibility.Settings .. Settings for polarizibility calculations.\n + yieldSettings ::DecayYield.Settings ... Settings for fluoresence and Auger yield calculations.\n + zeemanSettings ::LandeZeeman.Settings ... Settings for Lande-Zeeman coefficient calculations.\n + process ::Basic.AbstractProcess \n ... An (additional) process for which the properties are to be evaluated for the given initial- and final-state configurations.\n + processSettings ::Union{PhotoEmission.Settings, AutoIonization.Settings, PlasmaShift.AugerSettings, \n PhotoIonization.Settings, PlasmaShift.PhotoSettings, \n PhotoExcitation.Settings, PhotoExcitationAutoion.Settings, PhotoRecombination.Settings, \n DoubleAutoIonization.Settings, PhotoDoubleIonization.Settings,\n ImpactExcitation.Settings, Dielectronic.Settings, RadiativeAuger.Settings,\n PairAnnihilation1Photon.Settings, ImpactExcitationAutoion.Settings, \n MultiPhotonDeExcitation.Settings, CoulombExcitation.Settings, \n CoulombIonization.Settings} \n ... Provides the settings for the selected process.\n \"\"\"\n struct Computation\n name ::String\n nuclearModel ::Nuclear.Model\n grid ::Radial.Grid\n properties ::Array{AbstractLevelProperty,1}\n configs ::Array{Configuration,1}\n asfSettings ::AsfSettings\n initialConfigs ::Array{Configuration,1} \n initialAsfSettings ::AsfSettings\n intermediateConfigs ::Array{Configuration,1} \n intermediateAsfSettings ::AsfSettings\n finalConfigs ::Array{Configuration,1}\n finalAsfSettings ::AsfSettings\n alphaSettings ::AlphaVariation.Settings\n einsteinSettings ::Einstein.Settings\n formSettings ::FormFactor.Settings\n hfsSettings ::Hfs.Settings\n isotopeSettings ::IsotopeShift.Settings\n plasmaSettings ::PlasmaShift.Settings\n polaritySettings ::MultipolePolarizibility.Settings\n yieldSettings ::DecayYield.Settings\n zeemanSettings ::LandeZeeman.Settings\n process ::AbstractProcess\n processSettings ::Union{PhotoEmission.Settings, AutoIonization.Settings, PlasmaShift.AugerSettings, \n PhotoIonization.Settings, PlasmaShift.PhotoSettings,\n PhotoRecombination.Settings, Dielectronic.Settings, ImpactExcitation.Settings,\n CoulombExcitation.Settings, CoulombIonization.Settings, \n PhotoExcitation.Settings, PhotoExcitationFluores.Settings, \n PhotoExcitationAutoion.Settings, RayleighCompton.Settings, \n DoubleAutoIonization.Settings, PhotoDoubleIonization.Settings,\n MultiPhotonDeExcitation.Settings, PhotoIonizationFluores.Settings, \n PhotoIonizationAutoion.Settings, ImpactExcitationAutoion.Settings,\n RadiativeAuger.Settings, MultiPhotonIonization.Settings,\n MultiPhotonDoubleIon.Settings, InternalConversion.Settings} #= , \n #\n PairAnnihilation1Photon.Settings } =#\n end \n\n\n \"\"\"\n `Atomic.Computation()` ... constructor for an 'empty' instance::Atomic.Computation.\n \"\"\"\n function Computation()\n Computation(\"\", Nuclear.Model(1.), Radial.Grid(), AbstractLevelProperty[], \n Configuration[], AsfSettings(),\n Configuration[], AsfSettings(),\n Configuration[], AsfSettings(),\n Configuration[], AsfSettings(),\n AlphaVariation.Settings(), Einstein.Settings(), FormFactor.Settings(), Hfs.Settings(), IsotopeShift.Settings(), \n PlasmaShift.Settings(), MultipolePolarizibility.Settings(), DecayYield.Settings(), LandeZeeman.Settings(), \n Basics.NoProcess(), PhotoEmission.Settings() )\n end\n\n \n \"\"\"\n `Atomic.Computation(comp::Atomic.Computation;`\n \n name=.., nuclearModel=.., grid=.., configs=.., asfSettings=.., \n initialConfigs=.., initialAsfSettings=.., intermediateConfigs=.., intermediateAsfSettings=.., \n finalConfigs=.., finalAsfSettings=.., alphaSettings=.., einsteinSettings=.., \n formSettings=.., hfsSettings=.., isotopeSettings=.., plasmaSettings=..,\n polaritySettings=.., yieldSettings::=.., zeemanSettings=..,\n process=.., processSettings=.., printout::Bool=false)\n \n ... constructor for modifying the given Atomic.Computation by 'overwriting' the previously selected parameters.\n \"\"\"\n function Computation(comp::Atomic.Computation;\n name::Union{Nothing,String}=nothing, nuclearModel::Union{Nothing,Nuclear.Model}=nothing,\n grid::Union{Nothing,Radial.Grid}=nothing, properties::Union{Nothing,Array{AbstractLevelProperty,1},Any}=nothing, \n configs::Union{Nothing,Array{Configuration,1}}=nothing, asfSettings::Union{Nothing,AsfSettings}=nothing, \n initialConfigs::Union{Nothing,Array{Configuration,1}}=nothing, initialAsfSettings::Union{Nothing,AsfSettings}=nothing, \n intermediateConfigs::Union{Nothing,Array{Configuration,1}}=nothing, intermediateAsfSettings::Union{Nothing,AsfSettings}=nothing, \n finalConfigs::Union{Nothing,Array{Configuration,1}}=nothing, finalAsfSettings::Union{Nothing,AsfSettings}=nothing, \n alphaSettings::Union{Nothing,AlphaVariation.Settings}=nothing, einsteinSettings::Union{Nothing,Einstein.Settings}=nothing, \n formSettings::Union{Nothing,FormFactor.Settings}=nothing, hfsSettings::Union{Nothing,Hfs.Settings}=nothing,\n isotopeSettings::Union{Nothing,IsotopeShift.Settings}=nothing, plasmaSettings::Union{Nothing,PlasmaShift.Settings}=nothing, \n polaritySettings::Union{Nothing,MultipolePolarizibility.Settings}=nothing, yieldSettings::Union{Nothing,DecayYield.Settings}=nothing, \n zeemanSettings::Union{Nothing,LandeZeeman.Settings}=nothing, \n process::Union{Nothing,Basics.AbstractProcess}=nothing, processSettings::Union{Nothing,Any}=nothing, \n printout::Bool=false)\n \n if name == nothing namex = comp.name else namex = name end \n if nuclearModel == nothing nuclearModelx = comp.nuclearModel else nuclearModelx = nuclearModel end \n if grid == nothing gridx = comp.grid else gridx = grid end \n if properties == nothing propertiesx = comp.properties else propertiesx = properties end \n if configs == nothing configsx = comp.configs else configsx = configs end \n if asfSettings == nothing asfSettingsx = comp.asfSettings else asfSettingsx = asfSettings end \n if initialConfigs == nothing initialConfigsx = comp.initialConfigs else initialConfigsx = initialConfigs end \n if initialAsfSettings == nothing initialAsfSettingsx = comp.initialAsfSettings else initialAsfSettingsx = initialAsfSettings end \n if intermediateConfigs == nothing intermediateConfigsx = comp.intermediateConfigs else intermediateConfigsx = intermediateConfigs end \n if intermediateAsfSettings == nothing intermediateAsfSettingsx = comp.intermediateAsfSettings else intermediateAsfSettingsx = intermediateAsfSettings end \n if finalConfigs == nothing finalConfigsx = comp.finalConfigs else finalConfigsx = finalConfigs end \n if finalAsfSettings == nothing finalAsfSettingsx = comp.finalAsfSettings else finalAsfSettingsx = finalAsfSettings end \n if alphaSettings == nothing alphaSettingsx = comp.alphaSettings else alphaSettingsx = alphaSettings end \n if einsteinSettings == nothing einsteinSettingsx = comp.einsteinSettings else einsteinSettingsx = einsteinSettings end \n if formSettings == nothing formSettingsx = comp.formSettings else formSettingsx = formSettings end \n if hfsSettings == nothing hfsSettingsx = comp.hfsSettings else hfsSettingsx = hfsSettings end \n if isotopeSettings == nothing isotopeSettingsx = comp.isotopeSettings else isotopeSettingsx = isotopeSettings end \n if plasmaSettings == nothing plasmaSettingsx = comp.plasmaSettings else plasmaSettingsx = plasmaSettings end \n if polaritySettings == nothing polaritySettingsx = comp.polaritySettings else polaritySettingsx = polaritySettings end \n if yieldSettings == nothing yieldSettingsx = comp.yieldSettings else yieldSettingsx = yieldSettings end \n if zeemanSettings == nothing zeemanSettingsx = comp.zeemanSettings else zeemanSettingsx = zeemanSettings end \n if process == nothing processx = comp.process else processx = process end \n if processSettings == nothing prsx = comp.processSettings else prsx = processSettings end \n \n if processx == Basics.NoProcess prsx = PhotoEmission.Settings()\n elseif processx == Basics.Auger && typeof(prsx) != AutoIonization.Settings prsx = AutoIonization.Settings()\n elseif processx == Basics.AugerInPlasma && typeof(prsx) != PlasmaShift.AugerSettings prsx = PlasmaShift.AugerSettings()\n elseif processx == Basics.Radiative && typeof(prsx) != PhotoEmission.Settings prsx = PhotoEmission.Settings()\n elseif processx == Basics.PhotoExc && typeof(prsx) != PhotoExcitation.Settings prsx = PhotoExcitation.Settings()\n elseif process == Basics.Photo && typeof(prsx) != PhotoIonization.Settings prsx = PhotoIonization.Settings()\n elseif process == Basics.PhotoInPlasma && typeof(prsx) != PlasmaShift.PhotoSettings prsx = PlasmaShift.PhotoSettings()\n elseif process == Basics.Rec && typeof(prsx) != PhotoRecombination.Settings prsx = PhotoRecombination.Settings()\n elseif process == Basics.Dierec && typeof(prsx) != Dielectronic.Settings prsx = Dielectronic.Settings()\n elseif process == Basics.PhotoExcFluor && typeof(prsx) != PhotoExcitationFluores.Settings prsx = PhotoExcitationFluores.Settings()\n elseif process == Basics.PhotoExcAuto && typeof(prsx) != PhotoExcitationAutoion.Settings prsx = PhotoExcitationAutoion.Settings()\n elseif process == Basics.PhotoIonFluor && typeof(prsx) != PhotoIonizationFluores.Settings prsx = PhotoIonizationFluores.Settings()\n elseif process == Basics.PhotoIonAuto && typeof(prsx) != PhotoIonizationAutoion.Settings prsx = PhotoIonizationAutoion.Settings()\n elseif process == Basics.MultiPhotonDE && typeof(prsx) != MultiPhotonDeExcitation.Settings prsx = MultiPhotonDeExcitation.Settings()\n elseif process == Basics.Compton && typeof(prsx) != RayleighCompton.Settings prsx = RayleighCompton.Settings()\n elseif process == Basics.Eimex && typeof(prsx) != ImpactExcitation.Settings prsx = ImpactExcitation.Settings()\n elseif process == Basics.ImpactExcAuto && typeof(prsx) != ImpactExcitationAutoion.Settings prsx = ImpactExcitationAutoion.Settings()\n elseif process == Basics.RAuger && typeof(prsx) != RadiativeAuger.Settings prsx = RadiativeAuger.Settings()\n elseif process == Basics.MultiPI && typeof(prsx) != MultiPhotonIonization.Settings prsx = MultiPhotonIonization.Settings()\n elseif process == Basics.MultiPDI && typeof(prsx) != MultiPhotonDoubleIon.Settings prsx = MultiPhotonDoubleIon.Settings()\n elseif process == Basics.InternalConv && typeof(prsx) != InternalConversion.Settings prsx = InternalConversion.Settings()\n elseif process == Basics.Coulex && typeof(prsx) != CoulombExcitation.Settings prsx = CoulombExcitation.Settings()\n elseif process == Basics.Coulion && typeof(prsx) != CoulombIonization.Settings prsx = CoulombIonization.Settings()\n end\n \n cp = Computation(namex, nuclearModelx, gridx, propertiesx, configsx, asfSettingsx, initialConfigsx, initialAsfSettingsx, \n intermediateConfigsx, intermediateAsfSettingsx, finalConfigsx, finalAsfSettingsx, \n alphaSettingsx, einsteinSettingsx , formSettingsx, hfsSettingsx, isotopeSettingsx, plasmaSettingsx,\n polaritySettingsx, yieldSettingsx, zeemanSettingsx, processx, prsx) \n \n if printout Base.show(cp) end\n return( cp )\n end\n\n \n \"\"\"\n `Atomic.Computation( ... example for SCF computations)` \n \n grid = Radial.Grid(true)\n nuclearM = Nuclear.Model(18., \"Fermi\")\n settings = AsfSettings(AsfSettings(), selectLevelsCI = true, selectedLevelsCI = [1,2, 4,5, 7,8], jjLS = LSjjSettings(false) )\n configs = [Configuration(\"[Ne] 3s^2 3p^5\"), Configuration(\"[Ne] 3s 3p^6\")]\n Atomic.Computation(Atomic.Computation(), name=\"Example\", grid=grid, nuclearModel=nuclearM, configs=configs, asfSettings=settings )\n \n `Atomic.Computation( ... example for the computation of atomic properties)` \n \n grid = Radial.Grid(true)\n nuclearM = Nuclear.Model(26., \"Fermi\", 58., 3.81, AngularJ64(5//2), 1.0, 1.0)\n hfsSettings = Hfs.Settings(true, true, false, false, false, false, false, Int64[] )\n configs = [Configuration(\"[Ne] 3s\"), Configuration(\"[Ne] 3p\"), Configuration(\"[Ne] 3d\")]\n Atomic.Computation(Atomic.Computation(), name=\"Example\", grid=grid, nuclearModel=nuclearM, configs=configs, properties=[HFS()],\n hfsSettings=hfsSettings )\n \n `Atomic.Computation( ... example for the computation of one atomic process)` \n \n grid = Radial.Grid(true)\n initialConfigs = [Configuration(\"[Ne] 3s 3p^6\"), Configuration(\"[Ne] 3s^2 3p^4 3d\")]\n finalConfigs = [Configuration(\"[Ne] 3s^2 3p^5\")] \n photoSettings = PhotoEmission.Settings(PhotoEmission.Settings(), multipoles=[E1, M1], gauges=[UseCoulomb], printBefore=true)\n Atomic.Computation(Atomic.Computation(), name=\"Example\", grid=grid, nuclearModel=nuclearM;\n initialConfigs=initialConfigs, finalConfigs=finalConfigs, \n process = Radiative(), processSettings=photoSettings ); \n \n ... These simple examples can be further improved by overwriting the corresponding parameters.\n \"\"\"\n function Computation(wa::Bool) \n Atomic.Computation() \n end\n\n\n # `Base.string(comp::Atomic.Computation)` ... provides a String notation for the variable comp::Atomic.Computation.\n function Base.string(comp::Atomic.Computation)\n sa = \"Atomic computation: $(comp.name) for Z = $(comp.nuclearModel.Z), \"\n if comp.process != NoProcess sa = sa * \"for the process $(comp.process) and with the \\ninitial configurations: \"\n for config in comp.initialConfigs sa = sa * string(config) * \", \" end\n if length(comp.intermediateConfigs) > 0\n sa = sa * \"\\nintermediate configurations:\"\n for config in comp.finalConfigs sa = sa * string(config) * \", \" end\n end\n sa = sa * \"\\nfinal configurations: \"\n for config in comp.finalConfigs sa = sa * string(config) * \", \" end\n else sa = sa * \"for the properties $(comp.properties) and with the \\nconfigurations: \"\n for config in comp.configs sa = sa * string(config) * \", \" end\n end\n return( sa )\n end\n\n\n # `Base.show(io::IO, comp::Atomic.Computation)` ... prepares a printout of comp::Atomic.Computation.\n function Base.show(io::IO, comp::Atomic.Computation)\n sa = Base.string(comp); print(io, sa, \"\\n\")\n println(io, \"nuclearModel: $(comp.nuclearModel) \")\n println(io, \"grid: $(comp.grid) \")\n #\n # For the computation of some given atomic process\n if comp.process != NoProcess \n println(io, \"processSettings: \\n$(comp.processSettings) \")\n if comp.initialAsfSettings != AsfSettings() \n println(io, \"initialAsfSettings: \\n$(comp.initialAsfSettings) \") end\n if comp.intermediateAsfSettings != AsfSettings() \n println(io, \"intermediateAsfSettings: \\n$(comp.intermediateAsfSettings) \") end\n if comp.finalAsfSettings != AsfSettings() \n println(io, \"finalAsfSettings: \\n$(comp.finalAsfSettings) \") end\n #\n else\n # For the computation of no or several atomic properties\n if comp.asfSettings != AsfSettings() \n println(io, \"asfSettings: \\n$(comp.asfSettings) \") end\n if AlphaX in comp.properties && comp.alphaSettings != AlphaVariation.Settings()\n println(io, \"alphaSettings: \\n$(comp.alphaSettings) \") end\n if EinsteinX in comp.properties && comp.einsteinSettings != Einstein.Settings()\n println(io, \"einsteinSettings: \\n$(comp.einsteinSettings) \") end\n if FormF in comp.properties && comp.formSettings != FormFactor.Settings()\n println(io, \"formSettings: \\n$(comp.formSettings) \") end\n if HFS in comp.properties && comp.hfsSettings != Hfs.Settings()\n println(io, \"hfsSettings: \\n$(comp.hfsSettings) \") end\n if Isotope in comp.properties && comp.isotopeSettings != IsotopeShift.Settings()\n println(io, \"isotopeSettings: \\n$(comp.isotopeSettings) \") end\n if Plasma in comp.properties && comp.plasmaSettings != PlasmaShift.Settings()\n println(io, \"plasmaSettings: \\n$(comp.plasmaSettings) \") end\n if Polarity in comp.properties && comp.polaritySettings != MultipolePolarizibility.Settings()\n println(io, \"polaritySettings: \\n$(comp.polaritySettings) \") end\n if Yields in comp.properties && comp.yieldSettings != DecayYield.Settings()\n println(io, \"yieldSettings: \\n$(comp.yieldSettings) \") end\n if Zeeman in comp.properties && comp.zeemanSettings != LandeZeeman.Settings()\n println(io, \"zeemanSettings: \\n$(comp.zeemanSettings) \") end\n end\n end\n\nend # module\n", "meta": {"hexsha": "b1189c00226c0b5bb91b01c565ff0a3b254da701", "size": 25214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-Atomic.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-Atomic.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module-Atomic.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.7619047619, "max_line_length": 166, "alphanum_fraction": 0.571626874, "num_tokens": 5120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.23934933647101647, "lm_q1q2_score": 0.15926557571685826}} {"text": "#\n# Use git: git status ....; git add ; git commit -m \"..\"; git push; git rm \n# Use Jupyter notebooks: using IJulia; notebook()\n# Activation: ]; pkg> up; pkg> activate\n# Working with JAC: using Revise; using JAC; include(\"../src/jac.jl\"); pkg> test\n#\n\"\"\"\n`module JAC` \n ... Jena Atomic Calculator (JAC) provides tools for performing atomic (structure) calculations at various degrees of complexity \n and sophistication. It has been designed to not only calculate atomic level structures and properties [such as g-factors or\n hyperfine and isotope-shift parameters] but also transition amplitudes between bound-state levels [for the anapole moment, dipole \n operator, electron electric-dipole moment, parity non-conservation, etc.] and, in particular, (atomic) transition probabilities, \n Auger rates, photoionization cross sections, radiative and dielectronic recombination rates as well as cross sections for many \n other (elementary) processes. In the future, JAC will also facilitate interactive computations, the simulation of atomic cascades, \n the time-evolution of statistical tensors as well as various semi-empirical estimates of atomic properties. -- \n In addition, the JAC module supports the display of level energies, electron and photon spectra, radial orbitals and \n and other atomic data.\n\n\n**`Perform (atomic) computations of different complexity:`** \n JAC will eventually support **eight kinds** of computations which can be summarized as follows:\n\n + Atomic computations, based on explicitly specified electron configurations.\n + Restricted active-space computations (RAS; not yet properly implemented).\n + Interactive computations.\n + Atomic cascade computations (not yet fully implemented).\n + Atomic responses (not yet implemented).\n + Time-evolution of statistical tensors in (intense) light pusles (not yet implemented).\n + Semi-empirical estimates of cross sections, etc. (not yet properly implemented).\n + Symbolic evaluation of expressions from Racah's algebra, etc. (not yet properly implemented).\n\n\n**`Further details and information`**\n\n + Kinds of atomic implementation [cf. ? Details.kindsOfComputation]\n + Atomic amplitudes (partly) implemented in JAC [cf. ? Details.amplitudes]\n + Atomic level properties (partly) implemented in JAC [cf. ? Details.properties]\n + Atomic processes (partly) implemented in JAC [cf. ? Details.processes]\n + Interactive use of JAC procedures [cf. ? Details.interactive]\n + Design principles and limitations of the JAC program [cf. ? Details.design]\n + Data types, structs and name conventions of the JAC module [cf. ? Details.datatypes]\n + Atomic cascade computations and approximations [cf. ? Details.decayCascades]\n + Use of (em) light pulses in the time evolution of statist. tensors [cf. ? Details.pulses]\n + Why Julia ? [cf. ? Details.whyJulia]\n\n\"\"\"\nmodule JAC\n\nusing Dates, Printf, LinearAlgebra, Interact, SpecialFunctions, FortranFiles, GaussQuadrature, QuadGK, GSL, JLD\n\nexport @racahsum, \n add, analyze, AlphaVariation, AnapoleMoment, AngularJ64, AngularM64, AngularJ, AngularMomentum, \n AsfSettings, Atomic, Auger, AutoIonization, \n Basics, Basis, \n compute, convertUnits, Cascade, Configuration, ConfigurationR, Continuum, CsfR, CoulombExcitation, CoulombIonization, \n diagonalize, Defaults, DecayYield, Details, Dielectronic, DoubleAuger,\n estimate, ElectricDipoleMoment, Einstein, EmMultipole, \n E1, M1, E2, M2, E3, M3, E4, M4,\n FormFactor,\n generate, Green, GreenFunction, getDefaults, Gui,\n Hfs, HydrogenicIon,\n interpolate, integrate, ImpactExcitation, ImpactExcitationAutoion, ImpactIonization, InternalConversion, IsotopeShift, \n LandeZeeman, Level, LevelSymmetry, LSjj, LSjjSettings,\n ManyElectron, Model, modify, MultiPhotonDeExcitation, MultiPhotonDoubleIon, MultiPhotonIonization, MultipoleMoment, \n MultipolePolarizibility, Multiplet, \n NoAmplitude, NoProcess, Nuclear, NoneQed,\n Orbital, \n perform, provide, PairAnnihilation1Photon, PairAnnihilation2Photon, PairProduction, ParityNonConservation,\n PhotoEmission, PhotoExcitation, PhotoExcitationAutoion, PhotoExcitationFluores, PhotoIonization, PhotoIonizationFluores, \n PhotoIonizationAutoion, PhotoRecombination, PlasmaShift,\n QedPetersburg, QedSydney,\n Radial, RadialIntegrals, Radiative, RadiativeAuger, RayleighCompton, REDA, READI,\n SchiffMoment, Shell, Subshell, setDefaults,\n tabulate, tools,\n UseCoulomb, UseBabushkin, UseGauge\n \n# Basic data and data structures\ninclude(\"module-Basics.jl\")\ninclude(\"module-Radial.jl\")\ninclude(\"module-Math.jl\")\ninclude(\"module-Defaults.jl\")\ninclude(\"module-ManyElectron.jl\")\ninclude(\"module-Nuclear.jl\")\n\n# Specialized functions/methods to manipulate these data\ninclude(\"module-AngularMomentum.jl\")\ninclude(\"module-AngularCoefficients-Ratip2013.jl\")\ninclude(\"module-Bsplines.jl\")\ninclude(\"module-Continuum.jl\")\ninclude(\"module-Details.jl\")\ninclude(\"module-RadialIntegrals.jl\")\ninclude(\"module-HydrogenicIon.jl\")\ninclude(\"module-InteractionStrength.jl\")\ninclude(\"module-InteractionStrengthQED.jl\")\ninclude(\"module-PeriodicTable.jl\")\ninclude(\"module-TableStrings.jl\")\ninclude(\"module-Tools.jl\")\ninclude(\"module-LSjj.jl\")\n\n# Functions/methods for atomic amplitudes\ninclude(\"module-MultipoleMoment.jl\")\ninclude(\"module-ParityNonConservation.jl\") \n\ninclude(\"module-PhotoEmission.jl\")\n\n# Functions/methods for atomic properties\ninclude(\"module-Einstein.jl\") \ninclude(\"module-Hfs.jl\")\ninclude(\"module-IsotopeShift.jl\")\ninclude(\"module-LandeZeeman.jl\")\ninclude(\"module-AlphaVariation.jl\")\ninclude(\"module-FormFactor.jl\")\ninclude(\"module-DecayYield.jl\")\ninclude(\"module-GreenFunction.jl\")\ninclude(\"module-MultipolePolarizibility.jl\")\ninclude(\"module-PlasmaShift.jl\")\n\n# Functions/methods for atomic processes\ninclude(\"module-PhotoExcitation.jl\")\ninclude(\"module-PhotoIonization.jl\")\ninclude(\"module-PhotoRecombination.jl\")\ninclude(\"module-AutoIonization.jl\")\ninclude(\"module-Dielectronic.jl\")\ninclude(\"module-PhotoExcitationFluores.jl\")\ninclude(\"module-PhotoExcitationAutoion.jl\")\ninclude(\"module-RayleighCompton.jl\")\ninclude(\"module-MultiPhotonDeExcitation.jl\")\ninclude(\"module-CoulombExcitation.jl\")\ninclude(\"module-PhotoIonizationFluores.jl\")\ninclude(\"module-PhotoIonizationAutoion.jl\")\ninclude(\"module-CoulombIonization.jl\")\ninclude(\"module-ImpactExcitation.jl\")\ninclude(\"module-ImpactExcitationAutoion.jl\")\ninclude(\"module-RadiativeAuger.jl\")\ninclude(\"module-MultiPhotonIonization.jl\")\ninclude(\"module-MultiPhotonDoubleIon.jl\")\ninclude(\"module-InternalConversion.jl\") ## up to here + up to jac-tools\n#= Further processes, not yet included into the code\ninclude(\"module-DoubleAuger.jl\")\ninclude(\"module-REDA.jl\")\ninclude(\"module-READI.jl\")\ninclude(\"module-PairProduction.jl\")\ninclude(\"module-PairAnnihilation1Photon.jl\")\ninclude(\"module-PairAnnihilation2Photon.jl\") =#\n\n# Functions/methods for atomic and cascade computations\ninclude(\"module-Atomic.jl\")\ninclude(\"module-Cascade.jl\")\n\n# Functions/methods for atomic time evolutions\n# include(\"module-Pulse.jl\")\n# include(\"module-Statistical.jl\")\n\n# Functions/methods for semi-empirical estimations\n# include(\"module-ImpactIonization.jl\")\n# include(\"module-Semiempirical.jl\")\n\n# Functions/methods for symbolic computations\n# include(\"module-Racah.jl\")\n\n# Basic functions/methods to manipulate these data\ninclude(\"inc-module-Basics.jl\")\n\n# Specialized macros\ninclude(\"macro-racahsum.jl\")\n\n# All test functions/methods stay with the JAC root module\ninclude(\"jac-test.jl\")\n \nfunction __init__()\n # The following variables need to be initialized at runtime to enable precompilation\n global JAC_SUMMARY_IOSTREAM = stdout\n global JAC_TEST_IOSTREAM = stdout\nend\n\nprintln(\"\\nWelcome to JAC: A fresh computational approach to atomic structures, processes, casacdes and time evolutions [(C) Copyright by Stephan Fritzsche, Jena (2019)].\")\n\nend\n\n\n", "meta": {"hexsha": "be17548cfd4a82f3bc3b168961b70c9db69db9ad", "size": 8426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JAC.jl", "max_stars_repo_name": "Zstar95/JAC.jl", "max_stars_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-15T11:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T11:27:51.000Z", "max_issues_repo_path": "src/JAC.jl", "max_issues_repo_name": "Zstar95/JAC.jl", "max_issues_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JAC.jl", "max_forks_repo_name": "Zstar95/JAC.jl", "max_forks_repo_head_hexsha": "46d5ca43257247bb2cf4cbc90df2218c039418ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5524861878, "max_line_length": 173, "alphanum_fraction": 0.7296463328, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.2974699301485223, "lm_q1q2_score": 0.15917569659694725}} {"text": "struct DGModel{BL,G,NFND,NFD,GNF,AS,DS,D,MD}\n balancelaw::BL\n grid::G\n numfluxnondiff::NFND\n numfluxdiff::NFD\n gradnumflux::GNF\n auxstate::AS\n diffstate::DS\n direction::D\n modeldata::MD\nend\nfunction DGModel(balancelaw, grid, numfluxnondiff, numfluxdiff, gradnumflux;\n auxstate=create_auxstate(balancelaw, grid),\n diffstate=create_diffstate(balancelaw, grid),\n direction=EveryDirection(), modeldata=nothing)\n DGModel(balancelaw, grid, numfluxnondiff, numfluxdiff, gradnumflux, auxstate,\n diffstate, direction, modeldata)\nend\n\nfunction (dg::DGModel)(dQdt, Q, ::Nothing, t; increment=false)\n bl = dg.balancelaw\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n Nfp = Nq * Nqk\n nrealelem = length(topology.realelems)\n\n Qvisc = dg.diffstate\n auxstate = dg.auxstate\n\n FT = eltype(Q)\n nviscstate = num_diffusive(bl, FT)\n\n lgl_weights_vec = grid.ω\n Dmat = grid.D\n vgeo = grid.vgeo\n sgeo = grid.sgeo\n vmapM = grid.vmapM\n vmapP = grid.vmapP\n elemtobndy = grid.elemtobndy\n polyorder = polynomialorder(dg.grid)\n\n Np = dofs_per_element(grid)\n\n communicate = !(isstacked(topology) &&\n typeof(dg.direction) <: VerticalDirection)\n\n aux_comm = update_aux!(dg, bl, Q, t)\n @assert typeof(aux_comm) == Bool\n\n ########################\n # Gradient Computation #\n ########################\n if communicate\n MPIStateArrays.start_ghost_exchange!(Q)\n if aux_comm\n MPIStateArrays.start_ghost_exchange!(auxstate)\n end\n end\n\n if nviscstate > 0\n\n @launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,\n volumeviscterms!(bl, Val(dim), Val(polyorder), dg.direction, Q.data,\n Qvisc.data, auxstate.data, vgeo, t, Dmat,\n topology.realelems))\n\n if communicate\n MPIStateArrays.finish_ghost_recv!(Q)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n end\n\n @launch(device, threads=Nfp, blocks=nrealelem,\n faceviscterms!(bl, Val(dim), Val(polyorder), dg.direction,\n dg.gradnumflux, Q.data, Qvisc.data, auxstate.data,\n vgeo, sgeo, t, vmapM, vmapP, elemtobndy,\n topology.realelems))\n\n if communicate\n MPIStateArrays.start_ghost_exchange!(Qvisc)\n end\n\n aux_comm = update_aux_diffusive!(dg, bl, Q, t)\n @assert typeof(aux_comm) == Bool\n\n if aux_comm\n MPIStateArrays.start_ghost_exchange!(auxstate)\n end\n end\n\n\n ###################\n # RHS Computation #\n ###################\n @launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,\n volumerhs!(bl, Val(dim), Val(polyorder), dg.direction, dQdt.data,\n Q.data, Qvisc.data, auxstate.data, vgeo, t,\n lgl_weights_vec, Dmat, topology.realelems, increment))\n\n if communicate\n if nviscstate > 0\n MPIStateArrays.finish_ghost_recv!(Qvisc)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n else\n MPIStateArrays.finish_ghost_recv!(Q)\n if aux_comm\n MPIStateArrays.finish_ghost_recv!(auxstate)\n end\n end\n end\n\n @launch(device, threads=Nfp, blocks=nrealelem,\n facerhs!(bl, Val(dim), Val(polyorder), dg.direction,\n dg.numfluxnondiff,\n dg.numfluxdiff,\n dQdt.data, Q.data, Qvisc.data,\n auxstate.data, vgeo, sgeo, t, vmapM, vmapP, elemtobndy,\n topology.realelems))\n\n # Just to be safe, we wait on the sends we started.\n if communicate\n MPIStateArrays.finish_ghost_send!(Qvisc)\n MPIStateArrays.finish_ghost_send!(Q)\n end\nend\n\nfunction init_ode_state(dg::DGModel, args...;\n forcecpu=false,\n commtag=888)\n device = arraytype(dg.grid) <: Array ? CPU() : CUDA()\n\n bl = dg.balancelaw\n grid = dg.grid\n\n state = create_state(bl, grid, commtag)\n\n topology = grid.topology\n Np = dofs_per_element(grid)\n\n auxstate = dg.auxstate\n dim = dimensionality(grid)\n polyorder = polynomialorder(grid)\n vgeo = grid.vgeo\n nrealelem = length(topology.realelems)\n\n if !forcecpu\n @launch(device, threads=(Np,), blocks=nrealelem,\n initstate!(bl, Val(dim), Val(polyorder), state.data, auxstate.data, vgeo,\n topology.realelems, args...))\n else\n h_vgeo = Array(vgeo)\n h_state = similar(state, Array)\n h_auxstate = similar(auxstate, Array)\n h_auxstate .= auxstate\n @launch(CPU(), threads=(Np,), blocks=nrealelem,\n initstate!(bl, Val(dim), Val(polyorder), h_state.data, h_auxstate.data, h_vgeo,\n topology.realelems, args...))\n state .= h_state\n end\n\n MPIStateArrays.start_ghost_exchange!(state)\n MPIStateArrays.finish_ghost_exchange!(state)\n\n return state\nend\n\nfunction indefinite_stack_integral!(dg::DGModel, m::BalanceLaw,\n Q::MPIStateArray, auxstate::MPIStateArray,\n t::Real)\n\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n FT = eltype(Q)\n\n vgeo = grid.vgeo\n polyorder = polynomialorder(dg.grid)\n\n # do integrals\n nintegrals = num_integrals(m, FT)\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,\n knl_indefinite_stack_integral!(m, Val(dim), Val(polyorder),\n Val(nvertelem), Q.data, auxstate.data,\n vgeo, grid.Imat, 1:nhorzelem,\n Val(nintegrals)))\nend\n\n# fallback\nfunction update_aux!(dg::DGModel, bl::BalanceLaw, Q::MPIStateArray, t::Real)\n return false\nend\n\nfunction update_aux_diffusive!(dg::DGModel, bl::BalanceLaw, Q::MPIStateArray, t::Real)\n return false\nend\n\nfunction reverse_indefinite_stack_integral!(dg::DGModel, m::BalanceLaw,\n auxstate::MPIStateArray, t::Real)\n\n device = typeof(auxstate.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n FT = eltype(auxstate)\n\n vgeo = grid.vgeo\n polyorder = polynomialorder(dg.grid)\n\n # do integrals\n nintegrals = num_integrals(m, FT)\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,\n knl_reverse_indefinite_stack_integral!(Val(dim), Val(polyorder),\n Val(nvertelem), auxstate.data,\n 1:nhorzelem,\n Val(nintegrals)))\nend\n\nfunction nodal_update_aux!(f!, dg::DGModel, m::BalanceLaw, Q::MPIStateArray,\n t::Real; diffusive=false)\n device = typeof(Q.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n nrealelem = length(topology.realelems)\n\n polyorder = polynomialorder(dg.grid)\n\n Np = dofs_per_element(grid)\n\n ### update aux variables\n if diffusive\n @launch(device, threads=(Np,), blocks=nrealelem,\n knl_nodal_update_aux!(m, Val(dim), Val(polyorder), f!,\n Q.data, dg.auxstate.data, dg.diffstate.data, t,\n topology.realelems))\n else\n @launch(device, threads=(Np,), blocks=nrealelem,\n knl_nodal_update_aux!(m, Val(dim), Val(polyorder), f!,\n Q.data, dg.auxstate.data, t,\n topology.realelems))\n end\nend\n\nfunction copy_stack_field_down!(dg::DGModel, m::BalanceLaw,\n auxstate::MPIStateArray, fldin, fldout)\n\n device = typeof(auxstate.data) <: Array ? CPU() : CUDA()\n\n grid = dg.grid\n topology = grid.topology\n\n dim = dimensionality(grid)\n N = polynomialorder(grid)\n Nq = N + 1\n Nqk = dim == 2 ? 1 : Nq\n\n DFloat = eltype(auxstate)\n\n vgeo = grid.vgeo\n polyorder = polynomialorder(dg.grid)\n\n # do integrals\n nelem = length(topology.elems)\n nvertelem = topology.stacksize\n nhorzelem = div(nelem, nvertelem)\n\n @launch(device, threads=(Nq, Nqk, 1), blocks=nhorzelem,\n knl_copy_stack_field_down!(Val(dim), Val(polyorder), Val(nvertelem),\n auxstate.data, 1:nhorzelem, Val(fldin),\n Val(fldout)))\nend\n\nfunction MPIStateArrays.MPIStateArray(dg::DGModel, commtag=888)\n bl = dg.balancelaw\n grid = dg.grid\n\n state = create_state(bl, grid, commtag)\n\n return state\nend\n", "meta": {"hexsha": "c0b7c9f04f742820f66329e11adcd33f56a149c3", "size": 9010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DGmethods/DGmodel.jl", "max_stars_repo_name": "emassoud/CLIMA", "max_stars_repo_head_hexsha": "7dcd4d6c86f01f9c27cf18f6e19f6b54d72a19ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DGmethods/DGmodel.jl", "max_issues_repo_name": "emassoud/CLIMA", "max_issues_repo_head_hexsha": "7dcd4d6c86f01f9c27cf18f6e19f6b54d72a19ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DGmethods/DGmodel.jl", "max_forks_repo_name": "emassoud/CLIMA", "max_forks_repo_head_hexsha": "7dcd4d6c86f01f9c27cf18f6e19f6b54d72a19ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5126582278, "max_line_length": 86, "alphanum_fraction": 0.6075471698, "num_tokens": 2511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.15909033339750914}} {"text": "module SingleCrystal\n\nusing LinearAlgebra\nusing JSON\n\n# https://web.archive.org/web/20080324193801/http://cst-www.nrl.navy.mil/lattice/spcgrp/\n# coordinate system -> standard cartesian\n# primitive vectors -> describe the primitive cell\n# basis vectors -> describe positions of atoms in the primitive cell\n# translation of basis vectors by primitive vectors generate a crystal\n\n# https://wiki.fysik.dtu.dk/ase/ase/spacegroup/spacegroup.html\n\n\"\"\"\n get_chemical_info()\n\nReturns instances `chemical_symbols`, `atomic_numbers` and `masses` for the setup of `Cell`.\n\"\"\"\nfunction get_chemical_info()\n chemical_symbols = [\n # 0\n \"X\",\n # 1\n \"X\", \"He\",\n # 2\n \"Li\", \"Be\", \"B\", \"C\", \"N\", \"O\", \"F\", \"Ne\",\n # 3\n \"Na\", \"Mg\", \"Al\", \"Si\", \"P\", \"S\", \"Cl\", \"Ar\",\n # 4\n \"K\", \"Ca\", \"Sc\", \"Ti\", \"V\", \"Cr\", \"Mn\", \"Fe\", \"Co\", \"Ni\", \"Cu\", \"Zn\",\n \"Ga\", \"Ge\", \"As\", \"Se\", \"Br\", \"Kr\",\n # 5\n \"Rb\", \"Sr\", \"Y\", \"Zr\", \"Nb\", \"Mo\", \"Tc\", \"Ru\", \"Rh\", \"Pd\", \"Ag\", \"Cd\",\n \"In\", \"Sn\", \"Sb\", \"Te\", \"I\", \"Xe\",\n # 6\n \"Cs\", \"Ba\", \"La\", \"Ce\", \"Pr\", \"Nd\", \"Pm\", \"Sm\", \"Eu\", \"Gd\", \"Tb\", \"Dy\",\n \"Ho\", \"Er\", \"Tm\", \"Yb\", \"Lu\",\n \"Hf\", \"Ta\", \"W\", \"Re\", \"Os\", \"Ir\", \"Pt\", \"Au\", \"Hg\", \"Tl\", \"Pb\", \"Bi\",\n \"Po\", \"At\", \"Rn\",\n # 7\n \"Fr\", \"Ra\", \"Ac\", \"Th\", \"Pa\", \"U\", \"Np\", \"Pu\", \"Am\", \"Cm\", \"Bk\",\n \"Cf\", \"Es\", \"Fm\", \"Md\", \"No\", \"Lr\",\n \"Rf\", \"Db\", \"Sg\", \"Bh\", \"Hs\", \"Mt\", \"Ds\", \"Rg\", \"Cn\", \"Nh\", \"Fl\", \"Mc\",\n \"Lv\", \"Ts\", \"Og\"\n ]\n\n atomic_numbers = Dict()\n for (Z, symbol) in enumerate(chemical_symbols)\n atomic_numbers[symbol] = Z\n end\n\n atomic_masses_iupac2016 = [\n 1.0, # X\n 1.008, # H [1.00784, 1.00811]\n 4.002602, # He\n 6.94, # Li [6.938, 6.997]\n 9.0121831, # Be\n 10.81, # B [10.806, 10.821]\n 12.011, # C [12.0096, 12.0116]\n 14.007, # N [14.00643, 14.00728]\n 15.999, # O [15.99903, 15.99977]\n 18.998403163, # F\n 20.1797, # Ne\n 22.98976928, # Na\n 24.305, # Mg [24.304, 24.307]\n 26.9815385, # Al\n 28.085, # Si [28.084, 28.086]\n 30.973761998, # P\n 32.06, # S [32.059, 32.076]\n 35.45, # Cl [35.446, 35.457]\n 39.948, # Ar\n 39.0983, # K\n 40.078, # Ca\n 44.955908, # Sc\n 47.867, # Ti\n 50.9415, # V\n 51.9961, # Cr\n 54.938044, # Mn\n 55.845, # Fe\n 58.933194, # Co\n 58.6934, # Ni\n 63.546, # Cu\n 65.38, # Zn\n 69.723, # Ga\n 72.630, # Ge\n 74.921595, # As\n 78.971, # Se\n 79.904, # Br [79.901, 79.907]\n 83.798, # Kr\n 85.4678, # Rb\n 87.62, # Sr\n 88.90584, # Y\n 91.224, # Zr\n 92.90637, # Nb\n 95.95, # Mo\n 97.90721, # 98Tc\n 101.07, # Ru\n 102.90550, # Rh\n 106.42, # Pd\n 107.8682, # Ag\n 112.414, # Cd\n 114.818, # In\n 118.710, # Sn\n 121.760, # Sb\n 127.60, # Te\n 126.90447, # I\n 131.293, # Xe\n 132.90545196, # Cs\n 137.327, # Ba\n 138.90547, # La\n 140.116, # Ce\n 140.90766, # Pr\n 144.242, # Nd\n 144.91276, # 145Pm\n 150.36, # Sm\n 151.964, # Eu\n 157.25, # Gd\n 158.92535, # Tb\n 162.500, # Dy\n 164.93033, # Ho\n 167.259, # Er\n 168.93422, # Tm\n 173.054, # Yb\n 174.9668, # Lu\n 178.49, # Hf\n 180.94788, # Ta\n 183.84, # W\n 186.207, # Re\n 190.23, # Os\n 192.217, # Ir\n 195.084, # Pt\n 196.966569, # Au\n 200.592, # Hg\n 204.38, # Tl [204.382, 204.385]\n 207.2, # Pb\n 208.98040, # Bi\n 208.98243, # 209Po\n 209.98715, # 210At\n 222.01758, # 222Rn\n 223.01974, # 223Fr\n 226.02541, # 226Ra\n 227.02775, # 227Ac\n 232.0377, # Th\n 231.03588, # Pa\n 238.02891, # U\n 237.04817, # 237Np\n 244.06421, # 244Pu\n 243.06138, # 243Am\n 247.07035, # 247Cm\n 247.07031, # 247Bk\n 251.07959, # 251Cf\n 252.0830, # 252Es\n 257.09511, # 257Fm\n 258.09843, # 258Md\n 259.1010, # 259No\n 262.110, # 262Lr\n 267.122, # 267Rf\n 268.126, # 268Db\n 271.134, # 271Sg\n 270.133, # 270Bh\n 269.1338, # 269Hs\n 278.156, # 278Mt\n 281.165, # 281Ds\n 281.166, # 281Rg\n 285.177, # 285Cn\n 286.182, # 286Nh\n 289.190, # 289Fl\n 289.194, # 289Mc\n 293.204, # 293Lv\n 293.208, # 293Ts\n 294.214, # 294Og\n ]\n\n masses = Dict(k => atomic_masses_iupac2016[atomic_numbers[k]] for k in chemical_symbols)\n \n return chemical_symbols, atomic_numbers, masses\nend\n\nfunction load_spgs(;file::String=\"$(@__DIR__)/spacegroup.json\")\n return JSON.parsefile(file)\nend\n\nfunction load_refs(;file::String=\"$(@__DIR__)/ase-atoms.json\")\n return JSON.parsefile(file)\nend\n\n\n\"\"\"\n parse_json_spacegroup(spgs,nr,setting)\n\nFormats the info of a specific spacegroup, preparing its use in `get_symops`.\n\"\"\"\nfunction parse_json_spacegroup(spgs::Dict,nr::T0,setting::T1) where {T0<:Integer,T1<:Integer}\n spg = spgs[\"$(nr): $(setting)\"]\n spg[\"subtrans\"] = [Array{Float64}(reshape(v,3)) for v in spg[\"subtrans\"]]\n spg[\"translations\"] = [Array{Float64}(reshape(v,3)) for v in spg[\"translations\"]]\n spg[\"rotations\"] = [Array{Float64}(hcat(v...)) for v in spg[\"rotations\"]]\n return spg\nend\n\n\"\"\"\n get_symops(spg)\n\nGenerates rotation and translation operations for the given spacegroup info (`spg` from `parse_json_spacegroup`).\n\"\"\"\nfunction get_symops(spg::Dict)\n # `spg` is the output of `parse_json_spacegroup`\n parities = spg[\"centrosymmetric\"] ? [1,-1] : [1]\n symops = []\n @assert length(spg[\"rotations\"]) == length(spg[\"translations\"])\n for (parity, trans_sub) in Iterators.product(parities, spg[\"subtrans\"])\n for (rot, trans) in Iterators.zip(spg[\"rotations\"], spg[\"translations\"])\n push!(symops, (parity * rot,\n (trans + trans_sub) .% 1))\n end\n end\n return symops\nend\n\n\"\"\"\n fold(x)\n\nFolding `x` back into [0,1).\n\"\"\"\nfunction fold(x::T) where T<:Any\n return x < 0 ? x + 1 : x\nend\n\n\"\"\"\n get_equivalent_sites(basis, symops)\n\nComputes equivalent sites of in `basis` using rotations and translations in `symops`.\n\"\"\"\nfunction get_equivalent_sites(basis::Array{Array{Float64,2},1}, symops)\n kinds, sites = [], []\n\n for (kind, pos) in enumerate(basis)\n for (rot, trans) in symops\n site = (transpose(pos * rot) + trans) .% 1\n site = fold.(site)\n isdifferent = !any([v ≈ site for v in sites])\n if ((length(sites) == 0) | isdifferent)\n push!(sites, site)\n append!(kinds, kind)\n end\n end\n end\n return sites, kinds\nend\n\n\"\"\"\n make_unit_vec(x)\n\nComputes the normalized `x` vector.\n\"\"\"\nfunction make_unit_vec(x::Array{T,1}) where T<:Any\n return x / norm(x)\nend\n\n\"\"\"\n get_coords(a_direction, ab_normal)\n\nComputes the coordinate system given `a_direction` (usually [1 0 0]) and the vector normal to `a` and `b` (`ab_normal`, usually [0 0 1]).\n\"\"\"\nfunction get_coords(a_direction::Array{Float64,1}, ab_normal::Array{Float64,1})\n @assert dot(a_direction, ab_normal) ≈ 0.\n _x = make_unit_vec(a_direction)\n z = make_unit_vec(ab_normal)\n\n x = _x - dot(_x, ab_normal) * z\n xyz = hcat(x, cross(z,x), z)\n return xyz\nend\n\n\"\"\"\n deg2rad(x)\n\nConvert degrees to radians.\n\"\"\"\nfunction deg2rad(x::T) where T <: Real\n return x * π / 180.\nend\n\n\"\"\"\n get_cos(x)\n\nCompute the cosine of x degrees.\n\"\"\"\nfunction get_cos(x::T) where T <: Real\n return x ≈ 90 ? 0 : cos(deg2rad(x))\nend\n\n\"\"\"\n get_cell_vectors(cellpar)\n\nComputes 3x3 cell vectors (column-wise). cellpar = [a, b, c, α, β, γ]\n\"\"\"\nfunction get_cell_vectors(cellpar::Array{Float64,1})\n a, b, c, α, β, γ = cellpar\n cos_α = get_cos(α)\n cos_β = get_cos(β)\n cos_γ = get_cos(abs(γ))\n sin_γ = abs(γ) ≈ 90 ? sign(γ) : sin(deg2rad(γ))\n cos_α, cos_β, cos_γ, sin_γ\n \n cy = (cos_α - cos_β * cos_γ) / sin_γ\n abc = hcat([a; 0; 0], b*[cos_γ; sin_γ; 0], c*[cos_β; cy; √(1-cos_β*cos_β-cy*cy)])\n return abc\nend\n\n\nstruct CoordinateSystem{T}\n x::Array{T}\n y::Array{T}\n z::Array{T}\n M::Matrix{T} # contains x,y,z as column vectors\nend\n\n\"\"\"\n CartesianCoords(T)\n\nInitialization of the cartesian coordiantes using `CoordianteSystem`.\n\"\"\"\nCartesianCoords(T) = CoordinateSystem{T}([1; 0; 0], [0; 1; 0], [0; 0; 1], I(3))\n\n\"\"\"\n PrimitiveVectors(cc)\n\nGenerates vectors for a primitive cell on the basis of a coordinate system, like the `CartesianCoords`.\n\"\"\"\nfunction PrimitiveVectors(cc::CoordinateSystem{T}; \n A₁=[1; 0; 0], A₂=[0; 1; 0], A₃=[0; 0; 1]) where {T<:Real}\n # x = SVector{3}(sum([cc.x, cc.y, cc.z] .* A₁))\n x = cc.M * A₁\n y = cc.M * A₂\n z = cc.M * A₃\n M = hcat(x,y,z)\n return CoordinateSystem{T}(x, y, z, M)\nend\n\n\"\"\"\n Atom(; name, mass)\n\nGenerates an atom object for the creation of unit cells.\n\"\"\"\nstruct Atom{T}\n name::String\n mass::T\nend\n\nAtom(name,mass) = Atom{Float64}(name,mass)\nmake_atom(name,mass) = Atom{typeof(mass)}(name,mass)\n\nfunction Atom(;name::String=\"dummy\",mass::T=42) where T<:Real\n return Atom{typeof(mass)}(name, mass)\nend\n\nstruct Spacegroup\n nr::Int32 #spacegroup number\n setting::Int8 # spacegroup setting (1 or 2, inherited from ase.spacegroup)\n kinds::Array{Int16,1} \n sites::Array{Any,1}\nend\n\nSpacegroup() = Spacegroup(-1,-1,[-1],[0])\n\nstruct Cell{T}\n atoms::Array\n positions\n box::CoordinateSystem{T}\n edge_lengths::Array{T}\n # spacegroup related infos\n spacegroup::Spacegroup\nend\n\nCell(atoms, positions, box, edge_lengths) = Cell{Float64}(atoms, positions, box, edge_lengths, Spacegroup())\nCell(atoms, positions, box, edge_lengths, spg) = Cell{Float64}(atoms, positions, box, edge_lengths, spg)\n\n\"\"\"\n make_unitcell(basis, symbols, nr, setting, cellpar; spg_file=nothing, a_direction=[1.; 0.; 0.], ab_normal=[0.;0.;1.], atom_cb=make_atom)\n\nCreates a `Cell` struct including atom information, atom coordinates, the cell vectors/box and the edge lengths of the box. \n\"\"\"\nfunction make_unitcell(basis, symbols, nr, setting, cellpar; \n a_direction=[1.; 0.; 0.], ab_normal=[0.; 0.; 1.], \n atom_cb::Function=make_atom)\n # get constants\n chemical_symbols, atomic_numbers, masses = get_chemical_info() \n\n # get stored symmetry operation components\n spgs = load_spgs()\n spg = parse_json_spacegroup(spgs, nr, setting)\n \n # prepare symmetry operations for application to `basis`\n symops = get_symops(spg)\n\n # generating equivalent sites\n sites, kinds = get_equivalent_sites(basis, symops)\n\n # computing the simulation cell/box\n xyz = get_coords(a_direction, ab_normal)\n abc = get_cell_vectors(cellpar)\n cell = abc * xyz\n\n # storing crystal properties in a `SingleCrystal.Cell` instance\n el2atom_map = Dict(el => atom_cb(el, masses[el]) for el in symbols)\n\n cc = CartesianCoords(Float64)\n box = PrimitiveVectors(cc, A₁=abc[:,1], A₂=abc[:,2], A₃=abc[:,3])\n\n _spg = Spacegroup(nr, setting, kinds, sites)\n\n crystal = Cell(\n [el2atom_map[symbols[v]] for v in kinds],\n [cell * v for v in sites],\n box,\n [norm(abc[:,1]), norm(abc[:,2]), norm(abc[:,3])],\n _spg\n )\n return crystal\nend\n\n\"\"\"\n make_bcc_unitcell(symbol, a)\n\nConvenience function wrapping `make_unitcell` to create a bcc unit cell.\n\"\"\"\nmake_bcc_unitcell(symbol::String,a::T,atom_cb::Function=make_atom) where T<:Real = make_unitcell([[0. 0. 0.],], [symbol], 229, 1, [a,a,a,90.,90,90], atom_cb=atom_cb)\n\n\"\"\"\n make_fcc_unitcell(element, a)\n\nConvenience function wrapping `make_unitcell` to create a fcc unit cell.\n\"\"\"\nmake_fcc_unitcell(symbol::String,a::T,atom_cb::Function=make_atom) where T<:Real = make_unitcell([[0. 0. 0.],], [symbol], 225, 1, [a,a,a,90.,90,90], atom_cb=atom_cb)\n\n\n\"\"\"\n add_vacancies(c, ixs; random=false, n_vac=1)\n\nAdds a vacancy / removes an atom to/from a `Cell` struct.\n\"\"\"\nfunction add_vacancies(c::Cell; ixs::Array{Int}=[1], random::Bool=false, n_vac::Int=1)\n # if `random=true` then `n_vac` are generated and `ixs` is ignored\n n_atoms = length(c.atoms)\n if random == true\n ixs = rand(1:n_atoms, n_vac)\n end\n atoms_vac = [c.atoms[i] for i in 1:n_atoms if !(i in ixs)]\n positions_vac = [c.positions[i] for i in 1:n_atoms if !(i in ixs)]\n type = typeof(positions_vac[1][1])\n return Cell(atoms_vac, positions_vac, c.box, c.edge_lengths, c.spacegroup)\nend\n\n\"\"\"\n make_supercell(c;nx=1,ny=1,nz=1)\n\nCreates a supercell by replicating the unitcell `c` and translating it along the vectors in `cell.box` `nx` * `ny` * `nz` times.\n\"\"\"\nfunction make_supercell(c::Cell; nx::I=1, ny::I=1, nz::I=1) where {I <: Integer}\n @assert (nx > 0) & (ny > 0) & (nz > 0) \n atoms = []\n positions = []\n box = PrimitiveVectors(c.box, A₁=[nx; 0; 0], A₂=[0; ny; 0], A₃=[0; 0; nz])\n edge_lengths = [norm(box.x), norm(box.y), norm(box.z)]\n\n for i in 0:nx-1, j in 0:ny-1, k in 0:nz-1\n shift = c.box.M * [i, j, k] # [c.box.x * i + c.box.y * j + c.box.z * k]\n new_pos = [pos + shift for pos in c.positions]\n push!(positions, new_pos) # TODO: ((3, 1), Size(3,)) of input arrays do not match\n push!(atoms, c.atoms)\n end\n supercell = Cell(vcat(atoms...), vcat(positions...), box, edge_lengths)\n return supercell\nend\n\n\"\"\"\n vector1D(c1,c2,box_size)\n\nComputes the periodic 1D distance between `c1` and `c2` with `box_size` as the periodic boundary.\n\"\"\"\nfunction vector1D(c1::Real, c2::Real, box_size::Real)\n if c1 < c2\n return (c2 - c1) < (c1 - c2 + box_size) ? (c2 - c1) : (c2 - c1 - box_size)\n else\n return (c1 - c2) < (c2 - c1 + box_size) ? (c2 - c1) : (c2 - c1 + box_size)\n end\nend\n\n\"\"\"\n vector(c1,c2,box_size)\n\nConvenience function wrapping `vector1D` for the case of a cube.\n\"\"\"\nvector(c1, c2, box_size::Real) = vector1D.(c1, c2, box_size) # all box vectors orthogonal and of equal length\n\n\"\"\"\n vector(c1,c2,edge_lengths)\n\nConvenience function wrapping `vector1D` for the case of a non-cubic box with still orthogonal box vectors.\n\"\"\"\nvector(c1, c2, edge_lengths::Array) = vector1D.(c1, c2, edge_lengths) # all box vectors orthogonal\n\nfunction parse_json_crystal(json_ase_crystal::Dict{String,Any})\n ase_crystal = Dict()\n ase_crystal[\"spacegroup_kinds\"] = Array{Int32}(json_ase_crystal[\"spacegroup_kinds\"])\n ase_crystal[\"positions\"] = [Array{Float64}(v) for v in json_ase_crystal[\"positions\"]]\n ase_crystal[\"cell\"] = hcat(json_ase_crystal[\"cell\"]...)\n ase_crystal[\"symbols\"] = Array{String}(json_ase_crystal[\"symbols\"])\n return ase_crystal\nend\n\nfunction cell2dict(crystal::SingleCrystal.Cell)\n\n chemical_symbols, atomic_numbers, masses = get_chemical_info()\n\n d = Dict() \n d[\"numbers\"] = [atomic_numbers[atom.name] for atom in crystal.atoms] #[atomic_numbers[symbols[v]] for v in kinds]\n d[\"positions\"] = hcat(crystal.positions...)\n d[\"spacegroup_kinds\"] = crystal.spacegroup.kinds\n d[\"cell\"] = crystal.box.M\n d[\"pbc\"] = [true,true,true]\n d[\"info\"] = Dict(\"spacegroup\"=>Dict(\"nr\"=>crystal.spacegroup.nr, \"setting\"=>crystal.spacegroup.setting))\n return d\nend\n\nend", "meta": {"hexsha": "e568ff2e19896ddc7b9af085b3c1fc477b987e34", "size": 15567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SingleCrystal.jl", "max_stars_repo_name": "eschmidt42/crystal", "max_stars_repo_head_hexsha": "0b10cdddd2829d2f939d89c1f93b3cf04d6ff3d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-14T13:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T13:55:43.000Z", "max_issues_repo_path": "src/SingleCrystal.jl", "max_issues_repo_name": "eschmidt42/crystal", "max_issues_repo_head_hexsha": "0b10cdddd2829d2f939d89c1f93b3cf04d6ff3d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SingleCrystal.jl", "max_forks_repo_name": "eschmidt42/crystal", "max_forks_repo_head_hexsha": "0b10cdddd2829d2f939d89c1f93b3cf04d6ff3d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5388994307, "max_line_length": 165, "alphanum_fraction": 0.577118263, "num_tokens": 5506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15888647266465708}} {"text": "module trlib\n type trlib_data\n H \n invM\n grad :: Array{Float64, 1}\n itmax :: Int64\n equality :: Int64\n itmax_lanczos :: Int64\n tol_rel_i :: Float64\n tol_abs_i :: Float64\n tol_rel_b :: Float64\n tol_abs_b :: Float64\n zero :: Float64\n obj_lb :: Float64\n ctl_invariant :: Int64\n convexify :: Int64\n earlyterm :: Int64\n refine :: Int64\n verbose :: Int64\n h_pointer :: Int64\n iwork :: Array{Int64, 1}\n fwork :: Array{Float64, 1}\n timing :: Array{Int64, 1}\n init :: Int64\n sol :: Array{Float64, 1}\n g :: Array{Float64, 1}\n v :: Array{Float64, 1}\n gm :: Array{Float64, 1}\n p :: Array{Float64, 1}\n Hp :: Array{Float64, 1}\n Q :: Array{Float64, 2}\n ret :: Int64\n obj :: Float64\n lam :: Float64\n trlib_data(H, invM, grad) = (itmax = min(round(Int, 2e8/size(grad,1)), 2*size(grad, 1));\n iwork_size = Array{Clong}(1);\n fwork_size = Array{Clong}(1);\n h_pointer = Array{Clong}(1); \n ccall(\n (:trlib_krylov_memory_size, \"libtrlib\"),\n Clong,\n (Clong, Ptr{Clong}, Ptr{Clong}, Ptr{Clong}),\n itmax, iwork_size, fwork_size, h_pointer);\n fwork = Array{Cdouble}(fwork_size[1]);\n ccall(\n (:trlib_krylov_prepare_memory, \"libtrlib\"),\n Clong,\n (Clong, Ptr{Cdouble}),\n itmax, fwork);\n new(H, invM, grad, itmax,\n 0, 100, -2.0, 0.0, -3.0, 0.0, 2e-16, -1e20, 0, 1, 1, 1, 0,\n h_pointer[1], Array{Clong}(iwork_size[1]), fwork,\n Array{Clong}(ccall((:trlib_krylov_timing_size, \"libtrlib\"), Clong, ())),\n 1, similar(grad), similar(grad), similar(grad),\n similar(grad), similar(grad), similar(grad),\n Array{Float64}(size(grad,1), itmax+1), 0, 0.0, 0.0 ) )\n trlib_data(H, grad) = (itmax = min(round(Int, 2e8/size(grad,1)), 2*size(grad, 1));\n iwork_size = Array{Clong}(1);\n fwork_size = Array{Clong}(1);\n h_pointer = Array{Clong}(1); \n ccall(\n (:trlib_krylov_memory_size, \"libtrlib\"),\n Clong,\n (Clong, Ptr{Clong}, Ptr{Clong}, Ptr{Clong}),\n itmax, iwork_size, fwork_size, h_pointer);\n fwork = Array{Cdouble}(fwork_size[1]);\n ccall(\n (:trlib_krylov_prepare_memory, \"libtrlib\"),\n Clong,\n (Clong, Ptr{Cdouble}),\n itmax, fwork);\n new(H, speye(size(grad,1)), grad, itmax,\n 0, 100, -2.0, 0.0, -3.0, 0.0, 2e-16, -1e20, 0, 1, 1, 1, 0,\n h_pointer[1], Array{Clong}(iwork_size[1]), fwork,\n Array{Clong}(ccall((:trlib_krylov_timing_size, \"libtrlib\"), Clong, ())),\n 1, similar(grad), similar(grad), similar(grad),\n similar(grad), similar(grad), similar(grad),\n Array{Float64}(size(grad,1), itmax+1), 0, 0.0, 0.0 ) )\n end\n \n function trlib_solve(TR::trlib_data, radius::Float64)\n g_dot_g = 0.0\n v_dot_g = 0.0\n p_dot_Hp = 0.0\n \n action = Array{Clong}(1)\n it = Array{Clong}(1)\n ityp = Array{Clong}(1)\n flt1 = Array{Cdouble}(1)\n flt2 = Array{Cdouble}(1)\n flt3 = Array{Cdouble}(1)\n \n while true\n TR.ret = ccall(\n (:trlib_krylov_min, \"libtrlib\"),\n Clong,\n (Clong, Cdouble, Clong, Clong, Clong, Cdouble, Cdouble,\n Cdouble, Cdouble, Cdouble, Cdouble, Clong, Clong, Clong,\n Cdouble, Cdouble, Cdouble, Ptr{Clong}, Ptr{Cdouble},\n Clong, Clong, Clong, Cstring, Ptr{Clong}, Ptr{Clong},\n Ptr{Clong}, Ptr{Clong}, Ptr{Clong}, Ptr{Cdouble},\n Ptr{Cdouble}, Ptr{Cdouble}),\n TR.init, radius, TR.equality, TR.itmax, TR.itmax_lanczos,\n TR.tol_rel_i, TR.tol_abs_i, TR.tol_rel_b, TR.tol_abs_b,\n TR.zero, TR.obj_lb, TR.ctl_invariant, TR.convexify,\n TR.earlyterm, g_dot_g, v_dot_g, p_dot_Hp, TR.iwork,\n TR.fwork, TR.refine, 0, 0, \"\", C_NULL,\n TR.timing, action, it, ityp, flt1, flt2, flt3)\n TR.init = 0\n if action[1] == 1\n TR.sol[:] = 0.0\n TR.gm[:] = 0.0\n TR.g = TR.grad\n TR.v = TR.invM * TR.g\n g_dot_g = dot(TR.g, TR.g)\n v_dot_g = dot(TR.v, TR.g)\n TR.p = -TR.v\n TR.Hp = TR.H*TR.p\n p_dot_Hp = dot(TR.p, TR.Hp)\n TR.Q[:,1] = TR.v/sqrt(v_dot_g)\n end\n if action[1] == 2\n TR.sol = TR.Q[:,1:1+it[1]] * TR.fwork[1+TR.h_pointer:1+TR.h_pointer+it[1]]\n end\n if action[1] == 3\n if ityp[1] == 1\n TR.sol += flt1[1] * TR.p\n end\n end\n if action[1] == 4\n if ityp[1] == 1\n TR.Q[:,1+it] = flt2[1] * TR.v\n TR.gm = TR.g\n TR.g += flt1[1]*TR.Hp\n end\n if ityp[1] == 2\n TR.sol = TR.Hp + flt1[1] * TR.g + flt2[1] * TR.gm\n TR.gm = flt3[1] * TR.g\n TR.g = TR.sol\n end\n TR.v = TR.invM * TR.g\n g_dot_g = dot(TR.g, TR.g)\n v_dot_g = dot(TR.v, TR.g)\n end\n if action[1] == 5\n TR.p = flt1[1]*TR.v + flt2[1]*TR.p\n TR.Hp = TR.H*TR.p\n p_dot_Hp = dot(TR.p, TR.Hp)\n if ityp[1] == 2\n TR.Q[:,1+it] = TR.p\n end\n end\n if action[1] == 8\n g_dot_g = .5 * dot(TR.sol, TR.H*TR.sol) + dot(TR.sol, TR.grad)\n end\n if TR.ret < 10\n break\n end\n end\n TR.obj = TR.fwork[9]\n TR.lam = TR.fwork[8]\n TR.init = 2\n end\nend\n", "meta": {"hexsha": "71a01fad68e86178efcf88a287d0bf3adbd5d1d0", "size": 7470, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bindings/julia/trlib.jl", "max_stars_repo_name": "JonasZehn/trlib", "max_stars_repo_head_hexsha": "0af71b50de42500794d6aa308dd72d731de14998", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2017-04-14T11:16:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T13:48:56.000Z", "max_issues_repo_path": "bindings/julia/trlib.jl", "max_issues_repo_name": "JonasZehn/trlib", "max_issues_repo_head_hexsha": "0af71b50de42500794d6aa308dd72d731de14998", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-04-06T08:20:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T11:37:50.000Z", "max_forks_repo_path": "bindings/julia/trlib.jl", "max_forks_repo_name": "JonasZehn/trlib", "max_forks_repo_head_hexsha": "0af71b50de42500794d6aa308dd72d731de14998", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-03-08T19:37:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-06T07:36:45.000Z", "avg_line_length": 45.2727272727, "max_line_length": 107, "alphanum_fraction": 0.3744310576, "num_tokens": 1974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.15844707467787808}} {"text": "\n\nfunction apply_boundary_conditions_on_φ_axis!( rbpot::Array{T, 4}, iz::Int, ir::Int, rbi::Int, nrbi::Int, ax::DiscreteAxis{T, :periodic, :periodic}, int::Interval{:closed, :open, T},\n grid_boundary_factors::NTuple{2, T}, only2d::Val{only_2d})::Nothing where {T, only_2d}\n rbpot[iz, 1, ir, rbi] = rbpot[ iz, end - 1, ir, rbi] # cycling boundary\n rbpot[iz, end, ir, rbi] = rbpot[ iz, 2, ir, rbi] # cycling boundary\n nothing\nend\n\nfunction apply_boundary_conditions_on_φ_axis!( rbpot::Array{T, 4}, iz::Int, ir::Int, rbi::Int, nrbi::Int, ax::DiscreteAxis{T, :reflecting, :reflecting}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T}, only2d::Val{false})::Nothing where {T}\n rbpot[iz, 1, ir, rbi] = rbpot[ iz, 3, ir, rbi] # cycling boundary\n rbpot[iz, end, ir, rbi] = rbpot[ iz, end - 2, ir, rbi] # cycling boundary\n nothing\nend\nfunction apply_boundary_conditions_on_φ_axis!( rbpot::Array{T, 4}, iz::Int, ir::Int, rbi::Int, nrbi::Int, ax::DiscreteAxis{T, :reflecting, :reflecting}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T}, only2d::Val{true})::Nothing where {T}\n rbpot[iz, 1, ir, nrbi] = rbpot[ iz, 2, ir, rbi] # cycling boundary\n rbpot[iz, end, ir, nrbi] = rbpot[ iz, 2, ir, rbi] # cycling boundary\n nothing\nend\nfunction apply_boundary_conditions_on_r_axis!( rbpot::Array{T, 4}, iz::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :r0, :infinite}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[iz, iφ, end, rbi] = grid_boundary_factors[2] * rbpot[iz, iφ, end - 2, rbi] # infinity boundaries in r\n nothing\nend\nfunction apply_boundary_conditions_on_r_axis!( rbpot::Array{T, 4}, iz::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :r0, :reflecting}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[iz, iφ, end, rbi] = rbpot[iz, iφ, end - 2, rbi] # infinity boundaries in r\n nothing\nend\nfunction apply_boundary_conditions_on_r_axis!( rbpot::Array{T, 4}, iz::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :r0, :fixed}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n # rbpot[iz, iφ, end, rbi] = rbpot[iz, iφ, end - 2, rbi] # infinity boundaries in r\n nothing\nend\nfunction apply_boundary_conditions_on_cyl_z_axis!( rbpot::Array{T, 4}, ir::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :infinite, :infinite}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[ 1, iφ, ir, rbi] = grid_boundary_factors[1] * rbpot[ 2, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n rbpot[end, iφ, ir, rbi] = grid_boundary_factors[2] * rbpot[ end - 1, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n nothing\nend\nfunction apply_boundary_conditions_on_cyl_z_axis!( rbpot::Array{T, 4}, ir::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :infinite, :fixed}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[ 1, iφ, ir, rbi] = grid_boundary_factors[1] * rbpot[ 2, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n nothing\nend\nfunction apply_boundary_conditions_on_cyl_z_axis!( rbpot::Array{T, 4}, ir::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :fixed, :infinite}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[end, iφ, ir, rbi] = grid_boundary_factors[2] * rbpot[ end - 1, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n nothing\nend\nfunction apply_boundary_conditions_on_cyl_z_axis!( rbpot::Array{T, 4}, ir::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :reflecting, :reflecting}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[ 1, iφ, ir, rbi] = rbpot[ 2, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n rbpot[end, iφ, ir, rbi] = rbpot[ end - 1, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n nothing\nend\nfunction apply_boundary_conditions_on_cyl_z_axis!( rbpot::Array{T, 4}, ir::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :fixed, :reflecting}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[end, iφ, ir, rbi] = rbpot[ end - 1, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n nothing\nend\nfunction apply_boundary_conditions_on_cyl_z_axis!( rbpot::Array{T, 4}, ir::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :reflecting, :fixed}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n rbpot[ 1, iφ, ir, rbi] = rbpot[ 2, iφ, ir, rbi] # infinity boundaries in z (only ±1 because this is the compressed (redblack) dimension)\n nothing\nend\nfunction apply_boundary_conditions_on_cyl_z_axis!( rbpot::Array{T, 4}, ir::Int, iφ::Int, rbi::Int, ax::DiscreteAxis{T, :fixed, :fixed}, int::Interval{:closed, :closed, T},\n grid_boundary_factors::NTuple{2, T})::Nothing where {T}\n nothing\nend\n\n\nfunction apply_boundary_conditions!(fssrb::PotentialSimulationSetupRB{T, 3, 4, :cylindrical}, update_even_points::Val{even_points}, only2d::Val{only_2d}) where {T, even_points, only_2d}\n rbi::Int = even_points ? rb_even::Int : rb_odd::Int\n nrbi::Int = even_points ? rb_odd::Int : rb_even::Int\n ax1::typeof(fssrb.grid.axes[1]) = fssrb.grid.axes[1]\n ax2::typeof(fssrb.grid.axes[2]) = fssrb.grid.axes[2]\n ax3::typeof(fssrb.grid.axes[3]) = fssrb.grid.axes[3]\n int1::typeof(ax1.interval) = ax1.interval\n int2::typeof(ax2.interval) = ax2.interval\n int3::typeof(ax3.interval) = ax3.interval\n if only_2d\n iφ::Int = 2\n @inbounds for iz in axes(fssrb.potential, 1)\n # for ir in axes(fssrb.potential, 3)\n # apply_boundary_conditions_on_φ_axis!( fssrb.potential, iz, ir, rbi, nrbi, ax2, int2, fssrb.grid_boundary_factors[2], only2d)\n # end\n apply_boundary_conditions_on_r_axis!( fssrb.potential, iz, iφ, rbi, ax1, int1, fssrb.grid_boundary_factors[1])\n end\n @inbounds for ir in axes(fssrb.potential, 3)\n apply_boundary_conditions_on_cyl_z_axis!( fssrb.potential, ir, iφ, rbi, ax3, int3, fssrb.grid_boundary_factors[3])\n end\n else\n @inbounds for iz in axes(fssrb.potential, 1)\n for iφ in axes(fssrb.potential, 2)\n apply_boundary_conditions_on_r_axis!( fssrb.potential, iz, iφ, rbi, ax1, int1, fssrb.grid_boundary_factors[1])\n end\n for ir in axes(fssrb.potential, 3)\n apply_boundary_conditions_on_φ_axis!( fssrb.potential, iz, ir, rbi, nrbi, ax2, int2, fssrb.grid_boundary_factors[2], only2d)\n end\n end\n @inbounds for iφ in axes(fssrb.potential, 2) # z boundaries\n for ir in axes(fssrb.potential, 3)\n apply_boundary_conditions_on_cyl_z_axis!( fssrb.potential, ir, iφ, rbi, ax3, int3, fssrb.grid_boundary_factors[3])\n end\n end\n begin # r = 0 handling\n nφ::Int = size(fssrb.potential, 2) - 1\n gw_φ::Array{T, 2} = fssrb.geom_weights[2].weights\n @inbounds for inz in 1:(size(fssrb.ϵ, 3) - 1)\n m::T = 0\n l::T = 0\n for inφ in 1:nφ\n if even_points ? isodd(inz + inφ) : iseven(inz + inφ)\n l += gw_φ[3, inφ] \n m += fssrb.potential[rbidx(inz), inφ + 1, 2, rbi] * gw_φ[3, inφ] \n end\n end\n m *= inv(l)\n for inφ in 1:nφ\n if even_points ? isodd(inz + inφ) : iseven(inz + inφ)\n fssrb.potential[rbidx(inz), inφ + 1, 2, rbi]::T = m\n end\n end\n end\n end\n end\n nothing\nend\n\n", "meta": {"hexsha": "edb7695a9437773f66eee6e2ce02789429eff274", "size": 8819, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PotentialSimulation/PotentialSimulationSetups/BoundaryConditions/BoundaryConditionsCylindrical.jl", "max_stars_repo_name": "schustermartin/SolidStateDetectors.jl", "max_stars_repo_head_hexsha": "18101d5dc5bbafeb3001bd7f23e1084453a263c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-21T03:32:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:32:15.000Z", "max_issues_repo_path": "src/PotentialSimulation/PotentialSimulationSetups/BoundaryConditions/BoundaryConditionsCylindrical.jl", "max_issues_repo_name": "schustermartin/SolidStateDetectors.jl", "max_issues_repo_head_hexsha": "18101d5dc5bbafeb3001bd7f23e1084453a263c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PotentialSimulation/PotentialSimulationSetups/BoundaryConditions/BoundaryConditionsCylindrical.jl", "max_forks_repo_name": "schustermartin/SolidStateDetectors.jl", "max_forks_repo_head_hexsha": "18101d5dc5bbafeb3001bd7f23e1084453a263c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.3082706767, "max_line_length": 189, "alphanum_fraction": 0.6019956911, "num_tokens": 2818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1577742907201174}} {"text": "prob(p::LogProb) = p\nprob(s::Product) = first(s)\n\n#####################################################\n### Classes of Traversal, Completion, and ItemKey ###\n#####################################################\n\nstruct Traversal{S}\n edgeid :: Int\n consid :: Int\n score :: S\n inloop :: Bool\nend\nmake_accesses(Traversal)\n\nTraversal(edgeid, consid, score) = Traversal(edgeid, consid, score, false)\nprob(trav::Traversal) = prob(score(trav))\n\nabstract type Completion{S} end\nprob(comp::Completion) = prob(score(comp))\n\nstruct EdgeCompletion{CR,S} <: Completion{S}\n edgeid :: Int\n rule :: CR\n score :: S\n inloop :: Bool\nend\nmake_accesses(EdgeCompletion)\n\nEdgeCompletion(edgeid, rule, score) = EdgeCompletion(edgeid, rule, score, false)\nEdgeCompletion{CR,S}(edgeid, rule, score) where {CR,S} = EdgeCompletion{CR,S}(edgeid, rule, score, false)\n\nstruct TerminalCompletion{T,TR,S} <: Completion{S}\n terminal :: T\n rule :: TR\n score :: S\nend\nmake_accesses(TerminalCompletion)\n\n# is not a bitstype\n@auto_hash_equals struct EdgeKey{St}\n start :: Int\n tail :: Int\n state :: St\nend\nmake_accesses(EdgeKey)\n\n# is a bitstype\nstruct ConsKey{C}\n start :: Int\n tail :: Int\n cat :: C\nend\nmake_accesses(ConsKey)\n\nfunction ==(k1::ConsKey{T}, k2::ConsKey{T}) where {T <: AbstractString}\n k1.start == k2.start && k1.tail == k2.tail && k1.cat == k2.cat\nend\n\nfunction Base.hash(k::ConsKey{T}) where {T <: AbstractString}\n hash(k.start, hash(k.tail, hash(k.cat)))\nend\n\n##################\n### Item class ###\n##################\n\nabstract type Item end\nItem(key::EdgeKey, trav, id, grammar) = Edge(key, trav, id, grammar)\nItem(key::ConsKey, comp, id, grammar) = Constituent(key, comp, id, grammar)\nstart(item::Item) = item.start\ntail(item::Item) = item.tail\nlength(item::Item) = item.tail - item.start\nid(item::Item) = item.id\nlastpopscore(item::Item) = item.lastpopscore\ninsidepopnumber(item::Item) = item.insidepopnumber\noutsidepopnumber(item::Item) = item.outsidepopnumber\n\n##################\n### Edge class ###\n##################\n\nmutable struct Edge{St,S} <: Item\n start :: Int\n tail :: Int\n state :: St\n score :: S\n isfinished :: Bool\n traversals :: Vector{Traversal{S}}\n id :: Int # edges have positive ids\n lastpopscore :: S\n lastoutsidepopscore:: S\n insidepopnumber :: Int\n outsidepopnumber :: Int\n outside_finished :: Bool\n trav_outs_summands :: Dict{Tuple{Int, Int}, LogProb}\n comp_outs_summands :: Dict{Int, LogProb}\nend\nEdge(start, tail, state, traversals::Vector, id, score) =\n Edge(start, tail, state, score, false, traversals, id, score, score, 0, 0, false, Dict{Tuple{Int, Int}, LogProb}(), Dict{Int, LogProb}())\nEdge(start, tail, state, traversal::Traversal{S}, id) where S =\n Edge(start, tail, state, [traversal], id, zero(S))\nEdge(key::EdgeKey, traversal::Traversal, id, grammar) =\n Edge(start(key), tail(key), state(key), traversal, id)\n\nscore(edge::Edge) = if edge.isfinished\n edge.score\nelse\n sum(score(trav) for trav in traversals(edge))\nend\nprob(edge::Edge) = prob(score(edge))\noutside(edge::Edge) = sum(values(edge.trav_outs_summands)) + sum(values(edge.comp_outs_summands))\nstate(edge::Edge) = edge.state\ncat_or_state(edge::Edge) = edge.state\nkey(edge::Edge) = EdgeKey(edge.start, edge.tail, edge.state)\ntraversals(edge::Edge) = edge.traversals\nshow(io::IO, edge::Edge) = print(io, state(edge), \"(\", start(edge), \",\", tail(edge), \")\")\n\nfunction add!(edge::Edge, traversal)\n for (i, trav) in enumerate(traversals(edge))\n if edgeid(trav) == edgeid(traversal) && consid(trav) == consid(traversal)\n traversals(edge)[i] = @set traversal.inloop = true\n return edge\n end\n end\n push!(traversals(edge), traversal)\n edge\nend\n\n#########################\n### Constituent class ###\n#########################\n\nmutable struct Constituent{C,T,CR,TR,S} <: Item\n start :: Int\n tail :: Int\n cat :: C\n score :: S\n isfinished :: Bool\n completions :: Vector{EdgeCompletion{CR,S}}\n terminal_completion :: Nullable{TerminalCompletion{T,TR,S}}\n id :: Int # constituents have negative ids\n lastpopscore :: S\n lastoutsidepopscore :: S\n insidepopnumber :: Int\n outsidepopnumber :: Int\n outside_finished :: Bool\n trav_outs_summands :: Dict{Tuple{Int, Int}, LogProb}\nend\nConstituent(st,ta,ca,co,te,id,sc) =\n Constituent(st,ta,ca,sc,false,co,te,id,sc,sc,0,0,false,Dict{Tuple{Int, Int}, LogProb}())\nfunction Constituent(start, tail, cat, comp::EdgeCompletion, id, grammar)\n T, TR, S = terminal_type(grammar), terminal_rule_type(grammar), score_type(grammar)\n Constituent(start, tail, cat, [comp], Nullable{TerminalCompletion{T,TR,S}}(), id, zero(S))\nend\nfunction Constituent(start, tail, cat, comp::TerminalCompletion, id, grammar)\n CR, S = category_rule_type(grammar), score_type(grammar)\n Constituent(start, tail, cat, Vector{EdgeCompletion{CR,S}}(), Nullable(comp), id, zero(S))\nend\nConstituent(key::ConsKey, comp, id, grammar) =\n Constituent(start(key), tail(key), cat(key), comp, id, grammar)\n\nscore(cons::Constituent) = if cons.isfinished\n cons.score\nelse\n if has_terminal(cons)\n if isempty(completions(cons))\n score(get(cons.terminal_completion)) # get(cons.terminal_completion))\n else\n sum(score(comp) for comp in completions(cons)) +\n score(get(cons.terminal_completion)) # get(cons.terminal_completion))\n end\n else\n sum(score(comp) for comp in completions(cons))\n end\nend\n\nprob(cons::Constituent) = prob(score(cons))\noutside(cons::Constituent) = sum(values(cons.trav_outs_summands))\ncat(cons::Constituent) = cons.cat\ncat_or_state(cons::Constituent) = cons.cat\nkey(cons::Constituent) = ConsKey(cons.start, cons.tail, cons.cat)\ncompletions(cons::Constituent) = cons.completions\nhas_terminal(cons::Constituent) = !isnull(cons.terminal_completion)\nterminal_completion(cons::Constituent) = get(cons.terminal_completion)\nterminal(cons::Constituent) = terminal(terminal_completion(cons))\n\nfunction add!(cons::Constituent, completion::EdgeCompletion)\n for (i, comp) in enumerate(completions(cons))\n if edgeid(comp) == edgeid(completion)\n completions(cons)[i] = @set completion.inloop = true\n return cons\n end\n end\n push!(completions(cons), completion)\n nothing\nend\n\nfunction show(io::IO, c::Constituent)\n print(io, cat(c), \"(\", start(c), \",\", tail(c), \")\")\n if has_terminal(c)\n print(io, \"[\", terminal(c) ,\"]\")\n end\nend\n\n###########################\n### ParserLogbook class ###\n###########################\n\nmutable struct ParserLogbook{C,T,CR,TR,St,S}\n edges :: Vector{Edge{St,S}}\n conss :: Vector{Constituent{C,T,CR,TR,S}}\n edgeids :: Dict{EdgeKey{St}, Int}\n consids :: Dict{ConsKey{C}, Int}\nend\nParserLogbook(C, T, CR, TR, St, S) =\n ParserLogbook(Vector{Edge{St,S}}(),\n Vector{Constituent{C,T,CR,TR,S}}(),\n Dict{EdgeKey{St}, Int}(),\n Dict{ConsKey{C}, Int}())\n\nfunction discover!(logbook, edge::Edge)\n push!(logbook.edges, edge)\n id = length(logbook.edges)\n logbook.edgeids[key(edge)] = id\n edge.id = id\n nothing\nend\nfunction discover!(logbook, cons::Constituent)\n push!(logbook.conss, cons)\n id = -length(logbook.conss)\n logbook.consids[key(cons)] = id\n cons.id = id\n nothing\nend\nisdiscovered(logbook, key::EdgeKey) = haskey(logbook.edgeids, key)\nisdiscovered(logbook, key::ConsKey) = haskey(logbook.consids, key)\nget_edge(logbook, id::Int) = logbook.edges[id]\nget_cons(logbook, id::Int) = logbook.conss[-id]\nget_edge(logbook, key::EdgeKey) = get_edge(logbook, logbook.edgeids[key])\nget_cons(logbook, key::ConsKey) = get_cons(logbook, logbook.consids[key])\nget_item(logbook, key::EdgeKey) = get_edge(logbook, logbook.edgeids[key])\nget_item(logbook, key::ConsKey) = get_cons(logbook, logbook.consids[key])\n\n###################\n### Chart class ###\n###################\n\n# maybe be used in a future implementation, maybe not\n\"like normal merge, but value vectors with the same key will be concatenated\"\nfunction Base.merge(dicts::Dict{K,Vector{V}}...) where {K,V}\n result = Dict{K,Vector{V}}()\n for d in dicts\n for (key,valvec) in d # key and value vector\n if haskey(result, key)\n append!(result[key], valvec)\n else\n result[key] = valvec\n end\n end\n end\n result\nend\n\nmutable struct ChartCell{C,St}\n edgeids :: Dict{St, Vector{Int}}\n consids :: Dict{C, Vector{Int}}\nend\nChartCell(C, St) =\n ChartCell(Dict{St, Vector{Int}}(), Dict{C, Vector{Int}}())\n\nmutable struct Chart{C,St}\n cells :: Vector{ChartCell{C,St}}\nend\nedgeids(chart, edge::Edge) = chart.cells[tail(edge)].edgeids\nconsids(chart, edge::Edge) = chart.cells[tail(edge)].consids\nedgeids(chart, cons::Constituent) = chart.cells[start(cons)].edgeids\nconsids(chart, cons::Constituent) = chart.cells[start(cons)].consids\n# dict(chart, edge::Edge) = chart.cells[tail(edge)].edgeids\n# dict(chart, cons::Constituent) = chart.cells[start(cons)].consids\nfunction insert!(chart::Chart, edge::Edge)\n dict = edgeids(chart, edge)\n if haskey(dict, state(edge))\n push!(dict[state(edge)], id(edge))\n else\n dict[state(edge)] = [id(edge)]\n end\n nothing\nend\nfunction insert!(chart::Chart, cons::Constituent)\n dict = consids(chart, cons)\n if haskey(dict, cat(cons))\n push!(dict[cat(cons)], id(cons))\n else\n dict[cat(cons)] = [id(cons)]\n end\n nothing\nend\n\n####################\n### Agenda class ###\n####################\n\n# fast viterbi parsing does not work yet\n\nmutable struct Agenda{T}\n pqueue :: PriorityQueue{Int, T}\nend\n\nfunction Agenda(parsing_method)\n @assert parsing_method in (:full, :viterbi)\n if parsing_method == :full\n Agenda(PriorityQueue{Int, Int}())\n else\n Agenda(PriorityQueue{Int, Float64}())\n end\nend\n\nfunction enqueue!(agenda::Agenda, item, just_used)\n agenda.pqueue[id(item)] = priority(agenda, item, just_used) ::Int\n nothing\nend\n\ndequeue!(agenda::Agenda) = dequeue!(agenda.pqueue)\nisempty(agenda::Agenda) = isempty(agenda.pqueue)\n\npriority(agenda::Agenda{Int}, edge::Edge, just_completed::Bool) =\n 4 * length(edge) - 2*!just_completed - 1\npriority(agenda::Agenda{Int}, cons::Constituent, just_introduced_edge::Bool) =\n 4 * length(cons) - 2*!just_introduced_edge\n\npriority(agenda::Agenda{Float64}, item, just_used) =\n - prob(item).value # negative logprob, agenda favours high probs but is min orientated\n\n##########################\n### ParseForest class ###\n##########################\n\nmutable struct ParseForest{C,T,CR,TR,St,S}\n heads :: Vector{Constituent{C,T,CR,TR,S}}\n logbook :: ParserLogbook{C,T,CR,TR,St,S}\n terminals :: Vector{T}\nend\n\nfunction ParseForest(chart::Chart, logbook::ParserLogbook{C,T,CR,TR,St,S}, terminals, grammar) where {C,T,CR,TR,St,S}\n heads = Constituent{C,T,CR,TR,S}[]\n cell = chart.cells[1]\n for cat in startsymbols(grammar)\n if haskey(cell.consids, cat)\n for consid in cell.consids[cat]\n cons = get_cons(logbook, consid)\n if tail(cons) == length(terminals)+1\n push!(heads, cons)\n end\n end\n end\n end\n ParseForest(heads, logbook, terminals)\nend\n\nheads(f::ParseForest) = f.heads\nis_complete(f::ParseForest) = !isempty(f.heads)\nscore(f::ParseForest) = sum(map(score, f.heads))\n\n### OutsideAgenda ###\n\nmutable struct OutsideAgenda\n pqueue :: PriorityQueue{Int, Int}\nend\n\nfunction OutsideAgenda()\n OutsideAgenda(PriorityQueue{Int, Int}())\nend\n\nfunction enqueue!(agenda::OutsideAgenda, item, just_used)\n agenda.pqueue[id(item)] = priority(agenda, item, just_used)\n agenda\nend\n\ndequeue!(agenda::OutsideAgenda) = dequeue!(agenda.pqueue)\nisempty(agenda::OutsideAgenda) = isempty(agenda.pqueue)\n\npriority(agenda::OutsideAgenda, edge::Edge, just_used::Bool) =\n - 4 * length(edge) - 2*!just_used -1\npriority(agenda::OutsideAgenda, cons::Constituent, just_used::Bool) =\n - 4 * length(cons) - 2*!just_used\n\n######################\n\ninside = prob\n\n@inline function acc_or_init!(d::Dict, k, v)\n if haskey(d, k)\n d[k] += v\n else\n d[k] = v\n end\nend\n\nfunction calculate_outside_probs_and_expected_rule_usages!(f::ParseForest{C,T,CR,TR,St,S}, grammar) where {C,T,CR,TR,St,S}\n @assert is_complete(f)\n outside_agenda = OutsideAgenda()\n # mapping categories to rules to (startindex,endindex) to probabilities\n rule_usage_probs = Dict{C, Dict{typejoin(CR,TR), Dict{Tuple{Int,Int}, LogProb}}}()\n for head in heads(f)\n # traversal outside score summands\n head.trav_outs_summands[0,0] = one(LogProb)\n enqueue!(outside_agenda, head, false)\n end\n while !isempty(outside_agenda)\n id = dequeue!(outside_agenda)\n if id > 0\n parent_edge = get_edge(f.logbook, id)\n parent_edge.outsidepopnumber += 1\n # @show parent_edge.id\n # println()\n o = outside(parent_edge)\n if !(outside(parent_edge) ≈ parent_edge.lastoutsidepopscore) &&\n outsidepopnumber(parent_edge) < MAX_POP_NUMBER\n for trav in traversals(parent_edge)\n if trav.inloop\n cons = get_cons(f.logbook, consid(trav))\n if edgeid(trav) == 0\n acc_or_init!(cons.trav_outs_summands, (id,0), o)\n # cons.trav_outs_summands[id, 0] = o\n enqueue!(outside_agenda, cons, false)\n end\n end\n end\n parent_edge.lastoutsidepopscore = o\n enqueue!(outside_agenda, parent_edge, true)\n elseif !(parent_edge.outside_finished)\n parent_edge.outside_finished = true\n for trav in traversals(parent_edge)\n if true # !(trav.inloop)\n # println(\"edge\")\n cons = get_cons(f.logbook, consid(trav))\n if edgeid(trav) == 0\n # acc_or_init!(cons.trav_outs_summands, (id,0), o)\n cons.trav_outs_summands[id, 0] = o\n enqueue!(outside_agenda, cons, false)\n else\n edge = get_edge(f.logbook, edgeid(trav))\n edge.trav_outs_summands[id,cons.id] = o * inside(cons)\n # acc_or_init!(edge.trav_outs_summands, (id, cons.id), o * inside(cons))\n enqueue!(outside_agenda, edge, false)\n cons.trav_outs_summands[id,edge.id] = o * inside(edge)\n # acc_or_init!(cons.trav_outs_summands, (id, edge.id), o * inside(edge))\n enqueue!(outside_agenda, cons, false)\n end\n end\n end\n end\n else\n parent_cons = get_cons(f.logbook, id)\n parent_cons.outsidepopnumber += 1\n # @show parent_cons\n # println(map(c->c.edgeid, parent_cons.completions))\n # println(exp(score(parent_cons)))\n # println(parent_cons.trav_outs_summands)\n # println(outside(parent_cons) ≈ parent_cons.lastoutsidepopscore)\n # println()\n o = outside(parent_cons)\n if !(outside(parent_cons) ≈ parent_cons.lastoutsidepopscore) &&\n outsidepopnumber(parent_cons) < MAX_POP_NUMBER\n for comp in completions(parent_cons)\n if comp.inloop\n edge = get_edge(f.logbook, edgeid(comp))\n p = prob(grammar, cat(parent_cons), rule(comp))\n acc_or_init!(edge.comp_outs_summands, id, o * p)\n # edge.comp_outs_summands[id] = o * p\n enqueue!(outside_agenda, edge, false)\n end\n end\n parent_cons.lastoutsidepopscore = o\n enqueue!(outside_agenda, parent_cons, true)\n else#if !(parent_cons.outside_finished)\n parent_cons.outside_finished = true\n for comp in completions(parent_cons)\n if true # !(comp.inloop)\n # println(\"cons\")\n edge = get_edge(f.logbook, edgeid(comp))\n p = prob(grammar, cat(parent_cons), rule(comp))\n # acc_or_init!(edge.comp_outs_summands, id, o * p)\n edge.comp_outs_summands[id] = o * p\n enqueue!(outside_agenda, edge, false)\n if haskey(rule_usage_probs, cat(parent_cons))\n if haskey(rule_usage_probs[cat(parent_cons)], rule(comp))\n # if haskey(rule_usage_probs[cat(parent_cons)][rule(comp)], (start(parent_cons),tail(parent_cons)))\n # rule_usage_probs[cat(parent_cons)][rule(comp)][(start(parent_cons),tail(parent_cons))] += o * p * inside(edge)\n # else\n # rule_usage_probs[cat(parent_cons)][rule(comp)][(start(parent_cons),tail(parent_cons))] = o * p * inside(edge)\n # end\n rule_usage_probs[cat(parent_cons)][rule(comp)][(start(parent_cons),tail(parent_cons))] = o * p * inside(edge)\n else\n rule_usage_probs[cat(parent_cons)][rule(comp)] = Dict((start(parent_cons),tail(parent_cons)) => o * p * inside(edge))\n end\n else\n rule_usage_probs[cat(parent_cons)] = Dict(rule(comp)=>Dict((start(parent_cons),tail(parent_cons)) => o * p * inside(edge)))\n end\n end\n end\n if has_terminal(parent_cons)\n comp = terminal_completion(parent_cons)\n p = prob(grammar, cat(parent_cons), rule(comp))\n if haskey(rule_usage_probs, cat(parent_cons))\n if haskey(rule_usage_probs[cat(parent_cons)], rule(comp))\n # if haskey(rule_usage_probs[cat(parent_cons)][rule(comp)], (start(parent_cons),tail(parent_cons)))\n # rule_usage_probs[cat(parent_cons)][rule(comp)][(start(parent_cons),tail(parent_cons))] += o * p\n # else\n # rule_usage_probs[cat(parent_cons)][rule(comp)][(start(parent_cons),tail(parent_cons))] = o * p\n # end\n rule_usage_probs[cat(parent_cons)][rule(comp)][(start(parent_cons),tail(parent_cons))] = o * p\n else\n rule_usage_probs[cat(parent_cons)][rule(comp)] = Dict((start(parent_cons),tail(parent_cons)) => o * p)\n end\n else\n rule_usage_probs[cat(parent_cons)] = Dict(rule(comp)=>Dict((start(parent_cons),tail(parent_cons)) => o * p))\n end\n end\n end\n end\n end\n\n sequence_prop = sum(inside(head) for head in f.heads)\n\n expected_rule_usages = Dict(\n cat => Dict(\n rule => exp(sum(values(rule_usage_probs[cat][rule])).value - sequence_prop.value)\n for rule in keys(rule_usage_probs[cat]))\n for cat in keys(rule_usage_probs)\n )\nend\n\nfunction calculate_outside_probs_and_expected_rule_usages!(sent :: Vector{T}, grammar :: Grammar{C,T,CR,TR,S,Cond}) where {C,T,CR,TR,S,Cond}\n forest = run_chartparser(sent, grammar)\n d = calculate_outside_probs_and_expected_rule_usages!(forest, grammar)\n (forest, d)\nend\n\nfunction best_tree(f::ParseForest)\n @assert is_complete(f)\n best_tree(f, f.heads[findmax(map(prob, f.heads))[2]])\nend\n\nfunction best_tree(f::ParseForest{C,T,CR,TR,St,S}, cons::Constituent) where {C,T,CR,TR,St,S}\n if has_terminal(cons)\n TreeNode((cons,rule(terminal_completion(cons))),\n Tuple{Constituent{C,T,CR,TR,S}, Union{CR,TR}})\n else\n comp = completions(cons)[findmax(map(prob, completions(cons)))[2]]\n node = TreeNode((cons, rule(comp)),\n Tuple{Constituent{C,T,CR,TR,S}, Union{CR,TR}})\n trees = best_trees(f, get_edge(f.logbook, edgeid(comp))) # children trees\n for t in trees\n insert_child!(node, t)\n end\n node\n end\nend\n\nfunction best_trees(f::ParseForest, edge::Edge)\n best_traversal = traversals(edge)[findmax(map(prob, traversals(edge)))[2]]\n if edgeid(best_traversal) == 0\n (best_tree(f, get_cons(f.logbook, consid(best_traversal))),)\n else\n (best_trees(f, get_edge(f.logbook, edgeid(best_traversal)))...,\n best_tree(f, get_cons(f.logbook, consid(best_traversal))))\n end\nend\n\nfunction sample_tree(f::ParseForest)\n @assert is_complete(f)\n head = categorical_sample(heads(f), map(prob, heads(f)))\n sample_tree(f, head)\nend\n\nfunction sample_tree(f::ParseForest{C,T,CR,TR,St,S}, cons::Constituent) where{C,T,CR,TR,St,S}\n if has_terminal(cons)\n TreeNode((cons,rule(terminal_completion(cons))),\n Tuple{Constituent{C,T,CR,TR,S}, Union{CR,TR}})\n else\n comp = categorical_sample(completions(cons),\n map(prob, completions(cons)))\n node = TreeNode((cons, rule(comp)),\n Tuple{Constituent{C,T,CR,TR,S}, Union{CR,TR}})\n trees = sample_trees(f, get_edge(f.logbook, edgeid(comp))) # children trees\n for t in trees\n insert_child!(node, t)\n end\n node\n end\nend\n\nfunction sample_trees(f::ParseForest, edge::Edge)\n traversal = categorical_sample(traversals(edge),\n map(prob, traversals(edge)))\n if edgeid(traversal) == 0 # then this edge contains the start state\n (sample_tree(f, get_cons(f.logbook, consid(traversal))),)\n else\n (sample_trees(f, get_edge(f.logbook, edgeid(traversal)))...,\n sample_tree(f, get_cons(f.logbook, consid(traversal))))\n end\nend\n\n# # all_trees no yet implemented\n# function all_trees{C,T,CR,TR,St,S}(f::ParseForest{C,T,CR,TR,St,S})\n# if is_complete(f)\n# vcat([all_trees(f, cons) for cons in heads(f)]...)\n# else\n# Vector{TreeNode{Tuple{Constituent{C,T,CR,TR,S}, Union{CR,TR}}}}\n# end\n# end\n#\n# function all_trees{C,T,CR,TR,St,S}(\n# f :: ParseForest{C,T,CR,TR,St,S},\n# cons :: Constituent\n# )\n# if has_terminal(cons)\n# [TreeNode((cons,rule(terminal_completion(cons))),\n# Tuple{Constituent{C,T,CR,TR,S}, Union{CR,TR}})]\n# else\n# for comp in completions(cons)\n# node = TreeNode((cons, rule(comp)),\n# Tuple{Constituent{C,T,CR,TR,S}, Union{CR,TR}})\n# end\n# end\n# end\n#\n# function all_trees(f::ParseForest, edge::Edge)\n#\n# end\n\n#######################\n### ParseTree class ###\n#######################\n\nParseTree{Cons<:Constituent,R} = TreeNode{Tuple{Cons,R}}\n\nfunction show(io::IO, tree::ParseTree)\n print(io, \"[\", tree.data[1])\n for child in tree.children\n print(io, child)\n end\n print(io, \"]\")\nend\n\ncats_and_rules(t::ParseTree) = ((node.data[1].cat, node.data[2]) for node in t)\n", "meta": {"hexsha": "cb549d189342e247420fac98fd84aeb48764a5f3", "size": 23882, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeneralizedChartparsing/src/parser/parser_types.jl", "max_stars_repo_name": "yblainm/FragmentGrammar.jl", "max_stars_repo_head_hexsha": "3ae13bffd2d11824e0f32091cce20f44e871547a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-27T16:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T00:20:58.000Z", "max_issues_repo_path": "src/GeneralizedChartparsing/src/parser/parser_types.jl", "max_issues_repo_name": "yblainm/FragmentGrammar.jl", "max_issues_repo_head_hexsha": "3ae13bffd2d11824e0f32091cce20f44e871547a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GeneralizedChartparsing/src/parser/parser_types.jl", "max_forks_repo_name": "yblainm/FragmentGrammar.jl", "max_forks_repo_head_hexsha": "3ae13bffd2d11824e0f32091cce20f44e871547a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7981510015, "max_line_length": 151, "alphanum_fraction": 0.5888116573, "num_tokens": 6128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1577742907201174}} {"text": "# Parameters for Liquid Density\r\nDataLiquidDensity = Dict(\"1,1,1-Trichloroethane\"=>[[0.47476,0.27258,0.29333],[545.00,242.75,545.00]],\r\n \"1,1,2-Trichloroethane\"=>[[0.47455,0.25475,0.31000],[602.00,236.50,602.00]],\r\n \"1,1-Dichloroethane\"=>[[0.41231,0.26533,0.28700],[523.00,176.19,523.00]],\r\n \"1,2-Dichloroethane\"=>[[0.46501,0.28742,0.31041],[561.00,237.49,561.00]],\r\n \"1,3-Butadiene\"=>[[0.24597,0.27227,0.29074],[425.37,164.25,425.37]],\r\n \"1,4-Dioxane\"=>[[0.37018,0.28130,0.30470],[587.00,284.95,587.00]],\r\n \"1-Butanol\"=>[[0.26891,0.26674,0.24570],[562.93,183.85,562.93]],\r\n \"1-Butene\"=>[[0.23224,0.26630,0.28530],[419.59,87.80,419.59]],\r\n \"1-Decene\"=>[[0.23981,0.25776,0.28562],[617.05,206.89,617.05]],\r\n \"1-Nonane\"=>[[0.23364,0.25556,0.28571],[595.65,219.63,595.65]],\r\n \"1-Octene\"=>[[0.23682,0.25649,0.28571],[566.60,171.45,566.60]],\r\n \"1-Propanol\"=>[[0.27684,0.27200,0.24940],[536.71,146.95,536.71]],\r\n \"Acetaldehyde\"=>[[0.28207,0.26004,0.27760],[461.00,150.15,461.00]],\r\n \"Acetic acid\"=>[[0.35182,0.26954,0.26843],[592.71,289.81,592.71]],\r\n \"Acetic anhydride\"=>[[0.33578,0.24080,0.26990],[569.15,200.15,569.15]],\r\n \"Acetone\"=>[[0.27728,0.25760,0.29903],[508.20,178.45,508.20]],\r\n \"Acrylic acid\"=>[[0.34645,0.25822,0.30701],[615.00,286.65,615.00]],\r\n \"Ammonia\"=>[[0.23689,0.25471,0.28870],[405.65,195.41,405.65]],\r\n \"Aniline\"=>[[0.31190,0.25000,0.28571],[699.00,267.13,699.00]],\r\n \"Benzene\"=>[[0.30090,0.26770,0.28180],[562.16,278.68,562.16]],\r\n \"Butyric acid\"=>[[0.31132,0.26192,0.27997],[628.00,267.95,628.00]],\r\n \"Carbon disulfide\"=>[[0.47589,0.28749,0.32260],[552.00,161.58,552.00]],\r\n \"Carbon dioxide\"=>[[0.46382,0.26160,0.29030],[304.19,216.58,304.19]],\r\n \"Carbon monoxide\"=>[[0.29818,0.27655,0.29053],[132.92,68.15,132.92]],\r\n \"Carbon tetrachloride\"=>[[0.56607,0.27663,0.29000],[556.35,250.33,556.35]],\r\n \"Chlorine\"=>[[0.56600,0.27315,0.28830],[417.15,172.12,417.15]],\r\n \"Chloroform\"=>[[0.49807,0.25274,0.28766],[536.40,209.63,536.40,1.480]],\r\n \"Cyclohexane\"=>[[0.27376,0.27408,0.28511],[553.54,279.69,553.54]],\r\n \"Cyclohexanol\"=>[[0.29681,0.24340,0.28570],[625.15,296.60,625.15]],\r\n \"Cyclopropane\"=>[[0.25880,0.27400,0.28571],[397.91,145.73,397.91]],\r\n \"Dichloromethane\"=>[[0.45965,0.25678,0.29020],[510.00,178.01,510.00]],\r\n \"Diethyl ether\"=>[[0.27267,0.27608,0.29358],[466.70,156.85,466.70]],\r\n \"Diethyl ketone\"=>[[0.25635,0.24291,0.27364],[560.95,234.18,560.95]],\r\n \"Dimethylamine\"=>[[0.24110,0.26785,0.24800],[437.65,180.96,437.65]],\r\n \"Ethane\"=>[[0.20087,0.27330,0.28330],[305.42,90.35,305.42]],\r\n \"Ethanol\"=>[[0.26570,0.26395,0.23670],[516.25,159.05,516.25]],\r\n \"Ethyl acetate\"=>[[0.30654,0.25856,0.27800],[523.30,189.60,523.30]],\r\n \"Ethyl chloride\"=>[[0.32259,0.27464,0.23140],[460.35,136.75,460.35]],\r\n \"Ethylbenzene\"=>[[0.28889,0.26438,0.29210],[617.17,178.20,617.17]],\r\n \"Ethylene\"=>[[0.21428,0.28061,0.28571],[282.36,104.01,282.36]],\r\n \"Ethylene glycol\"=>[[0.32503,0.25499,0.17200],[645.00,260.15,645.00]],\r\n \"Ethylene oxide\"=>[[0.31402,0.26089,0.28253],[469.15,161.45,469.15]],\r\n \"Fluorine\"=>[[0.57092,0.28518,0.29000],[144.31,53.48,144.31]],\r\n \"Glycerol\"=>[[0.34908,0.24902,0.15410],[723.00,291.33,723.00]],\r\n \"Hydrogen\"=>[[0.03125,0.34730,0.27560],[33.18,13.95,33.18]],\r\n \"Hydrogen chloride\"=>[[0.44134,0.26957,0.31870],[324.65,159.97,324.65]],\r\n \"Hydrogen cyanide\"=>[[0.19501,0.18589,0.2820],[456.65,259.91,465.65]],\r\n \"Hydrogen peroxide\"=>[[0.43776,0.24982,0.28770],[730.15,272.74,730.15]],\r\n \"i-Butane\"=>[[0.22281,0.27294,0.27301],[408.14,113.54,408.14]],\r\n \"Methane\"=>[[0.15998,0.28810,0.27700],[190.58,90.67,190.58]],\r\n \"Methanol\"=>[[0.27197,0.27192,0.23310],[512.58,175.47,512.58]],\r\n \"Methyl bromide\"=>[[0.60859,0.26292,0.28030],[467.00,179.55,467.00]],\r\n \"Methyl chloride\"=>[[0.35821,0.26109,0.28690],[416.25,175.45,416.25]],\r\n \"Methyl isobutyl ketone\"=>[[0.26654,0.25887,0.28571],[571.40,189.15,571.40]],\r\n \"Methylamine\"=>[[0.20168,0.21405,0.22750],[430.05,179.69,430.05]],\r\n \"m-Xylene\"=>[[0.27866,0.25925,0.27243],[617.05,225.30,617.05]],\r\n \"Naphthalene\"=>[[0.30619,0.25037,0.28300],[748.35,353.43,748.35]],\r\n \"n-Butane\"=>[[0.22827,0.27240,0.28630],[425.18,134.86,425.18]],\r\n \"n-Decane\"=>[[0.23276,0.25240,0.28570],[618.45,243.49,618.45]],\r\n \"n-Heptane\"=>[[0.23237,0.26020,0.27910],[540.26,182.57,540.26]],\r\n \"n-Hexane\"=>[[0.23242,0.26500,0.27810],[507.43,177.84,507.43]],\r\n \"Nitrobenzene\"=>[[0.36140,0.24731,0.28570],[719.00,278.91,719.00]],\r\n \"Nitrogen\"=>[[0.31205,0.28479,0.29250],[126.10,63.15,126.10]],\r\n \"n-Nonane\"=>[[0.23364,0.25556,0.28571],[595.65,219.63,595.65]],\r\n \"n-Octane\"=>[[0.22807,0.25476,0.26940],[568.83,216.38,568.83]],\r\n \"n-Pentane\"=>[[0.23143,0.26923,0.28215],[469.65,143.42,469.65]],\r\n \"Oxygen\"=>[[0.43533,0.28772,0.29240],[154.58,54.35,154.58]],\r\n \"o-Xylene\"=>[[0.28381,0.26083,0.27410,630.37,247.98,630.37]],\r\n \"Phenol\"=>[[0.41476,0.32162,0.32120],[694.25,314.06,694.25]],\r\n \"p-Xylene\"=>[[0.27984,0.26003,0.27900],[616.26,286.41,616.26]],\r\n \"Pyridine\"=>[[0.30752,0.24333,0.30450],[619.95,231.53,619.95]],\r\n \"Styrene\"=>[[0.29383,0.26315,0.28570],[648.00,242.54,648.00]],\r\n \"Toluene\"=>[[0.29999,0.27108,0.29889],[591.79,178.18,591.79]],\r\n \"Vinyl acetate\"=>[[0.31843,0.25803,0.28270],[524.00,180.35,524.00]],\r\n \"Water\"=>[[0.34710,0.27400,0.28571],[647.13,273.16,647.13]])\r\n\r\n# Parameters for Gas Viscosity\r\nDataGasViscosity=Dict(\"1,1,1-Trichloroethane\"=>[-19.216 4.0308E-01 -6.8618E-05 347.0 997.0],\r\n \"1,1,2-Trichloroethane\"=>[-8.293 3.3989E-01 -5.3678E-05 387.0 987.0],\r\n \"1,1-Dichloroethane\"=>[-12.991 4.0085E-01 -1.1779E-04 320.0 472.0],\r\n \"1,2-Dichloroethane\"=>[1.025 3.1792E-01 -4.1853E-05 322.0 561.0],\r\n \"1,3-Butadiene\"=>[10.256 2.6833E-01 -4.1148E-05 250.0 650.0],\r\n \"1,4-Dioxane\"=>[-16701 3.4988E-01 -5.3736E-05 374.0 994.0],\r\n \"1-Butanol\"=>[-11.144 2.8790E-01 -5.6275E-05 391.0 1000.0],\r\n \"1-Butene\"=>[-9.143 3.1562E-01 -8.4164E-05 175.0 800.0],\r\n \"1-Decene\"=>[4.015 1.8083E-01 -3.8216E-05 444.0 1000.0],\r\n \"1-Nonane\"=>[-6.802 1.8688E-01 3.4929E-07 273.0 773.0],\r\n \"1-Octene\"=>[2.722 2.0327E-01 -4.3879E-05 394.0 994.0],\r\n \"1-Propanol\"=>[-14.894 3.2171E-01 -5.8021E-05 200.0 1000.0],\r\n \"Acetaldehyde\"=>[0.069 3.0246E-01 -4.2372E-05 294.0 1000.0],\r\n \"Acetic acid\"=>[-28.660 2.3510E-01 2.2087E-04 366.0 523.0],\r\n \"Acetic anhydride\"=>[-1.485 2.8869E-01 -2.3391E-05 295.0 993.0],\r\n \"Acetone\"=>[-4.055 2.6655E-01 -5.6936E-06 300.0 650.0],\r\n \"Acrylic acid\"=>[-6.532 3.0600E-01 -4.6620E-05 287.0 1000.0],\r\n \"Ammonia\"=>[-7.874 3.6700E-01 -4.4700E-06 195.0 1000.0],\r\n \"Aniline\"=>[-6.918 2.5935E-01 -3.4348E-05 458.0 1000.0],\r\n \"Benzene\"=>[-0.151 2.5706E-01 -8.9797E-06 287.0 628.0],\r\n \"Butyric acid\"=>[-5.781 2.6159E-01 -3.4903E-05 268.0 1000.0],\r\n \"Carbon disulfide\"=>[-7.700 3.6594E-01 -2.5416E-05 273.0 583.0],\r\n \"Carbon dioxide\"=>[11.811 4.9838E-01 -1.0851E-04 195.0 1500.0],\r\n \"Carbon monoxide\"=>[23.811 5.3944E-01 -1.5411E-04 68.0 1250.0],\r\n \"Carbon tetrachloride\"=>[-7.745 3.9481E-01 -1.1150E-04 280.0 800.0],\r\n \"Chloroform\"=>[-4.392 3.7309E-01 -5.1696E-05 250.0 700.0],\r\n \"Chlorine\"=>[-3.571 4.8700E-01 -8.5300E-05 200.0 1000.0],\r\n \"Cyclohexane\"=>[1.190 2.4542E-01 -3.8334E-05 315.0 600.0],\r\n \"Cyclohexanol\"=>[-13.542 2.9086E-01 -3.9472E-05 400.0 1000.0],\r\n \"Cyclopropane\"=>[-9.521 3.7037E-01 -1.3138E-04 240.0 446.0],\r\n \"Dichloromethane\"=>[-20.372 4.3745E-01 -7.7549E-05 273.0 993.0],\r\n \"Diethyl ether\"=>[-7.932 3.0235E-01 -7.3858E-05 200.0 1000.0],\r\n \"Diethyl ketone\"=>[-3.593 2.4308E-01 -3.7613E-05 234.0 1000.0],\r\n \"Dimethylamine\"=>[-9.275 2.8958E-01 -1.3875E-06 250.0 450.0],\r\n \"Ethane\"=>[0.514 3.3449E-01 -7.1071E-05 150.0 1000.0],\r\n \"Ethanol\"=>[1.499 3.0741E-01 -4.4479E-05 200.0 1000.0],\r\n \"Ethyl acetate\"=>[-9.259 3.0725E-01 -7.1069E-05 190.0 1000.0],\r\n \"Ethyl chloride\"=>[0.458 3.2827E-01 -1.2467E-05 213.0 523.0],\r\n \"Ethylbenzene\"=>[-4.267 2.4735E-01 -5.4264E-05 409.0 1000.0],\r\n \"Ethylene\"=>[-3.985 3.8726E-01 -1.1227E-04 150.0 1000.0],\r\n \"Ethylene glycol\"=>[-7.178 3.1246E-01 -4.4028E-05 260.0 1000.0],\r\n \"Ethylene oxide\"=>[-12.180 3.7672E-01 -7.7599E-05 250.0 1000.0],\r\n \"Fluorine\"=>[-0.811 8.9800E-01 -3.9600E-04 90.0 500.0],\r\n \"Glycerol\"=>[-23.119 2.8879E-01 -3.4277E-05 563.0 993.0],\r\n \"Hydrogen\"=>[27.758 2.1200E-01 -3.2800E-05 150.0 1500.0],\r\n \"Hydrogen chloride\"=>[-9.118 5.5500E-01 -1.1100E-04 200.0 1000.0],\r\n \"Hydrogen cyanide\"=>[-8.486 9.0368E-02 7.9146E-05 300.0 425.0],\r\n \"Hydrogen peroxide\"=>[8.039 2.7000E-01 8.2900E-05 373.0 600.0],\r\n \"i-Butane\"=>[-4.731 2.9131E-01 -8.0995E-05 150.0 1000.0],\r\n \"Methane\"=>[3.844 4.0112E-01 -1.4303E-04 91.0 850.0],\r\n \"Methanol\"=>[-14.236 3.8935E-01 -6.2762E-05 240.0 1000.0],\r\n \"Methyl bromide\"=>[-27.740 5.5901E-01 -7.0942E-05 260.0 440.0],\r\n \"Methyl chloride\"=>[-1.374 3.8627E-01 -4.8650E-05 230.0 700.0],\r\n \"Methyl isobutyl ketone\"=>[-3.237 2.3310E-01 -3.5612E-05 189 1000],\r\n \"Methylamine\"=>[-5.334 3.4181E-01 -7.4297E-05 267.0 1000.0],\r\n \"m-Xylene\"=>[-21.620 2.7820E-01 -6.0531E-05 250.0 1000.0],\r\n \"Naphthalene\"=>[-16.789 2.5406E-01 -3.5495E-05 353.0 1000.0],\r\n \"n-Butane\"=>[-4.946 2.9001E-01 -6.9665E-05 150.0 1200.0],\r\n \"n-Decane\"=>[-7.297 1.8506E-01 -4.8008E-06 287.0 783.0],\r\n \"n-Heptane\"=>[-10.378 2.4401E-01 -5.4003E-05 338.0 700.0],\r\n \"n-Hexane\"=>[-8.222 2.6229E-01 -5.7366E-05 300.0 1000.0],\r\n \"Nitrobenzene\"=>[-16.569 2.9184E-01 -2.5523E-05 450.0 1000.0],\r\n \"Nitrogen\"=>[42.606 4.7500E-01 -9.8800E-05 150.0 1500.0],\r\n \"n-Nonane\"=>[-6.802 1.8688E-01 3.4929E-07 273.0 773.0],\r\n \"n-Octane\"=>[3.940 1.6640E-01 1.4470E-05 374.0 670.0],\r\n \"n-Pentane\"=>[-3.202 2.6746E-01 -6.6178E-05 303.0 900.0],\r\n \"Oxygen\"=>[44.224 5.6200E-01 -1.1300E-04 150.0 1500.0],\r\n \"o-Xylene\"=>[-19.763 2.8022E-01 -5.9293E-05 250.0 1000.0],\r\n \"Phenol\"=>[-7.185 2.7179E-01 -3.6205E-05 455.0 1000.0],\r\n \"Propane\"=>[-5.462 3.2722E-01 -1.0672E-04 193.0 750.0],\r\n \"p-Xylene\"=>[-17.226 2.5098E-01 -2.8232E-05 286.0 1000.0],\r\n \"Pyridine\"=>[-5.739 2.7135E-01 -1.7202E-05 369.0 998.0],\r\n \"Styrene\"=>[-10.035 2.5191E-01 -3.7932E-05 243.0 1000.0],\r\n \"Sulfur dioxide\"=>[-11.103 5.0200E-01 -1.0800E-04 200.0 1000.0],\r\n \"Toluene\"=>[1.787 2.3566E-01 -9.3508E-06 275.0 600.0],\r\n \"Vinyl acetate\"=>[-7.462 3.0466E-01 -5.7544E-05 346.0 1000.0],\r\n \"Water\"=>[-36.826 4.2900E-01 -1.6200E-05 280.0 1073.0])\r\n\r\n# Parameters for Liquid Viscosity\r\nDataLiquidViscosity=Dict(\"1,1,1-Trichloroethane\"=>[-3.9096 7.0709E+02 7.5847E-03 -9.1662E-06 243 545],\r\n \"1,1,2-Trichloroethane\"=>[-3.2716 6.8810E+02 4.8932E-03 -5.4671E-06 237 602],\r\n \"1,1-Dichloroethane\"=>[-3.8388 5.9046E+02 8.0953E-03 -9.9210E-06 176 523],\r\n \"1,2-Dichloroethane\"=>[-0.1656 2.7576E+02 -3.3493E-03 1.4093E-06 245 561],\r\n \"1,3-Butadiene\"=>[0.3772 7.9658E+01 -5.8889E-03 2.9221E-06 250 425],\r\n \"1,4-Dioxane\"=>[-7.5724 1.3813E+03 1.3556E-02 -1.1464E-05 288 587],\r\n \"1-Butanol (n-Butanol)\"=>[-5.3970 1.3256E+03 6.2223E-03 -5.5062E-06 250 563],\r\n \"1-Butene\"=>[-4.9218 4.9503E+02 1.4390E-02 -2.0853E-05 160 420],\r\n \"1-Decene\"=>[-6.8845 1.1003E+03 1.4341E-02 -1.3520E-05 273 617],\r\n \"1-Nonane (n-Nonane)\"=>[-6.0742 9.6861E+02 1.2677E-02 -1.2675E-05 220 596],\r\n \"1-Octene\"=>[-5.6209 8.1305E+02 1.2523E-02 -1.3384E-05 250 567],\r\n \"1-Propanol (n-Propanol)\"=>[-3.7702 9.9151E+02 4.0836E-03 -5.4586E-06 220 537],\r\n \"Acetaldehyde\"=>[-6.6171 6.8123E+02 1.9979E-02 -2.5563E-05 260 461],\r\n \"Acetic acid\"=>[-3.8937 7.8482E+02 6.6650E-03 -7.5606E-06 290 593],\r\n \"Acetic anhydride\"=>[-17.3580 2.3611E+03 4.2734E-02 -3.8202E-05 265 569],\r\n \"Acetone\"=>[-7.2126 9.0305E+02 1.8385E-02 -2.0353E-05 223 508],\r\n \"Acrylic acid\"=>[5.9215 2.4408E+03 3.4383E-02 -2.7677E-05 293 615],\r\n \"Ammonia\"=>[-8.5910 8.7640E+02 2.6810E-02 -3.6120E-05 195 406],\r\n \"Aniline\"=>[-13.8625 2.5109E+03 2.5681E-02 -1.8281E-05 268 699],\r\n \"Benzene\"=>[-7.4005 1.1815E+03 1.4888E-02 -1.3713E-05 285 562],\r\n \"Butyric acid\"=>[-7.9846 1.3636E+03 1.6315E-02 -1.4511E-05 268 628],\r\n \"carbon disulfide\"=>[-9.1108 1.1216E+03 2.3216E-02 -2.2648E-05 235 552],\r\n \"Carbon dioxide\"=>[-19.4921 1.5948E+03 7.9274E-02 -1.2025E-04 219 304],\r\n \"Carbon monoxide\"=>[-1.1224 5.7858E+01 -4.9174E-03 8.2233E-06 69 133],\r\n \"Carbon tetrachloride\"=>[-6.4564 1.0379E+03 1.4021E-02 -1.4107E-05 265 556],\r\n \"Chlorine\"=>[-0.7681 1.5140E+02 -8.0650E-04 4.0750E-07 172 417],\r\n \"Chloroform\"=>[-47831 6.9902E+02 1.0929E-02 -1.2244E-05 210 536],\r\n \"Cyclohexane\"=>[.7423 -2.5322E+02 -1.6927E-02 1.2472E-05 285 554],\r\n \"Cyclohexanol\"=>[-5.3792 1.8793E+03 1.7011E-03 1.0187E-07 303 625],\r\n \"Cyclopropane\"=>[-3.2541 3.2192E+02 9.9766E-03 -1.8191E-05 146 398],\r\n \"Dichloromethane\"=>[5.1043 6.8653E+02 1.2459E-02 -1.4540E-05 208 510],\r\n \"Diethyl ether\"=>[-8.5060 1.0020E+03 2.2753E-02 -2.5780E-05 233 467],\r\n \"Diethyl ketone\"=>[-9.2905 1.2716E+03 2.1925E-02 -2.1036E-05 274 561],\r\n \"Dimethylamine\"=>[-11.5558 1.2126E+03 3.4999E-02 -4.1253E-05 240 438],\r\n \"Ethane\"=>[-4.2694 2.8954E+02 1.7111E-02 -3.6092E-05 98 305],\r\n \"Ethanol\"=>[-6.4406 1.1176E+03 1.3721E-02 -1.5465E-05 240 516],\r\n \"Ethyl acetate\"=>[-3.6861 5.5228E+02 8.0018E-03 -1.0439E-05 220 523],\r\n \"Ethyl chloride\"=>[-4.4279 5.1891E+02 1.2035E-02 -1.6620E-05 150 460],\r\n \"Ethylbenzene\"=>[-5.2585 8.3065E+02 1.0784E-02 -1.0618E-05 210 617],\r\n \"Ethylene\"=>[-4.5611 3.0811E+02 1.8030E-02 -3.8145E-05 105 282],\r\n \"Ethylene glycol\"=>[-16.9728 3.1886E+03 3.2537E-02 -2.4480E-05 261 645],\r\n \"Ethylene oxide\"=>[-5.7794 6.7020E+02 1.5686E-02 -1.9462E-05 190 469],\r\n \"Fluorine\"=>[-1.5760 8.5630E+01 -4.0730E-04 -2.7250E-06 54 145],\r\n \"Glycerol\"=>[-18.2152 4.2305E+03 2.8705E-02 -1.8648E-05 293 723],\r\n \"Hydrogen\"=>[-7.0154 4.0791E+01 2.3714E-01 -4.0830E-03 14 33],\r\n \"Hydrogen chloride\"=>[-1.5150 1.9460E+02 3.0670E-03 -1.3760E-05 159 325],\r\n \"Hydrogen cyanide\"=>[-12.0812 1.3183E+03 3.5234E-02 -4.0185E-05 260 457],\r\n \"Hydrogen peroxide\"=>[-1.6150 5.0380E+02 3.5010E-04 -1.1680E-06 273 728],\r\n \"i-Butane (iso-Butane)\"=>[-13.4207 1.3131E+03 4.4329E-02 -5.5793E-05 190 408],\r\n \"Methane\"=>[-7.3801 3.1925E+02 4.7934E-02 -1.4120E-04 91 191 - 0.020],\r\n \"Methyl bromide\"=>[-9.5533 1.0306E+03 2.8322E-02 -3.1920E-05 193 467],\r\n \"Methyl chloride\"=>[-7.3473 8.5395E+02 1.9485E-02 -2.3484E-05 249 416],\r\n \"Methyl isobutyl ketone\"=>[-3.0570 5.0050E+02 6.5038E-03 -8.8243E-06 246 571],\r\n \"Methylamine\"=>[-9.4670 9.8286E+02 2.8918E-02 -3.5672E-05 180 430],\r\n \"m-Xylene\"=>[-6.0517 9.2460E+02 1.2583E-02 -1.1850E-05 225 617],\r\n \"Naphthalene\"=>[-10.3716 1.8572E+03 1.9320E-02 -1.4012E-05 353 748],\r\n \"n-Butane\"=>[-6.8590 6.7393E+02 2.1973E-02 -3.0686E-05 180 425],\r\n \"n-Decane\"=>[-6.0716 1.0177E+03 1.2247E-02 -1.1892E-05 243 618],\r\n \"n-Heptane\"=>[-5.7782 8.0587E+02 1.3355E-02 -1.4794E-05 183 540],\r\n \"n-Hexane\"=>[-5.0715 6.5536E+02 1.2349E-02 -1.5042E-05 178 507],\r\n \"Nitrobenzene\"=>[-7.7710 1.4019E+03\t1.4653E-02 -1.1512E-05 273 719],\r\n \"Nitrogen\"=>[-15.6104 4.6505E+02 1.6259E-01 -6.3353E-04 63 125],\r\n \"n-Nonane\"=>[-6.0742 9.6861E+02 1.2677E-02 -1.2675E-05 220 596],\r\n \"n-Octane\"=>[-5.9245 8.8809E+02 1.2955E-02 -1.3596E-05 216 569],\r\n \"n-Pentane\"=>[-7.1711 7.4736E+02 2.1697E-02 -2.7176E-05 143\t470],\r\n \"Oxygen\"=>[-5.0957 1.7983E+02 3.9779E-02 -1.4664E-04 54 150],\r\n \"o-Xylene\"=>[-7.8805 1.2500E+03 1.6116E-02 -1.3993E-05 268 630],\r\n \"Phenol\"=>[.5349 4.2620E+02 -9.1577E-03 6.2322E-06 318 694],\r\n \"p-Xylene\"=>[-9.4655 1.4400E+03 1.9910E-02 -1.6994E-05 288 616],\r\n \"Pyridine\"=>[-6.8100 1.1496E+03 1.3229E-02 -1.1661E-05 232 620],\r\n \"Styrene\"=>[-8.0291 1.2666E+03 1.6127E-02 -1.3475E-05 243 648],\r\n \"Sulfur dioxide\"=>[-2.6700 4.0670E+02 6.1440E-03 -1.2540E-05 200 431],\r\n \"Toluene\"=>[-5.1649 8.1068E+02 1.0454E-02 -1.0488E-05 200 592],\r\n \"Vinyl acetate\"=>[-9.0671 1.1863E+03 2.2663E-02\t-2.3208E-05\t250 524],\r\n \"Water\"=>[-10.2158 1.7925E+03 1.7730E-02 -1.2631E-05 273 643])\r\n", "meta": {"hexsha": "c2bfda0476dcc3c6464cc6cd89bb583b8590d538", "size": 17938, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Data.jl", "max_stars_repo_name": "JuliaChem/ThermProps.jl", "max_stars_repo_head_hexsha": "e2bba4287b225df1fde6c71c28fed29439cc38a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-11-03T07:14:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T22:27:30.000Z", "max_issues_repo_path": "src/Data.jl", "max_issues_repo_name": "JuliaChem/ThermProps.jl", "max_issues_repo_head_hexsha": "e2bba4287b225df1fde6c71c28fed29439cc38a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data.jl", "max_forks_repo_name": "JuliaChem/ThermProps.jl", "max_forks_repo_head_hexsha": "e2bba4287b225df1fde6c71c28fed29439cc38a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-01T23:24:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-01T23:24:34.000Z", "avg_line_length": 76.9871244635, "max_line_length": 103, "alphanum_fraction": 0.549057866, "num_tokens": 8651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.15749850955526457}} {"text": "# MIT license\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# See LICENSE in the project root for full license information.\n\n# all other glasses should follow the format below, new glasses must be added to OTHER_GLASSES and OTHER_GLASS_NAMES where the index in the array matches the numeric part of the GlassID\n\nmodule CARGILLE\nusing ..GlassCat: Glass, GlassID, OTHER\n\nconst OG0608 = Glass(GlassID(OTHER, 1), -2, 1.4451400, 0.0043176, -1.80659e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.0009083144750540808, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.008, -1.0, -1.0, 800.0, -1.0, 0, -1.0, [(0.32, 0.03, 10.0), (0.365, 0.16, 100.0), (0.4047, 0.40, 100.0), (0.480, 0.71, 100.0), (0.4861, 0.72, 100.0), (0.5461, 0.80, 100.0), (0.5893, 0.90, 100.0), (0.6328, 0.92, 100.0), (0.6439, 0.95, 100.0), (0.6563, 0.96, 100.0), (0.6943, 0.99, 100.0), (0.840, 0.99, 100.0), (0.10648, 0.74, 100.0), (0.1300, 0.39, 100.0), (0.1550, 0.16, 100.0)], 1.457518, -1.0, -1.0, 0, 57.18978, 0, 0.878, -1)\nconst OG0607 = Glass(GlassID(OTHER, 2), -2, 1.44503, 0.0044096, -2.85878e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.0009083144750540808, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.008, -1.0, -1.0, 700.0, -1.0, 0, -1.0, [(0.32, 0.15, 10.0), (0.365, 0.12, 100.0), (0.4047, 0.42, 100.0), (0.480, 0.78, 100.0), (0.4861, 0.79, 100.0), (0.5461, 0.86, 100.0), (0.5893, 0.90, 100.0), (0.6328, 0.92, 100.0), (0.6439, 0.90, 100.0), (0.6563, 0.92, 100.0), (0.6943, 0.98, 100.0), (0.840, 0.99, 100.0), (0.10648, 0.61, 100.0), (0.1300, 0.39, 100.0), (0.1550, 0.11, 100.0)], 1.457587, -1.0, -1.0, 0, 57.19833, 0, 0.878, -1)\nconst OG081160 = Glass(GlassID(OTHER, 3), -2, 1.49614, 0.00692199, -8.07052e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32, 1.55, -0.000885983052189022, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.014, -1.0, -1.0, 700.0, -1.0, 0, -1.0, [(0.32, 0.04, 100.0), (0.365, 0.13, 100.0), (0.4047, 0.26, 100.0), (0.480, 0.48, 100.0), (0.4861, 0.49, 100.0), (0.5461, 0.60, 100.0), (0.5893, 0.68, 100.0), (0.6328, 0.71, 100.0), (0.6439, 0.73, 100.0), (0.6563, 0.74, 100.0), (0.6943, 0.76, 100.0), (0.840, 0.83, 100.0), (0.10648, 0.86, 100.0), (0.1300, 0.89, 100.0), (0.1550, 0.90, 100.0)], 1.515549, -1.0, -1.0, 0, 36.82493, 0, 1.11, -1)\n\nend\n\nconst OTHER_GLASSES = [CARGILLE.OG0607, CARGILLE.OG0608, CARGILLE.OG081160]\nconst OTHER_GLASS_NAMES = [\"CARGILLE.OG0607\", \"CARGILLE.OG0608\", \"CARGILLE.OG081160\"]\n", "meta": {"hexsha": "f544ea1737289bef50f6aa1a6ac624f7c525a997", "size": 2388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GlassCat/data/jl/CARGILLE.jl", "max_stars_repo_name": "KristofferC/OpticSim.jl", "max_stars_repo_head_hexsha": "3dbe82a51fb3c7d2896f19318d3e4756e54fb6d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-04T03:42:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-04T03:42:27.000Z", "max_issues_repo_path": "src/GlassCat/data/jl/CARGILLE.jl", "max_issues_repo_name": "KristofferC/OpticSim.jl", "max_issues_repo_head_hexsha": "3dbe82a51fb3c7d2896f19318d3e4756e54fb6d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GlassCat/data/jl/CARGILLE.jl", "max_forks_repo_name": "KristofferC/OpticSim.jl", "max_forks_repo_head_hexsha": "3dbe82a51fb3c7d2896f19318d3e4756e54fb6d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-20T23:30:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T23:30:02.000Z", "avg_line_length": 132.6666666667, "max_line_length": 612, "alphanum_fraction": 0.5887772194, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.15741634930955486}} {"text": "\nmutable struct EvoDuplex <: AbstractDuplex\n duplex::RNADuplex\n alignment::Array{DNA,2}\n first::Int\n bracket::Vector{Char}\n score::Float64\n\n function EvoDuplex( rdup::RNADuplex, tree::PhyloTree, dsa::RNADuplexArray, fwd_index, rev_index )\n alignment = Array{DNA,2}(length(tree.order), sum(lengths(rdup.path)))\n first = 1\n last = size(alignment, 2)\n bracket = Vector{Char}(size(alignment, 2))\n i,j = 0,0\n for k in 1:length(rdup.path)\n if isbulge(rdup[k]) && isfiveprime(rdup[k])\n i += 1\n col = DNA[dsa.fwd.species[s][i][fwd_index] for s in 1:length(tree.order)-1]\n unshift!(col, dsa.fwd.depth[i][fwd_index])\n alignment[:,first] = col\n bracket[first] = '.'\n first += 1\n elseif isbulge(rdup[k]) && !isfiveprime(rdup[k])\n j += 1\n col = DNA[dsa.rev.species[s][j][rev_index] for s in 1:length(tree.order)-1] \n unshift!(col, dsa.rev.depth[j][rev_index])\n alignment[:,last] = col\n bracket[last] = '.'\n last -= 1\n else\n i += 1\n j += 1\n const lcol = DNA[dsa.fwd.species[s][i][fwd_index] for s in 1:length(tree.order)-1]\n const rcol = DNA[dsa.rev.species[s][j][rev_index] for s in 1:length(tree.order)-1]\n unshift!(lcol, dsa.fwd.depth[i][fwd_index])\n unshift!(rcol, dsa.rev.depth[j][rev_index])\n #println(\"dsa.rev.depth $j $rev_index\")\n alignment[:,first] = lcol\n alignment[:,last] = rcol\n bracket[first] = '('\n bracket[last] = ')'\n first += 1\n last -= 1\n end\n end\n return new( deepcopy(rdup), alignment, first-1, bracket, 0.0 )\n end\n\n function EvoDuplex( rdup::RNADuplex, single::PhyloTree, paired::PhyloTree, dsa::RNADuplexArray, fwd_index, rev_index )\n evo = EvoDuplex( rdup, single, dsa, fwd_index, rev_index )\n score!( evo, single, paired )\n return evo\n end\nend\n\npath( evo::EvoDuplex ) = evo.duplex.path\n\nenergy( evo::EvoDuplex ) = energy( evo.duplex )\nenergies( evo::EvoDuplex ) = map( energy, [evo.duplex; evo.species] )\n\nnpairs( evo::EvoDuplex ) = npairs( evo.duplex )\nnmismatches( evo::EvoDuplex ) = nmismatches( evo.duplex )\nnbulges( evo::EvoDuplex ) = nbulges( evo.duplex )\n\nstrings( evo::EvoDuplex ) = strings( evo.duplex )\nbrackets( evo::EvoDuplex ) = brackets( evo.duplex )\n\nBase.push!{NP <: NucleotidePair}( evo::EvoDuplex, pair::NP ) = push!( evo.duplex, pair )\nBase.push!{NP <: NucleotidePair}( evo::EvoDuplex, path::Vector{NP} ) = push!( evo.duplex, path )\n\nfunction join_duplex!( left::EvoDuplex, right::EvoDuplex, npairs, npairs_first, npairs_last )\n push!( left.duplex, path(right.duplex)[npairs+1:end] )\n last = (size(left.alignment, 2) - left.first) - npairs_last - 1\n first = left.first - npairs_first\n# try\n left.alignment = hcat(left.alignment[:,1:first], right.alignment, left.alignment[:,(end-last:end)])\n left.bracket = vcat(left.bracket[1:first], right.bracket, left.bracket[end-last:end])\n left.first = right.first + first\n# catch\n# println(STDERR, \"$left\\n$right\\n$npairs\\n$npairs_first\\n$npairs_last\")\n# end\n left\nend\n\nmutable struct EvoScore \n unstr_cons::Float64\n struc_neut::Float64\n struc_cons::Float64\n mean_covar::Float64\n mean_cons::Float64\nend\n\n\nscore( evo::EvoDuplex ) = evo.score\n\nfunction score!( evo::EvoDuplex, single::PhyloTree, paired::PhyloTree )\n uns_like = 0.0\n str_like = 0.0\n first = 1\n last = size(evo.alignment, 2)\n for k in 1:length(evo.duplex.path)\n if isbulge(evo.duplex[k]) && isfiveprime(evo.duplex[k]) \n like = likelihood( single, evo.alignment[:,first] )\n str_like += log2(like)\n uns_like += log2(like)\n first += 1\n elseif isbulge(evo.duplex[k]) && !isfiveprime(evo.duplex[k])\n like = likelihood( single, evo.alignment[:,last] )\n str_like += log2(like)\n uns_like += log2(like)\n last -= 1\n else\n str_like += log2(likelihood(paired, evo.alignment[:,first], evo.alignment[:,last]))\n uns_like += log2(likelihood(single, evo.alignment[:,first])) + log2(likelihood(single, evo.alignment[:,last]))\n first += 1\n last -= 1\n end\n end\n evo.score = str_like - uns_like\n str_like\nend\n\nfunction score( evo::EvoDuplex, single::PhyloTree; gapdenom=1.0 )\n single_like = 0.0\n for k in 1:size(evo.alignment,2)\n single_like += log2(likelihood( single, evo.alignment[:,k], gapdenom=gapdenom ))\n end\n single_like\nend\n\nfunction pscore!( evo::EvoDuplex, single::PhyloTree, paired::PhyloTree )\n uns_like = 0.0\n str_like = 0.0\n first = 1\n last = size(evo.alignment, 2)\n for k in 1:length(evo.duplex.path)\n if isbulge(evo.duplex[k]) && isfiveprime(evo.duplex[k])\n like = likelihood( single, evo.alignment[:,first] )\n str_like += log2(like)\n uns_like += log2(like)\n first += 1\n elseif isbulge(evo.duplex[k]) && !isfiveprime(evo.duplex[k])\n like = likelihood( single, evo.alignment[:,last] )\n str_like += log2(like)\n uns_like += log2(like)\n last -= 1\n else\n str_like += log2(likelihood(paired, evo.alignment[:,first], evo.alignment[:,last]))\n uns_like += log2(likelihood(single, evo.alignment[:,first])) + log2(likelihood(single, evo.alignment[:,last]))\n first += 1\n last -= 1\n end\n end\n evo.score = str_like - uns_like\n evo.score\nend\n\nfunction covariance( evo::EvoDuplex )\n first = 1\n last = size(evo.alignment, 2)\n vals = 0.0\n npairs = 0\n for k in 1:length(evo.duplex.path)\n if isbulge(evo.duplex[k]) && isfiveprime(evo.duplex[k])\n first += 1\n elseif isbulge(evo.duplex[k]) && !isfiveprime(evo.duplex[k])\n last -= 1\n else\n cov = covariance_score(evo.alignment[:,first], evo.alignment[:,last])\n #print(\" $cov \")\n vals += cov\n first += 1\n last -= 1\n npairs += 1\n end\n end\n #println( \" $maxval \\n\" )\n vals / npairs\nend\n\nconst PI_MATRIX = [0.0 0.0 0.0 1.0\n 0.0 0.0 1.0 0.0\n 0.0 1.0 0.0 1.0\n 1.0 0.0 1.0 0.0]\n\ndelta( a::DNA, b::DNA ) = a == b ? 1 : 0\n\nfunction pi_matrix( a::DNA, b::DNA )\n if isgap( a ) || isgap( b ) \n return 0.0\n else\n const ind_a = trailing_zeros(reinterpret(UInt8, a)) + 1\n const ind_b = trailing_zeros(reinterpret(UInt8, b)) + 1\n return PI_MATRIX[ ind_a, ind_b ]\n end\nend\n\n# Calculated as described by Hofacker et al. Journal of Molecular Biology 2002.\n# https://www.ncbi.nlm.nih.gov/pubmed/12079347\nfunction covariance_score( a::Vector{DNA}, b::Vector{DNA} )\n denom = binomial(length(a), 2)\n numer = 0.0\n pairs = 0\n for i in 1:length(a)-1\n pairs += pi_matrix( a[i], b[i] )\n for j in i+1:length(a)\n numer += (2 - delta(a[i], a[j]) - delta(b[i], b[j])) * pi_matrix( a[i], b[i] ) * pi_matrix( a[j], b[j] )\n end\n end\n pairs += pi_matrix( a[end], b[end] )\n return (numer / denom) * (pairs / length(a))\nend\n\n\n", "meta": {"hexsha": "8a33153cbb40b46502cbe8b01bc6204bb581cf4c", "size": 7233, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evoduplex.jl", "max_stars_repo_name": "timbitz/EvoDuplexes.jl", "max_stars_repo_head_hexsha": "8eb7a6b529a3fe9e47cfb65dd4cf15067a3e0b5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-01-14T08:27:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T05:41:57.000Z", "max_issues_repo_path": "src/evoduplex.jl", "max_issues_repo_name": "timbitz/EvoDuplexes.jl", "max_issues_repo_head_hexsha": "8eb7a6b529a3fe9e47cfb65dd4cf15067a3e0b5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-10-16T00:04:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-16T22:53:21.000Z", "max_forks_repo_path": "src/evoduplex.jl", "max_forks_repo_name": "timbitz/EvoDuplexes.jl", "max_forks_repo_head_hexsha": "8eb7a6b529a3fe9e47cfb65dd4cf15067a3e0b5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T19:07:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T19:07:27.000Z", "avg_line_length": 33.6418604651, "max_line_length": 121, "alphanum_fraction": 0.5885524679, "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15448586725493532}} {"text": "export DistProduct, ProdGeneric\n\nimport Distributions\nimport Base: prod, show\n\n\"\"\"\n DistProduct\n\nIf inference backend cannot return an analytical solution for a product of two distributions it may fallback to the `DistProduct` structure\n`DistProduct` is useful to propagate the exact forms of two messages until it hits some approximation method for form-constraint.\nHowever `DistProduct` cannot be used to compute statistics such as mean or variance. \nIt has to be approximated before using in actual inference procedure.\n\nBackend exploits form constraints specification which usually help to deal with intractable distributions products. \nUser may use EM form constraint with a specific optimisation algorithm or it may approximate intractable product with Gaussian Distribution\nusing for example Laplace approximation \n\nSee also: [`prod`](@ref)\n\"\"\"\nstruct DistProduct{ L, R }\n left :: L\n right :: R\nend\n\nBase.show(io::IO, product::DistProduct) = print(io, \"DistProduct(\", getleft(product), \",\", getright(product), \")\")\n\ngetleft(product::DistProduct) = product.left\ngetright(product::DistProduct) = product.right\n\nfunction Distributions.support(product::DistProduct)\n lsupport = Distributions.support(getleft(product))\n rsupport = Distributions.support(getright(product))\n if lsupport != rsupport\n error(\"Product $product has different support for left and right entries.\")\n end\n return lsupport\nend\n\nDistributions.mean(product::DistProduct) = error(\"mean() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.median(product::DistProduct) = error(\"median() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.mode(product::DistProduct) = error(\"mode() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.shape(product::DistProduct) = error(\"shape() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.scale(product::DistProduct) = error(\"scale() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.rate(product::DistProduct) = error(\"rate() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.var(product::DistProduct) = error(\"var() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.std(product::DistProduct) = error(\"std() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.cov(product::DistProduct) = error(\"cov() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.invcov(product::DistProduct) = error(\"invcov() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.logdetcov(product::DistProduct) = error(\"logdetcov() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.entropy(product::DistProduct) = error(\"entropy() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nDistributions.params(product::DistProduct) = error(\"params() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\n\nDistributions.pdf(product::DistProduct, x) = Distributions.pdf(product.left, x) * Distributions.pdf(product.right, x)\nDistributions.logpdf(product::DistProduct, x) = Distributions.logpdf(product.left, x) + Distributions.logpdf(product.right, x)\n\nBase.precision(product::DistProduct) = error(\"precision() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nBase.length(product::DistProduct) = error(\"length() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nBase.ndims(product::DistProduct) = error(\"ndims() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nBase.size(product::DistProduct) = error(\"size() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\n\nprobvec(product::DistProduct) = error(\"probvec() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\nweightedmean(product::DistProduct) = error(\"weightedmean() is not defined for $(product). DistProduct structure has to be approximated and cannot be used in inference procedure.\")\n\nvariate_form(::P) where { P <: DistProduct } = variate_form(P)\nvariate_form(::Type{ DistProduct{L, R} }) where { L, R } = _check_dist_product_variate_form(variate_form(L), variate_form(R))\n\n_check_dist_product_variate_form(::Type{ F }, ::Type{ F }) where { F <: VariateForm } = F\n_check_dist_product_variate_form(::Type{ F1 }, ::Type{ F2 }) where { F1 <: VariateForm, F2 <: VariateForm } = error(\"DistProduct has different variate forms for left ($F1) and right ($F2) entries.\")\n\nvalue_support(::P) where { P <: DistProduct } = value_support(P)\nvalue_support(::Type{ DistProduct{L, R} }) where { L, R } = _check_dist_product_value_support(value_support(L), value_support(R))\n\n_check_dist_product_value_support(::Type{ S }, ::Type{ S }) where { S <: ValueSupport } = S\n_check_dist_product_value_support(::Type{ S1 }, ::Type{ S2 }) where { S1 <: ValueSupport, S2 <: ValueSupport } = error(\"DistProduct has different value supports for left ($S1) and right ($S2) entries.\")\n\n\"\"\"\n ProdGeneric{C}\n\n`ProdGeneric` is one of the strategies for `prod` function. This strategy mimics `prod_constraint` constraint but does not fail in case of no analytical rule is available.\n\nSee also: [`prod`](@ref), [`ProdAnalytical`](@ref), [`ProdPreserveType`](@ref)\n\"\"\"\nstruct ProdGeneric{C} \n prod_constraint :: C\nend\n\nget_constraint(prod_generic::ProdGeneric) = prod_generic.prod_constraint\n\nProdGeneric() = ProdGeneric(ProdAnalytical())\n\nprod(::ProdGeneric, ::Missing, right) = right\nprod(::ProdGeneric, left, ::Missing) = left\nprod(::ProdGeneric, ::Missing, ::Missing) = missing\n\nprod(generic::ProdGeneric, left::L, right::R) where { L, R } = prod(generic, prod_analytical_rule(L, R), left, right)\n\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleAvailable, left, right) = prod(get_constraint(generic), left, right)\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleUnknown, left, right) = DistProduct(left, right)\n\n# In case of ProdPointMass we want to propagate a single `DistProduct` as much as possible and do not create a big tree of product which will reduce performance significantly\n# In this methods the general rule is the folowing: If we see that one of the arguments of `DistProduct` has the same function form \n# as second argument of `prod` function it is better to try to `prod` them together with `NoConstraint` strategy.\nprod(generic::ProdGeneric, left::DistProduct{L, R}, right::T) where { L, R, T } = prod(generic, prod_analytical_rule(L, T), prod_analytical_rule(R, T), left, right)\nprod(generic::ProdGeneric, left::T, right::DistProduct{L, R}) where { L, R, T } = prod(generic, prod_analytical_rule(T, L), prod_analytical_rule(T, R), left, right)\n\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleUnknown, ::ProdAnalyticalRuleUnknown, left::DistProduct, right) = DistProduct(left, right)\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleAvailable, ::ProdAnalyticalRuleUnknown, left::DistProduct, right) = DistProduct(prod(get_constraint(generic), getleft(left), right), getright(left))\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleUnknown, ::ProdAnalyticalRuleAvailable, left::DistProduct, right) = DistProduct(getleft(left), prod(get_constraint(generic), getright(left), right))\n\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleUnknown, ::ProdAnalyticalRuleUnknown, left, right::DistProduct) = DistProduct(left, right)\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleAvailable, ::ProdAnalyticalRuleUnknown, left, right::DistProduct) = DistProduct(prod(get_constraint(generic), left, getleft(right)), getright(right))\nprod(generic::ProdGeneric, ::ProdAnalyticalRuleUnknown, ::ProdAnalyticalRuleAvailable, left, right::DistProduct) = DistProduct(getleft(right), prod(get_constraint(generic), left, getright(right)))\n\nfunction prod(generic::ProdGeneric, left::DistProduct{L1, R1}, right::DistProduct{L2, R2}) where {L1, R1, L2, R2}\n return prod(\n generic, \n prod_analytical_rule(L1, L2), prod_analytical_rule(L1, R2),\n prod_analytical_rule(R1, L2), prod_analytical_rule(R1, R2),\n left, right\n )\nend\n\nprod(::ProdGeneric, _, _, _, _, left::DistProduct, right::DistProduct) = DistProduct(left, right)\n\nfunction prod(generic::ProdGeneric, ::ProdAnalyticalRuleAvailable, _, _, ::ProdAnalyticalRuleAvailable, left::DistProduct, right::DistProduct)\n return prod(generic, prod(get_constraint(generic), getleft(left), getleft(right)), prod(get_constraint(generic), getright(left), getright(right)))\nend\n\n", "meta": {"hexsha": "0f6b74494e8ae7ad31957b8da217078daf301b49", "size": 9721, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/constraints/prod/prod_generic.jl", "max_stars_repo_name": "HoangMHNguyen/ReactiveMP.jl", "max_stars_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/constraints/prod/prod_generic.jl", "max_issues_repo_name": "HoangMHNguyen/ReactiveMP.jl", "max_issues_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constraints/prod/prod_generic.jl", "max_forks_repo_name": "HoangMHNguyen/ReactiveMP.jl", "max_forks_repo_head_hexsha": "f3e848ab171e0786e3d8eb6a0843dbf6dacc7415", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.3565891473, "max_line_length": 202, "alphanum_fraction": 0.7482769262, "num_tokens": 2272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2845760102840561, "lm_q1q2_score": 0.15338169455335207}} {"text": "#!/bin/env julia\n\nusing CLI, JLD, Distributions, HypothesisTests\n\nimmutable Region\n\tstart::Int32\n\tstop::Int32\nend\n\n# Print comment lines to stdout and return\n# first non-comment line\nfunction skip_to_header(vcf_file)\n\twhile true\n\t\tline = readline(vcf_file); \n\t\tif !startswith( line, \"#\") return line; end\t\t\n\t\tprintln(line);\n\tend\nend\n\ndrop_chr_prefix(chr) = startswith(chr, \"chr\") ? chr[4:end] : chr\n\nis_protein_altering(effect) = ismatch(\n\tr\"Missense|[Ff]rameshift|Stopgain|Stoploss|Splice\", effect);\n\nfunction mutation_class(ref, alt)\n\tif ref == \"C\"\n\t\tif alt == \"A\"; return 1; end\n\t\tif alt == \"G\"; return 2; end\n\t\tif alt == \"T\"; return 3; end\n\telseif ref == \"G\"\n\t\tif alt == \"T\"; return 1; end\n\t\tif alt == \"C\"; return 2; end\n\t\tif alt == \"A\"; return 3; end\n\telseif ref == \"T\"\n\t\tif alt == \"A\"; return 4; end\n\t\tif alt == \"C\"; return 5; end\n\t\tif alt == \"G\"; return 6; end\n\telseif ref == \"A\"\n\t\tif alt == \"T\"; return 4; end\n\t\tif alt == \"G\"; return 5; end\n\t\tif alt == \"C\"; return 6; end\n\tend\n\n\tif length(ref) > 1 || ref == \"-\" || length(alt) > 1 || alt == \"-\"\n\t\treturn 0\n\telse\n\t\terror(\"Mutation class could not be defined.\")\n\tend\nend\n\n\n\n\nfunction somatic(vcf_file::IO, samples_file::IO; alt_reads=3, alt_frac=0.1, \n\ttest_ref_ratio=5, test_bg_ratio=20, test_bg_alpha=1.0, ref_reads=0,\n\tkeep_all=false, min_mapq=10, min_sidedness=6, keep_old_stars::Bool=false)\n\n\theader = skip_to_header(vcf_file); println(header)\n\theader_cols = split(header, '\\t') \n\tnotes_col = findfirst(header_cols .== \"NOTES\")\n\talt_col = findfirst(header_cols .== \"ALT\")\n\tref_col = findfirst(header_cols .== \"REF\")\n\n\tsamples = header_cols[notes_col+1:end]; \n\tn_samples = length(samples);\n\n\t# Read samples file and separate the row header\n\td = readdlm(samples_file, '\\t'); \n\tsample_file_header = d[1, :][:]; \n\td = d[2:end, :];\n\n\tsample_test_col = findfirst(sample_file_header .== \"TEST\")\n\tsample_ref_col = findfirst(sample_file_header .== \"REF\")\n\tassert(sample_test_col != 0 && sample_ref_col != 0)\n\n\t# Check that all samples named in the design file are present in the VCF\n\tfor s in unique(d[:, [sample_test_col, sample_ref_col]])\n\t\tif s != \"\" && !(s in samples)\n\t\t\terror(\"Sample $s is listed in the design file but missing from VCF.\")\n\t\tend\n\tend\n\n\t# Background error is estimated based on paired *and* unpaired reference\n\t# samples.\n\tref_samples = filter(s -> s != \"\", unique(d[:, sample_ref_col]))\n\tbackground = indexin(ref_samples, samples)\n\n\t# Get indices of test and ref sample rows in the samples file\n\ttest_rows = d[:, sample_test_col] .!= \"\"\n\ttest = indexin(d[test_rows, sample_test_col], samples)\n\tn_tests = length(test);\n\tref = indexin(d[test_rows, sample_ref_col], samples)\n\tinfo(\"Analyzing $n_tests tumor-normal pairs...\")\n\n\tif !isempty(findin(background, test))\n\t\twarn(\"Some background reference samples also used as test samples.\")\n\tend\n\tinfo(\"Calculating background error rate based on $(length(background)) samples...\")\n\n\t# Read alt_frac from design file or command line parameter.\n\talt_frac_col = findfirst(sample_file_header .== \"ALT_FRAC\")\n\tif alt_frac_col == 0\n\t\tinfo(\"Using a mutant allele fraction threshold of $(alt_frac * 100)% for all samples...\")\n\t\talt_frac = ones(n_tests) * alt_frac\n\telse\n\t\talt_frac = convert(Array{Float64}, d[test_rows, alt_frac_col])\n\tend\n\n\t# TODO: Allow sample-specific values to be specified in design file for\n\t# alt_reads, test_ref_ratio and test_bg_ratio as well.\n\n\tfor line in eachline(vcf_file)\n\n\t\tcols = split(line, '\\t')\n\t\talt = zeros(Int32, n_samples); \n\t\ttotal = zeros(Int32, n_samples);\n\t\t# CALL2 support\n\t\tmapq = zeros(Int32, n_samples);\n\t\tbaseq = zeros(Int32, n_samples);\n\t\tsidedness = zeros(Int32, n_samples);\n\n\t\tcall2_format = false\n\t\tis_indel = length(cols[alt_col]) != length(cols[ref_col])\n\n\t\tfor s in 1:n_samples\n\t\t\tcol = cols[notes_col + s]\t\t\t\n\t\t\tgt = split(cols[notes_col + s], ':')\n\t\t\talt[s] = parse(Int32, gt[1])\n\t\t\ttotal[s] = parse(Int32, gt[2])\n\t\t\t# CALL2 support\t\t\t\n\t\t\tif length(gt) >= 5\n\t\t\t\tmapq[s] = parse(Int32, gt[3])\n\t\t\t\tbaseq[s] = parse(Int32, gt[4])\n\t\t\t\tsidedness[s] = parse(Int32, gt[5])\n\t\t\t\tcall2_format = true\n\t\t\tend\n\t\tend\n\n\t\tfracs = alt ./ total\n\t\tbg_alt = sum(alt[background])\n\t\tbg_total = sum(total[background])\n\t\tavg_ref_frac = bg_alt / bg_total\n\n\t\tsomatic = falses(n_samples)\n\t\tfor k in 1:n_tests\n\t\t\tt = test[k]; # Index of test sample col\n\t\t\tr = ref[k]; # Index of ref sample col\n\n\t\t\t# Perform checks to determine somatic status of mutation\n\t\t\tif fracs[t] < alt_frac[k]; continue; end\n\t\t\tif r != 0 && fracs[t] < test_ref_ratio * fracs[r]; continue; end\n\t\t\tif fracs[t] < test_bg_ratio * avg_ref_frac; continue; end\n\t\t\tif alt[t] < alt_reads; continue; end\n\t\t\tif r != 0 && total[r] < ref_reads; continue; end\n\t\t\tif call2_format\n\t\t\t\tif !is_indel && mapq[t] < min_mapq; continue; end \n\t\t\t\tif sidedness[t] < min_sidedness; continue; end \n\t\t\tend\n\n\t\t\t#if test_bg_alpha < 1.0\n\t\t\t#\tif pvalue(ChisqTest([alt[t] total[t] - alt[t]; bg_alt bg_total - bg_alt])) > test_ref_alpha; continue; end\n\t\t\t#end\n\t\t\t#chisq_p = pvalue(ChisqTest(\n\t\t\t#\t[alt[t] total[t] - alt[t]; bg_alt bg_total - bg_alt]))\n\t\t\t#baseq[t] = round(Int32, min(-10 * log10(chisq_p), 100))\n\n\t\t\tsomatic[t] = true\n\t\tend\n\n\t\tif keep_old_stars\n\t\t\tsomatic |= map(c -> endswith(c, '*'), cols[notes_col+1:end])\n\t\tend\n\n\t\tif !any(somatic) && keep_all == false; continue; end\n\t\t\n\t\tprint(join(cols[1:notes_col], '\\t'))\n\t\t@printf(\"BG: %.3f%%. \", avg_ref_frac * 100)\n\t\tfor s in 1:n_samples\n\t\t\tif call2_format\n\t\t\t\tprint(\"\\t$(alt[s]):$(total[s]):$(mapq[s]):$(baseq[s]):$(sidedness[s])\")\t\t\t\t\n\t\t\telse \n\t\t\t\tprint(\"\\t$(alt[s]):$(total[s])\")\n\t\t\tend\n\n\t\t\tif somatic[s]; print(\":*\"); end\n\t\tend\n\t\tprintln()\n\tend\nend\n\nfunction germline(vcf_file::IO, ref_regexps...; alt_reads=5, alt_frac=0.15, bg_ratio=20)\n\tline = skip_to_header(vcf_file); println(line)\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1\n\tsamples = split(line, '\\t')[sample_col:end]\n\tgermline = falses(samples)\n\tfor regex in ref_regexps; germline .|= ismatch.(Regex(regex), samples); end\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\tgtypes = [split(c, ':') for c in cols[sample_col:end]]\n\t\ttotal = [parse(Int32, gt[2]) for gt in gtypes]\n\t\talt = [parse(Int32, gt[1]) for gt in gtypes]\n\t\tfracs = alt ./ total\n\t\talt_gt = (fracs .>= alt_frac) .& (alt .>= alt_reads) .& germline\n\t\tif !any(alt_gt); continue; end\n\n\t\t# There might be non-reference samples that are not in alt_gt because\n\t\t# of the alt_reads threshold. We don't want to include these\n\t\t# samples in the background, so we only use alt_frac when picking\n\t\t# background samples.\n\t\tavg_alt = sum(alt[alt_gt]) / sum(total[alt_gt])\n\t\tbg = (fracs .< alt_frac) .& germline\n\t\tavg_ref = sum(alt[bg]) / sum(total[bg])\n\t\tif avg_alt / avg_ref < bg_ratio; continue; end\n\n\t\tprint(join(cols[1:sample_col-1], '\\t'))\n\t\tfor s in 1:length(total)\n\t\t\tprint(\"\\t$(alt[s]):$(total[s])\")\n\t\t\tif alt_gt[s]; print(\":*\"); end\n\t\tend\n\t\tprint('\\n')\n\tend\nend\n\nfunction above_background(vcf_file::IO, ref_regex...; alt_reads=3, alt_frac=0.1, bg_ratio=20)\n\tline = skip_to_header(vcf_file); println(line)\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1\n\tsamples = split(line, '\\t')[sample_col:end]\n\n\tbg = falses(samples)\n\tfor regex in ref_regex; bg .|= ismatch.(Regex(regex), samples); end\n\tinfo(\"Calculating background based on $(sum(bg)) samples...\")\n\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\tgtypes = map(c -> split(c, ':'), cols[sample_col:end])\n\t\ttotal = map(gt -> parse(Int, gt[2]), gtypes)\n\t\talt = map(gt -> parse(Int, gt[1]), gtypes)\n\t\tfracs = alt ./ total\n\t\tavg_bg_frac = sum(alt[bg]) / sum(total[bg])\n\t\talt_gt = (alt .>= alt_reads) .&\n\t\t\t(fracs .>= max(alt_frac, avg_bg_frac * bg_ratio))\n\t\tif !any(alt_gt); continue; end\n\n\t\tprint(join(cols[1:sample_col-1], '\\t'))\n\t\tfor s in 1:length(total)\n\t\t\tprint(\"\\t$(alt[s]):$(total[s])\")\n\t\t\tif alt_gt[s]; print(\":*\"); end\n\t\tend\n\t\tprintln()\n\tend\nend\n\nfunction heterozygous_snps(vcf_file::IO, ref_regex...; min_depth=30, min_frac=0.3, bg_fraction=0.1)\n\tline = skip_to_header(vcf_file); println(line)\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1\n\tsamples = split(line, '\\t')[sample_col:end]; S = length(samples)\n\n\tref = falses(samples)\n\tfor regex in ref_regex; ref .|= ismatch.(Regex(regex), samples); end\n\tinfo(\"Searching for heterozygous SNPs in $(sum(ref)) germline samples...\")\n\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\talt = zeros(Int, S); total = zeros(Int, S); starred = falses(S);\n\t\tunclear = 0\n\t\tfor (s, col) in enumerate(cols[sample_col:end])\n\t\t\tparts = split(col, ':')\n\t\t\talt[s] = parse(Int, parts[1])\n\t\t\ttotal[s] = parse(Int, parts[2])\n\t\t\tif ref[s] == false; continue; end\n\t\t\tif total[s] < min_depth; continue; end\n\t\t\t\n\t\t\tif alt[s] / total[s] < min_frac\n\t\t\t\terror_lower = Binomial(total[s], 0.01)\n\t\t\t\tif 1 - cdf(error_lower, alt[s] - 1) <= 0.05; unclear += 1; end\n\t\t\telseif alt[s] / total[s] > 1 - min_frac\n\t\t\t\terror_upper = Binomial(total[s], 0.99)\n\t\t\t\tif cdf(error_upper, alt[s]) <= 0.05; unclear += 1; end\n\t\t\tend\n\n\t\t\tif unclear / S >= bg_fraction\n\t\t\t\tstarred[:] = false; break;\n\t\t\tend\n\n\t\t\thetz = Binomial(total[s], 0.5)\n\t\t\tif 0.05 <= cdf(hetz, alt[s]) <= 0.95; starred[s] = true; end\n\t\tend\n\n\t\tif !any(starred); continue; end\n\n\t\tprint(join(cols[1:sample_col-1], '\\t'))\n\t\tfor s in 1:S\n\t\t\tprint(\"\\t$(alt[s]):$(total[s])\")\n\t\t\tif starred[s]; print(\":*\"); end\n\t\tend\n\t\tprint('\\n')\n\tend\nend\n\nannovar_valid_funcs = Set([\"exonic\", \"splicing\", \"intergenic\", \"intronic\",\n\t\"upstream\", \"downstream\", \"UTR5\", \"UTR3\", \"ncRNA_exonic\", \"ncRNA_intronic\",\n\t\"ncRNA_splicing\", \"\"])\n\nfunction translate_annovar_effect(gene, func, exonic_func, aa_change)\n\tfor f in split(func, ';')\n\t\tif !in(f, annovar_valid_funcs)\n\t\t\twarn(\"Unrecognized variant effect '$f'.\")\n\t\tend\n\tend\n\n\teffects = []\n\tif contains(func, \"splicing\"); push!(effects, \"Splice site\"); end\n\tif contains(func, \"exonic\")\n\t\tdetails = unique(map(m -> m.captures[1],\n\t\t\teachmatch(r\":(p\\..+?)(,|$)\", aa_change)))\n\t\tif exonic_func == \"synonymous SNV\"\n\t\t\tpush!(effects, \"Synonymous $(join(details, \", \"))\")\n\t\telseif exonic_func == \"nonsynonymous SNV\"\n\t\t\tpush!(effects, \"Missense $(join(details, \", \"))\")\n\t\telseif exonic_func == \"stopgain\"\n\t\t\tpush!(effects, \"Stopgain $(join(details, \", \"))\")\n\t\telseif exonic_func == \"stoploss\"\n\t\t\tpush!(effects, \"Stoploss $(join(details, \", \"))\")\n\t\telseif contains(exonic_func, \"nonframeshift\")\n\t\t\tpush!(effects, \"Non-frameshift indel $(join(details, \", \"))\")\n\t\telseif contains(exonic_func, \"frameshift\")\n\t\t\tpush!(effects, \"Frameshift $(join(details, \", \"))\")\n\t\telseif contains(func, \"ncRNA_exonic\")\n\t\t\tpush!(effects, \"Exonic (ncRNA)\")\n\t\telseif exonic_func == \"unknown\"\n\t\t\tpush!(effects, \"Exonic (unknown)\")\n\t\telse\n\t\t\terror(\"Unrecognized effect: $([func, exonic_func])\")\n\t\tend\n\tend\n\tif contains(func, \"UTR3\"); push!(effects, \"3'-UTR\"); end\n\tif contains(func, \"UTR5\"); push!(effects, \"5'-UTR\"); end\n\tif contains(func, \"upstream\"); push!(effects, \"Upstream\"); end\n\tif contains(func, \"downstream\"); push!(effects, \"Downstream\"); end\n\tif contains(func, \"intronic\"); push!(effects, \"Intronic\"); end\n\tif func == \"intergenic\"; push!(effects, \"Intergenic\"); gene = \"\"; end\n\n\treturn (gene, join(effects, \". \"))\nend\n\nfunction predict_effect(vcf_file::IO; genome=\"~/tools/annovar-2016-02-01/humandb/hg38\")\n\tgenome_version = basename(genome)\n\thumandb_dir = expanduser(dirname(genome))\n\ttmp_prefix = \"annovar-$(hex(rand(0:2^16-1), 4))\"\n\toriginal_path = \"$(tmp_prefix).original\"\n\treformatted_path = \"$(tmp_prefix).avinput\"\n\n\t# Reformat the input file to an ANNOVAR-compatible format. In particular,\n\t# indels must be changed so they use '-' as the ref or alt allele.\n\t# Since the input file could be a pipe, we must write the original VCF\n\t# into a separate file that will be used to build the final annotated VCF.\n\toriginal_file = open(original_path, \"w\")\n\treformatted_file = open(reformatted_path, \"w\")\t\n\theaders = split(skip_to_header(vcf_file), '\\t')\n\t\n\tfor line in eachline(vcf_file)\n\t\t\n\t\twrite(original_file, line, '\\n')\n\t\tc = split(line, '\\t')\n\t\tstart = parse(Int, c[2]); stop = start; ref = c[3]; alt = c[4]\n\n\t\tif length(ref) == 1 && length(alt) > 1 && ref[1] == alt[1]\n\t\t\t# Simple insertion\n\t\t\tref = \"-\"; alt = alt[2:end];\n\t\telseif length(ref) > 1 && length(alt) == 1 && ref[1] == alt[1]\n\t\t\t# Simple deletion\n\t\t\tref = ref[2:end]; alt = \"-\"; start += 1;\n\t\telseif length(ref) > 1 && length(alt) > 1\n\t\t\t# Block substitution\n\t\tend\n\t\tstop = start + length(ref) - 1\n\t\twrite(reformatted_file, \"$(c[1])\\t$(start)\\t$(stop)\\t$(ref)\\t$(alt)\\n\")\n\tend\n\tclose(original_file); close(reformatted_file); close(vcf_file)\n\n\trun(pipeline(`table_annovar.pl $(reformatted_path) $(humandb_dir) --buildver $(genome_version) --remove --outfile $(tmp_prefix) --operation g --protocol refGene`, stderr=DevNull))\n\n\tanno_path = \"$(tmp_prefix).$(genome_version)_multianno.txt\"\n\toriginal_file = open(original_path);\n\tanno_file = open(anno_path); readline(anno_file)\n\tprint(\"CHROM\\tPOSITION\\tREF\\tALT\\tGENE\\tEFFECT\\tNOTES\\t\")\n\tprintln(join(headers[6:end], '\\t'))\n\tfor line in eachline(anno_file)\n\t\tc = split(line, '\\t')\n\t\tif length(c) >= 7\n\t\t\tgene, effect = translate_annovar_effect(c[7], c[6],\n\t\t\t\tlength(c) >= 9 ? c[9] : \"\", length(c) >= 10 ? c[10] : \"\")\n\t\telse\n\t\t\tgene = \"\"; effect = \"\";\n\t\tend\n\n\t\torig_line = readline(original_file)\n\t\ttab = search(orig_line, '\\t')\n\t\tfor k in 1:3; tab = search(orig_line, '\\t', tab + 1); end\n\t\tprint(orig_line[1:tab])\n\t\tprint(\"$(gene)\\t$(effect)\\t\")\n\t\tprintln(orig_line[tab+1:end])\n\tend\n\tclose(anno_file); rm(original_path); rm(reformatted_path); rm(anno_path);\nend\n\ntype TextAnnotations\n\tposition::Vector{Int32}\n\tchange::Vector{Int16}\n\tannotation::Vector{String}\n\tTextAnnotations() = new([], [], [])\nend\n\ntype NumericAnnotations\n\tposition::Vector{Int32}\n\tchange::Vector{Int16}\n\tannotation::Vector{Float32}\n\tNumericAnnotations() = new([], [], [])\nend\n\nbase_num = Dict{String, Int16}(\"A\" => 1, \"C\" => 2, \"G\" => 3, \"T\" => 4)\nencode_ref_alt(ref, alt) = get(base_num, ref, 0) * 16 + get(base_num, alt, 0)\n\nfunction build_annotation_database(anno_path, db_path; prefix=\"\",\n\tformat=\"text\")\n\tdb = jldopen(db_path, \"w\", compress=true)\n\tanno_file = zopen(anno_path)\n\tif format == \"text\"\n\t\tbuild_annotation_database_text(anno_file, db)\n\telseif format == \"numeric\"\n\t\tbuild_annotation_database_numeric(anno_file, db)\n\telseif format == \"blank\"\n\t\tbuild_annotation_database_blank(anno_file, db)\n\telse\n\t\terror(\"Unrecognized annotation database format '$format' requested.\")\n\tend\n\twrite(db, \"prefix\", prefix)\n\twrite(db, \"format\", format)\n\tclose(db)\nend\n\nfunction build_annotation_database_blank(anno_file, db)\n\tchr = \"\"; anno = TextAnnotations()\n\tfor line in eachline(anno_file)\n\t\tc = split(rstrip(line, '\\t'))\n\t\tif c[1] != chr\n\t\t\tif chr != \"\"\n\t\t\t\tassert(issorted(anno.position))\n\t\t\t\twrite(db, chr, anno)\n\t\t\tend\n\t\t\tanno = TextAnnotations(); chr = String(c[1])\n\t\t\tprintln(STDERR, \"Chromosome $(chr)...\")\n\t\tend\n\t\tpush!(anno.position, parse(Int32, c[2]))\n\t\tpush!(anno.change, encode_ref_alt(c[3], c[4]))\n\tend\n\twrite(db, chr, anno)\nend\n\nfunction build_annotation_database_text(anno_file, db)\n\tchr = \"\"; anno = TextAnnotations()\n\tfor line in eachline(anno_file)\n\t\tc = split(rstrip(line, '\\t'))\n\t\tif c[1] != chr\n\t\t\tif chr != \"\"\n\t\t\t\tassert(issorted(anno.position))\n\t\t\t\twrite(db, chr, anno)\n\t\t\tend\n\t\t\tanno = TextAnnotations(); chr = String(c[1])\n\t\t\tprintln(STDERR, \"Chromosome $(chr)...\")\n\t\tend\n\t\tpush!(anno.position, parse(Int32, c[2]))\n\t\tpush!(anno.change, encode_ref_alt(c[3], c[4]))\n\t\tpush!(anno.annotation, c[5])\n\tend\n\twrite(db, chr, anno)\nend\n\nfunction build_annotation_database_numeric(anno_file, db)\n\tchr = \"\"; anno = NumericAnnotations()\n\tfor line in eachline(anno_file)\n\t\tc = split(rstrip(line, '\\t'))\n\t\tif c[1] != chr\n\t\t\tif chr != \"\"\n\t\t\t\tassert(issorted(anno.position))\n\t\t\t\twrite(db, chr, anno)\n\t\t\tend\n\t\t\tanno = NumericAnnotations(); chr = String(c[1])\n\t\t\tprintln(STDERR, \"Chromosome $(chr)...\")\n\t\tend\n\t\tpush!(anno.position, parse(Int32, c[2]))\n\t\tpush!(anno.change, encode_ref_alt(c[3], c[4]))\n\t\tpush!(anno.annotation, parse(Float32, c[5]))\n\tend\n\twrite(db, chr, anno)\nend\n\nfunction row_to_key( row::String)\t\n\t# Firstly, compare non-numeric parts (case-insensitive)\n\t# Next, compare numeric parts as integer\n\t# Next, compare position as integer\n\tchrom, pos = split(row, '\\t')[1:2]\n\treturn (filter(x -> !isnumber(x), lowercase(chrom)),\n\t\t parse(Int32, filter(x -> isnumber(x), '0'*chrom)),\n\t\t parse(Int32, pos))\nend\n\n# Sorts and prints VCF file rows by their chromosomal position\n# Does not allow comment lines anywhere else than the beginning\nfunction sort_by_position(vcf_file::IO)\n\n\tprintln( skip_to_header(vcf_file));\n\trows = readlines(vcf_file) \n\n\tsort!(rows, by=x -> row_to_key(x))\n\tfor row in rows println(row); end\nend\n\n\n\nfunction annotate(vcf_file::IO, db_path)\n\tdb = jldopen(db_path, \"r\")\n\tprefix = read(db, \"prefix\")\n\tformat = read(db, \"format\")\n\theaders = split(skip_to_header(vcf_file), '\\t')\n\tnotes_col = findfirst(headers .== \"NOTES\")\n\tprintln(join(headers, '\\t'))\n\n\tchr = \"\"; anno = nothing\n\tfor line in eachline(vcf_file)\n\n\t\tc = split(line, '\\t')\n\t\tif drop_chr_prefix(c[1]) != chr\n\t\t\tchr = String(drop_chr_prefix(c[1]))\n\t\t\tif any(x -> chr == x, names(db)) # in() does not work\n\t\t\t\tanno = read(db, chr)\n\t\t\telse\n\t\t\t\twarn(\"No annotations found for chromosome $(chr).\")\n\t\t\t\tanno = NumericAnnotations()\n\t\t\tend\n\t\tend\n\t\tmatches = searchsorted(anno.position, parse(Int32, c[2]))\n\t\tif !isempty(matches)\n\t\t\tchange = encode_ref_alt(c[3], c[4])\n\t\t\tfor m in matches\n\t\t\t\tif anno.change[m] == change\n\t\t\t\t\tif format == \"numeric\"\n\t\t\t\t\t\t# See https://github.com/JuliaLang/julia/issues/14331\n\t\t\t\t\t\tc[notes_col] *= rstrip(@sprintf(\"%s:%g\", prefix,\n\t\t\t\t\t\t\tanno.annotation[m])) * \". \"\n\t\t\t\t\telseif format == \"text\"\n\t\t\t\t\t\tc[notes_col] *= \"$(prefix):$(anno.annotation[m]). \"\n\t\t\t\t\telse\n\t\t\t\t\t\tc[notes_col] *= \"$(prefix). \"\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tprintln(join(c, '\\t'))\n\tend\nend\n\n# Filter VCF file lines based on if they are protein altering or not\n# ARG: invert: Set to false to output protein altering mutations\"\n# Set to true to output non protein altering mutations\"\nfunction protein_altering(vcf_file::IO; invert=false)\n\tline = skip_to_header(vcf_file); println(line)\n\tfunc_col = findfirst(split(line, '\\t') .== \"EFFECT\")\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\talters = ismatch(r\"Missense|rameshift|Stopgain|Stoploss|Splice\",\n\t\t\tcols[func_col])\n\t\tif !alters == invert; println(line); end\n\tend\nend\n\nfunction select_samples(invert::Bool, vcf_file::IO, regexps...)\n\theaders = split(skip_to_header(vcf_file), '\\t')\n\tsample_col = findfirst(headers .== \"NOTES\") + 1\n\tkeep = falses(length(headers))\n\tkeep[1:sample_col-1] = true\n\tfor col in sample_col:length(headers)\n\t\tkeep[col] = any(rx -> ismatch(Regex(rx), headers[col]), regexps)\n\tend\n\tif invert; keep[sample_col:end] = .!keep[sample_col:end]; end\n\tprintln(join(headers[keep], '\\t'))\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\tprintln(join(cols[keep], '\\t'))\n\tend\nend\nkeep_samples(vcf_file::IO, regexps...) = select_samples(false, vcf_file, regexps...)\ndiscard_samples(vcf_file::IO, regexps...) = select_samples(true, vcf_file, regexps...)\n\nfunction discard_shallow(vcf_file::IO, min_median_depth::Float64)\n\tline = skip_to_header(vcf_file); println(line);\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1\n\tfor line in eachline(vcf_file)\n\t\ttotal = map(c -> parse(Int, split(c, ':')[2]),\n\t\t\tsplit(line, '\\t')[sample_col:end])\n\t\tif median(total) >= min_median_depth; println(line); end\n\tend\nend\n\nfunction discard_blacklisted(vcf_file::IO, blacklist::IO)\n\td = readdlm(blacklist, '\\t', String)\n\tblacklist = Set(map(r -> d[r, 1:4][:], 1:size(d, 1)))\n\n\tline = skip_to_header(vcf_file); println(line);\n\tfor line in eachline(vcf_file)\n\t\tc = split(line, '\\t')\n\t\tif in(c[1:4], blacklist); continue; end\n\t\tprintln(line)\n\tend\nend\n\nfunction discard_indels(vcf_file::IO)\n\tline = skip_to_header(vcf_file); println(line);\n\tfor line in eachline(vcf_file)\n\t\tc = split(line, '\\t')\n\t\tif length(c[3]) == 1 && length(c[4]) == 1 && c[3] != \"-\" && c[4] != \"-\"\n\t\t\tprintln(line)\n\t\tend\n\tend\nend\n\nfunction discard_if_frequency_above(vcf_file::IO, db_path, threshold::Float64)\n\tdb = jldopen(db_path, \"r\")\n\tprintln(skip_to_header(vcf_file))\n\tchr = \"\"; anno = nothing\n\tfor line in eachline(vcf_file)\n\t\tc = split(line, '\\t')\n\t\tif drop_chr_prefix(c[1]) != chr\n\t\t\tchr = String(drop_chr_prefix(c[1])); anno = read(db, chr)\n\t\tend\n\t\tmatches = searchsorted(anno.position, parse(Int32, c[2]))\n\t\tif !isempty(matches)\n\t\t\tchange = encode_ref_alt(c[3], c[4])\n\t\t\tif any(m -> anno.change[m] == change &&\n\t\t\t\tanno.annotation[m] >= threshold, matches)\n\t\t\t\tcontinue;\n\t\t\tend\n\t\tend\n\t\tprintln(join(c, '\\t'))\n\tend\nend\n\nfunction inside(vcf_file::IO, region)\n\tm = match(r\"([a-zA-Z0-9]+):(\\d+)-(\\d+)\", region)\n\tif m == nothing\n\t\tif isfile(region) || isfifo(region)\n\t\t\tinside_bed_regions(vcf_file, region)\n\t\t\treturn\n\t\telse\n\t\t\terror(\"Invalid region specified.\")\n\t\tend\n\tend\n\n\tchr = m.captures[1]\n\tstart = parse(Int, m.captures[2])\n\tstop = parse(Int, m.captures[3])\n\n\tline = skip_to_header(vcf_file); println(line)\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1\n\tfor line in eachline(vcf_file)\n\t\tc = split(line, '\\t'); pos = parse(Int, c[2])\n\t\tif c[1] == chr && start <= pos <= stop; println(line); end\n\tend\nend\n\nfunction inside_bed_regions(vcf_file::IO, regions_path)\n\tregions = Dict{String, Array{Region}}()\n\tfor line in eachline(open(regions_path))\n\t\tc = split(rstrip(line), '\\t')\n\t\tpush!(get!(() -> Array{Region}(0), regions, c[1]),\n\t\t\tRegion(parse(Int, c[2])+1, parse(Int, c[3])))\n\tend\n\n\tline = skip_to_header(vcf_file); println(line)\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1 + 1\n\tfor line in eachline(vcf_file)\n\t\tc = split(line, '\\t'); pos = parse(Int, c[2])\n\t\tchr_regions = get(() -> Array{Region}(0), regions, c[1])\n\t\tif any(r -> r.start <= pos <= r.stop, chr_regions)\n\t\t\tprintln(line)\n\t\tend\n\tend\nend\n\nfunction discard_contingent(vcf_path, alpha::Float64)\n\tvcf_file = zopen(vcf_path)\n\tline = skip_to_header(vcf_file); print(line)\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1\n\tfor line in eachline(vcf_file)\n\t\tgtypes = map(c -> split(c, ':'), split(line, '\\t')[sample_col:end])\n\t\ttotal = map(gt -> parse(Int, gt[2]), gtypes)\n\t\talt = map(gt -> parse(Int, gt[1]), gtypes)\n\t\tvalid = total .>= 1\n\t\tp = any(valid) ? pvalue(ChisqTest([alt[valid] total[valid] - alt[valid]])) : 1\n\t\tif alpha == 1\n\t\t\tprint(line[1:end-1]); print(\"\\t$(p)\\n\")\n\t\telseif p <= alpha\n\t\t\tprint(line)\n\t\tend\n\tend\nend\n\n# Adds a warning to the Notes column if the mappability in the reference\n# genome is below a specified treshold (-> low mappability)\nfunction mappability(vcf_file::IO, track_path::String, threshold::Float64)\n\ttracks = jldopen(track_path, \"r\");\n\theaders = split(skip_to_header(vcf_file), '\\t')\n\tnotes_col = findfirst(headers .== \"NOTES\")\n\tprintln(join(headers, '\\t'))\n\n\t# We assume that the VCF file is sorted by chromosome.\n\tcurr_chr = \"\"; track = zeros(UInt8, 0);\n\tfor line in eachline(vcf_file)\n\t\tc = split(line, '\\t')\n\t\tif c[1] != curr_chr\n\t\t\tcurr_chr = String(c[1])\n\t\t\ttrack = read(tracks, curr_chr)\n\t\tend\n\t\tmappability = track[parse(Int, c[2])]\n\t\tif mappability < threshold\n\t\t\tc[notes_col] = \"$(c[notes_col])Mappability < $(threshold)%. \"\n\t\tend\n\t\tprintln(join(c, '\\t'))\n\tend\nend\n\n# Adds a warning to the NOTES column if there are indels within\n# dist distance of the alt read (line in VCF file).\n#\n# ARG: dist : largest distance that is considered\n# being \"nearby\"\nfunction nearby_indels(vcf_file::IO; dist=10)\n\n\tline = skip_to_header(vcf_file);\n\tprintln(line)\n\theaders = split(line, '\\t')\n\tnotes_col = findfirst(split(line, '\\t') .== \"NOTES\")\n\twarn_msg = \"INDEL within $dist bases. \"\n\n\t#notes_col = findfirst(split(skip_to_header(vcf_file), '\\t') .== \"NOTES\")\n\n\tprev_lines = Array{Array{String}}(0)\n\n\tfor line in eachline(vcf_file)\n\n\t\tif startswith(line, \"#\") println(line); continue; end \n\t\tc = split(line, '\\t')\n\t\tpos = parse(Int, c[2])\n\t\tstarred = map(x -> endswith(x, '*'), c[notes_col+1:end])\n\n\t\t# Forget old lines that are so far behind they cannot be affected.\n\t\tkeep = trues(length(prev_lines))\n\t\tfor (k, prev_line) in enumerate(prev_lines)\n\t\t\t# On different chromosome or too distant\n\t\t\tif c[1] != prev_line[1] || parse(Int, prev_line[2]) < pos - dist\n\t\t\t\tkeep[k] = false\n\t\t\t\tprintln(join(prev_line, '\\t'))\n\t\t\tend\n\t\tend\n\t\tprev_lines = prev_lines[keep]\n\n\t\t# Add warning to old lines if current line is an indel.\n\t\tif length(c[3]) != length(c[4])\n\t\t\tfor prev_line in prev_lines\n\t\t\t\tif any(s -> starred[s] && endswith(prev_line[notes_col+s], '*'), 1:length(starred))\n\t\t\t\t\tprev_line[notes_col] *= warn_msg\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\t# Add warning to current line if any old lines were indels.\n\t\tfor prev_line in prev_lines\n\t\t\tif length(prev_line[3]) != length(prev_line[4]) &&\n\t\t\t\tany(s -> starred[s] && endswith(prev_line[notes_col+s], '*'), 1:length(starred))\n\t\t\t\tc[notes_col] *= warn_msg\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\tpush!(prev_lines, c)\n\tend\n\n\tfor prev_line in prev_lines; println(join(prev_line, '\\t')); end\nend\n\nfunction statistics(vcf_path)\n\tvcf_file = zopen(vcf_path)\n\theaders = split(rstrip(skip_to_header(vcf_file)), '\\t')\n\tsample_col = findfirst(headers .== \"NOTES\") + 1\n\tsamples = headers[sample_col:end]; S = length(samples)\n\ttotal_subs = zeros(Int, S)\n\tpossible_subs = zeros(Int, S, 6)\n\ttotal_indels = zeros(Int, S)\n\n\tfor line in eachline(vcf_file)\n\t\tc = split(rstrip(line), '\\t')\n\t\talt = map(gt -> endswith(gt, '*'), c[sample_col:end])\n\t\tmut_class = mutation_class(c[3], c[4])\n\t\tif mut_class > 0\n\t\t\ttotal_subs += alt\n\t\t\tpossible_subs[:, mut_class] += alt\n\t\telseif mut_class == 0\n\t\t\ttotal_indels += alt\n\t\tend\n\tend\n\n\tprintln(\"SAMPLE\\tTOTAL SUBSTITUTIONS\\tTOTAL INDELS\\tC>A\\tC>G\\tC>T\\tT>A\\tT>C\\tT>G\")\n\tfor s in 1:S\n\t\tprint(\"$(samples[s])\\t$(total_subs[s])\\t$(total_indels[s])\")\n\t\tfor k in 1:6; print(\"\\t$(possible_subs[s, k])\"); end\n\t\tprintln()\n\tend\nend\n\n\n# CALL2 output format: \"alt_reads:total_reads:mapq:baseq:sidedness:significant\"\nfunction fractions(vcf_file::IO)\n\n\tline = skip_to_header(vcf_file); println(line)\n\tsample_col = findfirst(split(line, '\\t') .== \"NOTES\") + 1\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\tgtypes = [split(c, ':') for c in cols][sample_col:end]\n\n\t\ttotal = [parse(Int32, gt[2]) for gt in gtypes]\n\t\talt = [parse(Int32, gt[1]) for gt in gtypes]\n\n\t\tprint(join(cols[1:(sample_col-1)], '\\t'))\n\n\t\tfor s in 1:length(gtypes)\n\t\t\tfrac = alt[s] / total[s]\t\t\t\n\t\t\t@printf(\"\\t%.1f%% (%d)\", isnan(frac) ? 0.0 : frac * 100, total[s])\n\t\t\t#CALL2 support\n\t\t\tif length(gtypes[s]) >= 5 && parse( Int32, gtypes[s][ 3]) > 0; @printf(\" [mq:%s,bq:%s,sd:%s]\", gtypes[s][3], gtypes[s][4], gtypes[s][5] ); end\t\t\t\t\t\t\n\t\t\tif length(gtypes[s]) >= 3 && gtypes[s][ length(gtypes[s])] == \"*\"; print(\" *\"); end\n\t\tend\n\t\tprintln()\n\tend\nend\n\nfunction error_rate(bam_path, genome_path; min_mapq=10)\n\tbam_path = expanduser(bam_path)\n\tgenome_path = expanduser(genome_path)\n\tspileup = expanduser(\"~/tools/pypette/compiled/spileup\")\n\n\t# 2D histogram, mutant read count on rows, mutant read fraction on columns\n\t# Histogram bins are left-exclusive, right-inclusive.\n\tread_thresholds = 0:100\n\tfrac_thresholds = 0:0.001:0.10\n\thistogram = zeros(Int, length(read_thresholds), length(frac_thresholds))\n\n\tfor line in eachline(pipeline(`samtools mpileup -d 100000 -A -x -R -sB -q$(min_mapq) -f $(genome_path) $(bam_path)`, `$(spileup) 0 $(min_mapq)`))\n\t\tcols = split(rstrip(line), '\\t')\n\t\tif length(cols) < 4; continue; end\n\t\t#if cols[3] == \"N\"; print(line); continue; end\n\t\tassert(length(cols) == 4)\n\t\tassert(cols[3] != \"N\")\n\n\t\tpileup = cols[4]\n\t\tif pileup == \"\"; continue; end\n\t\tt = split(pileup, ' ')\n\n\t\ttotal_reads = 0\n\t\talt_reads = 0\n\n\t\tfor a in 1:3:length(t)\n\t\t \tcount = parse(Int, t[a+1])\n\t\t \ttotal_reads += count\n\t\t \tif t[a] != \".\"; alt_reads += count; end\n\t\tend\n\n\t\talt_frac = alt_reads / total_reads\n\t\tread_bin = Int(min(alt_reads + 1, 101))\n\t\tfrac_bin = min(ceil(Int, alt_frac / 0.001) + 1, 101)\n\t\thistogram[read_bin, frac_bin] += 1\n\n\t\t# allele_reads = zeros(Int32, max_alleles)\n\t\t# alleles = Array{String}(0)\n\n\t\t# pileup = cols[4]\n\t\t# if pileup == \"\"; continue; end\n\t\t# t = split(pileup, ' ')\n\t\t# for a in 1:3:length(t)\n\t\t# \tcount = int(t[a+1])\n\t\t# \ttotal_reads[s] += count\n\t\t# \tif t[a] == \".\"; continue; end\n\t\t# \tidx = findfirst(allele -> allele == t[a], alleles)\n\t\t# \tif idx == 0 && length(alleles) >= max_alleles; continue; end\n\t\t# \tif idx == 0; push!(alleles, t[a]); idx = length(alleles); end\n\t\t# \tallele_reads[s, idx] = count\n\t\t# end\n\n\t\t# for a in 1:length(alleles)\n\t\t# end\n\tend\n\n\twritedlm(STDOUT, histogram)\nend\n\nfunction group_by_snp_profile(hetz_snp_vcf::IO)\n\theaders = split(rstrip(skip_to_header(hetz_snp_vcf)), '\\t')\n\tsample_col = findfirst(headers .== \"NOTES\") + 1\n\tsamples = headers[sample_col:end]; S = length(samples);\n\n\t# The matrix stores genotypes for every sample:\n\t# 0 = unknown, 1 = homz ref, 2 = hetz, 3 = homz alt\n\tprintln(\"Constructing genotype matrix...\")\n\tgenotypes = zeros(Int8, 1_000_000, S); r = 0\n\tfor line in eachline(hetz_snp_vcf)\n\t\tc = split(rstrip(line, '\\n'), '\\t')\n\t\tr += 1\n\t\tfor (s, cell) in enumerate(c[sample_col:end])\n\t\t\tparts = split(cell, ':')\n\t\t\talt = parse(Int, parts[1]); total = parse(Int, parts[2])\n\t\t\tif total < 30; genotypes[r, s] = 0; continue; end\n\t\t\tb = Binomial(total, 0.5)\n\t\t\tif 0.05 <= cdf(b, alt) <= 0.95\n\t\t\t\tgenotypes[r, s] = 2\n\t\t\telseif alt / total >= 0.8\n\t\t\t\tgenotypes[r, s] = 3\n\t\t\telseif alt / total <= 0.2\n\t\t\t\tgenotypes[r, s] = 1\n\t\t\tend\n\t\tend\n\tend\n\tgenotypes = genotypes[1:r, :]\n\n\tfor i in 1:S\n\t\tany_matches = false\n\t\tfor j in 1:S\n\t\t\tif j == i; continue; end\n\t\t\tmatched = 0; total = 0;\n\t\t\tfor r in 1:size(genotypes, 1)\n\t\t\t\tif genotypes[r, i] == 0 || genotypes[r, j] == 0; continue; end\n\t\t\t\ttotal += 1\n\t\t\t\tmatched += (genotypes[r, i] == genotypes[r, j])\n\t\t\tend\n\t\t\tif matched / total >= 0.95 && total >= 50\n\t\t\t\tany_matches = true\n\t\t\t\tif j > i # Don't print pairs twice\n\t\t\t\t\tprintln(\"$(samples[i]) <-> $(samples[j]): $matched / $total matched\")\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\tif any_matches == false\n\t\t\tprintln(\"$(samples[i]) does not match with any other samples.\")\n\t\tend\n\tend\nend\n\nfunction mutation_rate(vcf_file::IO, coverage_histogram_dir; alt_reads=8)\n\tvcf = read_vcf(vcf_file); S = length(vcf.sample);\n\thuman_chr = vcat(map(x -> \"chr$(x)\", 1:22), [\"chrX\", \"chrY\"]);\n\tprintln(\"SAMPLE\\tPROTEIN ALTERING\\tSILENT\\tPROTEIN ALTERING (RATE)\\tSILENT (RATE)\")\n\tfor s in 1:S\n\t\tinfo(\"Analyzing $(vcf.sample[s])...\")\n\t\tprotein_altering = 0; silent = 0;\n\t\tprotein_altering_rate = 0; silent_rate = 0;\n\t\thistogram = zeros(5000) # Bins are 0, 1, 2, ..., 4999\n\t\tgenome_len = 0\n\t\thistogram_file = \"$(coverage_histogram_dir)/$(vcf.sample[s]).tsv\"\n\t\tif !isfile(histogram_file)\n\t\t\twarn(\"No coverage histogram found for $(vcf.sample[s])...\")\n\t\t\tcontinue\n\t\tend\n\t\td = readdlm(histogram_file, '\\t')\n\t\tfor chr in human_chr\n\t\t\tgenome_len += d[findfirst(x -> x == chr, d[:, 1]), 4]\n\t\t\tfor r in 1:size(d, 1)\n\t\t\t\tif d[r, 1] != chr || d[r, 2] >= 5000; continue; end\n\t\t\t\thistogram[d[r, 2] + 1] += d[r, 3]\n\t\t\tend\n\t\tend\n\n\t\tfor r in 1:size(vcf, 1)\n\t\t\tif !vcf.star[r, s]; continue; end\n\t\t\tmin_depth = ceil(Int, alt_reads / (vcf.alt[r, s] / vcf.total[r, s]))\n\t\t\tamenable_mbs = (genome_len - sum(histogram[1:min_depth-1])) / 1e6\n\t\t\tinfo(\"$(vcf.chromosome[r]):$(vcf.position[r]) - amenable $(amenable_mbs) Mb\")\n\t\t\tif is_protein_altering(vcf.effect[r])\n\t\t\t\tprotein_altering += 1\n\t\t\t\tprotein_altering_rate += 1 / amenable_mbs\n\t\t\telse\n\t\t\t\tsilent += 1\n\t\t\t\tsilent_rate += 1 / amenable_mbs\n\t\t\tend\n\t\tend\n\n\t\t@printf(\"%s\\t%d\\t%d\\t%.2f\\t%.2f\\n\", vcf.sample[s], protein_altering, silent, protein_altering_rate, silent_rate)\n\tend\nend\n\nfunction discard_sketchy_silent(vcf_file::IO)\n\tline = skip_to_header(vcf_file); println(line)\n\tnotes_col = findfirst(split(line, '\\t') .== \"NOTES\")\n\teffect_col = findfirst(split(line, '\\t') .== \"EFFECT\")\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\tif !is_protein_altering(cols[effect_col])\n\t\t\tif contains(cols[notes_col], \"INDEL within\"); continue; end\n\t\t\tif contains(cols[notes_col], \"Mappability < \"); continue; end\n\t\tend\n\t\tprintln(line)\n\tend\nend\n\nfunction sort_samples_by_name(vcf_file::IO)\n\tline = skip_to_header(vcf_file)\n\theaders = split(line, '\\t')\n\tnotes_col = findfirst(headers .== \"NOTES\")\n\tsamples = headers[notes_col+1:end]\n\torder = vcat(1:notes_col, notes_col .+ sortperm(samples))\n\tprintln(join(headers[order], '\\t'))\n\tfor line in eachline(vcf_file)\n\t\tcols = split(line, '\\t')\n\t\tprintln(join(cols[order], '\\t'))\n\tend\nend\n\nsubcommands(somatic, germline, above_background, heterozygous_snps,\n\tkeep_samples, discard_samples,\n\tdiscard_shallow, discard_if_frequency_above, discard_blacklisted,\n\tdiscard_indels, discard_contingent, discard_sketchy_silent,\n\tmappability, nearby_indels,\n\tinside, protein_altering, fractions, statistics,\n\tpredict_effect, annotate, build_annotation_database, error_rate,\n\tgroup_by_snp_profile, mutation_rate, sort_by_position, sort_samples_by_name)\n", "meta": {"hexsha": "608fc80c5e6b6f4b7a22ae1e94c8c20ba0b1ee88", "size": 32747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "variant.jl", "max_stars_repo_name": "annalam/foxa1-utr-manuscript-code", "max_stars_repo_head_hexsha": "8f1cc0eda0e1ac0c45f9ef2a49edad66a8352eb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-14T21:26:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T21:26:39.000Z", "max_issues_repo_path": "variant.jl", "max_issues_repo_name": "annalam/foxa1-utr-manuscript-code", "max_issues_repo_head_hexsha": "8f1cc0eda0e1ac0c45f9ef2a49edad66a8352eb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "variant.jl", "max_forks_repo_name": "annalam/foxa1-utr-manuscript-code", "max_forks_repo_head_hexsha": "8f1cc0eda0e1ac0c45f9ef2a49edad66a8352eb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.670212766, "max_line_length": 180, "alphanum_fraction": 0.6582893089, "num_tokens": 10395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.15338143315871686}} {"text": "\n # Functions and methods for cheme::Cascade.DielectronicCaptureScheme computations\n\n\n \"\"\"\n `Cascade.computeSteps(scheme::Cascade.DielectronicCaptureScheme, comp::Cascade.Computation, stepList::Array{Cascade.Step,1})` \n ... computes in turn all the requested capture & transition amplitudes as well as DielectronicCapture.Line's, AutoIonization.Line's, \n etc. for all pre-specified decay steps of the cascade. When compared with standard computations of these atomic \n processes, however, the amount of output is largely reduced and often just printed into the summary file. \n A set of data::Cascade.CaptureData is returned.\n \"\"\"\n function computeSteps(scheme::Cascade.DielectronicCaptureScheme, comp::Cascade.Computation, stepList::Array{Cascade.Step,1})\n linesA = AutoIonization.Line[]; linesR = PhotoEmission.Line[]; cOrbitals = Dict{Subshell, Orbital}()\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n nt = 0; st = 0; previousMeanEn = 0.\n for step in stepList\n st = st + 1\n nc = length(step.initialMultiplet.levels) * length(step.finalMultiplet.levels)\n sa = \"\\n $st) Perform $(string(step.process)) amplitude computations for up to $nc decay lines (without selection rules): \"\n println(sa); if printSummary println(iostream, sa) end \n \n if step.process == Basics.Auger() && comp.approach == Cascade.AverageSCA()\n meanEn = 0.; NoEn = 0\n for p = 1:length(step.initialMultiplet.levels), q = 1:length(step.finalMultiplet.levels)\n en = step.initialMultiplet.levels[p].energy - step.finalMultiplet.levels[q].energy\n if en > 0.03 meanEn = meanEn + en; NoEn = NoEn + 1 end\n end\n if NoEn > 0 meanEn = meanEn/ NoEn \n else \n println(\">> No transition with positive energy.\")\n continue \n end\n \n # Generate potential for continuum orbitals for this step\n nrContinuum = Continuum.gridConsistency(meanEn + 0.1, comp.grid)\n contSettings = Continuum.Settings(false, nrContinuum); \n npot = Nuclear.nuclearPotential(comp.nuclearModel, comp.grid)\n ## wp1 = compute(\"radial potential: core-Hartree\", grid, wLevel)\n ## wp2 = compute(\"radial potential: Hartree-Slater\", grid, wLevel)\n wp = Basics.computePotentialDFS(comp.grid, step.finalMultiplet.levels[1])\n pot = Basics.add(npot, wp)\n # Generate continuum if not yet available\n generatedKappas = Int64[]\n for p = 1:length(step.initialMultiplet.levels), q = 1:length(step.finalMultiplet.levels)\n en = step.initialMultiplet.levels[p].energy - step.finalMultiplet.levels[q].energy\n if en > 0.03 \n symi = LevelSymmetry(step.initialMultiplet.levels[p].J, step.initialMultiplet.levels[p].parity)\n symf = LevelSymmetry(step.finalMultiplet.levels[q].J, step.finalMultiplet.levels[q].parity)\n kappaList = AngularMomentum.allowedKappaSymmetries(symi, symf)\n for kappa in kappaList\n sh = Subshell(101, kappa)\n if abs(kappa) > step.settings.maxKappa ## continuum orbital not needed\n elseif kappa in generatedKappas ## already generated for this step\n elseif haskey(cOrbitals,sh) && cOrbitals[sh].energy - en / en < 0.15 ## use previous one\n println(\">> No new continum orbital generated for $sh and energy $en \")\n else ## generate new continuum orbital\n push!(generatedKappas, kappa)\n cOrbital, phase, normF = Continuum.generateOrbitalLocalPotential(en, sh, pot, contSettings)\n cOrbitals[sh] = cOrbital\n println(\">> New continum orbital generated for $sh and energy $en \")\n end\n end\n end\n end\n \n newLines = AutoIonization.computeLinesFromOrbitals(step.finalMultiplet, step.initialMultiplet, comp.nuclearModel, comp.grid, \n step.settings, cOrbitals, output=true, printout=false) \n append!(linesA, newLines); nt = length(linesA)\n elseif step.process == Basics.Auger() \n # Compute continuum orbitals independently for all transitions in the given block.\n newLines = AutoIonization.computeLinesCascade(step.finalMultiplet, step.initialMultiplet, comp.nuclearModel, comp.grid, \n step.settings, output=true, printout=false) \n append!(linesA, newLines); nt = length(linesA)\n elseif step.process == Basics.Radiative()\n newLines = PhotoEmission.computeLinesCascade(step.finalMultiplet, step.initialMultiplet, comp.grid, \n step.settings, output=true, printout=false) \n append!(linesR, newLines); nt = length(linesR)\n else error(\"Unsupported atomic process for cascade computations.\")\n end\n sa = \" Step $st:: A total of $(length(newLines)) $(string(step.process)) lines are calculated, giving now rise \" *\n \"to a total of $nt $(string(step.process)) decay lines.\"\n println(sa); if printSummary println(iostream, sa) end \n end\n #\n data = Cascade.DecayData(linesR, linesA)\n end\n\n \"\"\"\n `Cascade.determineSteps(scheme::Cascade.DielectronicCaptureScheme, comp::Cascade.Computation, \n initialList::Array{Cascade.Block,1}, captureList::Array{Cascade.Block,1}, decayList::Array{Cascade.Block,1})` \n ... determines all step::Cascade.Step's that need to be computed for this dielectronic cascade. It considers the autoionization\n between the blocks from the captureList and initialList as well as the radiative stabilization between the blocks from the \n captureList and decayList. It checks that at least on pair of levels supports either an `electron-capture' or \n `radiative stabilization' within the step. A stepList::Array{Cascade.Step,1} is returned, and for which subsequently all \n required transition amplitudes and rates/cross sections are computed.\n \"\"\"\n function determineSteps(scheme::Cascade.DielectronicCaptureScheme, comp::Cascade.Computation, \n initialList::Array{Cascade.Block,1}, capturedList::Array{Cascade.Block,1}, decayList::Array{Cascade.Block,1})\n stepList = Cascade.Step[]\n if comp.approach in [Cascade.AverageSCA(), Cascade.SCA()]\n for capturedBlock in capturedList\n for initialBlock in initialList\n if initialBlock.NoElectrons + 1 != capturedBlock.NoElectrons error(\"stop a\") end\n # Check that at least one energy supports autoionization\n settings = AutoIonization.Settings(AutoIonization.Settings(), maxKappa=7)\n push!( stepList, Cascade.Step(Basics.Auger(), settings, capturedBlock.confs, initialBlock.confs,\n capturedBlock.multiplet, initialBlock.multiplet) )\n end\n end\n #\n for capturedBlock in capturedList\n for decayBlock in decayList\n if decayBlock.NoElectrons != capturedBlock.NoElectrons error(\"stop b\") end\n # Check that at least one energy supports radiative stabilization\n if Basics.determineMeanEnergy(capturedBlock.multiplet) - Basics.determineMeanEnergy(decayBlock.multiplet) > scheme.minPhotonEnergy\n settings = PhotoEmission.Settings(PhotoEmission.Settings(), gauges=[UseCoulomb, UseBabushkin])\n push!( stepList, Cascade.Step(Basics.Radiative(), settings, capturedBlock.confs, decayBlock.confs,\n capturedBlock.multiplet, decayBlock.multiplet) )\n end\n end\n end\n #\n else error(\"Unsupported cascade approach.\")\n end\n return( stepList )\n end\n \n \n \"\"\"\n `Cascade.generateBlocks(scheme::Cascade.DielectronicCaptureScheme, comp::Cascade.Computation, confs::Array{Configuration,1}; printout::Bool=true)` \n ... generate all block::Cascade.Block's, that need to be computed for this electron-capture and subsequent stabilization (DR) cascade, \n and compute also the corresponding multiplets. The different cascade approches realized different strategies how these blocks are \n selected and computed. A blockList::Array{Cascade.Block,1} is returned.\n \"\"\"\n function generateBlocks(scheme::Cascade.DielectronicCaptureScheme, comp::Cascade.Computation, confs::Array{Configuration,1}; printout::Bool=true)\n blockList = Cascade.Block[]; basis = Basis()\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n #\n if comp.approach == AverageSCA()\n sa = \"\\n* Generate blocks for DR plasma rate coefficient computations: \\n\" *\n \"\\n In the cascade approach $(comp.approach), the following assumptions/simplifications are made: \" *\n \"\\n + orbitals are generated independently for the first block in a Dirac-Fock-Slater potential; \" *\n \"\\n + these orbitals are re-used for all other block, together with hydrogenic orbitals for the outer part; \" *\n \"\\n + all blocks (multiplets) are generated from single-CSF levels and without any configuration mixing even in the SC; \" *\n \"\\n + only the Coulomb interaction is considered for the electron capture. \" *\n \"\\n + only E1 excitations are considered for the stabilization. \\n\"\n if printout println(sa) end\n if printSummary println(iostream, sa) end\n #\n if length(confs) > 1\n # Determine a list of hydrogenic orbitals for later use \n relconfList = ConfigurationR[]\n for confa in confs\n wa = Basics.generate(\"configuration list: relativistic\", confa)\n append!( relconfList, wa)\n end\n subshellList = Basics.generate(\"subshells: ordered list for relativistic configurations\", relconfList)\n ##x @show \"aa1\", subshellList\n Defaults.setDefaults(\"relativistic subshell list\", subshellList; printout=printout)\n wa = Bsplines.generatePrimitives(comp.grid)\n hydrogenicOrbitals = Bsplines.generateOrbitalsHydrogenic(wa, comp.nuclearModel, subshellList; printout=printout)\n end\n \n for (ia, confa) in enumerate(confs)\n sa = \" Multiplet computations for $(string(confa)[1:end]) with $(confa.NoElectrons) electrons ... \"\n print(sa); if printSummary println(iostream, sa) end\n # Now distinguish between the first and all other blocks; for the first block, a SCF is generated and the occupied orbital\n # used also for all other blocks. In addition, a set of hydrogenic orbitals generated for later use\n if ia == 1\n basis = Basics.performSCF([confa], comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n else\n # Generate a list of relativistic configurations and determine an ordered list of subshells for these configurations\n relconfList = ConfigurationR[]\n wa = Basics.generate(\"configuration list: relativistic\", confa); append!( relconfList, wa)\n subshellList = Basics.generate(\"subshells: ordered list for relativistic configurations\", relconfList)\n Defaults.setDefaults(\"relativistic subshell list\", subshellList; printout=false)\n # Generate the relativistic CSF's for the given subshell list\n csfList = CsfR[]\n for relconf in relconfList\n newCsfs = Basics.generate(\"CSF list: from single ConfigurationR\", relconf, subshellList)\n append!( csfList, newCsfs)\n end\n # Determine the list of coreSubshells\n coreSubshellList = Subshell[]\n for k in 1:length(subshellList)\n mocc = Basics.subshell_2j(subshellList[k]) + 1; is_filled = true\n for csf in csfList\n if csf.occupation[k] != mocc is_filled = false; break end\n end\n if is_filled push!( coreSubshellList, subshellList[k]) end\n end\n # Add all missing orbitals as hydrogenic\n orbitals = copy(basis.orbitals)\n for subsh in subshellList\n if haskey(orbitals, subsh) ## do nothing\n else orbitals[subsh] = hydrogenicOrbitals[subsh]; print(\"hydrogenic $subsh ...\")\n end\n end\n \n basis = Basis(true, confa.NoElectrons, subshellList, csfList, coreSubshellList, orbitals)\n end\n multiplet = Basics.perform(\"computation: mutiplet from orbitals, no CI, CSF diagonal\", [confa], basis.orbitals, \n comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n push!( blockList, Cascade.Block(confa.NoElectrons, [confa], true, multiplet) )\n println(\"and $(length(multiplet.levels[1].basis.csfs)) CSF done. \")\n end\n elseif comp.approach == SCA()\n sa = \"\\n* Generate blocks for electron-capture & decay cascade computations: \\n\" *\n \"\\n In the cascade approach $(comp.approach), the following assumptions/simplifications are made: \" *\n \"\\n + each single configuration forms an individual cascade block; \" *\n \"\\n + orbitals are generated independently for each block for a Dirac-Fock-Slater potential; \" *\n \"\\n + configuration mixing is included for each block, based on H^(DC); \" *\n \"\\n + all requested multipoles are considered for the stabilization. \\n\"\n if printout println(sa) end\n if printSummary println(iostream, sa) end\n #\n for confa in confs\n print(\" Multiplet computations for $(string(confa)[1:end]) with $(confa.NoElectrons) electrons ... \")\n if printSummary println(iostream, \"\\n* Multiplet computations for $(string(confa)[1:end]) with $(confa.NoElectrons) electrons ... \") end\n basis = Basics.performSCF([confa], comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplet = Basics.performCI(basis, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n push!( blockList, Cascade.Block(confa.NoElectrons, [confa], true, multiplet) )\n println(\"and $(length(multiplet.levels[1].basis.csfs)) CSF done. \")\n end\n else error(\"Unsupported cascade approach.\")\n end\n\n return( blockList )\n end\n\n\n \"\"\"\n `Cascade.generateConfigurationsForDielectronicCapture(multiplets::Array{Multiplet,1}, scheme::DielectronicCaptureScheme, \n nm::Nuclear.Model, grid::Radial.Grid)` \n ... generates all possible doubly-excited configurations due to (dielectronic) electron capture into the given multiplets.\n The number and type of such doubly-generated configurations depend on (1) the maximum (electron) energy for capturing an electron\n that is closely related to the (maximum) temperature of the plasma; (2) the fromShells from which (and how many displacements)\n are accepted as well as (3) the maximum principle and orbital angular quantum number of the additional (to-) shellsthe fromShells\n into which electrons excited and/or captured. A Tuple(initialConfList::Array{Configuration,1}, confList::Array{Configuration,1}) \n is returned.\n \"\"\"\n function generateConfigurationsForDielectronicCapture(multiplets::Array{Multiplet,1}, scheme::DielectronicCaptureScheme, \n nm::Nuclear.Model, grid::Radial.Grid)\n # Determine all (reference) configurations from multiplets and generate the 'excited' configurations due to the specificed excitations\n initialConfList = Configuration[]\n for mp in multiplets \n confList = Basics.extractNonrelativisticConfigurations(mp.levels[1].basis)\n for conf in confList if conf in initialConfList nothing else push!(initialConfList, conf) end end\n end\n coreConfList = Basics.generateConfigurations(initialConfList, scheme.excitationFromShells, scheme.excitationToShells, \n scheme.NoExcitations)\n captureConfList = Basics.generateConfigurationsWithElectronCapture(coreConfList, scheme.excitationFromShells, scheme.intoShells, 0)\n decayConfList = Basics.generateConfigurationsWithElectronCapture(coreConfList, scheme.excitationFromShells, scheme.decayShells, 0)\n @show initialConfList\n @show coreConfList\n @show captureConfList\n @show decayConfList\n #\n # Determine first a hydrogenic spectrum for all subshells of the initial and doubly-excited states\n allConfList = Configuration[]; \n append!(allConfList, initialConfList); append!(allConfList, captureConfList); append!(allConfList, decayConfList)\n \n allSubshells = Basics.extractRelativisticSubshellList(allConfList)\n primitives = Bsplines.generatePrimitives(grid)\n orbitals = Bsplines.generateOrbitalsHydrogenic(primitives, nm, allSubshells, printout=true)\n # Exclude configurations with too high mean energies\n en = Float64[]; \n for conf in initialConfList\n wen = Basics.determineMeanEnergy(conf, orbitals, nm, grid)\n push!(en, wen)\n end\n initialMean = sum(en) / length(en)\n println(\">>> initial configuration(s) have mena energies $initialMean [a.u.].\")\n #\n newCaptureConfList = Configuration[]; meanEnergies = Float64[]\n for conf in captureConfList \n confMean = Basics.determineMeanEnergy(conf, orbitals, nm, grid)\n if confMean - initialMean <= scheme.maxExcitationEnergy push!(newCaptureConfList, conf) end\n end\n\n return( (initialConfList, newCaptureConfList, decayConfList) )\n end\n\n\n \"\"\"\n `Cascade.perform(scheme::DielectronicCaptureScheme, comp::Cascade.Computation)` \n ... to set-up and perform a dielectronic-recombination (DR) plasma rate coefficient computation that combines the electron capture\n and the subsequent radiative stabilization steps. Such a computation starts from a given set of initial configurations xor \n initial multiplets and (1) generates all doubly-excited configurations due to the capture of an electron with a given maximum\n electron energy; (2) selects all electron capture (inverse Auger) and re-autoionization (Auger) steps and (3) selects\n all steps for radiative stabilization due to given parameters of the scheme::DielectronicCaptureScheme. The results of \n these DR plasma rate computation are comprised into (output) data::ExcitationData, while these data are only printed during \n the generation and nothing is returned.\n\n `Cascade.perform(scheme::DielectronicCaptureScheme, comp::Cascade.Computation; output=true, outputToFile::Bool=true)` \n ... to perform the same but to return the complete output in a dictionary that is written to disk and can be used in subsequent\n cascade simulation. The particular output depends on the specifications of the cascade.\n \"\"\"\n function perform(scheme::DielectronicCaptureScheme, comp::Cascade.Computation; output::Bool=false, outputToFile::Bool=true)\n if output results = Dict{String, Any}() else results = nothing end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n #\n # Perform the SCF and CI computation for the intial-state multiplets if initial configurations are given\n if comp.initialConfigs != Configuration[]\n basis = Basics.performSCF(comp.initialConfigs, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplet = Basics.performCI(basis, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n ##x # Shift the initial level energy by -electronEnergyShift\n ##x if scheme.electronEnergyShift != 0. \n ##x multiplet = Basics.shiftTotalEnergies(multiplet, Defaults.convertUnits(\"energy: to atomic\", -scheme.electronEnergyShift))\n ##x println(\">> Shift all initial level energies by -$(scheme.electronEnergyShift) $(Defaults.getDefaults(\"unit: energy\"))\")\n ##x end\n multiplets = [Multiplet(\"initial states\", multiplet.levels)]\n else\n #== # Shift the initial level energy by -electronEnergyShift\n if scheme.electronEnergyShift != 0. \n multiplets = Multiplet\n for multiplet in comp.initialMultiplets\n newMultiplet = Basics.shiftTotalEnergies(multiplet, Defaults.convertUnits(\"energy: to atomic\", -scheme.electronEnergyShift)) \n push!(multiplets, newMultiplet)\n end\n println(\">> Shift all initial level energies by -$(scheme.electronEnergyShift) $(Defaults.getDefaults(\"unit: energy\"))\")\n else\n multiplets = comp.initialMultiplets\n end ==#\n multiplets = comp.initialMultiplets\n end\n # Print out initial configurations and levels \n Cascade.displayLevels(stdout, multiplets, sa=\"initial \")\n if printSummary Cascade.displayLevels(iostream, multiplets, sa=\"initial \") end\n #\n # Generate subsequent cascade configurations as well as display and group them together\n wa = Cascade.generateConfigurationsForDielectronicCapture(multiplets, comp.scheme, comp.nuclearModel, comp.grid)\n wb1 = Cascade.groupDisplayConfigurationList(comp.nuclearModel.Z, wa[1], sa=\"initial configurations of the DR cascade \")\n wb2 = Cascade.groupDisplayConfigurationList(comp.nuclearModel.Z, wa[2], sa=\"doubly-excited capture configurations of the DR cascade \")\n wb3 = Cascade.groupDisplayConfigurationList(comp.nuclearModel.Z, wa[3], sa=\"decay configurations of the DR cascade \")\n #\n # Determine first all configuration 'blocks' and from them the individual steps of the cascade\n wc1 = Cascade.generateBlocks(scheme, comp::Cascade.Computation, wb1)\n wc2 = Cascade.generateBlocks(scheme, comp::Cascade.Computation, wb2, printout=false)\n wc3 = Cascade.generateBlocks(scheme, comp::Cascade.Computation, wb3, printout=false)\n # Shift the initial level energy by -electronEnergyShift\n @show scheme.electronEnergyShift\n if scheme.electronEnergyShift != 0. \n wc1old = wc1; wc1 = Cascade.Block[]\n for block in wc1old\n newMultiplet = Basics.shiftTotalEnergies(multiplet, Defaults.convertUnits(\"energy: to atomic\", -scheme.electronEnergyShift))\n push!(wc1, Cascade.Block(block.NoElectrons, block.confs, block.hasMultiplet, newMultiplet))\n end\n println(\">> Shift all initial level energies by $(-scheme.electronEnergyShift) $(Defaults.getDefaults(\"unit: energy\"))\")\n end\n #\n Cascade.displayBlocks(stdout, wc1, sa=\"from the initial configurations of the DR cascade \"); \n Cascade.displayBlocks(stdout, wc2, sa=\"from the doubly-excited capture configurations of the DR cascade \")\n Cascade.displayBlocks(stdout, wc3, sa=\"from the decay configurations of the DR cascade \")\n if printSummary Cascade.displayBlocks(iostream, wc1, sa=\"from the initial configurations of the DR cascade \"); \n Cascade.displayBlocks(iostream, wc2, sa=\"from the doubly-excited capture configurations of the DR cascade \")\n Cascade.displayBlocks(iostream, wc3, sa=\"from the decay configurations of the DR cascade \") end \n #\n # Determine, modify and compute the transition data for all steps, ie. the PhotoIonization.Line's, etc.\n gMultiplets = Multiplet[]; \n for block in wc1 push!(gMultiplets, block.multiplet) end\n for block in wc2 push!(gMultiplets, block.multiplet) end\n for block in wc3 push!(gMultiplets, block.multiplet) end\n we = Cascade.determineSteps(scheme, comp, wc1, wc2, wc3)\n Cascade.displaySteps(stdout, we, sa=\"electron capture and stabilization \")\n if printSummary Cascade.displaySteps(iostream, we, sa=\"electron capture and stabilization \") end \n wf = Cascade.modifySteps(we)\n #\n data = Cascade.computeSteps(scheme, comp, wf)\n if output \n results = Base.merge( results, Dict(\"name\" => comp.name) ) \n results = Base.merge( results, Dict(\"cascade scheme\" => comp.scheme) ) \n results = Base.merge( results, Dict(\"initial multiplets:\" => multiplets) ) \n results = Base.merge( results, Dict(\"generated multiplets:\" => gMultiplets) ) \n results = Base.merge( results, Dict(\"decay line data:\" => data) )\n #\n # Write out the result to file to later continue with simulations on the cascade data\n filename = \"zzz-cascade-dr-rate-computations-\" * string(Dates.now())[1:13] * \".jld\"\n println(\"\\n* Write all results to disk; use:\\n JLD.save(''$filename'', results) \\n using JLD \" *\n \"\\n results = JLD.load(''$filename'') ... to load the results back from file.\")\n if printSummary println(iostream, \"\\n* Write all results to disk; use:\\n JLD.save(''$filename'', results) \\n using JLD \" *\n \"\\n results = JLD.load(''$filename'') ... to load the results back from file.\" ) end \n JLD2.@save filename results\n end\n ## return( results )\n return( results )\n end\n", "meta": {"hexsha": "c6e8804784ec53169e2f58ad2edd152575c22dc5", "size": 28049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-Cascade-inc-dielectronic-capture.jl", "max_stars_repo_name": "sostock/JAC.jl", "max_stars_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2019-03-11T11:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:33:28.000Z", "max_issues_repo_path": "src/module-Cascade-inc-dielectronic-capture.jl", "max_issues_repo_name": "sostock/JAC.jl", "max_issues_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-04-02T22:04:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T06:21:57.000Z", "max_forks_repo_path": "src/module-Cascade-inc-dielectronic-capture.jl", "max_forks_repo_name": "sostock/JAC.jl", "max_forks_repo_head_hexsha": "ae70a6b3277ea7e46f53f97cdc7a6ffd12e1faf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T12:51:19.000Z", "avg_line_length": 72.2912371134, "max_line_length": 160, "alphanum_fraction": 0.6072230739, "num_tokens": 5970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.27202454519235225, "lm_q1q2_score": 0.15187864670269327}} {"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d7ff772c-9d33-42e7-9df1-3e02ceee79c5\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents()\nend\n\n# ╔═╡ 7553b887-a16d-4f3b-a91b-043f89e963d7\nmd\"\"\"\n# Control flow\n\n- [Julia docs | control flow](https://docs.julialang.org/en/v1/manual/control-flow/)\n- [Julia docs | functions](https://docs.julialang.org/en/v1/manual/functions/)\n\n\nJulia programs are able to run nonlinearly by controlling its execution flow.\n\"\"\"\n\n# ╔═╡ 383e7736-dd64-44ce-ac21-60a9a5a7c0db\nmd\"\"\"\n## Conditional statements\n\nCompound expressions are already covered in the previous chapter: [intro to Julia](intro-to-julia.html)\n\n### `if`/`else` block:\n\n```julia\nresult = if cond1\n\trun_if_cond1_is_true()\nelseif cond2\n\trun_if_cond2_is_true_and_cond1_is_false()\nelse\n\trun_if_neither_is_true()\nend\n```\n\n- The `elseif` and `else` blocks are optional. `if` and `end` are mandatory.\n- `if` blocks return a value. Capturing the value is optional.\n- `if` blocks are \"leaky\", i.e. they do not introduce a local scope. (The same as Python)\n- Only boolean (true / false) could be evaluated in `if` blocks. Using other types (e.g. Int) will generate an error.\n\n### Ternary operator\n\n`cond ? tvalue : fvalue` is eqialent to:\n\n```julia\nif cond \n\ttvalue\nelse\n\tfvalue\nend\n```\n\n### ifelse function\n\nAll the arguments are evaluated first in `ifelse(cond, tvalue, fvalue)`.\n\n\n### short cicuit evaluation\n\n`&&` (logical and) and `||` (logical or) operators support [short circuit evaluation](\nShort-circuit evaluation - Wikipedia\nhttps://en.wikipedia.org › wiki › Short-circuit_evaluation).\n\n- In the expression `a && b`, the subexpression `b` is only evaluated if `a` evaluates to true.\n- In the expression `a || b`, the subexpression `b` is only evaluated if `a` evaluates to false.\n\"\"\"\n\n# ╔═╡ 0335796f-da7d-4acc-be19-a0b45cd6042a\ntrue && 1 # && evaluates and returns the second argument if the first is true\n\n# ╔═╡ 2ee995ac-d9e8-4ded-b6b9-5fd35d564a24\nfalse && 1 # && otherwise returns false\n\n# ╔═╡ ce2cbdb6-637d-4f07-bb91-580621485b66\nscore = 10\n\n# ╔═╡ 648e6be1-5e8b-4406-bee5-708a93ea20f3\nresponse = if 80 < score <= 100\n \"Good\"\nelseif 60 < score <= 80\n \"Okay\"\nelse\n \"Uh-Oh\"\nend\n\n# ╔═╡ 2732609d-86f3-4594-8f02-4f8066d41720\nmd\"\"\"\n## Loops\n\nLoops are repeated evaluations.\n\n- `while` loops are often controlled by evaluated conditions.\n- `for` loops are often controlled by sequence length.\n\n\n- `break`: exit the loop immediately.\n- `continue`: move on to the next item / evaluation immediately.\n\"\"\"\n\n# ╔═╡ af291389-2e9c-41fc-880b-28fe1fe70e49\n## Hailstone sequence (3n+1 problem) in a while loop\nlet n = 27\n step = 0\n while n != 1\n if iseven(n)\n n ÷= 2\n else\n n = 3n + 1\n end\n step += 1\n end\n step\nend\n\n# ╔═╡ 4bb1e57d-ab16-4c97-ad4b-3db6a76b7e11\nlet sum = 0, n = 100\n\tfor i in 1:n\n\t\tsum += i\n\tend\n\tsum\nend\n\n# ╔═╡ 0117590e-213b-4a70-a9c8-f44075c58854\nwith_terminal() do \n\tfor x in 1:9\n\t\tif x == 5\n\t\t\tcontinue # jump to line #2\n\t\telseif x >=8\n\t\t\tbreak # jump to line #9\n\t\tend\n\t\tprintln(x, \"^2 = \", x^2)\n\tend\nend\n\n# ╔═╡ d52dfdce-cd96-4d1b-8aa6-f1137758221b\nwith_terminal() do\n\t# Use enumerate(seq) to get a pair of one idx and one element\n\tfor (i, x) in enumerate(10:-1:1)\n\t\tprintln(\"xs[\", i, \"] = \", x)\n\tend\nend\n\n# ╔═╡ 81194437-5b15-4ab9-af47-33108dde7751\nmd\"\"\"\nMultiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables.\n\"\"\"\n\n# ╔═╡ 21c53be2-3d98-4fb5-87b5-dd53bac7dd76\nwith_terminal() do\n\t# Multiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables\n\tfor i = 'x':'z', j = '1':'3'\n\t\tprintln(i, j)\n\tend\nend\n\n# ╔═╡ bd4a9500-5b35-4f0a-bd1c-4e42a650308b\nmd\"\"\"\n# Functions\n\n> In Julia, a function is an object that maps a tuple of argument values to a return value. \n> [Julia docs](https://docs.julialang.org/en/v1/manual/functions/)\n\n\nFunctions facilitate:\n- Code reuse and encapsulation.\n- Specializations ([Methods](https://docs.julialang.org/en/v1/manual/methods/))\n\n- Functions are first-class objects and can be passed into a higher-order function.\n- The arguments are \"passed-by-sharing\". Modifications to mutable argument values (such as `Arrays`) will be reflected to the caller. (Similar to Python)\n- Functions that will update the arguments are named with a bang `!` by convention. (e.g. sort(arr) vs sort!(arr))\n- Often only the scalar version of a function is required; for vector element-wise operations, there are broadcast (dot) syntax.\n- You can write multiple function with the same name provided they have different parameter lists. Julia will choose the most apporpriate one for you.\n\"\"\"\n\n# ╔═╡ 0d1252a0-3ce8-4b96-ba08-a6f1895cc0dc\nmd\"\"\"\n## Standard form\n\"\"\"\n\n# ╔═╡ 5d26cdd5-9a6d-4307-89b7-6629997b9132\n\"Mechaelis-Menton function\" # Function documentations\nfunction mm(x, k) # function name and parameter list\n result = x / (x +k)\n return result # return statement is optional\nend\n\n# ╔═╡ ce413514-bf5c-4dc8-b2af-42e9f663fa87\nmd\"\"\"\n## One-liner form\n\"\"\"\n\n# ╔═╡ b87e79d8-91b0-4ecb-85b8-e2e8d01da426\n# One-liner function\nmm(x) = mm(x, one(x))\n\n# ╔═╡ 5d2c7cdc-d34a-4e97-82c4-ac58a9196fd8\nmm(0.5, 2)\n\n# ╔═╡ d137d92d-f629-41cf-824c-516391f26f11\nmm(1)\n\n# ╔═╡ 65de3953-6a86-4e3f-ba00-b6c352678284\nmd\"\"\"\n## Anonymous functions\n\nOften used with high-order functions e.g. `map()`\n\"\"\"\n\n# ╔═╡ f14ab8cb-db2e-47f7-adaa-d932ed25bb1b\nmap(x->x^2, 1:3)\n\n# ╔═╡ 26ba95b5-1d1c-4bed-b6dd-e17eba8136e3\nmd\"\"\"\nUse [`do` block](https://docs.julialang.org/en/v1/manual/functions/#Do-Block-Syntax-for-Function-Arguments) for long anonymous functions.\n\n`do` block are also useful in opening files.\n\n```julia\nopen(\"outfile\", \"w\") do io\n write(io, data)\nend\n```\n\"\"\"\n\n# ╔═╡ e2801350-24b7-4453-af27-ee63afbb4087\nval = rand(-6:6, 10)\n\n# ╔═╡ 2f07f81c-346a-4f17-872c-f174adf6ff1d\nmap(val) do x\n if x < 0 && iseven(x)\n return 0\n elseif x == 0\n return 1\n else\n return x\n end\nend\n\n# ╔═╡ ea04a83f-74a1-46b0-b686-f125e0972ca2\nmd\"\"\"\n## Optional arguments\n\n[Optional (positional) arguments](https://docs.julialang.org/en/v1/manual/functions/#Optional-Arguments) are listed after mandatory ones.\n\n```julia\nfunction func(a, b, c=1)\n# content\nend\n```\n\nAnd they are called with `func(a, b)` or `func(a, b, 3)`\n\n## Keyword arguments\n\n[Keyword arguments](https://docs.julialang.org/en/v1/manual/functions/#Keyword-Arguments) are listed after `;`\n\n```julia\nfunction plot(x, y; style=\"solid\", width=1, color=\"black\")\n ###\nend\n```\n\nAnd they are called with `plot(x, y, width=2)` or `plot(x, y; width=2)`\n\"\"\"\n\n# ╔═╡ d2e2e668-71f5-444b-98bf-5ea45df81c84\nargs_kwargs(args...; kwargs...) = (args, kwargs) # mind the semicolon ;\n\n# ╔═╡ 91e0412a-24ef-469a-9a67-3dcfa155d62a\nargs_kwargs(1,true, :IAmASymbol, b=4, c=\"IAmAString\")\n\n# ╔═╡ 33a48540-cb59-11eb-0602-8da0ecdcbe4c\nmd\"\"\"\n# See also\n\n- [Compositing functions and pipes](https://docs.julialang.org/en/v1/manual/functions/#Function-composition-and-piping)\n- [Variable argument (vararg) functions](https://docs.julialang.org/en/v1/manual/functions/#Varargs-Functions)\n- [Argument destructuring](https://docs.julialang.org/en/v1/manual/functions/#Argument-destructuring)\n- [Scope of variables](https://docs.julialang.org/en/v1/manual/variables-and-scoping/)\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlutoUI = \"~0.7.9\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"81690084b6198a2e1da36fcfda16eeca9f9f24e4\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.1\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"c8abc88faa3f7a3950832ac5d6e690881590d6dc\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.0\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═d7ff772c-9d33-42e7-9df1-3e02ceee79c5\n# ╠═7553b887-a16d-4f3b-a91b-043f89e963d7\n# ╠═383e7736-dd64-44ce-ac21-60a9a5a7c0db\n# ╠═0335796f-da7d-4acc-be19-a0b45cd6042a\n# ╠═2ee995ac-d9e8-4ded-b6b9-5fd35d564a24\n# ╠═ce2cbdb6-637d-4f07-bb91-580621485b66\n# ╠═648e6be1-5e8b-4406-bee5-708a93ea20f3\n# ╠═2732609d-86f3-4594-8f02-4f8066d41720\n# ╠═af291389-2e9c-41fc-880b-28fe1fe70e49\n# ╠═4bb1e57d-ab16-4c97-ad4b-3db6a76b7e11\n# ╠═0117590e-213b-4a70-a9c8-f44075c58854\n# ╠═d52dfdce-cd96-4d1b-8aa6-f1137758221b\n# ╠═81194437-5b15-4ab9-af47-33108dde7751\n# ╠═21c53be2-3d98-4fb5-87b5-dd53bac7dd76\n# ╠═bd4a9500-5b35-4f0a-bd1c-4e42a650308b\n# ╠═0d1252a0-3ce8-4b96-ba08-a6f1895cc0dc\n# ╠═5d26cdd5-9a6d-4307-89b7-6629997b9132\n# ╠═ce413514-bf5c-4dc8-b2af-42e9f663fa87\n# ╠═b87e79d8-91b0-4ecb-85b8-e2e8d01da426\n# ╠═5d2c7cdc-d34a-4e97-82c4-ac58a9196fd8\n# ╠═d137d92d-f629-41cf-824c-516391f26f11\n# ╠═65de3953-6a86-4e3f-ba00-b6c352678284\n# ╠═f14ab8cb-db2e-47f7-adaa-d932ed25bb1b\n# ╠═26ba95b5-1d1c-4bed-b6dd-e17eba8136e3\n# ╠═e2801350-24b7-4453-af27-ee63afbb4087\n# ╠═2f07f81c-346a-4f17-872c-f174adf6ff1d\n# ╠═ea04a83f-74a1-46b0-b686-f125e0972ca2\n# ╠═d2e2e668-71f5-444b-98bf-5ea45df81c84\n# ╠═91e0412a-24ef-469a-9a67-3dcfa155d62a\n# ╠═33a48540-cb59-11eb-0602-8da0ecdcbe4c\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "4c74c53aef66acc2e814d61e34869f36e736d86c", "size": 10550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "control-flow.jl", "max_stars_repo_name": "sosiristseng/BEBI-5009", "max_stars_repo_head_hexsha": "440ab8c8cb938dbca1f4de80f1c0127d8b4109b8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-05T02:54:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T08:46:31.000Z", "max_issues_repo_path": "control-flow.jl", "max_issues_repo_name": "sosiristseng/BEBI-5009", "max_issues_repo_head_hexsha": "440ab8c8cb938dbca1f4de80f1c0127d8b4109b8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-07-10T11:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T05:13:47.000Z", "max_forks_repo_path": "control-flow.jl", "max_forks_repo_name": "sosiristseng/BEBI-5009", "max_forks_repo_head_hexsha": "440ab8c8cb938dbca1f4de80f1c0127d8b4109b8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-22T02:29:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T13:44:57.000Z", "avg_line_length": 26.5075376884, "max_line_length": 153, "alphanum_fraction": 0.7121327014, "num_tokens": 4354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.32423539245106076, "lm_q1q2_score": 0.15073754344536544}}