Changing Monte Carlo calculation from VBA code to MATLAB - excel

I am trying to convert this Clausing Factor Monte Carlo calculation code (written in Visual Basic):https://descanso.jpl.nasa.gov/SciTechBook/series1/Goebel_AppG_Clausing.pdf into MATLAB code.
When I try to run this code in Excel, it always returns a consistent value at the first time running. But when I implemented in MATLAB it returns the clausing factor randomly. Could you please help me with the MATLAB code so that it could do the same like in VBA.
The value I am talking about in the VBA code is Range("C11") = (rBottom ^ 2) * iescape / npart
Here are my MATLAB code solve for clausingFactor
thickScreen = 0.5;
thickAccel = 1;
rScreen = 0.8;
rAccel = 0.5;
gridSpace = 1;
npart = 313;
Pi = 3.14159265358979;
%assumes rTop = 1
rBottom = rScreen/rAccel;
lenBottom = (thickScreen + gridSpace)/rAccel;
lenTop = thickAccel / rAccel;
Length = lenTop + lenBottom;
iescape = 0;
maxcount = 0;
icount = 0;
nlost = 0;
vztot = 0;
vz0tot = 0;
for ipart = 1: npart
%launch form bottom
notgone = true;
r0 = rBottom * sqrt(rand());
z0 = 0;
costheta = sqrt(1 - rand());
if (costheta > 0.99999)
costheta = 0.99999;
end
Phi = 2 * Pi * rand();
sintheta = sqrt(1 - costheta);
vx = cos(Phi) * sintheta;
vy = sin(Phi) * sintheta;
vz = costheta;
rf = rBottom;
t = (vx * r0 + sqrt((vx^2 + vy^2) * rf^2 - (vy * r0)^2)) / (vx^2 + vy^2);
z = z0 + vz * t;
vz0tot = vz0tot + vz;
icount = 0;
while notgone
icount = icount +1;
if (z < lenBottom)
%hit wall of bottom cylinder and is re-emitted
r0 = rBottom;
z0 = z;
costheta = sqrt(1-rand());
if (costheta > 0.99999)
costheta = 0.99999;
end
Phi = 2 * Pi * rand();
sintheta = sqrt(1 - costheta^2);
vz = cos(Phi) * sintheta;
vy = sin(Phi) * sintheta;
vx = costheta;
rf = rBottom;
t = (vx * r0 + sqrt((vx^2 + vy^2) * rf^2 - (vy * r0)^2)) / (vx^2 + vy^2);
z = z0 + t * vz;
end %bottom cylinder re-emission
if ((z >= lenBottom) && (z0 < lenBottom))
%emitted below but going up
%find radius at lenBottom
t = (lenBottom - z0) / vz;
r = sqrt((r0 - vx * t)^2 + (vy * t)^2);
if (r <= 1)
%continuing upward
rf = 1;
t = (vx * r0 + sqrt((vx^2 + vy^2) * rf^2 - (vy * r0)^2)) / (vx^2 + vy^2);
z = z0 + vz*t;
else
% hit the upstram side of the accel grid and is
% re-emitted downward
r0 = r;
z0 = lenBottom;
costheta = sqrt(1 - rand());
if (costheta > 0.99999)
costheta = 0.99999;
end
Phi = 2 * Pi * rand();
sintheta = sqrt(1 - costheta^2);
vz = cos(Phi) * sintheta;
vy = sin(Phi) * sintheta;
vx = costheta;
rf = rBottom;
t = (vx * r0 + sqrt((vx^2 + vy^2) * rf^2 - (vy * r0)^2)) / (vx^2 + vy^2);
z = z0 + t * vz;
end
end %end upward
if ((z >= lenBottom) && (z<= Length))
%hit the upper cylinder wall and is re-emitted
r0 = 1;
z0 = z;
costheta = sqrt(1 - rand());
if (costheta > 0.99999)
costheta = 0.99999;
end
Phi = 2 * Pi * rand();
sintheta = sqrt(1 - costheta^2);
vz = cos(Phi) * sintheta;
vy = sin(Phi) * sintheta;
vx = costheta;
rf = 1;
t = (vx * r0 + sqrt((vx^2 + vy^2) * rf^2 - (vy * r0)^2)) / (vx^2 + vy^2);
z = z0 + t * vz;
if (z < lenBottom)
%find z when particle hits the bottom cylinder
rf = rBottom;
if ((vx^2 + vy^2) * rf^2 - (vy * r0)^2 < 0 )
t = (vx * r0) / (vx^2 + vy^2);
%if sqrt argument is less than 0 then set sqr term
%to 0 12 May 2004
else
t = (vx * r0 + sqrt((vx^2 + vy^2) * rf^2 - (vy * r0)^2)) / (vx^2 + vy^2);
end
z = z0 + vz * t;
end
end %end upper cylinder emission
if (z < 0)
notgone = false;
end
if (z > Length)
iescape = iescape + 1;
vztot = vztot + vz;
notgone = false;
end
if (icount > 1000)
notgone = false;
icount = 0;
nlost = nlost + 1;
end
end
if (maxcount < icount)
maxcount = icount;
end
end
clausingFactor = (rBottom^2) * iescape / npart;
vz0av = vz0tot / npart;
vzav = vztot / iescape;
DenCor = vz0av / vzav;
Thank you.

Related

How to calculate coordinates of 6 point of intersection between a circle and a equilateral triangle?

I know of an equilateral triangle the center (cx,cy) and the radius (r) of a blue circle which circumscribed it.
If I draw a green circle of any radius (radius), assuming the circle is large enough to have this intersection, can I get the coordinates of the 6 intersection points (P1, P2, P3...)?
I'm looking for P5JS/processing but any other clue can help me...
Thank you in advance
Distance from the center to top point is r.
Distance from the center to the lowest triangle side is r/2 (median intersection point is center, they are divided in 1:2 ratio).
Horizontal distance from cx to p4 (and p5) is (Pythagoras' theorem)
dx = sqrt(radius^2 - r^2/4)
So coordinates of p4 and p5 are (relative to center)
p4x = dx
p4y = r/2
p5x = -dx
p5y = r/2
Other points might be calculated using rotation by 120 degrees
p2x = p4x*(-1/2) - p4y*(sqrt(3)/2)
p2y = p4x*(sqrt(3)/2) + p4y*(-1/2)
and so on.
And finally add cx,cy to get absolute coordinates
If you want to test... ;-)
function setup() {
createCanvas(500, 500);
const cx = width / 2;
const cy = height / 2;
const r = 250; // taille du triangle
const radius = 180; // externe
noFill();
strokeWeight(3);
stroke(0, 0, 0);
drawTriangle(cx, cy, r);
strokeWeight(1);
stroke(0, 0, 255);
circle(cx, cy, r * 2);
strokeWeight(2);
stroke(8, 115, 0);
circle(cx, cy, radius * 2);
noStroke();
fill(215, 0, 0);
// dx = sqrt(Math.pow(r / 2, 2) - Math.pow(r / 2, 2 / 4));
dx = sqrt(radius * radius - (r * r) / 4);
p4x = dx;
p4y = r / 2;
circle(cx + p4x, cy + p4y, 20);
text("p4", cx + p4x, cy + p4y + 30);
p5x = -dx;
p5y = r / 2;
circle(cx + p5x, cy + p5y, 20);
text("p5", cx + p5x - 10, cy + p5y + 30);
p6x = p4x * (-1 / 2) - p4y * (sqrt(3) / 2);
p6y = p4x * (sqrt(3) / 2) + p4y * (-1 / 2);
circle(cx + p6x, cy + p6y, 20);
text("p6", cx + p6x - 30, cy + p6y);
p2x = p6x * (-1 / 2) - p6y * (sqrt(3) / 2);
p2y = p6x * (sqrt(3) / 2) + p6y * (-1 / 2);
circle(cx + p2x, cy + p2y, 20);
text("p2", cx + p2x + 10, cy + p2y - 10);
p1x = p5x * (-1 / 2) - p5y * (sqrt(3) / 2);
p1y = p5x * (sqrt(3) / 2) + p5y * (-1 / 2);
circle(cx + p1x, cy + p1y, 20);
text("p1", cx + p1x - 20, cy + p1y - 10);
p3x = p1x * (-1 / 2) - p1y * (sqrt(3) / 2);
p3y = p1x * (sqrt(3) / 2) + p1y * (-1 / 2);
circle(cx + p3x, cy + p3y, 20);
text("p3", cx + p3x + 20, cy + p3y - 10);
noFill();
stroke(0, 255, 255);
triangle(cx + p2x, cx + p2y, cx + p4x, cx + p4y, cx + p6x, cx + p6y);
stroke(255, 0, 255);
// prettier-ignore
triangle(
cx + p1x, cx + p1y,
cx + p3x, cx + p3y,
cx + p5x, cx + p5y,
)
}
function drawTriangle(cx, cy, radius) {
noFill();
trianglePoints = [];
for (var i = 0; i < 3; i++) {
var x = cx + radius * cos((i * TWO_PI) / 3.0 - HALF_PI);
var y = cy + radius * sin((i * TWO_PI) / 3.0 - HALF_PI);
trianglePoints[i] = {
x,
y,
};
}
triangle(
trianglePoints[0].x,
trianglePoints[0].y,
trianglePoints[1].x,
trianglePoints[1].y,
trianglePoints[2].x,
trianglePoints[2].y
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script>

AttributeError: 'IAPWS97' object has no attribute 'rho'

I am trying to run this loop; however, I am getting a no attribute error in the second portion of my code. Below is the entire code (sorry for the length). When I run the first case (PWR) the code executes normally as expected. However, when I run the second case (BWR) I receive the error even though it is the same exact statement from case one. Is there any fix or explanation for this? Thank you.
import numpy as np
import math
from iapws import IAPWS97
import matplotlib.pyplot as plt
case = int(input('Which case [1 (PWR) or 2 (BWR)]? '))
if case == 1: # PWR
H = 3.8 # m
He = 3.8 # m
Pitch = 1.25 * 10 ** (-2) # m
Gap_t = 0.00006 # m
D_fuel = 0.0082 # m
k_gap = 0.25 # W/m-K
k_c = 21.5 # W/m-K
k_fuel = 3.6 # W/m-K
T0 = float(278 + 273.15) # K
q0_prime = float(330 * 10 ** (2)) # W/m
P0 = 15 # MPa
MF = float(3460) # kg/m^2-s
D_rod = .0095 # m
R_rod = D_rod / 2
R_fuel = D_fuel / 2
R_gap = R_fuel + Gap_t
R_clad = R_rod
Clad_t = D_rod - D_fuel - Gap_t # m
h0_enthalpy = (IAPWS97(T=T0, P=P0).h) * 10 ** (3)
T_sat0 = IAPWS97(P=P0, x=0).T
g = 9.81 # m/s
# geometry properties
heated_p = math.pi * D_rod
wetted_p = math.pi * D_rod
A_f = (Pitch ** 2) - ((1 / 4) * math.pi * (D_rod ** 2))
D_H = (4 * A_f) / heated_p
# grid setup
grid_points = 100
dz = H / grid_points
z_array = np.arange(0, H, dz)
z_arrayplots = np.arange(0, H, dz)
q_HeatFluxList = []
# defining array of q'' values in list
for z in z_array:
heat_fluxA = (q0_prime / (math.pi * D_rod)) * math.sin(math.pi * (z / He))
q_HeatFluxList.append(heat_fluxA)
q_heat_flux = np.array(q_HeatFluxList)
q_prime = np.zeros(len(z_array))
for i in range(0, len(z_array)):
q_prime[i] = q0_prime * math.sin((np.pi * z_array[i]) / He)
# defining array of h values
h_enthalpy_list = []
h_enthalpy_prefactor = ((heated_p * q0_prime * H) / (A_f * MF * (math.pi ** 2) * D_rod))
for z in z_array:
h_enthalpy = (-h_enthalpy_prefactor * math.cos(math.pi * (z / He))) + h_enthalpy_prefactor + h0_enthalpy
h_enthalpy_list.append(h_enthalpy)
h_enthalpy_array_J = np.array(h_enthalpy_list)
h_enthalpy_array = h_enthalpy_array_J * 10 ** (-3)
P_array = np.zeros(len(z_array))
P_array[0] = P0
T_sat = np.zeros(len(z_array))
T_sat[0] = T_sat0
T_f_array = np.zeros(len(z_array))
T_f_array[0] = T0
Re = np.zeros(len(z_array))
Re_f = np.zeros(len(z_array))
Pr = np.zeros(len(z_array))
k_fluid = np.zeros(len(z_array))
x_array = np.zeros(len(z_array))
xe_array = np.zeros(len(z_array))
frictional = np.zeros(len(z_array))
gravitational = np.zeros(len(z_array))
compressibility = np.zeros(len(z_array))
# Pressure Loop PWR
dp = 0.001
for i in range(0, len(z_array) - 1):
rho_f = IAPWS97(P=P_array[i], x=0).rho
vf = IAPWS97(P=P_array[i], x=0).v
vg = IAPWS97(P=P_array[i], x=1).v
hf_enthalpy = IAPWS97(P=P_array[i], x=0).h
hg_enthalpy = IAPWS97(P=P_array[i], x=1).h
muf = (IAPWS97(P=P_array[i], x=0).mu) * 10 ** (-6)
mug = (IAPWS97(P=P_array[i], x=1).mu) * 10 ** (-6)
k_fluid[i] = IAPWS97(P=P_array[i], T=T_f_array[i]).k
Pr[i] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
x_array[i] = 0
xe_array[i] = (h_enthalpy_array[i] - hf_enthalpy) / (hg_enthalpy - hf_enthalpy)
rho_m = 1 / ((x_array[i] * vg) + ((1 - x_array[i]) * vf))
mu_m = 1 / ((x_array[i] / mug) + ((1 - x_array[i]) / muf))
Re[i] = (MF * D_H) / (mu_m * 10 ** 6) # convert mu to Pa/s
f = 0.079 * (Re[i] ** -0.25) * (mu_m / muf)
Tau = (1 / 2) * f * ((MF ** 2) / rho_m)
Re_f[i] = Re[i]
vf_plus_dP = IAPWS97(P=P_array[i] + dp, x=0).v
vf_minus_dP = IAPWS97(P=P_array[i] - dp, x=0).v
ddP_vf = (vf_plus_dP - vf_minus_dP) / (2 * (dp * 10 ** 6))
frictional[i] = (Tau * wetted_p) / A_f
gravitational[i] = g * rho_f
compressibility[i] = (MF ** 2) * (ddP_vf)
dPdz_num = (frictional[i] + gravitational[i]) # Pa/m
dPdz_denom = 1 + compressibility[i] # Pa/m
dPdz = -dPdz_num / dPdz_denom # Pa/m
P_array[i + 1] = P_array[i] + ((dPdz * dz) * 10 ** (-6))
T_f_array[i + 1] = IAPWS97(P=P_array[i + 1], h=h_enthalpy_array[i + 1]).T
T_sat[i + 1] = IAPWS97(P=P_array[i + 1], x=0).T
# final calc for final value of quality and void fraction because loop stops before these
hf_final = IAPWS97(P=P_array[-1], x=0).h
hg_final = IAPWS97(P=P_array[-1], x=1).h
muf_final = (IAPWS97(P=P_array[-1], x=0).mu) * 10 ** (-6)
mug_final = (IAPWS97(P=P_array[-1], x=1).mu) * 10 ** (-6)
k_fluid[-1] = IAPWS97(P=P_array[-1], T=T_f_array[-1]).k
xe_array[-1] = (h_enthalpy_array[-1] - hf_final) / (hg_final - hf_final)
# fuel and clad temps
T_C_Outer = np.zeros(len(z_array))
mu_m_final = 1 / ((x_array[-1] / mug_final) + ((1 - x_array[-1]) / muf_final))
Re_f[-1] = (MF * D_H) / (muf_final * 10 ** 6)
Pr[-1] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
h_HT = 0.023 * (Re_f[0] ** 0.8) * (Pr[0] ** 0.4) * (k_fluid[0] / D_H)
T_C_Outer[0] = (q_heat_flux[0] + (h_HT * T_f_array[0])) / h_HT
for i in range(0, len(z_array) - 1):
h_HT = 0.023 * (Re_f[i + 1] ** 0.8) * (Pr[i + 1] ** 0.4) * (k_fluid[i + 1] / D_H)
T_C_Outer[i + 1] = (q_heat_flux[i + 1] + (h_HT * T_f_array[i + 1])) / h_HT
q_triple_prime = (q_prime * 4) / (np.pi * (D_fuel ** 2))
T_C_Inner = np.zeros(len(z_array))
T_F_Outer = np.zeros(len(z_array))
T_F_Center = np.zeros(len(z_array))
for i in range(0, len(z_array)):
C1 = -((q0_prime * R_clad) / (k_c * heated_p)) * np.sin(np.pi * (z_array[i] / H))
C2 = T_C_Outer[i] - (C1 * np.log(R_clad))
T_C_Inner[i] = (C1 * np.log(R_gap)) + C2
C3 = (k_c / k_gap) * C1
C4 = T_C_Inner[i] - (C3 * np.log(R_gap))
T_F_Outer[i] = (C3 * np.log(R_fuel)) + C4
C6 = T_F_Outer[i] + ((q_triple_prime[i] * (R_fuel ** 2)) / (4 * k_fuel))
T_F_Center[i] = C6
CL_max = np.amax(T_F_Center)
index = np.where(T_F_Center == CL_max)
z_CL_max = z_array[index]
Clad_max = np.amax(T_C_Inner)
index = np.where(T_C_Inner == Clad_max)
z_Clad_max = z_array[index]
plt.figure(1)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempClad.png", dpi=600)
plt.figure(2)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuelAndClad.png", dpi=600)
# radial calcs
T_array_A = [T_F_Center[25], T_F_Outer[25], T_C_Inner[25], T_C_Outer[25]]
T_array_B = [T_F_Center[49], T_F_Outer[49], T_C_Inner[49], T_C_Outer[49]]
T_array_C = [T_F_Center[53], T_F_Outer[53], T_C_Inner[53], T_C_Outer[53]]
r_array = [0, R_fuel, R_gap, R_clad]
plt.figure(3)
plt.plot(r_array, T_array_A, label='z = -H/4 = -0.9 m')
plt.plot(r_array, T_array_B, label='z = 0 m')
plt.plot(r_array, T_array_C, '--', label='z = zmax = 0.108 m')
plt.legend(loc='upper left')
plt.ylabel("Temperature [K]")
plt.xlabel("Radius r [m]")
plt.savefig("TempRadial.png", dpi=600)
# critical heat flux and DNBR
P_array_DNBR = np.delete(P_array, 0)
q_heat_flux_DNBR = np.delete(q_heat_flux, 0)
z_arrayplots_DNBR = np.delete(z_arrayplots, 0)
G_Mlbs = MF * (((2.20462 * 10 ** (-6)) * 3600) / 10.7639)
q_heat_flux_MBtu = q_heat_flux[1:] * 3.41 * (1 / 1000000) * (1 / 10.7639)
P_c = 22.064 # https://nuclearstreet.com/nuclear-power-plants/w/nuclear_power_plants/features-of-pressurized-water-reactors
P_crit = P_array_DNBR / P_c
P1 = 0.5328
P2 = 0.1212
P3 = 1.6151
P4 = 1.4066
P5 = -0.3040
P6 = 0.4843
P7 = -0.3285
P8 = -2.0749
A = P1 * (P_crit ** P2) * (G_Mlbs ** (P5 + (P7 * P_crit)))
C = P3 * (P_crit ** P4) * (G_Mlbs ** (P6 + (P8 * P_crit)))
q_crit_heat_flux_MBtu = (A - xe_array[0]) / (C + ((xe_array[1:] - xe_array[0]) / q_heat_flux_MBtu))
q_crit_heat_flux = q_crit_heat_flux_MBtu * (1 / 3.41) * 1000000 * 10.7639
DNBR = q_crit_heat_flux / q_heat_flux_DNBR
plt.figure(4)
plt.plot(DNBR, z_arrayplots_DNBR)
plt.xlabel("Departure from Nucleate Boiling Ratio")
plt.ylabel("Height z [m]")
plt.savefig("DNBR.png", dpi=600)
plt.figure(5)
plt.plot(P_array, z_arrayplots)
plt.xlabel('Pressure [MPa]')
plt.ylabel('Height z [m]')
plt.savefig("Pressure.png", dpi=600)
plt.figure(6)
plt.plot(T_f_array, z_arrayplots)
plt.xlabel('Temperature [K]')
plt.ylabel('Height z [m]')
plt.savefig("TempBulk.png", dpi=600)
plt.figure(7)
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuel.png", dpi=600)
tempdifference = T_C_Outer - T_f_array
print("Max clad vs bulk difference is " + str(np.amax(tempdifference)) + " K")
print("Max coolant temp is " + str(np.amax(T_f_array)) + " K")
print("Min coolant temp is " + str(np.amin(T_f_array)) + " K")
print("Max clad inner temp is " + str(np.amax(T_C_Inner)) + " K")
print("Max clad outer temp is " + str(np.amax(T_C_Outer)) + " K")
print("min clad outer temp is " + str(np.amin(T_C_Outer)) + " K")
print("Max fuel temp is " + str(np.amax(T_F_Center)) + " K")
print("Max fuel outer temp is " + str(np.amax(T_F_Outer)) + " K")
print("Min fuel outer temp is " + str(np.amin(T_F_Outer)) + " K")
print("Max centerline temp occurs at z = " + str(z_CL_max) + "m")
print("Max clad temp occurs at z = " + str(z_Clad_max) + "m")
MDNBR = np.amin(DNBR)
print("MDNBR is " + str(MDNBR))
plt.show()
if case == 2: # BWR
H = 3.8 # m
He = 3.8 # m
Pitch = 1.63 * 10 ** (-2) # m
Gap_t = 0.0001 # m
D_fuel = 0.0104 # m
k_gap = 0.25 # W/m-K
k_c = 21.5 # W/m-K
k_fuel = 3.6 # W/m-K
T0 = float(274 + 273.15) # K
q0_prime = float(410 * 10 ** (2)) # W/m
P0 = 7.5 # MPa
MF = float(2290) # kg/m^2-s
D_rod = .0123 # m
R_rod = D_rod / 2
R_fuel = D_fuel / 2
R_gap = R_fuel + Gap_t
R_clad = R_rod
Clad_t = D_rod - D_fuel - Gap_t # m
h0_enthalpy = (IAPWS97(T=T0, P=P0).h) * 10 ** (3)
T_sat0 = IAPWS97(P=P0, x=0).T
g = 9.81 # m/s
# geometry properties
heated_p = math.pi * D_rod
wetted_p = math.pi * D_rod
A_f = (Pitch ** 2) - ((1 / 4) * math.pi * (D_rod ** 2))
D_H = (4 * A_f) / heated_p
# grid setup
grid_points = 100
dz = H / grid_points
z_array = np.arange(0, H, dz)
z_arrayplots = np.arange(-H / 2, H / 2, dz)
q_HeatFluxList = []
# defining array of q'' values in list
for z in z_array:
heat_fluxA = (q0_prime / (math.pi * D_rod)) * math.sin(math.pi * (z / He))
q_HeatFluxList.append(heat_fluxA)
q_heat_flux = np.array(q_HeatFluxList)
q_prime = np.zeros(len(z_array))
for i in range(0, len(z_array)):
q_prime[i] = q0_prime * math.sin((np.pi * z_array[i]) / He)
# defining array of h values
h_enthalpy_list = []
h_enthalpy_prefactor = ((heated_p * q0_prime * H) / (A_f * MF * (math.pi ** 2) * D_rod))
for z in z_array:
h_enthalpy = (-h_enthalpy_prefactor * math.cos(math.pi * (z / He))) + h_enthalpy_prefactor + h0_enthalpy
h_enthalpy_list.append(h_enthalpy)
h_enthalpy_array_J = np.array(h_enthalpy_list)
h_enthalpy_array = h_enthalpy_array_J * 10 ** (-3)
P_array = np.zeros(len(z_array))
P_array[0] = P0
T_sat = np.zeros(len(z_array))
T_sat[0] = T_sat0
T_f_array = np.zeros(len(z_array))
T_f_array[0] = T0
Re = np.zeros(len(z_array))
Re_f = np.zeros(len(z_array))
Pr = np.zeros(len(z_array))
k_fluid = np.zeros(len(z_array))
x_array = np.zeros(len(z_array))
xe_array = np.zeros(len(z_array))
dxe_array = np.zeros(len(z_array))
frictional = np.zeros(len(z_array))
gravitational = np.zeros(len(z_array))
compressibility = np.zeros(len(z_array))
alpha_array = np.zeros(len(z_array))
# Pressure Loop BWR
dp = 0.001
for i in range(0, len(z_array) - 1):
rho_f = IAPWS97(P=P_array[i], x=0).rho
rho_m = IAPWS97(P=P_array[i], x=xe_array[i]).rho
vf = IAPWS97(P=P_array[i], x=0).v
vg = IAPWS97(P=P_array[i], x=1).v
vfg = vg - vf
hf_enthalpy = IAPWS97(P=P_array[i], x=0).h
hg_enthalpy = IAPWS97(P=P_array[i], x=1).h
hfg = hg_enthalpy - hf_enthalpy
hfg_sat = IAPWS97(P=P0, x=1).h - IAPWS97(P=P0, x=0).h
# vf = IAPWS97(P=P_array[i], x=0).v
# vg_sat = IAPWS97(P=P_array[i], x=1).v
hf_in = IAPWS97(P=P0, T=T0).h
muf = (IAPWS97(P=P_array[i], x=0).mu) * 10 ** (-6)
mum = (IAPWS97(P=P_array[i], x=xe_array[i]).mu) * 10 ** (-6)
mug = (IAPWS97(P=P_array[i], x=1).mu) * 10 ** (-6)
k_fluid[i] = IAPWS97(P=P_array[i], T=T_f_array[i]).k
Pr[i] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
xe_in = (hf_in - hf_enthalpy) / (hfg)
vf_sat = IAPWS97(P=P_array[i], x=xe_array[i])
# vapor quality
if xe_array[i] <= 0: # single phase
Re1p = MF * D_rod / muf
f1p = 0.316 * Re1p ** (-.25)
dp = -(.5 * f1p * MF * 2 * heated_p / (rho_f * A_f) + g / rho_f) * dz
x_array[i] = 0
dxe_array[i] = q0_prime * np.sin(np.pi * z_array[i] / H) / (MF * A_f * hfg_sat) * dz
xe_array = xe_array[i - 1] + dxe_array[i]
# P_array[i]=P[i-1]+dp1p
elif xe_array[i] > 0 and xe_array[i] < 1: # 2 phase
Re2p = MF * D_rod / mum
f2p = 0.046 * Re2p ** (-.2) * (muf / mum ** (-.2))
dp2p = (-MF ** 2 * vfg * dxe_array[i] + .5 * f2p * MF ** 2 * heated_p / (rho_m * A_f) + g * rho_m) * dz
xe_array[i] = (h_enthalpy_array[i] - hf_enthalpy) / (hg_enthalpy - hf_enthalpy)
# Void Fraction
if xe_array[i] <= 0:
alpha_array[0]
elif xe_array[i] > 0 and xe_array[i] < 1:
x_array[i] = xe_array[i]
vfg_sat = vg - vf
rho_m = (vf_sat + vfg_sat * x_array) ** (-1)
rhof = 1 / vf
rhog = 1 / vg
void = (rho_m - rhof) / (rhog - rhof)
alpha_array[void]
print("Void fraction is " + str(np.amax(alpha_array)))
if xe_array[i] <= 0:
alpha_array[0]
elif xe_array[i] > 0 and xe_array[i] < 1:
x_array[i] = xe_array[i]
vfg_sat = vg - vf
rho_m = (vf_sat + vfg_sat * x_array) ** (-1)
rhof = 1 / vf
rhog = 1 / vg
void = (rho_m - rhof) / (rhog - rhof)
alpha_array[void]
print("Void fraction is " + str(np.amax(alpha_array)))
rho_m = 1 / ((x_array[i] * vg) + ((1 - x_array[i]) * vf))
mu_m = 1 / ((x_array[i] / mug) + ((1 - x_array[i]) / muf))
Re[i] = (MF * D_H) / (mu_m * 10 ** 6) # convert mu to Pa/s
f = 0.079 * (Re[i] ** -0.25) * (mu_m / muf)
Tau = (1 / 2) * f * ((MF ** 2) / rho_m)
Re_f[i] = Re[i]
vf_plus_dP = IAPWS97(P=P_array[i] + dp, x=xe_array[i]).v
vf_minus_dP = IAPWS97(P=P_array[i] - dp, x=xe_array[i]).v
ddP_vf = (vf_plus_dP - vf_minus_dP) / (2 * (dp * 10 ** 6))
frictional[i] = (Tau * wetted_p) / A_f
gravitational[i] = g * rho_f
compressibility[i] = (MF ** 2) * (ddP_vf)
dPdz_num = (frictional[i] + gravitational[i]) # Pa/m
dPdz_denom = 1 + compressibility[i] # Pa/m
dPdz = -dPdz_num / dPdz_denom # Pa/m
P_array[i + 1] = P_array[i] + ((dPdz * dz) * 10 ** (-6))
T_f_array[i + 1] = IAPWS97(P=P_array[i + 1], h=h_enthalpy_array[i + 1]).T
T_sat[i + 1] = IAPWS97(P=P_array[i + 1], x=0).T
# final calc for final value of quality and void fraction because loop stops before these
hf_final = IAPWS97(P=P_array[-1], x=0).h
hg_final = IAPWS97(P=P_array[-1], x=1).h
muf_final = (IAPWS97(P=P_array[-1], x=0).mu) * 10 ** (-6)
mug_final = (IAPWS97(P=P_array[-1], x=1).mu) * 10 ** (-6)
k_fluid[-1] = IAPWS97(P=P_array[-1], T=T_f_array[-1]).k
xe_array[-1] = (h_enthalpy_array[-1] - hf_final) / (hg_final - hf_final)
# fuel and clad temps
T_C_Outer = np.zeros(len(z_array))
mu_m_final = 1 / ((x_array[-1] / mug_final) + ((1 - x_array[-1]) / muf_final))
Re_f[-1] = (MF * D_H) / (muf_final * 10 ** 6)
Pr[-1] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
h_HT = 0.023 * (Re_f[0] ** 0.8) * (Pr[0] ** 0.4) * (k_fluid[0] / D_H)
T_C_Outer[0] = (q_heat_flux[0] + (h_HT * T_f_array[0])) / h_HT
for i in range(0, len(z_array) - 1):
h_HT = 0.023 * (Re_f[i + 1] ** 0.8) * (Pr[i + 1] ** 0.4) * (k_fluid[i + 1] / D_H)
T_C_Outer[i + 1] = (q_heat_flux[i + 1] + (h_HT * T_f_array[i + 1])) / h_HT
q_triple_prime = (q_prime * 4) / (np.pi * (D_fuel ** 2))
T_C_Inner = np.zeros(len(z_array))
T_F_Outer = np.zeros(len(z_array))
T_F_Center = np.zeros(len(z_array))
for i in range(0, len(z_array)):
C1 = -((q0_prime * R_clad) / (k_c * heated_p)) * np.sin(np.pi * (z_array[i] / H))
C2 = T_C_Outer[i] - (C1 * np.log(R_clad))
T_C_Inner[i] = (C1 * np.log(R_gap)) + C2
C3 = (k_c / k_gap) * C1
C4 = T_C_Inner[i] - (C3 * np.log(R_gap))
T_F_Outer[i] = (C3 * np.log(R_fuel)) + C4
C6 = T_F_Outer[i] + ((q_triple_prime[i] * (R_fuel ** 2)) / (4 * k_fuel))
T_F_Center[i] = C6
CL_max = np.amax(T_F_Center)
index = np.where(T_F_Center == CL_max)
z_CL_max = z_array[index]
plt.figure(1)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempCladBWR.png", dpi=600)
plt.figure(2)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuelAndCladBWR.png", dpi=600)
# radial calcs
T_array_A = [T_F_Center[25], T_F_Outer[25], T_C_Inner[25], T_C_Outer[25]]
T_array_B = [T_F_Center[49], T_F_Outer[49], T_C_Inner[49], T_C_Outer[49]]
T_array_C = [T_F_Center[53], T_F_Outer[53], T_C_Inner[53], T_C_Outer[53]]
r_array = [0, R_fuel, R_gap, R_clad]
plt.figure(3)
plt.plot(r_array, T_array_A, label='z = -H/4 = -0.9 m')
plt.plot(r_array, T_array_B, label='z = 0 m')
plt.plot(r_array, T_array_C, '--', label='z = zmax = 0.108 m')
plt.legend(loc='upper left')
plt.ylabel("Temperature [K]")
plt.xlabel("Radius r [m]")
plt.savefig("TempRadialBWR.png", dpi=600)
# critical heat flux and DNBR
P_array_DNBR = np.delete(P_array, 0)
q_heat_flux_DNBR = np.delete(q_heat_flux, 0)
z_arrayplots_DNBR = np.delete(z_arrayplots, 0)
G_Mlbs = MF * (((2.20462 * 10 ** (-6)) * 3600) / 10.7639)
q_heat_flux_MBtu = q_heat_flux[1:] * 3.41 * (1 / 1000000) * (1 / 10.7639)
P_c = 22.064 # https://nuclearstreet.com/nuclear-power-plants/w/nuclear_power_plants/features-of-pressurized-water-reactors
P_crit = P_array_DNBR / P_c
P1 = 0.5328
P2 = 0.1212
P3 = 1.6151
P4 = 1.4066
P5 = -0.3040
P6 = 0.4843
P7 = -0.3285
P8 = -2.0749
A = P1 * (P_crit ** P2) * (G_Mlbs ** (P5 + (P7 * P_crit)))
C = P3 * (P_crit ** P4) * (G_Mlbs ** (P6 + (P8 * P_crit)))
q_crit_heat_flux_MBtu = (A - xe_array[0]) / (C + ((xe_array[1:] - xe_array[0]) / q_heat_flux_MBtu))
q_crit_heat_flux = q_crit_heat_flux_MBtu * (1 / 3.41) * 1000000 * 10.7639
DNBR = q_crit_heat_flux / q_heat_flux_DNBR
plt.figure(4)
plt.plot(DNBR, z_arrayplots_DNBR)
plt.xlabel("Onset of Nucleate Boiling Ratio")
plt.ylabel("Height z [m]")
plt.title("Onset of Nucleate Boiling Ratio versus Height")
plt.savefig("ONBR.png", dpi=600)
plt.figure(5)
plt.plot(P_array, z_arrayplots)
plt.xlabel('Pressure [MPa]')
plt.ylabel('Height z [m]')
plt.title('Pressure versus Height')
plt.savefig("PressureBWR.png", dpi=600)
plt.figure(6)
plt.plot(T_f_array, z_arrayplots)
plt.xlabel('Temperature [K]')
plt.ylabel('Height z [m]')
plt.title('Coolant Temperature vs Height')
plt.savefig("TempBulkBWR.png", dpi=600)
plt.figure(7)
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuelBWR.png", dpi=600)
# density
plt.figure(8)
plt.plot(Density, z_arrayplots, label='Density')
plt.legend(loc='upper left')
plt.xlabel("Pressure [mPa]")
plt.ylabel("Height z [m]")
plt.savefig("Density", dpi=600)
# quality
plt.figure(9)
plt.plot(x, z_arrayplots, label='Quality')
plt.plot(xe, z_arrayplots, label='Quality')
plt.legend(loc='upper left')
plt.xlabel("Quality")
plt.ylabel("Height z [m]")
plt.savefig("Quality", dpi=600)
# void
plt.figure(10)
plt.plot(alpha, z_arrayplots, label='Void Fraction')
plt.legend(loc='upper left')
plt.xlabel("Void Fraction")
plt.ylabel("Height z [m]")
plt.savefig("Void Fraction", dpi=600)
tempdifference = T_C_Outer - T_f_array
print("Max clad vs bulk difference is " + str(np.amax(tempdifference)) + " C")
print("Max coolant temp is " + str(np.amax(T_f_array) - 273.15) + " C")
print("Max coolant temp is " + str(np.amax(T_f_array)) + " K")
print("Max clad temp is " + str(np.amax(T_C_Inner) - 273.15) + " C")
print("Max clad temp is " + str(np.amax(T_C_Inner)) + " K")
print("Max fuel temp is " + str(np.amax(T_F_Center) - 273.15) + " C")
print("Max fuel temp is " + str(np.amax(T_F_Center)) + " K")
print("Max fuel temp is " + str(np.amax(T_F_Outer) - 273.15) + " C")
print("Max fuel temp is " + str(np.amax(T_F_Outer)) + " K")
print("Max centerline temp occurs at z = " + str(z_CL_max) + "m")
MDNBR = np.amin(DNBR)
print("MDNBR is " + str(MDNBR))

Converting SVG to Three.js path

Trying to use the sample SVG parsing code demonstrated at https://threejs.org/examples/#webgl_geometry_extrude_shapes2. It does not properly support the 'a' path command. I've made a few corrections found in https://gist.github.com/IkarosKappler/d3c39db08115085bcb18 and a few of my own referencing https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes, but still am coming up wrong.
Here's a sample with the original SVG shown.
https://codepen.io/matelich/pen/rKzXZV
Since stack wants code here, this is the code that incorrectly parses and interprets A and a paths:
// - elliptical arc
case "A":
case "a":
rx = eatNum();
ry = eatNum();
xar = eatNum() * DEGS_TO_RADS;
laf = eatNum(); //large arc flag
sf = eatNum(); //sweep flag
nx = eatNum();
ny = eatNum();
if (activeCmd == "a") {
// relative
nx += x;
ny += y;
}
if(rx != 0 && ry != 0) {
console.debug(
"Read arc params: rx=" + rx + ", ry=" + ry + ", xar=" + xar + ", laf=" + laf + ", sf=" + sf + ", nx=" + nx + ", ny=" + ny
);
//might need to bring this back if absellipse doesn't work
//if (rx !== ry)
// console.warn("Forcing elliptical arc to be a circular one :(", rx, ry);
// SVG implementation notes does all the math for us! woo!
// http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
// step1, using x1 as x1'
x1 = Math.cos(xar) * (x - nx) / 2 + Math.sin(xar) * (y - ny) / 2;
y1 = -Math.sin(xar) * (x - nx) / 2 + Math.cos(xar) * (y - ny) / 2;
// step 2, using x2 as cx'
console.debug( "TMP x1=" + x1 + ", y1=" + y1 + ", (rx*rx * y1*y1 + ry*ry * x1*x1)=" + (rx * rx * y1 * y1 + ry * ry * x1 * x1) + ", (rx*rx * ry*ry - rx*rx * y1*y1 - ry*ry * x1*x1)=" + (rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1));
var norm = Math.sqrt(
Math.abs(
(rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1) /
(rx * rx * y1 * y1 + ry * ry * x1 * x1)
)
);
if (laf === sf) norm = -norm;
x2 = norm * rx * y1 / ry;
y2 = norm * -ry * x1 / rx;
console.debug("TMP norm=" + norm + ", x2=" + x2 + ", y2=" + y2);
// step 3
cx = Math.cos(xar) * x2 - Math.sin(xar) * y2 + (x + nx) / 2;
cy = Math.sin(xar) * x2 + Math.cos(xar) * y2 + (y + ny) / 2;
console.debug("TMP cx=" + cx + ", cy=" + cy);
var u = new THREE.Vector2(1, 0),
v = new THREE.Vector2((x1 - x2) / rx, (y1 - y2) / ry);
var startAng = Math.acos(u.dot(v) / u.length() / v.length());
if (u.x * v.y - u.y * v.x < 0) startAng = -startAng;
// we can reuse 'v' from start angle as our 'u' for delta angle
u.x = (-x1 - x2) / rx;
u.y = (-y1 - y2) / ry;
var deltaAng = Math.acos(v.dot(u) / v.length() / u.length());
// This normalization ends up making our curves fail to triangulate...
if (u.x * v.y - u.y * v.x < 0) deltaAng = -deltaAng;
if (!sf && deltaAng > 0) deltaAng -= Math.PI * 2;
if (sf && deltaAng < 0) deltaAng += Math.PI * 2;
console.debug(
"Building arc from values: cx=" + cx + ", cy=" + cy + ", startAng=" + startAng + ", deltaAng=" + deltaAng + ", endAng=" + (startAng + deltaAng) + ", sweepFlag=" + sf );
// path.absarc(cx, cy, rx, startAng, startAng + deltaAng, sf);
path.absellipse(cx, cy, rx, ry, startAng, startAng + deltaAng, sf);
} else {
path.lineTo(nx, ny);
}
Or, perhaps its just my hack of ShapePath?
THREE.ShapePath.prototype.absarc = function( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
this.currentPath.absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise);
};
THREE.ShapePath.prototype.absellipse = function( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
this.currentPath.absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise );
};
You can still use SVGLoader to load the SVG and retrieve an array of ShapePath objects. You can then use ShapePath.toShapes and use these shapes for creating ExtrudeBufferGeometry's. It's actually the same workflow like in webgl_loader_svg.html, just with ExtrudeBufferGeometry

Matlab: How to run code using multi threading/parallel computing?

I have Matlab code that simulates something called the 2-D Lid Driven Cavity Flow. In this code I have the following structure:
for i = 1:timeStep
%Lets call this Part 1
for a1 = 1:N
for b1 = 1:N
%calculates things
end
end
%Lets call this Part 2
for a2 = 1:N
for b2 = 1:N
%calculates things
end
end
%Lets call this Part 3
for a3 = 1:N
for b3 = 1:N
%calculates things
end
end
end
Since Part 1, Part 2, and Part 3 are independent pf each other I would like to compute them in parallel, or multi thread them, every time there is a timeStep (every iteration of primary for loop). Is there any way I can achieve this?
Thanks!
I include my code to to reference:
Nx = 50;
Ny = 50;
numTimesteps = 10000;
reynoldsNum = 1000;
dt = 0.0025;
numIter = 100000;
Beta = 1.5;
maxErr = 0.001;
ds = 1/(Nx + 1);
x1 = 0:ds:1;
x2 = 0:ds:1;
time = 0;
boundarySpeed = 1;
PHI = zeros(Nx+2, Ny+2);
OMEGA = zeros(Nx+2, Ny+2);
U = zeros(Nx+2, Ny+2);
V = zeros(Nx+2, Ny+2);
x2d = zeros(Nx+2, Ny+2);
y2d = zeros(Nx+2, Ny+2);
PRESSURE = zeros(Nx+2, Ny+2);
B = zeros(Nx+2, Ny+2);
pressureOLD = zeros(Nx+2, Ny+2);
W = zeros(Nx+2, Ny+2);
for i = 1:Nx+2
for j = 1:Ny+2
x2d(i,j) = x1(i);
y2d(i,j) = x2(j);
end
end
for timeStep = 1:numTimesteps
if(mod(timeStep,10000) == 0)
disp(timeStep);
end
OLDPHI = PHI;
OLDOMEGA = OMEGA;
OLDPRESSURE = PRESSURE;
parfor parJob = 1:4
switch parJob
%{
----------------------------------
STREAM FUNCTION CALCULATION
----------------------------------
%}
case 1
for iter = 1:numIter
ERRMATRIX = OLDPHI;
for i = 2:Nx+1
for j = 2:Ny+1
PHI(i,j) = (1/4) * Beta * (OLDPHI(i+1,j) + OLDPHI(i-1,j) + OLDPHI(i,j+1) + OLDPHI(i,j-1) + ...
ds * ds * OLDOMEGA(i,j)) + (1 - Beta) * OLDPHI(i,j);
end
end
Err = 0;
for i = 1:Nx+2
for j = 1:Ny+2
Err = Err + abs(ERRMATRIX(i,j) - PHI(i,j));
end
end
if (Err <= maxErr)
break;
end
OLDPHI = PHI;
end
%{
----------------------------------
BOUNDARY CONDITIONS FOR VORTICITY
----------------------------------
%}
case 2
for i = 2:Nx+1
for j = 2:Ny+1
OMEGA(i,1) = -2 * OLDPHI(i,2) / (ds * ds); % bottom wall
OMEGA(i,Ny+2) = -2 * OLDPHI(i,Ny+1) / (ds * ds) - 2 * boundarySpeed / ds; % top wall
OMEGA(1,j) = -2 * OLDPHI(2,j) / (ds * ds); % right wall
OMEGA(Nx+2,j) = -2 * OLDPHI(Nx+1,j) / (ds * ds); % left wall
end
end
%{
----------------------------------
VORTICITY CALCULATIONS
----------------------------------
%}
for i = 2:Nx+1
for j = 2:Ny+1
W(i,j) = -(1 / 4) * ((OLDPHI(i,j+1) - OLDPHI(i,j-1)) * (OLDOMEGA(i+1,j) - OLDOMEGA(i-1,j)) ...
- (OLDPHI(i+1,j) - OLDPHI(i-1,j)) * (OLDOMEGA(i,j+1) - OLDOMEGA(i,j-1))) / (ds * ds) ...
+(1 / reynoldsNum) * (OLDOMEGA(i+1,j) + OLDOMEGA(i-1,j) + OLDOMEGA(i,j+1) + ...
OLDOMEGA(i,j-1) - 4 * OLDOMEGA(i,j)) / (ds * ds);
end
end
OMEGA(2:Nx+1,2:Ny+1) = OLDOMEGA(2:Nx+1,2:Ny+1) + dt * W(2:Nx+1,2:Ny+1);
time = time + dt;
for i = 1:Nx
for j = 1:Ny
x2d(i,j) = x1(i);
y2d(i,j) = x2(j);
end
end
%{
----------------------------------
U AND V CALCULATIONS
----------------------------------
%}
case 3
for i = 2:Nx+1
for j = 2:Ny+1
U(i,j) = (OLDPHI(i,j+1) - OLDPHI(i,j)) / (2 * ds);
V(i,j) = -(OLDPHI(i+1,j) - OLDPHI(i,j)) / (2 * ds);
U(:,Ny+2) = 1;
V(Nx+2,:) = 0.0;
end
end
%{
----------------------------------
PRESSURE CALCULATIONS
----------------------------------
%}
otherwise
for i = 2:Nx+1
for j = 2:Ny+1
PRESSURE(i,j) = (1/4) * (pressureOLD(i+1,j) + pressureOLD(i-1,j) + pressureOLD(i,j+1) ...
+ pressureOLD(i,j-1)) - (1/2) * (((((OLDPHI(i-1,j) - 2 * OLDPHI(i,j) + ...
OLDPHI(i+1,j)) / (ds^2)) * ((OLDPHI(i,j-1) - 2 * OLDPHI(i,j) + OLDPHI(i,j+1)) / (ds^2))) ...
- (OLDPHI(i+1,j+1) - OLDPHI(i+1,j-1) - OLDPHI(i-1,j+1) + OLDPHI(i-1,j-1)) / (4 * (ds^2))) * ds^2);
end
pressureOLD = PRESSURE;
end
end
end
You can use parfor to run jobs in parallel.
result = cell(3, 1);
parfor k = 1:3
result{k} = ['result-' num2str(k)];
switch k
case 1
disp('do part one')
case 2
disp('do part two')
otherwise
disp('do part three')
end
end

My "perlin" noise effect shader produces either all-white or all-black

I'm trying to code a "perlin" noise shader in NVidia FX Composer. However, no matter how I tweak the noise function, it returns either 100% white or 100% black. I have no clue how to solve this or even where the problem is.
Edit: If you've seen This page, you probably know where I got the code. Figured I'd start with a method I'd already gotten working on a CPU.
Help, please.
float Noise1(int x, int y)
{
int n = x + y * 57;
// int n = x + y * 1376312627;
// n = n * n;
// n = (int)pow(n * pow(2, 13), n);
// return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) + 0x7fffffff) / 1073741824.0);
// return abs( ( (n * (n * n * 15731 + 789221) + 1376312589) + 0x7fffffff) / 2147483647.0);
// return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) + 0x7fffffff) / 2147483647.0);
// return ( n / 2147483647.0);
return ( ((float)n) / 500.0 );
// return n = 2147483647.0;
}
float SmoothNoise_1(int x, int y)
{
float corners = ( Noise1(x-1, y-1) + Noise1(x+1, y-1) + Noise1(x-1, y+1) + Noise1(x+1, y+1) ) / 16.0;
float sides = ( Noise1(x-1, y) + Noise1(x+1, y) + Noise1(x, y-1) + Noise1(x, y+1) ) / 8.0;
float center = Noise1(x, y) / 4.0;
return corners + sides + center;
}
float Cosine_Interpolate(float a, float b, float x)
{
float ft = x * 3.1415927;
float f = (1 - cos(ft)) * 0.5;
return a*(1-f) + b*f;
}
float InterpolatedNoise_1(float x, float y)
{
int integer_X = (int)x;
float fractional_X = x - integer_X;
int integer_Y = (int)y;
float fractional_Y = y - integer_Y;
float v1 = SmoothNoise_1(integer_X, integer_Y);
float v2 = SmoothNoise_1(integer_X + 1, integer_Y);
float v3 = SmoothNoise_1(integer_X, integer_Y + 1);
float v4 = SmoothNoise_1(integer_X + 1, integer_Y + 1);
float i1 = Cosine_Interpolate(v1 , v2 , fractional_X);
float i2 = Cosine_Interpolate(v3 , v4 , fractional_X);
return Cosine_Interpolate(i1 , i2 , fractional_Y);
}
int width = 512;
int height = 512;
float4 PerlinNoise_2D(float2 xy : TEXCOORD0) : COLOR0
{
float4 total = 0;
// int p = persistence;
float p = 1.0;
// int n = Number_Of_Octaves - 1;
int n = 2;
for(int i = 0; i < n; ++i)
{
float frequency = pow(2, i);
float amplitude = pow(p, i);
/* total.a = InterpolatedNoise_1(xy.x * width * frequency, xy.y * height * frequency) * amplitude;
total.r = InterpolatedNoise_1(xy.x * width * frequency, xy.y * height * frequency) * amplitude;
total.g = InterpolatedNoise_1(xy.x * width * frequency, xy.y * height * frequency) * amplitude;
total.b = InterpolatedNoise_1(xy.x * width * frequency, xy.y * height * frequency) * amplitude; */
/* total.a = InterpolatedNoise_1(xy.x * frequency, xy.y * frequency) * amplitude;
total.r = InterpolatedNoise_1(xy.x * frequency, xy.y * frequency) * amplitude;
total.g = InterpolatedNoise_1(xy.x * frequency, xy.y * frequency) * amplitude;
total.b = InterpolatedNoise_1(xy.x * frequency, xy.y * frequency) * amplitude; */
total.a = InterpolatedNoise_1(xy.x * width, xy.y * height);
total.r = InterpolatedNoise_1(xy.x * width, xy.y * height);
total.g = InterpolatedNoise_1(xy.x * width, xy.y * height);
total.b = InterpolatedNoise_1(xy.x * width, xy.y * height);
}
return clamp(total, 0.0, 1.0);
// return (float)(int)(2147483647 + 2147483647 + 2147483647 / 2) / 2147483647.0;
}
technique Perlin
{
pass p0
{
VertexShader = null;
PixelShader = compile ps_3_0 PerlinNoise_2D();
}
}
Thanks.
In short form, because a GeForce 8800GT doesn't do Bitwise and pow() returns a float. So no spinning and wobbling integer bits. (Very technical explanation, that).

Resources