def calculateCoeffs(self): """ If forces exist, the respective coefficients are calculated accordingly. Otherwise a ValueError is raised. :param L: Reference length :type L: float :param A: Reference area :type A: float """ self.uInf = Utilities.mag(self.inletVelocity) self.Re = FlowProperties.Re(L=self.L, u=self.uInf) self.Fr = FlowProperties.Fr(L=self.L, u=self.uInf) if self.forces: self.t = self.forces[0] self.resistances['RF'] = self.direction * self.forces[ abs(self.direction) + 3] self.resistances['RT'] = self.resistances['RF'] +\ self.direction*self.forces[abs(self.direction)] self.resistances['CF'] = Resistance.forceCoeff( self.resistances['RF'], self.A, u=self.uInf) self.resistances['CT'] = Resistance.forceCoeff( self.resistances['RT'], self.A, u=self.uInf) else: raise ValueError
def updateInletVelocity(self): """ Reads and updates the inlet velocity. This has to be done without pyFoam, as this takes *ages* for a file with precalculated velocities. """ inletFound = False with open(join(self.name, self.first, 'U'), 'r') as bc: for line in bc: for patchI in self.inletPatch: if patchI in line: inletFound = True if inletFound: if "uniform" in line: vIn = line break numberRe = compile(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?") self.inletVelocity = [float(uI) for uI in findall(numberRe, vIn)] self.uInf = Utilities.mag(self.inletVelocity) self.Re = FlowProperties.Re(L=self.L, u=self.uInf) self.Fr = FlowProperties.Fr(L=self.L, u=self.uInf)
def main(): parser = OptionParser(usage="usage: %prog [options] area ref.Length (case)", version="%prog 1.0") parser.add_option( "-U", "--velocity", action="store", dest="U", type="string", default="False", help="Velocity vector as a list \"[x,y,z]\". If nothing is\ stated, a inlet patch needs to be specified. From that\ patch, the velocity is read automatically." ) parser.add_option( "-i", "--inlet", action="store", dest="inletPatch", type="string", default="XMAX", help="Name of the inlet patch. (default=XMAX)" ) parser.add_option( "-s", "--start", action="store", dest="startAtTime", type="float", default=0.0, help="Starttime of the plotting interval, spanning from that\ time to the end. (default=0.0)" ) parser.add_option( "-d", "--deviation-start", action="store", dest="deviationInterval", type="float", default=0.5, help="Specifies over which part of the plotted interval, the\ relative deviation between CF and ITTC\'57 as well as\ the average of CF should be calculated. (default=0.5)" ) parser.add_option( "-f", action="store", type="choice", choices=['1','2','3'], dest="direction", default=1, help="Main flow direction (1=x,2=y,3=z). (default=1)" ) (options, args) = parser.parse_args() if len(args) == 2: caseDir = getcwd() elif len(args) == 3: caseDir = args[2] else: parser.error("wrong number of arguments") area = float(args[0]) L = float(args[1]) U = eval(options.U) startAtElement = 0 deviationStartElement = 0 case = Case.case( caseDir, archive=None, paraviewLink=False, inletPatch=options.inletPatch, U=U ) uInf = Utilities.mag(case.inletVelocity) Re = FlowProperties.Re(L=L,u=uInf) data = case.forces t = data[0] RF = abs(data[options.direction+3]) RT = RF + abs(data[options.direction]) # The list element of the time has to be figured out, beyond which the # plotting should start. if options.startAtTime > 0.0: for i in range(0,len(data[0])): if data[0][i] > options.startAtTime: startAtElement = i break # Determine the start element for the deviation calculation deviationStartElement = startAtElement + \ int(len(t[startAtElement:])*(1-options.deviationInterval)) # Gather all data CF = Resistance.forceCoeff(RF,area,u=uInf) CT = Resistance.forceCoeff(RT,area,u=uInf) ittc57 = ones(len(CT))* SkinFriction.ittc57(Re=Re) deviationList = CF*100.0/ittc57 - 100 # Calculate the relative error between CF and ITTC57 for the respective # intervall deviation = sum(deviationList[deviationStartElement:]) / \ len(deviationList[deviationStartElement:]) # Calculate mean value of CF for the respective interval CFmean = mean(CF[deviationStartElement:]) fig = plt.figure() plt.title("case: %s\nCFmean = %.2e, rel.Error = %.2f%%, Re = %.2e" %(case.shortCasePath,CFmean,deviation,Re)) plt.grid(True) ax1 = fig.add_subplot(111) plt.grid(True) ax2 = ax1.twinx() CFPlot = ax1.plot(t[startAtElement:],CF[startAtElement:],'-',label='C_F',color='green') ittc57Plot = ax1.plot(t[startAtElement:], ittc57[startAtElement:],'-',label='ITTC57',color='red') CTPlot = ax2.plot(t[startAtElement:],CT[startAtElement:],'-',label='C_T') ax1.fill_between(t[deviationStartElement:], CF[deviationStartElement:], ittc57[deviationStartElement:], color="green",alpha=0.5) ax1.set_xlabel("simulation time [s]") ax1.set_ylabel("CF [-]") ax2.set_ylabel("CT [-]") #ax1.set_ylim([ # 0, # 1.2*max(CF[startAtElement].max(),ittc57[0]) # ]) lines = CFPlot+ittc57Plot+CTPlot labels = [l.get_label() for l in lines] plt.legend( lines, labels, loc=9, #bbox_to_anchor=(0., 1.02, 1., .102), ncol=3, mode="expand" ) plt.show()
def main(argv=None): """ """ parser = OptionParser( usage="usage: %prog [options]", version="%prog ", description=__doc__ ) parser.add_option( "-m", action="store", dest="mesh", type="string", default="", help="Specifies the mesh to work on" ) parser.add_option( "-t", action="store", dest="template", type="string", default="template", help="""Specifies the template case, that will be cloned. (Default = template)""" ) parser.add_option( "-s", "--subpath", action="store", dest="subpath", type="string", default="", help="""Optional subpath. This should be used to sort custom parameter variations into the existing file structure. %mesh/(%subpath, optional)/%beta/%v """ ) parser.add_option( "-b", action="store", dest="beta", type="float", default=0.0, help="Drift angle beta (Default = 0.0)" ) parser.add_option( "-n", action="store", dest="steps", type="int", default=10, help="""Number of velocities between 0 and vMax. v=0 m/s will be neglected. (Default = 10)""" ) parser.add_option( "-u", action="store", dest="u", type="string", default="0.0", help="Service speed in m/s (Default = 0.0m/s)" ) parser.add_option( "-r", action="store", dest="dh", type="float", default=100.0, help="""Characteristic length of the flow. For ships this should be the shiplength. (Default = 100.0m)""" ) group = OptionGroup(parser,"Flag Options") group.add_option( "--without-turbulence", action="store_true", dest="withoutTurbulence", help="""Do not look for the turbulence model and set the particular values in the boundary conditions. The values are calculated based on the equations presented in the Fluent (R) handbook.""" ) parser.add_option_group(group) (options, args) = parser.parse_args() try: u = float(options.u) v = linspace(0, u, options.steps + 1)[1:] except ValueError: exec "v = array(%s)" %options.u # Assemble the current working directory workingDir = path.join(getcwd(),options.mesh) # Put together the name of the target angle folder driftAngleName = "beta%.2f" %options.beta # Assemble the absolute path of the angle folder if not options.subpath: driftAngleDirectory = path.join(workingDir,driftAngleName) else: driftAngleDirectory = path.join(workingDir,options.subpath,driftAngleName) # Check if the directory exists, that should store the cases for the current # drift angle. if not path.exists(driftAngleDirectory): makedirs(driftAngleDirectory) else: raise IOError("Directory %s does already exist" %driftAngleDirectory) template = Case.case( path.join(getcwd(),options.mesh,options.template), archive=None, paraviewLink=False ) template.addToClone("runCluster") template.addToClone("customRegexp") print "\nDrift angle beta = %.2f\n" %options.beta i = 1 for vI in v: print "Cloning case for v = %.3f" %vI # Clone the template case and open velocity boundary condition case = template.cloneCase(path.join(driftAngleDirectory,"v%02d" %i)) uFile = ParsedParameterFile(path.join(case.name,"0","U")) # Rotate the velocity vector around z axis, according to the specified # drift angle. U = Vector( vI*math.cos(math.radians(options.beta)), vI*math.sin(math.radians(options.beta)), 0 ) # Update the boundary condition(s) with the respective values, that have # been calculated previously. uFile["internalField"].setUniform(U) for b in ["XMIN","XMAX","YMIN","YMAX","ZMIN", "ZMAX"]: patchType = uFile["boundaryField"][b]['type'] setPatch = False for inlet in ['value', 'inletValue', 'tangentialVelocity']: try: uFile["boundaryField"][b][inlet].setUniform(U) setPatch = True except KeyError: pass if setPatch: print "\tSetting patch: %s type %s" %(b, patchType) # Write changes to the boundary conditions uFile.writeFile() if not options.withoutTurbulence: print "\tFixing turbulence Dh =", options.dh case.writeTurbulence(options.dh, Utilities.mag(U)) # Update counter i += 1 print "\nDone!"
def main(argv=None): """ """ parser = OptionParser(usage="usage: %prog [options]", version="%prog ", description=__doc__) parser.add_option("-m", action="store", dest="mesh", type="string", default="", help="Specifies the mesh to work on") parser.add_option("-t", action="store", dest="template", type="string", default="template", help="""Specifies the template case, that will be cloned. (Default = template)""") parser.add_option( "-s", "--subpath", action="store", dest="subpath", type="string", default="", help="""Optional subpath. This should be used to sort custom parameter variations into the existing file structure. %mesh/(%subpath, optional)/%beta/%v """) parser.add_option("-b", action="store", dest="beta", type="float", default=0.0, help="Drift angle beta (Default = 0.0)") parser.add_option("-n", action="store", dest="steps", type="int", default=10, help="""Number of velocities between 0 and vMax. v=0 m/s will be neglected. (Default = 10)""") parser.add_option("-u", action="store", dest="u", type="string", default="0.0", help="Service speed in m/s (Default = 0.0m/s)") parser.add_option("-r", action="store", dest="dh", type="float", default=100.0, help="""Characteristic length of the flow. For ships this should be the shiplength. (Default = 100.0m)""") group = OptionGroup(parser, "Flag Options") group.add_option("--without-turbulence", action="store_true", dest="withoutTurbulence", help="""Do not look for the turbulence model and set the particular values in the boundary conditions. The values are calculated based on the equations presented in the Fluent (R) handbook.""") parser.add_option_group(group) (options, args) = parser.parse_args() try: u = float(options.u) v = linspace(0, u, options.steps + 1)[1:] except ValueError: exec "v = array(%s)" % options.u # Assemble the current working directory workingDir = path.join(getcwd(), options.mesh) # Put together the name of the target angle folder driftAngleName = "beta%.2f" % options.beta # Assemble the absolute path of the angle folder if not options.subpath: driftAngleDirectory = path.join(workingDir, driftAngleName) else: driftAngleDirectory = path.join(workingDir, options.subpath, driftAngleName) # Check if the directory exists, that should store the cases for the current # drift angle. if not path.exists(driftAngleDirectory): makedirs(driftAngleDirectory) else: raise IOError("Directory %s does already exist" % driftAngleDirectory) template = Case.case(path.join(getcwd(), options.mesh, options.template), archive=None, paraviewLink=False) template.addToClone("runCluster") template.addToClone("customRegexp") print "\nDrift angle beta = %.2f\n" % options.beta i = 1 for vI in v: print "Cloning case for v = %.3f" % vI # Clone the template case and open velocity boundary condition case = template.cloneCase(path.join(driftAngleDirectory, "v%02d" % i)) uFile = ParsedParameterFile(path.join(case.name, "0", "U")) # Rotate the velocity vector around z axis, according to the specified # drift angle. U = Vector(vI * math.cos(math.radians(options.beta)), vI * math.sin(math.radians(options.beta)), 0) # Update the boundary condition(s) with the respective values, that have # been calculated previously. uFile["internalField"].setUniform(U) for b in ["XMIN", "XMAX", "YMIN", "YMAX", "ZMIN", "ZMAX"]: patchType = uFile["boundaryField"][b]['type'] setPatch = False for inlet in ['value', 'inletValue', 'tangentialVelocity']: try: uFile["boundaryField"][b][inlet].setUniform(U) setPatch = True except KeyError: pass if setPatch: print "\tSetting patch: %s type %s" % (b, patchType) # Write changes to the boundary conditions uFile.writeFile() if not options.withoutTurbulence: print "\tFixing turbulence Dh =", options.dh case.writeTurbulence(options.dh, Utilities.mag(U)) # Update counter i += 1 print "\nDone!"