def __init__ (self, dt, N, dims, W = 1., B = .5, L = 100., rho = 1., mu = 1., DeltaType = 0, Dim = None, ConstitutiveEqn = ConstitutiveEqns.OB_TeranFauciShelley, ConvectionMethod = ConvectionMethods.Upwind): """dims should be a 2-vector or 3-vector holding the dimensions of the fluid box. N should likewise be an integer 2-vector or 3-vector which describes how fine the grid will be in each dimension. Dim is the number of spatial dimensions (2 or 3) of the fluid domain.""" Fluid.__init__(self, dt, N, dims, rho, mu, DeltaType = DeltaType, Dim = Dim) self.ConstitutiveEqn = ConstitutiveEqn self.ConvectionMethod = ConvectionMethod Dim = self.Dim # Get the relevant symmetric matrix helper class if Dim == 2: self.MySymmetricHelper = SymmetricHelper2x2 elif Dim == 3: self.MySymmetricHelper = SymmetricHelper3x3 else: raise Exception("Dim, the dimension of the fluid domain, must be either 2 or 3.") ScalarDim, VectorDim, SymMatrixDim, dSDim = self.ViscoFieldDims() self.W = float(W) # The Weissenberg number self.B = float(B) # beta self.L = float(L) # Maximum extension length for FENE self.S = zeros(SymMatrixDim,float64) # The polymeric stress (or conformation tensor), with 6 components at each material point (a 3x3 symmetric matix) # Initialize the stress (or conformation tensor) self.S[...] = self.MySymmetricHelper.identity() # Initial value is the 2x2 (3x3) identity matrix self.ArtificialDiffusion = self.h[0]**2
def runAll(self): fluids = Fluid() self.C = fluids.getInfo() self.getInput() print("Calculating...\n") T = self.solveT() area = self.solveArea(T) cost = self.solveCost(area) self.output(area, T, cost)
def runAll(self): fluids=Fluid() self.C=fluids.getInfo() self.getInput() print("Calculating...\n") T=self.solveT() area=self.solveArea(T) cost=self.solveCost(area) self.output(area,T,cost)
def __init__(self, dt, N, dims, W=1., B=.5, L=100., rho=1., mu=1., DeltaType=0, Dim=None, ConstitutiveEqn=ConstitutiveEqns.OB_TeranFauciShelley, ConvectionMethod=ConvectionMethods.Upwind): """dims should be a 2-vector or 3-vector holding the dimensions of the fluid box. N should likewise be an integer 2-vector or 3-vector which describes how fine the grid will be in each dimension. Dim is the number of spatial dimensions (2 or 3) of the fluid domain.""" Fluid.__init__(self, dt, N, dims, rho, mu, DeltaType=DeltaType, Dim=Dim) self.ConstitutiveEqn = ConstitutiveEqn self.ConvectionMethod = ConvectionMethod Dim = self.Dim # Get the relevant symmetric matrix helper class if Dim == 2: self.MySymmetricHelper = SymmetricHelper2x2 elif Dim == 3: self.MySymmetricHelper = SymmetricHelper3x3 else: raise Exception( "Dim, the dimension of the fluid domain, must be either 2 or 3." ) ScalarDim, VectorDim, SymMatrixDim, dSDim = self.ViscoFieldDims() self.W = float(W) # The Weissenberg number self.B = float(B) # beta self.L = float(L) # Maximum extension length for FENE self.S = zeros( SymMatrixDim, float64 ) # The polymeric stress (or conformation tensor), with 6 components at each material point (a 3x3 symmetric matix) # Initialize the stress (or conformation tensor) self.S[...] = self.MySymmetricHelper.identity( ) # Initial value is the 2x2 (3x3) identity matrix self.ArtificialDiffusion = self.h[0]**2
def MakeWorkVars(self): """Create working variables used in the fluid solver.""" Fluid.MakeWorkVars(self) ScalarDim, VectorDim, SymMatrixDim, dSDim = self.ViscoFieldDims() self.dS = zeros(dSDim, float64) # The total derivative of S self.g = zeros(SymMatrixDim, float64) # Used to update S self.CurrentStress = None # The actual polymeric stress, calculated from the conformation tensor
def main(): # Initialize pygame pygame.init() # Start application config = [ Config((640, 640), "Conway's Game of Life", 64, Conway()), Config((640, 640), "Langston's Ant", 64, Ant()), Config((640, 640), "Brian's Brain", 64, Brian()), Config((640, 640), "Rule 90", 64, Rule90()), Config((640, 640), "Rule 110", 64, Rule110()), Config((640, 640), "Fluid Simulation", 64, Fluid()) ] Application(config[5])
def UpdateFluid(self, f, Update_du=True, CalcPressure=False, UpdateStress=True, KeepUpdate=True): """Advance the fluid one timestep via a semi-implicit scheme. f is a force field applied to the fluid at the current time and must be a vector field.""" # Calculate polymeric stress contribution self.CurrentStress = self.PolymericStress() f += self.CurrentStress # Update the fluid Fluid.UpdateFluid(self, f, Update_du, CalcPressure, KeepUpdate) # Update the fluid stress if UpdateStress and KeepUpdate: self.UpdateS()
def pygame_window(): pygame.init() white = (255, 255, 255) black = (0, 0, 0) size = 32 scale = 15 fluid = Fluid(dt=0.5, diffusion=0, viscosity=0) field = Field(size, fluid) gameDisplay = pygame.display.set_mode((scale * size, scale * size)) gameDisplay.fill(black) clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEMOTION: pos = pygame.mouse.get_pos() vel = pygame.mouse.get_rel() x = int(pos[1] / scale) y = int(pos[0] / scale) field.add_density(x, y, 200) field.add_velocity(x, y, vel[1], vel[0]) for i in range(size - 2): for j in range(size - 2): d = int(field.density[i + j * size]) try: pygame.draw.rect(gameDisplay, (d, d, d), [j * scale, i * scale, scale, scale]) except Exception as e: print(e) field.fluidstep() pygame.display.update() clock.tick(1 / fluid.dt)
for i in range(0,2): vx = np.random.uniform(-3,3) vy = np.random.uniform(-3,3) t += 0.01 fluid.addVelocity(cx, cy, vx, vy) fluid.step() image = fluid.render() im = plt.imshow(image, cmap='YlOrRd', interpolation = "nearest", animated=True) return im if __name__ == "__main__": # Define the fluid object with a given time resolution # diffusion and viscosity fluid = Fluid(0.1, 0, 0.0000005) fig = plt.figure() ims = [] for i in tqdm(range(step)): im = iterate(fluid, t) ims.append([im]) ani = animation.ArtistAnimation(fig, ims, interval=100, blit=True, repeat_delay=1000) if(output_type == "mp4"): ani.save(f'./movies/movie_dif_vis_steps{step}.mp4') elif(output_type == "gif"): ani.save(f'./movies/movie_dif_vis_steps{step}_.gif', dpi=80, writer='imagemagick')
dt = .00000003 Time = SimTime(dt = dt, T = T) # Setup for saving the simulation output SavePeriod = 100 #int((T / dt) / 120) Save = SaveData.SaveDataControl(('EllipseRelaxation', 'Explicit')) # Ellipse X = Ellipse(2 * N, s, [.5,.5], [.8,.5], [.5,.6]) X.UseNativePython = False # If true native python code is used instead of C code # Initialize the fluid solver u = Fluid(dt = dt, N = [N,N], dims = [1., 1.]) # The simulation loop Time.StartTimer() while Time.t < Time.T: Time.PrintStepInfo() X.CheckForExplosion() # The FE/BE method # First calculate the fiber force F (stored in X.F) X.CalcForceDistribution() # Spread F to the Eulerian grid, storing the result in the force field u.f X.ToGrid(u)
def __getstate__(self): d = Fluid.__getstate__(self) del d['g'], d['dS'], d['CurrentStress'] return d
def prain(N): # Read name of output file from command line """ if len(sys.argv)!=3: print("Wrong number of arguments.") print("Usage: " + sys.argv[0] + " param.firstinput " + "traj.xyz") quit() else: infile_name = sys.argv[1] output_file = sys.argv[2] infile = open(infile_name,"r") infile = np.loadtxt(infile) """ visc = 8 leg = 0.00005 den = 1 speed = 0 #Initialising Sperm and Fluid Objects mean_force, mean_torque, summed_force_list, summed_torque_list = VectGen.FandTGen( N) #print(summed_torque_list) sperm = Spermatozoon(np.array([0.0001, 1, 0]), np.array([0, 0, 0]), 0.1, leg, np.array([0, 0, 0]), 0, 1) fluid = Fluid(visc, speed, den) sperm_position_list = [] # Set up simulation parameters dt = 0.01 numstep = 10000 time = 0.0 #Initial Force Value force = summed_force_list #Torque set-up alpha = angular_torque_tings(dt, mean_torque, sperm.mass, sperm.length) rot = PHAT_rot_matrix(summed_torque_list, alpha) #Initial Time and Position List time_list = [0.0] pos_list = [sperm.position] #Hopefully I can visulise it with this #f = open(output_file,'w') #Whatever Programme I use to model this # Start the time integration loop for t in range(numstep): #Position Update sperm.leap_pos2nd(dt, rot @ force) #Re-calculating Force force_new = rot @ (summed_force_list + DragForce(sperm, fluid)) #Velocity and Torque/Angle Update sperm.leap_velocity(dt, rot @ (force + force_new)) # Increase time and reset force value time += dt pos_list.append(sperm.position) time_list.append(time) force = force_new #Write a VMD file #f.write(str(1)+"\n") #f.write("Point = " + str(t+1) +"\n") #f.write("s"+ str(1) + " " + str(sperm.position[0]) + " " + str(sperm.position[1]) + " " + str(sperm.position[2]) + "\n") #print(scipy.linalg.norm(pos_list[numstep])) return (scipy.linalg.norm(pos_list[numstep]) - scipy.linalg.norm(pos_list[0]))
def main(): HEIGTH = Shape.HEIGTH WIDTH = Shape.WIDTH FORCE_VALUE = 500 DELAY_MILISECONDS = 17 FRICTION = 0.5 Shape.SCALING_FACTOR = 10 #TODO CHANGE THIS TO CHANGE SCALING #Note - acts weird if scaling is >= 14 enviroment = Fluid(1.225, np.array([0, 0])) #TODO COMMENT AND UNCOMMENT TO SWITCH FROM RECTANGLE TO BALL AND VICE VERSA ball = Ball(10, (250, 0, 0), 15, enviroment, FRICTION) #ball = Rect(10, (250, 0, 0), 200, 10, enviroment, FRICTION) #TODO COMMENT AND UNCOMMENT TO SWITCH FROM RECTANGLE TO BALL AND VICE VERSA east_wall = Rect(100, (0, 250, 0), 50, HEIGTH, enviroment, FRICTION, True) east_wall.position[0] = WIDTH - 5 east_wall.position[1] = HEIGTH / 2 west_wall = Rect(100, (0, 250, 0), 50, HEIGTH, enviroment, FRICTION, True) west_wall.position[0] = 50 west_wall.position[1] = HEIGTH / 2 south_wall = Rect(100, (0, 250, 0), WIDTH, 50, enviroment, FRICTION, True) south_wall.position[0] = WIDTH / 2 south_wall.position[1] = HEIGTH - 5 north_wall = Rect(100, (0, 250, 0), WIDTH, 50, enviroment, FRICTION, True) north_wall.position[0] = WIDTH / 2 north_wall.position[1] = 50 square = Rect(1, (0, 250, 0), 100, 20, enviroment, FRICTION, False) square.position[0] = 250 square.position[1] = 250 sprite_ball = Ball(100, (0, 250, 0), 20, enviroment, FRICTION, True) sprite_ball.position[0] = 250 sprite_ball.position[1] = 400 enviroment.add(ball) enviroment.add(east_wall) enviroment.add(west_wall) enviroment.add(south_wall) enviroment.add(north_wall) enviroment.add(square) enviroment.add(sprite_ball) enviroment.recalibrate_shapes_positions() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGTH)) pygame.display.set_caption("Koralovo") run = True while True: pygame.time.delay(DELAY_MILISECONDS) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: run = not run elif event.key == pygame.K_SPACE and not run: loop(ball, FORCE_VALUE, enviroment, window) if run: loop(ball, FORCE_VALUE, enviroment, window)
def ConstitutiveName(self): if self.W == 0: return Fluid.ConstitutiveName(self) else: return ConstitutiveEqns.Name[self.ConstitutiveEqn]
from Fluid import Fluid from Ellipse import Ellipse from MatrixUtility import Stack, Unstack # Simulation parameters N = 128 RestrictToEulerian = False # If True we restrict the fiber points to Eulerian intersections. When done the matrix should give EXACT results. # Create the fiber in the shape of an ellipse X = Ellipse(2 * N, s=10e6, c=[.5, .5], p1=[.8, .5], p2=[.5, .6]) if RestrictToEulerian: X.X = floor(X.X * N) / N # Initialize the fluid solver u = Fluid(dt=1. / N, N=[N, N], dims=[1., 1.]) # Calculate dX/dt (stored in X.U) using a fluid solve X.CalcForceDistribution() X.ToGrid(u) u.UpdateFluid(u.f) X.FromGrid(u) # Calculate dX/dt (stored in U) using the fluid matrix # First construt the fluid matrix M = X.ConstructFluidMatrix(u) # Then calculate U = M * F, where F is the fiber force U = Unstack(dot(M, Stack(X.F)), 2) # Calculate difference between X.U and U (the induced flow calculated via a fluid solve and via the matrix)
"Antoine coeff": [13.9320, 3056.96, 217.625] } Toluene = PureComponent(toluene) # PureComponent.save_component(toluene) # Toluene1 = PureComponent.load_component("toluene") Benzene = PureComponent(benzene) # PureComponent.save_component(benzene) # Benzene1 = PureComponent.load_component("benzene") Water = PureComponent(water) # PureComponent.save_component(water) # Water1 = PureComponent.load_component("water") fluid1 = Fluid(2, 288, 101325, [Benzene, Toluene], [0.6, 0.4], PR) fluid2 = Fluid(2, 363, 101325, [Water], [1], PR) phase_list1 = fluid1.phase_list phase_list2 = fluid2.phase_list # here you can read all phase properties like: phase_list1[0].H new_conditions1 = {"T": 300, "P": 100000, "composition": [0.5, 0.5]} fluid1.update(new_conditions1) new_conditions2 = {"T": 300, "P": 100000} fluid2.update(new_conditions2) new_conditions3 = {"T": 320} fluid1.update(new_conditions3)
def SaveState(self, Saver): Fluid.SaveState(self, Saver) Saver.Save(self.S, 'S_' + str(Saver.CurStep))