compute_granudrum_aor Namespace Reference

Functions

def compute_granudrum_aor (filename)
 This function computes the angle of repose in a similar way to the GranuDrum from GranuTools. More...
 
def write_to_file (filename, filecontent)
 This function writes a string to a file. More...
 

Variables

 parser
 
 type
 
 str
 
 help
 
 args = parser.parse_args()
 

Function Documentation

◆ compute_granudrum_aor()

def compute_granudrum_aor.compute_granudrum_aor (   filename)

This function computes the angle of repose in a similar way to the GranuDrum from GranuTools.

Parameters
[in]filenameThe name of the coarse-grained .stat file from MercuryCG.
23 def compute_granudrum_aor(filename):
24  """!
25  @brief This function computes the angle of repose in a similar way to the GranuDrum from GranuTools.
26 
27  @param[in] filename The name of the coarse-grained .stat file from MercuryCG.
28  """
29 
30  # load the data from a coarse grained stat file
31  data = mercury_cg(filename + ".stat")
32 
33  # Create the figure and axes
34  fig, ax = plt.subplots(figsize=(10, 8))
35  dim = len(data["x"].shape)
36  # this line of code is needed for this code to work for timesmoothed and timeaveraged CG data
37  if dim == 2:
38  # If the shape of the data is 2D, i.e. no time dimension we add an empty singleton dimension
39  for key in data:
40  data[key] = np.expand_dims(data[key], axis=-1)
41  # Plot the contour plot
42  contour = ax.contourf(data["x"][:, :, -1], data["z"][:, :, -1], data["VolumeFraction"][:, :, -1], cmap='viridis',
43  levels=20)
44  # Add a colorbar with label and formatting
45  fig.colorbar(contour, label='VolumeFraction', format='%1.2f')
46  # Add labels and title
47  ax.set_xlabel('X-axis')
48  ax.set_ylabel('Z-axis')
49  ax.set_title('Contour Plot of volume fraction')
50  # Add a grid for better readability
51  ax.grid(True, linestyle='--', alpha=0.7)
52 
53  # Plot the 0.1 volumen fraction contour line
54  contour_line_01 = ax.contour(data["x"][:, :, -1], data["z"][:, :, -1], data["VolumeFraction"][:, :, -1],
55  colors="red", levels=[np.max(data.VolumeFraction[:, :, -1])*0.5])
56  ax.clabel(contour_line_01, inline=True, fmt='%1.1f', fontsize=16)
57 
58  # Calculate the center and radius of the circle
59  center_x = (np.max(data["x"]) + np.min(data["x"])) / 2
60  center_z = (np.max(data["z"]) + np.min(data["z"])) / 2
61  radius = (np.max(data["x"]) - np.min(data["x"])) / 10 # D_drum/5
62 
63  # Create a circle of d = D_drum/5
64  circle = Circle((center_x, center_z), radius, fill=False, label='$D_{Drum}/5$ circle', color='b')
65 
66  # Find the intersection points with a tolerance of 1% of the circle radius
67  intersection_points = []
68  for line in contour_line_01.collections[0].get_paths():
69  for vert in line.vertices:
70  x, z = vert
71  if np.isclose((x - center_x) ** 2 + (z - center_z) ** 2, radius ** 2, atol=radius * 1e-2):
72  intersection_points.append((x, z))
73  # Save the x and z values of the intersection points
74  intersection_x = [point[0] for point in intersection_points]
75  intersection_z = [point[1] for point in intersection_points]
76  # Draw the circle and the line connecting the intersection points
77  ax.add_patch(circle)
78  ax.plot(intersection_x, intersection_z, 'ro-', label='Intersection points')
79 
80  # Fit a 1st degree polynomial (a line) to the intersection points
81  slope, intercept = np.polyfit(intersection_x, intersection_z, 1)
82  # Generate x values
83  line_x = np.linspace(min(intersection_x), max(intersection_x), 100)
84  # Calculate the corresponding y values
85  line_z = slope * line_x + intercept
86  # Plot the line
87  ax.plot(line_x, line_z, 'g-', label='angle of repose line', linewidth=2)
88 
89  # print the function of the line
90  print(f"f(x) = {slope} * x + {intercept}", )
91  # calculate the absolute angle of repose
92  angle_drum = np.abs(np.arctan(slope)) * 180 / np.pi
93  print(f"absolute angle of repose = {angle_drum} degrees")
94 
95  # matplotlib inline function which creates a legend entry in form a circle for our d/5 circle
96  class HandlerCircle(HandlerPatch):
97  def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
98  center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
99  p = mpatches.Circle(xy=center, radius=height / 2)
100  self.update_prop(p, orig_handle, legend)
101  p.set_transform(trans)
102  return [p]
103 
104  # add legend and specify the custom handler for the circle
105  ax.legend(handler_map={mpatches.Circle: HandlerCircle()})
106  # show the plot. set block to True to see it
107  plt.show(block=False)
108  # save the created figure
109  plt.savefig(f'{filename}_AOR.png', dpi=300)
110  # write the angle of repose to a file
111  write_to_file(f'{filename}.txt', f"{angle_drum:.2f}")
112 
113 
114 # function to write a string to a file
#define min(a, b)
Definition: datatypes.h:22
#define max(a, b)
Definition: datatypes.h:23
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet print(const Packet &a)
Definition: GenericPacketMath.h:1166
def write_to_file(filename, filecontent)
This function writes a string to a file.
Definition: compute_granudrum_aor.py:115
def compute_granudrum_aor(filename)
This function computes the angle of repose in a similar way to the GranuDrum from GranuTools.
Definition: compute_granudrum_aor.py:23
def mercury_cg(name='Chain.stat', print_summary=True, row_major_index_order=False)
This function reads a MercuryCG .stat file and returns a dictionary of the data.
Definition: read_mercury_cg.py:40

References max, read_mercury_cg.mercury_cg(), min, Eigen::internal.print(), and write_to_file().

◆ write_to_file()

def compute_granudrum_aor.write_to_file (   filename,
  filecontent 
)

This function writes a string to a file.

Parameters
[in]filenameThe name of the file to write to.
[in]filecontentThe content to write to the file.
Returns
True if the file was successfully written, False otherwise.
115 def write_to_file(filename, filecontent):
116  """!
117  @brief This function writes a string to a file.
118 
119  @param[in] filename The name of the file to write to.
120  @param[in] filecontent The content to write to the file.
121 
122  @return True if the file was successfully written, False otherwise.
123  """
124 
125  try:
126  with open(filename, 'w') as file:
127  file.write(filecontent)
128  return True
129  except OSError:
130  print('\033[91m' + 'Error in writeToFile: file could not be opened' + '\033[0m')
131  return False
132 
133 
134 """!
135 @brief This is the main function. It parses command line arguments and calls the compute_granudrum_aor function.
136 """
137 

References Eigen::internal.print().

Referenced by compute_granudrum_aor().

Variable Documentation

◆ args

compute_granudrum_aor.args = parser.parse_args()

◆ help

compute_granudrum_aor.help

◆ parser

compute_granudrum_aor.parser
Initial value:
1 = argparse.ArgumentParser(description='Compute the angle of repose in a similar way to the GranuDrum from '
2  'GranuTools', usage='%(prog)s <filename>')

◆ str

compute_granudrum_aor.str

Referenced by gdb.printers.cast_eigen_block_to_matrix(), framework.Frame.check_linking(), check-makefile-subdirs.check_makefileam(), DistanceWrapper< ELEMENT >.describe_local_dofs(), find_and_replace(), format(), parallel_self_test.get_oomph_root(), read_mercury_cg.get_variables(), AreaVTK.getTotalsurfaceAreaFromFile(), InputData.LoadPebbles(), framework.Frame.look_for_mpibinaries(), parallel_self_test.main(), CombineParallelOutFiles.main(), CombineParallelRestartFiles.main(), BatchRun.main(), fpsmall.main(), main(), match(), oomph::CommandLineArgs.output(), rapidjson::GenericDocument< Encoding, Allocator >.Parse(), rapidjson::GenericDocument< Encoding, Allocator >.ParseInsitu(), plotResults.plotParametersAndObservables(), Particles2023AnalysisHung.predict_model(), Chute.readNextArgument(), SimpleOpt.real_fun(), MultiOpt.RealFun(), SingleRun.RealFun(), utils.runShellCommand(), simulate.runSimulations(), simulateAWS.runSimulations(), SaveToVtu.SavePDToVtu(), SaveToVtu.SavePebblesToVtu(), SaveToStl.SaveStlSequence(), framework.Frame.set_download(), framework.Frame.set_mangling(), framework.Frame.set_ranlib(), set_repeat_from_string(), set_seed_from_string(), rapidjson::GenericDocument< Encoding, Allocator >.String(), rapidjson::PrettyWriter< Stream, Encoding, Allocator >.String(), rapidjson::Writer< Stream, Encoding, Allocator >.String(), strtolower(), strtoupper(), oomph-convert.tecplot_to_vtkxml(), oomph-convert.tecplot_to_vtpxml(), and rapidjson::Writer< Stream, Encoding, Allocator >.WriteString().

◆ type

compute_granudrum_aor.type
Examples
/home/plath/mercurydpm2/mercurydpm/Eigen/unsupported/Eigen/CXX11/src/Tensor/TensorLayoutSwap.h.

Referenced by addObject(), VTKData.addToTypes(), MPIContainer.broadcast(), Eigen::AlignedBox< Scalar_, AmbientDim_ >.cast(), Eigen::AngleAxis< Scalar_ >.cast(), Eigen::Hyperplane< Scalar_, AmbientDim_, Options_ >.cast(), Eigen::ParametrizedLine< Scalar_, AmbientDim_, Options_ >.cast(), Eigen::Rotation2D< Scalar_ >.cast(), Eigen::Transform< Scalar_, Dim_, Mode_, Options_ >.cast(), Eigen::Translation< Scalar_, Dim_ >.cast(), commandLineCG(), Eigen::GeneralizedSelfAdjointEigenSolver< MatrixType_ >.compute(), Eigen::internal.copyBToRowMajor(), BoundaryHandler.createObject(), ParticleHandler.createObject(), WallHandler.createObject(), MPIContainer.deleteMercuryMPITypes(), MPIContainer.directReceive(), MPIContainer.directSend(), EIGEN_DECLARE_TEST(), Eigen::DenseBase< Derived >.eval(), Eigen::SparseMatrixBase< Derived >.eval(), Eigen::TensorEvaluator< const TensorConversionOp< TargetType, ArgType >, Device >::TensorConversionOpBlockFactory.expr(), Eigen::TensorEvaluator< const TensorSelectOp< IfArgType, ThenArgType, ElseArgType >, Device >::TensorSelectOpBlockFactory.expr(), Eigen::internal.gemmKernel(), gemv_complex_col(), gemv_complex_row(), rapidjson::GenericValue< Encoding, Allocator >.GenericValue(), oomph::GeompackQuadScaffoldMesh.GeompackQuadScaffoldMesh(), MeshTriangle.getDistanceAndNormal(), MeshTriangle.getDistanceNormalOverlapType(), MeshTriangle.getInteractionWith(), CFile.getName(), ParticleHandler.getParticleAttribute(), ParticleHandler.getParticleAttributeLocal(), Eigen::internal::h_skip< n >.helper(), inputfile_t.inputfile_t(), load(), main(), Eigen::PlainObjectBase< Derived >.Map(), Eigen::PlainObjectBase< Derived >.MapAligned(), Eigen::SparseMatrix< Scalar_, Options_, StorageIndex_ >.operator=(), packetmath_real(), MyGenerator.packetOp(), Eigen::PardisoImpl< Derived >.pardisoInit(), Eigen::internal::permutation_matrix_product< ExpressionType, Side, Transposed, SparseShape >.permute_inner(), Eigen::internal.pfrexp_generic(), Eigen::internal.predux_half_dowto4(), rapidjson::Writer< Stream, Encoding, Allocator >.Prefix(), rapidjson::PrettyWriter< Stream, Encoding, Allocator >.PrettyPrefix(), Eigen::SelfAdjointView< MatrixType_, UpLo >.rankUpdate(), RNG.read(), SinterLinNormalSpecies.read(), SinterNormalSpecies.read(), InsertionBoundary.read(), BaseWall.read(), BasicIntersectionOfWalls.read(), BasicUnionOfWalls.read(), BoundaryHandler.readAndAddObject(), InteractionHandler.readAndAddObject(), SpeciesHandler.readAndAddObject(), ParticleHandler.readAndCreateObject(), WallHandler.readAndCreateObject(), MPIContainer.receive(), Eigen::Ref< const TPlainObjectType, Options, StrideType >.Ref(), Eigen::Ref< const SparseMatrix< MatScalar, MatOptions, MatIndex >, Options, StrideType >.Ref(), Eigen::Ref< const SparseVector< MatScalar, MatOptions, MatIndex >, Options, StrideType >.Ref(), Eigen::internal::CompressedStorage< Scalar_, StorageIndex_ >.resize(), Eigen::internal.returnUnsignedIndexValue(), cast_tests_impl< RowsAtCompileTime, ColsAtCompileTime, ScalarTypes >.run(), Eigen::internal::pardiso_run_selector< IndexType >.run(), Eigen::internal::pardiso_run_selector< long long int >.run(), Eigen::internal::conservative_sparse_sparse_product_selector< Lhs, Rhs, ResultType, ColMajor, ColMajor, ColMajor >.run(), Eigen::internal::tensor_static_symgroup_do_apply< internal::type_list< first, next... > >.run(), Eigen::internal::cross3_impl< Arch, VectorLhs, VectorRhs, Scalar, Vectorizable >.run(), Eigen::internal::general_matrix_vector_product< Index, LhsScalar, LhsMapper, RowMajor, ConjugateLhs, RhsScalar, RhsMapper, ConjugateRhs, Version >.run(), Eigen::internal::general_matrix_matrix_triangular_product< Index, LhsScalar, LhsStorageOrder, ConjugateLhs, RhsScalar, RhsStorageOrder, ConjugateRhs, ColMajor, ResInnerStride, UpLo, Version >.run(), run_on_gpu(), Eigen::internal.run_serialized(), Eigen::internal::generic_product_impl< Lhs, Rhs, SparseShape, DenseShape, ProductType >.scaleAndAddTo(), Eigen::internal::generic_product_impl< Lhs, Rhs, DenseShape, SparseShape, ProductType >.scaleAndAddTo(), MPIContainer.send(), Domain.sendAndReceiveMPIData(), FSICollapsibleChannelProblem< ELEMENT >.set_initial_condition(), CollapsibleChannelProblem< ELEMENT >.set_initial_condition(), RayleighProblem< ELEMENT, TIMESTEPPER >.set_initial_condition(), CGFields::LiquidMigrationFields.setCylindricalFields(), CGFields::StandardFields.setCylindricalFields(), CGFields::StandardFields.setFields(), RNG.setRandomNumberGenerator(), WallDetailsVTKWriter.shouldWrite(), test_concat(), test_eigen_type(), Detail.toVTKDataType(), Eigen::internal.triSolveKernelLxK(), Eigen::internal::tuple_impl.tuple_cat(), and SolidProblem< ELEMENT_TYPE >.writeToVTK().