licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 867 | # Example 8: Composite Multiscale Cross-Approximate Entropy
Import two signals of uniformly distributed pseudorandom integers in the range [1 8] and
create a multiscale entropy object with the following parameters:
`EnType` = XApEn(), embedding dimension = 2, time delay = 2, radius distance threshold = 0.5
```@example
using EntropyHub # hide
X = ExampleData("randintegers2");
Mobj = MSobject(XApEn, m = 2, tau = 2, r = 0.5)
Mobj # hide
```
Calculate the comsposite multiscale cross-approximate entropy over 3 temporal scales
where the radius distance threshold value (`r`) specified by `Mobj` becomes scaled by the
variance of the signal at each scale.
```@example
using EntropyHub # hide
X = ExampleData("randintegers2"); # hide
Mobj = MSobject(XApEn, m = 2, tau = 2, r = 0.5) # hide
MSx, _ = cXMSEn(X[:,1], X[:,2], Mobj, Scales = 3, RadNew = 1)
MSx # hide
``` | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 1194 | # Example 9: Hierarchical Multiscale corrected Cross-Conditional Entropy
Import the x and y components of the Henon system of equations and create a multiscale
entropy object with the following parameters:
`EnType` = XCondEn(), embedding dimension = 2, time delay = 2, number of symbols = 12,
logarithm base = 2, normalization = true
```
Data = ExampleData("henon");
Mobj = MSobject(XCondEn, m = 2, tau = 2, c = 12, Logx = 2, Norm = true)
using Plots
scatter(Data[:,1], Data[:,2], markercolor = "green", markerstrokecolor = "black",
markersize = 3, background_color = "black", grid = false)
```

Calculate the hierarchical multiscale corrected cross-conditional entropy over 4 temporal
scales and return the average cross-entropy at each scale (`Sn`), the complexity index (`Ci`),
and a plot of the multiscale entropy curve and the hierarchical tree with the cross-entropy
value at each node.
```@example
using EntropyHub # hide
Data = ExampleData("henon"); # hide
Mobj = MSobject(XCondEn, m = 2, tau = 2, c = 12, Logx = 2, Norm = true) # hide
MSx, Sn, Ci = hXMSEn(Data[:,1], Data[:,2], Mobj, Scales = 4, Plotx = true)
```
 | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 1822 | ```@contents
Pages = ["Example1.md", "Example2.md", "Example3.md", "Example4.md", "Example5.md",
"Example6.md","Example7.md","Example8.md","Example9.md","Example10.md",
"Example11.md", "Example12.md", "Example13.md"]
```
# Examples:
The following sections provide some basic examples of EntropyHub functions.
These examples are merely a snippet of the full range of EntropyHub functionality.
In the following examples, signals / data are imported into Julia using the [`ExampleData()`](@ref) function.
To use this function as shown in the examples below, __*an internet connection is required*__.
!!! tip "IMPORTANT TO NOTE"
Parameters of the base or cross- entropy methods are passed to multiscale and multiscale cross- functions using the multiscale entropy object using MSobject.
Base and cross- entropy methods are declared with MSobject() using any Base or Cross- entropy function.
See the MSobject example in the following sections for more info.
!!! warning "Hierarchical Multiscale Entropy (+ Multiscale Cross-Entropy)"
In hierarchical multiscale entropy ([hMSEn](@ref)) and hierarchical multiscale cross-entropy ([hXMSEn](@ref)) functions, the length of the time series signal(s) is halved at each scale.
Thus, hMSEn and hXMSEn only use the first 2^N data points where 2^N <= the length of the original time series signal.
i.e. For a signal of 5000 points, only the first 4096 are used. For a signal of 1500 points, only the first 1024 are used.
!!! danger "BIDIMENSIONAL ENTROPIES"
Each bidimensional entropy function (SampEn2D, FuzzEn2D, DistEn2D, EspEn2D) has an important keyword argument - `Lock`.
Bidimensional entropy functions are "locked" by default (`Lock == true`) to only permit matrices with a maximum size of 128 x 128.
| EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 719 | ```@meta
CollapsedDocStrings = true
Description = "Entropy of single time series signals"
```
# Base Entropies
__*Functions for estimating the entropy of a single univariate time series.*__
`The following functions also form the base entropy method used by Multiscale functions` -> [`MSEn`](@ref), [`cMSEn`](@ref), [`rMSEn`](@ref), [`hMSEn`](@ref)
```@docs
EntropyHub.ApEn
EntropyHub.SampEn
EntropyHub.FuzzEn
EntropyHub.K2En
EntropyHub.PermEn
EntropyHub.CondEn
EntropyHub.DistEn
EntropyHub.SpecEn
EntropyHub.DispEn
EntropyHub.SyDyEn
EntropyHub.IncrEn
EntropyHub.CoSiEn
EntropyHub.PhasEn
EntropyHub.SlopEn
EntropyHub.BubbEn
EntropyHub.GridEn
EntropyHub.EnofEn
EntropyHub.AttnEn
EntropyHub.RangEn
EntropyHub.DivEn
``` | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 1580 | ```@meta
CollapsedDocStrings = true
Description = "Entropy of two-dimensional (2D) data"
```
# Bidimensional Entropies
__*Functions for estimating the entropy of a two-dimensional univariate matrix.*__
While EntropyHub functions primarily apply to time series data, with the following
bidimensional entropy functions one can estimate the entropy of two-dimensional (2D)
matrices. Hence, bidimensional entropy functions are useful for applications such as image analysis.
!!! danger "IMPORTANT: Locked Matrix Size"
Each bidimensional entropy function ([`SampEn2D`](@ref), [`FuzzEn2D`](@ref), [`DistEn2D`](@ref), [`DispEn2D`](@ref),
[`EspEn2D`](@ref), [`PermEn2D`](@ref)) has an important keyword argument - `Lock`. Bidimensional entropy functions are
"locked" by default (`Lock == true`) to only permit matrices with a maximum size of 128 x 128.
The reason for this is because there are hundreds of millions of pairwise calculations
performed in the estimation of bidimensional entropy, so memory errors often
occur when storing data on RAM.
e.g. For a matrix of size [200 x 200], an embedding dimension (`m`) = 3, and a time
delay (`tau`) = 1, there are 753,049,836 pairwise matrix comparisons (6,777,448,524
elemental subtractions).
To pass matrices with sizes greater than [128 x 128], set `Lock = false`.
`CAUTION: unlocking the permitted matrix size may cause your Julia IDE to crash.`
```@docs
EntropyHub.SampEn2D
EntropyHub.FuzzEn2D
EntropyHub.DistEn2D
EntropyHub.DispEn2D
EntropyHub.PermEn2D
EntropyHub.EspEn2D
``` | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 541 | ```@meta
CollapsedDocStrings = true
Description = "Entropy between two time series signals"
```
# Cross Entropies
__*Functions for estimating the cross-entropy between two univariate time series.*__
`The following functions also form the cross-entropy method used by Multiscale Cross-Entropy functions.` -> [`XMSEn`](@ref), [`cXMSEn`](@ref), [`rXMSEn`](@ref), [`hXMSEn`](@ref)
```@docs
EntropyHub.XApEn
EntropyHub.XSampEn
EntropyHub.XFuzzEn
EntropyHub.XK2En
EntropyHub.XPermEn
EntropyHub.XCondEn
EntropyHub.XDistEn
EntropyHub.XSpecEn
``` | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 1068 | ```@meta
CollapsedDocStrings = true
Description = "Multiscale entropy between two time series signals"
```
# Multiscale Cross-Entropies
__*Functions for estimating the multiscale entropy between two univariate time series.*__
Just as one can calculate multiscale entropy using any Base entropy, the same functionality is possible with multiscale cross-entropy using any Cross-entropy function:
[`XApEn`](@ref), [`XSampEn`](@ref), [`XK2En`](@ref), [`XCondEn`](@ref), [`XPermEn`](@ref), [`XSpecEn`](@ref), [`XDistEn`](@ref), [`XFuzzEn`](@ref).
To do so, we again use the [`MSobject`](@ref) function to pass a multiscale object (`Mobj`) to the multiscale cross-entropy functions.
!!! info "NOTE:"
Multiscale cross-entropy functions have three positional arguments:
1. the first data seuqence, `Sig1` (a vector of >10 elements),
2. the second data seuqence, `Sig2` (a vector of > 10 elements),
3. the multiscale entropy object, `Mobj` -> see [`MSobject`](@ref)
```@docs
EntropyHub.XMSEn
EntropyHub.cXMSEn
EntropyHub.rXMSEn
EntropyHub.hXMSEn
``` | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 978 | ```@meta
CollapsedDocStrings = true
Description = "Multiscale entropy of single time series signals"
```
# Multiscale Entropies
__*Functions for estimating the multiscale entropy of a univariate time series.*__
Multiscale entropy can be calculated using any of the Base entropies:
([`ApEn`](@ref), [`AttnEn`](@ref), [`BubbEn`](@ref), [`CondEn`](@ref), [`CoSiEn`](@ref), [`DistEn`](@ref), [`DivEn`](@ref),
[`DispEn`](@ref), [`EnofEn`](@ref), [`FuzzEn`](@ref), [`GridEn`](@ref), [`IncrEn`](@ref), [`K2En`](@ref),
[`PermEn`](@ref), [`PhasEn`](@ref), [`RangEn`](@ref), [`SampEn`](@ref), [`SlopEn`](@ref), [`SpecEn`](@ref), [`SyDyEn`](@ref)).
!!! info "NOTE:"
Multiscale cross-entropy functions have two positional arguments:
1. the data sequence, `Sig` (a vector > 10 elements),
2. the multiscale entropy object, `Mobj` -> see [`MSobject`](@ref)
```@docs
EntropyHub.MSobject
EntropyHub.MSEn
EntropyHub.cMSEn
EntropyHub.rMSEn
EntropyHub.hMSEn
```
| EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 467 | ```@meta
CollapsedDocStrings = true
Description = "Entropy of multivariate time series "
```
# Multivariate Entropies
__*Functions for estimating the entropy of a multivariate time series dataset.*__
`The following functions also form the multivariate entropy method used by Multivariate Multiscale functions.` -> [`MvMSEn`](@ref), [`cMvMSEn`](@ref)
```@docs
EntropyHub.MvSampEn
EntropyHub.MvFuzzEn
EntropyHub.MvPermEn
EntropyHub.MvDispEn
EntropyHub.MvCoSiEn
``` | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 1024 | ```@meta
CollapsedDocStrings = true
Description = "Multivariate multiscale entropy of multivariate time series "
```
# Multivariate Multiscale Entropies
__*Functions for estimating the Multivariate multiscale entropy of a multivariate time series dataset.*__
Just as one can calculate multiscale entropy using any Base or Cross- entropy, the same functionality is possible with multivariate multiscale entropy using any Multivariate function:
[`MvSampEn`](@ref), [`MvFuzzEn`](@ref), [`MvDispEn`](@ref), [`MvPermEn`](@ref), [`MvCoSiEn`](@ref).
To do so, we again use the [`MSobject`](@ref) function to pass a multiscale object (`Mobj`) to the multivariate multiscale entropy functions.
!!! info "NOTE:"
Multivariate multiscale entropy functions have two positional arguments:
1. the multivariate dataset, `Data` (an NxM matrix of N observations (>10 elements), and M time series (>1)),
2. the multiscale entropy object, `Mobj` -> see [`MSobject`](@ref)
```@docs
EntropyHub.MvMSEn
EntropyHub.cMvMSEn
``` | EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"Apache-2.0"
] | 2.0.0 | c4c17ff5a1c4186a68e6cd8e504f830a8bd25890 | docs | 242 | ```@meta
CollapsedDocStrings = true
```
# Other Entropies
__*Supplementary functions for various tasks related to EntropyHub and signal processing.*__
```@docs
EntropyHub.ExampleData
EntropyHub.WindowData
```
[`EntropyHub.MSobject`](@ref)
| EntropyHub | https://github.com/MattWillFlood/EntropyHub.jl.git |
|
[
"MIT"
] | 0.3.0 | bfe2782c68eadd44e719a00bbaf96c83b921e4e1 | code | 163146 | module XSteam
#h_prho beh鰒er T_prho f鰎 samtliga regioner!!!!
#***********************************************************************************************************
#* Water and steam properties according to IAPWS IF-97 *
#* By Magnus Holmgren, www.x-eng.com *
#* The steam tables are free and provided as is. *
#* We take no responsibilities for any errors in the code or damage thereby. *
#* You are free to use, modify and distribute the code as long as authorship is properly acknowledged. *
#* Please notify me at [email protected] if the code is used in commercial applications *
#***********************************************************************************************************
#
# XSteam provides accurate steam and water properties from 0 - 1000 bar and from 0 - 2000 deg C according to
# the standard IAPWS IF-97. For accuracy of the functions in different regions see IF-97 (www.iapws.org)
#
# *** Using XSteam *****************************************************************************************
#XSteam take 2 or 3 arguments. The first argument must always be the steam table function you want to use.
#The other arguments are the inputs to that function.
#Example: XSteam("h_pt",1,20) Returns the enthalpy of water at 1 bar and 20 degC
#Example: XSteam("TSat_p",1) Returns the saturation temperature of water at 1 bar.
#For a list of valid Steam Table functions se bellow or the XSteam macros for MS Excel.
#
#*** Nomenclature ******************************************************************************************
# First the wanted property then a _ then the wanted input properties.
# Example. T_ph is temperature as a function of pressure and enthalpy.
# For a list of valid functions se bellow or XSteam for MS Excel.
# T Temperature (deg C)
# p Pressure (bar)
# h Enthalpy (kJ/kg)
# v Specific volume (m3/kg)
# rho Density
# s Specific entropy
# u Specific internal energy
# Cp Specific isobaric heat capacity
# Cv Specific isochoric heat capacity
# w Speed of sound
# my Viscosity
# tc Thermal Conductivity
# st Surface Tension
# x Vapour fraction
# vx Vapour Volume Fraction
#
#*** Valid Steam table functions. ****************************************************************************
#
#Temperature
#Tsat_p Saturation temperature
#T_ph Temperture as a function of pressure and enthalpy
#T_ps Temperture as a function of pressure and entropy
#T_hs Temperture as a function of enthalpy and entropy
#
#Pressure
#psat_T Saturation pressure
#p_hs Pressure as a function of h and s.
#p_hrho Pressure as a function of h and rho. Very unaccurate for solid water region since it"s almost incompressible!
#
#Enthalpy
#hV_p Saturated vapour enthalpy
#hL_p Saturated liquid enthalpy
#hV_T Saturated vapour enthalpy
#hL_T Saturated liquid enthalpy
#h_pT Entalpy as a function of pressure and temperature.
#h_ps Entalpy as a function of pressure and entropy.
#h_px Entalpy as a function of pressure and vapour fraction
#h_prho Entalpy as a function of pressure and density. Observe for low temperatures (liquid) this equation has 2 solutions.
#h_Tx Entalpy as a function of temperature and vapour fraction
#
#Specific volume
#vV_p Saturated vapour volume
#vL_p Saturated liquid volume
#vV_T Saturated vapour volume
#vL_T Saturated liquid volume
#v_pT Specific volume as a function of pressure and temperature.
#v_ph Specific volume as a function of pressure and enthalpy
#v_ps Specific volume as a function of pressure and entropy.
#
#Density
#rhoV_p Saturated vapour density
#rhoL_p Saturated liquid density
#rhoV_T Saturated vapour density
#rhoL_T Saturated liquid density
#rho_pT Density as a function of pressure and temperature.
#rho_ph Density as a function of pressure and enthalpy
#rho_ps Density as a function of pressure and entropy.
#
#Specific entropy
#sV_p Saturated vapour entropy
#sL_p Saturated liquid entropy
#sV_T Saturated vapour entropy
#sL_T Saturated liquid entropy
#s_pT Specific entropy as a function of pressure and temperature (Returns saturated vapour entalpy if mixture.)
#s_ph Specific entropy as a function of pressure and enthalpy
#
#Specific internal energy
#uV_p Saturated vapour internal energy
#uL_p Saturated liquid internal energy
#uV_T Saturated vapour internal energy
#uL_T Saturated liquid internal energy
#u_pT Specific internal energy as a function of pressure and temperature.
#u_ph Specific internal energy as a function of pressure and enthalpy
#u_ps Specific internal energy as a function of pressure and entropy.
#
#Specific isobaric heat capacity
#CpV_p Saturated vapour heat capacity
#CpL_p Saturated liquid heat capacity
#CpV_T Saturated vapour heat capacity
#CpL_T Saturated liquid heat capacity
#Cp_pT Specific isobaric heat capacity as a function of pressure and temperature.
#Cp_ph Specific isobaric heat capacity as a function of pressure and enthalpy
#Cp_ps Specific isobaric heat capacity as a function of pressure and entropy.
#
#Specific isochoric heat capacity
#CvV_p Saturated vapour isochoric heat capacity
#CvL_p Saturated liquid isochoric heat capacity
#CvV_T Saturated vapour isochoric heat capacity
#CvL_T Saturated liquid isochoric heat capacity
#Cv_pT Specific isochoric heat capacity as a function of pressure and temperature.
#Cv_ph Specific isochoric heat capacity as a function of pressure and enthalpy
#Cv_ps Specific isochoric heat capacity as a function of pressure and entropy.
#
#Speed of sound
#wV_p Saturated vapour speed of sound
#wL_p Saturated liquid speed of sound
#wV_T Saturated vapour speed of sound
#wL_T Saturated liquid speed of sound
#w_pT Speed of sound as a function of pressure and temperature.
#w_ph Speed of sound as a function of pressure and enthalpy
#w_ps Speed of sound as a function of pressure and entropy.
#
#Viscosity
#Viscosity is not part of IAPWS Steam IF97. Equations from
#"Revised Release on the IAPWS Formulation 1985 for the Viscosity of Ordinary Water Substance", 2003 are used.
#Viscosity in the mixed region (4) is interpolated according to the density. This is not true since it will be two fases.
#my_pT Viscosity as a function of pressure and temperature.
#my_ph Viscosity as a function of pressure and enthalpy
#my_ps Viscosity as a function of pressure and entropy.
#
#Thermal Conductivity
#Revised release on the IAPS Formulation 1985 for the Thermal Conductivity of ordinary water substance (IAPWS 1998)
#tcL_p Saturated vapour thermal conductivity
#tcV_p Saturated liquid thermal conductivity
#tcL_T Saturated vapour thermal conductivity
#tcV_T Saturated liquid thermal conductivity
#tc_pT Thermal conductivity as a function of pressure and temperature.
#tc_ph Thermal conductivity as a function of pressure and enthalpy
#tc_hs Thermal conductivity as a function of enthalpy and entropy
#
#Surface tension
#st_T Surface tension for two phase water/steam as a function of T
#st_p Surface tension for two phase water/steam as a function of T
#Vapour fraction
#x_ph Vapour fraction as a function of pressure and enthalpy
#x_ps Vapour fraction as a function of pressure and entropy.
#
#Vapour volume fraction
#vx_ph Vapour volume fraction as a function of pressure and enthalpy
#vx_ps Vapour volume fraction as a function of pressure and entropy.
#*Contents.
#*1 Calling functions
#*1.1
#*1.2 Temperature (T)
#*1.3 Pressure (p)
#*1.4 Enthalpy (h)
#*1.5 Specific Volume (v)
#*1.6 Density (rho)
#*1.7 Specific entropy (s)
#*1.8 Specific internal energy (u)
#*1.9 Specific isobaric heat capacity (Cp)
#*1.10 Specific isochoric heat capacity (Cv)
#*1.11 Speed of sound
#*1.12 Viscosity
#*1.13 Prandtl
#*1.14 Kappa
#*1.15 Surface tension
#*1.16 Heat conductivity
#*1.17 Vapour fraction
#*1.18 Vapour Volume Fraction
#
#*2 IAPWS IF 97 Calling functions
#*2.1 Functions for region 1
#*2.2 Functions for region 2
#*2.3 Functions for region 3
#*2.4 Functions for region 4
#*2.5 Functions for region 5
#
#*3 Region Selection
#*3.1 Regions as a function of pT
#*3.2 Regions as a function of ph
#*3.3 Regions as a function of ps
#*3.4 Regions as a function of hs
#
#4 Region Borders
#4.1 Boundary between region 1 and 3.
#4.2 Region 3. pSat_h and pSat_s
#4.3 Region boundary 1to3 and 3to2 as a functions of s
#
#5 Transport properties
#5.1 Viscosity (IAPWS formulation 1985)
#5.2 Thermal Conductivity (IAPWS formulation 1985)
#5.3 Surface Tension
#
#6 Units
#
#7 Verification
#7.1 Verifiy region 1
#7.2 Verifiy region 2
#7.3 Verifiy region 3
#7.4 Verifiy region 4
#7.5 Verifiy region 5
#***********************************************************************************************************
#*1 Calling functions *
#***********************************************************************************************************
#***********************************************************************************************************
#*1.1
#fun=lower(fun);
#switch fun
#***********************************************************************************************************
#*1.2 Temperature
function Tsat_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_T(T4_p(p));
else
Out = NaN;
end
Out
end
function Tsat_s(s)
s = toSIunit_s(s);
if s > -0.0001545495919 && s < 9.155759395
ps = p4_s(s);
Out = fromSIunit_T(T4_p(ps));
else
Out = NaN;
end
Out
end
function T_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
region = region_ph(p, h);
if region == 1
Out = fromSIunit_T(T1_ph(p, h));
elseif region == 2
Out = fromSIunit_T(T2_ph(p, h));
elseif region == 3
Out = fromSIunit_T(T3_ph(p, h));
elseif region == 4
Out = fromSIunit_T(T4_p(p));
elseif region == 5
Out = fromSIunit_T(T5_ph(p, h));
else
Out = NaN;
end
Out
end
function T_ps(p,s)
#println("p=",p,"s=",s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Out = fromSIunit_T(T1_ps(p, s));
elseif Region == 2
Out = fromSIunit_T(T2_ps(p, s));
elseif Region == 3
Out = fromSIunit_T(T3_ps(p, s));
elseif Region == 4
Out = fromSIunit_T(T4_p(p));
elseif Region == 5
Out = fromSIunit_T(T5_ps(p, s));
else
Out = NaN;
end
Out
end
function T_hs(h,s)
h = toSIunit_h(h);
s = toSIunit_s(s);
Region = region_hs(h, s);
if Region == 1
p1 = p1_hs(h, s);
Out = fromSIunit_T(T1_ph(p1, h));
elseif Region == 2
p2 = p2_hs(h, s);
Out = fromSIunit_T(T2_ph(p2, h));
elseif Region == 3
p3 = p3_hs(h, s);
Out = fromSIunit_T(T3_ph(p3, h));
elseif Region == 4
Out = fromSIunit_T(T4_hs(h, s));
elseif Region == 5
#error("functions of hs is not avlaible in region 5");
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.3 Pressure (p)
function psat_T(t)
T = toSIunit_T(t);
if T < 647.096 && T > 273.15
Out = fromSIunit_p(p4_T(T));
else
Out = NaN;
end
Out
end
function psat_s(s)
s = toSIunit_s(s);
if s > -0.0001545495919 && s < 9.155759395
Out = fromSIunit_p(p4_s(s));
else
Out = NaN;
end
Out
end
function p_hs(h,s)
h = toSIunit_h(h);
s = toSIunit_s(s);
Region = region_hs(h, s);
if Region == 1
Out = fromSIunit_p(p1_hs(h, s));
elseif Region == 2
Out = fromSIunit_p(p2_hs(h, s));
elseif Region == 3
Out = fromSIunit_p(p3_hs(h, s));
elseif Region == 4
tSat = T4_hs(h, s);
Out = fromSIunit_p(p4_T(tSat));
elseif Region == 5
#error("functions of hs is not avlaible in region 5");
else
Out = NaN;
end
Out
end
function p_hrho(h,rho)
h=h;
rho=rho;
#Not valid for water or sumpercritical since water rho does not change very much with p.
#Uses iteration to find p.
High_Bound = fromSIunit_p(100);
Low_Bound = fromSIunit_p(0.000611657);
ps = fromSIunit_p(10);
rhos = 1 / v_ph(ps, h);
while abs(rho - rhos) > 0.0000001
rhos = 1 / v_ph(ps, h);
if rhos >= rho
High_Bound = ps;
else
Low_Bound = ps;
end
ps = (Low_Bound + High_Bound) / 2;
end
Out = ps;
Out
end
#***********************************************************************************************************
#*1.4 Enthalpy (h)
function hV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_h(h4V_p(p));
else
Out = NaN;
end
Out
end
function hL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_h(h4L_p(p));
else
Out = NaN;
end
Out
end
function hV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
p = p4_T(T);
Out = fromSIunit_h(h4V_p(p));
else
Out = NaN;
end
Out
end
function hL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
p = p4_T(T);
Out = fromSIunit_h(h4L_p(p));
else
Out = NaN;
end
Out
end
function h_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_h(h1_pT(p, T));
elseif Region == 2
Out = fromSIunit_h(h2_pT(p, T));
elseif Region == 3
Out = fromSIunit_h(h3_pT(p, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_h(h5_pT(p, T));
else
Out = NaN;
end
Out
end
function h_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Out = fromSIunit_h(h1_pT(p, T1_ps(p, s)));
elseif Region == 2
Out = fromSIunit_h(h2_pT(p, T2_ps(p, s)));
elseif Region == 3
Out = fromSIunit_h(h3_rhoT(1 / v3_ps(p, s), T3_ps(p, s)));
elseif Region == 4
xs = x4_ps(p, s);
Out = fromSIunit_h(xs * h4V_p(p) + (1 - xs) * h4L_p(p));
elseif Region == 5
Out = fromSIunit_h(h5_pT(p, T5_ps(p, s)));
else
Out = NaN;
end
Out
end
function h_px(p,x)
p = toSIunit_p(p);
x = toSIunit_x(x);
if x > 1 || x < 0 || p >= 22.064
Out = NaN;
return
end
hL = h4L_p(p);
hV = h4V_p(p);
Out = hL + x * (hV - hL);
Out
end
function h_prho(p,rho)
p = toSIunit_p(p);
rho = 1 / toSIunit_v(1 / rho);
Region = Region_prho(p, rho);
if Region == 1
Out = fromSIunit_h(h1_pT(p, T1_prho(p, rho)));
elseif Region == 2
Out = fromSIunit_h(h2_pT(p, T2_prho(p, rho)));
elseif Region == 3
Out = fromSIunit_h(h3_rhoT(rho, T3_prho(p, rho)));
elseif Region == 4
if p < 16.529
vV = v2_pT(p, T4_p(p));
vL = v1_pT(p, T4_p(p));
else
vV = v3_ph(p, h4V_p(p));
vL = v3_ph(p, h4L_p(p));
end
hV = h4V_p(p);
hL = h4L_p(p);
x = (1 / rho - vL) / (vV - vL);
Out = fromSIunit_h((1 - x) * hL + x * hV);
elseif Region == 5
Out = fromSIunit_h(h5_pT(p, T5_prho(p, rho)));
else
Out = NaN;
end
Out
end
function h_Tx(t,x)
T = toSIunit_T(t);
x = toSIunit_x(x);
if x > 1 || x < 0 || T >= 647.096
Out = NaN;
return Out
end
p = p4_T(T);
hL = h4L_p(p);
hV = h4V_p(p);
Out = hL + x * (hV - hL);
Out
end
#***********************************************************************************************************
#*1.5 Specific Volume (v)
function vV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_v(v2_pT(p, T4_p(p)));
else
Out = fromSIunit_v(v3_ph(p, h4V_p(p)));
end
else
Out = NaN;
end
Out
end
rhoV_p(p)=1/vV_p(p)
function vL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_v(v1_pT(p, T4_p(p)));
else
Out = fromSIunit_v(v3_ph(p, h4L_p(p)));
end
else
Out = NaN;
end
Out
end
rhoL_p(p)=1/vL_p(p)
function vV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_v(v2_pT(p4_T(T), T));
else
Out = fromSIunit_v(v3_ph(p4_T(T), h4V_p(p4_T(T))));
end
else
Out = NaN;
end
Out
end
rhoV_T(t)=1/vV_T(t)
function vL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_v(v1_pT(p4_T(T), T));
else
Out = fromSIunit_v(v3_ph(p4_T(T), h4L_p(p4_T(T))));
end
else
Out = NaN;
end
Out
end
rhoL_T(t)=1/vL_T(t)
function v_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_v(v1_pT(p, T));
elseif Region == 2
Out = fromSIunit_v(v2_pT(p, T));
elseif Region == 3
Out = fromSIunit_v(v3_ph(p, h3_pT(p, T)));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_v(v5_pT(p, T));
else
Out = NaN;
end
Out
end
rho_pT(p,t)=1/v_pT(p,t)
function v_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Out = fromSIunit_v(v1_pT(p, T1_ph(p, h)));
elseif Region == 2
Out = fromSIunit_v(v2_pT(p, T2_ph(p, h)));
elseif Region == 3
Out = fromSIunit_v(v3_ph(p, h));
elseif Region == 4
xs = x4_ph(p, h);
if p < 16.529
v4v = v2_pT(p, T4_p(p));
v4L = v1_pT(p, T4_p(p));
else
v4v = v3_ph(p, h4V_p(p));
v4L = v3_ph(p, h4L_p(p));
end
Out = fromSIunit_v((xs * v4v + (1 - xs) * v4L));
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_v(v5_pT(p, Ts));
else
Out = NaN;
end
Out
end
rho_ph(p,h)=1/v_ph(p,h)
function v_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Out = fromSIunit_v(v1_pT(p, T1_ps(p, s)));
elseif Region == 2
Out = fromSIunit_v(v2_pT(p, T2_ps(p, s)));
elseif Region == 3
Out = fromSIunit_v(v3_ps(p, s));
elseif Region == 4
xs = x4_ps(p, s);
if p < 16.529
v4v = v2_pT(p, T4_p(p));
v4L = v1_pT(p, T4_p(p));
else
v4v = v3_ph(p, h4V_p(p));
v4L = v3_ph(p, h4L_p(p));
end
Out = fromSIunit_v((xs * v4v + (1 - xs) * v4L));
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_v(v5_pT(p, Ts));
else
Out = NaN;
end
Out
end
rho_ps(p,s)=1/v_ps(p,s)
#***********************************************************************************************************
#*1.6 Density (rho)
# Density is calculated as 1/v. Se section 1.5 Volume
#***********************************************************************************************************
#*1.7 Specific entropy (s)
function sV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_s(s2_pT(p, T4_p(p)));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function sL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_s(s1_pT(p, T4_p(p)));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function sV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_s(s2_pT(p4_T(T), T));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function sL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_s(s1_pT(p4_T(T), T));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function s_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_s(s1_pT(p, T));
elseif Region == 2
Out = fromSIunit_s(s2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_s(s3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_s(s5_pT(p, T));
else
Out = NaN;
end
Out
end
function s_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
T = T1_ph(p, h);
Out = fromSIunit_s(s1_pT(p, T));
elseif Region == 2
T = T2_ph(p, h);
Out = fromSIunit_s(s2_pT(p, T));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_s(s3_rhoT(rhos, Ts));
elseif Region == 4
Ts = T4_p(p);
xs = x4_ph(p, h);
if p < 16.529
s4v = s2_pT(p, Ts);
s4L = s1_pT(p, Ts);
else
v4v = v3_ph(p, h4V_p(p));
s4v = s3_rhoT(1 / v4v, Ts);
v4L = v3_ph(p, h4L_p(p));
s4L = s3_rhoT(1 / v4L, Ts);
end
Out = fromSIunit_s((xs * s4v + (1 - xs) * s4L));
elseif Region == 5
T = T5_ph(p, h);
Out = fromSIunit_s(s5_pT(p, T));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.8 Specific internal energy (u)
function uV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_u(u2_pT(p, T4_p(p)));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function uL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_u(u1_pT(p, T4_p(p)));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function uV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_u(u2_pT(p4_T(T), T));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function uL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_u(u1_pT(p4_T(T), T));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function u_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_u(u1_pT(p, T));
elseif Region == 2
Out = fromSIunit_u(u2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_u(u3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_u(u5_pT(p, T));
else
Out = NaN;
end
Out
end
function u_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_u(u1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_u(u2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_u(u3_rhoT(rhos, Ts));
elseif Region == 4
Ts = T4_p(p);
xs = x4_ph(p, h);
if p < 16.529
u4v = u2_pT(p, Ts);
u4L = u1_pT(p, Ts);
else
v4v = v3_ph(p, h4V_p(p));
u4v = u3_rhoT(1 / v4v, Ts);
v4L = v3_ph(p, h4L_p(p));
u4L = u3_rhoT(1 / v4L, Ts);
end
Out = fromSIunit_u((xs * u4v + (1 - xs) * u4L));
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_u(u5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function u_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_u(u1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_u(u2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_u(u3_rhoT(rhos, Ts));
elseif Region == 4
if p < 16.529
uLp = u1_pT(p, T4_p(p));
uVp = u2_pT(p, T4_p(p));
else
uLp = u3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p));
uVp = u3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p));
end
xs = x4_ps(p, s);
Out = fromSIunit_u((xs * uVp + (1 - xs) * uLp));
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_u(u5_pT(p, Ts));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.9 Specific isobaric heat capacity (Cp)
function CpV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cp(Cp2_pT(p, T4_p(p)));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CpL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cp(Cp1_pT(p, T4_p(p)));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CpV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cp(Cp2_pT(p4_T(T), T));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function CpL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cp(Cp1_pT(p4_T(T), T));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function Cp_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_Cp(Cp1_pT(p, T));
elseif Region == 2
Out = fromSIunit_Cp(Cp2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_Cp(Cp3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_Cp(Cp5_pT(p, T));
else
Out = NaN;
end
Out
end
function Cp_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_Cp(Cp1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_Cp(Cp2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_Cp(Cp3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_Cp(Cp5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function Cp_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_Cp(Cp1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_Cp(Cp2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_Cp(Cp3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_Cp(Cp5_pT(p, Ts));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.10 Specific isochoric heat capacity (Cv)
function CvV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cv(Cv2_pT(p, T4_p(p)));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CvL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cv(Cv1_pT(p, T4_p(p)));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CvV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cv(Cv2_pT(p4_T(T), T));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function CvL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cv(Cv1_pT(p4_T(T), T));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function Cv_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_Cv(Cv1_pT(p, T));
elseif Region == 2
Out = fromSIunit_Cv(Cv2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_Cv(Cv3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_Cv(Cv5_pT(p, T));
else
Out = NaN;
end
Out
end
function Cv_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_Cv(Cv1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_Cv(Cv2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_Cv(Cv3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_Cv(Cv5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function Cv_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_Cv(Cv1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_Cv(Cv2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_Cv(Cv3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN; #(xs * CvVp + (1 - xs) * CvLp) / Cv_scale - Cv_offset
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_Cv(Cv5_pT(p, Ts));
else
#Out = CVErr(xlErrValue);
end
Out
end
#***********************************************************************************************************
#*1.11 Speed of sound
function wV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_w(w2_pT(p, T4_p(p)));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function wL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_w(w1_pT(p, T4_p(p)));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function wV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_w(w2_pT(p4_T(T), T));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function wL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_w(w1_pT(p4_T(T), T));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function w_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_w(w1_pT(p, T));
elseif Region == 2
Out = fromSIunit_w(w2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_w(w3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_w(w5_pT(p, T));
else
Out = NaN;
end
Out
end
function w_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_w(w1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_w(w2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_w(w3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_w(w5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function w_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_w(w1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_w(w2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_w(w3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN; #(xs * wVp + (1 - xs) * wLp) / w_scale - w_offset
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_w(w5_pT(p, Ts));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.12 Viscosity
function my_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 4
Out = NaN;
elseif Region in [1,2,3,5]
Out = fromSIunit_my(my_AllRegions_pT(p, T));
else
Out = NaN;
end
Out
end
function my_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region in [1, 2, 3, 5]
Out = fromSIunit_my(my_AllRegions_ph(p, h));
elseif Region == 4
Out = NaN;
else
Out = NaN;
end
Out
end
function my_ps(p,s)
h = h_ps(p,s);
Out = my_ph(p,h);
Out
end
#***********************************************************************************************************
#*1.13 Prandtl
function pr_pT(p,t)
Cp = toSIunit_Cp(Cp_pT(p,t));
my = toSIunit_my(my_pT(p,t));
tc = toSIunit_tc(tc_pT(p,t));
Out = Cp * 1000 * my / tc;
Out
end
function pr_ph(p,h)
Cp = toSIunit_Cp(Cp_ph(p, h));
my = toSIunit_my(my_ph(p,h));
tc = toSIunit_tc(tc_ph(p,h));
Out = Cp * 1000 * my / tc;
Out
end
#***********************************************************************************************************
#*1.14 Kappa
#***********************************************************************************************************
#***********************************************************************************************************
#*1.15 Surface tension
function st_T(t)
T = toSIunit_T(t);
Out = fromSIunit_st(Surface_Tension_T(T));
Out
end
function st_p(p)
T = Tsat_p(p);
T = toSIunit_T(T);
Out = fromSIunit_st(Surface_Tension_T(T));
Out
end
#***********************************************************************************************************
#*1.16 Thermal conductivity
function tcL_p(p)
T = Tsat_p(p);
v = vL_p(p);
p = toSIunit_p(p);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tcV_p(p)
ps = p;
T = Tsat_p(ps);
v = vV_p(ps);
p = toSIunit_p(p);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tcL_T(t)
Ts = t;
p = psat_T(Ts);
v = vL_T(Ts);
p = toSIunit_p(p);
T = toSIunit_T(Ts);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tcV_T(t)
Ts = t;
p = psat_T(Ts);
v = vV_T(Ts);
p = toSIunit_p(p);
T = toSIunit_T(Ts);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tc_pT(p,t)
Ts = t;
ps = p;
v = v_pT(ps, Ts);
p = toSIunit_p(ps);
T = toSIunit_T(Ts);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tc_ph(p,h)
hs = h;
ps = p;
v = v_ph(ps, hs);
T = T_ph(ps, hs);
p = toSIunit_p(ps);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tc_hs(h,s)
hs = h;
p = p_hs(hs, s);
ps = p;
v = v_ph(ps, hs);
T = T_ph(ps, hs);
p = toSIunit_p(p);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
#***********************************************************************************************************
#*1.17 Vapour fraction
function x_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_x(x4_ph(p, h));
else
Out = NaN;
end
Out
end
function x_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_x(x4_ps(p, s));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.18 Vapour Volume Fraction
function vx_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
if p > 0.000611657 && p < 22.06395
if p < 16.529
vL = v1_pT(p, T4_p(p));
vV = v2_pT(p, T4_p(p));
else
vL = v3_ph(p, h4L_p(p));
vV = v3_ph(p, h4V_p(p));
end
xs = x4_ph(p, h);
Out = fromSIunit_vx((xs * vV / (xs * vV + (1 - xs) * vL)));
else
Out = NaN;
end
Out
end
function vx_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
if p > 0.000611657 && p < 22.06395
if p < 16.529
vL = v1_pT(p, T4_p(p));
vV = v2_pT(p, T4_p(p));
else
vL = v3_ph(p, h4L_p(p));
vV = v3_ph(p, h4V_p(p));
end
xs = x4_ps(p, s);
Out = fromSIunit_vx((xs * vV / (xs * vV + (1 - xs) * vL)));
else
Out = NaN;
end
Out
end
function check()
err=check();
err
end
#***********************************************************************************************************
#*2 IAPWS IF 97 Calling functions *
#***********************************************************************************************************
#
#***********************************************************************************************************
#*2.1 Functions for region 1
function v1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_pi = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i]- 1) * (tau - 1.222) ^ J1[i];
end
v1_pT = R * T / p * Pi * gamma_der_pi / 1000;
v1_pT
end
function h1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_tau = 0;
for i = 1 : 34
gamma_der_tau = gamma_der_tau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i]* (tau - 1.222) ^ (J1[i] - 1));
end
h1_pT = R * T * tau * gamma_der_tau;
h1_pT
end
function u1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_tau = 0;
gamma_der_pi = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * (tau - 1.222) ^ J1[i];
gamma_der_tau = gamma_der_tau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (tau - 1.222) ^ (J1[i] - 1));
end
u1_pT = R * T * (tau * gamma_der_tau - Pi * gamma_der_pi);
u1_pT
end
function s1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma = 0;
gamma_der_tau = 0;
for i = 1 : 34
gamma_der_tau = gamma_der_tau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (tau - 1.222) ^ (J1[i] - 1));
gamma = gamma + n1[i] * (7.1 - Pi) ^ I1[i] * (tau - 1.222) ^ J1[i];
end
s1_pT = R * tau * gamma_der_tau - R * gamma;
s1_pT
end
function Cp1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_tautau = 0;
for i = 1 :34
gamma_der_tautau = gamma_der_tautau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (J1[i] - 1) * (tau - 1.222) ^ (J1[i] - 2));
end
Cp1_pT = -R * tau ^ 2 * gamma_der_tautau;
Cp1_pT
end
function Cv1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_pi = 0;
gamma_der_pipi = 0;
gamma_der_pitau = 0;
gamma_der_tautau = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * (tau - 1.222) ^ J1[i];
gamma_der_pipi = gamma_der_pipi + n1[i] * I1[i] * (I1[i] - 1) * (7.1 - Pi) ^ (I1[i] - 2) * (tau - 1.222) ^ J1[i];
gamma_der_pitau = gamma_der_pitau - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * J1[i] * (tau - 1.222) ^ (J1[i] - 1);
gamma_der_tautau = gamma_der_tautau + n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (J1[i] - 1) * (tau - 1.222) ^ (J1[i] - 2);
end
Cv1_pT = R * (-tau ^ 2 * gamma_der_tautau + (gamma_der_pi - tau * gamma_der_pitau) ^ 2 / gamma_der_pipi);
Cv1_pT
end
function w1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_pi = 0;
gamma_der_pipi = 0;
gamma_der_pitau = 0;
gamma_der_tautau = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * (tau - 1.222) ^ J1[i];
gamma_der_pipi = gamma_der_pipi + n1[i] * I1[i] * (I1[i] - 1) * (7.1 - Pi) ^ (I1[i] - 2) * (tau - 1.222) ^ J1[i];
gamma_der_pitau = gamma_der_pitau - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * J1[i] * (tau - 1.222) ^ (J1[i] - 1);
gamma_der_tautau = gamma_der_tautau + n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (J1[i] - 1) * (tau - 1.222) ^ (J1[i] - 2);
end
w1_pT = (1000 * R * T * gamma_der_pi ^ 2 / ((gamma_der_pi - tau * gamma_der_pitau) ^ 2 / (tau ^ 2 * gamma_der_tautau) - gamma_der_pipi)) ^ 0.5;
w1_pT
end
function T1_ph(p, h)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation, 5.2.1 The Backward Equation T ( p,h )
#Eqution 11, Table 6, Page 10
I1 = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6];
J1 = [0, 1, 2, 6, 22, 32, 0, 1, 2, 3, 4, 10, 32, 10, 32, 10, 32, 32, 32, 32];
n1 = [-238.72489924521, 404.21188637945, 113.49746881718, -5.8457616048039, -1.528548241314E-04, -1.0866707695377E-06, -13.391744872602, 43.211039183559, -54.010067170506, 30.535892203916, -6.5964749423638, 9.3965400878363E-03, 1.157364750534E-07, -2.5858641282073E-05, -4.0644363084799E-09, 6.6456186191635E-08, 8.0670734103027E-11, -9.3477771213947E-13, 5.8265442020601E-15, -1.5020185953503E-17];
Pi = p / 1;
eta = h / 2500;
T = 0;
for i = 1 : 20
T = T + n1[i] * Pi ^ I1[i] * (eta + 1) ^ J1[i];
end
T1_ph = T;
T1_ph
end
function T1_ps(p, s)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation, 5.2.2 The Backward Equation T ( p, s )
#Eqution 13, Table 8, Page 11
I1 = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4];
J1 = [0, 1, 2, 3, 11, 31, 0, 1, 2, 3, 12, 31, 0, 1, 2, 9, 31, 10, 32, 32];
n1 = [174.78268058307, 34.806930892873, 6.5292584978455, 0.33039981775489, -1.9281382923196E-07, -2.4909197244573E-23, -0.26107636489332, 0.22592965981586, -0.064256463395226, 7.8876289270526E-03, 3.5672110607366E-10, 1.7332496994895E-24, 5.6608900654837E-04, -3.2635483139717E-04, 4.4778286690632E-05, -5.1322156908507E-10, -4.2522657042207E-26, 2.6400441360689E-13, 7.8124600459723E-29, -3.0732199903668E-31];
Pi = p / 1;
Sigma = s / 1;
T = 0;
for i = 1 : 20
T = T + n1[i] * Pi ^ I1[i] * (Sigma + 2) ^ J1[i];
end
T1_ps = T;
T1_ps
end
function p1_hs(h, s)
#Supplementary Release on Backward Equations for Pressure as a Function of Enthalpy and Entropy p(h,s) to the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#5 Backward Equation p(h,s) for Region 1
#Eqution 1, Table 2, Page 5
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5];
J1 = [0, 1, 2, 4, 5, 6, 8, 14, 0, 1, 4, 6, 0, 1, 10, 4, 1, 4, 0];
n1 = [-0.691997014660582, -18.361254878756, -9.28332409297335, 65.9639569909906, -16.2060388912024, 450.620017338667, 854.68067822417, 6075.23214001162, 32.6487682621856, -26.9408844582931, -319.9478483343, -928.35430704332, 30.3634537455249, -65.0540422444146, -4309.9131651613, -747.512324096068, 730.000345529245, 1142.84032569021, -436.407041874559];
eta = h / 3400;
Sigma = s / 7.6;
p = 0;
for i = 1 : 19
p = p + n1[i] * (eta + 0.05) ^ I1[i] * (Sigma + 0.05) ^ J1[i];
end
p1_hs = p * 100;
p1_hs
end
function T1_prho(p ,rho)
#Solve by iteration. Observe that for low temperatures this equation has 2 solutions.
#Solve with half interval method
Low_Bound = 273.15;
High_Bound = T4_p(p);
rhos=-1000;
Ts =0.0
while abs(rho - rhos) > 0.00001
Ts = (Low_Bound + High_Bound) / 2;
rhos = 1 / v1_pT(p, Ts);
if rhos < rho
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T1_prho = Ts;
T1_prho
end
#***********************************************************************************************************
#*2.2 functions for region 2
function v2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_pi = 1 / Pi;
gr_pi = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
end
v2_pT = R * T / p * Pi * (g0_pi + gr_pi) / 1000;
v2_pT
end
function h2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tau = 0;
for i = 1 : 9
g0_tau = g0_tau + n0[i] * J0[i] * tau ^ (J0[i] - 1);
end
gr_tau = 0;
for i = 1 : 43
gr_tau = gr_tau + nr[i] * Pi ^ Ir[i] * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
end
h2_pT = R * T * tau * (g0_tau + gr_tau);
h2_pT
end
function u2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_pi = 1 / Pi;
g0_tau = 0;
for i = 1 : 9
g0_tau = g0_tau + n0[i] * J0[i] * tau ^ (J0[i] - 1);
end
gr_pi = 0;
gr_tau = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
gr_tau = gr_tau + nr[i] * Pi ^ Ir[i] * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
end
u2_pT = R * T * (tau * (g0_tau + gr_tau) - Pi * (g0_pi + gr_pi));
u2_pT
end
function s2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0 = log(Pi);
g0_tau = 0;
for i = 1 : 9
g0 = g0 + n0[i] * tau ^ J0[i];
g0_tau = g0_tau + n0[i] * J0[i] * tau ^ (J0[i] - 1);
end
gr = 0;
gr_tau = 0;
for i = 1 : 43
gr = gr + nr[i] * Pi ^ Ir[i] * (tau - 0.5) ^ Jr[i];
gr_tau = gr_tau + nr[i] * Pi ^ Ir[i] * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
end
s2_pT = R * (tau * (g0_tau + gr_tau) - (g0 + gr));
s2_pT
end
function Cp2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tautau = 0;
for i = 1 : 9
g0_tautau = g0_tautau + n0[i] * J0[i] * (J0[i] - 1) * tau ^ (J0[i] - 2);
end
gr_tautau = 0;
for i = 1 : 43
gr_tautau = gr_tautau + nr[i] * Pi ^ Ir[i] * Jr[i] * (Jr[i] - 1) * (tau - 0.5) ^ (Jr[i] - 2);
end
Cp2_pT = -R * tau ^ 2 * (g0_tautau + gr_tautau);
Cp2_pT
end
function Cv2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tautau = 0;
for i = 1 : 9
g0_tautau = g0_tautau + n0[i] * J0[i] * (J0[i] - 1) * tau ^ (J0[i] - 2);
end
gr_pi = 0;
gr_pitau = 0;
gr_pipi = 0;
gr_tautau = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
gr_pipi = gr_pipi + nr[i] * Ir[i] * (Ir[i] - 1) * Pi ^ (Ir[i] - 2) * (tau - 0.5) ^ Jr[i];
gr_pitau = gr_pitau + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
gr_tautau = gr_tautau + nr[i] * Pi ^ Ir[i] * Jr[i] * (Jr[i] - 1) * (tau - 0.5) ^ (Jr[i] - 2);
end
Cv2_pT = R * (-tau ^ 2 * (g0_tautau + gr_tautau) - (1 + Pi * gr_pi - tau * Pi * gr_pitau) ^ 2 / (1 - Pi ^ 2 * gr_pipi));
Cv2_pT
end
function w2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tautau = 0;
for i = 1 : 9
g0_tautau = g0_tautau + n0[i] * J0[i] * (J0[i] - 1) * tau ^ (J0[i] - 2);
end
gr_pi = 0;
gr_pitau = 0;
gr_pipi = 0;
gr_tautau = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
gr_pipi = gr_pipi + nr[i] * Ir[i] * (Ir[i] - 1) * Pi ^ (Ir[i] - 2) * (tau - 0.5) ^ Jr[i];
gr_pitau = gr_pitau + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
gr_tautau = gr_tautau + nr[i] * Pi ^ Ir[i] * Jr[i] * (Jr[i] - 1) * (tau - 0.5) ^ (Jr[i] - 2);
end
w2_pT = (1000 * R * T * (1 + 2 * Pi * gr_pi + Pi ^ 2 * gr_pi ^ 2) / ((1 - Pi ^ 2 * gr_pipi) + (1 + Pi * gr_pi - tau * Pi * gr_pitau) ^ 2 / (tau ^ 2 * (g0_tautau + gr_tautau)))) ^ 0.5;
w2_pT
end
function T2_ph(p, h)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2,6.3.1 The Backward Equations T( p, h ) for Subregions 2a, 2b, and 2c
if p < 4
sub_reg = 1;
else
if p < (905.84278514723 - 0.67955786399241 * h + 1.2809002730136E-04 * h ^ 2)
sub_reg = 2;
else
sub_reg = 3;
end
end
if sub_reg == 1
#Subregion A
#Table 20, Eq 22, page 22
Ji = [0, 1, 2, 3, 7, 20, 0, 1, 2, 3, 7, 9, 11, 18, 44, 0, 2, 7, 36, 38, 40, 42, 44, 24, 44, 12, 32, 44, 32, 36, 42, 34, 44, 28];
Ii = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7];
ni = [1089.8952318288, 849.51654495535, -107.81748091826, 33.153654801263, -7.4232016790248, 11.765048724356, 1.844574935579, -4.1792700549624, 6.2478196935812, -17.344563108114, -200.58176862096, 271.96065473796, -455.11318285818, 3091.9688604755, 252266.40357872, -6.1707422868339E-03, -0.31078046629583, 11.670873077107, 128127984.04046, -985549096.23276, 2822454697.3002, -3594897141.0703, 1722734991.3197, -13551.334240775, 12848734.66465, 1.3865724283226, 235988.32556514, -13105236.545054, 7399.9835474766, -551966.9703006, 3715408.5996233, 19127.72923966, -415351.64835634, -62.459855192507];
Ts = 0;
hs = h / 2000;
for i = 1 : 34
Ts = Ts + ni[i] * p ^ (Ii[i]) * (hs - 2.1) ^ Ji[i];
end
T2_ph = Ts;
elseif sub_reg == 2
#Subregion B
#Table 21, Eq 23, page 23
Ji = [0, 1, 2, 12, 18, 24, 28, 40, 0, 2, 6, 12, 18, 24, 28, 40, 2, 8, 18, 40, 1, 2, 12, 24, 2, 12, 18, 24, 28, 40, 18, 24, 40, 28, 2, 28, 1, 40];
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 6, 7, 7, 9, 9];
ni = [1489.5041079516, 743.07798314034, -97.708318797837, 2.4742464705674, -0.63281320016026, 1.1385952129658, -0.47811863648625, 8.5208123431544E-03, 0.93747147377932, 3.3593118604916, 3.3809355601454, 0.16844539671904, 0.73875745236695, -0.47128737436186, 0.15020273139707, -0.002176411421975, -0.021810755324761, -0.10829784403677, -0.046333324635812, 7.1280351959551E-05, 1.1032831789999E-04, 1.8955248387902E-04, 3.0891541160537E-03, 1.3555504554949E-03, 2.8640237477456E-07, -1.0779857357512E-05, -7.6462712454814E-05, 1.4052392818316E-05, -3.1083814331434E-05, -1.0302738212103E-06, 2.821728163504E-07, 1.2704902271945E-06, 7.3803353468292E-08, -1.1030139238909E-08, -8.1456365207833E-14, -2.5180545682962E-11, -1.7565233969407E-18, 8.6934156344163E-15];
Ts = 0;
hs = h / 2000;
for i = 1 : 38
Ts = Ts + ni[i] * (p - 2) ^ (Ii[i]) * (hs - 2.6) ^ Ji[i];
end
T2_ph = Ts;
else
#Subregion C
#Table 22, Eq 24, page 24
Ji = [0, 4, 0, 2, 0, 2, 0, 1, 0, 2, 0, 1, 4, 8, 4, 0, 1, 4, 10, 12, 16, 20, 22];
Ii = [-7, -7, -6, -6, -5, -5, -2, -2, -1, -1, 0, 0, 1, 1, 2, 6, 6, 6, 6, 6, 6, 6, 6];
ni = [-3236839855524.2, 7326335090218.1, 358250899454.47, -583401318515.9, -10783068217.47, 20825544563.171, 610747.83564516, 859777.2253558, -25745.72360417, 31081.088422714, 1208.2315865936, 482.19755109255, 3.7966001272486, -10.842984880077, -0.04536417267666, 1.4559115658698E-13, 1.126159740723E-12, -1.7804982240686E-11, 1.2324579690832E-07, -1.1606921130984E-06, 2.7846367088554E-05, -5.9270038474176E-04, 1.2918582991878E-03];
Ts = 0;
hs = h / 2000;
for i = 1 : 23
Ts = Ts + ni[i] * (p + 25) ^ (Ii[i]) * (hs - 1.8) ^ Ji[i];
end
T2_ph = Ts;
end
T2_ph
end
function T2_ps(p, s)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2,6.3.2 The Backward Equations T( p, s ) for Subregions 2a, 2b, and 2c
#Page 26
if p < 4
sub_reg = 1;
else
if s < 5.85
sub_reg = 3;
else
sub_reg = 2;
end
end
if sub_reg == 1
#Subregion A
#Table 25, Eq 25, page 26
Ii = [-1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.25, -1.25, -1.25, -1, -1, -1, -1, -1, -1, -0.75, -0.75, -0.5, -0.5, -0.5, -0.5, -0.25, -0.25, -0.25, -0.25, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.75, 0.75, 0.75, 0.75, 1, 1, 1.25, 1.25, 1.5, 1.5];
Ji = [-24, -23, -19, -13, -11, -10, -19, -15, -6, -26, -21, -17, -16, -9, -8, -15, -14, -26, -13, -9, -7, -27, -25, -11, -6, 1, 4, 8, 11, 0, 1, 5, 6, 10, 14, 16, 0, 4, 9, 17, 7, 18, 3, 15, 5, 18];
ni = [-392359.83861984, 515265.7382727, 40482.443161048, -321.93790923902, 96.961424218694, -22.867846371773, -449429.14124357, -5011.8336020166, 0.35684463560015, 44235.33584819, -13673.388811708, 421632.60207864, 22516.925837475, 474.42144865646, -149.31130797647, -197811.26320452, -23554.39947076, -19070.616302076, 55375.669883164, 3829.3691437363, -603.91860580567, 1936.3102620331, 4266.064369861, -5978.0638872718, -704.01463926862, 338.36784107553, 20.862786635187, 0.033834172656196, -4.3124428414893E-05, 166.53791356412, -139.86292055898, -0.78849547999872, 0.072132411753872, -5.9754839398283E-03, -1.2141358953904E-05, 2.3227096733871E-07, -10.538463566194, 2.0718925496502, -0.072193155260427, 2.074988708112E-07, -0.018340657911379, 2.9036272348696E-07, 0.21037527893619, 2.5681239729999E-04, -0.012799002933781, -8.2198102652018E-06];
Pi = p;
Sigma = s / 2;
teta = 0;
for i = 1 : 46
teta = teta + ni[i] * Pi ^ Ii[i] * (Sigma - 2) ^ Ji[i];
end
T2_ps = teta;
elseif sub_reg == 2
#Subregion B
#Table 26, Eq 26, page 27
Ii = [-6, -6, -5, -5, -4, -4, -4, -3, -3, -3, -3, -2, -2, -2, -2, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5];
Ji = [0, 11, 0, 11, 0, 1, 11, 0, 1, 11, 12, 0, 1, 6, 10, 0, 1, 5, 8, 9, 0, 1, 2, 4, 5, 6, 9, 0, 1, 2, 3, 7, 8, 0, 1, 5, 0, 1, 3, 0, 1, 0, 1, 2];
ni = [316876.65083497, 20.864175881858, -398593.99803599, -21.816058518877, 223697.85194242, -2784.1703445817, 9.920743607148, -75197.512299157, 2970.8605951158, -3.4406878548526, 0.38815564249115, 17511.29508575, -1423.7112854449, 1.0943803364167, 0.89971619308495, -3375.9740098958, 471.62885818355, -1.9188241993679, 0.41078580492196, -0.33465378172097, 1387.0034777505, -406.63326195838, 41.72734715961, 2.1932549434532, -1.0320050009077, 0.35882943516703, 5.2511453726066E-03, 12.838916450705, -2.8642437219381, 0.56912683664855, -0.099962954584931, -3.2632037778459E-03, 2.3320922576723E-04, -0.1533480985745, 0.029072288239902, 3.7534702741167E-04, 1.7296691702411E-03, -3.8556050844504E-04, -3.5017712292608E-05, -1.4566393631492E-05, 5.6420857267269E-06, 4.1286150074605E-08, -2.0684671118824E-08, 1.6409393674725E-09];
Pi = p;
Sigma = s / 0.7853;
teta = 0;
for i = 1 : 44
teta = teta + ni[i] * Pi ^ Ii[i] * (10 - Sigma) ^ Ji[i];
end
T2_ps = teta;
else
#Subregion C
#Table 27, Eq 27, page 28
Ii = [-2, -2, -1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7, 7];
Ji = [0, 1, 0, 0, 1, 2, 3, 0, 1, 3, 4, 0, 1, 2, 0, 1, 5, 0, 1, 4, 0, 1, 2, 0, 1, 0, 1, 3, 4, 5];
ni = [909.68501005365, 2404.566708842, -591.6232638713, 541.45404128074, -270.98308411192, 979.76525097926, -469.66772959435, 14.399274604723, -19.104204230429, 5.3299167111971, -21.252975375934, -0.3114733441376, 0.60334840894623, -0.042764839702509, 5.8185597255259E-03, -0.014597008284753, 5.6631175631027E-03, -7.6155864584577E-05, 2.2440342919332E-04, -1.2561095013413E-05, 6.3323132660934E-07, -2.0541989675375E-06, 3.6405370390082E-08, -2.9759897789215E-09, 1.0136618529763E-08, 5.9925719692351E-12, -2.0677870105164E-11, -2.0874278181886E-11, 1.0162166825089E-10, -1.6429828281347E-10];
Pi = p;
Sigma = s / 2.9251;
teta = 0;
for i = 1 : 30
teta = teta + ni[i] * Pi ^ Ii[i] * (2 - Sigma) ^ Ji[i];
end
T2_ps = teta;
end
T2_ps
end
function p2_hs(h, s)
#Supplementary Release on Backward Equations for Pressure as a function of Enthalpy and Entropy p(h,s) to the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#Chapter 6:Backward Equations p(h,s) for Region 2
if h < (-3498.98083432139 + 2575.60716905876 * s - 421.073558227969 * s ^ 2 + 27.6349063799944 * s ^ 3)
sub_reg = 1;
else
if s < 5.85
sub_reg = 3;
else
sub_reg = 2;
end
end
if sub_reg == 1
#Subregion A
#Table 6, Eq 3, page 8
Ii = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 5, 5, 6, 7];
Ji = [1, 3, 6, 16, 20, 22, 0, 1, 2, 3, 5, 6, 10, 16, 20, 22, 3, 16, 20, 0, 2, 3, 6, 16, 16, 3, 16, 3, 1];
ni = [-1.82575361923032E-02, -0.125229548799536, 0.592290437320145, 6.04769706185122, 238.624965444474, -298.639090222922, 0.051225081304075, -0.437266515606486, 0.413336902999504, -5.16468254574773, -5.57014838445711, 12.8555037824478, 11.414410895329, -119.504225652714, -2847.7798596156, 4317.57846408006, 1.1289404080265, 1974.09186206319, 1516.12444706087, 1.41324451421235E-02, 0.585501282219601, -2.97258075863012, 5.94567314847319, -6236.56565798905, 9659.86235133332, 6.81500934948134, -6332.07286824489, -5.5891922446576, 4.00645798472063E-02];
eta = h / 4200;
Sigma = s / 12;
Pi = 0;
for i = 1 : 29
Pi = Pi + ni[i] * (eta - 0.5) ^ Ii[i] * (Sigma - 1.2) ^ Ji[i];
end
p2_hs = Pi ^ 4 * 4;
elseif sub_reg == 2
#Subregion B
#Table 7, Eq 4, page 9
Ii = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8, 8, 12, 14];
Ji = [0, 1, 2, 4, 8, 0, 1, 2, 3, 5, 12, 1, 6, 18, 0, 1, 7, 12, 1, 16, 1, 12, 1, 8, 18, 1, 16, 1, 3, 14, 18, 10, 16];
ni = [8.01496989929495E-02, -0.543862807146111, 0.337455597421283, 8.9055545115745, 313.840736431485, 0.797367065977789, -1.2161697355624, 8.72803386937477, -16.9769781757602, -186.552827328416, 95115.9274344237, -18.9168510120494, -4334.0703719484, 543212633.012715, 0.144793408386013, 128.024559637516, -67230.9534071268, 33697238.0095287, -586.63419676272, -22140322476.9889, 1716.06668708389, -570817595.806302, -3121.09693178482, -2078413.8463301, 3056059461577.86, 3221.57004314333, 326810259797.295, -1441.04158934487, 410.694867802691, 109077066873.024, -24796465425889.3, 1888019068.65134, -123651009018773];
eta = h / 4100;
Sigma = s / 7.9;
Pi = 0;
for i = 1 : 33
Pi = Pi + ni[i] * (eta - 0.6) ^ Ii[i] * (Sigma - 1.01) ^ Ji[i];
end
p2_hs = Pi ^ 4 * 100;
else
#Subregion C
#Table 8, Eq 5, page 10
Ii = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 10, 12, 16];
Ji = [0, 1, 2, 3, 4, 8, 0, 2, 5, 8, 14, 2, 3, 7, 10, 18, 0, 5, 8, 16, 18, 18, 1, 4, 6, 14, 8, 18, 7, 7, 10];
ni = [0.112225607199012, -3.39005953606712, -32.0503911730094, -197.5973051049, -407.693861553446, 13294.3775222331, 1.70846839774007, 37.3694198142245, 3581.44365815434, 423014.446424664, -751071025.760063, 52.3446127607898, -228.351290812417, -960652.417056937, -80705929.2526074, 1626980172256.69, 0.772465073604171, 46392.9973837746, -13731788.5134128, 1704703926305.12, -25110462818730.8, 31774883083552, 53.8685623675312, -55308.9094625169, -1028615.22421405, 2042494187562.34, 273918446.626977, -2.63963146312685E+15, -1078908541.08088, -29649262098.0124, -1.11754907323424E+15];
eta = h / 3500;
Sigma = s / 5.9;
Pi = 0;
for i = 1 : 31
Pi = Pi + ni[i] * (eta - 0.7) ^ Ii[i] * (Sigma - 1.1) ^ Ji[i];
end
p2_hs = Pi ^ 4 * 100;
end
p2_hs
end
function T2_prho(p,rho)
#Solve by iteration. Observe that fo low temperatures this equation has 2 solutions.
#Solve with half interval method
if p < 16.5292
Low_Bound = T4_p(p);
else
Low_Bound = B23T_p(p);
end
High_Bound = 1073.15;
rhos=-1000;
Ts=0.0
while abs(rho - rhos) > 0.000001
Ts = (Low_Bound + High_Bound) / 2;
rhos = 1 / v2_pT(p, Ts);
if rhos < rho
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T2_prho = Ts;
T2_prho
end
#***********************************************************************************************************
#*2.3 functions for region 3
function p3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fidelta = 0;
for i = 2 : 40
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
end
fidelta = fidelta + ni(1) / delta;
p3_rhoT = rho * R * T * delta * fidelta / 1000;
p3_rhoT
end
function u3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitau = 0;
for i = 2 : 40
fitau = fitau + ni[i] * delta ^ Ii[i] * Ji[i] * tau ^ (Ji[i] - 1);
end
u3_rhoT = R * T * (tau * fitau);
u3_rhoT
end
function h3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fidelta = 0;
fitau = 0;
for i = 2 : 40
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
fitau = fitau + ni[i] * delta ^ Ii[i] * Ji[i] * tau ^ (Ji[i] - 1);
end
fidelta = fidelta + ni(1) / delta;
h3_rhoT = R * T * (tau * fitau + delta * fidelta);
h3_rhoT
end
function s3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fi = 0;
fitau = 0;
for i = 2 : 40
fi = fi + ni[i] * delta ^ Ii[i] * tau ^ Ji[i];
fitau = fitau + ni[i] * delta ^ Ii[i] * Ji[i] * tau ^ (Ji[i] - 1);
end
fi = fi + ni(1) * log(delta);
s3_rhoT = R * (tau * fitau - fi);
s3_rhoT
end
function Cp3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitautau = 0;
fidelta = 0;
fideltatau = 0;
fideltadelta = 0;
for i = 2 : 40
fitautau = fitautau + ni[i] * delta ^ Ii[i] * Ji[i] * (Ji[i] - 1) * tau ^ (Ji[i] - 2);
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
fideltatau = fideltatau + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * Ji[i] * tau ^ (Ji[i] - 1);
fideltadelta = fideltadelta + ni[i] * Ii[i] * (Ii[i] - 1) * delta ^ (Ii[i] - 2) * tau ^ Ji[i];
end
fidelta = fidelta + ni(1) / delta;
fideltadelta = fideltadelta - ni(1) / (delta ^ 2);
Cp3_rhoT = R * (-tau ^ 2 * fitautau + (delta * fidelta - delta * tau * fideltatau) ^ 2 / (2 * delta * fidelta + delta ^ 2 * fideltadelta));
Cp3_rhoT
end
function Cv3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitautau = 0;
for i = 1 : 40
fitautau = fitautau + ni[i] * delta ^ Ii[i] * Ji[i] * (Ji[i] - 1) * tau ^ (Ji[i] - 2);
end
Cv3_rhoT = R * -(tau * tau * fitautau);
Cv3_rhoT
end
function w3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitautau = 0;
fidelta = 0;
fideltatau = 0;
fideltadelta = 0;
for i = 2 : 40
fitautau = fitautau + ni[i] * delta ^ Ii[i] * Ji[i] * (Ji[i] - 1) * tau ^ (Ji[i] - 2);
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
fideltatau = fideltatau + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * Ji[i] * tau ^ (Ji[i] - 1);
fideltadelta = fideltadelta + ni[i] * Ii[i] * (Ii[i] - 1) * delta ^ (Ii[i] - 2) * tau ^ Ji[i];
end
fidelta = fidelta + ni(1) / delta;
fideltadelta = fideltadelta - ni(1) / (delta ^ 2);
w3_rhoT = (1000 * R * T * (2 * delta * fidelta + delta ^ 2 * fideltadelta - (delta * fidelta - delta * tau * fideltatau) ^ 2 / (tau ^ 2 * fitautau))) ^ 0.5;
w3_rhoT
end
function T3_ph(p, h)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#Section 3.3 Backward Equations T(p,h) and v(p,h) for Subregions 3a and 3b
#Boundary equation, Eq 1 Page 5
h3ab = 2014.64004206875 + 3.74696550136983 * p - 2.19921901054187E-02 * p ^ 2 + 8.7513168600995E-05 * p ^ 3;
if h < h3ab
#Subregion 3a
#Eq 2, Table 3, Page 7
Ii = [-12, -12, -12, -12, -12, -12, -12, -12, -10, -10, -10, -8, -8, -8, -8, -5, -3, -2, -2, -2, -1, -1, 0, 0, 1, 3, 3, 4, 4, 10, 12];
Ji = [0, 1, 2, 6, 14, 16, 20, 22, 1, 5, 12, 0, 2, 4, 10, 2, 0, 1, 3, 4, 0, 2, 0, 1, 1, 0, 1, 0, 3, 4, 5];
ni = [-1.33645667811215E-07, 4.55912656802978E-06, -1.46294640700979E-05, 6.3934131297008E-03, 372.783927268847, -7186.54377460447, 573494.7521034, -2675693.29111439, -3.34066283302614E-05, -2.45479214069597E-02, 47.8087847764996, 7.64664131818904E-06, 1.28350627676972E-03, 1.71219081377331E-02, -8.51007304583213, -1.36513461629781E-02, -3.84460997596657E-06, 3.37423807911655E-03, -0.551624873066791, 0.72920227710747, -9.92522757376041E-03, -0.119308831407288, 0.793929190615421, 0.454270731799386, 0.20999859125991, -6.42109823904738E-03, -0.023515586860454, 2.52233108341612E-03, -7.64885133368119E-03, 1.36176427574291E-02, -1.33027883575669E-02];
ps = p / 100;
hs = h / 2300;
Ts = 0;
for i = 1 : 31
Ts = Ts + ni[i] * (ps + 0.24) ^ Ii[i] * (hs - 0.615) ^ Ji[i];
end
T3_ph = Ts * 760;
else
#Subregion 3b
#Eq 3, Table 4, Page 7,8
Ii = [-12, -12, -10, -10, -10, -10, -10, -8, -8, -8, -8, -8, -6, -6, -6, -4, -4, -3, -2, -2, -1, -1, -1, -1, -1, -1, 0, 0, 1, 3, 5, 6, 8];
Ji = [0, 1, 0, 1, 5, 10, 12, 0, 1, 2, 4, 10, 0, 1, 2, 0, 1, 5, 0, 4, 2, 4, 6, 10, 14, 16, 0, 2, 1, 1, 1, 1, 1];
ni = [3.2325457364492E-05, -1.27575556587181E-04, -4.75851877356068E-04, 1.56183014181602E-03, 0.105724860113781, -85.8514221132534, 724.140095480911, 2.96475810273257E-03, -5.92721983365988E-03, -1.26305422818666E-02, -0.115716196364853, 84.9000969739595, -1.08602260086615E-02, 1.54304475328851E-02, 7.50455441524466E-02, 2.52520973612982E-02, -6.02507901232996E-02, -3.07622221350501, -5.74011959864879E-02, 5.03471360939849, -0.925081888584834, 3.91733882917546, -77.314600713019, 9493.08762098587, -1410437.19679409, 8491662.30819026, 0.861095729446704, 0.32334644281172, 0.873281936020439, -0.436653048526683, 0.286596714529479, -0.131778331276228, 6.76682064330275E-03];
hs = h / 2800;
ps = p / 100;
Ts = 0;
for i = 1 : 33
Ts = Ts + ni[i] * (ps + 0.298) ^ Ii[i] * (hs - 0.72) ^ Ji[i];
end
T3_ph = Ts * 860;
end
T3_ph
end
function v3_ph(p, h)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#Section 3.3 Backward Equations T(p,h) and v(p,h) for Subregions 3a and 3b
#Boundary equation, Eq 1 Page 5
h3ab = 2014.64004206875 + 3.74696550136983 * p - 2.19921901054187E-02 * p ^ 2 + 8.7513168600995E-05 * p ^ 3;
if h < h3ab
#Subregion 3a
#Eq 4, Table 6, Page 9
Ii = [-12, -12, -12, -12, -10, -10, -10, -8, -8, -6, -6, -6, -4, -4, -3, -2, -2, -1, -1, -1, -1, 0, 0, 1, 1, 1, 2, 2, 3, 4, 5, 8];
Ji = [6, 8, 12, 18, 4, 7, 10, 5, 12, 3, 4, 22, 2, 3, 7, 3, 16, 0, 1, 2, 3, 0, 1, 0, 1, 2, 0, 2, 0, 2, 2, 2];
ni = [5.29944062966028E-03, -0.170099690234461, 11.1323814312927, -2178.98123145125, -5.06061827980875E-04, 0.556495239685324, -9.43672726094016, -0.297856807561527, 93.9353943717186, 1.92944939465981E-02, 0.421740664704763, -3689141.2628233, -7.37566847600639E-03, -0.354753242424366, -1.99768169338727, 1.15456297059049, 5683.6687581596, 8.08169540124668E-03, 0.172416341519307, 1.04270175292927, -0.297691372792847, 0.560394465163593, 0.275234661176914, -0.148347894866012, -6.51142513478515E-02, -2.92468715386302, 6.64876096952665E-02, 3.52335014263844, -1.46340792313332E-02, -2.24503486668184, 1.10533464706142, -4.08757344495612E-02];
ps = p / 100;
hs = h / 2100;
vs = 0;
for i = 1 : 32
vs = vs + ni[i] * (ps + 0.128) ^ Ii[i] * (hs - 0.727) ^ Ji[i];
end
v3_ph = vs * 0.0028;
else
#Subregion 3b
#Eq 5, Table 7, Page 9
Ii = [-12, -12, -8, -8, -8, -8, -8, -8, -6, -6, -6, -6, -6, -6, -4, -4, -4, -3, -3, -2, -2, -1, -1, -1, -1, 0, 1, 1, 2, 2];
Ji = [0, 1, 0, 1, 3, 6, 7, 8, 0, 1, 2, 5, 6, 10, 3, 6, 10, 0, 2, 1, 2, 0, 1, 4, 5, 0, 0, 1, 2, 6];
ni = [-2.25196934336318E-09, 1.40674363313486E-08, 2.3378408528056E-06, -3.31833715229001E-05, 1.07956778514318E-03, -0.271382067378863, 1.07202262490333, -0.853821329075382, -2.15214194340526E-05, 7.6965608822273E-04, -4.31136580433864E-03, 0.453342167309331, -0.507749535873652, -100.475154528389, -0.219201924648793, -3.21087965668917, 607.567815637771, 5.57686450685932E-04, 0.18749904002955, 9.05368030448107E-03, 0.285417173048685, 3.29924030996098E-02, 0.239897419685483, 4.82754995951394, -11.8035753702231, 0.169490044091791, -1.79967222507787E-02, 3.71810116332674E-02, -5.36288335065096E-02, 1.6069710109252];
ps = p / 100;
hs = h / 2800;
vs = 0;
for i = 1 : 30
vs = vs + ni[i] * (ps + 0.0661) ^ Ii[i] * (hs - 0.72) ^ Ji[i];
end
v3_ph = vs * 0.0088;
end
v3_ph
end
function T3_ps(p, s)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#3.4 Backward Equations T(p,s) and v(p,s) for Subregions 3a and 3b
#Boundary equation, Eq 6 Page 11
if s <= 4.41202148223476
#Subregion 3a
#Eq 6, Table 10, Page 11
Ii = [-12, -12, -10, -10, -10, -10, -8, -8, -8, -8, -6, -6, -6, -5, -5, -5, -4, -4, -4, -2, -2, -1, -1, 0, 0, 0, 1, 2, 2, 3, 8, 8, 10];
Ji = [28, 32, 4, 10, 12, 14, 5, 7, 8, 28, 2, 6, 32, 0, 14, 32, 6, 10, 36, 1, 4, 1, 6, 0, 1, 4, 0, 0, 3, 2, 0, 1, 2];
ni = [1500420082.63875, -159397258480.424, 5.02181140217975E-04, -67.2057767855466, 1450.58545404456, -8238.8953488889, -0.154852214233853, 11.2305046746695, -29.7000213482822, 43856513263.5495, 1.37837838635464E-03, -2.97478527157462, 9717779473494.13, -5.71527767052398E-05, 28830.794977842, -74442828926270.3, 12.8017324848921, -368.275545889071, 6.64768904779177E+15, 0.044935925195888, -4.22897836099655, -0.240614376434179, -4.74341365254924, 0.72409399912611, 0.923874349695897, 3.99043655281015, 3.84066651868009E-02, -3.59344365571848E-03, -0.735196448821653, 0.188367048396131, 1.41064266818704E-04, -2.57418501496337E-03, 1.23220024851555E-03];
Sigma = s / 4.4;
Pi = p / 100;
teta = 0;
for i = 1 : 33
teta = teta + ni[i] * (Pi + 0.24) ^ Ii[i] * (Sigma - 0.703) ^ Ji[i];
end
T3_ps = teta * 760;
else
#Subregion 3b
#Eq 7, Table 11, Page 11
Ii = [-12, -12, -12, -12, -8, -8, -8, -6, -6, -6, -5, -5, -5, -5, -5, -4, -3, -3, -2, 0, 2, 3, 4, 5, 6, 8, 12, 14];
Ji = [1, 3, 4, 7, 0, 1, 3, 0, 2, 4, 0, 1, 2, 4, 6, 12, 1, 6, 2, 0, 1, 1, 0, 24, 0, 3, 1, 2];
ni = [0.52711170160166, -40.1317830052742, 153.020073134484, -2247.99398218827, -0.193993484669048, -1.40467557893768, 42.6799878114024, 0.752810643416743, 22.6657238616417, -622.873556909932, -0.660823667935396, 0.841267087271658, -25.3717501764397, 485.708963532948, 880.531517490555, 2650155.92794626, -0.359287150025783, -656.991567673753, 2.41768149185367, 0.856873461222588, 0.655143675313458, -0.213535213206406, 5.62974957606348E-03, -316955725450471, -6.99997000152457E-04, 1.19845803210767E-02, 1.93848122022095E-05, -2.15095749182309E-05];
Sigma = s / 5.3;
Pi = p / 100;
teta = 0;
for i = 1 : 28
teta = teta + ni[i] * (Pi + 0.76) ^ Ii[i] * (Sigma - 0.818) ^ Ji[i];
end
T3_ps = teta * 860;
end
T3_ps
end
function v3_ps(p, s)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#3.4 Backward Equations T(p,s) and v(p,s) for Subregions 3a and 3b
#Boundary equation, Eq 6 Page 11
if s <= 4.41202148223476
#Subregion 3a
#Eq 8, Table 13, Page 14
Ii = [-12, -12, -12, -10, -10, -10, -10, -8, -8, -8, -8, -6, -5, -4, -3, -3, -2, -2, -1, -1, 0, 0, 0, 1, 2, 4, 5, 6];
Ji = [10, 12, 14, 4, 8, 10, 20, 5, 6, 14, 16, 28, 1, 5, 2, 4, 3, 8, 1, 2, 0, 1, 3, 0, 0, 2, 2, 0];
ni = [79.5544074093975, -2382.6124298459, 17681.3100617787, -1.10524727080379E-03, -15.3213833655326, 297.544599376982, -35031520.6871242, 0.277513761062119, -0.523964271036888, -148011.182995403, 1600148.99374266, 1708023226634.27, 2.46866996006494E-04, 1.6532608479798, -0.118008384666987, 2.537986423559, 0.965127704669424, -28.2172420532826, 0.203224612353823, 1.10648186063513, 0.52612794845128, 0.277000018736321, 1.08153340501132, -7.44127885357893E-02, 1.64094443541384E-02, -6.80468275301065E-02, 0.025798857610164, -1.45749861944416E-04];
Pi = p / 100;
Sigma = s / 4.4;
omega = 0;
for i = 1 : 28
omega = omega + ni[i] * (Pi + 0.187) ^ Ii[i] * (Sigma - 0.755) ^ Ji[i];
end
v3_ps = omega * 0.0028;
else
#Subregion 3b
#Eq 9, Table 14, Page 14
Ii = [-12, -12, -12, -12, -12, -12, -10, -10, -10, -10, -8, -5, -5, -5, -4, -4, -4, -4, -3, -2, -2, -2, -2, -2, -2, 0, 0, 0, 1, 1, 2];
Ji = [0, 1, 2, 3, 5, 6, 0, 1, 2, 4, 0, 1, 2, 3, 0, 1, 2, 3, 1, 0, 1, 2, 3, 4, 12, 0, 1, 2, 0, 2, 2];
ni = [5.91599780322238E-05, -1.85465997137856E-03, 1.04190510480013E-02, 5.9864730203859E-03, -0.771391189901699, 1.72549765557036, -4.67076079846526E-04, 1.34533823384439E-02, -8.08094336805495E-02, 0.508139374365767, 1.28584643361683E-03, -1.63899353915435, 5.86938199318063, -2.92466667918613, -6.14076301499537E-03, 5.76199014049172, -12.1613320606788, 1.67637540957944, -7.44135838773463, 3.78168091437659E-02, 4.01432203027688, 16.0279837479185, 3.17848779347728, -3.58362310304853, -1159952.60446827, 0.199256573577909, -0.122270624794624, -19.1449143716586, -1.50448002905284E-02, 14.6407900162154, -3.2747778718823];
Pi = p / 100;
Sigma = s / 5.3;
omega = 0;
for i = 1 : 31
omega = omega + ni[i] * (Pi + 0.298) ^ Ii[i] * (Sigma - 0.816) ^ Ji[i];
end
v3_ps = omega * 0.0088;
end
v3_ps
end
function p3_hs(h, s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Equations as a function of h and s for the Region Boundaries, and an Equation
#( ) sat , T hs for Region 4 of the IAPWS Industrial formulation 1997 for the
#Thermodynamic Properties of Water and Steam
#2004
#Section 3 Backward functions p(h,s), T(h,s), and v(h,s) for Region 3
if s < 4.41202148223476
#Subregion 3a
#Eq 1, Table 3, Page 8
Ii = [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8, 10, 10, 14, 18, 20, 22, 22, 24, 28, 28, 32, 32];
Ji = [0, 1, 5, 0, 3, 4, 8, 14, 6, 16, 0, 2, 3, 0, 1, 4, 5, 28, 28, 24, 1, 32, 36, 22, 28, 36, 16, 28, 36, 16, 36, 10, 28];
ni = [7.70889828326934, -26.0835009128688, 267.416218930389, 17.2221089496844, -293.54233214597, 614.135601882478, -61056.2757725674, -65127225.1118219, 73591.9313521937, -11664650591.4191, 35.5267086434461, -596.144543825955, -475.842430145708, 69.6781965359503, 335.674250377312, 25052.6809130882, 146997.380630766, 5.38069315091534E+19, 1.43619827291346E+21, 3.64985866165994E+19, -2547.41561156775, 2.40120197096563E+27, -3.93847464679496E+29, 1.47073407024852E+24, -4.26391250432059E+31, 1.94509340621077E+38, 6.66212132114896E+23, 7.06777016552858E+33, 1.75563621975576E+41, 1.08408607429124E+28, 7.30872705175151E+43, 1.5914584739887E+24, 3.77121605943324E+40];
Sigma = s / 4.4;
eta = h / 2300;
Pi = 0;
for i = 1 : 33
Pi = Pi + ni[i] * (eta - 1.01) ^ Ii[i] * (Sigma - 0.75) ^ Ji[i];
end
p3_hs = Pi * 99;
else
#Subregion 3b
#Eq 2, Table 4, Page 8
Ii = [-12, -12, -12, -12, -12, -10, -10, -10, -10, -8, -8, -6, -6, -6, -6, -5, -4, -4, -4, -3, -3, -3, -3, -2, -2, -1, 0, 2, 2, 5, 6, 8, 10, 14, 14];
Ji = [2, 10, 12, 14, 20, 2, 10, 14, 18, 2, 8, 2, 6, 7, 8, 10, 4, 5, 8, 1, 3, 5, 6, 0, 1, 0, 3, 0, 1, 0, 1, 1, 1, 3, 7];
ni = [1.25244360717979E-13, -1.26599322553713E-02, 5.06878030140626, 31.7847171154202, -391041.161399932, -9.75733406392044E-11, -18.6312419488279, 510.973543414101, 373847.005822362, 2.99804024666572E-08, 20.0544393820342, -4.98030487662829E-06, -10.230180636003, 55.2819126990325, -206.211367510878, -7940.12232324823, 7.82248472028153, -58.6544326902468, 3550.73647696481, -1.15303107290162E-04, -1.75092403171802, 257.98168774816, -727.048374179467, 1.21644822609198E-04, 3.93137871762692E-02, 7.04181005909296E-03, -82.910820069811, -0.26517881813125, 13.7531682453991, -52.2394090753046, 2405.56298941048, -22736.1631268929, 89074.6343932567, -23923456.5822486, 5687958081.29714];
Sigma = s / 5.3;
eta = h / 2800;
Pi = 0;
for i = 1 : 35
Pi = Pi + ni[i] * (eta - 0.681) ^ Ii[i] * (Sigma - 0.792) ^ Ji[i];
end
p3_hs = 16.6 / Pi;
end
p3_hs
end
function h3_pT(p, T)
#Not avalible with if 97
#Solve function T3_ph-T=0 with half interval method.
#ver2.6 Start corrected bug
if p < 22.06395 #Bellow tripple point
Ts = T4_p(p); #Saturation temperature
if T <= Ts #Liquid side
High_Bound = h4L_p(p); #Max h 鋜 liauid h.
Low_Bound = h1_pT(p, 623.15);
else
Low_Bound = h4V_p(p); #Min h 鋜 Vapour h.
High_Bound = h2_pT(p, B23T_p(p));
end
else #Above tripple point. R3 from R2 till R3.
Low_Bound = h1_pT(p, 623.15);
High_Bound = h2_pT(p, B23T_p(p));
end
#ver2.6 End corrected bug
Ts = T+1;
hs=0.0
while abs(T - Ts) > 0.00001
hs = (Low_Bound + High_Bound) / 2;
Ts = T3_ph(p, hs);
if Ts > T
High_Bound = hs;
else
Low_Bound = hs;
end
end
h3_pT = hs;
h3_pT
end
function T3_prho(p, rho)
#Solve by iteration. Observe that fo low temperatures this equation has 2 solutions.
#Solve with half interval method
Low_Bound = 623.15;
High_Bound = 1073.15;
ps=-1000;
Ts=0.0;
while abs(p - ps) > 0.00000001
Ts = (Low_Bound + High_Bound) / 2;
ps = p3_rhoT(rho, Ts);
if ps > p
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T3_prho = Ts;
T3_prho
end
#***********************************************************************************************************
#*2.4 functions for region 4
function p4_T(T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Section 8.1 The Saturation-Pressure Equation
#Eq 30, Page 33
teta = T - 0.23855557567849 / (T - 650.17534844798);
a = teta ^ 2 + 1167.0521452767 * teta - 724213.16703206;
B = -17.073846940092 * teta ^ 2 + 12020.82470247 * teta - 3232555.0322333;
C = 14.91510861353 * teta ^ 2 - 4823.2657361591 * teta + 405113.40542057;
p4_T = (2 * C / (-B + (B ^ 2 - 4 * a * C) ^ 0.5)) ^ 4;
p4_T
end
function T4_p(p)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Section 8.2 The Saturation-Temperature Equation
#Eq 31, Page 34
beta = p ^ 0.25;
E = beta ^ 2 - 17.073846940092 * beta + 14.91510861353;
f = 1167.0521452767 * beta ^ 2 + 12020.82470247 * beta - 4823.2657361591;
G = -724213.16703206 * beta ^ 2 - 3232555.0322333 * beta + 405113.40542057;
D = 2 * G / (-f - (f ^ 2 - 4 * E * G) ^ 0.5);
T4_p = (650.17534844798 + D - ((650.17534844798 + D) ^ 2 - 4 * (-0.23855557567849 + 650.17534844798 * D)) ^ 0.5) / 2;
T4_p
end
function h4_s(s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,Equations as a function of h and s for the Region Boundaries, and an Equation( ) sat , T hs for Region 4 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#4 Equations for Region Boundaries Given Enthalpy and Entropy
# Se picture page 14
if (s > -0.0001545495919 && s <= 3.77828134)==1
#hL1_s
#Eq 3,Table 9,Page 16
Ii = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 7, 8, 12, 12, 14, 14, 16, 20, 20, 22, 24, 28, 32, 32];
Ji = [14, 36, 3, 16, 0, 5, 4, 36, 4, 16, 24, 18, 24, 1, 4, 2, 4, 1, 22, 10, 12, 28, 8, 3, 0, 6, 8];
ni = [0.332171191705237, 6.11217706323496E-04, -8.82092478906822, -0.45562819254325, -2.63483840850452E-05, -22.3949661148062, -4.28398660164013, -0.616679338856916, -14.682303110404, 284.523138727299, -113.398503195444, 1156.71380760859, 395.551267359325, -1.54891257229285, 19.4486637751291, -3.57915139457043, -3.35369414148819, -0.66442679633246, 32332.1885383934, 3317.66744667084, -22350.1257931087, 5739538.75852936, 173.226193407919, -3.63968822121321E-02, 8.34596332878346E-07, 5.03611916682674, 65.5444787064505];
Sigma = s / 3.8;
eta = 0;
for i = 1 : 27
eta = eta + ni[i] * (Sigma - 1.09) ^ Ii[i] * (Sigma + 0.0000366) ^ Ji[i];
end
h4_s = eta * 1700;
elseif (s > 3.77828134 && s <= 4.41202148223476 )==1
#hL3_s
#Eq 4,Table 10,Page 16
Ii = [0, 0, 0, 0, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7, 10, 10, 10, 32, 32];
Ji = [1, 4, 10, 16, 1, 36, 3, 16, 20, 36, 4, 2, 28, 32, 14, 32, 36, 0, 6];
ni = [0.822673364673336, 0.181977213534479, -0.011200026031362, -7.46778287048033E-04, -0.179046263257381, 4.24220110836657E-02, -0.341355823438768, -2.09881740853565, -8.22477343323596, -4.99684082076008, 0.191413958471069, 5.81062241093136E-02, -1655.05498701029, 1588.70443421201, -85.0623535172818, -31771.4386511207, -94589.0406632871, -1.3927384708869E-06, 0.63105253224098];
Sigma = s / 3.8;
eta = 0;
for i = 1 : 19
eta = eta + ni[i] * (Sigma - 1.09) ^ Ii[i] * (Sigma + 0.0000366) ^ Ji[i];
end
h4_s = eta * 1700;
elseif (s > 4.41202148223476 && s <= 5.85 )==1
#Section 4.4 Equations ( ) 2ab " h s and ( ) 2c3b "h s for the Saturated Vapor Line
#Page 19, Eq 5
#hV2c3b_s(s)
Ii = [0, 0, 0, 1, 1, 5, 6, 7, 8, 8, 12, 16, 22, 22, 24, 36];
Ji = [0, 3, 4, 0, 12, 36, 12, 16, 2, 20, 32, 36, 2, 32, 7, 20];
ni = [1.04351280732769, -2.27807912708513, 1.80535256723202, 0.420440834792042, -105721.24483466, 4.36911607493884E+24, -328032702839.753, -6.7868676080427E+15, 7439.57464645363, -3.56896445355761E+19, 1.67590585186801E+31, -3.55028625419105E+37, 396611982166.538, -4.14716268484468E+40, 3.59080103867382E+18, -1.16994334851995E+40];
Sigma = s / 5.9;
eta = 0;
for i = 1 : 16
eta = eta + ni[i] * (Sigma - 1.02) ^ Ii[i] * (Sigma - 0.726) ^ Ji[i];
end
h4_s = eta ^ 4 * 2800;
elseif (s > 5.85 && s < 9.155759395)==1
#Section 4.4 Equations ( ) 2ab " h s and ( ) 2c3b "h s for the Saturated Vapor Line
#Page 20, Eq 6
Ii = [1, 1, 2, 2, 4, 4, 7, 8, 8, 10, 12, 12, 18, 20, 24, 28, 28, 28, 28, 28, 32, 32, 32, 32, 32, 36, 36, 36, 36, 36];
Ji = [8, 24, 4, 32, 1, 2, 7, 5, 12, 1, 0, 7, 10, 12, 32, 8, 12, 20, 22, 24, 2, 7, 12, 14, 24, 10, 12, 20, 22, 28];
ni = [-524.581170928788, -9269472.18142218, -237.385107491666, 21077015581.2776, -23.9494562010986, 221.802480294197, -5104725.33393438, 1249813.96109147, 2000084369.96201, -815.158509791035, -157.612685637523, -11420042233.2791, 6.62364680776872E+15, -2.27622818296144E+18, -1.71048081348406E+31, 6.60788766938091E+15, 1.66320055886021E+22, -2.18003784381501E+29, -7.87276140295618E+29, 1.51062329700346E+31, 7957321.70300541, 1.31957647355347E+15, -3.2509706829914E+23, -4.18600611419248E+25, 2.97478906557467E+34, -9.53588761745473E+19, 1.66957699620939E+24, -1.75407764869978E+32, 3.47581490626396E+34, -7.10971318427851E+38];
Sigma1 = s / 5.21;
Sigma2 = s / 9.2;
eta = 0;
for i = 1 : 30
eta = eta + ni[i] * (1 / Sigma1 - 0.513) ^ Ii[i] * (Sigma2 - 0.524) ^ Ji[i];
end
h4_s = exp(eta) * 2800;
else
h4_s = -99999;
end
h4_s
end
function p4_s(s)
#Uses h4_s and p_hs for the diffrent regions to determine p4_s
h_sat = h4_s(s);
if (s > -0.0001545495919 && s <= 3.77828134)==1
p4_s = p1_hs(h_sat, s);
elseif (s > 3.77828134 && s <= 5.210887663)==1
p4_s = p3_hs(h_sat, s);
elseif (s > 5.210887663 && s < 9.155759395)==1
p4_s = p2_hs(h_sat, s);
else
p4_s = -99999;
end
p4_s
end
function h4L_p(p)
hs=0.0
if (p > 0.000611657 && p < 22.06395)==1
Ts = T4_p(p);
if p < 16.529
h4L_p = h1_pT(p, Ts);
else
#Iterate to find the the backward solution of p3sat_h
Low_Bound = 1670.858218;
High_Bound = 2087.23500164864;
ps=-1000;
while abs(p - ps) > 0.00001
hs = (Low_Bound + High_Bound) / 2;
ps = p3sat_h(hs);
if ps > p
High_Bound = hs;
else
Low_Bound = hs;
end
end
h4L_p = hs;
end
else
h4L_p = -99999;
end
h4L_p
end
function h4V_p(p)
hs=0.0
if p > 0.000611657 && p < 22.06395
Ts = T4_p(p);
if p < 16.529
h4V_p = h2_pT(p, Ts);
else
#Iterate to find the the backward solution of p3sat_h
Low_Bound = 2087.23500164864;
High_Bound = 2563.592004+5;
ps=-1000;
while abs(p - ps) > 0.000001
hs = (Low_Bound + High_Bound) / 2;
ps = p3sat_h(hs);
if ps < p
High_Bound = hs;
else
Low_Bound = hs;
end
end
h4V_p = hs;
end
else
h4V_p = -99999;
end
h4V_p
end
function x4_ph(p, h)
#Calculate vapour fraction from hL and hV for given p
h4v = h4V_p(p);
h4L = h4L_p(p);
if h > h4v
x4_ph = 1;
elseif h < h4L
x4_ph = 0;
else
x4_ph = (h - h4L) / (h4v - h4L);
end
x4_ph
end
function x4_ps(p, s)
if p < 16.529
ssv = s2_pT(p, T4_p(p));
ssL = s1_pT(p, T4_p(p));
else
ssv = s3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p));
ssL = s3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p));
end
if s < ssL
x4_ps = 0;
elseif s > ssv
x4_ps = 1;
else
x4_ps = (s - ssL) / (ssv - ssL);
end
x4_ps
end
function T4_hs(h, s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Chapter 5.3 page 30.
#The if 97 function is only valid for part of region4. Use iteration outsida.
Ii = [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 8, 10, 10, 12, 14, 14, 16, 16, 18, 18, 18, 20, 28];
Ji = [0, 3, 12, 0, 1, 2, 5, 0, 5, 8, 0, 2, 3, 4, 0, 1, 1, 2, 4, 16, 6, 8, 22, 1, 20, 36, 24, 1, 28, 12, 32, 14, 22, 36, 24, 36];
ni = [0.179882673606601, -0.267507455199603, 1.162767226126, 0.147545428713616, -0.512871635973248, 0.421333567697984, 0.56374952218987, 0.429274443819153, -3.3570455214214, 10.8890916499278, -0.248483390456012, 0.30415322190639, -0.494819763939905, 1.07551674933261, 7.33888415457688E-02, 1.40170545411085E-02, -0.106110975998808, 1.68324361811875E-02, 1.25028363714877, 1013.16840309509, -1.51791558000712, 52.4277865990866, 23049.5545563912, 2.49459806365456E-02, 2107964.67412137, 366836848.613065, -144814105.365163, -1.7927637300359E-03, 4899556021.00459, 471.262212070518, -82929439019.8652, -1715.45662263191, 3557776.82973575, 586062760258.436, -12988763.5078195, 31724744937.1057];
if (s > 5.210887825 && s < 9.15546555571324)==1
Sigma = s / 9.2;
eta = h / 2800;
teta = 0;
for i = 1 : 36
teta = teta + ni[i] * (eta - 0.119) ^ Ii[i] * (Sigma - 1.07) ^ Ji[i];
end
T4_hs = teta * 550;
else
#function psat_h
if (s > -0.0001545495919 && s <= 3.77828134)==1
Low_Bound = 0.000611;
High_Bound = 165.291642526045;
hL=-1000;
while abs(hL - h) > 0.00001 && abs(High_Bound - Low_Bound) > 0.0001
PL = (Low_Bound + High_Bound) / 2;
Ts = T4_p(PL);
hL = h1_pT(PL, Ts);
if hL > h
High_Bound = PL;
else
Low_Bound = PL;
end
end
elseif s > 3.77828134 && s <= 4.41202148223476
PL = p3sat_h(h);
elseif s > 4.41202148223476 && s <= 5.210887663
PL = p3sat_h(h);
end
Low_Bound = 0.000611;
High_Bound = PL;
sss=-1000;
p=0.0
while (abs(s - sss) > 0.000001 && abs(High_Bound - Low_Bound) > 0.0000001)==1
p = (Low_Bound + High_Bound) / 2;
#Calculate s4_ph
Ts = T4_p(p);
xs = x4_ph(p, h);
if p < 16.529
s4v = s2_pT(p, Ts);
s4L = s1_pT(p, Ts);
else
v4v = v3_ph(p, h4V_p(p));
s4v = s3_rhoT(1 / v4v, Ts);
v4L = v3_ph(p, h4L_p(p));
s4L = s3_rhoT(1 / v4L, Ts);
end
sss = (xs * s4v + (1 - xs) * s4L);
if sss < s
High_Bound = p;
else
Low_Bound = p;
end
end
T4_hs = T4_p(p);
end
T4_hs
end
#***********************************************************************************************************
#*2.5 functions for region 5
function h5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tau = 0;
for i = 1 : 6
gamma0_tau = gamma0_tau + ni0[i] * Ji0[i] * tau ^ (Ji0[i] - 1);
end
gammar_tau = 0;
for i = 1 : 5
gammar_tau = gammar_tau + nir[i] * Pi ^ Iir[i] * Jir[i] * tau ^ (Jir[i] - 1);
end
h5_pT = R * T * tau * (gamma0_tau + gammar_tau);
h5_pT
end
function v5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_pi = 1 / Pi;
gammar_pi = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
end
v5_pT = R * T / p * Pi * (gamma0_pi + gammar_pi) / 1000;
v5_pT
end
function u5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_pi = 1 / Pi;
gamma0_tau = 0;
for i = 1 : 6
gamma0_tau = gamma0_tau + ni0[i] * Ji0[i] * tau ^ (Ji0[i] - 1);
end
gammar_pi = 0;
gammar_tau = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
gammar_tau = gammar_tau + nir[i] * Pi ^ Iir[i] * Jir[i] * tau ^ (Jir[i] - 1);
end
u5_pT = R * T * (tau * (gamma0_tau + gammar_tau) - Pi * (gamma0_pi + gammar_pi));
u5_pT
end
function Cp5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tautau = 0;
for i = 1 : 6
gamma0_tautau = gamma0_tautau + ni0[i] * Ji0[i] * (Ji0[i] - 1) * tau ^ (Ji0[i] - 2);
end
gammar_tautau = 0;
for i = 1 : 5
gammar_tautau = gammar_tautau + nir[i] * Pi ^ Iir[i] * Jir[i] * (Jir[i] - 1) * tau ^ (Jir[i] - 2);
end
Cp5_pT = -R * tau ^ 2 * (gamma0_tautau + gammar_tautau);
Cp5_pT
end
function s5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0 = log(Pi);
gamma0_tau = 0;
for i = 1 : 6
gamma0_tau = gamma0_tau + ni0[i] * Ji0[i] * tau ^ (Ji0[i] - 1);
gamma0 = gamma0 + ni0[i] * tau ^ Ji0[i];
end
gammar = 0;
gammar_tau = 0;
for i = 1 : 5
gammar = gammar + nir[i] * Pi ^ Iir[i] * tau ^ Jir[i];
gammar_tau = gammar_tau + nir[i] * Pi ^ Iir[i] * Jir[i] * tau ^ (Jir[i] - 1);
end
s5_pT = R * (tau * (gamma0_tau + gammar_tau) - (gamma0 + gammar));
s5_pT
end
function Cv5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tautau = 0;
for i = 1 : 6
gamma0_tautau = gamma0_tautau + ni0[i] * (Ji0[i] - 1) * Ji0[i] * tau ^ (Ji0[i] - 2);
end
gammar_pi = 0;
gammar_pitau = 0;
gammar_pipi = 0;
gammar_tautau = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
gammar_pitau = gammar_pitau + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * Jir[i] * tau ^ (Jir[i] - 1);
gammar_pipi = gammar_pipi + nir[i] * Iir[i] * (Iir[i] - 1) * Pi ^ (Iir[i] - 2) * tau ^ Jir[i];
gammar_tautau = gammar_tautau + nir[i] * Pi ^ Iir[i] * Jir[i] * (Jir[i] - 1) * tau ^ (Jir[i] - 2);
end
Cv5_pT = R * (-(tau ^ 2 *(gamma0_tautau + gammar_tautau)) - (1 + Pi * gammar_pi - tau * Pi * gammar_pitau)^2 / (1 - Pi ^ 2 * gammar_pipi));
Cv5_pT
end
function w5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tautau = 0;
for i = 1 : 6
gamma0_tautau = gamma0_tautau + ni0[i] * (Ji0[i] - 1) * Ji0[i] * tau ^ (Ji0[i] - 2);
end
gammar_pi = 0;
gammar_pitau = 0;
gammar_pipi = 0;
gammar_tautau = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
gammar_pitau = gammar_pitau + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * Jir[i] * tau ^ (Jir[i] - 1);
gammar_pipi = gammar_pipi + nir[i] * Iir[i] * (Iir[i] - 1) * Pi ^ (Iir[i] - 2) * tau ^ Jir[i];
gammar_tautau = gammar_tautau + nir[i] * Pi ^ Iir[i] * Jir[i] * (Jir[i] - 1) * tau ^ (Jir[i] - 2);
end
w5_pT = (1000 * R * T * (1 + 2 * Pi * gammar_pi + Pi ^ 2 * gammar_pi ^ 2) / ((1 - Pi ^ 2 * gammar_pipi) + (1 + Pi * gammar_pi - tau * Pi * gammar_pitau) ^ 2 / (tau ^ 2 * (gamma0_tautau + gammar_tautau)))) ^ 0.5;
w5_pT
end
function T5_ph(p, h)
#Solve with half interval method
Low_Bound = 1073.15;
High_Bound = 2273.15;
hs=h-1;
Ts=0.0
while abs(h - hs) > 0.00001
Ts = (Low_Bound + High_Bound) / 2;
hs = h5_pT(p, Ts);
if hs > h
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T5_ph = Ts;
T5_ph
end
function T5_ps(p, s)
#Solve with half interval method
Low_Bound = 1073.15;
High_Bound = 2273.15;
ss=s-1;
Ts=0.0
while abs(s - ss) > 0.00001
Ts = (Low_Bound + High_Bound) / 2;
ss = s5_pT(p, Ts);
if ss > s
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T5_ps = Ts;
T5_ps
end
function T5_prho(p,rho)
#Solve by iteration. Observe that fo low temperatures this equation has 2 solutions.
#Solve with half interval method
Ts=0.0
Low_Bound = 1073.15;
High_Bound = 2073.15;
rhos=-1000;
while abs(rho - rhos) > 0.000001
Ts = (Low_Bound + High_Bound) / 2;
rhos = 1 / v2_pT(p, Ts);
if rhos < rho
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T5_prho = Ts;
T5_prho
end
#***********************************************************************************************************
#*3 Region Selection
#***********************************************************************************************************
#*3.1 Regions as a function of pT
function region_pT(p, T)
if T > 1073.15 && p < 10 && T < 2273.15 && p > 0.000611
region_pT = 5;
elseif T <= 1073.15 && T > 273.15 && p <= 100 && p > 0.000611
if T > 623.15
if p > B23p_T(T)
region_pT = 3;
if T < 647.096
ps = p4_T(T);
if abs(p - ps) < 0.00001
region_pT = 4;
end
end
else
region_pT = 2;
end
else
ps = p4_T(T);
if abs(p - ps) < 0.00001
region_pT = 4;
elseif p > ps
region_pT = 1;
else
region_pT = 2;
end
end
else
region_pT = 0; #**Error, Outside valid area
end
region_pT
end
#***********************************************************************************************************
#*3.2 Regions as a function of ph
function region_ph( p, h)
#Check if outside pressure limits
if p < 0.000611657 || p > 100
region_ph = 0;
return region_ph
end
#Check if outside low h.
if h < 0.963 * p + 2.2 #Linear adaption to h1_pt()+2 to speed up calcualations.
if h < h1_pT(p, 273.15)
region_ph = 0;
return region_ph
end
end
if p < 16.5292 #Bellow region 3,Check region 1,4,2,5
#Check Region 1
Ts = T4_p(p);
hL = 109.6635 * log(p) + 40.3481 * p + 734.58; #Approximate function for hL_p
if abs(h - hL) < 100 #if approximate is not god enough use real function
hL = h1_pT(p, Ts);
end
if h <= hL
region_ph = 1;
return region_ph
end
#Check Region 4
hV = 45.1768 * log(p) - 20.158 * p + 2804.4; #Approximate function for hV_p
if abs(h - hV) < 50 #if approximate is not god enough use real function
hV = h2_pT(p, Ts);
end
if h < hV
region_ph = 4;
return region_ph
end
#Check upper limit of region 2 Quick Test
if h < 4000
region_ph = 2;
return region_ph
end
#Check region 2 (Real value)
h_45 = h2_pT(p, 1073.15);
if h <= h_45
region_ph = 2;
return region_ph
end
#Check region 5
if p > 10
region_ph = 0;
return region_ph
end
h_5u = h5_pT(p, 2273.15);
if h < h_5u
region_ph = 5;
return region_ph
end
region_ph = 0;
return
else #for p>16.5292
#Check if in region1
if h < h1_pT(p, 623.15)
region_ph = 1;
return region_ph
end
#Check if in region 3 or 4 (Bellow Reg 2)
if h < h2_pT(p, B23T_p(p))
#Region 3 or 4
if p > p3sat_h(h)
region_ph = 3;
return region_ph
else
region_ph = 4;
return region_ph
end
end
#Check if region 2
if h < h2_pT(p, 1073.15)
region_ph = 2;
return region_ph
end
end
region_ph = 0;
region_ph
end
#***********************************************************************************************************
#*3.3 Regions as a function of ps
function region_ps( p, s)
if p < 0.000611657 || p > 100 || s < 0 || s > s5_pT(p, 2273.15)
region_ps = 0;
return region_ps
end
#Check region 5
if s > s2_pT(p, 1073.15)
if p <= 10
region_ps = 5;
return region_ps
else
region_ps = 0;
return region_ps
end
end
#Check region 2
if p > 16.529
ss = s2_pT(p, B23T_p(p)); #Between 5.047 & 5.261. Use to speed up!
else
ss = s2_pT(p, T4_p(p));
end
if s > ss
region_ps = 2;
return region_ps
end
#Check region 3
ss = s1_pT(p, 623.15);
if p > 16.529 && s > ss
if p > p3sat_s(s)
region_ps = 3;
return region_ps
else
region_ps = 4;
return region_ps
end
end
#Check region 4 (Not inside region 3)
if p < 16.529 && s > s1_pT(p, T4_p(p))
region_ps = 4;
return region_ps
end
#Check region 1
if p > 0.000611657 && s > s1_pT(p, 273.15)
region_ps = 1;
return region_ps
end
region_ps = 1;
region_ps
end
#***********************************************************************************************************
#*3.4 Regions as a function of hs
function region_hs( h, s)
if s < -0.0001545495919
region_hs = 0;
return region_hs
end
#Check linear adaption to p=0.000611. if bellow region 4.
hMin = (((-0.0415878 - 2500.89262) / (-0.00015455 - 9.155759)) * s);
if s < 9.155759395 && h < hMin
region_hs = 0;
return region_hs
end
#******Kolla 1 eller 4. (+liten bit 鰒er B13)
if s >= -0.0001545495919 && s <= 3.77828134
if h < h4_s(s)
region_hs = 4;
return region_hs
elseif s < 3.397782955 #100MPa line is limiting
TMax = T1_ps(100, s);
hMax = h1_pT(100, TMax);
if h < hMax
region_hs = 1;
return region_hs
else
region_hs = 0;
return region_hs
end
else #The point is either in region 4,1,3. Check B23
hB = hB13_s(s);
if h < hB
region_hs = 1;
return region_hs
end
TMax = T3_ps(100, s);
vmax = v3_ps(100, s);
hMax = h3_rhoT(1 / vmax, TMax);
if h < hMax
region_hs = 3;
return region_hs
else
region_hs = 0;
return region_hs
end
end
end
#******Kolla region 2 eller 4. (講re delen av omr錮e b23-> max)
if s >= 5.260578707 && s <= 11.9212156897728
if s > 9.155759395 #Above region 4
Tmin = T2_ps(0.000611, s);
hMin = h2_pT(0.000611, Tmin);
#function adapted to h(1073.15,s)
hMax = -0.07554022 * s ^ 4 + 3.341571 * s ^ 3 - 55.42151 * s ^ 2 + 408.515 * s + 3031.338;
if h > hMin && h < hMax
region_hs = 2;
return region_hs
else
region_hs = 0;
return region_hs
end
end
hV = h4_s(s);
if h < hV #Region 4. Under region 3.
region_hs = 4;
return region_hs
end
if s < 6.04048367171238
TMax = T2_ps(100., s);
hMax = h2_pT(100., TMax);
else
#function adapted to h(1073.15,s)
hMax = -2.988734 * s ^ 4 + 121.4015 * s ^ 3 - 1805.15 * s ^ 2 + 11720.16 * s - 23998.33;
end
if h < hMax #Region 2. 講er region 4.
region_hs = 2;
return region_hs
else
region_hs = 0;
return region_hs
end
end
#Kolla region 3 eller 4. Under kritiska punkten.
if s >= 3.77828134 && s <= 4.41202148223476
hL = h4_s(s);
if h < hL
region_hs = 4;
return region_hs
end
TMax = T3_ps(100, s);
vmax = v3_ps(100, s);
hMax = h3_rhoT(1 / vmax, TMax);
if h < hMax
region_hs = 3;
return region_hs
else
region_hs = 0;
return region_hs
end
end
#Kolla region 3 eller 4 fr錸 kritiska punkten till 鰒re delen av b23
if s >= 4.41202148223476 && s <= 5.260578707
hV = h4_s(s);
if h < hV
region_hs = 4;
return region_hs
end
#Kolla om vi 鋜 under b23 giltighetsomr錮e.
if s <= 5.048096828
TMax = T3_ps(100, s);
vmax = v3_ps(100, s);
hMax = h3_rhoT(1 / vmax, TMax);
if h < hMax
region_hs = 3;
return region_hs
else
region_hs = 0;
return region_hs
end
else #Inom omr錮et f鰎 B23 i s led.
if (h > 2812.942061) #Ovanf鰎 B23 i h_led
if s > 5.09796573397125
TMax = T2_ps(100, s);
hMax = h2_pT(100, TMax);
if h < hMax
region_hs = 2;
return region_hs
else
region_hs = 0;
return region_hs
end
else
region_hs = 0;
return region_hs
end
end
if (h < 2563.592004) #Nedanf鰎 B23 i h_led men vi har redan kollat ovanf鰎 hV2c3b
region_hs = 3;
return region_hs
end
#Vi 鋜 inom b23 omr錮et i b錮e s och h led.
Tact = TB23_hs(h, s);
pact = p2_hs(h, s);
pBound = B23p_T(Tact);
if pact > pBound
region_hs = 3;
return region_hs
else
region_hs = 2;
return region_hs
end
end
end
region_hs = 0;
region_hs
end
#***********************************************************************************************************
#*3.5 Regions as a function of p and rho
function Region_prho(p,rho)
v = 1 / rho;
if p < 0.000611657 || p > 100
Region_prho = 0;
return
end
if p < 16.5292 #Bellow region 3, Check region 1,4,2
if v < v1_pT(p, 273.15) #Observe that this is not actually min of v. Not valid Water of 4癈 is ligther.
Region_prho = 0;
return Region_prho
end
if v <= v1_pT(p, T4_p(p))
Region_prho = 1;
return Region_prho
end
if v < v2_pT(p, T4_p(p))
Region_prho = 4;
return Region_prho
end
if v <= v2_pT(p, 1073.15)
Region_prho = 2;
return Region_prho
end
if p > 10 #Above region 5
Region_prho = 0;
return Region_prho
end
if v <= v5_pT(p, 2073.15)
Region_prho = 5;
return Region_prho
end
else #Check region 1,3,4,3,2 (Above the lowest point of region 3.)
if v < v1_pT(p, 273.15) #Observe that this is not actually min of v. Not valid Water of 4癈 is ligther.
Region_prho = 0;
return Region_prho
end
if v < v1_pT(p, 623.15)
Region_prho = 1;
return Region_prho
end
#Check if in region 3 or 4 (Bellow Reg 2)
if v < v2_pT(p, B23T_p(p))
#Region 3 or 4
if p > 22.064 #Above region 4
Region_prho = 3;
return Region_prho
end
if v < v3_ph(p, h4L_p(p)) || v > v3_ph(p, h4V_p(p)) #Uses iteration!!
Region_prho = 3;
return Region_prho
else
Region_prho = 4;
return Region_prho
end
end
#Check if region 2
if v < v2_pT(p, 1073.15)
Region_prho = 2;
return Region_prho
end
end
Region_prho = 0;
Region_prho
end
#***********************************************************************************************************
#*4 Region Borders
#***********************************************************************************************************
#***********************************************************************************************************
#*4.1 Boundary between region 2 and 3.
function B23p_T(T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#1997
#Section 4 Auxiliary Equation for the Boundary between Regions 2 and 3
#Eq 5, Page 5
B23p_T = 348.05185628969 - 1.1671859879975 * T + 1.0192970039326E-03 * T ^ 2;
B23p_T
end
function B23T_p(p)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#1997
#Section 4 Auxiliary Equation for the Boundary between Regions 2 and 3
#Eq 6, Page 6
B23T_p = 572.54459862746 + ((p - 13.91883977887) / 1.0192970039326E-03) ^ 0.5;
B23T_p
end
#***********************************************************************************************************
#*4.2 Region 3. pSat_h & pSat_s
function p3sat_h(h)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) & T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water & Steam
#2004
#Section 4 Boundary Equations psat(h) & psat(s) for the Saturation Lines of Region 3
#Se pictures Page 17, Eq 10, Table 17, Page 18
Ii = [0, 1, 1, 1, 1, 5, 7, 8, 14, 20, 22, 24, 28, 36];
Ji = [0, 1, 3, 4, 36, 3, 0, 24, 16, 16, 3, 18, 8, 24];
ni = [0.600073641753024, -9.36203654849857, 24.6590798594147, -107.014222858224, -91582131580576.8, -8623.32011700662, -23.5837344740032, 2.52304969384128E+17, -3.89718771997719E+18, -3.33775713645296E+22, 35649946963.6328, -1.48547544720641E+26, 3.30611514838798E+18, 8.13641294467829E+37];
hs = h / 2600;
ps = 0;
for i = 1:14
ps = ps + ni[i] * (hs - 1.02) ^ Ii[i] * (hs - 0.608) ^ Ji[i];
end
p3sat_h = ps * 22;
p3sat_h
end
function p3sat_s(s)
Ii = [0, 1, 1, 4, 12, 12, 16, 24, 28, 32];
Ji = [0, 1, 32, 7, 4, 14, 36, 10, 0, 18];
ni = [0.639767553612785, -12.9727445396014, -2.24595125848403E+15, 1774667.41801846, 7170793495.71538, -3.78829107169011E+17, -9.55586736431328E+34, 1.87269814676188E+23, 119254746466.473, 1.10649277244882E+36];
Sigma = s / 5.2;
Pi = 0;
for i = 1:10
Pi = Pi + ni[i] * (Sigma - 1.03) ^ Ii[i] * (Sigma - 0.699) ^ Ji[i];
end
p3sat_s = Pi * 22;
p3sat_s
end
#***********************************************************************************************************
#4.3 Region boundary 1to3 & 3to2 as a functions of s
function hB13_s(s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Chapter 4.5 page 23.
Ii = [0, 1, 1, 3, 5, 6];
Ji = [0, -2, 2, -12, -4, -3];
ni = [0.913965547600543, -4.30944856041991E-05, 60.3235694765419, 1.17518273082168E-18, 0.220000904781292, -69.0815545851641];
Sigma = s / 3.8;
eta = 0;
for i = 1 : 6
eta = eta + ni[i] * (Sigma - 0.884) ^ Ii[i] * (Sigma - 0.864) ^ Ji[i];
end
hB13_s = eta * 1700;
hB13_s
end
function TB23_hs(h, s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Chapter 4.6 page 25.
Ii = [-12, -10, -8, -4, -3, -2, -2, -2, -2, 0, 1, 1, 1, 3, 3, 5, 6, 6, 8, 8, 8, 12, 12, 14, 14];
Ji = [10, 8, 3, 4, 3, -6, 2, 3, 4, 0, -3, -2, 10, -2, -1, -5, -6, -3, -8, -2, -1, -12, -1, -12, 1];
ni = [6.2909626082981E-04, -8.23453502583165E-04, 5.15446951519474E-08, -1.17565945784945, 3.48519684726192, -5.07837382408313E-12, -2.84637670005479, -2.36092263939673, 6.01492324973779, 1.48039650824546, 3.60075182221907E-04, -1.26700045009952E-02, -1221843.32521413, 0.149276502463272, 0.698733471798484, -2.52207040114321E-02, 1.47151930985213E-02, -1.08618917681849, -9.36875039816322E-04, 81.9877897570217, -182.041861521835, 2.61907376402688E-06, -29162.6417025961, 1.40660774926165E-05, 7832370.62349385];
Sigma = s / 5.3;
eta = h / 3000;
teta = 0;
for i = 1 : 25
teta = teta + ni[i] * (eta - 0.727) ^ Ii[i] * (Sigma - 0.864) ^ Ji[i];
end
TB23_hs = teta * 900;
TB23_hs
end
#***********************************************************************************************************
#*5 Transport properties
#***********************************************************************************************************
#*5.1 Viscosity (IAPWS formulation 1985, Revised 2003)
#***********************************************************************************************************
function my_AllRegions_pT( p, T)
h0 = [0.5132047, 0.3205656, 0, 0, -0.7782567, 0.1885447];
h1 = [0.2151778, 0.7317883, 1.241044, 1.476783, 0, 0];
h2 = [-0.2818107, -1.070786, -1.263184, 0, 0, 0];
h3 = [0.1778064, 0.460504, 0.2340379, -0.4924179, 0, 0];
h4 = [-0.0417661, 0, 0, 0.1600435, 0, 0];
h5 = [0, -0.01578386, 0, 0, 0, 0];
h6 = [0, 0, 0, -0.003629481, 0, 0];
#Calcualte density.
region=region_pT(p,T)
if region ==1
rho = 1 / v1_pT(p, T);
elseif region == 2
rho = 1 / v2_pT(p, T);
elseif region == 3
hs = h3_pT(p, T);
rho = 1 / v3_ph(p, hs);
elseif region == 4
rho = NaN;
elseif region == 5
rho = 1 / v5_pT(p, T);
else
my_AllRegions_pT = NaN;
return my_AllRegions_pT
end
rhos = rho / 317.763;
Ts = T / 647.226;
ps = p / 22.115;
#Check valid area
if T > 900 + 273.15 || (T > 600 + 273.15 && p > 300) || (T > 150 + 273.15 && p > 350) || p > 500
my_AllRegions_pT = NaN;
return my_AllRegions_pT
end
my0 = Ts ^ 0.5 / (1 + 0.978197 / Ts + 0.579829 / (Ts ^ 2) - 0.202354 / (Ts ^ 3));
Sum = 0;
for i = 0 : 5
Sum = Sum + h0[i+1] * (1 / Ts - 1) ^ i + h1[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 1 + h2[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 2 + h3[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 3 + h4[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 4 + h5[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 5 + h6[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 6;
end
my1 = exp(rhos * Sum);
mys = my0 * my1;
my_AllRegions_pT = mys * 0.000055071;
my_AllRegions_pT
end
function my_AllRegions_ph(p,h)
h0 = [0.5132047, 0.3205656, 0, 0, -0.7782567, 0.1885447];
h1 = [0.2151778, 0.7317883, 1.241044, 1.476783, 0, 0];
h2 = [-0.2818107, -1.070786, -1.263184, 0, 0, 0];
h3 = [0.1778064, 0.460504, 0.2340379, -0.4924179, 0, 0];
h4 = [-0.0417661, 0, 0, 0.1600435, 0, 0];
h5 = [0, -0.01578386, 0, 0, 0, 0];
h6 = [0, 0, 0, -0.003629481, 0, 0];
#Calcualte density.
region = region_ph(p, h)
if region == 1
Ts = T1_ph(p, h);
T = Ts;
rho = 1 / v1_pT(p, Ts);
elseif region == 2
Ts = T2_ph(p, h);
T = Ts;
rho = 1 / v2_pT(p, Ts);
elseif region == 3
rho = 1 / v3_ph(p, h);
T = T3_ph(p, h);
elseif region == 4
xs = x4_ph(p, h);
if p < 16.529
v4v = v2_pT(p, T4_p(p));
v4L = v1_pT(p, T4_p(p));
else
v4v = v3_ph(p, h4V_p(p));
v4L = v3_ph(p, h4L_p(p));
end
rho = 1 / (xs * v4v + (1 - xs) * v4L);
T = T4_p(p);
elseif region == 5
Ts = T5_ph(p, h);
T = Ts;
rho = 1 / v5_pT(p, Ts);
else
my_AllRegions_ph = NaN;
return my_AllRegions_ph
end
rhos = rho / 317.763;
Ts = T / 647.226;
ps = p / 22.115;
#Check valid area
if T > 900 + 273.15 || (T > 600 + 273.15 && p > 300) || (T > 150 + 273.15 && p > 350) || p > 500
my_AllRegions_ph = NaN;
return my_AllRegions_ph
end
my0 = Ts ^ 0.5 / (1 + 0.978197 / Ts + 0.579829 / (Ts ^ 2) - 0.202354 / (Ts ^ 3));
Sum = 0;
for i = 0 : 5
Sum = Sum + h0[i+1] * (1 / Ts - 1) ^ i + h1[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 1 + h2[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 2 + h3[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 3 + h4[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 4 + h5[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 5 + h6[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 6;
end
my1 = exp(rhos * Sum);
mys = my0 * my1;
my_AllRegions_ph = mys * 0.000055071;
my_AllRegions_ph
end
#***********************************************************************************************************
#*5.2 Thermal Conductivity (IAPWS formulation 1985)
function tc_ptrho( p, T, rho)
#Revised release on the IAPWS formulation 1985 for the Thermal Conductivity of ordinary water
#IAPWS September 1998
#Page 8
#ver2.6 Start corrected bug
if T < 273.15
tc_ptrho = NaN; #Out of range of validity (para. B4)
return
elseif T < 500 + 273.15
if p > 100
tc_ptrho = NaN; #Out of range of validity (para. B4)
return tc_ptrho
end
elseif T <= 650 + 273.15
if p > 70
tc_ptrho = NaN; #Out of range of validity (para. B4)
return tc_ptrho
end
else T <= 800 + 273.15
if p > 40
tc_ptrho = NaN; #Out of range of validity (para. B4)
return tc_ptrho
end
end
#ver2.6 End corrected bug
T = T / 647.26;
rho = rho / 317.7;
tc0 = T ^ 0.5 * (0.0102811 + 0.0299621 * T + 0.0156146 * T ^ 2 - 0.00422464 * T ^ 3);
tc1 = -0.39707 + 0.400302 * rho + 1.06 * exp(-0.171587 * (rho + 2.39219) ^ 2);
dT = abs(T - 1) + 0.00308976;
Q = 2 + 0.0822994 / dT ^ (3 / 5);
if T >= 1
s = 1 / dT;
else
s = 10.0932 / dT ^ (3 / 5);
end
tc2 = (0.0701309 / T ^ 10 + 0.011852) * rho ^ (9 / 5) * exp(0.642857 * (1 - rho ^ (14 / 5))) + 0.00169937 * s * rho ^ Q * exp((Q / (1 + Q)) * (1 - rho ^ (1 + Q))) - 1.02 * exp(-4.11717 * T ^ (3 / 2) - 6.17937 / rho ^ 5);
tc_ptrho = tc0 + tc1 + tc2;
tc_ptrho
end
#***********************************************************************************************************
#5.3 Surface Tension
function Surface_Tension_T(T)
#IAPWS Release on Surface Tension of Ordinary Water Substance,
#September 1994
tc = 647.096; #K
B = 0.2358; #N/m
bb = -0.625;
my = 1.256;
if T < 0.01 || T > tc
Surface_Tension_T = NaN; #"Out of valid region"
return Surface_Tension_T
end
tau = 1 - T / tc;
Surface_Tension_T = B * tau ^ my * (1 + bb * tau);
Surface_Tension_T
end
#***********************************************************************************************************
#*6 Units *
#***********************************************************************************************************
function toSIunit_p( Ins )
#Translate bar to MPa
toSIunit_p = Ins / 10;
toSIunit_p
end
function fromSIunit_p( Ins )
#Translate bar to MPa
fromSIunit_p = Ins * 10;
fromSIunit_p
end
function toSIunit_T( Ins )
#Translate degC to Kelvon
toSIunit_T = Ins + 273.15;
toSIunit_T
end
function fromSIunit_T( Ins )
#Translate Kelvin to degC
fromSIunit_T = Ins - 273.15;
fromSIunit_T
end
function toSIunit_h( Ins )
toSIunit_h = Ins;
toSIunit_h
end
function fromSIunit_h( Ins )
fromSIunit_h = Ins;
fromSIunit_h
end
function toSIunit_v( Ins )
toSIunit_v = Ins;
toSIunit_v
end
function fromSIunit_v( Ins )
fromSIunit_v = Ins;
fromSIunit_v
end
function toSIunit_s( Ins )
toSIunit_s = Ins;
toSIunit_s
end
function fromSIunit_s( Ins )
fromSIunit_s = Ins;
fromSIunit_s
end
function toSIunit_u( Ins )
toSIunit_u = Ins;
toSIunit_u
end
function fromSIunit_u( Ins )
fromSIunit_u = Ins;
fromSIunit_u
end
function toSIunit_Cp( Ins )
toSIunit_Cp = Ins;
toSIunit_Cp
end
function fromSIunit_Cp( Ins )
fromSIunit_Cp = Ins;
fromSIunit_Cp
end
function toSIunit_Cv( Ins )
toSIunit_Cv = Ins;
toSIunit_Cv
end
function fromSIunit_Cv( Ins )
fromSIunit_Cv = Ins;
fromSIunit_Cv
end
function toSIunit_w( Ins )
toSIunit_w = Ins;
toSIunit_w
end
function fromSIunit_w( Ins )
fromSIunit_w = Ins;
fromSIunit_w
end
function toSIunit_tc( Ins )
toSIunit_tc = Ins;
toSIunit_tc
end
function fromSIunit_tc( Ins )
fromSIunit_tc = Ins;
fromSIunit_tc
end
function toSIunit_st( Ins )
toSIunit_st = Ins;
toSIunit_st
end
function fromSIunit_st( Ins )
fromSIunit_st = Ins;
fromSIunit_st
end
function toSIunit_x( Ins )
toSIunit_x = Ins;
toSIunit_x
end
function fromSIunit_x( Ins )
fromSIunit_x = Ins;
fromSIunit_x
end
function toSIunit_vx( Ins )
toSIunit_vx = Ins;
toSIunit_vx
end
function fromSIunit_vx( Ins )
fromSIunit_vx = Ins;
fromSIunit_vx
end
function toSIunit_my( Ins )
toSIunit_my = Ins;
toSIunit_my
end
function fromSIunit_my( Ins )
fromSIunit_my = Ins;
fromSIunit_my
end
#***********************************************************************************************************
#*7 Verification *
#***********************************************************************************************************
function check()
err=0;
#*********************************************************************************************************
#* 7.1 Verifiy region 1
#IF-97 Table 5, Page 9
p=[30/10,800/10,30/10];
T=[300,300,500];
Fun=[:v1_pT,:h1_pT,:u1_pT,:s1_pT,:Cp1_pT,:w1_pT];
IF97=[0.00100215168 0.000971180894 0.001202418;
115.331273 184.142828 975.542239;
112.324818 106.448356 971.934985;
0.392294792 0.368563852 2.58041912;
4.17301218 4.01008987 4.65580682;
1507.73921 1634.69054 1240.71337];
R1=zeros(6,3);
for i=1:3
for j=1:6
ex=:($(Fun(j))(p[$i],T[$i]))
R1[j,i]=eval(ex);
end
end
Region1_error=abs((R1-IF97)./IF97)
err=err+sum(sum(Region1_error>1E-8))
#IF-97 Table 7, Page 11
p=[30/10,800/10,800/10];
h=[500,500,1500];
IF97=[391.798509,378.108626,611.041229];
R1=zeros(1,3);
for i=1:3
R1[i]=T1_ph(p[i],h[i]);
end
T1_ph_error=abs((R1-IF97)./IF97)
err=err+sum(sum(T1_ph_error>1E-8))
#IF-97 Table 9, Page 12
p=[30/10,800/10,800/10];
s=[0.5,0.5,3];
IF97=[307.842258,309.979785,565.899909];
R1=zeros(1,3);
for i=1:3
R1[i]=T1_ps(p[i],s[i]);
end
T1_ps_error=abs((R1-IF97)./IF97)
err=err+sum(sum(T1_ps_error>1E-8))
#Supplementary Release on Backward Equations
#for Pressure as a Function of Enthalpy and Entropy p(h,s)
#Table 3, Page 6
h=[0.001,90,1500];
s=[0,0,3.4];
IF97=[0.0009800980612,91.929547272,58.68294423];
R1=zeros(1,3);
for i=1:3
R1[i]=p1_hs(h[i],s[i]);
end
p1_hs_error=abs((R1-IF97)./IF97)
err=err+sum(sum(p1_hs_error>1E-8))
#*********************************************************************************************************
#* 7.2 Verifiy region 2
# IF-97 Table 15, Page 17
p=[0.035/10,0.035/10,300/10];
T=[300,700,700];
Fun=[:v2_pT,:h2_pT,:u2_pT,:s2_pT,:Cp2_pT,:w2_pT];
IF97=[39.4913866 92.3015898 0.00542946619;
2549.91145 3335.68375 2631.49474;
2411.6916 3012.62819 2468.61076;
8.52238967 10.1749996 5.17540298;
1.91300162 2.08141274 10.3505092;
427.920172 644.289068 480.386523];
R2=zeros(6,3);
for i=1:3
for j=1:6
ex=:($(Fun(i))(p[$i],T[$i]))
R2[j,i]=eval(ex);
end
end
Region2_error=abs((R2-IF97)./IF97)
err=err+sum(sum(Region2_error>1E-8))
#IF-97 Table 24, Page 25
p=[0.01/10,30/10,30/10,50/10,50/10,250/10,400/10,600/10,600/10];
h=[3000,3000,4000,3500,4000,3500,2700,2700,3200];
IF97=[534.433241,575.37337,1010.77577,801.299102,1015.31583,875.279054,743.056411,791.137067,882.75686];
R2=zeros(1,9);
for i=1:9
R2[i]=T2_ph(p[i],h[i]);
end
T2_ph_error=abs((R2-IF97)./IF97)
err=err+sum(sum(T2_ph_error>1E-8))
#IF-97 Table 29, Page 29
p=[1/10,1/10,25/10,80/10,80/10,900/10,200/10,800/10,800/10];
s=[7.5,8,8,6,7.5,6,5.75,5.25,5.75];
IF97=[399.517097,514.127081,1039.84917,600.48404,1064.95556,1038.01126,697.992849,854.011484,949.017998];
R2=zeros(1,9);
for i=1:9
R2[i]=T2_ps(p[i],s[i]);
end
T2_ps_error=abs((R2-IF97)./IF97)
err=err+sum(sum(T2_ps_error>1E-8))
#Supplementary Release on Backward Equations for Pressure as a Function of Enthalpy and Entropy p(h,s)
#Table 3, Page 6
h=[2800,2800,4100,2800,3600,3600,2800,2800,3400];
s=[6.5,9.5,9.5,6,6,7,5.1,5.8,5.8];
IF97=[1.371012767,0.001879743844,0.1024788997,4.793911442,83.95519209,7.527161441,94.3920206,8.414574124,83.76903879];
R2=zeros(1,9);
for i=1:9
R2[i]=p2_hs(h[i],s[i]);
end
p2_hs_error=abs((R2-IF97)./IF97)
err=err+sum(sum(p2_hs_error>1E-8))
#*********************************************************************************************************
#* 7.3 Verifiy region 3
# IF-97 Table 33, Page 32
T=[650,650,750];
rho=[500,200,500];
Fun=[:p3_rhoT,:h3_rhoT,:u3_rhoT,:s3_rhoT,:Cp3_rhoT,:w3_rhoT];
IF97=[25.5837018 22.2930643 78.3095639;
1863.43019 2375.12401 2258.68845;
1812.26279 2263.65868 2102.06932;
4.05427273 4.85438792 4.46971906;
13.8935717 44.6579342 6.34165359;
502.005554 383.444594 760.696041];
R3=zeros(6,3);
for i=1:3
for j=1:6
R3[j,i]=eval(:($(Fun(i))(rho[$i],T[$i])));
end
end
Region3_error=abs((R3-IF97)./IF97)
err=err+sum(sum(Region3_error>1E-8))
#T3_ph
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
h=[1700,2000,2100,2500,2400,2700];
IF97=[629.3083892,690.5718338,733.6163014,641.8418053,735.1848618,842.0460876];
R3=zeros(1,6);
for i=1:6
R3[i]=T3_ph(p[i],h[i]);
end
T3_ph_error=abs((R3-IF97)./IF97)
err=err+sum(sum(T3_ph_error>1E-8))
#v3_ph
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
h=[1700,2000,2100,2500,2400,2700];
IF97=[0.001749903962,0.001908139035,0.001676229776,0.006670547043,0.0028012445,0.002404234998];
R3=zeros(1,6);
for i=1:6
R3[i]=v3_ph(p[i],h[i]);
end
v3_ph_error=abs((R3-IF97)./IF97)
err=err+sum(sum(v3_ph_error>1E-7))
#T3_ps
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
s=[3.7,3.5,4,5,4.5,5];
IF97=[620.8841563,618.1549029,705.6880237,640.1176443,716.3687517,847.4332825];
R3=zeros(1,6);
for i=1:6
R3[i]=T3_ps(p[i],s[i]);
end
T3_ps_error=abs((R3-IF97)./IF97)
err=err+sum(sum(T3_ps_error>1E-8))
#v3_ps
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
s=[3.7,3.5,4,5,4.5,5];
IF97=[0.001639890984,0.001423030205,0.001555893131,0.006262101987,0.002332634294,0.002449610757];
R3=zeros(1,6);
for i=1:6
R3[i]=v3_ps(p[i],s[i]);
end
v3_ps_error=abs((R3-IF97)./IF97)
err=err+sum(sum(v3_ps_error>1E-8))
#p3_hs
h=[1700,2000,2100,2500,2400,2700];
s=[3.8,4.2,4.3,5.1,4.7,5];
IF97=[25.55703246,45.40873468,60.7812334,17.20612413,63.63924887,88.39043281];
R3=zeros(1,6);
for i=1:6
R3[i]=p3_hs(h[i],s[i]);
end
p3_hs_error=abs((R3-IF97)./IF97)
err=err+sum(sum(p3_hs_error>1E-8))
#h3_pT (Iteration)
p=[255.83702,222.93064,783.09564]./10;
T=[650,650,750];
IF97=[1863.271389,2375.696155,2258.626582];
R3=zeros(1,3);
for i=1:3
R3[i]=h3_pT(p[i],T[i]);
end
h3_pT_error=abs((R3-IF97)./IF97)
err=err+sum(sum(h3_pT_error>1E-6)) #Decimals in IF97
#*********************************************************************************************************
#* 7.4 Verifiy region 4
#Saturation pressure, If97, Table 35, Page 34
T=[300,500,600];
IF97=[0.0353658941, 26.3889776, 123.443146]/10;
R3=zeros(1,3);
for i=1:3
R3[i]=p4_T(T[i]);
end
p4_t_error=abs((R3-IF97)./IF97)
err=err+sum(sum( p4_t_error>1E-7))
T=[1,10,100]/10;
IF97=[372.755919,453.035632,584.149488];
R3=zeros(1,3);
for i=1:3
R3[i]=T4_p(T[i]);
end
T4_p_error=abs((R3-IF97)./IF97)
err=err+sum(sum( T4_p_error>1E-7))
s=[1,2,3,3.8,4,4.2,7,8,9,5.5,5,4.5];
IF97=[308.5509647,700.6304472,1198.359754,1685.025565,1816.891476,1949.352563,2723.729985,2599.04721,2511.861477,2687.69385,2451.623609,2144.360448];
R3=zeros(1,12);
for i=1:12
R3[i]=h4_s(s[i]);
end
h4_s_error=abs((R3-IF97)./IF97)
err=err+sum(sum( h4_s_error>1E-7))
#*********************************************************************************************************
#* 7.5 Verifiy region 5
# IF-97 Table 42, Page 39
T=[1500,1500,2000];
p=[5,80,80]/10;
Fun=[:v5_pT,:h5_pT,:u5_pT,:s5_pT,:Cp5_pT,:w5_pT];
IF97=[1.38455354 0.0865156616 0.115743146;
5219.76332 5206.09634 6583.80291;
4527.48654 4513.97105 5657.85774;
9.65408431 8.36546724 9.15671044;
2.61610228 2.64453866 2.8530675;
917.071933 919.708859 1054.35806];
R5=zeros(6,3);
for i=1:3
for j=1:6
R5[j,i]=eval(:($(Fun(j))(p[$i],T[$i])));
end
end
Region5_error=abs((R5-IF97)./IF97)
err=err+sum(sum(Region5_error>1E-8))
#T5_ph (Iteration)
p=[0.5,8,8];
h=[5219.76331549428,5206.09634477373,6583.80290533381];
IF97=[1500,1500,2000];
R5=zeros(1,3);
for i=1:3
R5[i]=T5_ph(p[i],h[i]);
end
T5_ph_error=abs((R5-IF97)./IF97)
err=err+sum(sum(T5_ph_error>1E-7)) #Decimals in IF97
#T5_ps (Iteration)
p=[0.5,8,8];
s=[9.65408430982588,8.36546724495503,9.15671044273249];
IF97=[1500,1500,2000];
R5=zeros(1,3);
for i=1:3
R5[i]=T5_ps(p[i],s[i]);
end
T5_ps_error=abs((R5-IF97)./IF97)
err=err+sum(sum(T5_ps_error>1E-4)) #Decimals in IF97
end
#*********************************************************************************************************
#* 7.6 Verifiy calling funtions
#
#fun=["Tsat_p","T_ph","T_ps","T_hs","psat_T","p_hs","hV_p","hL_p","hV_T","hL_T","h_pT","h_ps","h_px","h_prho","h_Tx","vV_p","vL_p","vV_T","vL_T","v_pT","v_ph","v_ps","rhoV_p","rhoL_p","rhoV_T","rhoL_T","rho_pT","rho_ph","rho_ps","sV_p","sL_p","sV_T","sL_T","s_pT","s_ph","uV_p","uL_p","uV_T","uL_T","u_pT","u_ph","u_ps","CpV_p","CpL_p","CpV_T","CpL_T","Cp_pT","Cp_ph","Cp_ps","CvV_p","CvL_p","CvV_T","CvL_T","Cv_pT","Cv_ph","Cv_ps","wV_p","wL_p","wV_T","wL_T","w_pT","w_ph","w_ps","my_pT","my_ph","my_ps","tcL_p","tcV_p","tcL_T","tcV_T","tc_pT","tc_ph","tc_hs","st_T","st_p","x_ph","x_ps","vx_ph","vx_ps"];
#In1=["1","1","1","100","100","84","1","1","100","100","1","1","1","1","100","1","1","100","100","1","1","1","1","1","100","100","1","1","1","0.006117","0.0061171","0.0001","100","1","1","1","1","100","100","1","1","1","1","1","100","100","1","1","1","1","1","100","100","1","1","1","1","1","100","100","1","1","1","1","1","1","1","1","25","25","1","1","100","100","1","1","1","1","1"];
#In2=["0","100","1","0.2","0","0.296","0","0","0","0","20","1","0.5","2","0.5","0","0","0","0","100","1000","5","0","0","0","0","100","1000","1","0","0","0","0","20","84.01181117","0","0","0","0","100","1000","1","0","0","0","0","100","200","1","0","0","0","0","100","200","1","0","0","0","0","100","200","1","100","100","1","0","0","0","0","25","100","0.34","0","0","1000","4","418","4"];
#Control=["99.60591861","23.84481908","73.70859421","13.84933511","1.014179779","2.295498269","2674.949641","417.4364858","2675.572029","419.099155","84.01181117","308.6107171","1546.193063","1082.773391","1547.33559210927","1.694022523","0.001043148","1.671860601","0.001043455","1.695959407","0.437925658","1.03463539","0.590310924","958.6368897","0.598135993","958.3542773","0.589636754","2.283492601","975.6236788","9.155465556","1.8359E-05","9.155756716","1.307014328","0.296482921","0.296813845","2505.547389","417.332171","2506.015308","418.9933299","2506.171426","956.2074342","308.5082185","2.075938025","4.216149431","2.077491868","4.216645119","2.074108555","4.17913573168802","4.190607038","1.552696979","3.769699683","1.553698696","3.76770022","1.551397249","4.035176364","3.902919468","472.0541571","1545.451948","472.2559492","1545.092249","472.3375235","1542.682475","1557.8585","1.22704E-05","0.000914003770302108","0.000384222","0.677593822","0.024753668","0.607458162","0.018326723","0.607509806","0.605710062","0.606283124","0.0589118685876641","0.058987784","0.258055424","0.445397961","0.288493093","0.999233827"];
#
#for i=1:length(fun)
#
# T=:($(fun[i])(parse(Float64,$(In1[i])),parse(Float64,$(In2[i]))));
# Res=eval(T);
# Error=(Res-(parse(Float64,Control[i])))/parse(Float64,Control[i]);
# #Check=[T,"=",num2str(Res)," - (Control)",char(Control[i]),"=",num2str(Error)]
# if Error>1E-5
# err=err+1;
# error("To large error")
# end
#end
phc(p,h)=Cp_ph(p,h)
phg(p,h)=Cp_ph(p,h)/Cv_ph(p,h)
phq(p,h)=x_ph(p,h)
phs(p,h)=s_ph(p,h)
pht(p,h)=T_ph(p,h)
phv(p,h)=v_ph(p,h)
phw(p,h)=w_ph(p,h)
phm(p,h)=my_ph(p,h)
pqc(p,q)=(1.0-q)*CpL_p(p)+q*CpV_p(p)
pqh(p,q)=(1.0-q)*hL_p(p)+q*hV_p(p)
pqk(p,q)=(1.0-q)*tcL_p(p)+q*tcV_p(p)
pqg(p,q)=(1.0-q)*CpL_p(p)/CvL_p(p)+q*CpV_p(p)/CvV_p(p)
pqs(p,q)=(1.0-q)*sL_p(p)+q*sV_p(p)
pqv(p,q)=(1.0-q)*vL_p(p)+q*vV_p(p)
pqw(p,q)=(1.0-q)*wL_p(p)+q*wV_p(p)
pqm(p,q)=(1.0-q)*my_ph(p,hL_p(p))+q*my_ph(p,hV_p(p))
psc(p,s)=Cp_ps(p,s)
psg(p,s)=Cp_ps(p,s)/Cv_ps(p,s)
psh(p,s)=h_ps(p,s)
psq(p,s)=x_ps(p,s)
pst(p,s)=T_ps(p,s)
psv(p,s)=v_ps(p,s)
psw(p,s)=w_ps(p,s)
psm(p,s)=my_ps(p,s)
pt(p)=Tsat_p(p)
ptc(p,t)=Cp_pT(p,t)
ptg(p,t)=Cp_pT(p,t)/Cv_pT(p,t)
pth(p,t)=h_pT(p,t)
ptk(p,t)=tc_pT(p,t)
ptm(p,t)=my_pT(p,t)
pts(p,t)=s_pT(p,t)
ptv(p,t)=v_pT(p,t)
ptw(p,t)=w_pT(p,t)
tp(t)=psat_T(t)
tqc(t,q)=(1.0-q)*CpL_T(t)+q*CpV_T(t)
tqg(t,q)=(1.0-q)*CpL_T(t)/CvL_T(t)+q*CpV_T(t)/CvV_T(t)
tqh(t,q)=(1.0-q)*hL_T(t)+q*hV_T(t)
tqk(t,q)=(1.0-q)*tcL_T(t)+q*tcV_T(t)
tqs(t,q)=(1.0-q)*sL_T(t)+q*sV_T(t)
tqv(t,q)=(1.0-q)*vL_T(t)+q*vV_T(t)
tqw(t,q)=(1.0-q)*wL_T(t)+q*wV_T(t)
hst(h,s)=T_hs(h,s)
hsp(h,s)=p_hs(h,s)
pqu(p,q)=(1.0-q)*uL_p(p)+q*uV_p(p)
tqu(t,q)=(1.0-q)*uL_T(t)+q*uV_T(t)
ptu(p,t)=u_pT(p,t)
phu(p,h)=u_ph(p,h)
psu(p,h)=s_ph(p,h)
hsk(h,s)=tc_hs(h,s)
pvh(p,v)=h_prho(p,1/v)
hvp(h,v)=p_hrho(h,1/v)
export phc,phg,phq,phs,pht,phv,phw,phm,pqc,pqh,pqk,pqg,pqs,pqv,pqw,pqm,psc,psg,psh,psq,pst,psv,psw,psm
export pt,ptc,ptg,pth,ptk,ptm,pts,ptv,ptw,tp,tqc,tqg,tqh,tqk,tqs,tqv,tqw,hst,pqu,tqu,ptu,phu,psu,hsk,pvh,hvp
export Tsat_p,T_ph,T_ps,T_hs,psat_T,p_hs,hV_p,hL_p,hV_T,hL_T,h_pT,h_ps,h_px,h_prho,h_Tx,vV_p,vL_p,vV_T,vL_T,v_pT,v_ph,v_ps
export rhoV_p,rhoL_p,rhoV_T,rhoL_T,rho_pT,rho_ph,rho_ps,sV_p,sL_p,sV_T,sL_T,s_pT,s_ph,uV_p,uL_p,uV_T,uL_T,u_pT,u_ph,u_ps,CpV_p
export CpL_p,CpV_T,CpL_T,Cp_pT,Cp_ph,Cp_ps,CvV_p,CvL_p,CvV_T,CvL_T,Cv_pT,Cv_ph,Cv_ps,wV_p,wL_p,wV_T,wL_T,w_pT,w_ph,w_ps,my_pT,my_ph,my_ps
export tcL_p,tcV_p,tcL_T,tcV_T,tc_pT,tc_ph,tc_hs,st_T,st_p,x_ph,x_ps,vx_ph,vx_ps;
end
| XSteam | https://github.com/hzgzh/XSteam.jl.git |
|
[
"MIT"
] | 0.3.0 | bfe2782c68eadd44e719a00bbaf96c83b921e4e1 | docs | 9147 | ## XSteam for julia
Immigrate By hzgzh Date: 2019-9-29
X Steam for julia is a implementation of the IAPWS IF97 standard formulation immigrate from XSteam for matlab By Magnus Holmgren, www.x-eng.com
The steam tables are free and provided as is.
We take no responsibilities for any errors in the code or damage thereby.
You are free to use, modify and distribute the code as long as authorship is properly acknowledged.
Please notify me at [email protected] if the code is used in commercial applications. It
provides accurate data for water and steam and mixtures of water and steam properties from
0 - 1000 bar and from 0 - 2000 deg C.
The initial units of XSteam are SI units as denoted in this document. All functions however
call unit conversion functions so the units can be easily changed. A text file with unit
conversion functions for English units are enclosed with the file.
### Usage
The XSteam code are used in the following way:
* Example: rho_pT(1,200) returns the density at 1 bar and 200°C.
* winsteam syntax pth(1,200) returns the entalpy at 1bar and 200°C
### Introduction
X Steam for matlab is a implementation of the IAPWS IF97 standard formulation. It
provides accurate thermo hydraulic data for water and steam and mixtures of water and
steam in the region:
* 0°C < temperature < 2000°C for
* 0.00611 bar a < pressure < 100 bar a
* 0°C < temperature < 1000°C for
* 0.00611 bar a < pressure < 1000 bar a
For accuracy and further information on IAPWS IF97 formulation, se homepage of the
international association for properties of water and steam (www.iapws.org).
### Unit
|Notation|Quantity|Unit|
|-|-|-|
|T|Temperature|°C|
|p|Pressure|bar|
|h|Enthalpy|kJ/kg|
|v|Specific volume|$m^3/kg$|
|rho|Density|$kg/m^3$|
|s|Specific entropy|kJ/(kg °C)|
|u|Specific internal energy|kJ/kg|
|Cp|Specific isobaric heat capacity|kJ/(kg °C)|
|Cv|Specific isochoric heat capacity|kJ/(kg °C)|
|w|Speed of sound|m/s|
|my|Viscosity|Pa s|
|tc|Thermal Conductivity|W/(m °C)|
|st|Surface Tension|N/m|
|x or q|Vapour fraction (0-1)|-|
|vx|Vapour Volume Fraction (0-1)|-|
## XSteam functions
### Temperature
|Function|In1|In2|Out|
|-|-|-|-|
|Tsat_p or pt|p||Saturation temperature|
|T_ph or pht|p|H|Temperture as a function of pressure and enthalpy|
|T_ps or pst|p|S|Temperture as a function of pressure and entropy|
|T_hs or hst|h|S|Temperture as a function of enthalpy and entropy|
### Pressure
|Function|In1|In2|Out|
|-|-|-|-|
|psat_T or tp|T||Saturation pressure|
|p_hs or hsp|h|s|Pressure as a function of h and s.|
|p_hrho or hvp|h|rho|Pressure as a function of h and rho (density) or Specific volume .Very unaccurate for solid water region since it's almost incompressible!|
### Enthalpy
|Function|In1|In2|Out|
|-|-|-|-|
|hV_p or pqh(p,1)|p||Saturated vapour enthalpy|
|hL_p or pqh(p,0)|p||Saturated liquid enthalpy|
|hV_T or tqh(t,1)|T||Saturated vapour enthalpy|
|hL_T or tqh(t,0)|T||Saturated liquid enthalpy|
|h_pT or pth| p| T| Entalpy as a function of pressure and temperature.|
|h_ps or psh| p| s| Entalpy as a function of pressure and entropy.|
|h_px or pqh| p| x| Entalpy as a function of pressure and vapour fraction|
|h_Tx or tqh| T| X| Entalpy as a function of temperature and vapour fraction|
|h_prho or pvh| p| rho|Entalpy as a function of pressure and density or Specific volume. Observe for low temperatures (liquid) this equation has 2 solutions.(Not valid!!)|
### Specific volume
|Function|In1|In2|Out|
|-|-|-|-|
|vV_p or pqv(p,1)| p|| Saturated vapour volume|
|vL_p or pqv(p,0)| p|| Saturated liquid volume|
|vV_T or tqv(p,1)| T|| Saturated vapour volume|
|vL_T or tqv(p,0)| T|| Saturated liquid volume|
|v_pT or ptv| p| T|Specific volume as a function of pressure and temperature.|
|v_ph or phv| p| h| Specific volume as a function of pressure and enthalpy|
|v_ps or psv| p| s| Specific volume as a function of pressure and entropy.|
### Density
|Function|In1|In2|Out|
|-|-|-|-|
|rhoV_p or 1/pqv(p,1)| p|| Saturated vapour density|
|rhoL_p or 1/pqv(p,0)| p|| Saturated liquid density|
|rhoV_T or 1/tqv(t,1)| T|| Saturated vapour density|
|rhoL_T or 1/tqv(t,0)| T|| Saturated liquid density|
|rho_pT or 1/ptv| p| T| Density as a function of pressure and temperature.|
|rho_ph or 1/phv| p| h| Density as a function of pressure and enthalpy|
|rho_ps or 1/psv| p| s| Density as a function of pressure and entropy.|
### Specific entropy
|Function|In1|In2|Out|
|-|-|-|-|
|sV_p or pqs(p,1)| p|| Saturated vapour entropy|
|sL_p or pqs(p,0)| p|| Saturated liquid entropy|
|sV_T or tqs(p,1)| T|| Saturated vapour entropy|
|sL_T or tqs(p,0)| T|| Saturated liquid entropy|
|s_pT or pts|p| T|Specific entropy as a function of pressure and temperature(Returns saturated vapour entalpy if mixture.)|
|s_ph or phs| p| h|Specific entropy as a function of pressure and enthalpy|
### Specific internal energy
|Function|In1|In2|Out|
|-|-|-|-|
|uV_p or pqu(p,1)| p|| Saturated vapour internal energy|
|uL_p or pqu(p,0)| p|| Saturated liquid internal energy|
|uV_T or tqu(t,1)| T|| Saturated vapour internal energy|
|uL_T or tqu(t,0)| T|| Saturated liquid internal energy|
|u_pT or ptu|p| T|Specific internal energy as a function of pressure and temperature.|
|u_ph or phu|p| h|Specific internal energy as a function of pressure and enthalpy|
|u_ps or psu|p| s|Specific internal energy as a function of pressure and entropy.|
### Specific isobaric heat capacity
|Function|In1|In2|Out|
|-|-|-|-|
|CpV_p or pqc(p,1)| p||Saturated vapour heat capacity|
|CpL_p or pqc(p,0)| p|| Saturated liquid heat capacity|
|CpV_T or tqc(t,1)| T|| Saturated vapour heat capacity|
|CpL_T or tqc(t,0)| T|| Saturated liquid heat capacity|
|Cp_pT or ptc|p| T|Specific isobaric heat capacity as a function of pressure and temperature.|
|Cp_ph or phc|p| h|Specific isobaric heat capacity as a function of pressure and enthalpy|
|Cp_ps or psc|p| s|Specific isobaric heat capacity as a function of pressure and entropy.|
### Specific isochoric heat capacity
|Function|In1|In2|Out|
|-|-|-|-|
|CvV_p| p|| Saturated vapour isochoric heat capacity|
|CvL_p| p|| Saturated liquid isochoric heat capacity|
|CvV_T| T|| Saturated vapour isochoric heat capacity|
|CvL_T| T|| Saturated liquid isochoric heat capacity|
|Cv_pT|p| T|Specific isochoric heat capacity as a function of pressure and temperature.|
|Cv_ph|p| h|Specific isochoric heat capacity as a function of pressure and enthalpy|
|Cv_ps|p| s|Specific isochoric heat capacity as a function of pressure and entropy.|
### Speed of sound
|Function|In1|In2|Out|
|-|-|-|-|
|wV_p or pqw(p,1)| p|| Saturated vapour speed of sound|
|wL_p or pqw(p,0)| p|| Saturated liquid speed of sound|
|wV_T or tqw(t,1)| T|| Saturated vapour speed of sound|
|wL_T or tqw(t,0)| T|| Saturated liquid speed of sound|
|w_pT or ptw|p| T|Speed of sound as a function of pressure and temperature.|
|w_ph or phw| p| h| Speed of sound as a function of pressure and enthalpy|
|w_ps or psw| p| s| Speed of sound as a function of pressure and entropy.|
### Viscosity
Viscosity is not part of IAPWS Steam IF97. Equations from "Revised Release on the
IAPWS Formulation 1985 for the Viscosity of Ordinary Water Substance", 2003 are used.
Viscosity in the mixed region (4) is interpolated according to the density. This is not true
since it will be two fases.
|Function|In1|In2|Out|
|-|-|-|-|
|my_pT or ptm| p| T| Viscosity as a function of pressure and temperature.|
|my_ph or phm| p| h| Viscosity as a function of pressure and enthalpy|
|my_ps or psm| p| s| Viscosity as a function of pressure and entropy.|
|pqm|p|q| Viscosity as a function of pressure and quality.|
### Thermal Conductivity
Revised release on the IAPS Formulation 1985 for the Thermal Conductivity of ordinary water substance (IAPWS 1998)
|Function|In1|In2|Out|
|-|-|-|-|
|tcL_p or pqk(p,1)| p|| Saturated vapour thermal conductivity|
|tcV_p or pqk(p,0)| p|| Saturated liquid thermal conductivity|
|tcL_T or tqk(t,1)| T||Saturated vapour thermal conductivity|
|tcV_T or tqk(t,0)| T|| Saturated liquid thermal conductivity|
|tc_pT or ptk|p| T|Thermal conductivity as a function of pressure and temperature.|
|tc_ph or phk|p| h|Thermal conductivity as a function of pressure and enthalpy|
|tc_hs or hsk|h| s| Thermal conductivity as a function of enthalpy and entropy|
### Surface Tension
IAPWS Release on Surface Tension of Ordinary Water Substance,September 1994
|Function|In1|In2|Out|
|-|-|-|-|
|st_T|T||Surface tension for two phase water/steam as a function of T|
|st_p|p||Surface tension for two phase water/steam as a function of T|
### Vapour fraction
|Function|In1|In2|Out|
|-|-|-|-|
|x_ph or phq|p| h|Vapour fraction for two phase water/steam as a function of T|
|x_ps or psq|p| s|Vapour fraction for two phase water/steam as a function of T|
### Vapour Volume Fraction
Observe that vapour volume fraction is very sensitive. Vapour volume is about 1000 times greater than liquid volume and therefore vapour volume fraction gets close to the accurancy of IAPWS IF-97
|Function|In1|In2|Out|
|-|-|-|-|
|vx_ph|p| h|Vapour volume fraction as a function of pressure and enthalpy|
|vx_ps|p| s|Vapour volume fraction as a function of pressure and entropy.|
| XSteam | https://github.com/hzgzh/XSteam.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 935 | using PyCall
# Check devito version and update if necessary
struct DevitoException <: Exception
msg::String
end
pk = try
pyimport("pkg_resources")
catch e
run(PyCall.python_cmd(`-m pip install -U --user --no-cache-dir setuptools`))
pyimport("pkg_resources")
end
################## Devito ##################
# pip command
dvver = "4.8.10"
cmd = PyCall.python_cmd(`-m pip install --user --no-cache-dir devito\[extras,tests\]\>\=$(dvver)`)
try
dv_ver = VersionNumber(split(pk.get_distribution("devito").version, "+")[1])
if dv_ver < VersionNumber(dvver)
@info "Devito version too low, updating to >=$(dvver)"
run(cmd)
end
catch e
@info "Devito not installed, installing with PyCall python"
run(cmd)
end
################## Matplotlib ##################
try
mpl = pyimport("matplotlib")
catch e
run(PyCall.python_cmd(`-m pip install --user --no-cache-dir matplotlib`))
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 165 | using Pkg
Pkg.add(PackageSpec(url="https://github.com/JuliaLang/TOML.jl.git"))
using TOML
for k=keys(TOML.parsefile("./Project.toml")["deps"])
Pkg.add(k)
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1599 | using Documenter, JUDI, Weave
# Convert example to documentation markdown file
ex_path = "$(JUDI.JUDIPATH)/../examples/scripts"
doc_path = "$(JUDI.JUDIPATH)/../docs"
weave("$(ex_path)/modeling_basic_2D.jl"; out_path="$(doc_path)/src/tutorials/quickstart.md", doctype="github")
weave("$(ex_path)/imaging_conditions.jl"; out_path="$(doc_path)/src/tutorials/imaging_conditions.md", doctype="github")
# Create documentation
makedocs(sitename="JUDI documentation",
doctest=false, clean=true,
authors="Mathias Louboutin",
pages = Any[
"Home" => "index.md",
"About" => "about.md",
"Installation" => "installation.md",
"Getting Started" => "basics.md",
"JUDI API" => Any[
"Abstract vectors" => "abstract_vectors.md",
"Data Structures" => "data_structures.md",
"Linear Operators" => "linear_operators.md",
"Preconditioners" => "preconditioners.md",
"Input/Output" => "io.md",
"Helper Functions" => "helper.md"],
"Inversion" => "inversion.md",
"Tutorials" => map(
s -> "tutorials/$(s)",
sort(filter(x->endswith(x, ".md"), readdir(joinpath(@__DIR__, "src/tutorials/"))))),
"Devito backend reference" => "pysource.md"],
format = Documenter.HTML(
# assets = ["assets/slim.css"],
prettyurls = get(ENV, "CI", nothing) == "true"),
)
# Deploy documentation
deploydocs(repo="github.com/slimgroup/JUDI.jl") | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2021 | # Create BP Synthetic data w/ 20 Hz peak frequency and using
# the same geometry as the original data set, but w/o surface
# related multiples.
# Author: Philipp Witte, [email protected]
# Date: May 2018
#
# TO DO
# Set up path where data will be saved
data_path = "/path/to/data/"
using JUDI, SegyIO, JLD, PyPlot
# Load velocity
if !isfile("bp_synthetic_2004_true_velocity.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_true_velocity.jld`)
end
vp = load(join([pwd(), "/bp_synthetic_2004_true_velocity.jld"]))["vp"] / 1f3
# Load density
if !isfile("bp_synthetic_2004_density.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_density.jld`)
end
rho = load(join([pwd(), "/bp_synthetic_2004_density.jld"]))["rho"]
# Load geometry of original BP data set
if !isfile("bp_synthetic_2004_header_geometry.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_header_geometry.jld`)
end
geometry = load(join([pwd(), "/bp_synthetic_2004_header_geometry.jld"]))
# Set up model structure
d = (6.25, 6.25)
o = (0., 0.)
m0 = (1f0 ./ vp).^2
n = size(m0)
model0 = Model(n, d, o, m0; rho=rho)
# Load header geometry from original data set
src_geometry = geometry["src_geometry"]
rec_geometry = geometry["rec_geometry"]
nsrc = geometry["nsrc"]
# Set up source
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.020) # 27 Hz peak frequency
q = judiVector(src_geometry, wavelet)
###################################################################################################
# Save data to disk
opt = Options(limit_m = true,
space_order = 16,
buffer_size = 4000f0,
save_data_to_disk = true,
file_path = data_path,
file_name = "bp_observed_data_")
# Setup operators
F = judiModeling(model0, q.geometry, rec_geometry; options=opt)
# Model data (write to disk)
F*q
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2202 | # RTM of the BP synthetic 2007 data set
# Author: Philipp Witte
# Date: March 2018
#
# TO DO
# Set up path where data will be saved
data_path = "/path/to/data/"
using JUDI, SegyIO, JLD, PyPlot, LinearAlgebra
# Load velocity model
if !isfile("bp_synthetic_2004_migration_velocity.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_migration_velocity.jld`)
end
vp = load(join([pwd(), "/bp_synthetic_2004_migration_velocity.jld"]))["vp"] / 1f3
# Set up model structure
d = (6.25, 6.25)
o = (0., 0.)
m0 = (1f0 ./ vp).^2
n = size(m0)
model0 = Model(n, d, o, m0)
# Scan directory for segy files and create out-of-core data container
container = segy_scan(data_path, "bp_observed_data", ["GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
d_obs = judiVector(container; segy_depth_key = "SourceDepth")
# Set up source
src_geometry = Geometry(container; key = "source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.020) # 27 Hz peak frequency
q = judiVector(src_geometry, wavelet)
# Info structure for linear operators
ntComp = get_computational_nt(src_geometry, d_obs.geometry, model0) # no. of computational time steps
###################################################################################################
# Enable optimal checkpointing
opt = Options(limit_m = true,
buffer_size = 3000f0,
isic = true,
dft_subsampling_factor=8)
# Setup operators
q_dist = generate_distribution(q)
F = judiModeling(model0, q.geometry, d_obs.geometry; options=opt)
J = judiJacobian(F, q)
# Set up random frequencies
nfreq = 10
J.options.frequencies = Array{Any}(undef, d_obs.nsrc)
J.options.dft_subsampling_factor = 8
for k=1:d_obs.nsrc
J.options.frequencies[k] = select_frequencies(q_dist; fmin=0.003, fmax=0.04, nf=nfreq)
end
# Add random noise
d_lin = get_data(d_obs)
for j=1:d_lin.nsrc
noise = randn(Float32, size(d_lin.data[j]))
d_lin.data[j] += (noise/norm(vec(noise), Inf)*0.02f0)
end
# Topmute
Ml = judiDataMute(q.geometry, d_lin.geometry)
d_lin = Ml*d_lin
# RTM
rtm = adjoint(J)*d_lin
save("bp_synethic_2004_rtm_frequency.jld", "rtm", rtm)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3910 | # Least-squares RTM of the BP synthetic 2007 data set
# Author: Philipp Witte
# Date: March 2018
#
# TO DO
# Set up path where data will be saved
data_path = "/path/to/data/"
using JUDI, SegyIO, JLD, PyPlot, JOLI, Random, LinearAlgebra
# Load velocity model(replace with correct paths)
if !isfile("bp_synthetic_2004_migration_velocity.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_migration_velocity.jld`)
end
vp = load(join([pwd(), "/bp_synthetic_2004_migration_velocity.jld"]))["vp"] / 1f3
if !isfile("bp_synthetic_2004_water_bottom.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/bp_synthetic_2004_water_bottom.jld`)
end
water_bottom = load(join([pwd(), "/bp_synthetic_2004_water_bottom.jld"]))["wb"]
# Set up model structure
d = (6.25, 6.25)
o = (0., 0.)
m0 = (1f0 ./ vp).^2
n = size(m0)
model0 = Model(n, d, o, m0)
# Scan directory for segy files and create out-of-core data container
container = segy_scan(data_path, "bp_observed_data", ["GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
d_obs = judiVector(container; segy_depth_key = "SourceDepth")
# Set up source
src_geometry = Geometry(container; key = "source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.020) # 27 Hz peak frequency
q = judiVector(src_geometry, wavelet)
# Info structure for linear operators
ntComp = get_computational_nt(src_geometry, d_obs.geometry, model0) # no. of computational time steps
###################################################################################################
# Set options
opt = Options(limit_m = true,
buffer_size = 3000f0,
isic = true,
dft_subsampling_factor=8)
# Setup operators
F = judiModeling(model0, q.geometry, d_obs.geometry; options=opt)
J = judiJacobian(F, q)
# Right-hand preconditioners
D = judiDepthScaling(model0)
T = judiTopmute(model0.n, (1 .- water_bottom), [])
Mr = D*T
# Left-hand preconditioners
Ml = judiDataMute(q.geometry, d_obs.geometry)
# Linearized Bregman parameters
x = zeros(Float32, prod(model0.n))
z = zeros(Float32, prod(model0.n))
batchsize = 200
niter = 20
nfreq = 20
fval = zeros(Float32, niter)
q_dist = generate_distribution(q)
J.options.frequencies = Array{Any}(undef, d_obs.nsrc)
# Soft thresholding functions and Curvelet transform
soft_thresholding(x::Array{Float64}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float64,lambda), 0.0)
soft_thresholding(x::Array{Float32}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float32,lambda), 0f0)
C = joCurvelet2D(model0.n[1], model0.n[2]; zero_finest=true, DDT=Float32, RDT=Float64)
lambda = []
t = [] # t = 1f-4
# Main loop
for j=1:niter
println("Iteration: ", j)
# Set randomized frequencies
for k=1:d_obs.nsrc
J.options.frequencies[k] = select_frequencies(q_dist; fmin=0.003, fmax=0.04, nf=nfreq)
end
# Select batch and set up left-hand preconditioner
i = randperm(d_obs.nsrc)[1:batchsize]
d_sub = get_data(d_obs[i])
# Compute residual and estimate source
if j > 1
d_pred = J[i]*Mr*x
r = Ml[i]*d_pred - Ml[i]*d_sub
else
r = Ml[i]*d_sub*(-1f0) # skip forward modeling in first iteration
end
# Residual and gradient
g = adjoint(Mr)*adjoint(J[i])*adjoint(Ml[i])*r
# Step size and update variable
fval[j] = .5*norm(r)^2
t = norm(r)^2/norm(g)^2 # divide by 10
println(" Stepsize: ", t)
j==1 && (global lambda = 0.03*norm(C*t*g, Inf)) # estimate thresholding parameter in 1st iteration
# Update variables
global z -= t*g
global x = adjoint(C)*soft_thresholding(C*z, lambda)
# Save snapshot
save(join([path, "/results/splsrtm_freq_iteration_", string(j), ".jld"]), "x", reshape(x, model0.n), "z", reshape(z, model0.n), "t", t, "lambda", lambda, "fval", fval[j])
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3990 | # Example for basic 2D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, [email protected]
# Date: January 2017
#
using JUDI, PyPlot, JLD, SegyIO, LinearAlgebra
# Load Sigsbee model
if !isfile("sigsbee2A_model.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/sigsbee2A_model.jld`)
end
M = load("sigsbee2A_model.jld")
m = M["m"][1200:2200, 150:800]
m0 = M["m0"][1200:2200, 150:800]
dm = M["dm"][1200:2200, 150:800]
n = size(m)
# Setup model structure
model = Model(n, M["d"], M["o"], m)
model0 = Model(n, M["d"], M["o"], m0)
dm = vec(dm)
## Set up receiver geometry
nsrc = 1 # number of sources
nxrec = 1200
xrec = range(700f0, stop=6700f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)
# receiver sampling and recording time
timeR = 8000f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)
## Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell([6800f0])
ysrc = convertToCell([0f0])
zsrc = convertToCell([20f0])
# source sampling and number of time steps
timeS = 8000f0
dtS = 2f0
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
# setup wavelet
f0 = 0.015
wavelet = ricker_wavelet(timeS,dtS,f0)
q = judiVector(srcGeometry,wavelet)
#################################################################################################
opt = Options(isic=false,
save_data_to_disk=false,
optimal_checkpointing=false
)
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model; options=opt)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(srcGeometry)
J = judiJacobian(Pr*F0*Ps', q)
# Set frequencies
q_dist = generate_distribution(q)
J.options.frequencies = Array{Any}(undef, nsrc)
J.options.frequencies[1] = select_frequencies(q_dist; fmin=0.003, fmax=0.04, nf=20)
# Velocity contrast
d_lin1 = J*dm
rtm1 = J'*d_lin1
# Impedance
J.options.isic = true
d_lin2 = J*dm
rtm2 = J'*d_lin2
############################################## Plots ###############################################
# Normalize images
dm1 = rtm1 / norm(rtm1, Inf)
dm2 = rtm2 / norm(rtm2, Inf)
# Plot migration velocity
fig=figure(figsize=(6.66, 5))
s1 = subplot(2, 2, 1)
im1 = imshow(adjoint(sqrt.(1f0 ./ m0)), vmin=1.5, vmax=4.511,cmap="gray", extent=(9.144, 16.764, 6.096, 1.143))
s1[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t1 = title("a)", fontweight="bold", size=10, loc="left")
t1["set_position"]([-.14, 1])
# Plot true image
s2 = subplot(2, 2, 2)
im2 = imshow(adjoint(reshape(dm, n)), vmin=-6e-2, vmax=6e-2,cmap="gray", extent=(9.144, 16.764, 6.096, 1.143))
s2[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t2 = title("b)", fontweight="bold", size=10, loc="left")
t2["set_position"]([-.14, 1])
# RTM image w/ zero-lag cross-correlation imaging condition
s3 = subplot(2, 2, 3)
im3 = imshow(adjoint(reshape(dm1,n)), vmin=-1e-1, vmax=1e-1,cmap="gray", extent=(9.144, 16.764, 6.096, 1.143))
s3[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t3 = title("c)", fontweight="bold", size=10, loc="left")
t3["set_position"]([-.14, 1])
# RTM image w/ inverse-scattering/impedance imaging condition
s4 = subplot(2, 2, 4)
im4 = imshow(adjoint(reshape(dm2, n)), vmin=-4e-2, vmax=4e-2,cmap="gray", extent=(9.144, 16.764, 6.096, 1.143))
s4[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t4 = title("d)", fontweight="bold", size=10, loc="left")
t4["set_position"]([-.14, 1])
tight_layout()
savefig("figure1", dpi=300, format="png")
run(`mogrify -trim figure1`)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 4701 | # Example for basic 2D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, [email protected]
# Date: January 2017
#
using JUDI, PyPlot, JLD, SegyIO, LinearAlgebra
# Load Marmousi (4 km x 2 km)
if !isfile("marmousi_small.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/marmousi_small.jld`)
end
M = load("marmousi_small.jld")
# Setup model structure
model = Model(M["n"], M["d"], M["o"], M["m"])
model0 = Model(M["n"], M["d"], M["o"], M["m0"])
dm = vec(M["dm"])
# Setup receivers
nsrc = 10
nxrec = 761 # 10 m receiver spacing
xrec = range(100f0, stop=3900f0, length=nxrec)
yrec = 0f0
zrec = range(210f0, stop=210f0, length=nxrec)
# receiver sampling and recording time
timeR = 2500f0
dtR = 4f0
# Set up receiver structure
rec_geometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)
## Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell(range(200f0, stop=3800f0, length=nsrc))
ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc))
zsrc = convertToCell(range(20f0, stop=20f0, length=nsrc))
# source sampling and number of time steps
timeS = 2500f0
dtS = 1f0
# Set up source structure
src_geometry = Geometry(xsrc,ysrc,zsrc;dt=dtS,t=timeS)
# Set up source
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.030) # 25 Hz peak frequency
q = judiVector(src_geometry, wavelet)
#################################################################################################
opt = Options(isic=true, optimal_checkpointing=true)
# Setup operators
Pr = judiProjection(rec_geometry)
F = judiModeling(model; options=opt)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(src_geometry)
J = judiJacobian(Pr*F0*Ps', q)
# Time-domain RTM
d_lin = J*dm
rtm_time_5 = adjoint(J[5])*d_lin[5]
rtm_time = adjoint(J)*d_lin
# Frequency-domain RTM
J.options.optimal_checkpointing = false
J.options.dft_subsampling_factor = 8
q_dist = generate_distribution(q)
J.options.frequencies = Array{Any}(undef, nsrc)
for j=1:nsrc
J.options.frequencies[j] = select_frequencies(q_dist; fmin=0.002, fmax=0.05, nf=20)
end
rtm_freq = adjoint(J)*d_lin
rtm_freq_5 = adjoint(J[5])*d_lin[5]
######################################### Plots ####################################################
n = model0.n
rtm_time_5 = reshape(rtm_time_5, n)[:, 41:end]
rtm_time = reshape(rtm_time, n)[:, 41:end]
rtm_freq_5 = reshape(rtm_freq_5, n)[:, 41:end]
rtm_freq = reshape(rtm_freq, n)[:, 41:end]
rtm_time_5 /= norm(rtm_time_5, Inf)
rtm_time /= norm(rtm_time, Inf)
rtm_freq_5 /= norm(rtm_freq_5, Inf)
rtm_freq /= norm(rtm_freq, Inf)
figure(figsize=(6.66, 6))
s1=subplot(3, 2, 1)
im1 = imshow(adjoint(model0.m[:, 41:end]),cmap="gray", extent=(0.0, 4.0, 2.0, 0.2))
s1[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t1 = title("a)", fontweight="bold", size=10, loc="left")
t1["set_position"]([-.18, 1])
s2=subplot(3, 2, 2)
im1 = imshow(adjoint(reshape(dm, n)[:, 41:end]), vmin=-1e-1, vmax=1e-1,cmap="gray", extent=(0.0, 4.0, 2.0, 0.2))
s2[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t2 = title("b)", fontweight="bold", size=10, loc="left")
t2["set_position"]([-.18, 1])
s3=subplot(3, 2, 3)
im1 = imshow(adjoint(rtm_time_5), vmin=-2e-2, vmax=2e-2,cmap="gray", extent=(0.0, 4.0, 2.0, 0.2))
s3[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t3 = title("c)", fontweight="bold", size=10, loc="left")
t3["set_position"]([-.18, 1])
s4=subplot(3, 2, 4)
im1 = imshow(adjoint(rtm_time), vmin=-5e-2, vmax=5e-2,cmap="gray", extent=(0.0, 4.0, 2.0, 0.2))
s4[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t4 = title("d)", fontweight="bold", size=10, loc="left")
t4["set_position"]([-.18, 1])
s5=subplot(3, 2, 5)
im1 = imshow(adjoint(rtm_freq_5), vmin=-8e-2, vmax=8e-2,cmap="gray", extent=(0.0, 4.0, 2.0, 0.2))
s5[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t5 = title("e)", fontweight="bold", size=10, loc="left")
t5["set_position"]([-.18, 1])
s6=subplot(3, 2, 6)
im1 = imshow(adjoint(rtm_freq), vmin=-1.5e-1, vmax=1.5e-1,cmap="gray", extent=(0.0, 4.0, 2.0, 0.2))
s6[:tick_params]("both", labelsize=8)
xlabel("Lateral position [km]", size=8);
ylabel("Depth [km]", size=8)
t6 = title("f)", fontweight="bold", size=10, loc="left")
t6["set_position"]([-.18, 1])
tight_layout()
savefig("figure2", dpi=300, format="png")
run(`mogrify -trim figure2`)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2975 | # Generate observed linearized data for the Sigsbee2A velocity model
# Author: Philipp Witte, [email protected]
# Date: May 2018
#
# TO DO:
# Replace w/ full path the directory where the observed data will be stored
file_path="/path/to/data/"
file_name="sigsbee2A_marine"
using JUDI, PyPlot, JLD, SegyIO
# Load Sigsbee model
if !isfile("sigsbee2A_model.jld")
run(`wget ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/CompressiveLSRTM/sigsbee2A_model.jld`)
end
M = load("sigsbee2A_model.jld")
# Setup model structure
model0 = Model(M["n"], M["d"], M["o"], M["m0"])
dm = vec(M["dm"])
# Source interval [m]
source_spacing = 25
## Set up receiver geometry
domain_x = (model0.n[1] - 1)*model0.d[1]
nrec = 1200 # no. of receivers
xmin = 500f0
xmax = domain_x - 500f0
min_offset = 100f0 # [m]
max_offset = 12000f0
xmid = domain_x / 2
# Source/receivers
nsrc = Int(length(xmin:source_spacing:xmax))
xrec = Vector{Vector{Float32}}(undef, nsrc)
yrec = Vector{Vector{Float32}}(undef, nsrc)
zrec = Vector{Vector{Float32}}(undef, nsrc)
xsrc = Vector{Vector{Float32}}(undef, nsrc)
ysrc = Vector{Vector{Float32}}(undef, nsrc)
zsrc = Vector{Vector{Float32}}(undef, nsrc)
# Vessel goes from left to right in right-hand side of model
nsrc_half = Int(nsrc/2)
for j=1:nsrc_half
xloc = xmid + (j-1)*source_spacing
xrec[j] = range(xloc - max_offset, xloc - min_offset, length=nrec)
yrec[j] = [0.]
zrec[j] = range(50f0, 50f0, length=nrec)
xsrc[j] = [xloc]
ysrc[j] = [0f0]
zsrc[j] = [20f0]
end
# Vessel goes from right to left in left-hand side of model
for j=1:nsrc_half
xloc = xmid - (j-1)*source_spacing
xrec[nsrc_half + j] = range(xloc + min_offset, xloc + max_offset, length=nrec)
yrec[nsrc_half + j] = [0f0]
zrec[nsrc_half + j] = range(50f0, 50f0, length=nrec)
xsrc[nsrc_half + j] = [xloc]
ysrc[nsrc_half + j] = [0f0]
zsrc[nsrc_half + j] = [20f0]
end
# receiver sampling and recording time
timeR = 10000f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR)
# Source sampling and number of time steps
timeS = 10000f0
dtS = 2f0
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
# Setup wavelet
f0 = 0.015 # dominant frequency in [kHz]
wavelet = ricker_wavelet(timeS,dtS,f0)
q = judiVector(srcGeometry,wavelet)
#################################################################################################
opt = Options(isic=true, # impedance modeling
save_data_to_disk=true,
file_path = file_path, # directory for saving generated shots
file_name = file_name
)
# Setup operators
Pr = judiProjection(recGeometry)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(srcGeometry)
J = judiJacobian(Pr*F0*Ps', q)
# Linearized modeling (shots written to disk as SEG-Y files automatically)
J*dm
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2042 | # Reverse-time migration of the Sigsbee2A model: time-domain vs. frequency domain w/ on-the-fly Fourier transforms
# Author: Philipp Witte, [email protected]
# Date: May 2018
#
# TO DO:
# Replace w/ full path the observed data directory
path_to_data = "/path/to/directory/"
data_name = "sigsbee2A_marine" # common base name of all shots
using JUDI, PyPlot, JLD, SegyIO
# Load Sigsbee model
M = load("sigsbee2A_model.jld")
# Setup model structure
model0 = Model(M["n"], M["d"], M["o"], M["m0"])
dm = vec(M["dm"])
# Set up out-of-core data container
container = segy_scan(path_to_data, data_name, ["GroupX","GroupY","RecGroupElevation","SourceSurfaceElevation","dt"])
d_lin = judiVector(container)
# Set up source
src_geometry = Geometry(container; key="source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.015) # 15 Hz peak frequency
q = judiVector(src_geometry, wavelet)
#################################################################################################
opt = Options(isic=true, optimal_checkpointing=true) # use impedance imaging
# Setup operators
Pr = judiProjection(d_lin.geometry)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(q.geometry)
J = judiJacobian(Pr*F0*adjoint(Ps), q)
# Time-domain RTM w/ optimal checkpointing
rtm_time = adjoint(J)*d_lin
# Save time-domain result
save("sigsbee2A_rtm_time_domain", "rtm", reshape(rtm_time, model0.n))
# Generate probability density function from source spectrum
q_dist = generate_distribution(q)
# Select 20 random frequencies per source location
nfreq = 20
J.options.optimal_checkpointing = false
J.options.frequencies = Array{Any}(undef, d_lin.nsrc)
for j=1:d_lin.nsrc
J.options.frequencies[j] = select_frequencies(q_dist; fmin=0.003, fmax=0.04, nf=nfreq)
end
J.options.dft_subsampling_factor = 8 # perform dft every 8 time steps only
# Frequency-domain RTM w/ on-the-fly DFTs
rtm_freq = adjoint(J)*d_lin
# Save frequency-domain result
save("sigsbee2A_rtm_frequency_domain", "rtm", reshape(rtm_freq, model0.n))
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3077 | # Sparsity-promoting LS-RTM on the Sigsbee 2A model w/ on-the-fly Fourier transforms
# Author: Philipp Witte, [email protected]
# Date: May 2018
#
# TO DO:
# Replace w/ full path the observed data directory
#path_to_data = "/path/to/directory/"
path_to_data="/home/pwitte3/.julia/dev/JUDI/examples/compressive_splsrtm/Sigsbee2A/"
data_name = "sigsbee2A_marine" # common base name of all shots
using JUDI, PyPlot, JLD, SegyIO, JOLI, Random, LinearAlgebra
# Load Sigsbee model
M = load("sigsbee2A_model.jld")
# Setup model structure
model0 = Model(M["n"], M["d"], M["o"], M["m0"])
dm = vec(M["dm"])
# Load data
container = segy_scan(path_to_data, data_name, ["GroupX","GroupY","RecGroupElevation","SourceSurfaceElevation","dt"])
d_lin = judiVector(container)
# Set up source
src_geometry = Geometry(container; key="source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.015) # 15 Hz peak frequency
q = judiVector(src_geometry, wavelet)
#################################################################################################
opt = Options(isic=true)
# Setup operators
Pr = judiProjection(d_lin.geometry)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(src_geometry)
J = judiJacobian(Pr*F0*Ps', q)
# Right-hand preconditioners (model topmute)
idx_wb = find_water_bottom(reshape(dm, model0.n))
Tm = judiTopmute(model0.n, idx_wb, 10) # Mute water column
S = judiDepthScaling(model0)
Mr = S*Tm
# Linearized Bregman parameters
x = zeros(Float32, prod(model0.n))
z = zeros(Float32, prod(model0.n))
batchsize = 100
niter = 20
nfreq = 20
fval = zeros(Float32, niter)
q_dist = generate_distribution(q)
J.options.frequencies = Array{Any}(undef, d_lin.nsrc)
J.options.dft_subsampling_factor = 8
# Soft thresholding functions and Curvelet transform
soft_thresholding(x::Array{Float64}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float64, lambda), 0.0)
soft_thresholding(x::Array{Float32}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float32, lambda), 0f0)
C = joCurvelet2D(model0.n[1], model0.n[2]; zero_finest=true, DDT=Float32, RDT=Float64)
lambda = []
t = 2f-5 # 4f-5 for nfreq=10
# Main loop
for j=1:niter
println("Iteration: ", j)
# Set randomized frequencies
for k=1:d_lin.nsrc
J.options.frequencies[k] = select_frequencies(q_dist; fmin=0.002, fmax=0.04, nf=nfreq)
end
# Compute residual and gradient
i = randperm(d_lin.nsrc)[1:batchsize]
d_sub = get_data(d_lin[i]) # load current shots into memory
r = J[i]*Mr*x - d_sub
g = Mr'*J[i]'*r
# Step size and update variable
fval[j] = .5*norm(r)^2
j==1 && (global lambda = 0.05*norm(C*t*g, Inf)) # estimate thresholding parameter in 1st iteration
# Update variables
global z -= t*g
global x = adjoint(C)*soft_thresholding(C*z, lambda)
# Save snapshot
save(join(["snapshot_splsrtm_fourier_iteration_", string(j),".jld"]), "x", reshape(x, model0.n), "z", reshape(z, model0.n))
end
# Save final result
save("sigsbee2A_splsrtm_frequency_domain.jld", "x", x, "fval", fval, "lambda", lambda)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2713 | # Sparsity-promoting LS-RTM on the Sigsbee 2A model w/ optimal checkpointing
# Author: Philipp Witte, [email protected]
# Date: May 2018
#
# TO DO:
# Replace w/ full path the observed data directory
#path_to_data = "/path/to/directory/"
path_to_data="/home/pwitte3/.julia/dev/JUDI/examples/compressive_splsrtm/Sigsbee2A/"
data_name = "sigsbee2A_marine" # common base name of all shots
using JUDI, PyPlot, JLD, SegyIO, JOLI, Random
# Load Sigsbee model
M = load("sigsbee2A_model.jld")
# Setup model structure
model0 = Model(M["n"], M["d"], M["o"], M["m0"])
dm = vec(M["dm"])
# Load data
container = segy_scan(path_to_data, data_name, ["GroupX","GroupY","RecGroupElevation","SourceSurfaceElevation","dt"])
d_lin = judiVector(container)
# Set up source
src_geometry = Geometry(container; key="source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.015) # 15 Hz peak frequency
q = judiVector(src_geometry, wavelet)
#################################################################################################
opt = Options(isic=true, optimal_checkpointing=true)
# Setup operators
Pr = judiProjection(d_lin.geometry)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(src_geometry)
J = judiJacobian(Pr*F0*Ps', q)
# Right-hand preconditioners (model topmute)
idx_wb = find_water_bottom(reshape(dm, model0.n))
Tm = judiTopmute(model0.n, idx_wb, 10) # Mute water column
S = judiDepthScaling(model0)
Mr = S*Tm
# Linearized Bregman parameters
x = zeros(Float32, prod(model0.n))
z = zeros(Float32, prod(model0.n))
batchsize = 100
niter = 20
fval = zeros(Float32, niter)
t = 2f-5
# Soft thresholding functions and Curvelet transform
soft_thresholding(x::Array{Float64}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float64, lambda), 0.0)
soft_thresholding(x::Array{Float32}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float32, lambda), 0f0)
C = joCurvelet2D(model0.n[1], model0.n[2]; zero_finest=true, DDT=Float32, RDT=Float64)
lambda = []
# Main loop
for j=1:niter
println("Iteration: ", j)
# Compute residual and gradient
i = randperm(d_lin.nsrc)[1:batchsize]
d_sub = get_data(d_lin[i]) # load shots into memory
r = J[i]*Mr*x - d_sub
g = Mr'*J[i]'*r
# Step size and update variable
fval[j] = .5*norm(r)^2
isempty(t) && (global t = norm(r)^2/norm(g)^2)
j==1 && (global lambda = 0.01*norm(C*t*g, Inf)) # estimate thresholding parameter in 1st iteration
# Update variables and save snapshot
global z -= t*g
global x = adjoint(C)*soft_thresholding(C*z, lambda)
# Save snapshot
save(join(["splsrtm_checkpointing_iteration_", string(j),".jld"]), "x", reshape(x, model0.n), "z", reshape(z, model0.n))
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 321 | using Pkg
Pkg.add("Statistics")
Pkg.add("Random")
Pkg.add("LinearAlgebra")
Pkg.add("Interpolations")
Pkg.add("DelimitedFiles")
Pkg.add("Distributed")
Pkg.add("SlimOptim")
Pkg.add("NLopt")
Pkg.add("HDF5")
Pkg.add("SegyIO")
Pkg.add("Plots")
Pkg.add("SetIntersectionProjection")
Pkg.add("ImageFiltering")
Pkg.add("DrWatson") | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1377 | function save_data(x,z,data; pltfile,title,colormap,clim=nothing,h5file,h5openflag,h5varname)
@info "save_data: $h5file"
n = (length(x),length(z))
o = (x[1],z[1])
d = (x[2]-x[1],z[2]-z[1])
isnothing(clim) && (clim = (minimum(data),maximum(data)))
plt = Plots.heatmap(x, z, data, c=colormap,
xlims=(x[1],x[end]),
ylims=(z[1],z[end]), yflip=true,
title=title,
clim=clim,
xlabel="Lateral position [km]",
ylabel="Depth [km]",
dpi=600)
Plots.savefig(plt, pltfile)
fid = h5open(h5file, h5openflag)
(haskey(fid, h5varname)) && (delete_object(fid, h5varname))
(haskey(fid, "o")) && (delete_object(fid, "o"))
(haskey(fid, "n")) && (delete_object(fid, "n"))
(haskey(fid, "d")) && (delete_object(fid, "d"))
write(fid,
h5varname, Matrix(adjoint(data)), # convert adjoint(Matrix) type to Matrix
"o", collect(o.*1000f0),
"n", collect(n),
"d", collect(d.*1000f0))
close(fid)
end
function save_data_as_segy(x,z,data)
end
function save_fhistory(fhistory; h5file,h5openflag,h5varname)
@info "save_fhistory: $h5file"
fid = h5open(h5file, h5openflag)
(haskey(fid, h5varname)) && (delete_object(fid, h5varname))
write(fid, h5varname, fhistory)
close(fid)
end
"""
Recalculate slowness^2 to density using Gardner formulae
"""
rho_from_slowness(m) = 0.23.*(sqrt.(1f0 ./ m).*1000f0).^0.25 | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 7624 | using DrWatson
@quickactivate "Viking"
using Viking
using Statistics, Random, LinearAlgebra, Interpolations, DelimitedFiles, Distributed
using JUDI, SlimOptim, NLopt, HDF5, SegyIO, Plots, ImageFiltering
using SetIntersectionProjection
############# INITIAL DATA #############
modeling_type = "bulk" # slowness, bulk
frq = 0.005 # kHz
prestk_dir = "$(@__DIR__)/trim_segy/"
prestk_file = "shot"
dir_out = "$(@__DIR__)/fwi_lbfgs_$(modeling_type)/$(frq)Hz/"
model_file = "$(@__DIR__)/initial_model/model.h5"
# after each iteration you should set an appropriate model file computed with previous step
# model_file = "$(@__DIR__)/fwi_lbfgs_$(modeling_type)/0.005Hz/model 10.h5"
model_file_out = "model"
# use original wavelet file
wavelet_file = "$(@__DIR__)/../FarField.dat" # dt=1, skip=25
# or use deghosted wavelet
# wavelet_file = "$(@__DIR__)/../proc/FarField_deghosted.dat" # dt=4, skip=0
wavelet_skip_start = 25 # 25 [lines] for raw source and 0 for deghosted source
wavelet_dt = 1 # 1 [ms] for raw source and 4 [ms] for deghosted source
segy_depth_key_src = "SourceSurfaceElevation"
segy_depth_key_rec = "RecGroupElevation"
seabed = 355 # [m]
############# INITIAL PARAMS #############
# water velocity, km/s
global vwater = 1.5
# water density, g/cm^3
global rhowater = 1.02
# JUDI options
buffer_size = 0f0 # limit model (meters) even if 0 buffer makes reflections from borders that does't hurt much the FWI result
# prepare folder for output data
mkpath(dir_out)
# Load data and create data vector
container = segy_scan(prestk_dir, prestk_file, ["SourceX", "SourceY", "GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
d_obs = judiVector(container; segy_depth_key = segy_depth_key_rec)
srcx = Float32.(get_header(container, "SourceX")[:,1])
grpx = Float32.(get_header(container, "GroupX")[:,1])
min_src_x = minimum(srcx)./1000f0
max_src_x = maximum(srcx)./1000f0
min_grp_x = minimum(grpx)./1000f0
max_grp_x = maximum(grpx)./1000f0
min_x = minimum([min_src_x, min_grp_x])
max_x = maximum([max_src_x, max_grp_x])
# Load starting model (mlog - slowness built with Vs from logs; mvsp - built from VSP)
fid = h5open(model_file, "r")
n, d, o = read(fid, "n", "d", "o")
if haskey(fid, "mvsp")
m0 = Float32.(read(fid, "mvsp"))
else
m0 = Float32.(read(fid, "m"))
end
close(fid)
n = Tuple(Int64(i) for i in n)
d = Tuple(Float32(i) for i in d)
o = Tuple(Float32(i) for i in o)
if modeling_type == "slowness"
model0 = Model(n, d, o, m0)
elseif modeling_type == "bulk"
rho0 = rho_from_slowness(m0)
model0 = Model(n, d, o, m0, rho=rho0)
end
@info "modeling_type: $modeling_type"
@info "n: $n"
@info "d: $d"
@info "o: $o"
x = (o[1]:d[1]:o[1]+(n[1]-1)*d[1])./1000f0
z = (o[2]:d[2]:o[2]+(n[2]-1)*d[2])./1000f0
global seabed_ind = Int.(round.(seabed./d[2]))
if modeling_type == "slowness"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
elseif modeling_type == "bulk"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
model0.rho[:,1:seabed_ind] .= rhowater
end
# Set up wavelet and source vector
src_geometry = Geometry(container; key = "source", segy_depth_key = segy_depth_key_src)
# setup wavelet
wavelet_raw = readdlm(wavelet_file, skipstart=wavelet_skip_start)
itp = LinearInterpolation(0:wavelet_dt:wavelet_dt*(length(wavelet_raw)-1), wavelet_raw[:,1], extrapolation_bc=0f0)
wavelet = Matrix{Float32}(undef,src_geometry.nt[1],1)
wavelet[:,1] = itp(0:src_geometry.dt[1]:src_geometry.t[1])
q = judiVector(src_geometry, wavelet)
# Data muters (t0 somehow can't be 0)
Ml_ref = judiDataMute(q.geometry, d_obs.geometry, vp=1100f0, t0=0.001f0, mode=:reflection) # keep reflections
Ml_tur = judiDataMute(q.geometry, d_obs.geometry, vp=1100f0, t0=0.001f0, mode=:turning) # keep turning waves
# Bandpass filter
Ml_freq = judiFilter(d_obs.geometry, 0.001, frq*1000f0)
Mr_freq = judiFilter(q.geometry, 0.001, frq*1000f0)
# Bound constraints
vmin = 1.2
vmax = 5.2
# Slowness squared [s^2/km^2]
mmin = (1f0 ./ vmax).^2
mmax = (1f0 ./ vmin).^2
############# FWI #############
# JUDI options
global jopt = JUDI.Options(
IC = "fwi",
limit_m = true,
buffer_size = buffer_size,
optimal_checkpointing=false,
free_surface=true, # free_surface is ON to model multiples as well
space_order=16) # increase space order for > 12 Hz source wavelet
# optimization parameters
niterations = 10
shot_from = 1
shot_to = length(d_obs)
shot_step = 3 # we may want to calculate only each Nth shot to economy time
count = 0
fhistory = Vector{Float32}(undef, 0)
mute_reflections = false
mute_turning = false
# NLopt objective function
function nlopt_obj_fun!(m_update, grad)
global x, z, count, jopt, seabed_ind;
count += 1
# Update model
model0.m .= Float32.(reshape(m_update, size(model0)))
if modeling_type == "bulk"
model0.rho .= Float32.(reshape(rho_from_slowness(model0.m), size(model0)))
model0.rho[:,1:seabed_ind] .= rhowater
end
# Select batch and calculate gradient
# Subsampling the number of sources should in practice never be used for second order methods such as L-BFGS.
# get_data(d_obs) is a temporal solution as Ml_freq doesn't work yet with SeisCon
indsrc = shot_from:shot_step:shot_to
if mute_reflections
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_tur[indsrc]*Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt)
elseif mute_turning
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_ref[indsrc]*Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt)
else
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt)
end
gradient = reshape(gradient, size(model0))
gradient[:, 1:seabed_ind] .= 0f0
grad[1:end] .= gradient[1:end]
push!(fhistory, fval)
println("iteration: ", count, "\tfval: ", fval, "\tnorm: ", norm(gradient))
save_data(x,z,adjoint(reshape(model0.m.data,size(model0)));
pltfile=dir_out * "FWI slowness $count.png",
title="FWI slowness^2 with L-BFGS $modeling_type: $(frq*1000)Hz, iter $count",
colormap=:rainbow,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="w",
h5varname="m")
save_data(x,z,sqrt.(1f0 ./ adjoint(reshape(model0.m.data,size(model0))));
pltfile=dir_out * "FWI $count.png",
title="FWI velocity with L-BFGS $modeling_type: $(frq*1000)Hz, iter $count",
colormap=:rainbow,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="v")
save_data(x,z,adjoint(reshape(gradient.data,size(model0)));
pltfile=dir_out * "Gradient $count.png",
title="FWI gradient with L-BFGS $modeling_type: $(frq*1000)Hz, iter $count",
clim=(-maximum(gradient.data)/5f0, maximum(gradient.data)/5f0),
colormap=:bluesreds,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="grad")
save_fhistory(fhistory;
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="fhistory")
return convert(Float64, fval)
end
println("No. ", "fval ", "norm(gradient)")
opt = Opt(:LD_LBFGS, prod(size(model0)))
min_objective!(opt, nlopt_obj_fun!)
lower_bounds!(opt, mmin); upper_bounds!(opt, mmax)
maxeval!(opt, niterations)
(minf, minx, ret) = optimize(opt, copy(model0.m.data[:]))
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 9953 | using DrWatson
@quickactivate "Viking"
using Viking
using Statistics, Random, LinearAlgebra, Interpolations, DelimitedFiles, Distributed
using JUDI, SlimOptim, NLopt, HDF5, SegyIO, Plots, ImageFiltering
using SetIntersectionProjection
############# INITIAL DATA #############
modeling_type = "bulk" # slowness, bulk
frq = 0.005 # kHz
prestk_dir = "$(@__DIR__)/trim_segy/"
prestk_file = "shot"
dir_out = "$(@__DIR__)/fwi_pqn_$(modeling_type)/$(frq)Hz/"
model_file = "$(@__DIR__)/initial_model/model.h5"
# after each iteration you should set an appropriate model file computed with previous step
# model_file = "$(@__DIR__)/fwi_pqn_$(modeling_type)/0.005Hz/model 10.h5"
model_file_out = "model"
# use original wavelet file
wavelet_file = "$(@__DIR__)/../FarField.dat" # dt=1, skip=25
# or use deghosted wavelet
# wavelet_file = "$(@__DIR__)/../proc/FarField_deghosted.dat" # dt=4, skip=0
wavelet_skip_start = 25 # 25 [lines] for raw source and 0 for deghosted source
wavelet_dt = 1 # 1 [ms] for raw source and 4 [ms] for deghosted source
segy_depth_key_src = "SourceSurfaceElevation"
segy_depth_key_rec = "RecGroupElevation"
seabed = 355 # [m]
############# INITIAL PARAMS #############
# water velocity, km/s
global vwater = 1.5
# water density, g/cm^3
global rhowater = 1.02
# JUDI options
buffer_size = 0f0 # limit model (meters) even if 0 buffer makes reflections from borders that does't hurt much the FWI result
# prepare folder for output data
mkpath(dir_out)
# Load data and create data vector
container = segy_scan(prestk_dir, prestk_file, ["SourceX", "SourceY", "GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
d_obs = judiVector(container; segy_depth_key = segy_depth_key_rec)
srcx = Float32.(get_header(container, "SourceX")[:,1])
grpx = Float32.(get_header(container, "GroupX")[:,1])
min_src_x = minimum(srcx)./1000f0
max_src_x = maximum(srcx)./1000f0
min_grp_x = minimum(grpx)./1000f0
max_grp_x = maximum(grpx)./1000f0
min_x = minimum([min_src_x, min_grp_x])
max_x = maximum([max_src_x, max_grp_x])
# Load starting model (mlog - slowness built with Vs from logs; mvsp - built from VSP)
fid = h5open(model_file, "r")
n, d, o = read(fid, "n", "d", "o")
if haskey(fid, "mvsp")
m0 = Float32.(read(fid, "mvsp"))
else
m0 = Float32.(read(fid, "m"))
end
close(fid)
n = Tuple(Int64(i) for i in n)
d = Tuple(Float32(i) for i in d)
o = Tuple(Float32(i) for i in o)
if modeling_type == "slowness"
model0 = Model(n, d, o, m0)
elseif modeling_type == "bulk"
rho0 = rho_from_slowness(m0)
model0 = Model(n, d, o, m0, rho=rho0)
end
@info "modeling_type: $modeling_type"
@info "n: $n"
@info "d: $d"
@info "o: $o"
x = (o[1]:d[1]:o[1]+(n[1]-1)*d[1])./1000f0
z = (o[2]:d[2]:o[2]+(n[2]-1)*d[2])./1000f0
global seabed_ind = Int.(round.(seabed./d[2]))
if modeling_type == "slowness"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
elseif modeling_type == "bulk"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
model0.rho[:,1:seabed_ind] .= rhowater
end
# Set up wavelet and source vector
src_geometry = Geometry(container; key = "source", segy_depth_key = segy_depth_key_src)
# setup wavelet
wavelet_raw = readdlm(wavelet_file, skipstart=wavelet_skip_start)
itp = LinearInterpolation(0:wavelet_dt:wavelet_dt*(length(wavelet_raw)-1), wavelet_raw[:,1], extrapolation_bc=0f0)
wavelet = Matrix{Float32}(undef,src_geometry.nt[1],1)
wavelet[:,1] = itp(0:src_geometry.dt[1]:src_geometry.t[1])
q = judiVector(src_geometry, wavelet)
# Data muters (t0 somehow can't be 0)
Ml_ref = judiDataMute(q.geometry, d_obs.geometry, vp=1100f0, t0=0.001f0, mode=:reflection) # keep reflections
Ml_tur = judiDataMute(q.geometry, d_obs.geometry, vp=1100f0, t0=0.001f0, mode=:turning) # keep turning waves
# Bandpass filter
Ml_freq = judiFilter(d_obs.geometry, 0.001, frq*1000f0)
Mr_freq = judiFilter(q.geometry, 0.001, frq*1000f0)
############# FWI #############
# JUDI options
global jopt = JUDI.Options(
IC = "fwi",
limit_m = true,
buffer_size = buffer_size,
optimal_checkpointing=false,
free_surface=true, # free_surface is ON to model multiples as well
space_order=16) # increase space order for > 12 Hz source wavelet
# optimization parameters
niterations = 10
shot_from = 1
shot_to = length(d_obs)
shot_step = 3 # we may want to calculate only each Nth shot to economy time
count = 0
fhistory = Vector{Float32}(undef, 0)
mute_reflections = false
mute_turning = false
# SETUP CONSTARAINTS
options=PARSDMM_options()
options.FL=Float32
options=default_PARSDMM_options(options,options.FL)
constraint = Vector{SetIntersectionProjection.set_definitions}()
# Bound constraints
vmin = 1.2
vmax = 5.2
vBoundCoef = 0.5
kr = 50
# Slowness squared [s^2/km^2]
mmin = (1f0 ./ vmax).^2
mmax = (1f0 ./ vmin).^2
mminArr = ones(Float32, size(model0)) .* mmin
mmaxArr = ones(Float32, size(model0)) .* mmax
# mminArr = imfilter(model0.m.data * (1f0-vBoundCoef), Kernel.gaussian(kr))
# mmaxArr = imfilter(model0.m.data * (1f0+vBoundCoef), Kernel.gaussian(kr))
# ind = model0.m .< mminArr
# mminArr[ind] .= model0.m[ind]
# ind = model0.m .> mmaxArr
# mmaxArr[ind] .= model0.m[ind]
# bounds:
set_type = "bounds"
TD_OP = "identity"
app_mode = ("matrix","")
custom_TD_OP = ([],false)
push!(constraint, set_definitions(set_type,TD_OP,vec(mminArr),vec(mmaxArr),app_mode,custom_TD_OP));
#TV
(TV,dummy1,dummy2,dummy3) = get_TD_operator(model0.m,"TV",options.FL)
mvar_min = 0.0
mvar_max = norm(TV*vec(m0),1) * 2.5
set_type = "l1"
TD_OP = "TV"
app_mode = ("matrix","")
custom_TD_OP = ([],false)
push!(constraint, set_definitions(set_type,TD_OP,mvar_min,mvar_max,app_mode,custom_TD_OP));
# set up constraints with bounds and TV
(P_sub,TD_OP,set_Prop) = setup_constraints(constraint, model0,options.FL)
(TD_OP,AtA,l,y) = PARSDMM_precompute_distribute(TD_OP,set_Prop,model0,options)
options.rho_ini = ones(Float32, length(TD_OP))*10.0f0
proj_intersection = x-> PARSDMM(x, AtA, TD_OP, set_Prop, P_sub, model0, options)
# Projection function
function prj(input)
@info "prj minimum(input): $(minimum(input))"
input = Float32.(input)
(x,dummy1,dummy2,dymmy3) = proj_intersection(vec(input))
return x
end
# Set water bottom mask
wb_mask = ones(Float32,size(m0))
wb_mask[:, 1:seabed_ind] .= 0f0
# wb_mask[:, 1:seabed_ind+20] .= 0f0
# Build small cluster
nthread = Sys.CPU_THREADS
nw = 2
ENV["OMP_DISPLAY_ENV"] = "true"
ENV["OMP_PROC_BIND"] = "close"
ENV["OMP_NUM_THREADS"] = "$(div(nthread, nw))"
addprocs(nw)
@show workers()
for k in 1:nworkers()
place1 = (k - 1) * div(nthread,nworkers())
place2 = (k + 0) * div(nthread,nworkers()) - 1
@show place1, place2, div(nthread, nw)
@spawnat workers()[k] ENV["GOMP_CPU_AFFINITY"] = "$(place1)-$(place2)";
end
@everywhere using Distributed, JUDI.TimeModeling, SlimOptim, LinearAlgebra, PyPlot, SetIntersectionProjection, SegyIO
function objective(m, d_obs, wb_mask)
global x, z, count, jopt, seabed_ind, mminArr, mmaxArr;
count += 1
@info "objective minimum(m): $(minimum(m))"
m = reshape(m, size(model0))
# pqn may cross the mmin/mmax limits
ind = m .< mminArr
m[ind] .= mminArr[ind]
ind = m .> mmaxArr
m[ind] .= mmaxArr[ind]
model0.m .= Float32.(reshape(m, size(model0)))
if modeling_type == "bulk"
model0.rho .= Float32.(reshape(rho_from_slowness(model0.m), size(model0)))
model0.rho[:,1:seabed_ind] .= rhowater
end
t = @elapsed begin
indsrc = shot_from:shot_step:shot_to
if mute_reflections
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_tur[indsrc]*Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt)
elseif mute_turning
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_ref[indsrc]*Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt)
else
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt)
end
gradient = reshape(gradient, size(model0))
end
@info "elapsed fwi_objective time: $t"
gradient .*= wb_mask
if gscale == 0f0
# compute scalar from first gradient, apply to future gradients
global gscale = .25f0 ./ maximum(gradient)
@show gscale
end
gradient .*= gscale
push!(fhistory, fval)
println("iteration: ", count, "\tfval: ", fval, "\tnorm: ", norm(gradient))
save_data(x,z,adjoint(reshape(model0.m.data,size(model0)));
pltfile=dir_out * "FWI slowness $count.png",
title="FWI slowness^2 with PQN $modeling_type: $(frq*1000)Hz, iter $count",
colormap=:rainbow,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="w",
h5varname="m")
save_data(x,z,sqrt.(1f0 ./ adjoint(reshape(model0.m.data,size(model0))));
pltfile=dir_out * "FWI $count.png",
title="FWI velocity with PQN $modeling_type: $(frq*1000)Hz, iter $count",
colormap=:rainbow,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="v")
save_data(x,z,adjoint(reshape(gradient.data,size(model0)));
pltfile=dir_out * "Gradient $count.png",
title="FWI gradient with PQN $modeling_type: $(frq*1000)Hz, iter $count",
clim=(-maximum(gradient.data)/5f0, maximum(gradient.data)/5f0),
colormap=:bluesreds,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="grad")
save_fhistory(fhistory;
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="fhistory")
return fval, vec(gradient.data)
end
# struct to save the first gradient scalar
gscale = 0f0
g(x) = objective(x, d_obs, wb_mask)
# FWI with PQN
gscale = 0f0
options_pqn = pqn_options(progTol=0, store_trace=true, verbose=3, maxIter=niterations)
sol = pqn(g, vec(m0), prj, options_pqn);
rmprocs(workers()); | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 8569 | using DrWatson
@quickactivate "Viking"
using Viking
using Statistics, Random, LinearAlgebra, Interpolations, DelimitedFiles, Distributed
using JUDI, SlimOptim, NLopt, HDF5, SegyIO, Plots, ImageFiltering
using SetIntersectionProjection
@everywhere using JUDI.FFTW, Zygote, Flux
############# INITIAL DATA #############
modeling_type = "bulk" # slowness, bulk
frq = 0.005 # kHz
prestk_dir = "$(@__DIR__)/trim_segy/"
# prestk_dir = "$(@__DIR__)/trim_segy_200_500/"
prestk_file = "shot"
dir_out = "$(@__DIR__)/fwi_spg_$(modeling_type)/$(frq)Hz/"
# dir_out = "$(@__DIR__)/fwi_spg_$(modeling_type)_buffer_3km/$(frq)Hz/"
model_file = "$(@__DIR__)/initial_model/model.h5"
# after each iteration you should set an appropriate model file computed with previous step
# model_file = "$(@__DIR__)/fwi_spg_$(modeling_type)/0.008Hz/model 10.h5"
model_file_out = "model"
# use original wavelet file
wavelet_file = "$(@__DIR__)/../FarField.dat" # dt=1, skip=25
# or use deghosted wavelet
# wavelet_file = "$(@__DIR__)/../proc/FarField_deghosted.dat" # dt=4, skip=0
wavelet_skip_start = 25 # 25 [lines] for raw source and 0 for deghosted source
wavelet_dt = 1 # 1 [ms] for raw source and 4 [ms] for deghosted source
segy_depth_key_src = "SourceSurfaceElevation"
segy_depth_key_rec = "RecGroupElevation"
seabed = 355 # [m]
############# INITIAL PARAMS #############
# water velocity, km/s
global vwater = 1.5
# water density, g/cm^3
global rhowater = 1.02
# JUDI options
buffer_size = 0f0 # limit model (meters) even if 0 buffer makes reflections from borders that does't hurt much the FWI result
# prepare folder for output data
mkpath(dir_out)
# Load data and create data vector
container = segy_scan(prestk_dir, prestk_file, ["SourceX", "SourceY", "GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
d_obs = judiVector(container; segy_depth_key = segy_depth_key_rec)
srcx = Float32.(get_header(container, "SourceX")[:,1])
grpx = Float32.(get_header(container, "GroupX")[:,1])
min_src_x = minimum(srcx)./1000f0
max_src_x = maximum(srcx)./1000f0
min_grp_x = minimum(grpx)./1000f0
max_grp_x = maximum(grpx)./1000f0
min_x = minimum([min_src_x, min_grp_x])
max_x = maximum([max_src_x, max_grp_x])
# Load starting model (mlog - slowness built with Vs from logs; mvsp - built from VSP)
fid = h5open(model_file, "r")
n, d, o = read(fid, "n", "d", "o")
if haskey(fid, "mvsp")
m0 = Float32.(read(fid, "mvsp"))
else
m0 = Float32.(read(fid, "m"))
end
close(fid)
n = Tuple(Int64(i) for i in n)
d = Tuple(Float32(i) for i in d)
o = Tuple(Float32(i) for i in o)
if modeling_type == "slowness"
model0 = Model(n, d, o, m0)
elseif modeling_type == "bulk"
rho0 = rho_from_slowness(m0)
model0 = Model(n, d, o, m0, rho=rho0)
end
@info "modeling_type: $modeling_type"
@info "n: $n"
@info "d: $d"
@info "o: $o"
x = (o[1]:d[1]:o[1]+(n[1]-1)*d[1])./1000f0
z = (o[2]:d[2]:o[2]+(n[2]-1)*d[2])./1000f0
global seabed_ind = Int.(round.(seabed./d[2]))
if modeling_type == "slowness"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
elseif modeling_type == "bulk"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
model0.rho[:,1:seabed_ind] .= rhowater
end
# Set up wavelet and source vector
src_geometry = Geometry(container; key = "source", segy_depth_key = segy_depth_key_src)
# setup wavelet
wavelet_raw = readdlm(wavelet_file, skipstart=wavelet_skip_start)
itp = LinearInterpolation(0:wavelet_dt:wavelet_dt*(length(wavelet_raw)-1), wavelet_raw[:,1], extrapolation_bc=0f0)
wavelet = Matrix{Float32}(undef,src_geometry.nt[1],1)
wavelet[:,1] = itp(0:src_geometry.dt[1]:src_geometry.t[1])
q = judiVector(src_geometry, wavelet)
# Data muters (t0 somehow can't be 0)
Ml_ref = judiDataMute(q.geometry, d_obs.geometry, vp=1100f0, t0=0.001f0, mode=:reflection) # keep reflections
Ml_tur = judiDataMute(q.geometry, d_obs.geometry, vp=1100f0, t0=0.001f0, mode=:turning) # keep turning waves
# Bandpass filter
Ml_freq = judiFilter(d_obs.geometry, 0.001, frq*1000f0)
Mr_freq = judiFilter(q.geometry, 0.001, frq*1000f0)
############# FWI #############
# JUDI options
global jopt = JUDI.Options(
IC = "fwi",
limit_m = true,
buffer_size = buffer_size,
optimal_checkpointing=false,
free_surface=true, # free_surface is ON to model multiples as well
space_order=16) # increase space order for > 12 Hz source wavelet
# optimization parameters
niterations = 20
count = 0
fhistory = Vector{Float32}(undef, 0)
mute_reflections = false
mute_turning = false
# SETUP CONSTARAINTS
options=PARSDMM_options()
options.FL=Float32
options=default_PARSDMM_options(options,options.FL)
constraint = Vector{SetIntersectionProjection.set_definitions}()
# Bound constraints
vmin = 1.2
vmax = 5.2
vBoundCoef = 0.5
kr = 50
# Slowness squared [s^2/km^2]
mmin = (1f0 ./ vmax).^2
mmax = (1f0 ./ vmin).^2
mminArr = ones(Float32, size(model0)) .* mmin
mmaxArr = ones(Float32, size(model0)) .* mmax
# mminArr = imfilter(model0.m.data * (1f0-vBoundCoef), Kernel.gaussian(kr))
# mmaxArr = imfilter(model0.m.data * (1f0+vBoundCoef), Kernel.gaussian(kr))
# ind = model0.m .< mminArr
# mminArr[ind] .= model0.m[ind]
# ind = model0.m .> mmaxArr
# mmaxArr[ind] .= model0.m[ind]
@everywhere function H(x)
n = size(x, 1)
σ = ifftshift(sign.(-n/2+1:n/2))
y = imag(ifft(σ.*fft(x, 1), 1))
return y
end
@everywhere envelope(x, y) = sum(abs2.((x - y) .+ 1im .* H(x - y)))
@everywhere denvelope(x, y) = Zygote.gradient(xs->envelope(xs, y), x)[1]
@everywhere myloss(x, y) = (envelope(x, y), denvelope(x, y))
@everywhere myloss(randn(Float32, 10, 10), randn(Float32, 10, 10))
# Optimization parameters
batchsize = 300
# Objective function for minConf library
count = 0
function objective_function(m_update)
global x, z, count, jopt, seabed_ind;
count += 1
# Update model
model0.m .= Float32.(reshape(m_update, size(model0)))
if modeling_type == "bulk"
model0.rho .= Float32.(reshape(rho_from_slowness(model0.m), size(model0)))
model0.rho[:,1:seabed_ind] .= rhowater
end
# fwi function value and gradient
indsrc = randperm(d_obs.nsrc)[1:batchsize]
if mute_reflections
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_tur[indsrc]*Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt, misfit=myloss)
elseif mute_turning
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_ref[indsrc]*Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt, misfit=myloss)
else
fval, gradient = fwi_objective(model0, Mr_freq[indsrc]*q[indsrc], Ml_freq[indsrc]*get_data(d_obs[indsrc]), options=jopt, misfit=myloss)
end
gradient = reshape(gradient, size(model0))
gradient[:, 1:seabed_ind] .= 0f0
gradient = .125f0*gradient/maximum(abs.(gradient)) # scale for line search
push!(fhistory, fval)
println("iteration: ", count, "\tfval: ", fval, "\tnorm: ", norm(gradient))
save_data(x,z,adjoint(reshape(model0.m.data,size(model0)));
pltfile=dir_out * "FWI slowness $count.png",
title="FWI slowness^2 with L-BFGS $modeling_type: $(frq*1000)Hz, iter $count",
colormap=:rainbow,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="w",
h5varname="m")
save_data(x,z,sqrt.(1f0 ./ adjoint(reshape(model0.m.data,size(model0))));
pltfile=dir_out * "FWI $count.png",
title="FWI velocity with L-BFGS $modeling_type: $(frq*1000)Hz, iter $count",
colormap=:rainbow,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="v")
save_data(x,z,adjoint(reshape(gradient.data,size(model0)));
pltfile=dir_out * "Gradient $count.png",
title="FWI gradient with L-BFGS $modeling_type: $(frq*1000)Hz, iter $count",
clim=(-maximum(gradient.data)/5f0, maximum(gradient.data)/5f0),
colormap=:bluesreds,
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="grad")
save_fhistory(fhistory;
h5file=dir_out * model_file_out * " " * string(count) * ".h5",
h5openflag="r+",
h5varname="fhistory")
return fval, gradient
end
# Bound projection
proj(x) = reshape(median([vec(mminArr) vec(x) vec(mmaxArr)]; dims=2), size(model0))
# FWI with SPG
options = spg_options(verbose=3, maxIter=niterations, memory=3)
sol = spg(objective_function, model0.m.data, proj, options) | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1128 | using DrWatson
@quickactivate "Viking"
using SegyIO
prestk_dir = "$(@__DIR__)/../"
prestk_file = "seismic.segy"
dt = 4 # ms
ns = 1000 # limit number of samples as there is no useful waves below 4 seconds
dir_out = "$(@__DIR__)/trim_segy/"
container = segy_scan(prestk_dir, prestk_file, ["SourceX", "SourceY", "GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
# prepare folder for output data
mkpath(dir_out)
I = length(container)
progress = 0
for i in 1:I
block = container[i]
block_out = SeisBlock(Float32.(block.data[1:ns,:]))
# without copying (copy is not supported for fileheader)
block_out.fileheader = block.fileheader
block_out.fileheader.bfh.DataSampleFormat = 5
block_out.traceheaders = block.traceheaders
block_out.fileheader.bfh.dt = Int(round(dt*1000f0))
block_out.fileheader.bfh.ns = ns
set_header!(block_out, "dt", Int(round(dt*1000f0)))
set_header!(block_out, "ns", ns)
segy_write(dir_out * "shot_$i.sgy", block_out)
if round(i/I*100f0) > progress
global progress = round(i/I*100f0)
@info "progress: ($progress)%"
end
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 5392 | using DrWatson
@quickactivate "Viking"
using Viking
using Statistics, Random, LinearAlgebra, Interpolations, DelimitedFiles, Distributed
using JUDI, NLopt, HDF5, SegyIO, Plots
############# INITIAL DATA #############
modeling_type = "bulk" # slowness, bulk
prestk_dir = "$(@__DIR__)/../proc/"
prestk_file = "s_deghost_gain_mute_dip_radon.sgy"
# dir_out = "$(@__DIR__)/rtm_pqn/"
# dir_out = "$(@__DIR__)/rtm_spg/"
dir_out = "$(@__DIR__)/rtm_lbfgs/"
# choose the most accurate model
# model_file = "$(@__DIR__)/../fwi/fwi_pqn_$(modeling_type)/0.005Hz/model 10.h5"
# model_file = "$(@__DIR__)/../fwi/fwi_spg_$(modeling_type)/0.005Hz/model 10.h5"
model_file = "$(@__DIR__)/../fwi/fwi_lbfgs_$(modeling_type)/0.005Hz/model 10.h5"
# use original wavelet file
# wavelet_file = "$(@__DIR__)/../FarField.dat" # dt=1, skip=25
# or use deghosted wavelet
wavelet_file = "$(@__DIR__)/../proc/FarField_deghosted.dat" # dt=4, skip=0
wavelet_skip_start = 0 # 25 [lines] for raw source and 0 for deghosted source
wavelet_dt = 4 # 1 [ms] for raw source and 4 [ms] for deghosted source
segy_depth_key_src = "SourceSurfaceElevation"
segy_depth_key_rec = "RecGroupElevation"
dense_factor = 2 # make model n-times denser to achieve better stability
seabed = 355 # [m]
# water velocity, km/s
global vwater = 1.5
# water density, g/cm^3
global rhowater = 1.02
# JUDI options
buffer_size = 0f0 # limit model (meters)
# prepare folder for output data
mkpath(dir_out)
# Load data and create data vector
# block = segy_read(prestk_dir * prestk_file)
container = segy_scan(prestk_dir, prestk_file, ["SourceX", "SourceY", "GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
d_obs = judiVector(container; segy_depth_key = segy_depth_key_rec)
srcx = Float32.(get_header(container, "SourceX")[:,1])
grpx = Float32.(get_header(container, "GroupX")[:,1])
min_src_x = minimum(srcx)./1000f0
max_src_x = maximum(srcx)./1000f0
min_grp_x = minimum(grpx)./1000f0
max_grp_x = maximum(grpx)./1000f0
min_cdp_x = (min_src_x+min_grp_x)/2f0
max_cdp_x = (max_src_x+max_grp_x)/2f0
min_x = minimum([min_src_x, min_grp_x])
max_x = maximum([max_src_x, max_grp_x])
# Load starting model (mlog - slowness built with Vs from logs; mvsp - built from VSP)
n, d, o, m0 = read(h5open(model_file, "r"), "n", "d", "o", "m")
n = Tuple(Int64(i) for i in n)
d = Tuple(Float32(i) for i in d)
o = Tuple(Float32(i) for i in o)
i_dense = 1:1/Float32(dense_factor):size(m0)[1]
j_dense = 1:1/Float32(dense_factor):size(m0)[2]
m0_itp = interpolate(m0, BSpline(Linear()))
m0 = m0_itp(i_dense, j_dense)
n = size(m0)
d = Tuple(Float32(i/dense_factor) for i in d)
if modeling_type == "slowness"
model0 = Model(n, d, o, m0_dense)
elseif modeling_type == "bulk"
rho0 = rho_from_slowness(m0)
model0 = Model(n, d, o, m0, rho=rho0)
end
x = (o[1]:d[1]:o[1]+(n[1]-1)*d[1])./1000f0
z = (o[2]:d[2]:o[2]+(n[2]-1)*d[2])./1000f0
global seabed_ind = Int.(round.(seabed./d[2]))
if modeling_type == "slowness"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
elseif modeling_type == "bulk"
model0.m[:,1:seabed_ind] .= (1/vwater)^2
model0.rho[:,1:seabed_ind] .= rhowater
end
# Set up wavelet and source vector
src_geometry = Geometry(container; key = "source", segy_depth_key = segy_depth_key_src)
# setup wavelet
wavelet_raw = readdlm(wavelet_file, skipstart=wavelet_skip_start)
itp = LinearInterpolation(0:wavelet_dt:wavelet_dt*(length(wavelet_raw)-1), wavelet_raw[:,1], extrapolation_bc=0f0)
wavelet = Matrix{Float32}(undef,src_geometry.nt[1],1)
wavelet[:,1] = itp(0:src_geometry.dt[1]:src_geometry.t[1])
q = judiVector(src_geometry, wavelet)
############################################## RTM #################################################
# JUDI options
jopt = JUDI.Options(
space_order=32,
limit_m = true,
buffer_size = buffer_size,
optimal_checkpointing=false,
IC = "isic")
# Right-hand preconditioners (model topmute)
idx_wb = find_water_bottom(reshape(model0.m, size(model0)))
Tm = judiTopmute(size(model0), idx_wb, 10) # Mute water column
S = judiDepthScaling(model0)
Mr = S*Tm
# Left-hand side preconditioners
Ml = judiDataMute(q.geometry, d_obs.geometry, vp=1100f0, t0=0.001f0, mode=:reflection) # keep reflections
# Setup operators
Pr = judiProjection(d_obs.geometry)
F = judiModeling(model0; options=jopt)
Ps = judiProjection(q.geometry)
J = judiJacobian(Pr*F*adjoint(Ps), q)
shot_from = 1
shot_to = length(d_obs)
shot_step = 3 # only compute each 3rd shot (that is enough)
indsrc = rand(shot_from:shot_from+shot_step-1):shot_step:shot_to
# Topmute
d_obs = Ml[indsrc]*d_obs[indsrc]
# RTM
rtm = adjoint(Mr)*adjoint(J[indsrc])*d_obs
data = rtm isa Vector ? rtm : rtm.data
zmax = 3.2f0 # km
nz = sum(z .<= zmax)
# save RTM as HDF5 and plots
save_data(x,z[1:nz],adjoint(reshape(data, size(model0))[:,1:nz]);
pltfile=dir_out * "RTM_$(modeling_type).png",
title="RTM",
clim=(-mean(abs.(data))*15f0, mean(abs.(data))*15f0),
colormap=:seismic,
h5file=dir_out * "rtm_$(modeling_type).h5",
h5openflag="w",
h5varname="rtm")
# save RTM as SEGY
block_out = SeisBlock(collect(reshape(data, size(model0))'))
set_header!(block_out, "dt", Int16(round(z[2]*1e6)))
set_header!(block_out, "CDP", collect(1:size(data)[1]))
set_header!(block_out, "CDPX", collect(Int32.(round.(x*100f0))))
segy_write(dir_out * "rtm_$(modeling_type).sgy", block_out) | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 57 | module Viking
using HDF5, Plots
include("utils.jl")
end | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1387 | export save_data, save_fhistory, rho_from_slowness
function save_data(x,z,data; pltfile,title,colormap,clim=nothing,h5file,h5openflag,h5varname)
@info "save_data: $h5file"
n = (length(x),length(z))
o = (x[1],z[1])
d = (x[2]-x[1],z[2]-z[1])
isnothing(clim) && (clim = (minimum(data),maximum(data)))
plt = Plots.heatmap(x, z, data, c=colormap,
xlims=(x[1],x[end]),
ylims=(z[1],z[end]), yflip=true,
title=title,
clim=clim,
xlabel="Lateral position [km]",
ylabel="Depth [km]",
dpi=600)
Plots.savefig(plt, pltfile)
fid = h5open(h5file, h5openflag)
(haskey(fid, h5varname)) && (delete_object(fid, h5varname))
(haskey(fid, "o")) && (delete_object(fid, "o"))
(haskey(fid, "n")) && (delete_object(fid, "n"))
(haskey(fid, "d")) && (delete_object(fid, "d"))
write(fid,
h5varname, Matrix(adjoint(data)), # convert adjoint(Matrix) type to Matrix
"o", collect(o.*1000f0),
"n", collect(n),
"d", collect(d.*1000f0))
close(fid)
end
function save_fhistory(fhistory; h5file,h5openflag,h5varname)
@info "save_fhistory: $h5file"
fid = h5open(h5file, h5openflag)
(haskey(fid, h5varname)) && (delete_object(fid, h5varname))
write(fid, h5varname, fhistory)
close(fid)
end
"""
Recalculate slowness^2 to density using Gardner formulae
"""
rho_from_slowness(m) = 0.23.*(sqrt.(1f0 ./ m).*1000f0).^0.25 | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2435 | # Example for linearized modeling with Flux networks
# Author: Mathias Louboutin, [email protected]
# Date: June 2022
# Adapted from https://github.com/slimgroup/JUDI4Flux.jl/tree/master/examples
using JUDI, SegyIO, JOLI, Flux
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v0 = ones(Float32,n) .+ 0.4f0
v[:, Int(round(end/2)):end] .= 4f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
dm = vec(m - m0)
# Setup model structure
nsrc = 1 # number of sources
model0 = Model(n, d, o, m0)
# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)
# receiver sampling and recording time
time = 1000f0 # receiver recording time [ms]
dt = 1f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)
## Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell([600f0])
ysrc = convertToCell([0f0])
zsrc = convertToCell([20f0])
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dt, t=time)
# setup wavelet
f0 = 0.01f0 # MHz
wavelet = ricker_wavelet(time, dt, f0)
q = judiVector(srcGeometry, wavelet)
# return linearized data as Julia array
opt = Options(return_array=true)
# Non-linear forward modeling operator
F0 = judiModeling(model0, srcGeometry, recGeometry; options=opt)
num_samples = recGeometry.nt[1] * nxrec
##################################################################################
# Fully connected neural network with linearized modeling operator
n_in = 100
n_out = 10
W1 = randn(Float32, prod(model0.n), n_in)
b1 = randn(Float32, prod(model0.n))
W2 = judiJacobian(F0, q)
b2 = randn(Float32, num_samples)
W3 = randn(Float32, n_out, num_samples)
b3 = randn(Float32, n_out)
function network(x)
x = W1*x .+ b1
x = vec(W2*x) .+ b2
x = W3*x .+ b3
return x
end
# Inputs and target
x = zeros(Float32, n_in)
y = randn(Float32, n_out)
# Evaluate MSE loss
loss(x, y) = Flux.mse(network(x), y)
# Compute gradient w.r.t. x and y
Δx, Δy = gradient(loss, x, y)
# Compute gradient for x, y and weights (except for W2)
p = Flux.params(x, y, W1, b1, b2, W3, b3)
gs = gradient(() -> loss(x, y), p)
# Access gradients
Δx = gs[x]
ΔW1 = gs[W1]
Δb1 = gs[b1]
# and so on...
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1611 | # Example for extended source modeling with Flux
# Author: Mathias Louboutin, [email protected]
# Date: June 2022
# Adapted from https://github.com/slimgroup/JUDI4Flux.jl/tree/master/examples
using JUDI, SegyIO, JOLI, Flux
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v[:, Int(round(end/2)):end] .= 4f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
# Setup model structure
nsrc = 1 # number of sources
model = Model(n, d, o, m)
# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)
# receiver sampling and recording time
time = 1000f0 # receiver recording time [ms]
dt = 1f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)
# setup wavelet
f0 = 0.01f0 # MHz
wavelet = ricker_wavelet(time, dt, f0)
# return linearized data as Julia array
opt = Options(return_array=true, dt_comp=dt)
# Linear operators
Pr = judiProjection(recGeometry)
A_inv = judiModeling(model; options=opt)
Pw = judiLRWF(dt, wavelet)
F = Pr*A_inv*adjoint(Pw)
# Extended source weight
w = randn(Float32, model.n)
#####################################################################################
# Extended source forward
# Build CNN
w = reshape(w, n[1], n[2], 1, 1)
m = reshape(m, n[1], n[2], 1, 1)
y = randn(Float32, recGeometry.nt[1], nxrec, 1, 1)
loss(w, m, y) = Flux.mse(F(m, w), y)
p = Flux.params(w, m, y)
gs = gradient(() -> loss(w, m, y), p)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1953 | # Example for extended source modeling with Flux
# Author: Mathias Louboutin, [email protected]
# Date: June 2022
# Adapted from https://github.com/slimgroup/JUDI4Flux.jl/tree/master/examples
using JUDI, SegyIO, JOLI, Flux
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v[:, Int(round(end/2)):end] .= 4f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
# Setup info and model structure
nsrc = 1 # number of sources
model = Model(n, d, o, m)
# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)
# receiver sampling and recording time
time = 1000f0 # receiver recording time [ms]
dt = 1f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)
# setup wavelet
f0 = 0.01f0 # MHz
wavelet = ricker_wavelet(time, dt, f0)
# return linearized data as Julia array
opt = Options(return_array=true, dt_comp=dt)
# Linear operators
Pr = judiProjection(recGeometry)
A_inv = judiModeling( model; options=opt)
Pw = judiLRWF(dt, wavelet)
F = Pr*A_inv*adjoint(Pw)
#####################################################################################
# Build CNN
n_in = 10
n_out = 8
batchsize = nsrc
conv1 = Conv((3, 3), n_in => 1, stride=1, pad=1)
conv2 = Conv((3, 3), 1 => n_out, stride=1, pad=1)
function network(x, m)
x = conv1(x)
x = F(m, x)
x = F'(m, x)
x = conv2(x)
return x
end
loss(x, m, y) = Flux.mse(network(x, m), y)
x = randn(Float32, n[1], n[2], n_in, batchsize)
m = reshape(m, n[1], n[2], 1, 1) #
y = randn(Float32, n[1], n[2], n_out, batchsize)
# Compute gradient of parameters
p = Flux.params(x, m, y, conv1, conv2)
gs = gradient(() -> loss(x, m, y), p)
# Access gradients
Δx = gs[x]
Δm = gs[m]
Δy = gs[y]
Δw1 = gs[conv1.weight]
Δb1 = gs[conv1.bias]
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2692 | # Example for basic 2D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, [email protected]
# Date: January 2017
#
using JUDI, SegyIO, LinearAlgebra, PyPlot, IterativeSolvers, JOLI
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v[:,Int(round(end/2)):end] .= 5f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
# Setup model structure
nsrc = 1 # number of sources
model = Model(n, d, o, m)
# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)
# receiver sampling and recording time
time = 2000f0 # receiver recording time [ms]
dt = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)
# Source wavelet
f0 = 0.01f0 # kHz
wavelet = ricker_wavelet(time, dt, f0)
###################################################################################################
# Write shots as segy files to disk
opt = Options()
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model; options=opt)
# Random weights (size of the model)
w = judiWeights(randn(Float32, model.n))
# Create operator for injecting the weights, multiplied by the provided wavelet(s)
Pw = judiLRWF(dt, wavelet)
# Model observed data w/ extended source
lambda = 1f2
I = joDirac(prod(model.n), DDT=Float32, RDT=Float32)
F = Pr*F*adjoint(Pw)
F̄ = [F; lambda*I]
# Simultaneous observed data
d_sim = F*w
# # Adjoint operation
w_adj = adjoint(F)*d_sim
# # LSQR
w_inv = 0f0 .* w
w_inv_no_damp = 0f0 .* w
lsqr!(w_inv, F̄, [d_sim; lambda*w]; maxiter=2, verbose=true, damp=1e2)
lsqr!(w_inv_no_damp, F, d_sim; maxiter=2, verbose=true, damp=1e2)
d_pred = F*w_inv;
d_pred_no_damp = F*w_inv_no_damp;
# Plot results
figure()
subplot(1,3,1)
imshow(d_sim.data[1], vmin=-5e2, vmax=5e2, cmap="gray"); title("Observed data")
subplot(1,3,2)
imshow(d_pred.data[1], vmin=-2e2, vmax=2e2, cmap="gray"); title("Predicted data")
subplot(1,3,3)
imshow(d_pred_no_damp.data[1], vmin=-2e2, vmax=2e2, cmap="gray"); title("Predicted data no damp")
figure()
subplot(2,2,1)
imshow(w.weights[1], vmin=-3, vmax=3, cmap="gray"); title("Weights")
subplot(2,2,2)
imshow(w_adj.weights[1], vmin=minimum(w_adj), vmax=maximum(w_adj), cmap="gray"); title("Adjoint")
subplot(2,2,3)
imshow(w_inv.weights[1], vmin=minimum(w_inv), vmax=maximum(w_inv), cmap="gray"); title("D-LSQR")
subplot(2,2,4)
imshow(w_inv_no_damp.weights[1], vmin=minimum(w_inv), vmax=maximum(w_inv), cmap="gray"); title("LSQR")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2124 | # 2D FWI on Overthrust model using minConf library
# Author: Philipp Witte, [email protected]
# Date: December 2017
#
using Statistics, Random, LinearAlgebra
using JUDI, HDF5, SegyIO, SlimOptim, SlimPlotting
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ m0)
vmin = ones(Float32, model0.n) .* 1.3f0
vmax = ones(Float32, model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
############################### FWI ###########################################
F0 = judiModeling(deepcopy(model0), src_geometry, d_obs.geometry)
# Optimization parameters
niterations = parse(Int, get(ENV, "NITER", "10"))
batchsize = 16
fhistory_SGD = zeros(Float32, niterations)
# Projection operator for bound constraints
proj(x) = reshape(median([vec(mmin) vec(x) vec(mmax)]; dims=2),model0.n)
ls = BackTracking(order=3, iterations=10, )
# Main loop
for j=1:niterations
# get fwi objective function value and gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, gradient = fwi_objective(model0, q[i], d_obs[i])
p = -gradient/norm(gradient, Inf)
println("FWI iteration no: ",j,"; function value: ",fval)
fhistory_SGD[j] = fval
# linesearch
function ϕ(α)
F0.model.m .= proj(model0.m .+ α * p)
misfit = .5*norm(F0[i]*q[i] - d_obs[i])^2
@show α, misfit
return misfit
end
step, fval = ls(ϕ, 1f-1, fval, dot(gradient, p))
# Update model and bound projection
model0.m .= proj(model0.m .+ step .* p)
end
figure()
plot_velocity(model0.m'.^(-.5))
title("FWI with SGD")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2387 | # 2D Envelope FWI on Overthrust model with SPG using minConf library and Zygote for the derivative of the Envelope misfit
# Author: Mathias Louboutin
# Date: September 2022
#
using Statistics, Random, LinearAlgebra, PyPlot, Distributed
using JUDI, SlimOptim, HDF5, SegyIO
@everywhere using JUDI.FFTW, Zygote
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ m0)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
############################### FWI ###########################################
@everywhere function H(x)
n = size(x, 1)
σ = ifftshift(sign.(-n/2+1:n/2))
y = imag(ifft(σ.*fft(x, 1), 1))
return y
end
@everywhere envelope(x, y) = sum(abs2.((x - y) .+ 1im .* H(x - y)))
@everywhere denvelope(x, y) = gradient(xs->envelope(xs, y), x)[1]
@everywhere myloss(x, y)= (envelope(x, y), denvelope(x, y))
@everywhere myloss(randn(Float32, 10, 10), randn(Float32, 10, 10))
# Optimization parameters
fevals = parse(Int, get(ENV, "NITER", "10"))
batchsize = 8
# Objective function for minConf library
count = 0
function objective_function(x)
model0.m .= reshape(x,model0.n);
# fwi function value and gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, grad = fwi_objective(model0, q[i], d_obs[i]; misfit=myloss)
grad = .125f0*grad/maximum(abs.(grad)) # scale for line search
global count; count+= 1
return fval, grad
end
# Bound projection
proj(x) = reshape(median([vec(mmin) vec(x) vec(mmax)]; dims=2),model0.n)
# FWI with SPG
options = spg_options(verbose=3, maxIter=fevals, memory=3)
sol = spg(objective_function, model0.m, proj, options)
# Plot result
imshow(reshape(sqrt.(1f0 ./ sol.x), model0.n)', extent=[0, 10, 3, 0])
xlabel("Lateral position [km]")
ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1861 | # 2D FWI on Overthrust model with L-BFGS using NLopt library
# Author: Philipp Witte, [email protected]
# Date: December 2017
#
using Statistics, Random, LinearAlgebra
using JUDI, HDF5, NLopt, SegyIO
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./m0)
vmin = ones(Float32, model0.n) .* 1.3f0
vmax = ones(Float32, model0.n) .* 6.5f0
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry, wavelet)
############################### FWI ###########################################
# optimization parameters
batchsize = 16
count = 0
# NLopt objective function
println("No. ", "fval ", "norm(gradient)")
function f!(x,grad)
# Update model
model0.m .= convert(Array{Float32, 2}, reshape(x, model0.n))
# Seclect batch and calculate gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, gradient = fwi_objective(model0, q[i], d_obs[i])
# Reset gradient in water column to zero
gradient = reshape(gradient, model0.n)
gradient[:, 1:21] .= 0f0
grad[1:end] = vec(gradient)
global count; count += 1
println(count, " ", fval, " ", norm(grad))
return convert(Float64, fval)
end
# Optimization parameters
opt = Opt(:LD_LBFGS, prod(model0.n))
lower_bounds!(opt, mmin); upper_bounds!(opt, mmax)
min_objective!(opt, f!)
maxeval!(opt, parse(Int, get(ENV, "NITER", "10")))
(minf, minx, ret) = optimize(opt, vec(model0.m.data))
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3647 | # 2D FWI on Overthrust model using minConf library
# Authors:
# Philipp Witte, [email protected]
# Date: December 2017
# Mathias Louboutin, [email protected]
# Date: January 2022
using Statistics, Random, LinearAlgebra
using JUDI, SlimOptim, HDF5, SegyIO, PyPlot
using SetIntersectionProjection
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ m0)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
############################### FWI ###########################################
# Optimization parameters
niterations = parse(Int, get(ENV, "NITER", "10"))
batchsize = 10
fhistory_SGD = zeros(Float32,niterations)
########## Setup constraints
# with constraints:
options=PARSDMM_options()
options.FL=Float32
options=default_PARSDMM_options(options,options.FL)
options.adjust_gamma = true
options.adjust_rho = true
options.adjust_feasibility_rho = true
options.Blas_active = true
options.maxit = 1000
options.feas_tol = 0.001
options.obj_tol = 0.001
options.evol_rel_tol = 0.00001
options.rho_ini=[1.0f0]
set_zero_subnormals(true)
BLAS.set_num_threads(2)
options.parallel=false
options.feasibility_only = false
options.zero_ini_guess=true
constraint = Vector{SetIntersectionProjection.set_definitions}()
#bounds:
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
m_min = vec((1f0 ./ vmax).^2)
m_max = vec((1f0 ./ vmin).^2)
set_type = "bounds"
TD_OP = "identity"
app_mode = ("matrix","")
custom_TD_OP = ([],false)
push!(constraint, set_definitions(set_type,TD_OP,m_min,m_max,app_mode,custom_TD_OP))
#TV
(TV,dummy1,dummy2,dummy3) = get_TD_operator(model0,"TV",options.FL)
m_min = 0.0
m_max = norm(TV*vec(v0),1) *2.0f0
set_type = "l1"
TD_OP = "TV"
app_mode = ("matrix","")
custom_TD_OP = ([],false)
push!(constraint, set_definitions(set_type,TD_OP,m_min,m_max,app_mode,custom_TD_OP))
#set up constraints, precompute some things and define projector
(P_sub,TD_OP,set_Prop) = setup_constraints(constraint,model0,options.FL)
(TD_OP,AtA,l,y) = PARSDMM_precompute_distribute(TD_OP,set_Prop,model0,options)
options.rho_ini = ones(length(TD_OP))*10.0
proj_intersection = x-> PARSDMM(x, AtA, TD_OP, set_Prop, P_sub, model0, options)
function proj(input)
input = Float32.(input)
(x,dummy1,dummy2,dymmy3) = proj_intersection(vec(input.data))
return reshape(x, model0.n)
end
########## Run
F0 = judiModeling(deepcopy(model0), q.geometry, d_obs.geometry)
ls = BackTracking(order=3, iterations=10)
# Main loop
for j=1:niterations
# get fwi objective function value and gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, gradient = fwi_objective(model0,q[i],d_obs[i])
p = -gradient/norm(gradient, Inf)
println("FWI iteration no: ",j,"; function value: ",fval)
fhistory_SGD[j] = fval
# linesearch
function ϕ(α)
F0.model.m .= proj(model0.m .+ α * p)
misfit = .5*norm(F0[i]*q[i] - d_obs[i])^2
return misfit
end
step, fval = ls(ϕ, 1f0, fval, dot(gradient, p))
# Update model and bound projection
model0.m .= proj(model0.m .+ step .* p)
end
figure(); imshow(sqrt.(1f0./adjoint(model0.m))); title("FWI with SPG")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1878 | # 2D FWI on Overthrust model with SPG using minConf library
# Author: Philipp Witte, [email protected]
# Date: December 2017
#
using Statistics, Random, LinearAlgebra, PyPlot
using JUDI, SlimOptim, HDF5, SegyIO
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ m0)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
############################### FWI ###########################################
# Optimization parameters
fevals = parse(Int, get(ENV, "NITER", "10"))
batchsize = 8
# Objective function for minConf library
count = 0
function objective_function(x)
model0.m .= reshape(x,model0.n);
# fwi function value and gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, grad = fwi_objective(model0, q[i], d_obs[i])
grad = .125f0*grad/maximum(abs.(grad)) # scale for line search
global count; count+= 1
return fval, grad
end
# Bound projection
proj(x) = reshape(median([vec(mmin) vec(x) vec(mmax)]; dims=2),model0.n)
# FWI with SPG
options = spg_options(verbose=3, maxIter=fevals, memory=3)
sol = spg(objective_function, model0.m, proj, options)
# Plot result
imshow(reshape(sqrt.(1f0 ./ sol.x), model0.n)', extent=[0, 10, 3, 0])
xlabel("Lateral position [km]")
ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2353 | # 2D FWI with student's t misfit on Overthrust model with SPG using minConf library
# Author: Mathias Louboutin
# Date: September 2022
#
using Statistics, Random, LinearAlgebra, PyPlot, SlimPlotting
using JUDI, SlimOptim, HDF5, SegyIO
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ m0)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
## Add outliers to the data
for s=1:d_obs.nsrc
# wrongly scale a few traces
nrec = d_obs[s].geometry.nrec[1]
inds = rand(1:nrec, 10)
d_obs.data[s][:, inds] .*= 20
end
############################### FWI ###########################################
# Optimization parameters
fevals = parse(Int, get(ENV, "NITER", "10"))
batchsize = 8
# Objective function for minConf library
count = 0
function objective_function(x, misfit=mse)
model0.m .= reshape(x,model0.n);
# fwi function value and gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, grad = fwi_objective(model0, q[i], d_obs[i]; misfit=misfit)
grad = .125f0*grad/maximum(abs.(grad)) # scale for line search
global count; count+= 1
return fval, vec(grad.data)
end
# Bound projection
proj(x) = reshape(median([vec(mmin) vec(x) vec(mmax)]; dims=2), size(x))
# Compare l2 with students t
ϕmse = x->objective_function(x)
ϕst = x->objective_function(x, studentst)
# FWI with SPG
options = spg_options(verbose=3, maxIter=fevals, memory=3)
solmse = spg(ϕmse, vec(m0), proj, options)
solst = spg(ϕst, vec(m0), proj, options)
# Plot result
figure(figsize=(10, 10))
subplot(211)
plot_velocity(reshape(solmse.x.^(-.5), model0.n)', d; name="MSE", new_fig=false)
subplot(212)
plot_velocity(reshape(solst.x.^(-.5), model0.n)', d; name="Student's t", new_fig=false)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1971 | # FWI on Overthrust model using minConf library
# Author: Philipp Witte, [email protected]
# Date: December 2017
#
using Statistics, Random, LinearAlgebra
using JUDI, HDF5, SegyIO, PyPlot, IterativeSolvers
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1 ./ m0)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
############################### FWI ###########################################
# Set up operators
F = judiModeling(model0, q.geometry, d_obs.geometry)
J = judiJacobian(F,q)
# Optimization parameters
maxiter = parse(Int, get(ENV, "NITER", "10"))
maxiter_GN = parse(Int, get(ENV, "NITER", "5"))
batch_size = 5 * parse(Int, get(ENV, "NITER", "$(q.nsrc ÷ 5)"))
fhistory_GN = zeros(Float32,maxiter)
proj(x) = reshape(median([vec(mmin) vec(x) vec(mmax)]; dims=2),model0.n)
# Gauss-Newton method
for j=1:maxiter
println("Iteration: ",j)
i = randperm(q.nsrc)[1:batch_size]
# # Model predicted data for subset of sources
d_pred = F[i]*q[i]
fhistory_GN[j] = .5f0*norm(d_pred - d_obs[i])^2
# GN update direction
p = lsqr!(similar(model0.m), J[i], d_pred - d_obs[i]; maxiter=maxiter_GN, verbose=true)
# update model and bound constraints
model0.m .= proj(model0.m .- reshape(p, model0.n)) # alpha=1
end
figure(); imshow(sqrt.(1f0./model0.m)'); title("FWI with Gauss-Newton")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3246 | # Example for basic 2D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Mathias Louboutin, [email protected]
# February 2022
using JUDI, HDF5, SlimPlotting, PyPlot, LinearAlgebra, Downloads, SlimPlotting, Distributed
# Load model
data_path = dirname(pathof(JUDI))*"/../data/"
# Load migration velocity model
if ~isfile(data_path*"marmousi_model.h5")
Downloads.download("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_model.h5", data_path*"marmousi_model.h5")
end
n, d, o, m0, m = read(h5open(data_path*"marmousi_model.h5","r"), "n", "d", "o", "m0", "m")
# Subsample tso that runs ok with ci
fact = 3
m = m[1:fact:end, 1:fact:end]
m0 = m0[1:fact:end, 1:fact:end]
n = size(m)
d = (fact*d[1], fact*d[2]) # Base is 5m spacing
# Setup info and model structure
nsrc = 21 # number of sources
model = Model(n, d, o, m)
model0 = Model(n, d, o, m0)
# Set up receiver geometry
nxrec = n[1]
xrec = range(0f0, stop=(n[1] - 1)*d[1], length=nxrec)
yrec = 0f0
zrec = range(d[end], stop=d[end], length=nxrec)
# receiver sampling and recording time
td = 3000f0 # receiver recording time [ms]
dtd = 2f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtd, t=td, nsrc=nsrc)
# Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell(range(0f0, stop=(n[1] - 1)*d[1], length=nsrc))
ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc))
zsrc = convertToCell(range(d[2], stop=d[2], length=nsrc))
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtd, t=td)
# setup wavelet
f0 = 0.015f0 # kHz
wavelet = ricker_wavelet(td, dtd, f0)
q = judiVector(srcGeometry, wavelet)
###################################################################################################
# Infer subsampling based on free memory
mem = Sys.free_memory()/(1024^3)
grad_mem = 40
t_sub = max(1, ceil(Int, nworkers()*grad_mem/mem))
# Write shots as segy files to disk
opt = Options(IC="isic", subsampling_factor=t_sub)
# Setup operators
F = judiModeling(model, srcGeometry, recGeometry; options=opt)
F0 = judiModeling(model0, srcGeometry, recGeometry; options=opt)
J = judiJacobian(F0, q)
# Nonlinear modeling
dobs = F*q
d0 = F0*q
I = inv(judiIllumination(J; mode="uv"))
rtm = J'*(d0 - dobs)
# Plot illum
c1, c2 = maximum(I.illums["u"])/10, maximum(I.illums["v"])/2
figure()
subplot(311)
plot_velocity(I.illums["u"]'; new_fig=false, cmap="gist_ncar", vmax=c1)
subplot(312)
plot_velocity(I.illums["v"]'; new_fig=false, cmap="gist_ncar", vmax=c2)
subplot(313)
plot_velocity(I.illums["u"]'.*I.illums["v"]'; new_fig=false, cmap="gist_ncar", vmax=c1*c2)
# savefig("Illums.png", bbox_inches="tight")
tight_layout()
# Plot rtm with corrections
figure(figsize=(10, 5))
subplot(221)
plot_simage(rtm'; new_fig=false, name="rtm", aspect="auto")
subplot(222)
plot_simage((I*rtm)'; new_fig=false, name="rtmu", aspect="auto")
subplot(223)
plot_simage((I("v")*rtm)'; new_fig=false, name="rtmv", aspect="auto")
subplot(224)
plot_simage((I("uv")*rtm)'; new_fig=false, name="rtmuv", aspect="auto")
tight_layout()
# savefig("rtms.png", bbox_inches="tight")
tight_layout()
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 6807 | #' # Imaging conditions in JUDI
#' ---
#' title: Overview of JUDI imaging conditions for inversion
#' author: Mathias Louboutin
#' date: October 2022
#' ---
#' This example script is written using [Weave.jl](https://github.com/JunoLab/Weave.jl) and can be converted to different format for documentation and usage
#' This example is converted to a markdown file for the documentation.
#' # Import JUDI, Linear algebra utilities and Plotting
using JUDI, LinearAlgebra, PyPlot
#+ echo = false; results = "hidden"
close("all")
#' # Create a JUDI model structure
#' In JUDI, a `Model` structure contains the grid information (origin, spacing, number of gridpoints)
#' and the physical parameters. The squared slowness is always required as the base physical parameter for propagation. In addition,
#' JUDI supports additional physical representations. First we accept `density` that can either be a direct input `Model(n, d, o, m, rho)` or
#' an optional keyword argument `Model(n,d,o,m;rho=rho)`. Second, we also provide VTI/TTI kernels parametrized by the THomsen parameters that can be input as keyword arguments
#' `Model(n,d,o,m; rho=rho, epsilon=epsilon;delta=delta,theta=theta,phi=phi)`. Because the thomsen parameters are optional the propagator wil lonloy use the ones provided.
#' For example `Model(n,d,o,m; rho=rho, epsilon=epsilon;delta=delta)` will infer a VTI propagation
#' ## Create discrete parameters
# Set up model structure
n = (601, 151) # (x,y,z) or (x,z)
d = (10f0, 10f0)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.5f0
v0 = ones(Float32,n) .+ 0.51f0
v[:, 101:end] .= 2f0
v0[:, 101:end] .= 2f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
# Setup model structure
nsrc = 1 # number of sources
model = Model(n, d, o, m)
model0 = Model(n, d, o, m0)
#' # Create acquisition geometry
#' In this simple usage example, we create a simple acquisiton by hand. In practice the acquisition geometry will be defined by the dataset
#' beeing inverted. We show in a spearate tutorial how to use [SegyIO.jl](https://github.com/slimgroup/SegyIO.jl) to handle SEGY seismic datasets in JUDI.
#' ## Create source and receivers positions at the surface
# Set up receiver geometry
xrec = [1 * (n[1] - 1) * d[1] / 4]
yrec = [0f0] # WE have to set the y coordiante to zero (or any number) for 2D modeling
zrec = [d[1]]
# receiver sampling and recording time
timeD = 2500f0 # receiver recording time [ms]
dtD = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtD, t=timeD, nsrc=nsrc)
#' The source geometry is a but different. Because we want to create a survey with `nsrc` shot records, we need
#' to convert the vector of sources postions `[s0, s1, ... sn]` into an array of array [[s0], [s1], ...] so that
#' JUDI understands that this is a set of indepednet `nsrc`
xsrc = 3 * (n[1] - 1) * d[1] / 4
ysrc = 0f0
zsrc = d[1]
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtD, t=timeD)
#' # Source judiVector
#' Finally, with the geometry defined, we can create a source wavelet (a simple Ricker wavelet here) a our first `judiVector`
#' In JUDI, a `judiVector` is the core structure that represent a acquisition-geometry based dataset. This structure encapsulate
#' the physical locations (trace coordinates) and corrsponding data trace in a source-based structure. for a given `judiVector` `d` then
#' `d[1]` will be the shot record for the first source, or in the case of the source term, the first source wavelet and its positon.
# setup wavelet
f0 = 0.015f0 # kHz
wavelet = ricker_wavelet(timeD, dtD, f0)
q = judiVector(srcGeometry, wavelet)
#' # Modeling
#' With our survey and subsurface model setup, we can now model and image seismic data.
#' Linear Operators
#' The core idea behind JUDI is to abstract seismic inverse problems in term of linear algebra. In its simplest form, seismic inversion can be formulated as
#' ```math
#' \underset{\mathbf{m}}{\text{argmin}} \ \ \phi(\mathbf{m}) = \frac{1}{2} ||\mathbf{P}_r \mathbf{F}(\mathbf{m}) \mathbf{P}_s^{\top} \mathbf{q} - \mathbf{d} ||_2^2 \\
#' \text{ } \\
#' \nabla_{\mathbf{m}} \phi(\mathbf{m}) = \mathbf{J}(\mathbf{m}, \mathbf{q})^{\top} (\mathbf{P}_r \mathbf{F}(\mathbf{m}) \mathbf{P}_s^{\top} \mathbf{q} - \mathbf{d})
#' ```
#'
#' where $\mathbf{P}_r$ is the receiver projection (measurment operator) and $\mathbf{P}_s^{\top}$ is the source injection operator (adjoint of measurment at the source location).
#' Therefore, we bastracted these operation to be able to define these operators
# Setup operators
F = judiModeling(model, srcGeometry, recGeometry)
F0 = judiModeling(model0, srcGeometry, recGeometry)
#' # Model and image data
#' We first model synthetic data using our defined source and true model
# Nonlinear modeling
dobs = F*q
#' # Inversion
#' Our main goal is to provide an inversion framework for seismic inversion. In this tutorial, we highlight the different imaging conditions
#' available in JUDI. These imaging conditions are designed to enhanced properties in the gradient beneficial to the inversion problem such
#' as the frequency content. Because these imaging conditions are intended tho be used in potential least-square problems, we also implemented
#' (and test as part of our CI) their adjoint such that we can model linearized data with the JAcobian that correspond to the adjoint of the
#' modified adjoint state crosscorelation imaging condition.
#' We compute now the FWI gradient with three different imaging conditions:
#' - "as" adjoint state imaging condition. This is the conventional cross-correlation adjoint state gradient.
#' - "isic" that computes the inverse scattering imaging condition designed to provide reflections for LSRTM (high frequency content)
#' - "FWI" that computes the complement of "isic" and brings up the low frequency content for velocity inversion
#'
#' These can be specified in the Option structure via `IC="as/isic/fwi`
fas, g_as = fwi_objective(model0, q, 0*dobs; options=Options(IC="as", space_order=12))
fisic, g_isic = fwi_objective(model0, q, 0*dobs; options=Options(IC="isic", space_order=12))
ffwi, g_fwi = fwi_objective(model0, q, 0*dobs; options=Options(IC="fwi", space_order=12))
#' We show below the sensitivity kernels for a single source-receiver pair highlighting the inversion properties of these imaging conditions
ni(x) = 10 * x ./ norm(x, Inf)
fig = figure(figsize=(8, 12))
subplot(311)
imshow(ni(g_isic'), cmap="seismic", aspect="auto", vmin=-1, vmax=1)
title("ISIC")
subplot(312)
imshow(ni(g_fwi'), cmap="seismic", aspect="auto", vmin=-1, vmax=1)
title("FWI")
subplot(313)
imshow(ni(g_as'), cmap="seismic", aspect="auto", vmin=-1, vmax=1)
title("Adjoint State")
tight_layout()
display(fig)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2698 | # LS-RTM of the 2D Marmousi model using LSQR
# Author: [email protected]
# Date: June 2022
using Statistics, Random, LinearAlgebra, JOLI, Distributed
using JUDI, SegyIO, HDF5, PyPlot, IterativeSolvers
# Load migration velocity model
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_model.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/marmousi_model.h5", "r"), "n", "d", "o", "m0")
# Smaller model for CI
if get(ENV, "NITER", "10") == "2"
fact = 4
m0 = m0[1:fact:end, 1:fact:end]
n = size(m0)
d = d .* fact
else
fact = 1
end
# Set up model structure
model0 = Model(n, d, o, m0)
grad_mem = 40 / (fact^3) # Based on n and CFL condition
# Load data
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_2D.segy")
end
block = segy_scan(JUDI.JUDI_DATA, "marmousi_2D.segy", ["GroupX","GroupY","RecGroupElevation","SourceSurfaceElevation","dt"])
d_lin = judiVector(block) # linearized observed data
# Set up wavelet
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.03) # 30 Hz wavelet
q = judiVector(src_geometry, wavelet)
###################################################################################################
# Infer subsampling based on free memory
mem = Sys.free_memory()/(1024^3)
t_sub = max(1, ceil(Int, .5*nworkers()*grad_mem/mem))
# Setup operators
opt = Options(subsampling_factor=t_sub, isic=true) # ~40 GB of memory per source without subsampling
M = judiModeling(model0, q.geometry, d_lin.geometry; options=opt)
J = judiJacobian(M, q)
# Right-hand preconditioners (model topmute)
Mr = judiTopmute(model0; taperwidth=10)
# Left-hand Preconditionners (data top mute)
Ml = judiDataMute(q.geometry, d_lin.geometry)
#' set up number of iterations
niter = parse(Int, get(ENV, "NITER", "10"))
# Default to 64, 5 for CI only with NITER=1
nsrc = 5 * parse(Int, get(ENV, "NITER", "10"))
indsrc = randperm(q.nsrc)[1:nsrc]
lsqr_sol = zeros(Float32, prod(model0.n))
# LSQR
dinv = d_lin[indsrc]
Jinv = J[indsrc]
Jp = Ml[indsrc]*Jinv*Mr
dinvp = Ml[indsrc]*dinv
lsqr!(lsqr_sol, Jp, dinvp; maxiter=niter)
# Save final velocity model, function value and history
h5open("lsrtm_marmousi_lsqr_result.h5", "w") do file
write(file, "x", reshape(lsqr_sol, model0.n))
end
# Plot final image
figure(); imshow(reshape(lsqr_sol, model0.n)', extent = (0, 7.99, 3.19, 0), cmap = "gray", vmin = -3e-2, vmax = 3e-2)
title("LS-RTM with LSQR")
xlabel("Lateral position [km]")
ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 9957 | #' # Modeling and inversion with JUDI
#' ---
#' title: Overview of JUDI modeling and inversion usage
#' author: Mathias Louboutin, Philipp Witte
#' date: April 2022
#' ---
#' This example script is written using [Weave.jl](https://github.com/JunoLab/Weave.jl) and can be converted to different format for documentation and usage
#' This example is converted to a markdown file for the documentation.
#' # Import JUDI, Linear algebra utilities and Plotting
using JUDI, LinearAlgebra, SlimPlotting
#+ echo = false; results = "hidden"
close("all")
imcmap = "cet_CET_L1"
dcmap = "PuOr"
#' # Create a JUDI model structure
#' In JUDI, a `Model` structure contains the grid information (origin, spacing, number of gridpoints)
#' and the physical parameters. The squared slowness is always required as the base physical parameter for propagation. In addition,
#' JUDI supports additional physical representations. First we accept `density` that can either be a direct input `Model(n, d, o, m, rho)` or
#' an optional keyword argument `Model(n,d,o,m;rho=rho)`. Second, we also provide VTI/TTI kernels parametrized by the THomsen parameters that can be input as keyword arguments
#' `Model(n,d,o,m; rho=rho, epsilon=epsilon;delta=delta,theta=theta,phi=phi)`. Because the thomsen parameters are optional the propagator wil lonloy use the ones provided.
#' For example `Model(n,d,o,m; rho=rho, epsilon=epsilon;delta=delta)` will infer a VTI propagation
#' ## Create discrete parameters
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.5f0
v0 = ones(Float32,n) .+ 0.5f0
v[:,Int(round(end/2)):end] .= 3.5f0
rho = (v0 .+ .5f0) ./ 2
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
dm = vec(m0 - m)
# Setup model structure
nsrc = 2 # number of sources
model = Model(n, d, o, m)
model0 = Model(n, d, o, m0)
#' # Create acquisition geometry
#' In this simple usage example, we create a simple acquisiton by hand. In practice the acquisition geometry will be defined by the dataset
#' beeing inverted. We show in a spearate tutorial how to use [SegyIO.jl](https://github.com/slimgroup/SegyIO.jl) to handle SEGY seismic datasets in JUDI.
#' ## Create source and receivers positions at the surface
# Set up receiver geometry
nxrec = 120
xrec = range(0f0, stop=(n[1]-1)*d[1], length=nxrec)
yrec = 0f0 # WE have to set the y coordiante to zero (or any number) for 2D modeling
zrec = range(d[1], stop=d[1], length=nxrec)
# receiver sampling and recording time
timeD = 1250f0 # receiver recording time [ms]
dtD = 2f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtD, t=timeD, nsrc=nsrc)
#' The source geometry is a but different. Because we want to create a survey with `nsrc` shot records, we need
#' to convert the vector of sources postions `[s0, s1, ... sn]` into an array of array [[s0], [s1], ...] so that
#' JUDI understands that this is a set of indepednet `nsrc`
xsrc = convertToCell(range(0f0, stop=(n[1]-1)*d[1], length=nsrc))
ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc))
zsrc = convertToCell(range(d[1], stop=d[1], length=nsrc))
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtD, t=timeD)
#' # Source judiVector
#' Finally, with the geometry defined, we can create a source wavelet (a simple Ricker wavelet here) a our first `judiVector`
#' In JUDI, a `judiVector` is the core structure that represent a acquisition-geometry based dataset. This structure encapsulate
#' the physical locations (trace coordinates) and corrsponding data trace in a source-based structure. for a given `judiVector` `d` then
#' `d[1]` will be the shot record for the first source, or in the case of the source term, the first source wavelet and its positon.
# setup wavelet
f0 = 0.01f0 # kHz
wavelet = ricker_wavelet(timeD, dtD, f0)
q = judiVector(srcGeometry, wavelet)
#' # Modeling
#' With our survey and subsurface model setup, we can now model and image seismic data. We first define a few options. In this tutorial
#' we will choose to compute gradients/images subsampling the forward wavefield every two time steps `subsampling_factor=2` and we fix the computational
#' time step to be `1ms` wiuth `dt_comp=1.0` know to satisfy the CFL condition for this simple example. In practice, when `dt_comp` isn't provided, JUDI will compute the CFL
#' condition for the propagation.
# Setup options
opt = Options(subsampling_factor=2, space_order=16, free_surface=false)
#' Linear Operators
#' The core idea behind JUDI is to abstract seismic inverse problems in term of linear algebra. In its simplest form, seismic inversion can be formulated as
#' ```math
#' \underset{\mathbf{m}}{\text{argmin}} \ \ \phi(\mathbf{m}) = \frac{1}{2} ||\mathbf{P}_r \mathbf{F}(\mathbf{m}) \mathbf{P}_s^{\top} \mathbf{q} - \mathbf{d} ||_2^2 \\
#' \text{ } \\
#' \nabla_{\mathbf{m}} \phi(\mathbf{m}) = \mathbf{J}(\mathbf{m}, \mathbf{q})^{\top} (\mathbf{P}_r \mathbf{F}(\mathbf{m}) \mathbf{P}_s^{\top} \mathbf{q} - \mathbf{d})
#' ```
#'
#' where $\mathbf{P}_r$ is the receiver projection (measurment operator) and $\mathbf{P}_s^{\top}$ is the source injection operator (adjoint of measurment at the source location).
#' Therefore, we bastracted these operation to be able to define these operators
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model; options=opt)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(srcGeometry)
J = judiJacobian(Pr*F0*adjoint(Ps), q)
#' # Model and image data
#' We first model synthetic data using our defined source and true model
# Nonlinear modeling
dobs = Pr*F*adjoint(Ps)*q
#' Plot the shot record
fig = figure()
plot_sdata(dobs[1]; new_fig=false, name="Synthetic data", cmap=dcmap)
display(fig)
#' Because we have abstracted the linear algebra, we can solve the adjoint wave-equation as well
#' where the data becomes the source. This adjoint solve will be part of the imaging procedure.
# # Adjoint
qad = Ps*adjoint(F)*adjoint(Pr)*dobs
#' We can easily now test the adjointness of our operator with the standard dot test. Because we
#' intend to conserve our linear algebra abstraction, `judiVector` implements all the necessary linear
#' algebra functions such as dot product or norm to be used directly.
# <x, F'y>
dot1 = dot(q, qad)
# <F x, y>
dot2 = dot(dobs, dobs)
# Compare
@show dot1, dot2, (dot2 - dot2)/(dot1 + dot2)
#' # Inversion
#' Our main goal is to provide an inversion framework for seismic inversion. To this end, as shown earlier,
#' users can easily define the Jacobian operator and compute an RTM image (i.e FWI gradient) with a simple matrix-vector product.
#' Once again, we provide both the Jacobian and its adjoint and we can compute Born linearized data.
# Linearized modeling J*dm
dD = J*dm
# Adjoint jacobian, RTM image
rtm = adjoint(J)*dD
#' We show the linearized data.
fig = figure()
plot_sdata(dobs[1]; new_fig=false, name="Linearized data", cmap=dcmap)
display(fig)
#' And the RTM image
fig = figure()
plot_simage(rtm'; new_fig=false, name="RTM image", cmap=imcmap)
display(fig)
#' ## Inversion utility functions
#' We currently introduced the lineaar operators that allow to write seismic modeling and inversion in a high-level, linear algebra way. These linear operators allow the script to closely follow the mathematics and to be readable and understandable.
#'
#' However, these come with overhead. In particular, consider the following compuation on the FWI gradient:
#'
#' ```julia
#' d_syn = F*q
#' r = judiJacobian(F, q)' * (d_syn - d_obs)
#' ```
#'
#' In this two lines, the forward modeling is performed twice: once to compute `d_syn` then once again to compute the Jacobian adjoint. In order to avoid this overhead for practical inversion, we provide utility function that directly comput the gradient and objective function (L2- misfit) of FWI, LSRTM and TWRI with minimum overhead.
#' FWI misfit and gradient
# evaluate FWI objective function
f, g = fwi_objective(model0, q, dobs; options=opt)
#' Plot gradient
fig = figure()
plot_simage(g'; new_fig=false, name="FWI gradient", cmap=imcmap)
display(fig)
#' LSRTM misfit and gradient
# evaluate LSRTM objective function
fj, gj = lsrtm_objective(model0, q, dD, dm; options=opt)
fjn, gjn = lsrtm_objective(model0, q, dobs, dm; nlind=true, options=opt)
#' Plot gradients
fig = figure()
plot_simage(gj'; new_fig=false, name="LSRTM gradient", cmap=imcmap, cbar=true)
display(fig)
fig = figure()
plot_simage(gjn'; new_fig=false, name="LSRTM gradient with background data substracted", cmap=imcmap, cbar=true)
display(fig)
#' By extension, lsrtm_objective is the same as fwi_objecive when `dm` is zero
#' And with computing of the residual. Small noise can be seen in the difference
#' due to floating point roundoff errors with openMP, but running with
#' OMP_NUM_THREADS=1 (no parllelism) produces the exact (difference == 0) same result
#' gjn2 == g
fjn2, gjn2 = lsrtm_objective(model0, q, dobs, 0f0.*dm; nlind=true, options=opt)
#' Plot gradient
fig = figure()
plot_simage(gjn2'; new_fig=false, name="LSRTM gradient with zero perturbation", cmap=imcmap)
display(fig)
#' # TWRI
#' Finally, JUDI implements TWRI, an augmented method to tackle cycle skipping. Once again we provide a computationnally efficient wrapper function that returns the objective value and necessary gradients
f, gm, gy = twri_objective(model0, q, dobs, nothing; options=opt, optionswri=TWRIOptions(params=:all))
# With on-the-fly DFT, experimental
f, gmf = twri_objective(model0, q, dobs, nothing; options=Options(frequencies=[[.009, .011], [.008, .012]]), optionswri=TWRIOptions(params=:m))
#' Plot gradients
fig = figure()
plot_simage(gm'; new_fig=false, name="TWRI gradient w.r.t m", cmap=imcmap)
display(fig)
fig = figure()
plot_sdata(gy[1]; new_fig=false, name="TWRI gradient w.r.t y", cmap=dcmap)
display(fig) | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2354 | # Example for basic 3D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, [email protected]
# Date: January 2017
#
using JUDI
# Set up model structure
n = (120, 100, 90) # (x,y,z) or (x,z)
d = (10., 10., 10.)
o = (0., 0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .* 1.4f0
v0 = ones(Float32,n) .* 1.4f0
v[:, :, Int(round(end/2)):end] .= 4.0f0
rho = ones(Float32, n)
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
dm = vec(m - m0)
# Setup model structure
nsrc = 4
model = Model(n, d, o, m) # to include density call Model(n,d,o,m,rho)
model0 = Model(n, d, o, m0)
# Set up 3D receiver geometry by defining one receiver vector in each x and y direction
nxrec = 120
nyrec = 100
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = range(100f0, stop=900f0, length=nyrec)
zrec = 50f0
# Construct 3D grid from basis vectors
(xrec, yrec, zrec) = setup_3D_grid(xrec, yrec, zrec)
# receiver sampling and recording time
timeR = 100f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)
# Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell([250f0, 500f0, 750f0, 1000f0])
ysrc = convertToCell([200f0, 400f0, 600f0, 800f0])
zsrc = convertToCell([50f0, 60f0, 70f0, 80f0])
# source sampling and number of time steps
timeS = 100f0 # source length in [ms]
dtS = 2f0 # source sampling interval
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
# setup wavelet
f0 = 0.01f0
wavelet = ricker_wavelet(timeS, dtS, f0)
###################################################################################################
# Enable optimal checkpointing
opt = Options(optimal_checkpointing=true)
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model)
Ps = judiProjection(srcGeometry)
q = judiVector(srcGeometry, wavelet)
# Nonlinear modeling
dobs = Pr*F*adjoint(Ps)*q
qad = Ps*F*adjoint(Pr)*dobs
# Linearied modeling
F0 = judiModeling(model0) # modeling operator for background model
J = judiJacobian(Pr*F0*adjoint(Ps), q)
dD = J*dm
rtm = adjoint(J)*dD
# evaluate FWI objective function
f, g = fwi_objective(model0, q, dobs; options=opt)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1711 | # Example for basic 3D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, [email protected]
# Date: January 2017
#
using JUDI
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ .5f0
v[:, Int(round(end/2)):end] .= 4.0f0
rho = ones(Float32, n)
vs = zeros(Float32,n)
vs[:, Int(round(end/2)):end] .= 2f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
# Setup model structure
nsrc = 1
model = Model(n, d, o, m; rho=rho, vs=vs)
# Set up 3D receiver geometry by defining one receiver vector in each x and y direction
nxrec = 120
nyrec = 100
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(10f0, stop=10f0, length=nxrec)
# receiver sampling and recording time
timeR = 1500f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)
# Set up source geometry (cell array with source locations for each shot)
xsrc = 600f0
ysrc = 0f0
zsrc = 10f0
# source sampling and number of time steps
timeS = 1500f0 # source length in [ms]
dtS = 2f0 # source sampling interval
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
# setup wavelet
f0 = 0.01f0
wavelet = ricker_wavelet(timeS, dtS, f0)
###################################################################################################
# Setup operators
F = judiModeling(model, srcGeometry, recGeometry; options=Options(space_order=8, free_surface=true))
q = judiVector(srcGeometry, wavelet)
# Nonlinear modeling
dobs = F*q
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2096 | using JUDI, SegyIO, LinearAlgebra, PyPlot
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v[:,Int(round(end/2)):end] .= 3f0
v0 = ones(Float32,n) .+ 0.4f0
# Slowness squared [s^2/km^2]
m0 = (1f0 ./ v0).^2
m = (1f0 ./ v).^2
dm = vec(m - m0)
# Setup model structure
nsrc = 2 # number of sources
model0 = Model(n, d, o, m0)
model = Model(n, d, o, m)
# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)
# receiver sampling and recording time
time = 1000f0 # receiver recording time [ms]
dt = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)
# Source wavelet
f0 = 0.01f0 # kHz
wavelet = ricker_wavelet(time, dt, f0)
###################################################################################################
# Write shots as segy files to disk
opt = Options(return_array=false, dt_comp=1.0, free_surface=true)
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model; options=opt)
# Extended source weights
weights = Array{Array}(undef, nsrc)
for j=1:nsrc
weights[j] = randn(Float32, model.n)
end
w = judiWeights(weights)
# Create operator for injecting the weights, multiplied by the provided wavelet(s)
Pw = judiLRWF(nsrc, dt, wavelet)
# Model observed data w/ extended source
F = Pr*F*adjoint(Pw)
# Simultaneous observed data
d_sim = F*w
dw = adjoint(F)*d_sim
# Jacobian
J = judiJacobian(F, w)
d_lin = J*dm
g = adjoint(J)*d_lin
# Plot results
figure()
subplot(1,2,1)
imshow(d_sim.data[1], vmin=-5e2, vmax=5e2, cmap="gray"); title("Non-linear shot record")
subplot(1,2,2)
imshow(d_lin.data[1], vmin=-5e3, vmax=5e3, cmap="gray"); title("Linearized shot record")
figure()
subplot(1,2,1)
imshow(adjoint(dw.weights[1]), vmin=-5e6, vmax=5e6, cmap="gray"); title("Weights 1")
subplot(1,2,2)
imshow(adjoint(reshape(g, model0.n)), vmin=-1e8, vmax=1e8, cmap="gray"); title("Gradient w.r.t. m") | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1863 | # Example for basic 2D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, [email protected]
# Date: January 2017
#
using JUDI, SegyIO, LinearAlgebra, PyPlot
# Set up model structure
n = (100, 100, 80) # (x,y,z) or (x,z)
d = (10., 10., 10.)
o = (0., 0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v[:, :, Int(round(end/2)):end] .= 3f0
v0 = ones(Float32,n) .+ 0.4f0
# Slowness squared [s^2/km^2]
m0 = (1f0 ./ v0).^2
m = (1f0 ./ v).^2
dm = vec(m - m0)
# Setup model structure
nsrc = 1 # number of sources
model0 = Model(n, d, o, m0)
model = Model(n, d, o, m)
# Receiver geometry
nxrec = 120
nyrec = 100
xrec = range(50f0, stop=950f0, length=nxrec)
yrec = range(100f0, stop=900f0, length=nyrec)
zrec = 50f0
# Construct 3D grid from basis vectors
(xrec, yrec, zrec) = setup_3D_grid(xrec, yrec, zrec)
# receiver sampling and recording time
time = 60f0 # receiver recording time [ms]
dt = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)
# Source wavelet
f0 = 0.01f0 # kHz
wavelet = ricker_wavelet(time, dt, f0)
###################################################################################################
# Write shots as segy files to disk
opt = Options(return_array=false)
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model; options=opt)
# Random weights (size of the model)
weights = randn(Float32, model.n)
w = judiWeights(weights)
# Create operator for injecting the weights, multiplied by the provided wavelet(s)
Pw = judiLRWF(dt, wavelet)
# Model observed data w/ extended source
F = Pr*F*adjoint(Pw)
# Simultaneous observed data
d_sim = F*w
dw = adjoint(F)*d_sim
# Jacobian
J = judiJacobian(F, w)
d_lin = J*dm
g = adjoint(J)*d_lin
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2040 | using JUDI, SegyIO, LinearAlgebra, PyPlot
# Set up model structure
n = (121, 101) # (x,y,z) or (x,z)
d = (2.5f0, 2.5f0) # in mm
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.5f0
v0 = ones(Float32,n) .+ 0.5f0
v[:,Int(round(end/2)):end] .= 4f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
dm = vec(m - m0)
# Setup model structure
nsrc = 1 # number of sources
model = Model(n, d, o, m)
model0 = Model(n, d, o, m0)
## Set up receiver geometry
nxrec = 120
xrec = range(d[1], stop=d[2]*(n[1]-1), length=nxrec)
yrec = 0f0
zrec = range(d[1], stop=d[1], length=nxrec)
# receiver sampling and recording time
timeR = 250f0 # receiver recording time [ms]
dtR = 0.25f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)
## Set up source geometry (cell array with source locations for each shot)
xsrc = d[1]*61
ysrc = 0f0
zsrc = d[1]
# source sampling and number of time steps
timeS = 250f0 # ms
dtS = 0.25f0 # ms
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
# setup wavelet
f0 = .05 # kHz
wavelet = ricker_wavelet(timeS, dtS, f0)
q = judiVector(srcGeometry, wavelet)
###################################################################################################
opt = Options(isic=true)
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(srcGeometry)
J = judiJacobian(Pr*F0*adjoint(Ps), q)
# Nonlinear modeling
dobs = Pr*F*adjoint(Ps)*q
# With a transducer source pointing down so pi/2 angle and radius 5mm (1cm diameter)
q2 = transducer(q, model.d, 5, pi/2 .* ones(q.nsrc))
Ps2 = judiProjection(q2.geometry)
dobs2 = Pr*F*adjoint(Ps2)*q2
a = 1e-1
figure()
subplot(121)
imshow(dobs.data[1], vmin=-a, vmax=a, cmap="seismic", aspect=.25)
title("Point source")
subplot(122)
imshow(dobs2.data[1], vmin=-a, vmax=a, cmap="seismic", aspect=.25)
title("Transducer source")
dm = J'*dobs2
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2741 | # Example for basic 2D modeling:
# The receiver positions and the source wavelets are the same for each of the four experiments.
# Author: Philipp Witte, [email protected]
# Date: January 2017
#
using LinearAlgebra, Random
using JUDI, SegyIO
# Set up model structure
n = (120, 100) # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v0 = ones(Float32,n) .+ 0.4f0
v[:,Int(round(end/2)):end] .= 3f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
dm = vec(m - m0)
# Setup model structure
nsrc = 2 # number of sources
model = Model(n, d, o, m)
model0 = Model(n, d, o, m0)
# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)
# receiver sampling and recording time
timeR = 1000f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc)
# Set up source geometry (cell array with source locations for each shot)
xsrc = convertToCell([400f0, 800f0])
ysrc = convertToCell([0f0, 0f0])
zsrc = convertToCell([20f0, 20f0])
# source sampling and number of time steps
timeS = 1000f0 # ms
dtS = 4f0 # ms
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
# setup wavelet
f0 = 0.01f0 # kHz
wavelet = ricker_wavelet(timeS, dtS, f0)
q = judiVector(srcGeometry, wavelet)
###################################################################################################
# Write shots as segy files to disk
opt = Options()
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model; options=opt)
F0 = judiModeling(model0; options=opt)
Ps = judiProjection(srcGeometry)
J = judiJacobian(Pr*F0*adjoint(Ps), q)
# Nonlinear modeling
dobs = Pr*F*adjoint(Ps)*q
qad = Ps*adjoint(F)*adjoint(Pr)*dobs
# Return wavefields
u = F*adjoint(Ps)*q
v = adjoint(F)*adjoint(Pr)*dobs
# Modify wavefields
v = abs(v) # take absolute value
u = 2*u # multiple by scalar
# Wavefields as source
dnew = Pr*F*v
qnew = Ps*adjoint(F)*u
# Create custom wavefield as source (needs to be on computational time axis and contain padding)
dtComp = get_dt(model)
ntComp = get_computational_nt(q.geometry, model)
u0 = zeros(Float32, ntComp[1], model.n[1] + 2*model.nb, model.n[2] + 2*model.nb)
wavelet = -ricker_wavelet(timeS, dtComp, f0)
u0[1:length(wavelet), 100, 45] .= wavelet
uf = judiWavefield(dtComp, u0)
dobs2 = Pr*F*uf # same as dobs
# Wavefields as source + return wavefields
u2 = F*u
v2 = F*v
# Supported algebraic operations
u_add = u + u
u_sub = u - v
u_mult = u * 2f0
u_div = u / 2f0
u_norm = norm(u)
u_dot = dot(u, u)
u_abs = abs(u)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3356 | # LS-RTM of the 2D Marmousi model using linearized bregmann
# Author: [email protected]
# Date: April 2022
using Statistics, Random, LinearAlgebra, JOLI
using JUDI, SegyIO, HDF5, PyPlot, SlimOptim
# Load migration velocity model
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_model.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/marmousi_model.h5", "r"), "n", "d", "o", "m0")
# Smaller model for CI
if get(ENV, "NITER", "10") == "2"
fact = 4
m0 = m0[1:fact:end, 1:fact:end]
n = size(m0)
d = d .* fact
else
fact = 1
end
# Set up model structure
model0 = Model(n, d, o, m0)
grad_mem = 40 / (fact^3) # Based on n and CFL condition
# Coarsen for CI
if get(ENV, "CI", nothing) == "true"
model0 = Model(ceil.(Int, n ./ 2), d .* 2, o, m0[1:2:end, 1:2:end])
grad_mem = 5
end
# Load data
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_2D.segy")
end
block = segy_scan(JUDI.JUDI_DATA, "marmousi_2D.segy", ["GroupX","GroupY","RecGroupElevation","SourceSurfaceElevation","dt"])
d_lin = judiVector(block) # linearized observed data
# Set up wavelet
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.03) # 30 Hz wavelet
q = judiVector(src_geometry, wavelet)
###################################################################################################
# Infer subsampling based on free memory
mem = Sys.free_memory()/(1024^3)
t_sub = max(1, ceil(Int, .5*nworkers()*grad_mem/mem))
# Setup operators
opt = Options(subsampling_factor=t_sub, isic=true) # ~40 GB of memory per source without subsampling
M = judiModeling(model0, q.geometry, d_lin.geometry; options=opt)
J = judiJacobian(M, q)
# Right-hand preconditioners (model topmute)
Mr = judiTopmute(model0; taperwidth=10)
# Left-hand Preconditionners (data top mute)
Ml = judiDataMute(q.geometry, d_lin.geometry)
# Sparsity
C = joEye(prod(model0.n); DDT=Float32, RDT=Float32)
# If available use curvelet instead for better result
# Setup linearized bregman
batchsize = 5 * parse(Int, get(ENV, "NITER", "10"))
niter = parse(Int, get(ENV, "NITER", "10"))
g_scale = 0
function obj(x)
flush(stdout)
dm = PhysicalParameter(x, model0.n, model0.d, model0.o)
inds = randperm(q.nsrc)[1:batchsize]
residual = Ml[inds]*J[inds]*Mr*dm - Ml[inds]*d_lin[inds]
# grad
G = reshape(Mr'*J[inds]'*Ml[inds]'*residual, model0.n)
g_scale == 0 && (global g_scale = .05f0/maximum(G))
G .*= g_scale
return .5f0*norm(residual)^2, G[:]
end
# Bregman
bregopt = bregman_options(maxIter=niter, verbose=2, quantile=.9, alpha=.1, antichatter=false, spg=true)
solb = bregman(obj, zeros(Float32, prod(model0.n)), bregopt, C);
# Save final velocity model, function value and history
h5open("lsrtm_marmousi_breg_result.h5", "w") do file
write(file, "x", reshape(solb.x, model0.n), "z", reshape(solb.z, model0.n), "fval", Float32.(solb.ϕ_trace))
end
# Plot final image
figure()
imshow(reshape(solb.x, model0.n)', extent = (0, 7.99, 3.19, 0), cmap = "gray", vmin = -3e-2, vmax = 3e-2)
title("SPLS-RTM with Linearized Bregman")
xlabel("Lateral position [km]")
ylabel("Depth [km]") | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2764 | # FWI on the 2D Overthrust model with L-BFGS from the NLopt library
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, NLopt, HDF5, SegyIO, PyPlot
# Load starting model
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_model_2D.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5", "r"), "n", "d", "o", "m0")
model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)
# Bound constraints
vmin = 1.4f0
vmax = 6.5f0
# Load data and create data vector
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D.segy")
end
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_2D.segy")
d_obs = judiVector(block)
# Set up wavelet and source vector
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry, wavelet)
############################################## FWI #################################################
# optimization parameters
fevals = 10 # allow 10 function evalutations
batchsize = 40
count = 0
fhistory = zeros(Float32, fevals+1)
# NLopt objective function
println("No. ", "fval ", "norm(gradient)")
function f!(x, grad)
# Update model
model0.m .= x
# Select batch and calculate gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, gradient = fwi_objective(model0, q[i], d_obs[i])
# Reset gradient in water column to zero
gradient = reshape(gradient, model0.n); gradient[:, 1:21] .= 0f0
grad[1:end] .= gradient[1:end]
global count; count += 1
println(count, " ", fval, " ", norm(grad))
fhistory[count] = fval
return convert(Float64, fval)
end
# Optimization parameters
opt = Opt(:LD_LBFGS, prod(model0.n))
min_objective!(opt, f!)
mmin = (1f0 ./ vmax)^2 # bound constraints on slowness squared
mmax = (1f0 ./ vmin)^2
lower_bounds!(opt, mmin); upper_bounds!(opt, mmax)
maxeval!(opt, fevals)
(minf, minx, ret) = optimize(opt, copy(model0.m))
# Save results, function values and elapsed time
h5open("result_2D_overthrust_lbfgs.h5", "w") do file
write(file, "x", sqrt.(1f0 ./ reshape(minx, model0.n)), "fhistory", fhistory)
end
# Plot convergence and final result
figure(); plot(fhistory/norm(fhistory, Inf));
xlabel("Iteration no."); ylabel("Normalized residual"); title("Convergence of FWI w/ L-BFGS")
figure(); imshow(sqrt.(1f0 ./ adjoint(model0.m)), extent=(0, 20.0, 5.15, 0)); title("FWI with L-BFGS");
xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3536 | # FWI on the 2D Overthrust model with stochastic gradient descent
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, SlimOptim, HDF5, SegyIO, PyPlot
# Load starting model
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_model_2D.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5", "r"), "n", "d", "o", "m0")
model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ model0.m)
vmin = ones(Float32, model0.n) .* 1.3f0
vmax = ones(Float32, model0.n) .* 6.5f0
vmin[:, 1:21] .= v0[:, 1:21] # keep water column fixed
vmax[:, 1:21] .= v0[:, 1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data and create data vector
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D.segy")
end
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_2D.segy")
d_obs = judiVector(block)
# Set up wavelet and source vector
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry, wavelet)
########################################### FWI ####################################################
# Optimization parameters
maxiter = 20
batchsize = 20
fhistory_SGD = zeros(Float32, maxiter)
fTerm = 1e3
gTerm = 1e1
# Projection operator for bound constraints
proj(x) = reshape(median([vec(mmin) vec(x) vec(mmax)], dims=2), model0.n)
# Define misfit function
function fwi_misfit(model::Model, q::judiVector, d::judiVector; misfit = "L2", compute_gradient = true)
# Set up operators
M = judiModeling(model, q.geometry, d.geometry)
J = judiJacobian(M, q)
# Data residual, function value and gradient
if misfit == "L2"
r = M*q - d
f = .5f0*norm(r)^2
compute_gradient == true && (g = adjoint(J)*r) # gradient not necessary for line search
elseif misifit == "huber"
r = M*q - d
f = eps^2*sqrt(1f0 + dot(r, r)/eps^2) - eps^2
compute_gradient == true && (g = adjoint(J)*r/sqrt(1f0 + dot(r, r)/eps^2))
else
throw("Wrong misfit method specified")
end
if compute_gradient == true
return f, g
else
return f
end
end
# Main loop
for j = 1: maxiter
# select current subset of shots
i = randperm(d_obs.nsrc)[1:batchsize]
f, g = fwi_misfit(model0, q[i], d_obs[i])
println("FWI iteration no: ", j, "; function value: ", f)
fhistory_SGD[j] = f
# linesearch
step = backtracking_linesearch(model0, q[i], d_obs[i], f, g,proj, fwi_misfit; alpha=1f0)
# Update model and bound projection
model0.m = proj(model0.m + reshape(step, model0.n))
if f <= fTerm || norm(g) <= gTerm
break
end
end
# Save results
h5open("result_2D_overthrust_sgd.h5", "w") do file
write(file, "x", sqrt.(1f0 ./ reshape(model0.m, model0.n)), "fhistory", fhistory_SGD)
end
# Plot convergence and final result
figure(); plot(1:maxiter, fhistory_SGD/norm(fhistory_SGD, Inf));
xlabel("Iteration no."); ylabel("Normalized residual"); title("Convergence of FWI w/ SGD")
figure(); imshow(sqrt.(1f0./adjoint(model0.m)), extent=(0, 20.0, 5.15, 0)); title("FWI with SGD");
xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2683 | # FWI on the 2D Overthrust model using spectral projected gradient descent
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, SlimOptim, HDF5, SegyIO, PyPlot
# Load starting model
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_model_2D.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5", "r"), "n", "d", "o", "m0")
model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ model0.m)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:, 1:21] .= v0[:, 1:21] # keep water column fixed
vmax[:, 1:21] .= v0[:, 1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data and create data vector
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_2D.segy")
end
block = segy_read("$(JUDI.JUDI_DATA)/overthrust_2D.segy")
d_obs = judiVector(block)
# Set up wavelet and source vector
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry, wavelet)
########################################### FWI ####################################################
# Optimization parameters
fevals = 20
batchsize = 20
fvals = []
# Objective function for library
function objective_function(x)
model0.m .= x;
# select batch "elapsed_time", elapsed_time
idx = randperm(d_obs.nsrc)[1:batchsize]
f, g = fwi_objective(model0, q[idx], d_obs[idx])
global fvals; fvals = [fvals; f]
return f, vec(g.data/norm(g, Inf)) # normalize gradient for line search
end
# Bound projection
ProjBound(x) = median([mmin x mmax], dims=2)[1:end]
# FWI with SPG
options = spg_options(verbose = 3, maxIter = fevals, memory = 3, iniStep = 1f0)
x, fsave, funEvals = spg(objective_function, vec(m0), ProjBound, options)
# Save results
h5open("result_2D_overthrust_spg.h5", "w") do file
write(file, "x", sqrt.(1f0 ./ reshape(x, model0.n)), "fsave", fsave, "fhistory", convert(Array{Float32, 1}, fvals))
end
# Plot convergence and final result
figure(); plot(fvals/norm(fvals, Inf));
xlabel("Iteration no."); ylabel("Normalized residual"); title("Convergence of FWI w/ SPG")
figure(); imshow(sqrt.(1f0 ./ adjoint(reshape(x, model0.n))), extent=(0, 20.0, 5.15, 0)); title("FWI with SPG");
xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2385 | # 2D FWI on a small version of the Overthrust model with L-BFGS from the NLopt library
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, HDF5, NLopt, SegyIO, PyPlot
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/small_overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ model0.m)
vmin = ones(Float32, model0.n) .* 1.3f0
vmax = ones(Float32, model0.n) .* 6.5f0
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/small_overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry, wavelet)
############################### FWI ###########################################
# optimization parameters
fevals = 10
batchsize = 16
count = 0
fhistory = zeros(Float32, fevals+1)
# NLopt objective function
println("No. ", "fval ", "norm(gradient)")
function f!(x,grad)
# Update model
model0.m .= x
# Seclect batch and calculate gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, gradient = fwi_objective(model0, q[i], d_obs[i])
# Reset gradient in water column to zero
gradient[:, 1:21] .= 0f0
grad[1:end] .= gradient[1:end]
global count; count += 1
println(count, " ", fval, " ", norm(grad))
fhistory[count] = fval
return convert(Float64, fval)
end
# Optimization parameters
opt = Opt(:LD_LBFGS, prod(model0.n))
lower_bounds!(opt, mmin); upper_bounds!(opt, mmax)
min_objective!(opt, f!)
maxeval!(opt, fevals)
(minf, minx, ret) = optimize(opt, copy(model0.m))
# Save results, function values and elapsed time
h5open("result_2D_small_overthrust_lbfgs.h5", "w") do file
write(file, "x", sqrt.(1f0 ./ reshape(minx, model0.n)), "fhistory", fhistory)
end
# Plot convergence and final result
figure(); plot(fhistory/norm(fhistory, Inf));
xlabel("Iteration no."); ylabel("Normalized residual"); title("Convergence of FWI w/ L-BFGS")
figure(); imshow(sqrt.(1f0./adjoint(model0.m)), extent=(0, 20.0, 5.15, 0)); title("FWI with L-BFGS");
xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3143 | # 2D FWI on a small version of the Overthrust model using stochastic gradient descent
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, SlimOptim, HDF5, SegyIO, PyPlot
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/small_overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ model0.m)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/small_overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
############################### FWI ###########################################
# Optimization parameters
maxiter = 10
batchsize = 8
fhistory_SGD = zeros(Float32, maxiter)
fTerm = 1e3
gTerm = 1e1
# Projection operator for bound constraints
proj(x) = reshape(median([vec(mmin) vec(x) vec(mmax)], dims=2), model0.n)
# Define misfit function
function fwi_misfit(model::Model, q::judiVector, d::judiVector; misfit = "L2", compute_gradient = true)
# Set up operators
M = judiModeling(model, q.geometry, d.geometry)
J = judiJacobian(M, q)
# Data residual, function value and gradient
if misfit == "L2"
r = M*q - d
f = .5f0*norm(r)^2
compute_gradient == true && (g = adjoint(J)*r) # gradient not necessary for line search
elseif misifit == "huber"
r = M*q - d
f = eps^2*sqrt(1f0 + dot(r, r)/eps^2) - eps^2
compute_gradient == true && (g = adjoint(J)*r/sqrt(1f0 + dot(r, r)/eps^2))
else
throw("Wrong misfit method specified")
end
if compute_gradient == true
return f, g
else
return f
end
end
# Main loop
for j = 1: maxiter
# select current subset of shots
i = randperm(d_obs.nsrc)[1:batchsize]
f, g = fwi_misfit(model0, q[i], d_obs[i])
println("FWI iteration no: ", j, "; function value: ", f)
fhistory_SGD[j] = f
# linesearch
step = backtracking_linesearch(model0, q[i], d_obs[i], f, g,proj, fwi_misfit; alpha=1f0)
# Update model and bound projection
model0.m = proj(model0.m + reshape(step, model0.n))
if f <= fTerm || norm(g) <= gTerm
break
end
end
# Save results
h5open("result_2D_small_overthrust_sgd.h5", "w") do file
write(file, "x", sqrt.(1f0 ./ reshape(model0.m, model0.n)), "fhistory", fhistory_SGD)
end
# Plot convergence and final result
figure(); plot(1:maxiter, fhistory_SGD/norm(fhistory_SGD, Inf));
xlabel("Iteration no."); ylabel("Normalized residual"); title("Convergence of FWI w/ SGD")
figure(); imshow(sqrt.(1f0 ./ adjoint(model0.m)), extent=(0, 20.0, 5.15, 0)); title("FWI with SGD");
xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2267 | # 2D FWI on a small version of the Overthrust model with SPG from the minConf library
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, SlimOptim, HDF5, SegyIO, PyPlot
# Load starting model
n,d,o,m0 = read(h5open("$(JUDI.JUDI_DATA)/small_overthrust_model.h5","r"), "n", "d", "o", "m0")
model0 = Model((n[1],n[2]), (d[1],d[2]), (o[1],o[2]), m0)
# Bound constraints
v0 = sqrt.(1f0 ./ model0.m)
vmin = ones(Float32,model0.n) .* 1.3f0
vmax = ones(Float32,model0.n) .* 6.5f0
vmin[:,1:21] .= v0[:,1:21] # keep water column fixed
vmax[:,1:21] .= v0[:,1:21]
# Slowness squared [s^2/km^2]
mmin = vec((1f0 ./ vmax).^2)
mmax = vec((1f0 ./ vmin).^2)
# Load data
block = segy_read("$(JUDI.JUDI_DATA)/small_overthrust_shot_records.segy")
d_obs = judiVector(block)
# Set up wavelet
src_geometry = Geometry(block; key="source")
wavelet = ricker_wavelet(src_geometry.t[1],src_geometry.dt[1],0.008f0) # 8 Hz wavelet
q = judiVector(src_geometry,wavelet)
############################### FWI ###########################################
# Optimization parameters
fevals = 10
batchsize = 8
fvals = []
# Objective function for minConf library
function objective_function(x)
model0.m .= x
# fwi function value and gradient
i = randperm(d_obs.nsrc)[1:batchsize]
fval, grad = fwi_objective(model0, q[i], d_obs[i])
grad = .125f0*grad/norm(grad, Inf) # scale for line search
global fvals; fvals = [fvals; fval]
return fval, vec(grad.data)
end
# Bound projection
ProjBound(x) = median([mmin x mmax]; dims=2)[1:end]
# FWI with SPG
options = spg_options(verbose=3, maxIter=fevals, memory=3)
x, fsave, funEvals= spg(objective_function, vec(m0), ProjBound, options)
# Save results
h5open("result_2D_small_overthrust_spg.h5", "w") do file
write(file, "x", sqrt.(1f0 ./ reshape(x, model0.n)), "fsave", fsave, "fhistory", convert(Array{Float32, 1}, fvals))
end
# Plot convergence and final result
figure(); plot(fvals/norm(fvals, Inf));
xlabel("Iteration no."); ylabel("Normalized residual"); title("Convergence of FWI w/ SPG")
figure(); imshow(sqrt.(1f0 ./ adjoint(reshape(x, model0.n))), extent=(0, 20.0, 5.15, 0)); title("FWI with SPG");
xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2754 | # FWI on the 3D Overthrust model using spectral projected gradient descent
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, SlimOptim, HDF5, SegyIO
# Load overthrust model
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_3D_initial_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/3DFWI/overthrust_3D_initial_model.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/overthrust_3D_initial_model.h5", "r"), "n", "d", "o", "m0")
# Set up model structure
model0 = Model((n[1], n[2], n[3]), (d[1], d[2], d[3]), (o[1], o[2], o[3]), m0)
# Bound constraints
vmin = ones(Float32, model0.n) .+ 0.4f0
vmax = ones(Float32, model0.n) .+ 5.5f0
mmin = vec((1f0 ./ vmax).^2); vmax = []
mmax = vec((1f0 ./ vmin).^2); vmin = []
# Scan directory for segy files and create out-of-core data container
container = segy_scan("/path/to/shot/records/", "overthrust_3D_shot",
["GroupX", "GroupY", "RecGroupElevation", "SourceSurfaceElevation", "dt"])
d_obs = judiVector(container)
# Set up source
src_geometry = Geometry(container; key = "source")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.008) # 8 Hz peak frequency
q = judiVector(src_geometry, wavelet)
########################################### FWI ####################################################
# Optimization parameters
fevals = 15
batchsize = 1080
count = 0
fvals = []
opt = Options(limit_m = true, # model in only in area with receivers
buffer_size = 500f0, # w/ 500 m buffer zone
optimal_checkpointing = true
)
# Objective function for minConf library
function objective_function(x)
# update model and save snapshot
model0.m = reshape(x, model0.n);
write(h5open(join(["snapshot_3D_FWI_iteration_", string(count),".h5"]), "w"), "v", sqrt.(1f0 ./ model0.m))
# select batch
idx = randperm(d_obs.nsrc)[1:batchsize]
# fwi function value and gradient
f, g = fwi_objective(model0, q[idx], d_obs[idx]; options = opt)
g = reshape(g, model0.n); g[:, :, 1:21] .= 0f0 # reset gradient in water column to 0.
g = .125f0*g/maximum(abs.(g)) # scale gradient to help line search
global count; count += 1;
global fvals; fvals = [fvals; f]
return f, vec(g)
end
# Bound projection
ProjBound(x) = median([mmin x mmax], dims=2)
# FWI with SPG
spg_opt = spg_options(verbose = 3, maxIter = fevals, memory = 1)
x, fsave, funEvals = minConf_SPG(objective_function, vec(model0.m), ProjBound, spg_opt)
# Save results
h5open("result_3D_overthrust_spg.h5", "w") do file
write(file, "x", sqrt.(1 ./reshape(x, model0.n)), "fsave", fsave, "fhistory", convert(Array{Float32, 1}, fvals))
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2164 | # Generate observed Born data for Marmousi examples
# Author: [email protected]
# Date: December 2018
#
using JUDI, SegyIO, HDF5, LinearAlgebra
# Load migration velocity model
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_model.h5")
end
n, d, o, m0, "dm" = read(h5open("$(JUDI.JUDI_DATA)/marmousi_model.h5", "r"), "n", "d", "o", "m0", "dm")
# Set up model structure
model = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)
dm = vec(dm)
# Set up source geometry (cell array with source locations for each shot)
nsrc = 320
xsrc = convertToCell(range(25f0, stop=7965f0, length=nsrc))
ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc))
zsrc = convertToCell(range(10f0, stop=10f0, length=nsrc))
# source sampling and number of time steps
timeS = 4000f0 # ms
dtS = 4f0 # ms
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
## Set up receiver geometry
nxrec = 800
max_offset = 3990
nsrc_half = Int(round(nsrc/2))
xrec = Array{Any}(undef, nsrc)
yrec = Array{Any}(undef, nsrc)
zrec = Array{Any}(undef, nsrc)
for j=1:nsrc_half
xrec[j] = range(xsrc[j], stop=xsrc[j] + max_offset, length=nxrec)
yrec[j] = range(0f0, stop=0f0, length=nxrec)
zrec[j] = range(210f0, 210f0, length=nxrec)
end
for j=nsrc_half+1:nsrc
xrec[j] = range(xsrc[j], stop=xsrc[j] - max_offset, length=nxrec)
yrec[j] = range(0f0, stop=0f0, length=nxrec)
zrec[j] = range(210f0, 210f0, length=nxrec)
end
# receiver sampling and recording time
timeR = 4000f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval [ms]
# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR)
# setup wavelet
f0 = 0.03f0 # kHz
wavelet = ricker_wavelet(timeS, dtS, f0)
q = judiVector(srcGeometry, wavelet)
# Setup operators
Pr = judiProjection(recGeometry)
F = judiModeling(model)
Ps = judiProjection(srcGeometry)
J = judiJacobian(Pr*F*adjoint(Ps), q)
# Born modeling
dobs = J*dm
block_out = judiVector_to_SeisBlock(dobs, q; source_depth_key="SourceDepth")
segy_write("marmousi_2D.segy", block_out)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2078 | # Generate 2D data for the overthrust model
# Author: [email protected]
# Date: December 2018
#
using JUDI, HDF5, SegyIO
# Load overthrust model
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/2DFWI/overthrust_model_2D.h5")
end
n, d, o, m = read(h5open("$(JUDI.JUDI_DATA)/overthrust_model_2D.h5","r"), "n", "d", "o", "m")
# Set up model structure
model = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m)
# Set up source geometry (cell array with source locations for each shot)
nsrc = 97
xsrc = convertToCell(range(400f0, stop=19600f0, length=nsrc))
ysrc = convertToCell(range(0f0, stop=0f0, length=nsrc))
zsrc = convertToCell(range(50f0, stop=50f0, length=nsrc))
# source sampling and number of time steps
timeS = 3000f0 # ms
dtS = 4f0 # ms
# Set up source structure
src_geometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS)
## Set up receivers
xmin = 100f0; xmax = 19900f0
offset = 6000f0
nxrec = 240
xrec = Array{Any}(undef, nsrc)
yrec = Array{Any}(undef, nsrc)
zrec = Array{Any}(undef, nsrc)
for j = 1: nsrc
# 6 km max. offset around current source
xsrc[j] - offset < xmin ? xlocal1 = xmin : xlocal1 = xsrc[j] - offset
xsrc[j] + offset > xmax ? xlocal2 = xmax : xlocal2 = xsrc[j] + offset
xrec[j] = xlocal1: 50f0: xlocal2
yrec[j] = range(0f0, stop=0f0, length=length(xrec[j]))
zrec[j] = range(500f0, stop=500f0, length=length(xrec[j]))
end
timeR = 3000f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval
rec_geometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR)
# Set up source
f0 = 0.008
wavelet = ricker_wavelet(timeS, dtS, f0)
#######################################################################
# Set up operators
Pr = judiProjection(rec_geometry)
Ps = judiProjection(src_geometry)
A_inv = judiModeling(model)
q = judiVector(src_geometry, wavelet)
# Generate data
d_obs = Pr*A_inv*adjoint(Ps)*q
block_out = judiVector_to_SeisBlock(d_obs, q; source_depth_key="SourceDepth")
segy_write("overthrust_2D.segy", block_out)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2491 | # Generate 3D data for the overthrust model
# Author: [email protected]
# Date: January 2017
#
using JUDI, HDF5
# Load overthrust model
if ~isfile("$(JUDI.JUDI_DATA)/overthrust_3D_true_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/WaveformInversion.jl/3DFWI/overthrust_3D_true_model.h5")
end
n, d, o, m = read(h5open("$(JUDI.JUDI_DATA)/overthrust_3D_true_model.h5","r"), "n", "d", "o", "m")
# Set up model structure
model = Model((n[1], n[2], n[3]), (d[1], d[2], d[3]), (o[1], o[2], o[3]), m)
# Set up source grid
nsrc = 97^2
xsrc = 400f0: 200f0: 19600f0 # 400 m space from boundary
ysrc = 400f0: 200f0: 19600f0
zsrc = 50f0
(xsrc, ysrc, zsrc) = setup_3D_grid(xsrc, ysrc, zsrc)
xsrc = convertToCell(xsrc)
ysrc = convertToCell(ysrc)
zsrc = convertToCell(zsrc)
timeS = 3000f0
dtS = 4f0
src_geometry = Geometry(xsrc, ysrc, zsrc; dt = dtS, t = timeS)
## Set up receivers
xmin = 100f0; xmax = 19900f0
ymin = 100f0; ymax = 19900f0
offset = 6000f0
nxrec = 240
nyrec = 240
xrec = Array{Any,1}(undef, nsrc)
yrec = Array{Any,1}(undef, nsrc)
zrec = Array{Any}(undef, nsrc)
for j = 1: nsrc
# 6 km max. offset around current source
xsrc[j] - offset < xmin ? xlocal1 = xmin : xlocal1 = xsrc[j] - offset
xsrc[j] + offset > xmax ? xlocal2 = xmax : xlocal2 = xsrc[j] + offset
ysrc[j] - offset < ymin ? ylocal1 = ymin : ylocal1 = ysrc[j] - offset
ysrc[j] + offset > ymax ? ylocal2 = ymax : ylocal2 = ysrc[j] + offset
xlocal = xlocal1: 50f0: xlocal2
ylocal = ylocal1: 50f0: ylocal2
zlocal = 500f0
(xlocal,ylocal,zlocal) = setup_3D_grid(xlocal, ylocal, zlocal)
xrec[j] = xlocal
yrec[j] = ylocal
zrec[j] = zlocal
end
timeR = 3000f0 # receiver recording time [ms]
dtR = 4f0 # receiver sampling interval
rec_geometry = Geometry(xrec, yrec, zrec; dt = dtR, t = timeR)
# Set up source
f0 = 0.008
wavelet = ricker_wavelet(timeS, dtS, f0)
#######################################################################
# Set up modeling options
opt = Options(limit_m = true,
save_data_to_disk = true,
file_path = "path/to/shot/records", # replace w/ path to directory in which data will be stored (~total of 1.7 TB)
file_name = "overthrust_3D_shot_" # adds x-y coordinates to name
)
# Set up operators
Pr = judiProjection(rec_geometry)
Ps = judiProjection(src_geometry)
A_inv = judiModeling(model; options=opt)
q = judiVector(src_geometry, wavelet)
# Generate data and save as individual SEG-Y files to disk
d_obs = Pr*A_inv*adjoint(Ps)*q
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3082 | # LS-RTM of the 2D Marmousi model using elastic average stochastic gradient descent
# Author: [email protected]
# Date: December 2018
#
# Warning: The examples requires ~40 GB of memory per shot if used without optimal checkpointing.
#
using Statistics, Random, LinearAlgebra, Distributed
using JUDI, SegyIO, HDF5, PyPlot
# Load migration velocity model
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_model.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/marmousi_model.h5", "r"), "n", "d", "o", "m0")
# Set up model structure
model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)
# Load data
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_2D.segy")
end
block = segy_read("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
d_lin = judiVector(block) # linearized observed data
# Set up wavelet
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.03) # 30 Hz wavelet
q = judiVector(src_geometry, wavelet)
###################################################################################################
# Setup operators
opt = Options(optimal_checkpointing=true) # ~40 GB of memory per source w/o checkpointing
M = judiModeling(model0, q.geometry, d_lin.geometry;options=opt)
J = judiJacobian(M, q)
# Right-hand preconditioners (model topmute)
Mr = judiTopmute(model0; taperwidth=10)
# Left preconditioner
Ml = judiDataMute(q.geometry, d_lin.geometry) # data topmute
# Elastic average stochastic gradient descent
niter = 20
p = 10
batchsize = 1
eta = 0.03f0
rho = 1f0
alpha = eta*rho
beta = p*alpha
x = zeros(Float32, prod(model0.n), p)
xnew = zeros(Float32, prod(model0.n), p)
xav = zeros(Float32, prod(model0.n))
# Parallel gradient function
@everywhere function update_x(Ml, J, Mr, x, d, eta, alpha, xav)
# gradient
r = Ml*J*Mr*x - Ml*d
g = adjoint(Mr)*adjoint(J)*adjoint(Ml)*r
# Update variable
return x - eta*g - alpha*(x - xav)
end
update_x_par = remote(update_x) # parallel function instance
# Main loop
for j = 1: niter
println("Iteration: ", j)
@sync begin
for k = 1: p
# Select batch
batchsize == 1 ? i = randperm(d_lin.nsrc)[1] : i = randperm(d_lin.nsrc)[1:batchsize]
# Calculate x update
@async xnew[:, k] = update_x_par(Ml[i], J[i], Mr, x[:,k], d_lin[i], eta, alpha, xav)
end
end
global xav = (1-beta)*xav + beta*(1/p *sum(x, dims=2))
global x = copy(xnew)
end
# Save final velocity model, function value and history
h5open("lsrtm_marmousi_easgd_result.h5", "w") do file
write(file, "x", reshape(xav, model0.n))
end
# Plot final image
figure(); imshow(copy(adjoint(reshape(xav, model0.n))), extent = (0, 7.99, 3.19, 0), cmap = "gray", vmin = -3e-2, vmax = 3e-2)
title("LS-RTM with elastic average SGD"); xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3393 | # Sparisty-promoting LS-RTM of the 2D Marmousi model with on-the-fly Fourier transforms
# Author: [email protected]
# Date: December 2018
#
using Statistics, Random, LinearAlgebra
using JUDI, SegyIO, HDF5, JOLI, PyPlot
# Load migration velocity model
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_model.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/marmousi_model.h5", "r"), "n", "d", "o", "m0")
# Set up model structure
model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)
# Load data
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_2D.segy")
end
block = segy_read("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
d_lin = judiVector(block) # linearized observed data
# Set up wavelet
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.03) # 30 Hz wavelet
q = judiVector(src_geometry, wavelet)
###################################################################################################
# Setup operators
opt = Options(optimal_checkpointing=false)
M = judiModeling(model0, q.geometry, d_lin.geometry; options=opt)
J = judiJacobian(M, q)
# Right-hand preconditioners (model topmute)
Mr = judiTopmute(model0; taperwidth=10)
# Left preconditioner
Ml = judiDataMute(q.geometry, d_lin.geometry) # data topmute
# Generate distribution of frequecies from source wavelet
q_dist = generate_distribution(q)
# Linearized Bregman parameters
x = zeros(Float32, prod(model0.n))
z = zeros(Float32, prod(model0.n))
batchsize = 10
niter = 20
fval = zeros(Float32, niter)
J.options.frequencies = Array{Any}(undef, d_lin.nsrc)
# Soft thresholding functions and Curvelet transform
soft_thresholding(x::Array{Float64}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float64, lambda), 0.0)
soft_thresholding(x::Array{Float32}, lambda) = sign.(x) .* max.(abs.(x) .- convert(Float32, lambda), 0f0)
C = joCurvelet2D(model0.n[1], model0.n[2]; zero_finest = true, DDT = Float32, RDT = Float64)
lambda = []
t = 1f-4
# Main loop
for j = 1: niter
println("Iteration: ", j)
# Select batch and set up left-hand preconditioner
i = randperm(d_lin.nsrc)[1:batchsize]
# Select randomly selected batch of frequencies for each shot
for k = 1: d_lin.nsrc
J.options.frequencies[k] = select_frequencies(q_dist; fmin = 0.004f0, fmax = 0.05f0, nf=10)
end
# Compute residual and gradient
r = Ml[i]*J[i]*Mr*x - Ml[i]*d_lin[i]
g = adjoint(Mr)*adjoint(J[i])*adjoint(Ml[i])*r
# Step size and update variable
fval[j] = .5f0*norm(r)^2
j == 1 && (global lambda = 0.5*norm(C*t*g, Inf)) # estimate thresholding parameter in 1st iteration
# Update variables and save snapshot
global z -= t*g
global x = adjoint(C)*soft_thresholding(C*z, lambda)
end
# Save final velocity model, function value and history
h5open("lsrtm_marmousi_frequency_result.h5", "w") do file
write(file, "x", reshape(x, model0.n), "fval", fval)
end
# Plot final image
figure(); imshow(copy(adjoint(reshape(x, model0.n))), extent = (0, 7.99, 3.19, 0), cmap = "gray", vmin = -3e-2, vmax = 3e-2)
title("SPLS-RTM with on on-the-fly DFTs"); xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2542 | # LS-RTM of the 2D Marmousi model using stochastic gradient descent
# Author: [email protected]
# Date: December 2018
#
# Warning: The examples requires ~40 GB of memory per shot if used without optimal checkpointing.
#
using Statistics, Random, LinearAlgebra
using JUDI, SegyIO, HDF5, PyPlot
# Load migration velocity model
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_model.h5")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_model.h5")
end
n, d, o, m0 = read(h5open("$(JUDI.JUDI_DATA)/marmousi_model.h5", "r"), "n", "d", "o", "m0")
# Set up model structure
model0 = Model((n[1], n[2]), (d[1], d[2]), (o[1], o[2]), m0)
# Load data
if ~isfile("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
ftp_data("ftp://slim.gatech.edu/data/SoftwareRelease/Imaging.jl/2DLSRTM/marmousi_2D.segy")
end
block = segy_read("$(JUDI.JUDI_DATA)/marmousi_2D.segy")
d_lin = judiVector(block) # linearized observed data
# Set up wavelet
src_geometry = Geometry(block; key = "source", segy_depth_key = "SourceDepth")
wavelet = ricker_wavelet(src_geometry.t[1], src_geometry.dt[1], 0.03) # 30 Hz wavelet
q = judiVector(src_geometry, wavelet)
###################################################################################################
# Setup operators
opt = Options(optimal_checkpointing=true) # ~40 GB of memory per source w/o checkpointing
M = judiModeling(model0, q.geometry, d_lin.geometry; options=opt)
J = judiJacobian(M, q)
# Right-hand preconditioners (model topmute)
Mr = judiTopmute(model0; taperwidth=10)
# Left preconditioner
Ml = judiDataMute(q.geometry, d_lin.geometry) # data topmute
# Stochastic gradient
x = zeros(Float32, prod(model.n))
batchsize = 10
niter = 20
fval = zeros(Float32, niter)
# Main loop
for j = 1: niter
println("Iteration: ", j)
# Select batch and set up left-hand preconditioner
i = randperm(d_lin.nsrc)[1: batchsize]
# Compute residual and gradient
r = Ml[i]*J[i]*Mr*x - Ml[i]*d_lin[i]
g = adjoint(Mr)*adjoint(J[i])*adjoint(Ml[i])*r
# Step size and update variable
fval[j] = .5f0*norm(r)^2
t = norm(r)^2/norm(g)^2
global x -= t*g
end
# Save final velocity model, function value and history
h5open("lsrtm_marmousi_sgd_result.h5", "w") do file
write(file, "x", reshape(x, model0.n), "fval", fval)
end
# Plot final image
figure(); imshow(copy(adjoint(reshape(x, model0.n))), extent = (0, 7.99, 3.19, 0), cmap = "gray", vmin = -3e-2, vmax = 3e-2)
title("LS-RTM with SGD"); xlabel("Lateral position [km]"); ylabel("Depth [km]")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2341 | # Example for modeling simultaneous sources and reverse-time migration
# Author: [email protected]
# Date: December 2018
#
using JUDI, PyPlot
## Set up model structure
n = (120, 100) # (x, y, z) or (x, z)
d = (10., 10.)
o = (0., 0.)
# Velocity [km/s]
v = ones(Float32, n) .+ 0.4f0
v0 = ones(Float32, n) .+ 0.4f0
v[:, Int(round(end/2)):end] .= 4.0f0
# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2
m0 = (1f0 ./ v0).^2
dm = vec(m - m0)
# Setup model structure
nsrc = 1 # one simultaneous source experiment
model = Model(n, d, o, m)
model0 = Model(n, d, o, m0)
## Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(100f0, stop=100f0, length=nxrec)
timeR = 2000f0
dtR = 4f0
# Setup receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt = dtR, t = timeR)
## Set up source geometry
xsrc = [250f0, 500f0, 750f0, 1000f0] # four simultaneous sources
ysrc = 0f0
zsrc = [50f0, 50f0, 50f0, 50f0]
# Source sampling and number of time steps
timeS = 2000f0
dtS = 4f0
# Set up source structure
srcGeometry = Geometry(xsrc, ysrc, zsrc; dt = dtS, t = timeS)
# setup wavelets
f0 = 0.01 # source peak frequencies
q = ricker_wavelet(500f0, dtS, f0) # 500 ms wavelet
# Create four source functions with different time shifts of q
wavelet1 = zeros(srcGeometry.nt[1])
wavelet1[1:1+length(q)-1] = q
wavelet2 = zeros(srcGeometry.nt[1])
wavelet2[41:41+length(q)-1] = q
wavelet3 = zeros(srcGeometry.nt[1])
wavelet3[121:121+length(q)-1] = q
wavelet4 = zeros(srcGeometry.nt[1])
wavelet4[201:201+length(q)-1] = q
wavelet = [wavelet1 wavelet2 wavelet3 wavelet4] # Collect all wavelets
###################################################################################################
# Setup operators
Pr = judiProjection(recGeometry)
A_inv = judiModeling(model)
A0_inv = judiModeling(model0)
Ps = judiProjection(srcGeometry)
q = judiVector(srcGeometry, wavelet)
# Linearized modeling
d = Pr*A_inv*adjoint(Ps)*q # simultaneous shot
J = judiJacobian(Pr*A0_inv*adjoint(Ps), q)
dD = J*dm # simultaneous reflection data
rtm = adjoint(J)*dD # RTM
# Plot results
figure(); imshow(d.data[1], vmin = -1e1, vmax = 1e1, cmap = "seismic"); title("Simultaneous shot w/ four sources")
figure(); imshow(copy(adjoint(reshape(rtm,model.n))), ColorMap("gray")); title("Migrated simultaneous shot")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1452 | ################################################################################
#
# Generate synthetic data for the BG Compass model
#
# Author: Mathias Loubout and Gabbrio Rizzuti
# Date: September 2020
################################################################################
### Module loading
using JUDI, JLD2
### Load true model
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
@load string(base_path*"data//BGCompass_tti.jld") n d o m
# Model
model_true = Model(n, d, o, m; nb=80)
### Acquisition geometrye
dt = 4f0
T = 2500f0 # total recording time [ms]
# Source wavelet
freq_peak = 0.01f0
wavelet = ricker_wavelet(T, dt, freq_peak)
# Sources
nsrc = 51
x_src = convertToCell(range(0f0, stop = (n[1]-1)*d[1], length = nsrc))
y_src = convertToCell(range(0f0, stop = 0f0, length = nsrc))
z_src = convertToCell(range(0f0, stop = 0f0, length = nsrc))
# Receivers
nrcv = n[1]
x_rcv = range(0f0, stop = (n[1]-1)*d[1], length = nrcv)
y_rcv = 0f0
z_rcv = range(12.5f0, stop = 12.5f0, length = nrcv)
# Geometry structures
src_geom = Geometry(x_src, y_src, z_src; dt = dt, t = T)
rcv_geom = Geometry(x_rcv, y_rcv, z_rcv; dt = dt, t = T, nsrc = nsrc)
# Source function
fsrc = judiVector(src_geom, wavelet)
# Setup operators
F = judiModeling(model_true, src_geom,rcv_geom)
dat = F*fsrc
### Saving data
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
@save string(base_path*"data/BGCompass_data_acou.jld") model_true fsrc dat
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1513 | ################################################################################
#
# Generate synthetic data for the BG Compass model
#
# Author: Mathias Loubout and Gabbrio Rizzuti
# Date: September 2020
################################################################################
### Module loading
using JUDI, JLD2
### Load true model
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
@load string(base_path*"data/BGCompass_tti.jld") n d o m epsilon delta theta
# Model
model_true = Model(n, d, o, m; nb=80, epsilon=epsilon, delta=delta, theta=theta)
### Acquisition geometrye
dt = 4f0
T = 2500f0 # total recording time [ms]
# Source wavelet
freq_peak = 0.01f0
wavelet = ricker_wavelet(T, dt, freq_peak)
# Sources
nsrc = 51
x_src = convertToCell(range(0f0, stop = (n[1]-1)*d[1], length = nsrc))
y_src = convertToCell(range(0f0, stop = 0f0, length = nsrc))
z_src = convertToCell(range(0f0, stop = 0f0, length = nsrc))
# Receivers
nrcv = n[1]
x_rcv = range(0f0, stop = (n[1]-1)*d[1], length = nrcv)
y_rcv = 0f0
z_rcv = range(12.5f0, stop = 12.5f0, length = nrcv)
# Geometry structures
src_geom = Geometry(x_src, y_src, z_src; dt = dt, t = T)
rcv_geom = Geometry(x_rcv, y_rcv, z_rcv; dt = dt, t = T, nsrc = nsrc)
# Source function
fsrc = judiVector(src_geom, wavelet)
# Setup operators
F = judiModeling(model_true, src_geom,rcv_geom)
dat = F*fsrc
### Saving data
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
@save string(base_path*"data/BGCompass_data_tti.jld") model_true fsrc dat
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1508 | ################################################################################
#
# Generate synthetic data for the BG Compass model
#
# Author: Mathias Loubout and Gabbrio Rizzuti
# Date: September 2020
################################################################################
### Module loading
using JUDI, JLD2
### Load true model
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
@load string(base_path*"data/GaussLens.jld") n d o m
# Model
model_true = Model(n, d, o, m; nb=80)
### Acquisition geometrye
dt = 1f0
T = 2000f0 # total recording time [ms]
# Source wavelet
freq_peak = 0.006f0
wavelet = ricker_wavelet(T, dt, freq_peak)
# Sources
ix_src = 3:14:199
nsrc = length(ix_src)
iz_src = 3
x_src = convertToCell((ix_src.-1)*d[1])
y_src = convertToCell(range(0f0, stop = 0f0, length = nsrc))
z_src = convertToCell(range((iz_src-1)*d[2], stop = (iz_src-1)*d[2], length = nsrc))
# Receivers
ix_rcv = 3:199
iz_rcv = 199
nrcv = length(ix_rcv)
x_rcv = (ix_rcv.-1)*d[1]
y_rcv = 0f0
z_rcv = range((iz_rcv-1)*d[2], stop = (iz_rcv-1)*d[2], length = nrcv)
# Geometry structures
src_geom = Geometry(x_src, y_src, z_src; dt = dt, t = T)
rcv_geom = Geometry(x_rcv, y_rcv, z_rcv; dt = dt, t = T, nsrc = nsrc)
# Source function
fsrc = judiVector(src_geom, wavelet)
# Setup operators
F = judiModeling(model_true, src_geom,rcv_geom)
dat = F*fsrc
### Saving data
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
@save string(base_path*"data/GaussLens_data_acou.jld") model_true fsrc dat
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3103 | ################################################################################
#
# Run inversion for the BG Compass model
#
################################################################################
### Module loading
using LinearAlgebra, JLD2, PyPlot, Dates, Distributed, Images
using Optim, LineSearches
using JUDI, SlimOptim
### Load synthetic data
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
try
@load string(base_path*"data/BGCompass_data_acou.jld") model_true dat fsrc
catch e
@info "Data not found, modeling true data"
include(base_path*"data/gen_data_bg_acou.jl")
@load string(base_path*"data/BGCompass_data_acou.jld") model_true dat fsrc
end
### Background mode
idx_w = 1
var = 20
m0 = deepcopy(model_true.m)
m0[:, idx_w+1:end] = R.(imfilter(m0[:, idx_w+1:end], Kernel.gaussian(var)))
model0 = model_true
model0.m = m0
n = model0.n
### Set objective functional
# Pre- and post-conditioning
mask = zeros(Float32, model0.n)
mask[:, idx_w+1:end] .= 1
function proj_bounds(m, mmin, mmax)
m[m[:] .< mmin] .= mmin
m[m[:] .> mmax] .= mmax
return m
end
mmin = 1f0/6f0^2
mmax = .5f0
preproc(x) = proj_bounds(x, mmin, mmax)
# [FWI]
function funFWI!(F, G, x, dat, fsrc)
model0.m .= preproc(x)
fun, g = fwi_objective(model0, fsrc, dat)
F = fun
isnothing(G) && return fun
isnothing(g_const) && (global g_const = .1/maximum(abs.(g)))
G .= g_const .* g[:] .* vec(mask)
return fun
end
# # [TWRIdual]
ε0 = zeros(Float32, dat.nsrc)
weight_fun_pars = ("srcfocus", 0)
optwri = TWRIOptions(;grad_corr=true, comp_alpha=false, weight_fun=weight_fun_pars, eps=ε, params=:m)
function funWRI!(F, G, x, dat, fsrc, freq)
# Frequency specific focusing
δ = sqrt(2)*m0[1]^(-.5)/(2*freq)
optwri.weight_fun = ("srcfocus", δ)
# Compute objective and gradient
model0.m .= preproc(x)
fun, g = twri_objective(model0, fsrc, dat, nothing; optionswri=optwri)
F = fun
isnothing(g_const) && (global g_const = .1/maximum(abs.(g)))
G .= g_const .* g[:].* vec(mask)
return fun
end
### Optimization
linesearch = HagerZhang(display=1, linesearchmax=5)
method = LBFGS(;linesearch=linesearch)
niter = 10
optimopt = Optim.Options(iterations = niter, store_trace = true, show_trace = true, show_every = 1)
## Starting guess
x0_fwi = vec(m0)
x0_wri = vec(m0)
freq_list = 5:2:19
for f in freq_list
println("\nInverting freqs: ", string(f-1), " - ", string(f+1), " Hz\n")
dat_loc = low_filter(dat, 4; fmin=f-1, fmax=f+1)
fsrc_loc = low_filter(fsrc, 4; fmin=f-1, fmax=f+1)
fwi!(F, G, x) = funFWI!(F, G, x, dat_loc, fsrc_loc)
wri!(F, G, x) = funWRI!(F, G, x, dat_loc, fsrc_loc, f)
# FWI
result = optimize(Optim.only_fg!(fwi!), x0_fwi, method, optimopt)
global x0_fwi = Optim.minimizer(result)
m_inv_fwi = preproc(x0_fwi)
# WRI
result = optimize(Optim.only_fg!(wri!), x0_wri, method, optimopt)
global x0_wri = Optim.minimizer(result)
m_inv_wri = preproc(x0_wri)
# Save iter
@save "$(base_path)/data/BG_compass_acou_sweep_$(f)Hz.jld" f m_inv_fwi m_inv_wri n
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3306 | ################################################################################
#
# Run inversion for the BG Compass model
#
################################################################################
### Module loading
using LinearAlgebra, Dates, Distributed, Images, Random
using JUDI, JUDI.SLIM_optim, JLD2
R = Float32
### Load synthetic data
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
try
@load string(base_path*"data/BGCompass_data_tti.jld") model_true dat fsrc
catch e
@info "Data not found, modeling true data"
include(base_path*"data/gen_data_bg_tti.jl")
@load string(base_path*"data/BGCompass_data_tti.jld") model_true dat fsrc
end
# Different sigmas for smoothing
vvar = [20, 25, 30, 40]
# Global parameters
idx_w = 17
vare = 15
fevals = 20
batchsize = 25
# Bound projection
function proj_bounds(m, mmin, mmax)
m[m[:] .< mmin] .= mmin
m[m[:] .> mmax] .= mmax
return m
end
mmin = 1f0/4.5f0^2
mmax = 1f0/1.4f0^2
ProjBound(x) = proj_bounds(x, mmin, mmax)
for var=vvar
for anis=["tt", "st"]
### Background model
model0 = deepcopy(model_true)
model0.m[:, idx_w+1:end] = R.(imfilter(model0.m[:, idx_w+1:end], Kernel.gaussian(var)))
if anis == "st"
model0.epsilon[:, idx_w+1:end] = R.(imfilter(model0.epsilon[:, idx_w+1:end], Kernel.gaussian(vare)))
model0.delta[:, idx_w+1:end] = R.(imfilter(model0.delta[:, idx_w+1:end], Kernel.gaussian(vare)))
model0.theta[:, idx_w+1:end] = R.(imfilter(model0.theta[:, idx_w+1:end], Kernel.gaussian(vare)))
end
m0 = model0.m
### Set objective functional
mask = zeros(Float32, model0.n)
mask[:, idx_w+1:end] .= 1
# [TWRIdual]
ε = zeros(Float32, fsrc.nsrc)
## Run
# Very basic approximate inverse Hessian
DZ = judiDepthScaling(model0)
# Optimization parameters
optwri = TWRIOptions(;grad_corr=false, comp_alpha=false, weight_fun=nothing, eps=ε, params=:m)
# Objective function for minConf library
function objective_function(x, fun="fwi")
flush(Base.stdout)
x = reshape(x, model0.n)
# fwi function value and gradient
i = randperm(dat.nsrc)[1:batchsize]
# weight_fun_pars=weight_fun_pars
if fun == "wri"
fval, grad = twri_objective(model0, fsrc[i], dat[i], nothing; optionswri=optwri)
else
fval, grad = fwi_objective(model0, fsrc[i], dat[i])
end
grad = DZ*(vec(mask) .* vec(grad))
grad = .1f0 .* grad ./ maximum(abs.(grad)) # scale for line search
return fval, grad
end
wri_fun(x) = objective_function(x, "wri")
fwi_fun(x) = objective_function(x, "fwi")
# FWI with SPG
x0 = vec(m0)
options = spg_options(verbose=3, maxIter=fevals, memory=3, interp=0)
sol = spg(wri_fun, x0, ProjBound, options)
xwri, hwri = sol.x, sol.ϕ_trace
@save string(base_path*"data/wriw_$(anis)_$(var).jld") xwri hwri
x0 = vec(m0)
sol = spg(fwi_fun, x0, ProjBound, options)
xfwi, hfwi = sol.x, sol.ϕ_trace
@save string(base_path*"data/fwiw_$(anis)_$(var).jld") xfwi hfwi
end
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2838 | ################################################################################
#
# Run inversion for the Gaussian lens model
#
################################################################################
R = Float32
### Module loading
using LinearAlgebra, JLD2, PyPlot, Dates, Distributed
using Optim, LineSearches
using JUDI
### Load or model synthetic data
base_path = dirname(pathof(JUDI))*"/../examples/twri/"
try
@load string(base_path*"data/GaussLens_data_acou.jld") model_true dat fsrc
catch e
@info "Data not found, modeling true data"
include(base_path*"data/gen_data_gausslens_acou.jl")
@load string(base_path*"data/GaussLens_data_acou.jld") model_true dat fsrc
end
### Background model
m0 = 1f0./2f0.^2*ones(R, model_true.n)
n = model_true.n
d = model_true.d
o = model_true.o
model0 = Model(n, d, o, m0)
# Pre- and post-conditioning
mask = zeros(Float32, model0.n)
mask[6:end-5, 6:end-5] .= 1
function proj_bounds(m, mmin, mmax)
m[m[:] .< mmin] .= mmin
m[m[:] .> mmax] .= mmax
return m
end
mmin = 1f0/4f0^2
mmax = 1f0/1f0^2
preproc(x) = proj_bounds(x, mmin, mmax)
# [FWI]
function funFWI!(F, G, x)
i = rand(1:15, 4)
model0.m .= preproc(x)
fun, g = fwi_objective(model0, fsrc[i], dat[i])
F = fun
isnothing(G) && return fun
isnothing(g_const) && (global g_const = .1/maximum(abs.(g)))
G .= g_const .* g[:] .* vec(mask)
return fun
end
# # [TWRIdual]
ε = zeros(Float32, fsrc.nsrc)
v_bg = sqrt(1/m0[1])
freq_peak = 0.006f0
δ = R(sqrt(2)/2)*v_bg/freq_peak
weight_fun_pars = ("srcfocus", δ)
optwri = TWRIOptions(;grad_corr=true, comp_alpha=true, weight_fun=weight_fun_pars, eps=ε, params=:m)
function funWRI(F, G, x, optwri)
i = rand(1:15, 4)
model0.m .= preproc(x)
fun, g = twri_objective(model0, fsrc[i], dat[i], nothing; optionswri=optwri)
F = fun
isnothing(G) && return fun
isnothing(g_const) && (global g_const = .1/maximum(abs.(g)))
G .= g_const .* g[:].* vec(mask)
return fun
end
funWRI!(F, G, x) = funWRI(F, G, x, optwri)
### Optimization
linesearch = HagerZhang(display=1, linesearchmax=10)
# Options
method = LBFGS(;linesearch=linesearch)
niter = 20
optimopt = Optim.Options(g_calls_limit=200, iterations = niter, store_trace = true, show_trace = true, show_every = 1)
# ## Run FWI
g_const = nothing
x0_fwi = vec(m0)
result = optimize(Optim.only_fg!(funFWI!), x0_fwi, method, optimopt)
x0_fwi .= Optim.minimizer(result)
m_inv_fwi = preproc(x0_fwi)
loss_log_fwi = Optim.f_trace(result)
@save "./GaussLens_result_fwi.jld" m_inv_fwi loss_log_fwi
## Run WRI
g_const = nothing
x0_wri = vec(m0)
result = optimize(Optim.only_fg!(funWRI!), x0_wri, method, optimopt)
x0_wri .= Optim.minimizer(result)
m_inv_wri = preproc(x0_wri)
loss_log_wri = Optim.f_trace(result)
@save "./GaussLens_result_wri.jld" m_inv_wri loss_log_wri
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 383 | module CUDAJUDIExt
import JUDI: LazyPropagation, judiVector, eval_prop
isdefined(Base, :get_extension) ? (using CUDA) : (using ..CUDA)
CUDA.cu(F::LazyPropagation) = CUDA.cu(eval_prop(F))
CUDA.cu(x::Vector{Matrix{T}}) where T = [CUDA.cu(x[i]) for i=1:length(x)]
CUDA.cu(x::judiVector{T, Matrix{T}}) where T = judiVector{T, CUDA.CuMatrix{T}}(x.nsrc, x.geometry, CUDA.cu(x.data))
end | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 226 | module FluxJUDIExt
import JUDI: LazyPropagation
isdefined(Base, :get_extension) ? (using Flux) : (using ..Flux)
Flux.cpu(x::LazyPropagation) = Flux.cpu(eval_prop(x))
Flux.gpu(x::LazyPropagation) = Flux.gpu(eval_prop(x))
end | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 625 | module JLD2JUDIExt
using JUDI
isdefined(Base, :get_extension) ? (using JLD2) : (using ..JLD2)
JLD2.rconvert(::Type{Geometry}, x::JLD2.ReconstructedMutable{N, FN, NT}) where {N, FN, NT} = Geometry([JUDI.tof32(getproperty(x, f)) for f in FN]...)
JUDI.Geometry(x::JLD2.ReconstructedMutable{N, FN, NT}) where {N, FN, NT} = Geometry([JUDI.tof32(getproperty(x, f)) for f in FN]...)
function JUDI.tof32(x::JLD2.ReconstructedStatic{N, FN, NT}) where {N, FN, NT}
# Drop "typed" signature
reconstructT = Symbol(split(string(N), "{")[1])
return JUDI.tof32(eval(reconstructT)([getproperty(x, f) for f in FN]...))
end
end | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 444 | module ZygoteJUDIExt
import JUDI: LazyPropagation, judiVector, eval_prop
isdefined(Base, :get_extension) ? (using Zygote) : (using ..Zygote)
Zygote.unbroadcast(x::AbstractArray, x̄::LazyPropagation) = Zygote.unbroadcast(x, eval_prop(x̄))
function Zygote.accum(x::judiVector{T, AT}, y::DenseArray) where {T, AT}
newd = [Zygote.accum(x.data[i], y[:, :, i, 1]) for i=1:x.nsrc]
return judiVector{T, AT}(x.nsrc, x.geometry, newd)
end
end | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 4666 | # Module with functions for time-domain modeling and inversion using OPESCI/devito
# Author: Philipp Witte, [email protected]
# Date: January, 2017
# Updated, December 2020, Mathias Louboutin, [email protected]
__precompile__()
module JUDI
export JUDIPATH, set_verbosity, ftp_data, get_serial, set_serial, set_parallel
JUDIPATH = dirname(pathof(JUDI))
# Only needed if extension not available (julia < 1.9)
if !isdefined(Base, :get_extension)
using Requires
end
# Dependencies
using LinearAlgebra, Random, Printf
using Distributed
using DSP, FFTW, Dierckx
using PyCall
using JOLI, SegyIO
using ChainRulesCore
using OrderedCollections
# Import Base functions to dispatch on JUDI types
import Base.depwarn
import Base.*, Base./, Base.+, Base.-, Base.==, Base.\
import Base.copy!, Base.copy, Base.copyto!, Base.deepcopy, Base.summary
import Base.sum, Base.ndims, Base.reshape, Base.fill!, Base.axes, Base.dotview
import Base.eltype, Base.length, Base.size, Base.iterate, Base.show, Base.display, Base.showarg, Base.elsize
import Base.maximum, Base.minimum, Base.push!
import Base.Broadcast.ArrayStyle, Base.Broadcast.extrude
import Base.Broadcast.broadcasted, Base.BroadcastStyle, Base.Broadcast.DefaultArrayStyle, Base.Broadcast, Base.broadcast!
import Base.getindex, Base.setindex!, Base.firstindex, Base.lastindex
import Base.similar, Base.isapprox, Base.isequal
import Base.materialize!, Base.materialize, Base.Broadcast.instantiate
import Base.promote_shape, Base.diff, Base.cumsum, Base.cumsum!
import Base.getproperty, Base.unsafe_convert, Base.convert
# Import Linear Lagebra functions to dispatch on JUDI types
import LinearAlgebra.transpose, LinearAlgebra.conj, LinearAlgebra.vcat, LinearAlgebra.adjoint
import LinearAlgebra.vec, LinearAlgebra.dot, LinearAlgebra.norm, LinearAlgebra.abs
import LinearAlgebra.rmul!, LinearAlgebra.lmul!, LinearAlgebra.rdiv!, LinearAlgebra.ldiv!
import LinearAlgebra.mul!, Base.isfinite, Base.inv
# JOLI
import JOLI: jo_convert
# FFTW
import FFTW: fft, ifft
# Import pycall array to python for easy plotting
import PyCall.NpyArray
# Import AD rrule
import ChainRulesCore: rrule
# Set python paths
export devito
const pm = PyNULL()
const ac = PyNULL()
const pyut = PyNULL()
const devito = PyNULL()
# Constants
nworkers(::Any) = length(workers())
_TFuture = Future
_verbose = false
_devices = []
# Some usefull types
const RangeOrVec = Union{AbstractRange, Vector}
# Utils
include("utilities.jl")
# JUDI time modeling
include("TimeModeling/TimeModeling.jl")
module TimeModeling
using ..JUDI
# Define backward compatible types so that old JLD files load properly
# Old JLD file expected to be arrays, SeisCon are expected to be read and built
# from SEGY files
const judiVector{T} = JUDI.judiVector{T, Matrix{T}} where T
const GeometryIC = JUDI.GeometryIC{Float32}
const GeometryOOC = JUDI.GeometryOOC{Float32}
end
# Backward Compatibility
include("compat.jl")
# Automatic Differentiation
include("rrules.jl")
# Initialize
function __init__()
pushfirst!(PyVector(pyimport("sys")."path"), joinpath(JUDIPATH, "pysource"))
copy!(pm, pyimport("models"))
copy!(ac, pyimport("interface"))
copy!(pyut, pyimport("utils"))
copy!(devito, pyimport("devito"))
# Initialize lock at session start
PYLOCK[] = ReentrantLock()
# Make sure there is no conflict for the cuda init thread with CUDA.jl
if get(ENV, "DEVITO_PLATFORM", "") == "nvidiaX"
@info "Initializing openacc/openmp offloading"
devito_model(Model((21, 21, 21), (10., 10., 10.), (0., 0., 0.), randn(Float32, 21, 21, 21)), Options())
global _devices = parse.(Int, get(ENV, "CUDA_VISIBLE_DEVICES", "-1"))
end
# Optional dependencies
@static if !isdefined(Base, :get_extension)
# JLD2 compat for loading older version of JUDI types
@require JLD2="033835bb-8acc-5ee8-8aae-3f567f8a3819" begin
@info "JLD2 compat enabled"
include("../ext/JLD2JUDIExt.jl")
end
# Additional Zygote compat if in use
@require Zygote="e88e6eb3-aa80-5325-afca-941959d7151f" begin
@info "Zygote compat enabled"
include("../ext/ZygoteJUDIExt.jl")
end
# Additional Flux compat if in use
@require Flux="587475ba-b771-5e3f-ad9e-33799f191a9c" begin
@info "Flux compat enabled"
include("../ext/FluxJUDIExt.jl")
end
# Additional Flux compat if in use
@require CUDA="052768ef-5323-5732-b1bb-66c8b64840ba" begin
@info "CUDA compat enabled"
include("../ext/CUDAJUDIExt.jl")
end
end
end
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1189 | export Info
# Compatibility with `info`
const IntNum = Union{Integer, Tuple{Integer,Integer}, Tuple{Integer,Integer,Integer}}
mutable struct Info
n::IntNum
nsrc::Integer
nt::Array{Integer,1}
end
function Info(n::IntNum, nsrc::Integer, nt::Integer)
depwarn("Info is deprecated and will be removed in future versions", :Info; force=true)
Info(n, nsrc, [nt for i=1:nsrc])
end
for f in [:judiModeling, :judiProjection, :judiWavefield]
@eval function $f(info::Info, ar...;kw...)
depwarn("$($f)(info::Info, ar...; kw...) is deprecated, use $($f)(ar...; kw...)", Symbol($f); force=true)
$f(ar...; kw...)
end
end
for f in [:judiLRWF, :judiRHS]
@eval $f(info::Info, ar...;kw...) = throw(ArgumentError("$($f)(info::Info, ...) is deprecated and requires a time sampling rate `dt`"))
end
# model.n, model.d, model.o
function getproperty(m::AbstractModel, s::Symbol)
for (sl, ns) in zip([:n, :d, :o, :nb], [:size, :spacing, :origin, :nbl])
if s == sl
depwarn("Deprecated model.$(s), use $(ns)(model)", Symbol("model.$(s)"); force=true)
return getfield(m.G, s)
end
end
return getfield(m, s)
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 7085 | """
LazyPropagation
post::Function
F::judiPropagator
q
A structure to encapsulate a JUDI propagation that may not need to be computed. This allows to
to bypass ChainRule's thunks that do not play well with Zygote (may be fixed). Only a few arithmetic operations
are supported. By default, any attempt to perform an arithmectic (+, -, *, ...) operation on a LazyPropagation will evaluate the propagation.
**Note**: Long term, this should be extended in order to allow writing FWI/LSRTM with linear operators
rather than the `fwi_objective/lsrtm_objective` wrapper and infer what needs to be computed from these unevaluated propagations.
Parameters
===========
* `RT`: the return type of F*q for dispatch
* `post`: Function (default to identity). Function to be applied to the result `post(F*q)` after propagation
* `F`: the JUDI propgator
* `q`: The source to compute F*q
"""
struct LazyPropagation
post::Function
F::judiPropagator
q
end
eval_prop(F::LazyPropagation) = F.post(F.F * F.q)
Base.collect(F::LazyPropagation) = eval_prop(F)
LazyPropagation(F::judiPropagator, q) = LazyPropagation(identity, F, q)
# Only a few arithmetic operation are supported
for op in [:+, :-, :*, :/]
@eval begin
$(op)(F::LazyPropagation, y::AbstractArray{T}) where T = $(op)(eval_prop(F), y)
$(op)(y::AbstractArray{T}, F::LazyPropagation) where T = $(op)(y, eval_prop(F))
$(op)(y::LazyPropagation, F::LazyPropagation) = $(op)(eval_prop(y), eval_prop(F))
broadcasted(::typeof($op), y::LazyPropagation, F::LazyPropagation) = broadcasted($(op), eval_prop(y), eval_prop(F))
end
for YT ∈ [AbstractArray, Broadcast.Broadcasted]
@eval begin
broadcasted(::typeof($op), F::LazyPropagation, y::$(YT)) = broadcasted($(op), eval_prop(F), y)
broadcasted(::typeof($op), y::$(YT), F::LazyPropagation) = broadcasted($(op), y, eval_prop(F))
end
end
end
broadcasted(::typeof(^), y::LazyPropagation, p::Real) = eval_prop(y).^(p)
*(F::judiPropagator, q::LazyPropagation) = F*eval_prop(q)
*(M::Preconditioner, q::LazyPropagation) = M*eval_prop(q)
matvec(M::Preconditioner, q::LazyPropagation) = matvec(M, eval_prop(q))
matvec(M::MultiPreconditioner, q::LazyPropagation) = matvec(M, eval_prop(q))
reshape(F::LazyPropagation, dims...) = LazyPropagation(x->reshape(x, dims...), F.F, F.q)
copyto!(x::AbstractArray, F::LazyPropagation) = copyto!(x, eval_prop(F))
dot(x::AbstractArray, F::LazyPropagation) = dot(x, eval_prop(F))
dot(F::LazyPropagation, x::AbstractArray) = dot(x, F)
norm(F::LazyPropagation, p::Real=2) = norm(eval_prop(F), p)
adjoint(F::JUDI.LazyPropagation) = LazyPropagation(x->adjoint(F.post(x)), F.F, F.q)
############################ Two params rules ############################################
function rrule(F::judiPropagator{T, O}, m::AbstractArray{T}, q::AbstractArray{T}) where {T, O}
y = F(m, q)
function pullback(Δy)
dm = ∇m(F, m, q, Δy)
dq = ∇source(F, m, Δy)
return (NoTangent(), dm, dq)
end
y = F.options.return_array ? reshape(y, F.rInterpolation, F.model; with_batch=true) : y
return y, pullback
end
function ∇source(F::judiPropagator{T, O}, m::AbstractArray{T}, Δy) where {T, O}
ra = F.options.return_array
# Reshape if vector
post::Function = ra ? (dq -> reshape_array(dq, F')) : identity
return LazyPropagation(post, F(m)', Δy)
end
function ∇m(F::judiPropagator{T, :forward}, m::AbstractArray{T}, q::AbstractArray{T}, Δy) where {T}
ra = F.options.return_array
# Reshape if vector and a-dimensionalize
post::Function = ra ? (dm -> reshape(dm, F.model.n..., 1, 1)) : identity
q = _as_src(F.qInjection.op, F.model, q)
return LazyPropagation(post, judiJacobian(F(m), q)', Δy)
end
∇m(F::judiPropagator{T, :adjoint}, m, q, Δy) where {T} = ∇m(adjoint(F), m, Δy, q)
############################ Single param rules ############################################
# We derive the following rule based on linear algebra calculus for parametric matrices
# The derivation of the dF where F = F(m) is derived below for F a wave-equation
# propagator. The derivation is not valid for J the Jacobian that is not currently supported
# for this case but is ony supported for J(q) where q is the source of the underlying wave equation.
#
# d (f(F*x))/dm = tr( (d (f(F*x))/dF)^T dF/dm)
# dF/dm = J(m)
# d (f(F*x))/dF = dy x^T
# d (f(F*x))/dm = tr( (dy x^T)^T J ) = tr( x dy^T dF/dm ) = tr( x dy^T dF/dm )
# = tr( - Pr Ai da/dm Ai Ps' x dy^T)
# = tr( - Pr Ai (u.dt2) dy^T)
# = tr( - dy^T Pr Ai (u.dt2) )
# = tr(- (u.dt2)^T Ai^T Pr^ dy) = J^T dy
# F = Pr Ai(m) Ps'
# dF/dm = Pr dAi/dm Ps' = - Pr Ai da/dm Ai Ps'
#
#
# Finally, for simplicity, we directly return `dm` rather than a Tangent to avoid
# complications with the fields.
function rrule(::typeof(*), F::judiPropagator, x::AbstractArray{T}) where T
ra = F.options.return_array
y = F*x
postx = ra ? (dx -> reshape(dx, size(x))) : identity
function Fback(Δy)
dx = LazyPropagation(postx, F', Δy)
# F is m parametric
dF = ∇prop(F, x, Δy)
return NoTangent(), dF, dx
end
y = F.options.return_array ? reshape_array(y, F) : y
return y, Fback
end
# Rule for x->F(x). Currently supported are
# m -> F(m) where m is the squared slowness and F is a wave-equation propagator
# q -> J(a) where q is a source and J is the Jacobian w.r.t m of a wave-equation propagator
# This rules expect the input of the pullback to come from F*q and to be a LazyPropagation
function rrule(F::judiPropagator, x)
Fx = F(x)
postx = F.options.return_array ? (dx -> reshape(dx, size(x))) : identity
function backx(ΔF)
dx = LazyPropagation(postx, ΔF.F, ΔF.q)
return NoTangent(), dx
end
return Fx, backx
end
∇prop(F::judiPropagator, q::AbstractArray, dy::AbstractArray) = LazyPropagation(judiJacobian(F, q)', dy)
∇prop(J::judiJacobian{D, :born, FT}, dm::AbstractArray, δd::AbstractArray) where {D, FT} = LazyPropagation(judiJacobian(adjoint(J.F), δd), dm)
∇prop(J::judiJacobian{D, :adjoint_born, FT}, δd::AbstractArray, dm::AbstractArray) where {D, FT} = LazyPropagation(judiJacobian(adjoint(J.F), δd), dm)
# projection
(project::ProjectTo{AbstractArray})(dx::PhysicalParameter) = project(reshape(dx.data, project.axes))
(project::ProjectTo{AbstractArray})(dx::LazyPropagation) = project(reshape(eval_prop(dx), project.axes))
# Reshaping
reshape_array(u, F::judiPropagator) = reshape(u, F.rInterpolation, F.model; with_batch=true)
reshape_array(u, F::judiAbstractJacobian{T, :adjoint_born, FT}) where {T, FT} = reshape(u, F.model.n..., 1, 1)
# Adjoint to avoid odd corner cases in some Zygote version
function rrule(::typeof(adjoint), F::judiPropagator)
Fa = adjoint(F)
_LinOp_pullback(y) = (NoTangent(), adjoint(y))
return Fa, _LinOp_pullback
end
# Preconditioners
function rrule(::typeof(*), P::Preconditioner, x)
back(y) = NoTangent(), NoTangent(), matvec_T(P, y)
return matvec(P, x), back
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3023 | export set_devito_config, ftp_data, set_serial, set_parallel, set_verbosity
export devito_omp, devito_icx, devito_acc, devito_nvc_host, devito_cuda, devito_sycl, devito_hip
# Logging utilities
set_verbosity(x::Bool) = begin global _verbose = x; end
judilog(msg) = _verbose ? printstyled("JUDI: $(msg) \n", color=:magenta) : nothing
function human_readable_time(t::Float64, decimals=2)
units = ["ns", "μs", "ms", "s", "min", "hour"]
scales = [1e-9, 1e-6, 1e-3, 1, 60, 3600]
if t < 1e-9
tr = round(t/1e-9; sigdigits=decimals)
return "$(tr) ns"
end
for i=2:6
if t < scales[i]
tr = round(t/scales[i-1]; sigdigits=decimals)
return "$(tr) $(units[i-1])"
end
end
tr1 = div(t, 3600)
tr2 = round(Int, rem(t, 3600))
return "$(tr1) h $(tr2) min"
end
macro juditime(msg, ex)
return quote
local t
t = @elapsed $(esc(ex))
tr = human_readable_time(t)
judilog($(esc(msg))*": $(tr)")
end
end
# Utility for data loading
JUDI_DATA = joinpath(JUDIPATH, "../data")
ftp_data(ftp::String, name::String) = Base.Downloads().download("$(ftp)/$(name)", "$(JUDI.JUDI_DATA)/$(name)")
ftp_data(ftp::String) = Base.Downloads().download(ftp, "$(JUDI.JUDI_DATA)/$(split(ftp, "/")[end])")
# Parallelism
_serial = false
get_serial() = _serial
set_serial(x::Bool) = begin global _serial = x; end
set_serial() = begin global _serial = true; end
set_parallel() = begin global _serial = false; end
function _worker_pool()
if _serial
return nothing
end
p = default_worker_pool()
pool = nworkers(p) < 2 ? nothing : p
return pool
end
# Create a lock for pycall FOR THREAD/TASK SAFETY
# See discussion at
# https://github.com/JuliaPy/PyCall.jl/issues/882
const PYLOCK = Ref{ReentrantLock}()
# acquire the lock before any code calls Python
pylock(f::Function) = Base.lock(PYLOCK[]) do
prev_gc = GC.enable(false)
try
return f()
finally
GC.enable(prev_gc) # recover previous state
end
end
function rlock_pycall(meth, ::Type{T}, args...; kw...) where T
out::T = pylock() do
pycall(meth, T, args...; kw...)
end
return out
end
# Devito configuration
set_devito_config(key::String, val::String) = set!(devito."configuration", key, val)
set_devito_config(key::String, val::Bool) = set!(devito."configuration", key, val)
set_devito_config(kw...) = begin
for (k, v) in kw
set_devito_config(k, v)
end
end
# Easy configurations setupes
devito_omp() = set_devito_config("language", "openmp")
devito_icx() = set_devito_config(language="openmp", compiler="icx")
devito_acc() = set_devito_config(language="openacc", compiler="nvc", platform="nvidiaX")
devito_nvc_host() = set_devito_config(language="openmp", compiler="nvc")
devito_cuda() = set_devito_config(language="cuda", platform="nvidiaX")
devito_sycl() = set_devito_config(language="sycl", platform="intelgpuX")
devito_hip() = set_devito_config(language="hip", platform="amdgpuX")
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3284 | # Functions for time-domain modeling and inversion using devito
# Author: Philipp Witte, [email protected]
# Date: January, 2017
# Updated, December 2020, Mathias Louboutin, [email protected]
#############################################################################
# Basics
include("LinearOperators/basics.jl")
#############################################################################
# Containers
const Pdtypes = Union{Float32, Float16}
include("Types/ModelStructure.jl") # model container
include("Types/GeometryStructure.jl") # source or receiver setup, recording time and sampling
include("Types/OptionsStructure.jl")
#############################################################################
# Abstract vectors
include("Types/abstract.jl")
include("Types/lazy_msv.jl")
include("Types/broadcasting.jl")
include("Types/judiWavefield.jl") # dense RHS (wavefield)
include("Types/judiWeights.jl") # Extended source weight vector
include("Types/judiVector.jl") # Julia data container
include("Types/judiComposites.jl") # A composite type to work with hcat/vcat of judi types
# Utility types
const SourceType{T} = Union{Vector{T}, Matrix{T}, judiMultiSourceVector{T}, PhysicalParameter{T}}
const dmType{T} = Union{Vector{T}, PhysicalParameter{T}}
#############################################################################
# Utils
include("Utils/auxiliaryFunctions.jl")
include("Utils/time_utilities.jl")
include("Modeling/losses.jl")
#############################################################################
# Linear operators
include("LinearOperators/lazy.jl")
include("LinearOperators/operators.jl")
include("LinearOperators/callable.jl")
#############################################################################
# Preconditioners
include("Preconditioners/base.jl")
include("Preconditioners/utils.jl")
include("Preconditioners/DataPreconditioners.jl")
include("Preconditioners/ModelPreconditioners.jl")
#############################################################################
# PDE solvers
include("Modeling/distributed.jl") # Modeling functions utilities
include("Modeling/python_interface.jl") # forward/adjoint linear/nonlinear modeling
include("Modeling/time_modeling_serial.jl") # forward/adjoint linear/nonlinear modeling
include("Modeling/misfit_fg.jl") # FWI/LSRTM objective function value and gradient
include("Modeling/twri_objective.jl") # TWRI objective function value and gradient
include("Modeling/propagation.jl")
#############################################################################
# Extra that need all imports
############################################################################################################################
# Enforce right precedence. Mainly we always want (rightfully)
# - First data operation on the right
# - Then propagation
# - Then right preconditioning
# I.e Ml * P * M * q must do Ml * (P * (M * q))
# It''s easier to just hard code the few cases that can happen
for T in [judiMultiSourceVector, dmType]
@eval *(Ml::Preconditioner, P::judiPropagator, Mr::Preconditioner, v::$(T)) = Ml * (P * (Mr * v))
@eval *(P::judiPropagator, Mr::Preconditioner, v::$(T)) = P * (Mr * v)
@eval *(Ml::Preconditioner, P::judiPropagator, v::$(T)) = Ml * (P * v)
end | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3113 | export AbstractSize, time_space, time_space_src, time_src, rec_space, space, space_src
struct AbstractSize
dims::Dict
end
AbstractSize(n::NTuple{N, Symbol}, sizes) where N = AbstractSize(Dict(zip(n, sizes)))
# Base
function getindex(S::AbstractSize, sinds::Union{AbstractRange, Vector{<:Integer}})
k = keys(S.dims)
dim_map = copy(S.dims)
for (k, v) in S.dims
new_v = typeof(v) <: Integer ? v : v[sinds]
dim_map[k] = new_v
end
:src ∈ keys(dim_map) && (dim_map[:src] = length(sinds))
AbstractSize(dim_map)
end
getindex(S::AbstractSize, i::Integer) = getindex(S, i:i)
getindex(S::AbstractSize, I...) = AbstractSize(keys(S.dims[I...]), values(S.dims[I...]))
getindex(S::AbstractSize, I::Symbol) = S.dims[I]
setindex!(S::AbstractSize, v, I::Symbol) = setindex!(S.dims, v, I)
iterate(S::AbstractSize) = iterate(S.dims)
iterate(S::AbstractSize, state) = iterate(S.dims, state)
Base.isless(i::Int64, a::AbstractSize) = isless(i, nsamples(a))
convert(::Type{T}, S::AbstractSize) where T<:Number = convert(T, nsamples(S))
(::Type{T})(S::AbstractSize) where T<:Union{Integer, AbstractFloat} = convert(T, nsamples(S))
(c::Colon)(i::T, S::AbstractSize) where T = c(i, T(S))
Base.keys(S::AbstractSize) = keys(S.dims)
Base.values(S::AbstractSize) = values(S.dims)
Base.merge!(S1::AbstractSize, S2::AbstractSize) = merge!(S1.dims, S2.dims)
==(S1::AbstractSize, S2::AbstractSize) = S1.dims == S2.dims
==(S1::Integer, S2::AbstractSize) = nsamples(S2) == S1
==(S1::AbstractSize, S2::Integer) = nsamples(S1) == S2
Base.repr(S::AbstractSize) = "($(join(keys(S.dims), " * ")))"
similar(x::AbstractVector, ::Type{ET}, dims::AbstractSize) where ET = similar(x, ET, Int(dims))
# Update size
set_space_size!(S::AbstractSize, vals::NTuple{2, Integer}) = begin pop!(S.dims, :y, 0); merge!(S.dims, Dict(zip((:x, :z), vals))) end
set_space_size!(S::AbstractSize, vals::NTuple{3, Integer}) = merge!(S.dims, Dict(zip((:x, :y, :z), vals)))
# Actual integer size
nsamples(dims::Dict{Symbol, Any}) = sum(.*(values(dims)...)) ÷ get(dims, :src, 1)
nsamples(dims::Dict{N, <:Integer}) where N = prod(values(dims))
nsamples(D::AbstractSize) = nsamples(D.dims)
# Constructors
space(N::NTuple{2, Integer}) = AbstractSize((:x, :z), (N[1], N[2]))
space(N::NTuple{3, Integer}) = AbstractSize((:x, :y, :z), (N[1], N[2], N[3]))
time_space(N::NTuple{2, Integer}) = AbstractSize((:time, :x, :z), ([0], N[1], N[2]))
time_space(N::NTuple{3, Integer}) = AbstractSize((:time, :x, :y, :z), ([0], N[1], N[2], N[3]))
time_space_src(nsrc::Integer, nt, N::Integer) = AbstractSize((:src, :time, :x, :y, :z), (nsrc, nt, zeros(Int, N)...))
time_space_src(nsrc::Integer, nt, N::NTuple{2, Integer}) = AbstractSize((:src, :time, :x, :z), (nsrc, nt, N...))
time_space_src(nsrc::Integer, nt, N::NTuple{3, Integer}) = AbstractSize((:src, :time, :x, :y, :z), (nsrc, nt, N...))
time_space_src(nsrc::Integer, nt) = AbstractSize((:src, :time, :x, :y, :z), (nsrc, nt, 0, 0, 0))
space_src(nsrc::Integer) = AbstractSize((:src, :x, :y, :z), (nsrc, 0, 0, 0))
time_src(nsrc::Integer, nt) = AbstractSize((:src, :time), (nsrc, nt)) | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 1876 |
#############################################################################
(F::judiModeling{D, O})(m::AbstractModel{D, N}) where {D, O, N} = judiModeling(m; options=F.options)
(FS::judiDataSourceModeling{D, O})(F::judiModeling{D, O}) where {D, O} = judiDataSourceModeling{D, O}(FS.rInterpolation, F, FS.qInjection)
(FS::judiDataModeling{D, O})(F::judiModeling{D, O}) where {D, O} = judiDataModeling{D, O}(FS.rInterpolation, F)
(FS::judiPointSourceModeling{D, O})(F::judiModeling{D, O}) where {D, O} = judiPointSourceModeling{D, O}(F, FS.qInjection)
(J::judiJacobian{D, O, FT})(F::judiModeling{D, O}) where {D, O, FT} = judiJacobian(J.F(F), J.q)
for FT in [judiPointSourceModeling, judiDataModeling, judiDataSourceModeling, judiJacobian]
@eval begin
(F::$(FT))(m::AbstractModel) = F(F.F(m))
end
end
function (F::judiPropagator)(;kwargs...)
Fl = deepcopy(F)
for (k, v) in kwargs
k in _mparams(Fl.model) && getfield(Fl.model, k) .= reshape(v, size(Fl.model))
end
Fl
end
function (F::judiPropagator)(m, q)
Fm = F(;m=m)
_track_illum(F.model, Fm.model)
return Fm*as_src(q)
end
function (F::judiPropagator)(m::AbstractArray)
@info "Assuming m to be squared slowness for $(typeof(F))"
return F(;m=reshape(m, size(F.model)))
end
(F::judiPropagator)(m::AbstractModel, q) = F(m)*as_src(q)
function (J::judiJacobian{D, O, FT})(q::judiMultiSourceVector) where {D, O, FT}
newJ = judiJacobian{D, O, FT}(J.m, J.n, J.F, q)
_track_illum(J.model, newJ.model)
return newJ
end
function (J::judiJacobian{D, O, FT})(x::Array{D, N}) where {D, O, FT, N}
if length(x) == prod(size(J.model))
return J(;m=reshape(x, size(F.model.n)))
end
new_q = _as_src(J.qInjection.op, J.model, x)
newJ = judiJacobian{D, O, FT}(J.m, J.n, J.F, new_q)
_track_illum(J.model, newJ.model)
return newJ
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 9116 | export judiProjection, judiWavelet, judiLRWF, judiRHS
############################################################################################################################
# Abstract types
abstract type judiNoopOperator{D} <: joAbstractLinearOperator{D, D} end
############################################################################################################################
# Concrete types
# Lazy adjoint like in LinearAlgebra
struct jAdjoint{T}
op::T
end
# Projection operator
struct judiProjection{D} <: judiNoopOperator{D}
m::AbstractSize
n::AbstractSize
geometry::Geometry
end
# Wavelet "projection"
struct judiWavelet{D} <: judiNoopOperator{D}
m::AbstractSize
n::AbstractSize
wavelet::Vector{Array{D, N}} where N
dt::Vector{D}
end
# Poorly named backward compat
const judiLRWF{T} = judiWavelet{T}
const Projection{D} = Union{judiProjection{D}, judiWavelet{D}}
const AdjointProjection{D} = jAdjoint{<:Projection{D}}
"""
judiRHS
dt::Vector{T}
geometry::Geometry
data
Abstract sparse vector for right-hand-sides of the modeling operators. The `judiRHS` vector has the\\
dimensions of the full time history of the wavefields, but contains only the data defined at the \\
source or receiver positions (i.e. wavelets or shot records).
Constructor
==========
judiRHS(dt, geometry, data)
Examples
========
Assuming `Pr` and `Ps` are projection operators of type `judiProjection` and `dobs` and `q` are\\
seismic vectors of type `judiVector`, then a `judiRHS` vector can be created as follows:
rhs = Pr'*dobs # right-hand-side with injected observed data
rhs = Ps'*q # right-hand-side with injected wavelet
"""
struct judiRHS{D} <: judiMultiSourceVector{D}
nsrc::Integer
P::jAdjoint{judiProjection{D}}
d::judiVector
end
############################################################################################################################
# Constructors
"""
judiProjection(geometry)
Projection operator for sources/receivers to restrict or inject data at specified locations.
Examples
========
`F` is a modeling operator of type `judiModeling` and `q` is a seismic source of type `judiVector`:
Pr = judiProjection(rec_geometry)
Ps = judiProjection(q.geometry)
dobs = Pr*F*Ps'*q
qad = Ps*F'*Pr'*dobs
"""
judiProjection(G::Geometry) = judiProjection{Float32}(rec_space(G), time_space_src(get_nsrc(G), G.nt, 3), G)
"""
judiWavelet(dt, wavelet)
Low-rank wavefield operator which injects a wavelet q at every point of the subsurface.
Examples
========
`F` is a modeling operator of type `judiModeling` and `w` is a weighting matrix of type `judiWeights`:
Pr = judiProjection(rec_geometry)
Pw = judiWavelet(rec_geometry.dt, q.data) # or judiLRWF(rec_geometry.dt, q.data)
dobs = Pr*F*Pw'*w
dw = Pw*F'*Pr'*dobs
"""
judiWavelet(nsrc::Integer, dt::T, w::Array{T, N}) where {T<:AbstractFloat, N} = judiWavelet{Float32}(space_src(nsrc), time_space_src(nsrc, length.(w)), [w for i=1:nsrc], [dt for i=1:nsrc])
judiWavelet(dt::T, w::Array{T, N}) where {T<:AbstractFloat, N} = judiWavelet(1, dt, w)
judiWavelet(dt::Vector{<:Number}, w::Vector{T}) where T<:Array = judiWavelet{Float32}(space_src(length(dt)), time_space_src(length(dt), length.(w)), w, dt)
judiWavelet(dt::Vector{<:Number}, w::Vector{<:Number}) = judiWavelet{Float32}(space_src(length(dt)), time_space_src(length(dt), [length(w) for i=1:length(dt)]), [w for i=1:length(dt)], dt)
judiWavelet(dt::dtT, w::Array{T, N}) where {dtT<:Number, T<:Array, N} = judiWavelet([dt for i=1:length(w)], w)
# Deprecation error
judiWavelet(::Integer, ::Array{T, N}) where {T<:AbstractFloat, N} = throw(ArgumentError("Time sampling of the wavelet need to be suplied `judiWavelet(nsrc, dt, wavelet)`"))
############################################################################################################################
# Base overload
getproperty(P::judiProjection, s::Symbol) = s == :data ? P.geometry : getfield(P, s)
getproperty(P::judiWavelet, s::Symbol) = s == :data ? P.wavelet : getfield(P, s)
function getproperty(jA::jAdjoint, s::Symbol)
s == :m && (return jA.op.n)
s == :n && (return jA.op.m)
s == :op && (return getfield(jA, s))
return getproperty(jA.op, s)
end
size(jA::jAdjoint) = (jA.op.n, jA.op.m)
display(P::jAdjoint) = println("Adjoint($(P.op))")
display(P::judiProjection{D}) where D = println("JUDI projection operator $(repr(P.n)) -> $(repr(P.m))")
############################################################################################################################
# Indexing
getindex(jA::jAdjoint{T}, i) where T = jAdjoint{T}(jA.op[i])
getindex(P::judiProjection{D}, i) where D = judiProjection{D}(P.m[i], P.n[i], P.geometry[i])
getindex(P::judiProjection{D}, i::Integer) where D = judiProjection{D}(P.m[i], P.n[i], P.geometry[i:i])
getindex(P::judiWavelet{D}, i) where D = judiWavelet{D}(P.m[i], P.n[i], P.wavelet[i], P.dt[i])
getindex(P::judiWavelet{D}, i::Integer) where D = judiWavelet{D}(P.m[i], P.n[i], P.wavelet[i:i], P.dt[i:i])
getindex(rhs::judiRHS{D}, i::Integer) where D = judiRHS{D}(length(i), rhs.P[i], rhs.d[i])
getindex(rhs::judiRHS{D}, i::RangeOrVec) where D = judiRHS{D}(length(i), rhs.P[i], rhs.d[i])
# Backward compatible subsample
subsample(P::judiNoopOperator{D}, i) where D = getindex(P, i)
############################################################################################################################
# Linear algebra
adjoint(jA::jAdjoint) = jA.op
adjoint(P::judiNoopOperator{D}) where D = jAdjoint(P)
transpose(jA::jAdjoint) = jA.op
transpose(P::judiNoopOperator{D}) where D = jAdjoint(P)
conj(jA::jAdjoint) = jA
conj(P::judiNoopOperator{D}) where D = P
*(P::jAdjoint{judiProjection{D}}, d::judiVector{D, AT}) where {D, AT} = judiRHS{D}(d.nsrc, P, d)
# Combinations of rhs
for (op, s) in zip([:+, :-], (1, -1))
for T1 in [judiRHS, LazyAdd]
for T2 in [judiRHS, LazyAdd]
@eval function $(op)(r1::$(T1){D}, r2::$(T2){D}) where D
r1.nsrc == r2.nsrc || throw(ArgumentError("Incompatible number of source experiment"))
LazyAdd{D}(r1.nsrc, r1, r2, $s)
end
end
end
end
function *(M::Matrix{T}, P::judiProjection{T}) where T
@assert size(M, 2) == get_nsrc(P)
g = super_shot_geometry(P.geometry)
geom = Geometry(g.xloc[1], g.yloc[1], g.zloc[1]; dt=g.dt[1], t=g.t[1], nsrc=size(M, 1))
return judiProjection(geom)
end
*(M::Matrix{T}, P::jAdjoint{judiProjection{T}}) where T = jAdjoint(M*P.op)
*(M::Matrix{T}, R::judiRHS{T}) where T = judiRHS{T}(size(M, 1), M*R.P, M*R.d)
############################################################################################################################
# Comparison
==(jA1::jAdjoint, jA2::jAdjoint) = jA1.op == jA2.op
==(P1::judiProjection, P2::judiProjection) = P1.data == P2.data
==(P1::judiWavelet, P2::judiWavelet) = (P1.wavelet == P2.wavelet && P1.dt == P2.dt)
############################################################################################################################
###### Inpout processing for propagation
function make_src(q::judiMultiSourceVector, P::judiProjection{D}) where D
P.data[1] ≈ q.geometry[1] || throw(ArgumentError("Incompatible geometry and source"))
return P.data[1], make_input(q)
end
make_src(q, P::judiProjection{D}) where D = (P.data[1], reshape(make_input(q), P.data.nt[1], P.data.nrec[1]))
make_src(q, P::judiLRWF{D}) where D = (make_input(q), P.data[1])
make_src(rhs::judiWavelet) = make_src(rhs.d, rhs.P)
make_src(q, P::jAdjoint{<:judiNoopOperator}) = make_src(q, P.op)
get_nsrc(P::Projection) = P.m[:src]
get_nsrc(P::jAdjoint{<:Projection}) = P.op.m[:src]
get_nt(P::Projection) = P.n[:time]
get_nt(P::jAdjoint{<:Projection}) = P.op.n[:time]
"""
reshape(x, P::judiProjection, m::AbstractModel; with_batch=false)
reshape the input `x` into an ML friendly format `HWCB` using the projection operator and model to infer dimensions sizes.
"""
function reshape(x::Vector{T}, P::judiProjection{T}, ::AbstractModel; with_batch=false) where T
out = reshape(x, P.geometry)
out = with_batch ? reshape(out, size(out, 1), size(out, 2), 1, size(out, 3)) : out
return out
end
function reshape(x::Vector{T}, P::judiWavelet{T}, m::AbstractModel; with_batch=false) where T
out = with_batch ? reshape(x, m.n..., 1,get_nsrc(P)) : reshape(x, m.n..., get_nsrc(P))
return out
end
function _as_src(P::judiLRWF{T}, model::AbstractModel, q::Array{T}) where T
qcell = process_input_data(q, model, get_nsrc(P))
return judiWeights{T}(get_nsrc(P), qcell)
end
function _as_src(P::judiProjection{T}, ::AbstractModel, q::Array{T}) where T
qcell = process_input_data(q, P.geometry)
return judiVector{T, Matrix{T}}(get_nsrc(P), P.geometry, qcell)
end
_as_src(::judiNoopOperator, ::AbstractModel, q::judiMultiSourceVector) = q
############################################################################################################################
###### Evaluate lazy operation
eval(rhs::judiRHS) = rhs.d
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 14595 | export judiModeling, judiDataModeling, judiDataSourceModeling, judiPointSourceModeling, judiJacobian
const adjoint_map = Dict(:forward => :adjoint, :adjoint => :forward, :born => :adjoint_born, :adjoint_born => :born)
# Base abstract types
abstract type judiPropagator{D, O} <: joAbstractLinearOperator{D, D} end
abstract type judiComposedPropagator{D, O} <: judiPropagator{D, O} end
abstract type judiAbstractJacobian{D, O, FT} <: judiComposedPropagator{D, O} end
############################################################################################################################
# Concrete types
struct judiModeling{D, O, MT} <: judiPropagator{D, O}
m::AbstractSize
n::AbstractSize
model::MT
options::JUDIOptions
end
struct judiPointSourceModeling{D, O} <: judiComposedPropagator{D, O}
m::AbstractSize
n::AbstractSize
F::judiModeling{D, O}
qInjection::AdjointProjection{D}
function judiPointSourceModeling{D, O}(F::judiModeling{D, O}, qInjection::AdjointProjection{D}) where {D, O}
# instantiate un-initialized sizes
ts = time_space_src(get_nsrc(qInjection), get_nt(qInjection), size(F.model))
merge!(F.n, ts)
merge!(F.m, ts)
update_size(qInjection, F)
new(F.m, qInjection.n, F, qInjection)
end
end
struct judiDataModeling{D, O} <: judiComposedPropagator{D, O}
m::AbstractSize
n::AbstractSize
rInterpolation::Projection{D}
F::judiModeling{D, O}
function judiDataModeling{D, O}(rInterpolation::Projection{D}, F::judiModeling{D, O}) where {D, O}
ts = time_space_src(get_nsrc(rInterpolation), get_nt(rInterpolation), size(F.model))
merge!(F.n, ts)
merge!(F.m, ts)
update_size(rInterpolation, F)
new(rInterpolation.m, F.n, rInterpolation, F)
end
end
struct judiDataSourceModeling{D, O} <: judiComposedPropagator{D, O}
m::AbstractSize
n::AbstractSize
rInterpolation::Projection{D}
F::judiModeling{D, O}
qInjection::AdjointProjection{D}
function judiDataSourceModeling{D, O}(rInterpolation::Projection{D}, F::judiModeling{D, O}, qInjection::AdjointProjection{D}) where {D, O}
ts = time_space_src(get_nsrc(rInterpolation), get_nt(rInterpolation), size(F.model))
merge!(F.n, ts)
merge!(F.m, ts)
update_size(rInterpolation, F)
update_size(qInjection, F)
new(rInterpolation.m, qInjection.n, rInterpolation, F, qInjection)
end
end
struct judiJacobian{D, O, FT} <: judiAbstractJacobian{D, O, FT}
m::AbstractSize
n::AbstractSize
F::FT
q::judiMultiSourceVector
end
struct LazyScal
s::Number
P::judiPropagator
end
############################################################################################################################
# Base and JOLI compat
_get_property(::judiPropagator{T, O}, ::Val{:mode}) where {T, O} = O
_get_property(J::judiPropagator, ::Val{:fop}) = x -> J*x
_get_property(J::judiPropagator, ::Val{:fop_T}) = x -> J'*x
_get_property(J::judiPropagator, ::Val{:name}) = "$(typeof(J))"
_get_property(J::judiAbstractJacobian, ::Val{:rInterpolation}) = J.F.rInterpolation
_get_property(J::judiAbstractJacobian, ::Val{:qInjection}) = J.F.qInjection
_get_property(J::judiPropagator, ::Val{s}) where {s} = getfield(J, s)
_get_property(C::judiComposedPropagator, ::Val{:model}) = C.F.model
_get_property(C::judiComposedPropagator, ::Val{:options}) = C.F.options
getproperty(J::judiPropagator, s::Symbol) = _get_property(J, Val{s}())
display(P::judiPropagator{D, O}) where {D, O} = println("JUDI $(String(O)){$D} propagator $(repr(P.n)) -> $(repr(P.m))")
show(io::Union{IOBuffer, IOContext}, P::judiPropagator{D, O}) where {D, O} = print(io, "JUDI $(String(O)){$D} propagator $(repr(P.n)) -> $(repr(P.m))")
############################################################################################################################
# Constructors
"""
judiModeling(model; options=Options())
judiModeling(model, src_geometry, rec_geometry; options=Options())
Create seismic modeling operator for a velocity model given as a `Model` structure.
The function also takes the source and receiver geometries
as additional input arguments, which creates a combined operator `judiProjection*judiModeling*judiProjection'`.
Example
=======
`Pr` and `Ps` are projection operatos of type `judiProjection` and
`q` is a data vector of type `judiVector`:
F = judiModeling(model)
dobs = Pr*F*Ps'*q
F = judiModeling(model, q.geometry, rec_geometry)
dobs = F*q
"""
function judiModeling(model::MT; options=Options()) where {MT<:AbstractModel}
D = eltype(model)
m = time_space(size(model))
return judiModeling{D, :forward, MT}(m, m, model, options)
end
judiModeling(model::MT, src_geom::Geometry, rec_geom::Geometry; options=Options()) where {MT<:AbstractModel} =
judiProjection(rec_geom) * judiModeling(model; options=options) * adjoint(judiProjection(src_geom))
"""
judiJacobian(F,q)
Create a linearized modeling operator from the non-linear modeling operator `F` and
the source `q`. `q` can be either a judiVector (point source Jacobian) or a `judiWeight` for
extended source modeling.
`F` is a full modeling operator including source/receiver projections.
Examples
========
1) `F` is a modeling operator without source/receiver projections:
J = judiJacobian(Pr*F*Ps',q)
2) `F` is the combined operator `Pr*F*Ps'`:
J = judiJacobian(F,q)
"""
function judiJacobian(F::judiComposedPropagator{D, O}, q::judiMultiSourceVector; options=nothing) where {D, O}
update!(F.F.options, options)
return judiJacobian{D, :born, typeof(F)}(F.m, space(size(F.model)), F, q)
end
# Backward compat with giving weights as array. Not recommened
function judiJacobian(F::judiComposedPropagator{D, O}, q::Array{D, N}; options=nothing) where {D, O, N}
update!(F.F.options, options)
q = _as_src(F.qInjection.op, F.model, q)
return judiJacobian(F, q)
end
############################################################################################################################
# Linear algebra (conj/adj/...)
# Adjoints
conj(F::judiPropagator) = F
transpose(F::judiPropagator) = adjoint(F)
adjoint(s::Symbol) = adjoint_map[s]
adjoint(F::judiModeling{D, O, MT}) where {D, O, MT} = judiModeling{D, adjoint(O), MT}(F.n, F.m, F.model, F.options)
adjoint(F::judiDataModeling{D, O}) where {D, O} = judiPointSourceModeling{D, adjoint(O)}(adjoint(F.F), adjoint(F.rInterpolation))
adjoint(F::judiPointSourceModeling{D, O}) where {D, O}= judiDataModeling{D, adjoint(O)}(adjoint(F.qInjection), adjoint(F.F))
adjoint(F::judiDataSourceModeling{D, O}) where {D, O} = judiDataSourceModeling{D, adjoint(O)}(adjoint(F.qInjection), adjoint(F.F), adjoint(F.rInterpolation))
adjoint(J::judiJacobian{D, O, FT}) where {D, O, FT} = judiJacobian{D, adjoint(O), FT}(J.n, J.m, J.F, J.q)
adjoint(L::LazyScal) = LazyScal(L.s, adjoint(L.P))
# Composition
*(F::judiModeling{D, O}, P::AdjointProjection{D}) where {D, O} = judiPointSourceModeling{D, O}(F, P)
*(P::Projection{D}, F::judiModeling{D, O}) where {D, O} = judiDataModeling{D, O}(P, F)
*(P::Projection{D}, F::judiPointSourceModeling{D, O}) where {D, O} = judiDataSourceModeling{D, O}(P, F.F, F.qInjection)
*(F::judiDataModeling{D, O}, P::AdjointProjection{D}) where {D, O} = judiDataSourceModeling{D, O}(F.rInterpolation, F.F, P)
*(s::Number, P::judiPropagator) = LazyScal(s, P)
\(P::judiPropagator, s::Number) = LazyScal(1/s, P)
*(L::LazyScal, x::SourceType{T}) where {T<:Number} = L.s * (L.P * x)
*(L::LazyScal, x::Array{T, N}) where {T<:Number, N} = L.s * (L.P * x)
# Propagation via linear algebra `*`
*(F::judiPropagator{T, O}, q::judiMultiSourceVector{T}) where {T<:Number, O} = multi_src_propagate(F, q)
*(F::judiPropagator{T, O}, q::AbstractVector{T}) where {T<:Number, O} = multi_src_propagate(F, q)
*(F::judiPropagator{T, O}, q::DenseArray{T}) where {T<:Number, O} = multi_src_propagate(F, q)
*(F::judiAbstractJacobian{T, O, FT}, q::dmType{Tq}) where {T<:Number, Tq<:Pdtypes, O, FT} = multi_src_propagate(F, q)
mul!(out::SourceType{T}, F::judiPropagator{T, O}, q::SourceType{T}) where {T<:Number, O} = begin y = F*q; copyto!(out, y) end
mul!(out::SourceType{T}, F::judiAbstractJacobian{T, :born, FT}, q::Vector{T}) where {T<:Number, FT} = begin y = F*q[:]; copyto!(out, y) end
mul!(out::SourceType{T}, F::judiAbstractJacobian{T, :born, FT}, q::Array{T, 2}) where {T<:Number, FT} = begin y = F*q[:]; copyto!(out, y) end
mul!(out::SourceType{T}, F::judiAbstractJacobian{T, :born, FT}, q::Array{T, 3}) where {T<:Number, FT} = begin y = F*q[:]; copyto!(out, y) end
mul!(out::SourceType{T1}, F::Union{joLinearFunction{T2, T1}, joLinearOperator{T2, T1}}, q::SourceType{T2}) where {T1<:Number, T2<:Number} = begin y = F*q; copyto!(out, y) end
mul!(out::SourceType{T1}, F::Union{joLinearFunction{T2, T1}, joLinearOperator{T2, T1}}, q::Array{T2, 2}) where {T1<:Number, T2<:Number} = begin y = F*q[:]; copyto!(out, y) end
mul!(out::SourceType{T1}, F::Union{joLinearFunction{T2, T1}, joLinearOperator{T2, T1}}, q::Array{T2, 3}) where {T1<:Number, T2<:Number} = begin y = F*q[:]; copyto!(out, y) end
mul!(out::Array{T, 2}, F::judiAbstractJacobian{T, :adjoint_born, FT}, q::SourceType{T}) where {T<:Number, FT} = begin y = F*q; copyto!(out, y) end
mul!(out::Array{T, 3}, F::judiAbstractJacobian{T, :adjoint_born, FT}, q::SourceType{T}) where {T<:Number, FT} = begin y = F*q; copyto!(out, y) end
############################################################################################################################
# Propagation input
process_input_data(::judiPropagator{T}, data::judiMultiSourceVector{T}) where T = data
process_input_data(F::judiModeling, q::DenseArray) = process_input_data(q, F.model)
process_input_data(F::judiPointSourceModeling, q::DenseArray) = process_input_data(q, F.qInjection.geometry)
process_input_data(F::judiDataSourceModeling, q::DenseArray) = process_input_data(q, F.qInjection.data)
process_input_data(F::judiDataModeling, q::DenseArray) = process_input_data(q, F.model)
process_input_data(J::judiJacobian{D, :adjoint_born, FT}, q::DenseArray) where {D, FT} = process_input_data(q, J.F.rInterpolation.data)
process_input_data(::judiJacobian{D, :born, FT}, q::dmType{D}) where {D<:Number, FT} = q
process_input_data(J::judiJacobian{D, :born, FT}, q::DenseArray) where {D<:Number, FT} = PhysicalParameter(J.model.m, q)
make_input(::judiModeling, q::SourceType) = (nothing, make_input(q), nothing, nothing, nothing)
make_input(::judiModeling, rhs::judiRHS) = (make_src(rhs)..., nothing, nothing, nothing)
make_input(F::judiPointSourceModeling, q::SourceType{T}) where {T} = (make_src(q, F.qInjection)..., nothing, nothing, nothing)
make_input(F::judiPointSourceModeling, q::Matrix{T}) where {T} = (F.qInjection.data[1], q, nothing, nothing, nothing)
make_input(F::judiDataModeling, q::SourceType{T}) where {T} = (nothing, make_input(q), F.rInterpolation.geometry, nothing, nothing)
make_input(F::judiDataModeling{T, O}, q::LazyAdd{T}) where {T, O} = (make_src(q)..., F.rInterpolation.geometry, nothing, nothing)
make_input(F::judiDataModeling, rhs::judiRHS) = (make_src(rhs)..., F.rInterpolation.geometry, nothing, nothing)
make_input(F::judiDataSourceModeling, q::SourceType{T}) where {T} = (make_src(q, F.qInjection)..., F.rInterpolation.data[1], nothing, nothing)
make_input(F::judiDataSourceModeling, q::Matrix{T}) where {T} = (F.qInjection.data[1], q, F.rInterpolation.data[1], nothing, nothing)
function make_input(J::judiJacobian{D, :born, FT}, q::dmType{Dq}) where {D<:Number, Dq<:Pdtypes, FT}
srcGeom, srcData = make_src(J.q, J.F.qInjection)
return srcGeom, srcData, J.F.rInterpolation.data[1], nothing, reshape(q, size(J.model))
end
function make_input(J::judiJacobian{D, :adjoint_born, FT}, q::SourceType{D}) where {D, FT}
srcGeom, srcData = make_src(J.q, J.F.qInjection)
recGeom, recData = make_src(q, J.F.rInterpolation)
return srcGeom, srcData, recGeom, recData, nothing
end
############################################################################################################################
# Size update based on linear operator
update_size(w::judiProjection, F::judiPropagator) = set_space_size!(w.n, size(F.model))
update_size(w::jAdjoint{<:judiProjection}, F::judiPropagator) = set_space_size!(w.op.n, size(F.model))
update_size(w::judiWavelet, F::judiPropagator) = set_space_size!(w.m, size(F.model))
update_size(w::jAdjoint{<:judiWavelet}, F::judiPropagator) = set_space_size!(w.op.m, size(F.model))
############################################################################################################################
# indexing
getindex(F::judiModeling{D, O, MT}, i) where {D, O, MT} = judiModeling{D, O, MT}(F.m[i], F.n[i], F.model, F.options[i])
getindex(F::judiDataModeling{D, O}, i) where {D, O} = judiDataModeling{D, O}(F.rInterpolation[i], F.F[i])
getindex(F::judiPointSourceModeling{D, O}, i) where {D, O}= judiPointSourceModeling{D, O}(F.F[i], F.qInjection[i])
getindex(F::judiDataSourceModeling{D, O}, i) where {D, O} = judiDataSourceModeling{D, O}(F.rInterpolation[i], F.F[i], F.qInjection[i])
getindex(J::judiJacobian{D, O, FT}, i) where {D, O, FT} = judiJacobian{D, O, FT}(J.m[i], J.n[i], J.F[i], J.q[i])
# SimSource
*(M::Matrix{T}, F::judiPointSourceModeling{D, O}) where {T, D, O} = judiPointSourceModeling{D, O}(F.F, M*F.qInjection)
*(M::Matrix{T}, F::judiDataModeling{D, O}) where {T, D, O} = judiDataModeling{D, O}(M*F.rInterpolation, F.F)
*(M::Matrix{T}, F::judiDataSourceModeling{D, O}) where {T, D, O} = judiDataSourceModeling{D, O}(M*F.rInterpolation, F.F, M*F.qInjection)
*(M::Matrix{T}, J::judiJacobian{D, O, FT}) where {T, D, O, FT} = judiJacobian(M*J.F, M*J.q)
############################################################################################################################
# Comparisons
isequal(P1::judiPropagator, P2::judiPropagator) = P1 == P2
==(F1::judiModeling{D, O1}, F2::judiModeling{D, O2}) where {D, O1, O2} = (O1 == O2 && F1.model == F2.model && F1.options == F2.options)
==(F1::judiDataModeling, F2::judiDataModeling) = (F1.F == F2.F && F1.rInterpolation == F2.rInterpolation)
==(F1::judiPointSourceModeling, F2::judiPointSourceModeling) = (F1.F == F2.F && F1.qInjection == F2.qInjection)
==(F1::judiDataSourceModeling, F2::judiDataSourceModeling) = (F1.F == F2.F && F1.qInjection == F2.qInjection && F1.rInterpolation == F2.rInterpolation)
==(F1::judiJacobian{D, O1, FT1}, F2::judiJacobian{D, O2, FT2}) where {D, O1, O2, FT1, FT2} = (O1 == O2 && FT1 == FT2 && F1.F == F2.F && F1.q == F2.q)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2605 | """
single_reduce!(x, y)
Inplace reduction of y into x.
"""
@inline single_reduce!(x::T, y::T) where T = x .+= y
for T in [judiVector, judiWeights, judiWavefield]
@eval @inline single_reduce!(x::$T, y::$T) = begin push!(x, y); x end
end
@inline single_reduce!(x::Ref, y::Ref) = begin x[] += y[]; x end
@inline function single_reduce!(x::Tuple, y::Tuple)
nx = length(x)
ny = length(y)
(nx == ny) || throw(ArgumentError("Incompatible lengths ($nx, $ny)"))
for (xi, yi) in zip(x, y)
single_reduce!(xi, yi)
end
x
end
"""
local_reduce!(future, other)
Reduce `other` future into local `future`. This is perform remotely on the julia worker
`future.where`.
"""
function local_reduce!(my_future::_TFuture, other_future::_TFuture)
y = remotecall_fetch(fetch, other_future.where, other_future)
x = fetch(my_future)
single_reduce!(x, y)
y = []
nothing
end
"""
reduce_level!(futures, nleaf)
Reduce one level of the reduction tree consisting of `nleaf` futures. Each `leaf`
reduces into itself `futures[i]`.
"""
function reduce_level!(futures::Vector{_TFuture}, nleaf::Int)
nleaf == 0 && return
@sync for i = 1:2:2*nleaf
@async remotecall_wait(local_reduce!, futures[i].where, futures[i], futures[i+1])
end
deleteat!(futures, 2:2:2*nleaf)
end
"""
reduce!(x)
binary-tree reduction of a Vector of Futures `x`
Adapted from `DistributedOperations.jl` (MIT license). Striped from custom types in it and extended to multiple outputs
with different reduction functions.
"""
function reduce!(futures::Vector{_TFuture})
isnothing(_worker_pool()) && return reduce_all_workers!(futures)
# Number of parallel workers
nwork = nworkers(_worker_pool())
nf = length(futures)
# Reduction batch. We want to avoid finished task to hang waiting for the
# binary tree reduction to reach their index holding memory.
bsize = min(nwork, nf)
# First batch
res = reduce_all_workers!(futures[1:bsize])
# Loop until all reduced
for i = bsize+1:bsize:nf
last = min(nf, i + bsize - 1)
single_reduce!(res, reduce_all_workers!(futures[i:last]))
end
return res
end
function reduce_all_workers!(futures::Vector{_TFuture})
# Get length a next power of two for binary reduction
M = length(futures)
L = round(Int, log2(prevpow(2,M)))
m = 2^L
# remainder
R = M - m
# Reduce the remainder
reduce_level!(futures, R)
# Binary tree reduction
for l = L:-1:1
reduce_level!(futures, 2^(l-1))
end
fetch(futures[myid()])
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 744 | export mse, studentst
"""
mse(x, y)
Mean square error
`5f0 * norm(x - y, 2)^2`
and its derivative w.r.t `x`
`x-y`
"""
function mse(x::Matrix{T}, y::Matrix{T}) where {T<:Number}
f = .5f0 * norm(x - y, 2)^2
r = x - y
return f::T, r::Matrix{T}
end
_studentst_loss(x::T, y::T, k::T) where {T<:Number} = T(1/2) * (k + 1) * log(1 + (x-y)^2 / k)
"""
studentst(x, y)
Student's T misfit
`.5 * (k+1) * log(1 + (x-y)^2 / k)`
and its derivative w.r.t x
`(k + 1) * (x - y) / (k + (x - y)^2)`
"""
function studentst(x::Matrix{T}, y::Matrix{T}; k=T(2)) where {T<:Number}
k = convert(T, k)
f = sum(_studentst_loss.(x, y, k))
r = (k + 1) .* (x - y) ./ (k .+ (x - y).^2)
return f::T, r::Matrix{T}
end | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 8798 |
export fwi_objective, lsrtm_objective, fwi_objective!, lsrtm_objective!
# Type of accepted input
Dtypes = Union{<:judiVector, NTuple{N, <:judiVector} where N, Vector{<:judiVector}, <:LazyMul}
MTypes = Union{<:AbstractModel, NTuple{N, <:AbstractModel} where N, Vector{<:AbstractModel}}
dmTypes = Union{dmType, NTuple{N, dmType} where N, Vector{dmType}}
function _multi_src_fg(model_full::AbstractModel, source::Dtypes, dObs::Dtypes, dm, options::JUDIOptions;
nlind::Bool=false, lin::Bool=false, misfit::Function=mse, illum::Bool=false,
data_precon=nothing, model_precon=LinearAlgebra.I)
GC.gc(true)
devito.clear_cache()
# assert this is for single source LSRTM
@assert source.nsrc == 1 "Multiple sources are used in a single-source fwi_objective"
@assert dObs.nsrc == 1 "Multiple-source data is used in a single-source fwi_objective"
# Load full geometry for out-of-core geometry containers
d_geometry = Geometry(dObs.geometry)
s_geometry = Geometry(source.geometry)
# If model preconditioner is provided, apply it
dm = isnothing(dm) ? dm : model_precon * dm
# Limit model to area with sources/receivers
if options.limit_m == true
@juditime "Limit model to geometry" begin
model = deepcopy(model_full)
model, dm = limit_model_to_receiver_area(s_geometry, d_geometry, model, options.buffer_size; pert=dm)
end
else
model = model_full
end
# Set up Python model
@juditime "Devito Model" begin
modelPy = devito_model(model, options, dm)
dtComp = convert(Float32, modelPy."critical_dt")
end
# Extrapolate input data to computational grid
qIn = time_resample(make_input(source), s_geometry, dtComp)
dObserved = time_resample(make_input(dObs), d_geometry, dtComp)
qIn, dObserved = _maybe_pad_t0(qIn, s_geometry, dObserved, d_geometry, dtComp)
# Set up coordinates
@juditime "Sparse coords setup" begin
src_coords = setup_grid(s_geometry, size(model)) # shifts source coordinates by origin
rec_coords = setup_grid(d_geometry, size(model)) # shifts rec coordinates by origin
end
# Setup misfit function
if !isnothing(data_precon)
# resample
new_t = StepRangeLen(0f0, Float32(dtComp), Int64(size(dObserved, 1)))
Pcomp = time_resample(data_precon, new_t)
runtime_misfit = (x, y) -> misfit(Pcomp*x, Pcomp*y)
else
runtime_misfit = misfit
end
mfunc = pyfunction(runtime_misfit, Matrix{Float32}, Matrix{Float32})
length(options.frequencies) == 0 ? freqs = nothing : freqs = options.frequencies
IT = illum ? (PyArray, PyArray) : (PyObject, PyObject)
@juditime "Python call to J_adjoint" begin
argout = rlock_pycall(ac."J_adjoint", Tuple{Float32, PyArray, IT...}, modelPy,
src_coords, qIn, rec_coords, dObserved, t_sub=options.subsampling_factor,
checkpointing=options.optimal_checkpointing,
freq_list=freqs, ic=options.IC, is_residual=false, born_fwd=lin, nlind=nlind,
dft_sub=options.dft_subsampling_factor[1], f0=options.f0, return_obj=true,
misfit=mfunc, illum=illum)
end
@juditime "Filter empty output" begin
argout = filter_none(argout)
end
@juditime "Remove padding from gradient" begin
grad = PhysicalParameter(remove_padding(argout[2], modelPy.padsizes; true_adjoint=options.sum_padding), spacing(model), origin(model))
end
fval = Ref{Float32}(argout[1])
if illum
@juditime "Process illumination" begin
illumu = PhysicalParameter(remove_padding(argout[3], modelPy.padsizes; true_adjoint=false), spacing(model), origin(model))
illumv = PhysicalParameter(remove_padding(argout[4], modelPy.padsizes; true_adjoint=false), spacing(model), origin(model))
end
return fval, grad, illumu, illumv
end
return fval, grad
end
multi_src_fg = retry(_multi_src_fg)
# Find number of experiments
"""
get_nexp(x)
Get number of experiments given a JUDI type. By default we have only one experiment unless we input
a Vector of judiType such as [model, model] to compute gradient for different cases at once.
"""
get_nexp(x) = 1
for T in [judiVector, AbstractModel, judiWeights, judiWavefield, PhysicalParameter, Vector{Float32}]
@eval get_nexp(v::Vector{<:$T}) = length(v)
@eval get_nexp(v::Tuple{N, <:$T}) where N = length(v)
end
# Filter arguments for given task
"""
get_exp(x, i)
Filter input `x`` for experiment number `i`. Returns `x` is a constant not depending on experiment.
"""
get_exp(x, i) = x
get_exp(x::Tuple{}, i::Any) = x[i]
for T in [judiVector, AbstractModel, judiWeights, judiWavefield, Array{Float32}, PhysicalParameter]
@eval get_exp(v::Vector{<:$T}, i) = v[i]
@eval get_exp(v::NTuple{N, <:$T}, i) where N = v[i]
end
function check_args(args...)
n = [get_nexp(a) for a in args]
nexp = maximum(n)
check = all(ni -> (ni==nexp || ni==1), n)
check || throw(ArgumentError("Incompatible number of experiements"))
return nexp
end
################################################################################################
####################### User Interface #########################################################
################################################################################################
"""
fwi_objective(model, source, dobs; options=Options())
Evaluate the full-waveform-inversion (reduced state) objective function. Returns a tuple with function value and vectorized \\
gradient. `model` is a `Model` structure with the current velocity model and `source` and `dobs` are the wavelets and \\
observed data of type `judiVector`.
Example
=======
function_value, gradient = fwi_objective(model, source, dobs)
"""
function fwi_objective(model::MTypes, q::Dtypes, dobs::Dtypes; options=Options(), kw...)
n_exp = check_args(model, q, dobs)
G = n_exp == 1 ? similar(model.m, model) : [similar(get_exp(model, i).m, get_exp(model, i)) for i=1:n_exp]
f = fwi_objective!(G, model, q, dobs; options=options, kw...)
f, G
end
"""
lsrtm_objective(model, source, dobs, dm; options=Options(), nlind=false)
Evaluate the least-square migration objective function. Returns a tuple with function value and \\
gradient. `model` is a `Model` structure with the current velocity model and `source` and `dobs` are the wavelets and \\
observed data of type `judiVector`.
Example
=======
function_value, gradient = lsrtm_objective(model, source, dobs, dm)
"""
function lsrtm_objective(model::MTypes, q::Dtypes, dobs::Dtypes, dm::dmTypes; options=Options(), nlind=false, kw...)
n_exp = check_args(model, q, dobs, dm)
G = n_exp == 1 ? similar(model.m, model) : [similar(get_exp(model, i).m, get_exp(model, i)) for i=1:n_exp]
f = lsrtm_objective!(G, model, q, dobs, dm; options=options, nlind=nlind, kw...)
f, G
end
"""
fwi_objective!(G, model, source, dobs; options=Options())
Evaluate the full-waveform-inversion (reduced state) objective function. Returns a the function value and assigns in-place \\
the gradient to G. `model` is a `Model` structure with the current velocity model and `source` and `dobs` are the wavelets and \\
observed data of type `judiVector`.
Example
=======
function_value = fwi_objective!(gradient, model, source, dobs)
"""
function fwi_objective!(G, model::MTypes, q::Dtypes, dobs::Dtypes; options=Options(), kw...)
n_exp = check_args(G, model, dobs, q)
return multi_exp_fg!(Val(n_exp), G, model, q, dobs, nothing; options=options, nlind=false, lin=false, kw...)
end
"""
lsrtm_objective!(G, model, source, dobs, dm; options=Options(), nlind=false)
Evaluate the least-square migration (data-space) objective function. Returns the function value and assigns in-place \\
the gradient to G. `model` is a `Model` structure with the current velocity model and `source` and `dobs` are the wavelets and \\
observed data of type `judiVector`.
Example
=======
function_value = lsrtm_objective!(gradient, model, source, dobs, dm; options=Options(), nlind=false)
"""
function lsrtm_objective!(G, model::MTypes, q::Dtypes, dobs::Dtypes, dm::dmTypes; options=Options(), nlind=false, kw...)
n_exp = check_args(G, model, q, dobs, dm)
return multi_exp_fg!(Val(n_exp), G, model, q, dobs, dm; options=options, nlind=nlind, lin=true, kw...)
end
multi_exp_fg!(n::Val{1}, ar...; kw...) = multi_src_fg!(ar...; kw...)
function multi_exp_fg!(n::Val{N}, ar...; kw...) where N
f = zeros(Float32, N)
@sync for i=1:N
ai = (get_exp(a, i) for a in ar)
@async f[i] = multi_src_fg!(ai...; kw...)
end
sum(f)
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 4935 | """
propagate(F::judiPropagator{T, mode}, q)
Base propagation interfaces that calls the devito `mode` propagator (forward/adjoint/..)
with `q` as a source. The return type is infered from `F`.
"""
function propagate(F::judiPropagator{T, O}, q::AbstractArray{Tq}, illum::Bool) where {T, Tq, O}
srcGeometry, srcData, recGeometry, recData, dm = make_input(F, q)
return time_modeling(F.model, srcGeometry, srcData, recGeometry, recData, dm, O, F.options, _prop_fw(F), illum)
end
propagate(t::Tuple{judiPropagator, AbstractArray}) = propagate(t[1], t[2], compute_illum(t[1].model, t[1].mode))
propagate(F::judiPropagator{T, O}, q::AbstractArray{T}) where {T, O} = propagate(F, q, compute_illum(F.model, O))
"""
run_and_reduce(func, pool, nsrc, arg_func)
Runs the function `func` for indices `1:nsrc` within arguments `func(arg_func(i))`. If the
the pool is empty, a standard loop and accumulation is ran. If the pool is a julia WorkerPool or
any custom Distributed pool, the loop is distributed via `remotecall` followed by are binary tree remote reduction.
"""
function run_and_reduce(func, pool, nsrc, arg_func::Function; kw=nothing)
# Run distributed loop
res = Vector{_TFuture}(undef, nsrc)
for i = 1:nsrc
args_loc = arg_func(i)
kw_loc = isnothing(kw) ? Dict() : kw(i)
res[i] = remotecall(func, pool, args_loc...; kw_loc...)
end
res = reduce!(res)
return res
end
function run_and_reduce(func, ::Nothing, nsrc, arg_func::Function; kw=nothing)
@juditime "Running $(func) for first src" begin
kw_loc = isnothing(kw) ? Dict() : kw(1)
out = func(arg_func(1)...; kw_loc...)
end
for i=2:nsrc
@juditime "Running $(func) for src $(i)" begin
kw_loc = isnothing(kw) ? Dict() : kw(i)
next = func(arg_func(i)...; kw_loc...)
end
@juditime "Reducting $(func) for src $(i)" begin
single_reduce!(out, next)
end
end
out
end
_prop_fw(::judiPropagator{T, O}) where {T, O} = true
_prop_fw(::judiPropagator{T, :adjoint}) where T = false
_prop_fw(J::judiJacobian) = _prop_fw(J.F)
src_i(::judiAbstractJacobian{T, :born, FT}, q::dmType{Tq}, ::Integer) where {T<:Number, Tq<:Pdtypes, FT} = q
src_i(::judiPropagator{T, O}, q::judiMultiSourceVector{T}, i::Integer) where {T, O} = q[i]
src_i(::judiPropagator{T, O}, q::Vector{<:Array{T}}, i::Integer) where {T, O} = q[i]
get_nsrc(::judiPropagator, q::judiMultiSourceVector) = q.nsrc
get_nsrc(::judiPropagator, q::Vector{<:Array}) = length(q)
get_nsrc(J::judiAbstractJacobian, ::dmType{T}) where T<:Number = J.q.nsrc
"""
multi_src_propagate(F::judiPropagator{T, O}, q::AbstractVector)
Propagates the source `q` with the `F` propagator. The return type is infered from `F` and the
propagation kernel is defined by `O` (forward, adjoint, born or adjoint_born).
"""
function multi_src_propagate(F::judiPropagator{T, O}, q::AbstractArray{Tq}) where {T<:Number, Tq<:Pdtypes, O}
q = process_input_data(F, q)
# Number of sources and init result
nsrc = get_nsrc(F, q)
pool = _worker_pool()
illum = compute_illum(F.model, O)
arg_func = i -> (F[i], src_i(F, q, i), illum)
# Distribute source
res = run_and_reduce(propagate, pool, nsrc, arg_func)
res = update_illum(res, F)
res = _project_to_physical_domain(res, F.model)
res = as_vec(res, Val(F.options.return_array))
return res
end
"""
multi_src_fg!(G, model, q, dobs, dm; options=Options(), nlind=false, lin=false)
This is the main multi-source wrapper function for `fwi_objective` and `lsrtm_objective`.
Computes the misifit and gradient (LSRTM if `lin` else FWI) for the given `q` source and `dobs` and
perturbation `dm`.
"""
function multi_src_fg!(G, model, q, dobs, dm; options=Options(), ms_func=multi_src_fg, kw...)
# Number of sources and init result
nsrc = try q.nsrc catch; dobs.nsrc end
pool = _worker_pool()
illum = compute_illum(model, :adjoint_born)
# Distribute source
arg_func = i -> (model, q[i], dobs[i], dm, options[i])
kw_func = i -> Dict(:illum=> illum, Dict(k => kw_i(v, i) for (k, v) in kw)...)
# Distribute source
res = run_and_reduce(ms_func, pool, nsrc, arg_func; kw=kw_func)
res = update_illum(res, model, :adjoint_born)
f, g = as_vec(res, Val(options.return_array))
G .+= g
return f
end
kw_i(b::Bool, ::Integer) = b
kw_i(f::Function, ::Integer) = f
kw_i(msv::judiMultiSourceVector, i::Integer) = msv[i]
kw_i(P::DataPreconditioner, i::Integer) = P[i]
kw_i(P::ModelPreconditioner, ::Integer) = P
kw_i(P::MultiPreconditioner{TP, T}, i::Integer) where {TP, T} = MultiPreconditioner{TP, T}([kw_i(Pi, i) for Pi in P.precs])
kw_i(t::Tuple, i::Integer) = tuple(kw_i(ti, i) for ti in t)
kw_i(d::Vector{<:Preconditioner}, i::Integer) = foldr(*, [kw_i(di, i) for di in d])
kw_i(d::Tuple{Vararg{<:Preconditioner}}, i::Integer) = foldr(*, [kw_i(di, i) for di in d])
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 10016 | export devito_interface
########################################### Logging utility ########################################################
_op_str(fw::Bool) = fw ? "F" : "F'"
########################################## Python pycall wrappers with lock #########################################
_outtype(::Nothing, ::Integer, type) = type
function _outtype(b::Bool, n::Integer, type)
T = b ? PyArray : PyObject
IT = n==1 ? (T,) : (T, T)
return Tuple{type, IT...}
end
function wrapcall_data(func, args...;kw...)
rtype = _outtype(get(kw, :illum, nothing), 1, PyArray)
out = rlock_pycall(func, rtype, args...;kw...)
tup = isa(out, Tuple)
# The returned array `out` is a Python Row-Major array with dimension (time, rec).
# Unlike standard array we want to keep this ordering in julia (time first) so we need to
# make a wrapper around the pointer, to flip the dimension the re-permute the dimensions.
shot = tup ? out[1] : out
shot = permutedims(unsafe_wrap(Array, shot.data, reverse(size(shot))), length(size(shot)):-1:1)
# Check what to return
out = tup ? (shot, out[2]) : shot
return out
end
function wrapcall_weights(func, args...;kw...)
rtype = _outtype(get(kw, :illum, nothing), 1, PyArray)
out = rlock_pycall(func, rtype, args...;kw...)
return out
end
function wrapcall_wf(func, args...;kw...)
rtype = _outtype(get(kw, :illum, nothing), 1, Array{Float32})
out = rlock_pycall(func, rtype, args...;kw...)
return out
end
function wrapcall_grad(func, args...;kw...)
rtype = _outtype(get(kw, :illum, nothing), 2, PyArray)
out = rlock_pycall(func, rtype, args...;kw...)
return out
end
# legacy
wrapcall_function = wrapcall_grad
# d_obs = Pr*F*Ps'*q
function devito_interface(modelPy::PyObject, srcGeometry::Geometry, srcData::Array, recGeometry::Geometry, recData::Nothing, dm::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("Pr*$(_op_str(fw))*Ps'*q")
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
qIn = time_resample(srcData, srcGeometry, dtComp)
qIn = _maybe_pad_t0(qIn, srcGeometry, recGeometry, dtComp)
# Set up coordinates with devito dimensions
src_coords = setup_grid(srcGeometry, modelPy.shape)
rec_coords = setup_grid(recGeometry, modelPy.shape)
# Devito call
return wrapcall_data(ac."forward_rec", modelPy, src_coords, qIn, rec_coords, fw=fw, f0=options.f0, illum=illum)
end
# u = F*Ps'*q
function devito_interface(modelPy::PyObject, srcGeometry::Geometry, srcData::Array, recGeometry::Nothing, recData::Nothing, dm::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("$(_op_str(fw))*Ps'*q")
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
qIn = time_resample(srcData, srcGeometry, dtComp)
# Set up coordinates with devito dimensions
src_coords = setup_grid(srcGeometry, modelPy.shape)
# Devito call
return wrapcall_wf(ac."forward_no_rec", modelPy, src_coords, qIn, fw=fw, illum=illum)
end
# d_obs = Pr*F*u
function devito_interface(modelPy::PyObject, srcGeometry::Nothing, srcData::Array, recGeometry::Geometry, recData::Nothing, dm::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("Pr*$(_op_str(fw))*u")
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
# Set up coordinates with devito dimensions
rec_coords = setup_grid(recGeometry, modelPy.shape)
# Devito call
return wrapcall_data(ac."forward_wf_src", modelPy, srcData, rec_coords, fw=fw, f0=options.f0, illum=illum)
end
# u_out = F*u_in
function devito_interface(modelPy::PyObject, srcGeometry::Nothing, srcData::Array, recGeometry::Nothing, recData::Nothing, dm::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("$(_op_str(fw))*u_in")
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
# Devito call
return wrapcall_wf(ac."forward_wf_src_norec", modelPy, srcData, fw=fw, illum=illum)
end
# d_lin = J*dm
function devito_interface(modelPy::PyObject, srcGeometry::Geometry, srcData::Array, recGeometry::Geometry,
recData::Nothing, dm::Union{PhysicalParameter, Array}, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("J($(_op_str(fw)), q)*dm")
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
qIn = time_resample(srcData, srcGeometry, dtComp)
qIn = _maybe_pad_t0(qIn, srcGeometry, recGeometry, dtComp)
# Set up coordinates with devito dimensions
#origin = get_origin(modelPy)
src_coords = setup_grid(srcGeometry, modelPy.shape)
rec_coords = setup_grid(recGeometry, modelPy.shape)
# Devito call
return wrapcall_data(ac."born_rec", modelPy, src_coords, qIn, rec_coords, fw=fw,
ic=options.IC, f0=options.f0, illum=illum)
end
# dm = J'*d_lin
function devito_interface(modelPy::PyObject, srcGeometry::Geometry, srcData::Array, recGeometry::Geometry,
recData::Array, dm::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("J($(_op_str(fw)), q)'*d_lin")
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
qIn = time_resample(srcData, srcGeometry, dtComp)
dIn = time_resample(recData, recGeometry, dtComp)
qIn, dIn = _maybe_pad_t0(qIn, srcGeometry, dIn, recGeometry, dtComp)
# Set up coordinates with devito dimensions
src_coords = setup_grid(srcGeometry, modelPy.shape)
rec_coords = setup_grid(recGeometry, modelPy.shape)
length(options.frequencies) == 0 ? freqs = nothing : freqs = options.frequencies
return wrapcall_grad(ac."J_adjoint", modelPy,
src_coords, qIn, rec_coords, dIn, fw=fw, t_sub=options.subsampling_factor,
checkpointing=options.optimal_checkpointing,
freq_list=freqs, ic=options.IC, is_residual=true,
dft_sub=options.dft_subsampling_factor[1], f0=options.f0, illum=illum)
end
######################################################################################################################################################
# d_obs = Pr*F*Pw'*w - modeling w/ extended source
function devito_interface(modelPy::PyObject, weights::Array, srcData::Array, recGeometry::Geometry, recData::Nothing,
dm::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("Pr*$(_op_str(fw))*Pw'*w")
weights = pad_array(reshape(weights, modelPy.shape), modelPy.padsizes; mode=:zeros)
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
qIn = time_resample(srcData, recGeometry, dtComp)
# Set up coordinates with devito dimensions
rec_coords = setup_grid(recGeometry, modelPy.shape)
# Devito call
return wrapcall_data(ac."forward_rec_w", modelPy, weights, qIn, rec_coords,
fw=fw, f0=options.f0, illum=illum)
end
# dw = Pw*F'*Pr'*d_obs - adjoint modeling w/ extended source
function devito_interface(modelPy::PyObject, recGeometry::Geometry, recData::Array, srcData::Array, ::Nothing, ::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("Pw*$(_op_str(fw))*Pr'*d_obs")
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
dIn = time_resample(recData, recGeometry, dtComp)
qIn = time_resample(srcData, recGeometry, dtComp)
qIn, dIn = _maybe_pad_t0(qIn, recGeometry, dIn, recGeometry, dtComp)
# Set up coordinates with devito dimensions
rec_coords = setup_grid(recGeometry, modelPy.shape)
# Devito call
return wrapcall_weights(ac."adjoint_w", modelPy, rec_coords, dIn, qIn,
fw=fw, f0=options.f0, illum=illum)
end
# Jacobian of extended source modeling: d_lin = J*dm
function devito_interface(modelPy::PyObject, weights::Array, srcData::Array, recGeometry::Geometry, recData::Nothing,
dm::Union{PhysicalParameter, Array}, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("Jw($(_op_str(fw)), q)*dm")
weights = pad_array(reshape(weights, modelPy.shape), modelPy.padsizes; mode=:zeros)
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
qIn = time_resample(srcData, recGeometry, dtComp)
# Set up coordinates with devito dimensions
rec_coords = setup_grid(recGeometry, modelPy.shape)
# Devito call
return wrapcall_data(ac."born_rec_w", modelPy, weights, qIn, rec_coords,
fw=fw, ic=options.IC, f0=options.f0, illum=illum)
end
# Adjoint Jacobian of extended source modeling: dm = J'*d_lin
function devito_interface(modelPy::PyObject, weights::Array, srcData::Array, recGeometry::Geometry, recData::Array, dm::Nothing, options::JUDIOptions, illum::Bool, fw::Bool)
judilog("Jw($(_op_str(fw)), q)'*d_lin")
weights = pad_array(reshape(weights, modelPy.shape), modelPy.padsizes; mode=:zeros)
# Interpolate input data to computational grid
dtComp = convert(Float32, modelPy."critical_dt")
qIn = time_resample(srcData, recGeometry, dtComp)
dIn = time_resample(recData, recGeometry, dtComp)
qIn, dIn = _maybe_pad_t0(qIn, recGeometry, dIn, recGeometry, dtComp)
# Set up coordinates with devito dimensions
rec_coords = setup_grid(recGeometry, modelPy.shape)
length(options.frequencies) == 0 ? freqs = nothing : freqs = options.frequencies
return wrapcall_grad(ac."J_adjoint", modelPy,
nothing, qIn, rec_coords, dIn, fw=fw, t_sub=options.subsampling_factor,
checkpointing=options.optimal_checkpointing,
freq_list=freqs, ic=options.IC, ws=weights, is_residual=true,
dft_sub=options.dft_subsampling_factor[1], f0=options.f0, illum=illum)
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 4690 |
export time_modeling
GeomOrNot = Union{Geometry, Array, Nothing}
ArrayOrNot = Union{Array, PyArray, PyObject, Nothing}
PhysOrNot = Union{PhysicalParameter, Array, Nothing}
# Setup time-domain linear or nonlinear foward and adjoint modeling and interface to devito
function _time_modeling(model_full::AbstractModel, srcGeometry::GeomOrNot, srcData::ArrayOrNot,
recGeometry::GeomOrNot, recData::ArrayOrNot, dm::PhysOrNot,
op::Symbol, options::JUDIOptions, fw::Bool, illum::Bool)
GC.gc(true)
devito.clear_cache()
# Load full geometry for out-of-core geometry containers
recGeometry = Geometry(recGeometry)
srcGeometry = Geometry(srcGeometry)
# Reutrn directly for J*0
if (op==:born && norm(dm) == 0)
return judiVector(recGeometry, zeros(Float32, recGeometry.nt[1], length(recGeometry.xloc[1])))
end
# limit model to area with sources/receivers
if options.limit_m == true
@juditime "Limit model to geometry" begin
model = deepcopy(model_full)
model, dm = limit_model_to_receiver_area(srcGeometry, recGeometry, model, options.buffer_size; pert=dm)
end
else
model = model_full
end
# Set up Python model structure
@juditime "Devito Model" begin
modelPy = devito_model(model, options, dm)
end
# Devito interface
@juditime "Propagation" begin
argout = devito_interface(modelPy, srcGeometry, srcData, recGeometry, recData, dm, options, illum, fw)
end
@juditime "Filter empty output" begin
argout = filter_none(argout)
end
argout = post_process(argout, modelPy, Val(op), recGeometry, srcGeometry, options)
argout = save_to_disk(argout, srcGeometry, srcData, options, Val(fw), Val(options.save_data_to_disk))
return argout
end
# Backward compat for external packages
post_process(t::Tuple, modelPy::PyObject, op::Val, Gr, o::JUDIOptions) = post_process(t, modelPy, op, Gr, nothing, o)
# Post processing of output of devito based on parameters
post_process(t::Tuple, modelPy::PyObject, op::Val, Gr, Gs, o::JUDIOptions) = (post_process(t[1], modelPy, op, Gr, Gs, o), post_process(Base.tail(t), modelPy, Val(:adjoint_born), Gr, Gs, Options(;sum_padding=false))...)
post_process(t::Tuple{}, ::PyObject, ::Val, ::Any, ::Any, ::JUDIOptions) = t
function post_process(v::AbstractArray{T, N}, modelPy::PyObject, ::Val{:adjoint}, ::Any, ::Any, options::JUDIOptions) where {T, N}
if N == modelPy.dim
return judiWeights{T}(1, [remove_padding(v, modelPy.padsizes; true_adjoint=false)])
else
return judiWavefield{T}(1, [calculate_dt(modelPy)], [v])
end
end
post_process(v::AbstractArray{T}, modelPy::PyObject, ::Val{:forward}, ::Any, ::Any, options::JUDIOptions) where {T<:Number} = judiWavefield{T}(1, [calculate_dt(modelPy)], [v])
function post_process(v::AbstractArray{T}, modelPy::PyObject, ::Val{:adjoint_born}, Gr::Geometry{T}, ::Any, options::JUDIOptions) where {T<:Number}
grad = remove_padding(v, modelPy.padsizes; true_adjoint=options.sum_padding)
return PhysicalParameter(grad, modelPy.spacing, modelPy.origin)
end
post_process(v::AbstractArray{T}, modelPy::PyObject, ::Val{:forward}, G::Geometry{T}, Gs, options::JUDIOptions) where {T<:Number} = post_process_src(v, calculate_dt(modelPy), G, Gs)
post_process(v::AbstractArray{T}, modelPy::PyObject, ::Val{:adjoint}, G::Geometry{T}, Gs, options::JUDIOptions) where {T<:Number} = post_process_src(v, calculate_dt(modelPy), G, Gs)
post_process(v::AbstractArray{T}, modelPy::PyObject, ::Val{:born}, G::Geometry{T}, Gs, options::JUDIOptions) where {T<:Number} = post_process_src(v, calculate_dt(modelPy), G, Gs)
post_process_src(v::AbstractArray{T}, dt::T, Gr::Geometry, Gs::Geometry) where {T<:Number} = judiVector{T, Matrix{T}}(1, Gr, [time_resample(v, dt, Gs, Gr)])
post_process_src(v::AbstractArray{T}, dt::T, Gr::Geometry, ::Any) where {T<:Number} = judiVector{T, Matrix{T}}(1, Gr, [time_resample(v, dt, Gr)])
# Saving to disk utilities
save_to_disk(shot, args...) = shot
save_to_disk(t::Tuple, args...) = save_to_disk(t[1], args...), Base.tail(t)...
save_to_disk(shot::judiVector{T, Matrix{T}}, ::Any, ::Any, ::Any, ::Any, ::Val{false}) where {T<:Number} = shot
function save_to_disk(shot::judiVector{T}, srcGeometry::GeometryIC{T}, srcData::Array, options::JUDIOptions,
::Val{true}, ::Val{true}) where {T<:Number}
@juditime "Dump data to segy" begin
container = write_shot_record(srcGeometry, [srcData], shot.geometry, shot.data, options)
dout = judiVector(container)
end
return dout
end
time_modeling = retry(_time_modeling) | JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 5538 |
export twri_objective, TWRIOptions
# TWRI options
mutable struct TWRIOptions
grad_corr::Bool
comp_alpha::Bool
weight_fun
eps
params
Invq::String
end
"""
TWRIOptions
grad_corr::Bool
comp_alpha::Bool
weight_fun
eps
params::Symbol
Invq::String
Options structure for TWRI.
`grad_corr`: Whether to add the gradient correction J'(m0, q)*∇_y
`comp_alpha`: Whether to compute optimal alpha (alpha=1 if not)
`weight_fun`: Whether to apply focusing/weighting function to F(m0)'*y and its norm
`eps`: Epsilon (noise level) value (default=0)
`Invq`: How to compute F'Y, either as full field or as a rank 1 approximation `w(t)*q(x)` using the source wavelet for w
`param`: Which gradient to compute. Choices are `nothing` (objective only), `:m`, `:y` or `:all`
Constructor
==========
All arguments are optional keyword arguments with the following default values:
TWRIOptions(;grad_corr=false, comp_alpha=true, weight_fun=nothing, eps=0, params=:m)
"""
TWRIOptions(;grad_corr=false, comp_alpha=true,
weight_fun=nothing, eps=0, params=:m, Invq="standard")=
TWRIOptions(grad_corr, comp_alpha, weight_fun, eps, params, Invq)
function getindex(opt::TWRIOptions, srcnum::Int)
eloc = length(opt.eps) == 1 ? opt.eps : opt.eps[srcnum]
return TWRIOptions(opt.grad_corr, opt.comp_alpha, opt.weight_fun, eloc, opt.params, opt.Invq)
end
subsample(opt::TWRIOptions, srcnum::Int) = getindex(opt, srcnum)
function _twri_objective(model_full::AbstractModel, source::judiVector, dObs::judiVector, y::Union{judiVector, Nothing},
options::JUDIOptions, optionswri::TWRIOptions)
# Load full geometry for out-of-core geometry containers
dObs.geometry = Geometry(dObs.geometry)
source.geometry = Geometry(source.geometry)
# Limit model to area with sources/receivers
if options.limit_m == true
model = deepcopy(model_full)
model = limit_model_to_receiver_area(source.geometry, dObs.geometry, model, options.buffer_size)
else
model = model_full
end
# Set up Python model structure
modelPy = devito_model(model, options)
dtComp = convert(Float32, modelPy."critical_dt")
# Extrapolate input data to computational grid
qIn = time_resample(make_input(source), source.geometry, dtComp)
dObserved = time_resample(make_input(dObs), dObs.geometry, dtComp)
if isnothing(y)
Y = nothing
else
Y = time_resample(make_input(y), y.geometry, dtComp)
_, Y = _maybe_pad_t0(qIn, source.geometry, Y, y.geometry, dtComp)
end
qIn, dObserved = _maybe_pad_t0(qIn, source.geometry, dObserved, dObs.geometry, dtComp)
# Set up coordinates
src_coords = setup_grid(source.geometry, size(model)) # shifts source coordinates by origin
rec_coords = setup_grid(dObs.geometry, size(model)) # shifts rec coordinates by origin
~isempty(options.frequencies) ? freqs = options.frequencies : freqs = nothing
~isempty(options.frequencies) ? (wfilt, freqs) = filter_w(qIn, dtComp, freqs) : wfilt = nothing
obj, gradm, grady = rlock_pycall(ac."wri_func", PyObject,
modelPy, src_coords, qIn, rec_coords, dObserved, Y, t_sub=options.subsampling_factor,
grad=optionswri.params, grad_corr=optionswri.grad_corr, eps=optionswri.eps,
alpha_op=optionswri.comp_alpha, w_fun=optionswri.weight_fun,
freq_list=freqs, wfilt=wfilt, f0=options.f0)
if (optionswri.params in [:m, :all])
gradm = remove_padding(gradm, modelPy.padsizes; true_adjoint=options.sum_padding)
gradm = PhysicalParameter(gradm, spacing(model), origin(model))
end
if ~isnothing(grady)
grady = time_resample(grady, dtComp, dObs.geometry)
grady = judiVector(dObs.geometry, grady)
end
return filter_out(Ref{Float32}(obj), gradm, grady)
end
function filter_w(qIn, dt, freqs)
ff = FFTW.fftfreq(length(qIn), 1/dt)
df = ff[2] - ff[1]
inds = [findmin(abs.(ff.-f))[2] for f in freqs]
DFT = joDFT(length(qIn); DDT=Float32)
R = joRestriction(size(DFT,1), inds; RDT=Complex{Float32}, DDT=Complex{Float32})
qfilt = DFT'*R'*R*DFT*qIn
return qfilt, freqs
end
filter_out(obj, ::Nothing, ::Nothing) = obj
filter_out(obj, m, ::Nothing) = obj, m
filter_out(obj, ::Nothing, y) = obj, y
filter_out(obj, m, y) = obj, m, y
twri = retry(_twri_objective)
# Parallel
"""
twri_objective(model, source, dobs; options=Options(), optionswri=TWRIOptions())
Evaluate the time domain Wavefield reconstruction inversion objective function. Returns a tuple with function value and \\
gradient(s) w.r.t to m and/or y. `model` is a `Model` structure with the current velocity model and `source` and `dobs` are the wavelets and \\
observed data of type `judiVector`.
Example
=======
function_value, gradient = fwi_objective(model, source, dobs)
"""
function twri_objective(model::AbstractModel, source::judiVector, dObs::judiVector, y::Union{judiVector, Nothing};
options=Options(), optionswri=TWRIOptions())
pool = _worker_pool()
if isnothing(y)
arg_func = j -> (model, source[j], dObs[j], nothing, options[j], optionswri[j])
else
arg_func = j -> (model, source[j], dObs[j], y[j], options[j], optionswri[j])
end
results = run_and_reduce(twri, pool, source.nsrc, arg_func)
# Collect and reduce gradients
out = as_vec(results, Val(options.return_array))
return out
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 14173 | export DataMute, FrequencyFilter, judiTimeDerivative, judiTimeIntegration, TimeDifferential
export judiFilter, filter_data, judiDataMute, muteshot, judiTimeGain
time_resample(t::Tuple{Vararg{<:DataPreconditioner}}, newt) = prod(time_resample(ti, newt) for ti in t)
time_resample(t::Vector{<:DataPreconditioner}, newt) = prod(time_resample(ti, newt) for ti in t)
############################################ Data mute ###############################################
"""
struct DataMute{T, mode} <: DataPreconditioner{T, T}
srcGeom::Geometry
recGeom::Geometry
vp::Vector{T}
t0::Vector{T}
taperwidth::Vector{Int64}
end
Data mute linear operator a where {T, N}sociated with source `srcGeom` and receiver `recGeom` geometries used to compute the distance to the source
for each trace in the data. Data mute preconditionner. Supports two modes (:reflection, :turning) that mute either the turning waves (standard direct wave mute) or mutes the reflections.
A cosine tapr is applied with width `taperwidth` to avoid abrupt change and infinite frequency jumps in the data.
Constructors
============
judiDataMute(srcGeom, recGeom; vp=1500, t0=.1, mode=:reflection, taperwidth=floor(Int, 2/t0))
Construct the data mute operator from the source `srcGeom` and receiver `recGeom` geometries.
judiDataMute(q, d; vp=1500, t0=.1, mode=:reflection, taperwidth=floor(Int, 2/t0))
Construct the data mute operator from the judivector source `q` and judivector data `d`.
Parameters
============
The following optional paramet where {T, N}rs control the muting operator
- `vp`: P wave velocity of the direct wave (usually water velocity). Can be a constant or a Vector with one value per source position. Devfaults to `1500m/s`
- `t0`: Time shift in seconds (usually width of the wavelet). Defaults to ``.1 sec``
- `mode`:
`:reflection` to keep the reflections and mute above the direct wave (i.e for RTM)
`:turning` to keep the turning waves and mute below the direct wave (i.e for FWI)
- `taperwidth`: Width of the cosine taper in number of samples. Defaults to `2 / t0`
"""
struct DataMute{T, mode} <: DataPreconditioner{T, T}
m::Integer
srcGeom::Geometry
recGeom::Geometry
vp::Vector{T}
t0::Vector{T}
taperwidth::Vector{Int64}
end
function judiDataMute(srcGeom::Geometry, recGeom::Geometry; vp=1500, t0=.1, mode=:reflection, taperwidth=floor(Int, 2/t0))
mode ∈ [:reflection, :turning] || throw(ArgumentError("Only reflection (mute turning) and turning (mute refelctions) modes supported"))
nsrc = get_nsrc(srcGeom)
get_nsrc(recGeom) == nsrc || throw(ArgumentError("Incompatible geometries with $(nsrc) and $(get_nsrc(recGeom)) number of sources"))
VP = Vector{Float32}(undef, nsrc); VP .= vp
T0 = Vector{Float32}(undef, nsrc); T0 .= t0
TW = Vector{Int64}(undef, nsrc); TW .= taperwidth
m = n_samples(recGeom)
return DataMute{Float32, mode}(m, srcGeom, recGeom, VP, T0, TW)
end
judiDataMute(q::judiVector, d::judiVector; kw...) = judiDataMute(q.geometry, d.geometry; kw...)
# Implementation
matvec_T(D::DataMute{T, mode} , x::AbstractVecOrMat{T}) where {T, mode} = matvec(D, x) # Basically a mask so symmetric and self adjoint
matvec(D::DataMute{T, mode} , x::AbstractVecOrMat{T}) where {T, mode} = muteshot(x, D.srcGeom, D.recGeom; vp=D.vp, t0=D.t0, mode=mode, taperwidth=D.taperwidth)
# Real diagonal operator
conj(I::DataMute{T, mode}) where {T, mode} = I
adjoint(I::DataMute{T, mode}) where {T, mode} = I
transpose(I::DataMute{T, mode}) where {T, mode} = I
# getindex for source subsampling
function getindex(P::DataMute{T, mode}, i) where {T, mode}
geomi = P.recGeom[i]
m = n_samples(geomi)
inds = isa(i, Integer) ? (i:i) : i
DataMute{T, mode}(m, P.srcGeom[inds], geomi, P.vp[inds], P.t0[inds], P.taperwidth[inds])
end
function time_resample(d::DataMute{T, mode}, taxis::AbstractRange) where {T, mode}
@assert get_nsrc(d.recGeom) == 1
new_rgeom = deepcopy(d.recGeom)
new_sgeom = deepcopy(d.srcGeom)
new_rgeom.taxis[1] = taxis
new_sgeom.taxis[1] = taxis
taperwidth = trunc.(Int64, d.taperwidth .* (d.recGeom.dt ./ taxis.step))
return DataMute{T, mode}(d.m, new_sgeom, new_rgeom, d.vp, d.t0, taperwidth)
end
function _mutetrace!(t::AbstractVector{T}, taper::AbstractVector{T}, i::Integer, taperwidth::Integer, ::Val{:reflection}) where T
t[1:i-taperwidth] .= 0f0
t[i-taperwidth+1:i] .*= taper
end
function _mutetrace!(t::AbstractVector{T}, taper::AbstractVector{T}, i::Integer, taperwidth::Integer, ::Val{:turning}) where T
t[i+taperwidth+1:end] .= 0f0
t[i+1:i+taperwidth] .*= taper
end
function muteshot!(shot::AbstractMatrix{T}, rGeom::Geometry, srcGeom::Geometry; vp=1500, t0=.1, mode=:reflection, taperwidth=floor(Int, 2/t0)) where T
sGeom = Geometry(srcGeom)
rGeom = Geometry(rGeom)
nt, nrec = size(shot)
taper = _taper(Val(mode), taperwidth)
# Loop over traces
@inbounds for t=1:nrec
r = radius(rGeom, sGeom, t)
tt = 1f3 * (r / vp + t0) / get_dt(rGeom, 1)
i = min(max(1, floor(Int, tt)), nt)
if _tapew(i, taperwidth, nt, Val(mode))
_mutew!(view(shot, :, t), taper, i, nt, Val(mode))
else
_mutetrace!(view(shot, :, t), taper, i, taperwidth, Val(mode))
end
end
end
function muteshot(shot::VecOrMat{T}, srcGeom::Geometry, recGeom::Geometry;
vp=1500, t0=.1, mode=:reflection, taperwidth=floor(Int, 2/t0)) where {T<:Number}
sr = reshape(shot, recGeom)
for s=1:get_nsrc(recGeom)
sri = view(sr, :, :, s)
muteshot!(sri, recGeom[s], srcGeom[s]; vp=vp[s], t0=t0[s], mode=mode, taperwidth=taperwidth[s])
end
return reshape(sr, size(shot))
end
function muteshot(shot::judiVector, srcGeom::Geometry; vp=1500, t0=.1, mode=:reflection, taperwidth=20)
out = deepcopy(get_data(shot))
for s=1:out.nsrc
muteshot!(out.data[s], shot.geometry[s], srcGeom[s]; vp=vp[s], t0=t0[s], mode=mode, taperwidth=taperwidth[s])
end
out
end
muteshot(shot::judiVector, srcGeom::Geometry, recGeom::Geometry; kw...) = muteshot(shot, srcGeom; kw...)
"""
struct FrequencyFilter
recGeom
Bandpass filter linear operator. Filters the input `judiVector` or `Vector`
Constructor
============
judiFilter(geometry, fmin, fmax)
judiFilter(judiVector, fmin, fmax)
"""
struct FrequencyFilter{T, fm, FM} <: DataPreconditioner{T, T}
m::Integer
recGeom::Geometry
end
judiFilter(geometry::Geometry, fmin::T, fmax::T) where T = judiFilter(geometry, Float32(fmin), Float32(fmax))
judiFilter(geometry::Geometry, fmin::Float32, fmax::Float32) = FrequencyFilter{Float32, fmin, fmax}(n_samples(geometry), geometry)
judiFilter(v::judiVector, fmin, fmax) = judiFilter(v.geometry, fmin, fmax)
function matvec(D::FrequencyFilter{T, fm, FM}, x::VecOrMat{T}) where {T, fm, FM}
dr = reshape(x, D.recGeom)
for j=1:get_nsrc(D.recGeom)
dri = view(dr, :, :, j)
filter!(dri, dri, get_dt(D.recGeom, j); fmin=fm, fmax=FM)
end
return reshape(vcat(dr...), size(x))
end
function matvec(::FrequencyFilter{T, fm, FM}, Din::judiVector{T, AT}) where {T, fm, FM, AT}
Dout = deepcopy(Din)
for j=1:Dout.nsrc
filter!(Dout.data[j], Din.data[j], get_dt(Din.geometry, j); fmin=fm, fmax=FM)
end
return Dout
end
# getindex for source subsampling
function getindex(P::FrequencyFilter{T, fm, FM}, i) where {T, fm, FM}
geomi = P.recGeom[i]
return FrequencyFilter{T, fm, FM}(n_samples(geomi), geomi)
end
function time_resample(d::FrequencyFilter{T, fm, fM}, taxis::AbstractRange) where {T, fm, fM}
@assert get_nsrc(d.recGeom) == 1
new_geom = deepcopy(d.recGeom)
new_geom.taxis[1] = taxis
return FrequencyFilter{T, fm, fM}(d.m, new_geom)
end
# filtering is self-adjoint (diagonal in fourier domain)
matvec_T(D::FrequencyFilter{T, fm, FM}, x) where {T, fm, FM} = matvec(D, x)
# Real diagonal operator
conj(I::FrequencyFilter{T}) where T = I
adjoint(I::FrequencyFilter{T}) where T = I
transpose(I::FrequencyFilter{T}) where T = I
function tracefilt!(x, y, ypad, filter)
n = length(y)
ypad[n:end] .= y
ypad[1:n] .= view(y, n:-1:1)
x .= filtfilt(filter, ypad)[n:end]
nothing
end
function filter!(dout::AbstractArray{T, N}, din::AbstractArray{T, N}, dt::T; fmin=T(0.01), fmax=T(100)) where {T, N}
if fmin == 0
responsetype = Lowpass(fmax; fs=1e3/dt)
elseif isinf(fmax)
responsetype = Highpass(fmin; fs=1e3/dt)
else
responsetype = Bandpass(fmin, fmax; fs=1e3/dt)
end
filter = digitalfilter(responsetype, Butterworth(5))
ytmp = zeros(T, size(din, 1)*2-1)
map(i-> tracefilt!(selectdim(dout, N, i), selectdim(din, N, i), ytmp, filter), 1:size(dout, 2))
end
filter_data(Din::judiVector; fmin=0, fmax=Inf) = judiFilter(Din.geometry, fmin, fmax)*Din
filter_data(Din::judiVector, ::Any; fmin=0, fmax=Inf) = filter_data(Din; fmin=fmin, fmax=fmax)
"""
filter(Din, dt_in; fmin=0, fmax=25)
Performs a causal filtering [fmin, fmax] on the input data bases on its sampling rate `dt`.
Automatically perfroms a lowpass if fmin=0 (default)
"""
function filter_data(Din::Matrix{T}, dt_in; fmin=0, fmax=Inf) where T
out = similar(Din)
filter!(out, Din, dt_in; fmin=T(fmin), fmax=T(fmax))
return out
end
# Legacy `low_filter`
low_filter(ar...) = filter_data(ar...)
# Legacy top mute is deprecated since only working for marine data
judiMarineTopmute2D(::Integer, geometry::Geometry; params=Array{Any}(undef, 3), flipmask=false) = throw(MethodError(judiMarineTopmute2D, "judiMarineTopmute2D is deprecated due to its limitations and inaccuracy, please use judiDataMute"))
"""
struct TimeDifferential
recGeom
Differential operator of order `K` to be applied along the time dimension. Applies the ilter `w^k` where `k` is the order. For example,
the tinme derivative is `TimeDifferential{1}` and the time integration is `TimeDifferential{-1}`
Constructor
============
judiTimeIntegration(recGeom, order)
judiTimeIntegration(judiVector, order)
judiTimeDerivative(recGeom, order)
judiTimeDerivative(judiVector, order)
"""
struct TimeDifferential{T, K} <: DataPreconditioner{T, T}
m::Integer
recGeom::Geometry
end
TimeDifferential(g::Geometry{T}, order::Number) where T = TimeDifferential{T, order}(n_samples(g), g)
judiTimeDerivative(v::judiVector{T, AT}, order::Number) where {T, AT} = TimeDifferential(v.geometry, order)
judiTimeDerivative(g::Geometry{T}, order::Number) where {T} = TimeDifferential(g, order)
judiTimeIntegration(v::judiVector{T, AT}, order::Number) where {T, AT} = TimeDifferential(v.geometry, -order)
judiTimeIntegration(g::Geometry{T}, order::Number) where {T} = TimeDifferential(g, -order)
# Real diagonal operator
conj(D::TimeDifferential{T, K}) where {T, K} = D
adjoint(D::TimeDifferential{T, K}) where {T, K} = D
transpose(D::TimeDifferential{T, K}) where {T, K} = D
inv(D::TimeDifferential{T, K}) where {T, K} = TimeDifferential{T, -K}(D.m, D.recGeom)
# diagonal in fourier domain so self-adjoint
matvec_T(D::TimeDifferential{T, K}, x) where {T, K} = matvec(D, x)
# getindex for source subsampling
function getindex(P::TimeDifferential{T, K}, i) where {T, K}
geomi = P.recGeom[i]
m = n_samples(geomi)
TimeDifferential{T, K}(m, geomi)
end
function time_resample(d::TimeDifferential{T, K}, taxis::AbstractRange) where {T, K}
@assert get_nsrc(d.recGeom) == 1
new_geom = deepcopy(d.recGeom)
new_geom.taxis[1] = taxis
return TimeDifferential{T, K}(d.m, new_geom)
end
function matvec(D::TimeDifferential{T, K}, x::judiVector{T, AT}) where {T, AT, K}
out = similar(x)
for s=1:out.nsrc
# make omega^K
ω = 2 .* pi .* fftfreq(get_nt(D.recGeom, s), 1/get_dt(D.recGeom, s))
ω[ω.==0] .= 1f0
ω .= abs.(ω).^K
out.data[s] .= real.(ifft(ω .* fft(x.data[s], 1), 1))
end
return out
end
function matvec(D::TimeDifferential{T, K}, x::Array{T}) where {T, K}
xr = reshape(x, D.recGeom)
out = similar(xr)
# make omega^K
ω = 2 .* pi .* fftfreq(get_nt(D.recGeom, 1), 1/get_dt(D.recGeom, 1))
ω[ω.==0] .= 1f0
ω .= abs.(ω).^K
out .= real.(ifft(ω .* fft(xr, 1), 1))
return reshape(out, size(x))
end
"""
struct TimeGain
recGeom
Apply gain `t^K` to the data along the time axis for each trace. This is used in practice to correct for
3D amplitude decay when running 2D inversion
Constructor
============
judiTimeGain(recGeom, pow)
judiTimeGain(judiVector, pow)
"""
struct TimeGain{T, K} <: DataPreconditioner{T, T}
m::Integer
recGeom::Geometry
TimeGain{T, K}(recGeom::Geometry) where {T, K} = new{T, K}(n_samples(recGeom), recGeom)
end
TimeGain(g::Geometry{T}, pow::Number) where T = TimeGain{T, pow}(g)
judiTimeGain(v::judiVector{T, AT}, pow::Number) where {T, AT} = TimeGain(v.geometry, pow)
judiTimeGain(g::Geometry{T}, pow::Number) where {T} = TimeGain(g, pow)
# Real diagonal operator
conj(D::TimeGain{T, K}) where {T, K} = D
adjoint(D::TimeGain{T, K}) where {T, K} = D
transpose(D::TimeGain{T, K}) where {T, K} = D
inv(D::TimeGain{T, K}) where {T, K} = TimeGain{T, -K}(D.recGeom)
# diagonal in fourier domain so self-adjoint
matvec_T(D::TimeGain{T, K}, x) where {T, K} = matvec(D, x)
# getindex for source subsampling
getindex(D::TimeGain{T, K}, i) where {T, K} = TimeGain{T, K}(D.recGeom[i])
function time_resample(d::TimeGain{T, K}, taxis::AbstractRange) where {T, K}
@assert get_nsrc(d.recGeom) == 1
new_geom = deepcopy(d.recGeom)
new_geom.taxis[1] = taxis
return TimeGain{T, K}(new_geom)
end
function matvec(D::TimeGain{T, K}, x::judiVector{T, AT}) where {T, AT, K}
out = similar(x)
for s=1:out.nsrc
# make time^K
timek = (D.recGeom.taxis[s]).^K
out.data[s] .= timek .* x.data[s]
end
return out
end
function matvec(D::TimeGain{T, K}, x::Array{T}) where {T, K}
xr = reshape(x, D.recGeom)
# make time^K
timek = (D.recGeom.taxis[1]).^K
out = timek .* xr
return reshape(out, size(x))
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 8732 | export judiIllumination, judiDepthScaling, judiTopmute
export DepthScaling, TopMute
"""
DepthScaling{T, N, K}
Depth scaling operator in `N` dimensions scaling by `depth^K`.
Constructor
===========
judiDepthScaling(model::AbstractModel; K=.5)
"""
struct DepthScaling{T, N, K} <: ModelPreconditioner{T, T}
m::Integer
depth::Array{T, N}
end
function judiDepthScaling(model::AbstractModel; K=.5f0)
N = length(size(model))
depth = reshape(range(0f0, stop=(size(model)[end] - 1) * spacing(model)[end], length=size(model)[end]), ones(Int64, N-1)..., :)
return DepthScaling{Float32, N, K}(prod(size(model)), depth)
end
matvec(D::DepthScaling{T, N, K}, x::Vector{T}) where {T, N, K} = vec(reshape(x, :, size(D.depth, N)) .* D.depth[:]'.^K)
matvec(D::DepthScaling{T, N, K}, x::AbstractArray{T, N}) where {T, N, K} = x .* D.depth.^K
matvec(D::DepthScaling{T, N, K}, x::PhysicalParameter{T}) where {T, N, K} = PhysicalParameter(x.n, x.d, x.o, x.data .* D.depth.^K)
matvec(D::DepthScaling{T, N, K}, x::judiWeights{T}) where {T, N, K} = judiWeights{T}(x.nsrc, [matvec(D, x.data[s]) for s=1:x.nsrc])
# Diagonal operator, self-adjoint
matvec_T(D::DepthScaling{T, N, K}, x) where {T, N, K} = matvec(D, x)
# Real diagonal operator
conj(I::DepthScaling{T}) where T = I
adjoint(I::DepthScaling{T}) where T = I
transpose(I::DepthScaling{T}) where T = I
inv(I::DepthScaling{T, N, K}) where {T, N, K} = DepthScaling{Float32, N, -K}(I.m, I.depth)
"""
TopMute{T, N, Nw}
Mute top of the model in `N` dimensions
Constructor
===========
judiTopmute(model; taperwidht=10)
judiTopmute(n, wb, taperwidth) # Legacy
"""
struct TopMute{T, N, Nw} <: ModelPreconditioner{T, T}
m::Integer
wb::Array{Int64, Nw}
taperwidth::Int64
TopMute(m::Integer, wb::Array{T, Nw}, taperwidth::Integer) where {T, Nw} = new{Float32, Nw+1, Nw}(m, wb, taperwidth)
end
judiTopmute(n::NTuple{N, Integer}, wb::Array{T, Nw}, taperwidth::Integer) where {T, N, Nw} = TopMute(prod(n), wb, taperwidth)
judiTopmute(n::NTuple{N, Integer}, wb::Integer, taperwidth::Integer) where {N} = TopMute(prod(n), wb*ones(Int64, n[1:end-1]), taperwidth)
function judiTopmute(model::AbstractModel; taperwidth=10)
wb = find_water_bottom(model.m.data)
return TopMute(prod(size(model)), wb, taperwidth)
end
function matvec(D::TopMute{T, N}, x::Array{T, N}) where {T, N}
out = 1 .* x
taper = D.taperwidth < 2 ? 1 : _taper(Val(:reflection), D.taperwidth)
for i in CartesianIndices(D.wb)
out[i, 1:D.wb[i]-D.taperwidth] .= 0
s = max(D.wb[i]-D.taperwidth+1, 1)
ni = length(s:D.wb[i])
tap = D.taperwidth < 2 ? 1 : taper[end-ni+1:end]
out[i, s:D.wb[i]] .*= tap
end
out
end
matvec(D::TopMute{T, N}, x::PhysicalParameter{T}) where {T, N} = PhysicalParameter(x, matvec(D, x.data))
matvec(D::TopMute{T, N}, x::judiWeights{T}) where {T, N} = judiWeights{T}(x.nsrc, [matvec(D, x.data[s]) for s=1:x.nsrc])
matvec(D::TopMute{T, N}, x::Vector{T}) where {T, N} = vec(matvec(D, reshape(x, size(D.wb)..., :)))
matvec_T(D::TopMute{T, N}, x) where {T, N} = matvec(D, x)
# Real diagonal operator
conj(I::TopMute{T, N}) where {T, N} = I
adjoint(I::TopMute{T, N}) where {T, N} = I
transpose(I::TopMute{T, N}) where {T, N} = I
inv(::TopMute{T, N}) where {T, N} = throw(MethodError(inv, "Topmute masks contains zeros cannot be inverted"))
"""
judiIllumination(model; mode="u", k=1, recompute=true)
# Arguments
- `model`: JUDI Model structure
- `mode`: Type of ilumination, choicees of ("u", "v", "uv")
- `k`: Power of the illumination, real number
- `recompute`: Flag whether to recompute the illumination at each new propagation (Defaults to true)
judiIllumination(F; mode="u", k=1, recompute=true)
# Arguments
- `F`: JUDI propagator
- `mode`: Type of ilumination, choicees of ("u", "v", "uv")
- `k`: Power of the illumination, real positive number
- `recompute`: Flag whether to recompute the illumination at each new propagation (Defaults to true)
Diagonal approximation of the FWI Hessian as the energy of the wavefield. The diagonal contains the sum over time
of the wavefield chosen as `mode`.
Options for the mode are "u" for the forward wavefield illumination, "v" for the adjoint wavefield illumination, and
"uv" for the pointwise product of the forward and adjoint wavefields illuminations. Additionally, the parameter "k" provides control on the scaling of
the daiagonal raising it to the power `k`.
Example
========
I = judiIllumination(model)
Construct the diagonal operator such that I*x = x ./ |||u||_2^2
"""
struct judiIllumination{DDT, M, K, R} <: ModelPreconditioner{DDT, DDT}
name::String
illums
m::Integer
end
function judiIllumination(model::AbstractModel; mode="u", k=1, recompute=true)
n = prod(size(model))
# Initialize the illumination as the identity
illum = Dict(s=>PhysicalParameter(size(model), spacing(model), origin(model), ones(Float32, size(model))) for s in split(mode, ""))
I = judiIllumination{Float32, Symbol(mode), k, recompute}("Illumination", illum, n)
init_illum(model, I)
return I
end
judiIllumination(F::judiPropagator; kw...) = judiIllumination(F.model; kw...)
# Real diagonal operator
conj(I::judiIllumination{T}) where T = I
adjoint(I::judiIllumination{T}) where T = I
transpose(I::judiIllumination{T}) where T = I
# Inverse
inv(I::judiIllumination{T, M, K, R}) where {T, M, K, R} = judiIllumination{T, M, -K, R}(I.name, I.illums, I.m)
# Mul
function matvec(I::judiIllumination{T, M, K, R}, x::Vector{T}) where {T, M, K, R}
illum = (.*(values(I.illums)...)).^(1/length(I.illums))
inds = findall(illum[:] .> eps(T))
out = T(0) * x
out[inds] .= illum[:][inds].^K .* x[inds]
return out
end
function matvec(I::judiIllumination{T, M, K, R}, x::PhysicalParameter{T}) where {T, M, K, R}
illum = (.*(values(I.illums)...)).^(1/length(I.illums))
inds = findall(illum .> eps(T))
out = T(0) * x
out[inds] .= illum[inds].^K .* x[inds]
return out
end
# Functor
function (I::judiIllumination{T, M, K, R})(mode::String) where {T, M, K, R}
illum = Dict(s=>similar(first(values(I.illums))) for s in split(mode, ""))
for k ∈ keys(illum)
if k ∈ keys(I.illums)
illum[k] = deepcopy(I.illums[k])
else
fill!(illum[k], 1)
end
end
judiIllumination{T, Symbol(mode), K, R}(I.name, illum, I.m)
end
# Assignment
function set_val(I::judiIllumination{T, M, K, R}, mode, v) where {T, M, K, R}
key = mode ∈ [:forward, :born] ? "u" : "v"
if key in keys(I.illums)
# For safety when propagation doesn't reach all the model
v[v .== 0] .= 1f0
combine!(I.illums[key], v)
end
end
# status
function is_updated(I::judiIllumination{T, M, K, R}) where {T, M, K, R}
updated = true
for (k, v) in I.illums
im, iM = extrema(v)
updated = (im == iM == 1) && updated
end
return ~updated
end
################## Illumination tracker. ####################
# We carry a global tracker that associate an illumination operator
# with its model so that we can extract it after propagation
_illums = Dict()
init_illum(model::AbstractModel, Tm::judiIllumination) = (_illums[objectid(model)] = [Tm, false])
function update_illum(vals::Tuple, F::judiPropagator{D, O}) where {D, O}
if length(vals) == 3
update_illum(F.model, vals[2], :forward)
update_illum(F.model, vals[3], :adjoint)
else
update_illum(F.model, vals[2], O)
end
return vals[1]
end
update_illum(vals, ::judiPropagator) = vals
function update_illum(vals::Tuple, model::AbstractModel, ::Any)
length(vals) == 2 && (return vals)
update_illum(model, vals[3], :forward)
update_illum(model, vals[4], :adjoint)
return vals[1:2]
end
function update_illum(model::AbstractModel, i::PhysicalParameter, mode)
set_val(_illums[objectid(model)][1], mode, i)
_illums[objectid(model)][2] = is_updated(_illums[objectid(model)][1])
end
function _compute_illum(::judiIllumination{T, M, K, R}, status, mode) where {T, M, K, R}
if status && ~R
return false
elseif (mode ∈ [:forward, :born] && M ∈ [:u, :uv]) || (mode == :adjoint && M ∈ [:v, :uv]) || (mode == :adjoint_born)
return true
else
return false
end
end
function compute_illum(model::AbstractModel, mode::Symbol)
objectid(model) ∉ keys(_illums) && (return false)
return _compute_illum(_illums[objectid(model)]..., mode)
end
function _track_illum(old_m::AbstractModel, new_m::AbstractModel)
if (objectid(old_m) ∈ keys(_illums)) && (objectid(new_m) ∉ keys(_illums))
_illums[objectid(new_m)] = _illums[objectid(old_m)]
end
end
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 3059 | abstract type Preconditioner{D, R} <: joAbstractLinearOperator{D, R} end
"""
ModelPreconditioner{T}
Base abstract type for model space preconditioners. Acta on [`PhysicalParameter{T}`](@ref) or `Vector{T}`
"""
abstract type ModelPreconditioner{D, R} <: Preconditioner{D, R} end
"""
DataPreconditioner{T}
Base abstract for Data space preconditioner. As a data space operator, it must implement `getindex(M, i)` to be aplied on a single shot record.
Acts on `judiVector{T}` or `Vector{T}`.
"""
abstract type DataPreconditioner{D, R} <: Preconditioner{D, R} end
# JOLI compat
_get_property(J::Preconditioner, ::Val{:fop}) = x -> matvec(J, x)
_get_property(J::Preconditioner, ::Val{:fop_T}) = x -> matvec_T(J, x)
_get_property(J::Preconditioner, ::Val{:name}) = "$(typeof(J))"
_get_property(J::Preconditioner, ::Val{:n}) = getfield(J, :m)
_get_property(J::Preconditioner, ::Val{s}) where {s} = getfield(J, s)
getproperty(J::Preconditioner, s::Symbol) = _get_property(J, Val{s}())
# Base compat
*(J::Preconditioner, ms::judiMultiSourceVector) = matvec(J, ms)
*(J::Preconditioner, ms::PhysicalParameter) = matvec(J, ms)
*(J::Preconditioner, v::VecOrMat{T}) where T = matvec(J, v)
mul!(out::judiMultiSourceVector, J::Preconditioner, ms::judiMultiSourceVector) = copyto!(out, matvec(J, ms))
mul!(out::PhysicalParameter, J::Preconditioner, ms::PhysicalParameter) = copyto!(out, matvec(J, ms))
# OOC judiVector
*(J::DataPreconditioner, v::judiVector{T, SegyIO.SeisCon}) where T = LazyMul(v.nsrc, J, v)
*(J::Preconditioner, v::LazyMul) = LazyMul(v.nsrc, J*v.P, v)
"""
MultiPrcontinioner{TP, T}
Type for the combination of preconditioners. It is a linear operator that applies the preconditioners in sequence.
"""
struct MultiPreconditioner{TP, T} <: Preconditioner{T, T}
precs::Vector{TP}
end
function matvec(J::MultiPreconditioner, x)
y = J.precs[end] * x
for P in J.precs[1:end-1]
y = P * y
end
return y
end
function matvec_T(J::MultiPreconditioner, x)
y = J.precs[1]' * x
for P in J.precs[2:end]
y = P' * y
end
return y
end
conj(I::MultiPreconditioner{TP, T}) where {TP, T} = MultiPreconditioner{TP, T}(conj.(I.precs))
adjoint(I::MultiPreconditioner{TP, T}) where {TP, T} = MultiPreconditioner{TP, T}(adjoint.(reverse(I.precs)))
transpose(I::MultiPreconditioner{TP, T}) where {TP, T} = MultiPreconditioner{TP, T}(transpose.(reverse(I.precs)))
getindex(I::MultiPreconditioner{TP, T}, i) where {TP, T} = MultiPreconditioner{TP, T}([getindex(P, i) for P in I.precs])
for T in [DataPreconditioner, ModelPreconditioner]
@eval *(P1::$(T){DT}, P2::$(T){DT}) where DT = MultiPreconditioner{$(T), DT}([P1, P2])
@eval *(P::$(T){DT}, P2::MultiPreconditioner{$(T), DT}) where DT = MultiPreconditioner{$(T), DT}([P, P2.precs...])
@eval *(P2::MultiPreconditioner{$(T), DT}, P::$(T){DT}) where DT = MultiPreconditioner{$(T), DT}([P2.precs..., P])
end
time_resample(x::MultiPreconditioner{TP, T}, newt) where {TP, T} = MultiPreconditioner{TP, T}([time_resample(P, newt) for P in x.precs])
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
|
[
"MIT"
] | 3.4.7 | 21f9b9ae041be1caba073bb496235bceaa1d2ff0 | code | 2253 | export find_water_bottom
# Taper function. Used for data and model muting
_taper(::Val{:reflection}, n::Integer=20) = convert(Vector{Float32}, (cos.(range(pi, stop=2*pi, length=n)) .+ 1) ./ 2)
_taper(::Val{:turning}, n::Integer=20) = convert(Vector{Float32}, (cos.(range(0, stop=pi, length=n)) .+ 1) ./ 2)
# Muting utils
_yloc(y::Vector{T}, t::Integer) where T = length(y) > 1 ? y[t] : y[1]
radius(G1::Geometry, G2::Geometry, t::Integer) = sqrt.((G1.xloc[1][t] .- G2.xloc[1][1]).^2 .+ (_yloc(G1.yloc[1], t) .- G2.yloc[1][1]).^2 .+ (G1.zloc[1][t] .- G2.zloc[1][1]).^2)
_tapew(i::Integer, taperwidth::Integer, ::Integer, ::Val{:reflection}) = i < taperwidth
_tapew(i::Integer, taperwidth::Integer, nt::Integer, ::Val{:turning}) = i > (nt - taperwidth)
_mutew!(t::AbstractVector{T}, taper::AbstractVector{T}, i::Integer, ::Integer, ::Val{:reflection}) where T = broadcast!(*, t[1:i], t[1:i], taper[end-i+1:end])
_mutew!(t::AbstractVector{T}, taper::AbstractVector{T}, i::Integer, nt::Integer, ::Val{:turning}) where T = broadcast!(*, t[i:nt], t[i:nt], taper[1:(nt-i+1)])
# water bottom
"""
find_water_bottom(v; eps=1e-4)
Fund water bottom based on (x, y) or (x, y, z) input array by finding the first value for each vertical trace that
is not close to the top value (first value such that m[x,y,z] > m[x,y,1] for each x, y)
"""
function find_water_bottom(m::AbstractArray{avDT, N};eps = 1e-4) where {avDT, N}
#return the indices of the water bottom of a seismic image
n = size(m)
idx = zeros(Integer, n[1:end-1])
wbfunc(x, x1) = abs(x - x1) > eps
for i in CartesianIndices(idx)
idx[i] = findfirst(x->wbfunc(x, m[i, 1]), m[i, :])
end
return idx
end
function find_water_bottom(m::AbstractArray{avDT, N}, wbval::Number; inv=true) where {avDT, N}
#return the indices of the water bottom of a seismic image
n = size(m)
idx = zeros(Integer, n[1:end-1])
wbfunc(x) = inv ? x < wbval : x > wbval
for i in CartesianIndices(idx)
idx[i] = findfirst(wbfunc, m[i, :])
end
return idx
end
find_water_bottom(m::PhysicalParameter, wbval::Number; inv=true) = find_water_bottom(m.data, wbval; inv=inv)
find_water_bottom(m::PhysicalParameter;eps=1e-4) = find_water_bottom(m.data; eps=eps)
| JUDI | https://github.com/slimgroup/JUDI.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.