From 96ad358f83ebcf5d561fb0d33855b45564635289 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Tue, 15 Sep 2020 00:58:06 -0400 Subject: [PATCH 01/61] modified file reading/writing methods to load_X, save_X formalism --- PRIVATE | 2 +- processing/legacy/addAPS34IDEstrainCoords.py | 9 +- processing/legacy/addCumulative.py | 10 +- processing/post/DADF5_postResults.py | 6 +- processing/post/addCompatibilityMismatch.py | 4 +- processing/post/addCurl.py | 4 +- processing/post/addDerivative.py | 10 +- processing/post/addDisplacement.py | 14 +- processing/post/addDivergence.py | 4 +- processing/post/addEuclideanDistance.py | 6 +- processing/post/addGaussian.py | 4 +- processing/post/addGradient.py | 4 +- processing/post/addOrientations.py | 4 +- processing/post/addSchmidfactors.py | 4 +- processing/post/filterTable.py | 18 +- processing/post/permuteData.py | 4 +- processing/pre/geom_fromDREAM3D.py | 2 +- processing/pre/geom_fromMinimalSurface.py | 2 +- processing/pre/geom_fromOsteonGeometry.py | 2 +- processing/pre/geom_fromTable.py | 5 +- .../pre/geom_fromVoronoiTessellation.py | 5 +- processing/pre/geom_grainGrowth.py | 6 +- processing/pre/hybridIA_linODFsampling.py | 48 +-- processing/pre/mentat_spectralBox.py | 14 +- processing/pre/seeds_fromDistribution.py | 19 +- processing/pre/seeds_fromGeom.py | 8 +- processing/pre/seeds_fromPokes.py | 8 +- processing/pre/seeds_fromRandom.py | 6 +- python/damask/_colormap.py | 128 ++++---- python/damask/_geom.py | 196 ++++++------- python/damask/_result.py | 4 +- python/damask/_table.py | 92 +++--- python/damask/_test.py | 59 ++-- python/damask/_vtk.py | 4 +- ...sualize_hybridIA_sampling-checkpoint.ipynb | 6 + .../Visualize_hybridIA_sampling.ipynb | 276 ++++++++++++++++++ python/tests/test_Colormap.py | 39 ++- python/tests/test_Geom.py | 48 ++- python/tests/test_Orientation.py | 3 +- python/tests/test_Result.py | 2 +- python/tests/test_Table.py | 36 +-- python/tests/test_VTK.py | 38 +-- 42 files changed, 708 insertions(+), 455 deletions(-) create mode 100644 python/tests/reference/Rotation/.ipynb_checkpoints/Visualize_hybridIA_sampling-checkpoint.ipynb create mode 100644 python/tests/reference/Rotation/Visualize_hybridIA_sampling.ipynb diff --git a/PRIVATE b/PRIVATE index 65ec74c07..5b7c34e58 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 65ec74c07052e77f35a4b5e80bf110aff1f5ae61 +Subproject commit 5b7c34e586589141d1e061f021512e65308fc1f7 diff --git a/processing/legacy/addAPS34IDEstrainCoords.py b/processing/legacy/addAPS34IDEstrainCoords.py index 9ba51ada1..c82ff35a3 100755 --- a/processing/legacy/addAPS34IDEstrainCoords.py +++ b/processing/legacy/addAPS34IDEstrainCoords.py @@ -42,11 +42,10 @@ rot_to_TSL = damask.Rotation.from_axis_angle([-1,0,0,.75*np.pi]) for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) - + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + coord = - table.get(options.frame) coord[:,2] += table.get(options.depth)[:,0] - table.add('coord',rot_to_TSL.broadcast_to(coord.shape[0]) @ coord,scriptID+' '+' '.join(sys.argv[1:])) - - table.to_file(sys.stdout if name is None else name) + table.add('coord',rot_to_TSL.broadcast_to(coord.shape[0]) @ coord,scriptID+' '+' '.join(sys.argv[1:]))\ + .save_ASCII(sys.stdout if name is None else name) diff --git a/processing/legacy/addCumulative.py b/processing/legacy/addCumulative.py index f84828a89..14d8bcfea 100755 --- a/processing/legacy/addCumulative.py +++ b/processing/legacy/addCumulative.py @@ -39,10 +39,10 @@ if options.labels is None: for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) for label in options.labels: - table.add('cum_{}({})'.format('prod' if options.product else 'sum',label), - np.cumprod(table.get(label),0) if options.product else np.cumsum(table.get(label),0), - scriptID+' '+' '.join(sys.argv[1:])) + table = table.add('cum_{}({})'.format('prod' if options.product else 'sum',label), + np.cumprod(table.get(label),0) if options.product else np.cumsum(table.get(label),0), + scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/DADF5_postResults.py b/processing/post/DADF5_postResults.py index e81330581..fa9df27b0 100755 --- a/processing/post/DADF5_postResults.py +++ b/processing/post/DADF5_postResults.py @@ -38,8 +38,8 @@ for filename in options.filenames: N_digits = int(np.floor(np.log10(int(results.increments[-1][3:]))))+1 N_digits = 5 # hack to keep test intact for inc in damask.util.show_progress(results.iterate('increments'),len(results.increments)): - table = damask.Table(np.ones(np.product(results.grid),dtype=int)*int(inc[3:]),{'inc':(1,)}) - table = table.add('pos',coords.reshape(-1,3)) + table = damask.Table(np.ones(np.product(results.grid),dtype=int)*int(inc[3:]),{'inc':(1,)})\ + .add('pos',coords.reshape(-1,3)) results.pick('materialpoints',False) results.pick('constituents', True) @@ -60,4 +60,4 @@ for filename in options.filenames: os.mkdir(dirname,0o755) file_out = '{}_inc{}.txt'.format(os.path.splitext(os.path.split(filename)[-1])[0], inc[3:].zfill(N_digits)) - table.to_file(os.path.join(dirname,file_out)) + table.save_ASCII(os.path.join(dirname,file_out)) diff --git a/processing/post/addCompatibilityMismatch.py b/processing/post/addCompatibilityMismatch.py index 5009d44a0..e274092d2 100755 --- a/processing/post/addCompatibilityMismatch.py +++ b/processing/post/addCompatibilityMismatch.py @@ -172,7 +172,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) F = table.get(options.defgrad).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3)) @@ -191,4 +191,4 @@ for name in filenames: volumeMismatch.reshape(-1,1,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addCurl.py b/processing/post/addCurl.py index 1033e3303..9adb06a00 100755 --- a/processing/post/addCurl.py +++ b/processing/post/addCurl.py @@ -43,7 +43,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) for label in options.labels: @@ -55,4 +55,4 @@ for name in filenames: curl.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape),order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addDerivative.py b/processing/post/addDerivative.py index b6b19c98a..179715e23 100755 --- a/processing/post/addDerivative.py +++ b/processing/post/addDerivative.py @@ -14,9 +14,9 @@ scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptID = ' '.join([scriptName,damask.version]) def derivative(coordinates,what): - + result = np.empty_like(what) - + # use differentiation by interpolation # as described in http://www2.math.umd.edu/~dlevy/classes/amsc466/lecture-notes/differentiation-chap.pdf @@ -31,7 +31,7 @@ def derivative(coordinates,what): (coordinates[0] - coordinates[1]) result[-1,:] = (what[-1,:] - what[-2,:]) / \ (coordinates[-1] - coordinates[-2]) - + return result @@ -65,10 +65,10 @@ if options.labels is None: for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) for label in options.labels: table = table.add('d({})/d({})'.format(label,options.coordinates), derivative(table.get(options.coordinates),table.get(label)), scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addDisplacement.py b/processing/post/addDisplacement.py index f1ab565b0..8dc3051d3 100755 --- a/processing/post/addDisplacement.py +++ b/processing/post/addDisplacement.py @@ -47,25 +47,25 @@ parser.set_defaults(f = 'f', for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) F = table.get(options.f).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3)) if options.nodal: - table = damask.Table(damask.grid_filters.node_coord0(grid,size).reshape(-1,3,order='F'), + damask.Table(damask.grid_filters.node_coord0(grid,size).reshape(-1,3,order='F'), {'pos':(3,)})\ .add('avg({}).{}'.format(options.f,options.pos), damask.grid_filters.node_displacement_avg(size,F).reshape(-1,3,order='F'), scriptID+' '+' '.join(sys.argv[1:]))\ .add('fluct({}).{}'.format(options.f,options.pos), damask.grid_filters.node_displacement_fluct(size,F).reshape(-1,3,order='F'), - scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt') + scriptID+' '+' '.join(sys.argv[1:]))\ + .save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt') else: - table = table.add('avg({}).{}'.format(options.f,options.pos), + table.add('avg({}).{}'.format(options.f,options.pos), damask.grid_filters.cell_displacement_avg(size,F).reshape(-1,3,order='F'), scriptID+' '+' '.join(sys.argv[1:]))\ .add('fluct({}).{}'.format(options.f,options.pos), damask.grid_filters.cell_displacement_fluct(size,F).reshape(-1,3,order='F'), - scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + scriptID+' '+' '.join(sys.argv[1:]))\ + .save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addDivergence.py b/processing/post/addDivergence.py index 6495793cf..b4c0bb7b4 100755 --- a/processing/post/addDivergence.py +++ b/processing/post/addDivergence.py @@ -43,7 +43,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) for label in options.labels: @@ -55,4 +55,4 @@ for name in filenames: div.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape)//3,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addEuclideanDistance.py b/processing/post/addEuclideanDistance.py index f5cf58ab3..305fc2ad5 100755 --- a/processing/post/addEuclideanDistance.py +++ b/processing/post/addEuclideanDistance.py @@ -142,7 +142,7 @@ for i,feature in enumerate(features): for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) neighborhood = neighborhoods[options.neighborhood] @@ -158,7 +158,7 @@ for name in filenames: diffToNeighbor[:,:,:,i] = ndimage.convolve(microstructure,stencil) # compare ID at each point... # ...to every one in the specified neighborhood # for same IDs at both locations ==> 0 - + diffToNeighbor = np.sort(diffToNeighbor) # sort diff such that number of changes in diff (steps)... # ...reflects number of unique neighbors uniques = np.where(diffToNeighbor[1:-1,1:-1,1:-1,0] != 0, 1,0) # initialize unique value counter (exclude myself [= 0]) @@ -184,4 +184,4 @@ for name in filenames: distance[i,:], scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addGaussian.py b/processing/post/addGaussian.py index 8e58da884..708617c1f 100755 --- a/processing/post/addGaussian.py +++ b/processing/post/addGaussian.py @@ -63,7 +63,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) damask.grid_filters.coord0_check(table.get(options.pos)) for label in options.labels: @@ -73,4 +73,4 @@ for name in filenames: mode = 'wrap' if options.periodic else 'nearest'), scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addGradient.py b/processing/post/addGradient.py index 718a972f3..e216ed34c 100755 --- a/processing/post/addGradient.py +++ b/processing/post/addGradient.py @@ -43,7 +43,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) for label in options.labels: @@ -55,4 +55,4 @@ for name in filenames: grad.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape)*3,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addOrientations.py b/processing/post/addOrientations.py index dddc14193..3a320241c 100755 --- a/processing/post/addOrientations.py +++ b/processing/post/addOrientations.py @@ -110,7 +110,7 @@ R = damask.Rotation.from_axis_angle(np.array(options.labrotation),options.degree for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) if options.eulers is not None: label = options.eulers @@ -147,4 +147,4 @@ for name in filenames: if 'axisangle' in options.output: table = table.add('om({})'.format(label),o.as_axisangle(options.degrees), scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/addSchmidfactors.py b/processing/post/addSchmidfactors.py index dc4117d78..40db4da34 100755 --- a/processing/post/addSchmidfactors.py +++ b/processing/post/addSchmidfactors.py @@ -175,7 +175,7 @@ labels = ['S[{direction[0]:.1g}_{direction[1]:.1g}_{direction[2]:.1g}]' for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) o = damask.Rotation.from_quaternion(table.get(options.quaternion)) @@ -189,4 +189,4 @@ for name in filenames: for i,label in enumerate(labels): table = table.add(label,S[:,i],scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/post/filterTable.py b/processing/post/filterTable.py index 494257a60..4f4af088b 100755 --- a/processing/post/filterTable.py +++ b/processing/post/filterTable.py @@ -27,7 +27,7 @@ def sortingList(labels,whitelistitems): else: indices.append(0) names.append(label) - + return [indices,names,whitelistitems] @@ -72,11 +72,11 @@ for name in filenames: continue damask.util.report(scriptName,name) -# ------------------------------------------ assemble info --------------------------------------- +# ------------------------------------------ assemble info --------------------------------------- table.head_read() -# ------------------------------------------ process data --------------------------------------- +# ------------------------------------------ process data --------------------------------------- specials = { \ '_row_': 0, @@ -103,12 +103,12 @@ for name in filenames: else np.lexsort(sortingList(labels,whitelistitem)) # reorder if unique, i.e. no "-1" in whitelistitem else: order = range(len(labels)) # maintain original order of labels - + # --------------------------------------- evaluate condition --------------------------------------- if options.condition is not None: condition = options.condition # copy per file, since might be altered inline breaker = False - + for position,(all,marker,column) in enumerate(set(re.findall(r'#(([s]#)?(.+?))#',condition))): # find three groups idx = table.label_index(column) dim = table.label_dimension(column) @@ -123,11 +123,11 @@ for name in filenames: 's#':'str'}[marker],idx) # take float or string value of data column elif dim > 1: # multidimensional input (vector, tensor, etc.) replacement = 'np.array(table.data[{}:{}],dtype=float)'.format(idx,idx+dim) # use (flat) array representation - + condition = condition.replace('#'+all+'#',replacement) - + if breaker: continue # found mistake in condition evaluation --> next file - + # ------------------------------------------ assemble header --------------------------------------- table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:])) @@ -138,7 +138,7 @@ for name in filenames: # ------------------------------------------ process and output data ------------------------------------------ positions = np.array(positions)[order] - + atOnce = options.condition is None if atOnce: # read full array and filter columns try: diff --git a/processing/post/permuteData.py b/processing/post/permuteData.py index 316fdd3da..af184924d 100755 --- a/processing/post/permuteData.py +++ b/processing/post/permuteData.py @@ -47,7 +47,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) randomSeed = int(os.urandom(4).hex(), 16) if options.randomSeed is None else options.randomSeed # random seed per file rng = np.random.default_rng(randomSeed) @@ -58,4 +58,4 @@ for name in filenames: rng.shuffle(uniques) table = table.set(label,uniques[inverse], scriptID+' '+' '.join(sys.argv[1:])) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/processing/pre/geom_fromDREAM3D.py b/processing/pre/geom_fromDREAM3D.py index 6b7ccc21a..471435766 100755 --- a/processing/pre/geom_fromDREAM3D.py +++ b/processing/pre/geom_fromDREAM3D.py @@ -154,4 +154,4 @@ for name in filenames: homogenization=options.homogenization,comments=header) damask.util.croak(geom) - geom.to_file(os.path.splitext(name)[0]+'.geom',format='ASCII',pack=False) + geom.save_ASCII(os.path.splitext(name)[0]+'.geom',pack=False) diff --git a/processing/pre/geom_fromMinimalSurface.py b/processing/pre/geom_fromMinimalSurface.py index e6289ba0a..b64bac417 100755 --- a/processing/pre/geom_fromMinimalSurface.py +++ b/processing/pre/geom_fromMinimalSurface.py @@ -89,4 +89,4 @@ geom=damask.Geom(microstructure,options.size, comments=[scriptID + ' ' + ' '.join(sys.argv[1:])]) damask.util.croak(geom) -geom.to_file(sys.stdout if name is None else name,format='ASCII',pack=False) +geom.save_ASCII(sys.stdout if name is None else name,pack=False) diff --git a/processing/pre/geom_fromOsteonGeometry.py b/processing/pre/geom_fromOsteonGeometry.py index 6c6326163..c2583d0ed 100755 --- a/processing/pre/geom_fromOsteonGeometry.py +++ b/processing/pre/geom_fromOsteonGeometry.py @@ -142,4 +142,4 @@ geom = damask.Geom(microstructure.reshape(grid), homogenization=options.homogenization,comments=header) damask.util.croak(geom) -geom.to_file(sys.stdout if name is None else name,format='ASCII',pack=False) +geom.save_ASCII(sys.stdout if name is None else name,pack=False) diff --git a/processing/pre/geom_fromTable.py b/processing/pre/geom_fromTable.py index dc968b82e..11c0761b5 100755 --- a/processing/pre/geom_fromTable.py +++ b/processing/pre/geom_fromTable.py @@ -68,7 +68,7 @@ if options.axes is not None and not set(options.axes).issubset(set(['x','+x','-x for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) table.sort_by(['{}_{}'.format(i,options.pos) for i in range(3,0,-1)]) # x fast, y slow grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) @@ -105,5 +105,4 @@ for name in filenames: homogenization=options.homogenization,comments=header) damask.util.croak(geom) - geom.to_file(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom', - format='ASCII',pack=False) + geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',pack=False) diff --git a/processing/pre/geom_fromVoronoiTessellation.py b/processing/pre/geom_fromVoronoiTessellation.py index 67a0dfecc..a3a54882a 100755 --- a/processing/pre/geom_fromVoronoiTessellation.py +++ b/processing/pre/geom_fromVoronoiTessellation.py @@ -171,7 +171,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) size = np.ones(3) origin = np.zeros(3) @@ -228,5 +228,4 @@ for name in filenames: homogenization=options.homogenization,comments=header) damask.util.croak(geom) - geom.to_file(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom', - format='ASCII',pack=False) + geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',pack=False) diff --git a/processing/pre/geom_grainGrowth.py b/processing/pre/geom_grainGrowth.py index 0652d0583..dbe1f1a74 100755 --- a/processing/pre/geom_grainGrowth.py +++ b/processing/pre/geom_grainGrowth.py @@ -62,7 +62,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) + geom = damask.Geom.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) grid_original = geom.get_grid() damask.util.croak(geom) @@ -169,7 +169,7 @@ for name in filenames: # undo any changes involving immutable microstructures microstructure = np.where(immutable, microstructure_original,microstructure) - geom=geom.duplicate(microstructure[0:grid_original[0],0:grid_original[1],0:grid_original[2]]) + geom = geom.duplicate(microstructure[0:grid_original[0],0:grid_original[1],0:grid_original[2]]) geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:])) - geom.to_file(sys.stdout if name is None else name,format='ASCII',pack=False) + geom.save_ASCII(sys.stdout if name is None else name,pack=False) diff --git a/processing/pre/hybridIA_linODFsampling.py b/processing/pre/hybridIA_linODFsampling.py index 6f5827f8b..01704197e 100755 --- a/processing/pre/hybridIA_linODFsampling.py +++ b/processing/pre/hybridIA_linODFsampling.py @@ -31,7 +31,7 @@ def binAsBins(bin,intervals): bins[1] = (bin//intervals[2]) % intervals[1] bins[2] = bin % intervals[2] return bins - + def binsAsBin(bins,intervals): """Implode 3D bins into compound bin.""" return (bins[0]*intervals[1] + bins[1])*intervals[2] + bins[2] @@ -95,7 +95,7 @@ def directInversion (ODF,nSamples): float(nInvSamples)/nOptSamples-1.0, scale,nSamples)) repetition = [None]*ODF['nBins'] # preallocate and clear - + for bin in range(ODF['nBins']): # loop over bins repetition[bin] = int(round(ODF['dV_V'][bin]*scale)) # calc repetition @@ -105,7 +105,7 @@ def directInversion (ODF,nSamples): for bin in range(ODF['nBins']): set[i:i+repetition[bin]] = [bin]*repetition[bin] # fill set with bin, i.e. orientation i += repetition[bin] # advance set counter - + orientations = np.zeros((nSamples,3),'f') reconstructedODF = np.zeros(ODF['nBins'],'f') unitInc = 1.0/nSamples @@ -117,7 +117,7 @@ def directInversion (ODF,nSamples): orientations[j] = np.degrees(Eulers) reconstructedODF[bin] += unitInc set[ex] = set[j] # exchange orientations - + return orientations, reconstructedODF @@ -130,7 +130,7 @@ def MonteCarloEulers (ODF,nSamples): orientations = np.zeros((nSamples,3),'f') reconstructedODF = np.zeros(ODF['nBins'],'f') unitInc = 1.0/nSamples - + for j in range(nSamples): MC = maxdV_V*2.0 bin = 0 @@ -153,7 +153,7 @@ def MonteCarloBins (ODF,nSamples): orientations = np.zeros((nSamples,3),'f') reconstructedODF = np.zeros(ODF['nBins'],'f') unitInc = 1.0/nSamples - + for j in range(nSamples): MC = maxdV_V*2.0 bin = 0 @@ -173,14 +173,14 @@ def TothVanHoutteSTAT (ODF,nSamples): orientations = np.zeros((nSamples,3),'f') reconstructedODF = np.zeros(ODF['nBins'],'f') unitInc = 1.0/nSamples - + selectors = [random.random() for i in range(nSamples)] selectors.sort() indexSelector = 0 - + cumdV_V = 0.0 countSamples = 0 - + for bin in range(ODF['nBins']) : cumdV_V += ODF['dV_V'][bin] while indexSelector < nSamples and selectors[indexSelector] < cumdV_V: @@ -191,7 +191,7 @@ def TothVanHoutteSTAT (ODF,nSamples): indexSelector += 1 damask.util.croak('created set of %i when asked to deliver %i'%(countSamples,nSamples)) - + return orientations, reconstructedODF @@ -233,8 +233,8 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - - table = damask.Table.from_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + + table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) randomSeed = int(os.urandom(4).hex(),16) if options.randomSeed is None else options.randomSeed # random seed per file random.seed(randomSeed) @@ -253,7 +253,7 @@ for name in filenames: if eulers.shape[0] != ODF['nBins']: damask.util.croak('expecting %i values but got %i'%(ODF['nBins'],eulers.shape[0])) continue - + # ----- build binnedODF array and normalize ------------------------------------------------------ sumdV_V = 0.0 ODF['dV_V'] = [None]*ODF['nBins'] @@ -267,7 +267,7 @@ for name in filenames: if ODF['dV_V'][b] > 0.0: sumdV_V += ODF['dV_V'][b] ODF['nNonZero'] += 1 - + for b in range(ODF['nBins']): ODF['dV_V'][b] /= sumdV_V # normalize dV/V @@ -277,19 +277,19 @@ for name in filenames: 'Volume integral of ODF: %12.11f\n'%sumdV_V, 'Reference Integral: %12.11f\n'%(ODF['limit'][0]*ODF['limit'][2]*(1-math.cos(ODF['limit'][1]))), ]) - + Functions = {'IA': 'directInversion', 'STAT': 'TothVanHoutteSTAT', 'MC': 'MonteCarloBins'} method = Functions[options.algorithm] Orientations, ReconstructedODF = (globals()[method])(ODF,options.number) - + # calculate accuracy of sample squaredDiff = {'orig':0.0,method:0.0} squaredRelDiff = {'orig':0.0,method:0.0} mutualProd = {'orig':0.0,method:0.0} indivSum = {'orig':0.0,method:0.0} indivSquaredSum = {'orig':0.0,method:0.0} - + for bin in range(ODF['nBins']): squaredDiff[method] += (ODF['dV_V'][bin] - ReconstructedODF[bin])**2 if ODF['dV_V'][bin] > 0.0: @@ -299,7 +299,7 @@ for name in filenames: indivSquaredSum[method] += ReconstructedODF[bin]**2 indivSum['orig'] += ODF['dV_V'][bin] indivSquaredSum['orig'] += ODF['dV_V'][bin]**2 - + damask.util.croak(['sqrt(N*)RMSD of ODFs:\t %12.11f'% math.sqrt(options.number*squaredDiff[method]), 'RMSrD of ODFs:\t %12.11f'%math.sqrt(squaredRelDiff[method]), 'rMSD of ODFs:\t %12.11f'%(squaredDiff[method]/indivSquaredSum['orig']), @@ -311,10 +311,10 @@ for name in filenames: (ODF['nNonZero']*math.sqrt((indivSquaredSum['orig']/ODF['nNonZero']-(indivSum['orig']/ODF['nNonZero'])**2)*\ (indivSquaredSum[method]/ODF['nNonZero']-(indivSum[method]/ODF['nNonZero'])**2)))), ]) - + if method == 'IA' and options.number < ODF['nNonZero']: strOpt = '(%i)'%ODF['nNonZero'] - + formatwidth = 1+int(math.log10(options.number)) materialConfig = [ @@ -324,12 +324,12 @@ for name in filenames: '', '#-------------------#', ] - + for i,ID in enumerate(range(options.number)): materialConfig += ['[Grain%s]'%(str(ID+1).zfill(formatwidth)), '(constituent) phase %i texture %s fraction 1.0'%(options.phase,str(ID+1).rjust(formatwidth)), ] - + materialConfig += [ '#-------------------#', '', @@ -338,12 +338,12 @@ for name in filenames: for ID in range(options.number): eulers = Orientations[ID] - + materialConfig += ['[Grain%s]'%(str(ID+1).zfill(formatwidth)), '(gauss) phi1 {} Phi {} phi2 {} scatter 0.0 fraction 1.0'.format(*eulers), ] -#--- output finalization -------------------------------------------------------------------------- +#--- output finalization -------------------------------------------------------------------------- with (open(os.path.splitext(name)[0]+'_'+method+'_'+str(options.number)+'_material.config','w')) as outfile: outfile.write('\n'.join(materialConfig)+'\n') diff --git a/processing/pre/mentat_spectralBox.py b/processing/pre/mentat_spectralBox.py index 027240044..e9a246f8f 100755 --- a/processing/pre/mentat_spectralBox.py +++ b/processing/pre/mentat_spectralBox.py @@ -42,7 +42,7 @@ def output(cmds,locals,dest): else: outFile(str(cmd),locals,dest) - + #------------------------------------------------------------------------------------------------- def init(): return [ @@ -114,7 +114,7 @@ def material(): "*add_geometry_elements", "all_existing", ] - + #------------------------------------------------------------------------------------------------- def geometry(): @@ -127,14 +127,14 @@ def geometry(): "*element_type 7", "all_existing", ] - + #------------------------------------------------------------------------------------------------- def initial_conditions(microstructures): elements = [] element = 0 for id in microstructures: - element += 1 + element += 1 if len(elements) < id: for i in range(id-len(elements)): elements.append([]) @@ -195,8 +195,8 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - - geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) + + geom = damask.Geom.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) microstructure = geom.get_microstructure().flatten(order='F') cmds = [\ @@ -210,7 +210,7 @@ for name in filenames: '*redraw', '*draw_automatic', ] - + outputLocals = {} if options.port: py_mentat.py_connect('',options.port) diff --git a/processing/pre/seeds_fromDistribution.py b/processing/pre/seeds_fromDistribution.py index 1a4ec6971..1cf35450c 100755 --- a/processing/pre/seeds_fromDistribution.py +++ b/processing/pre/seeds_fromDistribution.py @@ -78,7 +78,7 @@ class myThread (threading.Thread): perturbedSeedsVFile = StringIO() myBestSeedsVFile.seek(0) - perturbedSeedsTable = damask.Table.from_ASCII(myBestSeedsVFile) + perturbedSeedsTable = damask.Table.load_ASCII(myBestSeedsVFile) coords = perturbedSeedsTable.get('pos') i = 0 for ms,coord in enumerate(coords): @@ -89,8 +89,7 @@ class myThread (threading.Thread): coords[i]=newCoords direction[i]*=2. i+= 1 - perturbedSeedsTable.set('pos',coords) - perturbedSeedsTable.to_file(perturbedSeedsVFile) + perturbedSeedsTable.set('pos',coords).save_ASCII(perturbedSeedsVFile) #--- do tesselation with perturbed seed file ------------------------------------------------------ perturbedGeomVFile.close() @@ -101,7 +100,7 @@ class myThread (threading.Thread): perturbedGeomVFile.seek(0) #--- evaluate current seeds file ------------------------------------------------------------------ - perturbedGeom = damask.Geom.from_file(perturbedGeomVFile) + perturbedGeom = damask.Geom.load_ASCII(perturbedGeomVFile) myNmicrostructures = len(np.unique(perturbedGeom.microstructure)) currentData=np.bincount(perturbedGeom.microstructure.ravel())[1:]/points currentError=[] @@ -213,14 +212,14 @@ if options.randomSeed is None: options.randomSeed = int(os.urandom(4).hex(),16) damask.util.croak(options.randomSeed) delta = options.scale/np.array(options.grid) -baseFile=os.path.splitext(os.path.basename(options.seedFile))[0] +baseFile = os.path.splitext(os.path.basename(options.seedFile))[0] points = np.array(options.grid).prod().astype('float') # ----------- calculate target distribution and bin edges -targetGeom = damask.Geom.from_file(os.path.splitext(os.path.basename(options.target))[0]+'.geom') +targetGeom = damask.Geom.load_ASCII(os.path.splitext(os.path.basename(options.target))[0]+'.geom') nMicrostructures = len(np.unique(targetGeom.microstructure)) targetVolFrac = np.bincount(targetGeom.microstructure.flatten())/targetGeom.grid.prod().astype(np.float) -target=[] +target = [] for i in range(1,nMicrostructures+1): targetHist,targetBins = np.histogram(targetVolFrac,bins=i) #bin boundaries target.append({'histogram':targetHist,'bins':targetBins}) @@ -243,7 +242,7 @@ initialGeomVFile = StringIO() initialGeomVFile.write(damask.util.execute('geom_fromVoronoiTessellation '+ ' -g '+' '.join(list(map(str, options.grid))),bestSeedsVFile)[0]) initialGeomVFile.seek(0) -initialGeom = damask.Geom.from_file(initialGeomVFile) +initialGeom = damask.Geom.load_ASCII(initialGeomVFile) if len(np.unique(targetGeom.microstructure)) != nMicrostructures: damask.util.croak('error. Microstructure count mismatch') @@ -273,8 +272,8 @@ sys.stdout.flush() initialGeomVFile.close() # start mulithreaded monte carlo simulation -threads=[] -s=threading.Semaphore(1) +threads = [] +s = threading.Semaphore(1) for i in range(options.threads): threads.append(myThread(i)) diff --git a/processing/pre/seeds_fromGeom.py b/processing/pre/seeds_fromGeom.py index 97550ce13..95f0d3815 100755 --- a/processing/pre/seeds_fromGeom.py +++ b/processing/pre/seeds_fromGeom.py @@ -46,7 +46,7 @@ options.blacklist = [int(i) for i in options.blacklist] for name in filenames: damask.util.report(scriptName,name) - geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) + geom = damask.Geom.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) microstructure = geom.get_microstructure().reshape((-1,1),order='F') mask = np.logical_and(np.in1d(microstructure,options.whitelist,invert=False) if options.whitelist else \ @@ -63,6 +63,6 @@ for name in filenames: 'origin\tx {}\ty {}\tz {}'.format(*geom.origin), 'homogenization\t{}'.format(geom.homogenization)] - table = damask.Table(seeds[mask],{'pos':(3,)},comments) - table = table.add('microstructure',microstructure[mask]) - table.to_file(sys.stdout if name is None else os.path.splitext(name)[0]+'.seeds') + damask.Table(seeds[mask],{'pos':(3,)},comments)\ + .add('microstructure',microstructure[mask].astype(int))\ + .save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.seeds') diff --git a/processing/pre/seeds_fromPokes.py b/processing/pre/seeds_fromPokes.py index 78172fc23..5deb0ab1a 100755 --- a/processing/pre/seeds_fromPokes.py +++ b/processing/pre/seeds_fromPokes.py @@ -52,7 +52,7 @@ options.box = np.array(options.box).reshape(3,2) for name in filenames: damask.util.report(scriptName,name) - geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) + geom = damask.Geom.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) offset =(np.amin(options.box, axis=1)*geom.grid/geom.size).astype(int) box = np.amax(options.box, axis=1) \ @@ -91,6 +91,6 @@ for name in filenames: 'homogenization\t{}'.format(geom.homogenization)] table = damask.Table(seeds,{'pos':(3,),'microstructure':(1,)},comments) - table.set('microstructure',table.get('microstructure').astype(np.int)) - table.to_file(sys.stdout if name is None else \ - os.path.splitext(name)[0]+f'_poked_{options.N}.seeds') + table.set('microstructure',table.get('microstructure').astype(np.int))\ + .save_ASCII(sys.stdout if name is None else \ + os.path.splitext(name)[0]+f'_poked_{options.N}.seeds') diff --git a/processing/pre/seeds_fromRandom.py b/processing/pre/seeds_fromRandom.py index a544528cf..c1d454f67 100755 --- a/processing/pre/seeds_fromRandom.py +++ b/processing/pre/seeds_fromRandom.py @@ -154,12 +154,12 @@ for name in filenames: 'randomSeed\t{}'.format(options.randomSeed), ] - table = damask.Table(np.hstack((seeds,eulers)),{'pos':(3,),'euler':(3,)},comments) - table = table.add('microstructure',np.arange(options.microstructure,options.microstructure + options.N,dtype=int)) + table = damask.Table(np.hstack((seeds,eulers)),{'pos':(3,),'euler':(3,)},comments)\ + .add('microstructure',np.arange(options.microstructure,options.microstructure + options.N,dtype=int)) if options.weights: weights = np.random.uniform(low = 0, high = options.max, size = options.N) if options.max > 0.0 \ else np.random.normal(loc = options.mean, scale = options.sigma, size = options.N) table = table.add('weight',weights) - table.to_file(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name) diff --git a/python/damask/_colormap.py b/python/damask/_colormap.py index fccb8642b..f3065ebc8 100644 --- a/python/damask/_colormap.py +++ b/python/damask/_colormap.py @@ -235,100 +235,128 @@ class Colormap(mpl.colors.ListedColormap): return Colormap(np.array(rev.colors),rev.name[:-4] if rev.name.endswith('_r_r') else rev.name) - def to_file(self,fname=None,format='ParaView'): + + def save_paraview(self,fname=None): """ - Export colormap to file for use in external programs. + Write colormap to JSON file for Paraview. Parameters ---------- fname : file, str, or pathlib.Path, optional. Filename to store results. If not given, the filename will - consist of the name of the colormap and an extension that - depends on the file format. - format : {'ParaView', 'ASCII', 'GOM', 'gmsh'}, optional - File format, defaults to 'ParaView'. Available formats are: - - ParaView: JSON file, extension '.json'. - - ASCII: Plain text file, extension '.txt'. - - GOM: Aramis GOM (DIC), extension '.legend'. - - Gmsh: Gmsh FEM mesh-generator, extension '.msh'. + consist of the name of the colormap and extension '.json'. """ if fname is not None: try: - f = open(fname,'w') + fhandle = open(fname,'w') except TypeError: - f = fname + fhandle = fname else: - f = None + fhandle = None - if format.lower() == 'paraview': - Colormap._export_paraview(self,f) - elif format.lower() == 'ascii': - Colormap._export_ASCII(self,f) - elif format.lower() == 'gom': - Colormap._export_GOM(self,f) - elif format.lower() == 'gmsh': - Colormap._export_gmsh(self,f) - else: - raise ValueError('Unknown output format: {format}.') - - @staticmethod - def _export_paraview(colormap,fhandle=None): - """Write colormap to JSON file for Paraview.""" colors = [] - for i,c in enumerate(np.round(colormap.colors,6).tolist()): + for i,c in enumerate(np.round(self.colors,6).tolist()): colors+=[i]+c out = [{ 'Creator':util.execution_stamp('Colormap'), 'ColorSpace':'RGB', - 'Name':colormap.name, + 'Name':self.name, 'DefaultMap':True, 'RGBPoints':colors }] if fhandle is None: - with open(colormap.name.replace(' ','_')+'.json', 'w') as f: + with open(self.name.replace(' ','_')+'.json', 'w') as f: json.dump(out, f,indent=4) else: json.dump(out,fhandle,indent=4) - @staticmethod - def _export_ASCII(colormap,fhandle=None): - """Write colormap to ASCII table.""" - labels = {'RGBA':4} if colormap.colors.shape[1] == 4 else {'RGB': 3} - t = Table(colormap.colors,labels,f'Creator: {util.execution_stamp("Colormap")}') + + def save_ASCII(self,fname=None): + """ + Write colormap to ASCII table. + + Parameters + ---------- + fname : file, str, or pathlib.Path, optional. + Filename to store results. If not given, the filename will + consist of the name of the colormap and extension '.txt'. + + """ + if fname is not None: + try: + fhandle = open(fname,'w') + except TypeError: + fhandle = fname + else: + fhandle = None + + labels = {'RGBA':4} if self.colors.shape[1] == 4 else {'RGB': 3} + t = Table(self.colors,labels,f'Creator: {util.execution_stamp("Colormap")}') if fhandle is None: - with open(colormap.name.replace(' ','_')+'.txt', 'w') as f: - t.to_file(f,new_style=True) + with open(self.name.replace(' ','_')+'.txt', 'w') as f: + t.save_ASCII(f) else: - t.to_file(fhandle,new_style=True) + t.save_ASCII(fhandle) - @staticmethod - def _export_GOM(colormap,fhandle=None): - """Write colormap to GOM Aramis compatible format.""" + + def save_GOM(self,fname=None): + """ + Write colormap to GOM Aramis compatible format. + + Parameters + ---------- + fname : file, str, or pathlib.Path, optional. + Filename to store results. If not given, the filename will + consist of the name of the colormap and extension '.legend'. + + """ + if fname is not None: + try: + fhandle = open(fname,'w') + except TypeError: + fhandle = fname + else: + fhandle = None # ToDo: test in GOM - GOM_str = f'1 1 {colormap.name.replace(" ","_")} 9 {colormap.name.replace(" ","_")} ' \ + GOM_str = '1 1 {name} 9 {name} '.format(name=self.name.replace(" ","_")) \ + '0 1 0 3 0 0 -1 9 \\ 0 0 0 255 255 255 0 0 255 ' \ - + f'30 NO_UNIT 1 1 64 64 64 255 1 0 0 0 0 0 0 3 0 {len(colormap.colors)}' \ - + ' '.join([f' 0 {c[0]} {c[1]} {c[2]} 255 1' for c in reversed((colormap.colors*255).astype(int))]) \ + + f'30 NO_UNIT 1 1 64 64 64 255 1 0 0 0 0 0 0 3 0 {len(self.colors)}' \ + + ' '.join([f' 0 {c[0]} {c[1]} {c[2]} 255 1' for c in reversed((self.colors*255).astype(int))]) \ + '\n' if fhandle is None: - with open(colormap.name.replace(' ','_')+'.legend', 'w') as f: + with open(self.name.replace(' ','_')+'.legend', 'w') as f: f.write(GOM_str) else: fhandle.write(GOM_str) - @staticmethod - def _export_gmsh(colormap,fhandle=None): - """Write colormap to Gmsh compatible format.""" + def save_gmsh(self,fname=None): + """ + Write colormap to Gmsh compatible format. + + Parameters + ---------- + fname : file, str, or pathlib.Path, optional. + Filename to store results. If not given, the filename will + consist of the name of the colormap and extension '.msh'. + + """ + if fname is not None: + try: + fhandle = open(fname,'w') + except TypeError: + fhandle = fname + else: + fhandle = None # ToDo: test in gmsh gmsh_str = 'View.ColorTable = {\n' \ - +'\n'.join([f'{c[0]},{c[1]},{c[2]},' for c in colormap.colors[:,:3]*255]) \ + +'\n'.join([f'{c[0]},{c[1]},{c[2]},' for c in self.colors[:,:3]*255]) \ +'\n}\n' if fhandle is None: - with open(colormap.name.replace(' ','_')+'.msh', 'w') as f: + with open(self.name.replace(' ','_')+'.msh', 'w') as f: f.write(gmsh_str) else: fhandle.write(gmsh_str) diff --git a/python/damask/_geom.py b/python/damask/_geom.py index f5dc05f2f..8fa0b533a 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -284,7 +284,7 @@ class Geom: @staticmethod - def from_file(fname): + def load_ASCII(fname): """ Read a geom file. @@ -350,7 +350,7 @@ class Geom: @staticmethod - def from_vtr(fname): + def load_vtr(fname): """ Read a VTK rectilinear grid. @@ -361,7 +361,7 @@ class Geom: Valid extension is .vtr, it will be appended if not given. """ - v = VTK.from_file(fname if str(fname).endswith('.vtr') else str(fname)+'.vtr') + v = VTK.load(fname if str(fname).endswith('.vtr') else str(fname)+'.vtr') comments = v.get_comments() grid = np.array(v.vtk_data.GetDimensions())-1 bbox = np.array(v.vtk_data.GetBounds()).reshape(3,2).T @@ -447,128 +447,106 @@ class Geom: ) - def to_file(self,fname,format='vtr',pack=None): + def save_ASCII(self,fname,pack=None): """ Writes a geom file. Parameters ---------- + geom : Geom object + Geometry to write. fname : str or file handle - Geometry file to write. - format : {'vtr', 'ASCII'}, optional - File format, defaults to 'vtr'. Available formats are: - - vtr: VTK rectilinear grid file, extension '.vtr'. - - ASCII: Plain text file, extension '.geom'. + Geometry file to write with extension '.geom'. pack : bool, optional - Compress ASCII geometry with 'x of y' and 'a to b'. + Compress geometry with 'x of y' and 'a to b'. """ - def _to_ASCII(geom,fname,pack=None): - """ - Writes a geom file. + header = [f'{len(self.comments)+4} header'] + self.comments + header.append('grid a {} b {} c {}'.format(*self.get_grid())) + header.append('size x {} y {} z {}'.format(*self.get_size())) + header.append('origin x {} y {} z {}'.format(*self.get_origin())) + header.append(f'homogenization {self.get_homogenization()}') - Parameters - ---------- - geom : Geom object - Geometry to write. - fname : str or file handle - Geometry file to write. - pack : bool, optional - Compress geometry with 'x of y' and 'a to b'. + grid = self.get_grid() - """ - header = [f'{len(geom.comments)+4} header'] + geom.comments - header.append('grid a {} b {} c {}'.format(*geom.get_grid())) - header.append('size x {} y {} z {}'.format(*geom.get_size())) - header.append('origin x {} y {} z {}'.format(*geom.get_origin())) - header.append(f'homogenization {geom.get_homogenization()}') - - grid = geom.get_grid() - - if pack is None: - plain = grid.prod()/geom.N_microstructure < 250 - else: - plain = not pack - - if plain: - format_string = '%g' if geom.microstructure.dtype in np.sctypes['float'] else \ - '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(geom.microstructure))))) - np.savetxt(fname, - geom.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T, - header='\n'.join(header), fmt=format_string, comments='') - else: - try: - f = open(fname,'w') - except TypeError: - f = fname - - compressType = None - former = start = -1 - reps = 0 - for current in geom.microstructure.flatten('F'): - if abs(current - former) == 1 and (start - current) == reps*(former - current): - compressType = 'to' - reps += 1 - elif current == former and start == former: - compressType = 'of' - reps += 1 - else: - if compressType is None: - f.write('\n'.join(header)+'\n') - elif compressType == '.': - f.write(f'{former}\n') - elif compressType == 'to': - f.write(f'{start} to {former}\n') - elif compressType == 'of': - f.write(f'{reps} of {former}\n') - - compressType = '.' - start = current - reps = 1 - - former = current - - if compressType == '.': - f.write(f'{former}\n') - elif compressType == 'to': - f.write(f'{start} to {former}\n') - elif compressType == 'of': - f.write(f'{reps} of {former}\n') - - - def _to_vtr(geom,fname=None): - """ - Generates vtk rectilinear grid. - - Parameters - ---------- - geom : Geom object - Geometry to write. - fname : str, optional - Filename to write. If no file is given, a string is returned. - Valid extension is .vtr, it will be appended if not given. - - """ - v = VTK.from_rectilinearGrid(geom.grid,geom.size,geom.origin) - v.add(geom.microstructure.flatten(order='F'),'materialpoint') - v.add_comments(geom.comments) - - if fname: - v.to_file(fname if str(fname).endswith('.vtr') else str(fname)+'.vtr') - else: - sys.stdout.write(v.__repr__()) - - if format.lower() == 'ascii': - return _to_ASCII(self,fname,pack) - elif format.lower() == 'vtr': - return _to_vtr(self,fname) + if pack is None: + plain = grid.prod()/self.N_microstructure < 250 else: - raise TypeError(f'Unknown format {format}.') + plain = not pack + + if plain: + format_string = '%g' if self.microstructure.dtype in np.sctypes['float'] else \ + '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(self.microstructure))))) + np.savetxt(fname, + self.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T, + header='\n'.join(header), fmt=format_string, comments='') + else: + try: + f = open(fname,'w') + except TypeError: + f = fname + + compressType = None + former = start = -1 + reps = 0 + for current in self.microstructure.flatten('F'): + if abs(current - former) == 1 and (start - current) == reps*(former - current): + compressType = 'to' + reps += 1 + elif current == former and start == former: + compressType = 'of' + reps += 1 + else: + if compressType is None: + f.write('\n'.join(header)+'\n') + elif compressType == '.': + f.write(f'{former}\n') + elif compressType == 'to': + f.write(f'{start} to {former}\n') + elif compressType == 'of': + f.write(f'{reps} of {former}\n') + + compressType = '.' + start = current + reps = 1 + + former = current + + if compressType == '.': + f.write(f'{former}\n') + elif compressType == 'to': + f.write(f'{start} to {former}\n') + elif compressType == 'of': + f.write(f'{reps} of {former}\n') + + + def save_vtr(self,fname=None): + """ + Generates vtk rectilinear grid. + + Parameters + ---------- + geom : Geom object + Geometry to write with extension '.vtr'. + fname : str, optional + Filename to write. If no file is given, a string is returned. + Valid extension is .vtr, it will be appended if not given. + + """ + v = VTK.from_rectilinearGrid(self.grid,self.size,self.origin) + v.add(self.microstructure.flatten(order='F'),'materialpoint') + v.add_comments(self.comments) + + if fname: + v.save(fname if str(fname).endswith('.vtr') else str(fname)+'.vtr') + else: + sys.stdout.write(v.__repr__()) + def as_ASCII(self,pack=False): """Format geometry as human-readable ASCII.""" f = StringIO() - self.to_file(f,'ASCII',pack) + self.save_ASCII(f,pack) f.seek(0) return ''.join(f.readlines()) diff --git a/python/damask/_result.py b/python/damask/_result.py index 723a9f3eb..02d0c0abe 100644 --- a/python/damask/_result.py +++ b/python/damask/_result.py @@ -1196,7 +1196,7 @@ class Result: f.write(xml.dom.minidom.parseString(ET.tostring(xdmf).decode()).toprettyxml()) - def to_vtk(self,labels=[],mode='cell'): + def save_vtk(self,labels=[],mode='cell'): """ Export to vtk cell/point data. @@ -1268,4 +1268,4 @@ class Result: u = self.read_dataset(self.get_dataset_location('u_n' if mode.lower() == 'cell' else 'u_p')) v.add(u,'u') - v.to_file(f'{self.fname.stem}_inc{inc[3:].zfill(N_digits)}') + v.save(f'{self.fname.stem}_inc{inc[3:].zfill(N_digits)}') diff --git a/python/damask/_table.py b/python/damask/_table.py index b4fd2975a..987233153 100644 --- a/python/damask/_table.py +++ b/python/damask/_table.py @@ -27,7 +27,7 @@ class Table: self.comments = [] if comments_ is None else [c for c in comments_] self.data = pd.DataFrame(data=data) self.shapes = { k:(v,) if isinstance(v,(np.int,int)) else v for k,v in shapes.items() } - self._label_condensed() + self._label_uniform() def __copy__(self): @@ -39,7 +39,7 @@ class Table: return self.__copy__() - def _label_flat(self): + def _label_discrete(self): """Label data individually, e.g. v v v ==> 1_v 2_v 3_v.""" labels = [] for label,shape in self.shapes.items(): @@ -48,8 +48,8 @@ class Table: self.data.columns = labels - def _label_condensed(self): - """Label data condensed, e.g. 1_v 2_v 3_v ==> v v v.""" + def _label_uniform(self): + """Label data uniformly, e.g. 1_v 2_v 3_v ==> v v v.""" labels = [] for label,shape in self.shapes.items(): labels += [label] * int(np.prod(shape)) @@ -64,12 +64,15 @@ class Table: @staticmethod - def from_ASCII(fname): + def load_ASCII(fname): """ Create table from ASCII file. - The first line can indicate the number of subsequent header lines as 'n header', - alternatively first line is the header and comments are marked by '#' ('new style'). + In legacy style, the first line indicates the number of + subsequent header lines as "N header", with the last header line being + interpreted as column labels. + Alternatively, initial comments are marked by '#', with the first non-comment line + containing the column labels. Vector data column labels are indicated by '1_v, 2_v, ..., n_v'. Tensor data column labels are indicated by '3x3:1_T, 3x3:2_T, ..., 3x3:9_T'. @@ -119,7 +122,7 @@ class Table: return Table(data,shapes,comments) @staticmethod - def from_ang(fname): + def load_ang(fname): """ Create table from TSL ang file. @@ -289,9 +292,9 @@ class Table: """ dup = self.copy() - dup._label_flat() + dup._label_discrete() dup.data.sort_values(labels,axis=0,inplace=True,ascending=ascending) - dup._label_condensed() + dup._label_uniform() dup.comments.append(f'sorted {"ascending" if ascending else "descending"} by {labels}') return dup @@ -338,59 +341,40 @@ class Table: return dup - def to_file(self,fname,format='ASCII',new_style=False): + def save_ASCII(table,fname,legacy=False): """ Store as plain text file. Parameters ---------- + table : Table object + Table to write. fname : file, str, or pathlib.Path Filename or file for writing. - format : {ASCII'}, optional - File format, defaults to 'ASCII'. Available formats are: - - ASCII: Plain text file, extension '.txt'. - new_style : Boolean, optional - Write table in new style, indicating header lines by comment sign ('#') only. + legacy : Boolean, optional + Write table in legacy style, indicating header lines by "N header" + in contrast to using comment sign ('#') at beginning of lines. """ - def _to_ASCII(table,fname,new_style=False): - """ - Store as plain text file. + seen = set() + labels = [] + for l in [x for x in table.data.columns if not (x in seen or seen.add(x))]: + if table.shapes[l] == (1,): + labels.append(f'{l}') + elif len(table.shapes[l]) == 1: + labels += [f'{i+1}_{l}' \ + for i in range(table.shapes[l][0])] + else: + labels += [f'{util.srepr(table.shapes[l],"x")}:{i+1}_{l}' \ + for i in range(np.prod(table.shapes[l]))] - Parameters - ---------- - table : Table object - Table to write. - fname : file, str, or pathlib.Path - Filename or file for writing. - new_style : Boolean, optional - Write table in new style, indicating header lines by comment sign ('#') only. + header = ([f'{len(table.comments)+1} header'] + table.comments) if legacy else \ + [f'# {comment}' for comment in table.comments] - """ - seen = set() - labels = [] - for l in [x for x in table.data.columns if not (x in seen or seen.add(x))]: - if table.shapes[l] == (1,): - labels.append(f'{l}') - elif len(table.shapes[l]) == 1: - labels += [f'{i+1}_{l}' \ - for i in range(table.shapes[l][0])] - else: - labels += [f'{util.srepr(table.shapes[l],"x")}:{i+1}_{l}' \ - for i in range(np.prod(table.shapes[l]))] + try: + f = open(fname,'w') + except TypeError: + f = fname - header = [f'# {comment}' for comment in table.comments] if new_style else \ - [f'{len(table.comments)+1} header'] + table.comments - - try: - f = open(fname,'w') - except TypeError: - f = fname - - for line in header + [' '.join(labels)]: f.write(line+'\n') - table.data.to_csv(f,sep=' ',na_rep='nan',index=False,header=False) - - if format.lower() == 'ascii': - return _to_ASCII(self,fname,new_style) - else: - raise TypeError(f'Unknown format {format}.') + for line in header + [' '.join(labels)]: f.write(line+'\n') + table.data.to_csv(f,sep=' ',na_rep='nan',index=False,header=False) diff --git a/python/damask/_test.py b/python/damask/_test.py index 78616fabf..c75266e72 100644 --- a/python/damask/_test.py +++ b/python/damask/_test.py @@ -228,7 +228,7 @@ class Test: def copy_Base2Current(self,sourceDir,sourcefiles=[],targetfiles=[]): - source=os.path.normpath(os.path.join(self.dirBase,'../../..',sourceDir)) + source = os.path.normpath(os.path.join(self.dirBase,'../../..',sourceDir)) if len(targetfiles) == 0: targetfiles = sourcefiles for i,f in enumerate(sourcefiles): try: @@ -287,30 +287,30 @@ class Test: import numpy as np logging.info('\n '.join(['comparing',File1,File2])) - table = damask.Table.from_ASCII(File1) - len1=len(table.comments)+2 - table = damask.Table.from_ASCII(File2) - len2=len(table.comments)+2 + table = damask.Table.load_ASCII(File1) + len1 = len(table.comments)+1 + table = damask.Table.load_ASCII(File2) + len2 = len(table.comments)+1 refArray = np.nan_to_num(np.genfromtxt(File1,missing_values='n/a',skip_header = len1,autostrip=True)) curArray = np.nan_to_num(np.genfromtxt(File2,missing_values='n/a',skip_header = len2,autostrip=True)) if len(curArray) == len(refArray): refArrayNonZero = refArray[refArray.nonzero()] - curArray = curArray[refArray.nonzero()] - max_err=np.max(abs(refArrayNonZero[curArray.nonzero()]/curArray[curArray.nonzero()]-1.)) - max_loc=np.argmax(abs(refArrayNonZero[curArray.nonzero()]/curArray[curArray.nonzero()]-1.)) + curArray = curArray[refArray.nonzero()] + max_err = np. max(abs(refArrayNonZero[curArray.nonzero()]/curArray[curArray.nonzero()]-1.)) + max_loc = np.argmax(abs(refArrayNonZero[curArray.nonzero()]/curArray[curArray.nonzero()]-1.)) refArrayNonZero = refArrayNonZero[curArray.nonzero()] - curArray = curArray[curArray.nonzero()] + curArray = curArray[curArray.nonzero()] print(f' ********\n * maximum relative error {max_err} between {refArrayNonZero[max_loc]} and {curArray[max_loc]}\n ********') return max_err else: - raise Exception('mismatch in array size to compare') + raise Exception(f'mismatch in array sizes ({len(refArray)} and {len(curArray)}) to compare') def compare_ArrayRefCur(self,ref,cur=''): - if cur =='': cur = ref + if cur == '': cur = ref refName = self.fileInReference(ref) curName = self.fileInCurrent(cur) return self.compare_Array(refName,curName) @@ -399,10 +399,8 @@ class Test: if any(norm[i]) == 0.0 or absTol[i]: norm[i] = [1.0 for j in range(line0-len(skipLines))] absTol[i] = True - if perLine: - logging.warning(f"At least one norm of \"{headings0[i]['label']}\" in first table is 0.0, using absolute tolerance") - else: - logging.warning(f"Maximum norm of \"{headings0[i]['label']}\" in first table is 0.0, using absolute tolerance") + logging.warning(f'''{"At least one" if perLine else "Maximum"} norm of + "{headings0[i]['label']}" in first table is 0.0, using absolute tolerance''') line1 = 0 while table1.data_read(): # read next data line of ASCII table @@ -418,20 +416,18 @@ class Test: logging.info(' ********') for i in range(dataLength): - if absTol[i]: - logging.info(f" * maximum absolute error {maxError[i]} between {headings0[i]['label']} and {headings1[i]['label']}") - else: - logging.info(f" * maximum relative error {maxError[i]} between {headings0[i]['label']} and {headings1[i]['label']}") + logging.info(f''' * maximum {'absolute' if absTol[i] else 'relative'} error {maxError[i]} + between {headings0[i]['label']} and {headings1[i]['label']}''') logging.info(' ********') return maxError def compare_TablesStatistically(self, - files = [None,None], # list of file names - columns = [None], # list of list of column labels (per file) - meanTol = 1.0e-4, - stdTol = 1.0e-6, - preFilter = 1.0e-9): + files = [None,None], # list of file names + columns = [None], # list of list of column labels (per file) + meanTol = 1.0e-4, + stdTol = 1.0e-6, + preFilter = 1.0e-9): """ Calculate statistics of tables. @@ -440,9 +436,9 @@ class Test: if not (isinstance(files, Iterable) and not isinstance(files, str)): # check whether list of files is requested files = [str(files)] - tables = [damask.Table.from_ASCII(filename) for filename in files] + tables = [damask.Table.load_ASCII(filename) for filename in files] for table in tables: - table._label_flat() + table._label_discrete() columns += [columns[0]]*(len(files)-len(columns)) # extend to same length as files columns = columns[:len(files)] # truncate to same length as files @@ -462,7 +458,7 @@ class Test: data = [] for table,labels in zip(tables,columns): - table._label_condensed() + table._label_uniform() data.append(np.hstack(list(table.get(label) for label in labels))) @@ -471,12 +467,11 @@ class Test: normBy = (np.abs(data[i]) + np.abs(data[i-1]))*0.5 normedDelta = np.where(normBy>preFilter,delta/normBy,0.0) mean = np.amax(np.abs(np.mean(normedDelta,0))) - std = np.amax(np.std(normedDelta,0)) + std = np.amax(np.std(normedDelta,0)) logging.info(f'mean: {mean:f}') logging.info(f'std: {std:f}') - return (mean 1: - current.to_file(reference,format='vtr') + current.save_vtr(reference) for _ in range(10): time.sleep(.2) if os.path.exists(reference.with_suffix('.vtr')): break - assert geom_equal(Geom.from_vtr(reference) if stencil > 1 else default, + assert geom_equal(Geom.load_vtr(reference) if stencil > 1 else default, current ) @@ -220,8 +216,8 @@ class TestGeom: modified = default.scale(grid) tag = f'grid={util.srepr(grid,"-")}' reference = reference_dir/f'scale_{tag}.geom' - if update: modified.to_file(reference) - assert geom_equal(Geom.from_file(reference), + if update: modified.save_ASCII(reference) + assert geom_equal(Geom.load_ASCII(reference), modified) def test_renumber(self,default): @@ -255,8 +251,8 @@ class TestGeom: modified = default.rotate(Rotation.from_Eulers(Eulers,degrees=True)) tag = f'Eulers={util.srepr(Eulers,"-")}' reference = reference_dir/f'rotate_{tag}.geom' - if update: modified.to_file(reference) - assert geom_equal(Geom.from_file(reference), + if update: modified.save_ASCII(reference) + assert geom_equal(Geom.load_ASCII(reference), modified) def test_canvas(self,default): diff --git a/python/tests/test_Orientation.py b/python/tests/test_Orientation.py index 9a23dc0ed..1c92340bf 100644 --- a/python/tests/test_Orientation.py +++ b/python/tests/test_Orientation.py @@ -107,7 +107,7 @@ class TestOrientation: table = Table(eu,{'Eulers':(3,)}) table = table.add('pos',coords) table.to_ASCII(reference) - assert np.allclose(eu,Table.from_ASCII(reference).get('Eulers')) + assert np.allclose(eu,Table.load_ASCII(reference).get('Eulers')) @pytest.mark.parametrize('lattice',Lattice.lattices) def test_disorientation360(self,lattice): @@ -129,4 +129,3 @@ class TestOrientation: eqs = [r for r in R_1.equivalent] R_2 = Orientation.from_average(eqs) assert np.allclose(R_1.rotation.quaternion,R_2.rotation.quaternion) - diff --git a/python/tests/test_Result.py b/python/tests/test_Result.py index 6000f50f9..c25bf7a4c 100644 --- a/python/tests/test_Result.py +++ b/python/tests/test_Result.py @@ -339,7 +339,7 @@ class TestResult: @pytest.mark.parametrize('output',['F',[],['F','P']]) def test_vtk(self,tmp_path,default,output): os.chdir(tmp_path) - default.to_vtk(output) + default.save_vtk(output) def test_XDMF(self,tmp_path,single_phase): os.chdir(tmp_path) diff --git a/python/tests/test_Table.py b/python/tests/test_Table.py index 1763e27ef..af940a037 100644 --- a/python/tests/test_Table.py +++ b/python/tests/test_Table.py @@ -35,50 +35,50 @@ class TestTable: @pytest.mark.parametrize('mode',['str','path']) def test_write_read(self,default,tmpdir,mode): - default.to_file(tmpdir/'default.txt') + default.save_ASCII(tmpdir/'default.txt') if mode == 'path': - new = Table.from_ASCII(tmpdir/'default.txt') + new = Table.load_ASCII(tmpdir/'default.txt') elif mode == 'str': - new = Table.from_ASCII(str(tmpdir/'default.txt')) + new = Table.load_ASCII(str(tmpdir/'default.txt')) assert all(default.data==new.data) and default.shapes == new.shapes def test_write_read_file(self,default,tmpdir): with open(tmpdir/'default.txt','w') as f: - default.to_file(f) + default.save_ASCII(f) with open(tmpdir/'default.txt') as f: - new = Table.from_ASCII(f) + new = Table.load_ASCII(f) assert all(default.data==new.data) and default.shapes == new.shapes - def test_write_read_new_style(self,default,tmpdir): - with open(tmpdir/'new_style.txt','w') as f: - default.to_file(f,new_style=True) - with open(tmpdir/'new_style.txt') as f: - new = Table.from_ASCII(f) + def test_write_read_legacy_style(self,default,tmpdir): + with open(tmpdir/'legacy.txt','w') as f: + default.save_ASCII(f,legacy=True) + with open(tmpdir/'legacy.txt') as f: + new = Table.load_ASCII(f) assert all(default.data==new.data) and default.shapes == new.shapes def test_write_invalid_format(self,default,tmpdir): with pytest.raises(TypeError): - default.to_file(tmpdir/'shouldnotbethere.txt',format='invalid') + default.save_ASCII(tmpdir/'shouldnotbethere.txt',format='invalid') @pytest.mark.parametrize('mode',['str','path']) def test_read_ang(self,reference_dir,mode): if mode == 'path': - new = Table.from_ang(reference_dir/'simple.ang') + new = Table.load_ang(reference_dir/'simple.ang') elif mode == 'str': - new = Table.from_ang(str(reference_dir/'simple.ang')) + new = Table.load_ang(str(reference_dir/'simple.ang')) assert new.data.shape == (4,10) and \ new.labels == ['eu', 'pos', 'IQ', 'CI', 'ID', 'intensity', 'fit'] def test_read_ang_file(self,reference_dir): f = open(reference_dir/'simple.ang') - new = Table.from_ang(f) + new = Table.load_ang(f) assert new.data.shape == (4,10) and \ new.labels == ['eu', 'pos', 'IQ', 'CI', 'ID', 'intensity', 'fit'] @pytest.mark.parametrize('fname',['datatype-mix.txt','whitespace-mix.txt']) def test_read_strange(self,reference_dir,fname): with open(reference_dir/fname) as f: - Table.from_ASCII(f) + Table.load_ASCII(f) def test_set(self,default): d = default.set('F',np.zeros((5,3,3)),'set to zero').get('F') @@ -166,7 +166,7 @@ class TestTable: x = np.random.random((5,12)) t = Table(x,{'F':(3,3),'v':(3,)},['random test data']) unsort = t.get('4_F') - sort = t.sort_by('4_F').get('4_F') + sort = t.sort_by('4_F').get('4_F') assert np.all(np.sort(unsort,0)==sort) def test_sort_revert(self): @@ -179,6 +179,6 @@ class TestTable: t = Table(np.array([[0,1,],[2,1,]]), {'v':(2,)}, ['test data'])\ - .add('s',np.array(['b','a']))\ - .sort_by('s') + .add('s',np.array(['b','a']))\ + .sort_by('s') assert np.all(t.get('1_v') == np.array([2,0]).reshape(2,1)) diff --git a/python/tests/test_VTK.py b/python/tests/test_VTK.py index f6be4da25..81c9eb772 100644 --- a/python/tests/test_VTK.py +++ b/python/tests/test_VTK.py @@ -32,22 +32,22 @@ class TestVTK: origin = np.random.random(3) v = VTK.from_rectilinearGrid(grid,size,origin) string = v.__repr__() - v.to_file(tmp_path/'rectilinearGrid',False) - vtr = VTK.from_file(tmp_path/'rectilinearGrid.vtr') + v.save(tmp_path/'rectilinearGrid',False) + vtr = VTK.load(tmp_path/'rectilinearGrid.vtr') with open(tmp_path/'rectilinearGrid.vtk','w') as f: f.write(string) - vtk = VTK.from_file(tmp_path/'rectilinearGrid.vtk','VTK_rectilinearGrid') + vtk = VTK.load(tmp_path/'rectilinearGrid.vtk','VTK_rectilinearGrid') assert(string == vtr.__repr__() == vtk.__repr__()) def test_polyData(self,tmp_path): points = np.random.rand(100,3) v = VTK.from_polyData(points) string = v.__repr__() - v.to_file(tmp_path/'polyData',False) - vtp = VTK.from_file(tmp_path/'polyData.vtp') + v.save(tmp_path/'polyData',False) + vtp = VTK.load(tmp_path/'polyData.vtp') with open(tmp_path/'polyData.vtk','w') as f: f.write(string) - vtk = VTK.from_file(tmp_path/'polyData.vtk','polyData') + vtk = VTK.load(tmp_path/'polyData.vtk','polyData') assert(string == vtp.__repr__() == vtk.__repr__()) @pytest.mark.parametrize('cell_type,n',[ @@ -62,11 +62,11 @@ class TestVTK: connectivity = np.random.choice(np.arange(n),n,False).reshape(-1,n) v = VTK.from_unstructuredGrid(nodes,connectivity,cell_type) string = v.__repr__() - v.to_file(tmp_path/'unstructuredGrid',False) - vtu = VTK.from_file(tmp_path/'unstructuredGrid.vtu') + v.save(tmp_path/'unstructuredGrid',False) + vtu = VTK.load(tmp_path/'unstructuredGrid.vtu') with open(tmp_path/'unstructuredGrid.vtk','w') as f: f.write(string) - vtk = VTK.from_file(tmp_path/'unstructuredGrid.vtk','unstructuredgrid') + vtk = VTK.load(tmp_path/'unstructuredGrid.vtk','unstructuredgrid') assert(string == vtu.__repr__() == vtk.__repr__()) @@ -75,8 +75,8 @@ class TestVTK: v = VTK.from_polyData(points) fname_s = tmp_path/'single.vtp' fname_p = tmp_path/'parallel.vtp' - v.to_file(fname_s,False) - v.to_file(fname_p,True) + v.save(fname_s,False) + v.save(fname_p,True) for i in range(10): if os.path.isfile(fname_p) and filecmp.cmp(fname_s,fname_p): assert(True) @@ -90,11 +90,11 @@ class TestVTK: ('this_file_does_not_exist.vtx', None)]) def test_invalid_dataset_type(self,name,dataset_type): with pytest.raises(TypeError): - VTK.from_file(name,dataset_type) + VTK.load(name,dataset_type) def test_invalid_extension_write(self,default): with pytest.raises(ValueError): - default.to_file('default.txt') + default.save('default.txt') def test_invalid_get(self,default): with pytest.raises(ValueError): @@ -115,8 +115,8 @@ class TestVTK: def test_comments(self,tmp_path,default): default.add_comments(['this is a comment']) - default.to_file(tmp_path/'with_comments',parallel=False) - new = VTK.from_file(tmp_path/'with_comments.vtr') + default.save(tmp_path/'with_comments',parallel=False) + new = VTK.load(tmp_path/'with_comments.vtr') assert new.get_comments() == ['this is a comment'] def test_compare_reference_polyData(self,update,reference_dir,tmp_path): @@ -124,9 +124,9 @@ class TestVTK: polyData = VTK.from_polyData(points) polyData.add(points,'coordinates') if update: - polyData.to_file(reference_dir/'polyData') + polyData.save(reference_dir/'polyData') else: - reference = VTK.from_file(reference_dir/'polyData.vtp') + reference = VTK.load(reference_dir/'polyData.vtp') assert polyData.__repr__() == reference.__repr__() and \ np.allclose(polyData.get('coordinates'),points) @@ -139,8 +139,8 @@ class TestVTK: rectilinearGrid.add(c,'cell') rectilinearGrid.add(n,'node') if update: - rectilinearGrid.to_file(reference_dir/'rectilinearGrid') + rectilinearGrid.save(reference_dir/'rectilinearGrid') else: - reference = VTK.from_file(reference_dir/'rectilinearGrid.vtr') + reference = VTK.load(reference_dir/'rectilinearGrid.vtr') assert rectilinearGrid.__repr__() == reference.__repr__() and \ np.allclose(rectilinearGrid.get('cell'),c) From 2114c510983bf56aa6eaf9896a9a994884bdc2a8 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Tue, 15 Sep 2020 01:47:26 -0400 Subject: [PATCH 02/61] revert mistakenly made header length change in array-comparison --- python/damask/_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python/damask/_test.py b/python/damask/_test.py index c75266e72..ab4df6d68 100644 --- a/python/damask/_test.py +++ b/python/damask/_test.py @@ -288,9 +288,9 @@ class Test: import numpy as np logging.info('\n '.join(['comparing',File1,File2])) table = damask.Table.load_ASCII(File1) - len1 = len(table.comments)+1 + len1 = len(table.comments)+2 table = damask.Table.load_ASCII(File2) - len2 = len(table.comments)+1 + len2 = len(table.comments)+2 refArray = np.nan_to_num(np.genfromtxt(File1,missing_values='n/a',skip_header = len1,autostrip=True)) curArray = np.nan_to_num(np.genfromtxt(File2,missing_values='n/a',skip_header = len2,autostrip=True)) @@ -331,7 +331,7 @@ class Test: logging.info('\n '.join(['comparing ASCII Tables',file0,file1])) if normHeadings == '': normHeadings = headings0 -# check if comparison is possible and determine lenght of columns +# check if comparison is possible and determine length of columns if len(headings0) == len(headings1) == len(normHeadings): dataLength = len(headings0) length = [1 for i in range(dataLength)] From f52aae3c29ca6e165c6a37244b7fb72895da4ae9 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Tue, 15 Sep 2020 10:19:19 -0400 Subject: [PATCH 03/61] legacy shell scripts again output legacy ASCIItables --- processing/post/addCompatibilityMismatch.py | 2 +- processing/post/addCurl.py | 2 +- processing/post/addDerivative.py | 2 +- processing/post/addDisplacement.py | 4 ++-- processing/post/addDivergence.py | 2 +- processing/post/addEuclideanDistance.py | 2 +- processing/post/addGaussian.py | 2 +- processing/post/addGradient.py | 2 +- processing/post/addOrientations.py | 2 +- processing/post/addSchmidfactors.py | 2 +- processing/post/permuteData.py | 2 +- 11 files changed, 12 insertions(+), 12 deletions(-) diff --git a/processing/post/addCompatibilityMismatch.py b/processing/post/addCompatibilityMismatch.py index e274092d2..40a1391e0 100755 --- a/processing/post/addCompatibilityMismatch.py +++ b/processing/post/addCompatibilityMismatch.py @@ -191,4 +191,4 @@ for name in filenames: volumeMismatch.reshape(-1,1,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addCurl.py b/processing/post/addCurl.py index 9adb06a00..5a5f4c074 100755 --- a/processing/post/addCurl.py +++ b/processing/post/addCurl.py @@ -55,4 +55,4 @@ for name in filenames: curl.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape),order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addDerivative.py b/processing/post/addDerivative.py index 179715e23..63a5bf73e 100755 --- a/processing/post/addDerivative.py +++ b/processing/post/addDerivative.py @@ -71,4 +71,4 @@ for name in filenames: derivative(table.get(options.coordinates),table.get(label)), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addDisplacement.py b/processing/post/addDisplacement.py index 8dc3051d3..079bcd970 100755 --- a/processing/post/addDisplacement.py +++ b/processing/post/addDisplacement.py @@ -60,7 +60,7 @@ for name in filenames: .add('fluct({}).{}'.format(options.f,options.pos), damask.grid_filters.node_displacement_fluct(size,F).reshape(-1,3,order='F'), scriptID+' '+' '.join(sys.argv[1:]))\ - .save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt') + .save_ASCII((sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt'), legacy=True) else: table.add('avg({}).{}'.format(options.f,options.pos), damask.grid_filters.cell_displacement_avg(size,F).reshape(-1,3,order='F'), @@ -68,4 +68,4 @@ for name in filenames: .add('fluct({}).{}'.format(options.f,options.pos), damask.grid_filters.cell_displacement_fluct(size,F).reshape(-1,3,order='F'), scriptID+' '+' '.join(sys.argv[1:]))\ - .save_ASCII(sys.stdout if name is None else name) + .save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addDivergence.py b/processing/post/addDivergence.py index b4c0bb7b4..bc4880788 100755 --- a/processing/post/addDivergence.py +++ b/processing/post/addDivergence.py @@ -55,4 +55,4 @@ for name in filenames: div.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape)//3,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addEuclideanDistance.py b/processing/post/addEuclideanDistance.py index 305fc2ad5..7e99dc3d5 100755 --- a/processing/post/addEuclideanDistance.py +++ b/processing/post/addEuclideanDistance.py @@ -184,4 +184,4 @@ for name in filenames: distance[i,:], scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addGaussian.py b/processing/post/addGaussian.py index 708617c1f..095a17bc2 100755 --- a/processing/post/addGaussian.py +++ b/processing/post/addGaussian.py @@ -73,4 +73,4 @@ for name in filenames: mode = 'wrap' if options.periodic else 'nearest'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addGradient.py b/processing/post/addGradient.py index e216ed34c..69241598c 100755 --- a/processing/post/addGradient.py +++ b/processing/post/addGradient.py @@ -55,4 +55,4 @@ for name in filenames: grad.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape)*3,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addOrientations.py b/processing/post/addOrientations.py index 3a320241c..16f8d62d6 100755 --- a/processing/post/addOrientations.py +++ b/processing/post/addOrientations.py @@ -147,4 +147,4 @@ for name in filenames: if 'axisangle' in options.output: table = table.add('om({})'.format(label),o.as_axisangle(options.degrees), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addSchmidfactors.py b/processing/post/addSchmidfactors.py index 40db4da34..beaf18331 100755 --- a/processing/post/addSchmidfactors.py +++ b/processing/post/addSchmidfactors.py @@ -189,4 +189,4 @@ for name in filenames: for i,label in enumerate(labels): table = table.add(label,S[:,i],scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/permuteData.py b/processing/post/permuteData.py index af184924d..34451404c 100755 --- a/processing/post/permuteData.py +++ b/processing/post/permuteData.py @@ -58,4 +58,4 @@ for name in filenames: rng.shuffle(uniques) table = table.set(label,uniques[inverse], scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name), legacy=True) From b57e8e69a87f66e1fb81eca0e1236125fd5432b4 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Tue, 15 Sep 2020 22:38:50 -0400 Subject: [PATCH 04/61] switched save_ASCII() in more legacy scripts to legacy mode --- PRIVATE | 2 +- processing/legacy/addAPS34IDEstrainCoords.py | 2 +- processing/legacy/addCumulative.py | 2 +- processing/post/DADF5_postResults.py | 2 +- processing/pre/seeds_fromDistribution.py | 2 +- processing/pre/seeds_fromGeom.py | 2 +- processing/pre/seeds_fromPokes.py | 2 +- processing/pre/seeds_fromRandom.py | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/PRIVATE b/PRIVATE index 5b7c34e58..3e789fc51 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 5b7c34e586589141d1e061f021512e65308fc1f7 +Subproject commit 3e789fc515dc2bdc63e042286dc06d8d072d096f diff --git a/processing/legacy/addAPS34IDEstrainCoords.py b/processing/legacy/addAPS34IDEstrainCoords.py index c82ff35a3..8f566b614 100755 --- a/processing/legacy/addAPS34IDEstrainCoords.py +++ b/processing/legacy/addAPS34IDEstrainCoords.py @@ -48,4 +48,4 @@ for name in filenames: coord[:,2] += table.get(options.depth)[:,0] table.add('coord',rot_to_TSL.broadcast_to(coord.shape[0]) @ coord,scriptID+' '+' '.join(sys.argv[1:]))\ - .save_ASCII(sys.stdout if name is None else name) + .save_ASCII((sys.stdout if name is None else name),legacy=True) diff --git a/processing/legacy/addCumulative.py b/processing/legacy/addCumulative.py index 14d8bcfea..0d88cc575 100755 --- a/processing/legacy/addCumulative.py +++ b/processing/legacy/addCumulative.py @@ -45,4 +45,4 @@ for name in filenames: np.cumprod(table.get(label),0) if options.product else np.cumsum(table.get(label),0), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII((sys.stdout if name is None else name),legacy=True) diff --git a/processing/post/DADF5_postResults.py b/processing/post/DADF5_postResults.py index fa9df27b0..0226ad551 100755 --- a/processing/post/DADF5_postResults.py +++ b/processing/post/DADF5_postResults.py @@ -60,4 +60,4 @@ for filename in options.filenames: os.mkdir(dirname,0o755) file_out = '{}_inc{}.txt'.format(os.path.splitext(os.path.split(filename)[-1])[0], inc[3:].zfill(N_digits)) - table.save_ASCII(os.path.join(dirname,file_out)) + table.save_ASCII(os.path.join(dirname,file_out),legacy=True) diff --git a/processing/pre/seeds_fromDistribution.py b/processing/pre/seeds_fromDistribution.py index 1cf35450c..cc72920d3 100755 --- a/processing/pre/seeds_fromDistribution.py +++ b/processing/pre/seeds_fromDistribution.py @@ -89,7 +89,7 @@ class myThread (threading.Thread): coords[i]=newCoords direction[i]*=2. i+= 1 - perturbedSeedsTable.set('pos',coords).save_ASCII(perturbedSeedsVFile) + perturbedSeedsTable.set('pos',coords).save_ASCII(perturbedSeedsVFile,legacy=True) #--- do tesselation with perturbed seed file ------------------------------------------------------ perturbedGeomVFile.close() diff --git a/processing/pre/seeds_fromGeom.py b/processing/pre/seeds_fromGeom.py index 95f0d3815..4110405d6 100755 --- a/processing/pre/seeds_fromGeom.py +++ b/processing/pre/seeds_fromGeom.py @@ -65,4 +65,4 @@ for name in filenames: damask.Table(seeds[mask],{'pos':(3,)},comments)\ .add('microstructure',microstructure[mask].astype(int))\ - .save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.seeds') + .save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.seeds',legacy=True) diff --git a/processing/pre/seeds_fromPokes.py b/processing/pre/seeds_fromPokes.py index 5deb0ab1a..fdff40da3 100755 --- a/processing/pre/seeds_fromPokes.py +++ b/processing/pre/seeds_fromPokes.py @@ -93,4 +93,4 @@ for name in filenames: table = damask.Table(seeds,{'pos':(3,),'microstructure':(1,)},comments) table.set('microstructure',table.get('microstructure').astype(np.int))\ .save_ASCII(sys.stdout if name is None else \ - os.path.splitext(name)[0]+f'_poked_{options.N}.seeds') + os.path.splitext(name)[0]+f'_poked_{options.N}.seeds',legacy=True) diff --git a/processing/pre/seeds_fromRandom.py b/processing/pre/seeds_fromRandom.py index c1d454f67..8700a4648 100755 --- a/processing/pre/seeds_fromRandom.py +++ b/processing/pre/seeds_fromRandom.py @@ -162,4 +162,4 @@ for name in filenames: else np.random.normal(loc = options.mean, scale = options.sigma, size = options.N) table = table.add('weight',weights) - table.save_ASCII(sys.stdout if name is None else name) + table.save_ASCII(sys.stdout if name is None else name,legacy=True) From 505d8fef21c01308e77bade1a91edb2493d7eecd Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Wed, 16 Sep 2020 09:22:49 -0400 Subject: [PATCH 05/61] reverted references of seed_fromX tests to legacy ASCII style in PRIVATE --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 3e789fc51..52b0af920 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 3e789fc515dc2bdc63e042286dc06d8d072d096f +Subproject commit 52b0af9208bfcd988a2d8152d2c2dfd7dea42e30 From 2c741455f09c5ebe259a2d2d7e46d63ced0e599d Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Wed, 16 Sep 2020 19:30:09 -0400 Subject: [PATCH 06/61] fixed left-over to_vtk --> save_vtk in PRIVATE --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 52b0af920..0b5204381 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 52b0af9208bfcd988a2d8152d2c2dfd7dea42e30 +Subproject commit 0b5204381cc8b86212ed8c0de43110d0175badd4 From 4d4283a03249be87a9e6a955da66e80aad428489 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 12:03:21 +0200 Subject: [PATCH 07/61] report next pipeline --- .gitlab-ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index ed5e762b7..c412b0abe 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -87,6 +87,7 @@ checkout: - echo $CI_PIPELINE_ID >> $TESTROOT/GitLabCI.queue - while [ $(awk "/$CI_PIPELINE_ID/{print NR}" $TESTROOT/GitLabCI.queue) != 1 ]; do sleep 5m; + echo 'next pipeline $(head -n 1 $TESTROOT/GitLabCI.queue)'; done script: - mkdir -p $DAMASKROOT From f34525fd3ac30dc61fffb5909bfa26be7452919e Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 12:33:54 +0200 Subject: [PATCH 08/61] allow shell substitution --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c412b0abe..ff58727d5 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -87,7 +87,7 @@ checkout: - echo $CI_PIPELINE_ID >> $TESTROOT/GitLabCI.queue - while [ $(awk "/$CI_PIPELINE_ID/{print NR}" $TESTROOT/GitLabCI.queue) != 1 ]; do sleep 5m; - echo 'next pipeline $(head -n 1 $TESTROOT/GitLabCI.queue)'; + echo "next pipeline $(head -n 1 $TESTROOT/GitLabCI.queue)"; done script: - mkdir -p $DAMASKROOT From beb8f07a91f5cfc21e2abe283db8bfb860913f7f Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 12:58:37 +0200 Subject: [PATCH 09/61] more helpful information --- .gitlab-ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index ff58727d5..fb0f17030 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -25,6 +25,7 @@ before_script: fi - while [ $(awk "/$CI_PIPELINE_ID/{print NR}" $TESTROOT/GitLabCI.queue) != 1 ]; do sleep 5m; + echo "next pipeline in queue has ID $(head -n 1 $TESTROOT/GitLabCI.queue)"; done - source $DAMASKROOT/env/DAMASK.sh - cd $DAMASKROOT/PRIVATE/testing @@ -87,7 +88,7 @@ checkout: - echo $CI_PIPELINE_ID >> $TESTROOT/GitLabCI.queue - while [ $(awk "/$CI_PIPELINE_ID/{print NR}" $TESTROOT/GitLabCI.queue) != 1 ]; do sleep 5m; - echo "next pipeline $(head -n 1 $TESTROOT/GitLabCI.queue)"; + echo "next pipeline in queue has ID $(head -n 1 $TESTROOT/GitLabCI.queue)"; done script: - mkdir -p $DAMASKROOT From 25ad07764081f27f4f774db79afdfc7a8c5fe2f9 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 14:19:23 +0200 Subject: [PATCH 10/61] report all pipelines in front of me --- .gitlab-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index fb0f17030..bb4a2e7a0 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -25,7 +25,7 @@ before_script: fi - while [ $(awk "/$CI_PIPELINE_ID/{print NR}" $TESTROOT/GitLabCI.queue) != 1 ]; do sleep 5m; - echo "next pipeline in queue has ID $(head -n 1 $TESTROOT/GitLabCI.queue)"; + echo -e "Currently queued pipelines:\n$(cat $TESTROOT/GitLabCI.queue)\n"; done - source $DAMASKROOT/env/DAMASK.sh - cd $DAMASKROOT/PRIVATE/testing @@ -88,7 +88,7 @@ checkout: - echo $CI_PIPELINE_ID >> $TESTROOT/GitLabCI.queue - while [ $(awk "/$CI_PIPELINE_ID/{print NR}" $TESTROOT/GitLabCI.queue) != 1 ]; do sleep 5m; - echo "next pipeline in queue has ID $(head -n 1 $TESTROOT/GitLabCI.queue)"; + echo -e "Currently queued pipelines:\n$(cat $TESTROOT/GitLabCI.queue)\n"; done script: - mkdir -p $DAMASKROOT From ec7dbb4c9ade601fcd4475ed0c6b61fd1b1f4259 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 14:21:30 +0200 Subject: [PATCH 11/61] do not store temp files --- .../Visualize_hybridIA_sampling-checkpoint.ipynb | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 python/tests/reference/Rotation/.ipynb_checkpoints/Visualize_hybridIA_sampling-checkpoint.ipynb diff --git a/python/tests/reference/Rotation/.ipynb_checkpoints/Visualize_hybridIA_sampling-checkpoint.ipynb b/python/tests/reference/Rotation/.ipynb_checkpoints/Visualize_hybridIA_sampling-checkpoint.ipynb deleted file mode 100644 index 7fec51502..000000000 --- a/python/tests/reference/Rotation/.ipynb_checkpoints/Visualize_hybridIA_sampling-checkpoint.ipynb +++ /dev/null @@ -1,6 +0,0 @@ -{ - "cells": [], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 4 -} From e2cd3da29551233d5068acc249c20838726ac2d9 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 14:29:27 +0200 Subject: [PATCH 12/61] remaning to_xx --- python/tests/test_Orientation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tests/test_Orientation.py b/python/tests/test_Orientation.py index 1c92340bf..bee3c8c59 100644 --- a/python/tests/test_Orientation.py +++ b/python/tests/test_Orientation.py @@ -106,7 +106,7 @@ class TestOrientation: coords = np.array([(1,i+1) for i,x in enumerate(eu)]) table = Table(eu,{'Eulers':(3,)}) table = table.add('pos',coords) - table.to_ASCII(reference) + table.write(reference) assert np.allclose(eu,Table.load_ASCII(reference).get('Eulers')) @pytest.mark.parametrize('lattice',Lattice.lattices) From 1849ff0330bc7fa0e06e5d3c6102d3e86536d666 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 15:03:51 +0200 Subject: [PATCH 13/61] polishing --- python/damask/_geom.py | 4 ---- python/damask/_table.py | 34 +++++++++++++++----------------- python/tests/test_Orientation.py | 2 +- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/python/damask/_geom.py b/python/damask/_geom.py index 8fa0b533a..60f7b90a5 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -453,8 +453,6 @@ class Geom: Parameters ---------- - geom : Geom object - Geometry to write. fname : str or file handle Geometry file to write with extension '.geom'. pack : bool, optional @@ -526,8 +524,6 @@ class Geom: Parameters ---------- - geom : Geom object - Geometry to write with extension '.vtr'. fname : str, optional Filename to write. If no file is given, a string is returned. Valid extension is .vtr, it will be appended if not given. diff --git a/python/damask/_table.py b/python/damask/_table.py index 987233153..3215cd8db 100644 --- a/python/damask/_table.py +++ b/python/damask/_table.py @@ -66,7 +66,7 @@ class Table: @staticmethod def load_ASCII(fname): """ - Create table from ASCII file. + Load ASCII table file. In legacy style, the first line indicates the number of subsequent header lines as "N header", with the last header line being @@ -124,7 +124,7 @@ class Table: @staticmethod def load_ang(fname): """ - Create table from TSL ang file. + Load ang file. A valid TSL ang file needs to contains the following columns: * Euler angles (Bunge notation) in radians, 3 floats, label 'eu'. @@ -341,14 +341,12 @@ class Table: return dup - def save_ASCII(table,fname,legacy=False): + def save_ASCII(self,fname,legacy=False): """ - Store as plain text file. + Save as plain text file. Parameters ---------- - table : Table object - Table to write. fname : file, str, or pathlib.Path Filename or file for writing. legacy : Boolean, optional @@ -358,23 +356,23 @@ class Table: """ seen = set() labels = [] - for l in [x for x in table.data.columns if not (x in seen or seen.add(x))]: - if table.shapes[l] == (1,): + for l in [x for x in self.data.columns if not (x in seen or seen.add(x))]: + if self.shapes[l] == (1,): labels.append(f'{l}') - elif len(table.shapes[l]) == 1: + elif len(self.shapes[l]) == 1: labels += [f'{i+1}_{l}' \ - for i in range(table.shapes[l][0])] + for i in range(self.shapes[l][0])] else: - labels += [f'{util.srepr(table.shapes[l],"x")}:{i+1}_{l}' \ - for i in range(np.prod(table.shapes[l]))] + labels += [f'{util.srepr(self.shapes[l],"x")}:{i+1}_{l}' \ + for i in range(np.prod(self.shapes[l]))] - header = ([f'{len(table.comments)+1} header'] + table.comments) if legacy else \ - [f'# {comment}' for comment in table.comments] + header = ([f'{len(self.comments)+1} header'] + self.comments) if legacy else \ + [f'# {comment}' for comment in self.comments] try: - f = open(fname,'w') + fhandle = open(fname,'w') except TypeError: - f = fname + fhandle = fname - for line in header + [' '.join(labels)]: f.write(line+'\n') - table.data.to_csv(f,sep=' ',na_rep='nan',index=False,header=False) + for line in header + [' '.join(labels)]: fhandle.write(line+'\n') + self.data.to_csv(fhandle,sep=' ',na_rep='nan',index=False,header=False) diff --git a/python/tests/test_Orientation.py b/python/tests/test_Orientation.py index bee3c8c59..3a7425ddb 100644 --- a/python/tests/test_Orientation.py +++ b/python/tests/test_Orientation.py @@ -106,7 +106,7 @@ class TestOrientation: coords = np.array([(1,i+1) for i,x in enumerate(eu)]) table = Table(eu,{'Eulers':(3,)}) table = table.add('pos',coords) - table.write(reference) + table.save_ASCII(reference) assert np.allclose(eu,Table.load_ASCII(reference).get('Eulers')) @pytest.mark.parametrize('lattice',Lattice.lattices) From c935ba12153161f4abc90985e760642e40a315c9 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 16:23:23 +0200 Subject: [PATCH 14/61] user friendly self reporting --- python/damask/_table.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python/damask/_table.py b/python/damask/_table.py index 3215cd8db..9789c8be6 100644 --- a/python/damask/_table.py +++ b/python/damask/_table.py @@ -29,6 +29,9 @@ class Table: self.shapes = { k:(v,) if isinstance(v,(np.int,int)) else v for k,v in shapes.items() } self._label_uniform() + def __repr__(self): + """Brief overview.""" + return util.srepr(self.comments)+'\n'+self.data.__repr__() def __copy__(self): """Copy Table.""" From f23b89f05596b952b5b58c3e84bcb38b13014acd Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 16:30:22 +0200 Subject: [PATCH 15/61] get rid of annoying warning during test --- python/damask/util.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/damask/util.py b/python/damask/util.py index a04ee47de..655f75879 100644 --- a/python/damask/util.py +++ b/python/damask/util.py @@ -172,8 +172,9 @@ def scale_to_coprime(v): m = (np.array(v) * reduce(lcm, map(lambda x: int(get_square_denominator(x)),v)) ** 0.5).astype(np.int) m = m//reduce(np.gcd,m) - if not np.allclose(v[v.nonzero()]/m[v.nonzero()],v[v.nonzero()][0]/m[m.nonzero()][0]): - raise ValueError(f'Invalid result {m} for input {v}. Insufficient precision?') + with np.errstate(divide='ignore'): + if not np.allclose(v/m,v[0]/m[0]): + raise ValueError(f'Invalid result {m} for input {v}. Insufficient precision?') return m From c42511f101c9607ffa2d80efee1c6dfadde548ec Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Fri, 18 Sep 2020 16:32:08 +0200 Subject: [PATCH 16/61] small polishing --- python/damask/_geom.py | 33 ++++++++++++++------------------- python/damask/_vtk.py | 2 ++ python/tests/test_Geom.py | 15 ++++----------- 3 files changed, 20 insertions(+), 30 deletions(-) diff --git a/python/damask/_geom.py b/python/damask/_geom.py index 60f7b90a5..be4f596c1 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -1,7 +1,5 @@ -import sys import copy -import multiprocessing -from io import StringIO +import multiprocessing as mp from functools import partial import numpy as np @@ -404,7 +402,7 @@ class Geom: seeds_p = seeds coords = grid_filters.cell_coord0(grid,size).reshape(-1,3) - pool = multiprocessing.Pool(processes = int(environment.options['DAMASK_NUM_THREADS'])) + pool = mp.Pool(processes = int(environment.options['DAMASK_NUM_THREADS'])) result = pool.map_async(partial(Geom._find_closest_seed,seeds_p,weights_p), [coord for coord in coords]) pool.close() pool.join() @@ -447,7 +445,7 @@ class Geom: ) - def save_ASCII(self,fname,pack=None): + def save_ASCII(self,fname,compress=None): """ Writes a geom file. @@ -455,7 +453,7 @@ class Geom: ---------- fname : str or file handle Geometry file to write with extension '.geom'. - pack : bool, optional + compress : bool, optional Compress geometry with 'x of y' and 'a to b'. """ @@ -467,10 +465,10 @@ class Geom: grid = self.get_grid() - if pack is None: + if compress is None: plain = grid.prod()/self.N_microstructure < 250 else: - plain = not pack + plain = not compress if plain: format_string = '%g' if self.microstructure.dtype in np.sctypes['float'] else \ @@ -518,7 +516,7 @@ class Geom: f.write(f'{reps} of {former}\n') - def save_vtr(self,fname=None): + def save_vtr(self,fname,compress=True): """ Generates vtk rectilinear grid. @@ -527,24 +525,21 @@ class Geom: fname : str, optional Filename to write. If no file is given, a string is returned. Valid extension is .vtr, it will be appended if not given. + compress : bool, optional + Compress with zlib algorithm. Defaults to True. """ v = VTK.from_rectilinearGrid(self.grid,self.size,self.origin) v.add(self.microstructure.flatten(order='F'),'materialpoint') v.add_comments(self.comments) - if fname: - v.save(fname if str(fname).endswith('.vtr') else str(fname)+'.vtr') - else: - sys.stdout.write(v.__repr__()) + v.save(fname if str(fname).endswith('.vtr') else str(fname)+'.vtr',parallel=False,compress=compress) - def as_ASCII(self,pack=False): - """Format geometry as human-readable ASCII.""" - f = StringIO() - self.save_ASCII(f,pack) - f.seek(0) - return ''.join(f.readlines()) + def show(self): + """Show on screen.""" + v = VTK.from_rectilinearGrid(self.grid,self.size,self.origin) + v.show() def add_primitive(self,dimension,center,exponent, diff --git a/python/damask/_vtk.py b/python/damask/_vtk.py index 2e424aefc..c1fe52f38 100644 --- a/python/damask/_vtk.py +++ b/python/damask/_vtk.py @@ -178,6 +178,8 @@ class VTK: Filename for writing. parallel : boolean, optional Write data in parallel background process. Defaults to True. + compress : bool, optional + Compress with zlib algorithm. Defaults to True. """ if isinstance(self.vtk_data,vtk.vtkRectilinearGrid): diff --git a/python/tests/test_Geom.py b/python/tests/test_Geom.py index 8c9e84c1f..12f50be96 100644 --- a/python/tests/test_Geom.py +++ b/python/tests/test_Geom.py @@ -69,18 +69,11 @@ class TestGeom: def test_write_read_file(self,default,tmpdir): with open(tmpdir/'default.geom','w') as f: - default.save_ASCII(f,pack=True) + default.save_ASCII(f,compress=True) with open(tmpdir/'default.geom') as f: new = Geom.load_ASCII(f) assert geom_equal(default,new) - def test_write_as_ASCII(self,default,tmpdir): - with open(tmpdir/'str.geom','w') as f: - f.write(default.as_ASCII()) - with open(tmpdir/'str.geom') as f: - new = Geom.load_ASCII(f) - assert geom_equal(default,new) - def test_read_write_vtr(self,default,tmpdir): default.save_vtr(tmpdir/'default') for _ in range(10): @@ -107,9 +100,9 @@ class TestGeom: Geom.load_vtr(tmpdir/'no_materialpoint.vtr') - @pytest.mark.parametrize('pack',[True,False]) - def test_pack(self,default,tmpdir,pack): - default.save_ASCII(tmpdir/'default.geom',pack=pack) + @pytest.mark.parametrize('compress',[True,False]) + def test_compress(self,default,tmpdir,compress): + default.save_ASCII(tmpdir/'default.geom',compress=compress) new = Geom.load_ASCII(tmpdir/'default.geom') assert geom_equal(new,default) From d6b681569326ba2d0602020d0efb0f1dbf053ed1 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Fri, 18 Sep 2020 11:35:58 -0400 Subject: [PATCH 17/61] resolve conflicting PRIVATE/master changes --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 0b5204381..576f3af61 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 0b5204381cc8b86212ed8c0de43110d0175badd4 +Subproject commit 576f3af61c3d893b608809cc91e46647809010f1 From cc92b0ad84dc6a48ac60fa7c885e33aa70281bba Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 08:20:29 +0200 Subject: [PATCH 18/61] print is more appropriate than write --- src/DAMASK_interface.f90 | 4 +- src/constitutive_plastic_nonlocal.f90 | 2 +- src/grid/DAMASK_grid.f90 | 40 ++++++++++---------- src/grid/discretization_grid.f90 | 2 +- src/grid/grid_damage_spectral.f90 | 38 ++++++++----------- src/grid/grid_mech_FEM.f90 | 29 +++++++------- src/grid/grid_mech_spectral_basic.f90 | 30 +++++++-------- src/grid/grid_mech_spectral_polarisation.f90 | 27 +++++++------ src/grid/grid_thermal_spectral.f90 | 30 ++++++--------- src/grid/spectral_utilities.f90 | 14 +++---- src/marc/discretization_marc.f90 | 2 +- src/mesh/DAMASK_mesh.f90 | 30 +++++++-------- src/mesh/FEM_quadrature.f90 | 2 +- src/mesh/FEM_utilities.f90 | 6 +-- src/mesh/discretization_mesh.f90 | 2 +- src/mesh/mesh_mech_FEM.f90 | 6 +-- 16 files changed, 124 insertions(+), 140 deletions(-) diff --git a/src/DAMASK_interface.f90 b/src/DAMASK_interface.f90 index 46ecd4da0..4c3258556 100644 --- a/src/DAMASK_interface.f90 +++ b/src/DAMASK_interface.f90 @@ -101,8 +101,8 @@ subroutine DAMASK_interface_init #endif print*, achar(27)//'[0m' - print'(a)', ' Roters et al., Computational Materials Science 158:420–478, 2019' - print'(a)', ' https://doi.org/10.1016/j.commatsci.2018.04.030' + print*, 'Roters et al., Computational Materials Science 158:420–478, 2019' + print*, 'https://doi.org/10.1016/j.commatsci.2018.04.030' print'(/,a)', ' Version: '//DAMASKVERSION diff --git a/src/constitutive_plastic_nonlocal.f90 b/src/constitutive_plastic_nonlocal.f90 index c96301691..9eef17719 100644 --- a/src/constitutive_plastic_nonlocal.f90 +++ b/src/constitutive_plastic_nonlocal.f90 @@ -199,7 +199,7 @@ module function plastic_nonlocal_init() result(myPlasticity) print*, 'https://doi.org/10.1016/j.actamat.2014.03.012'//IO_EOL print*, 'Kords, Dissertation RWTH Aachen, 2014' - print*, 'http://publications.rwth-aachen.de/record/229993'//IO_EOL + print*, 'http://publications.rwth-aachen.de/record/229993' allocate(param(Ninstance)) allocate(state(Ninstance)) diff --git a/src/grid/DAMASK_grid.f90 b/src/grid/DAMASK_grid.f90 index a5001de44..341210afc 100644 --- a/src/grid/DAMASK_grid.f90 +++ b/src/grid/DAMASK_grid.f90 @@ -99,10 +99,10 @@ program DAMASK_grid ! init DAMASK (all modules) call CPFEM_initAll - write(6,'(/,a)') ' <<<+- DAMASK_spectral init -+>>>'; flush(6) + print'(/,a)', ' <<<+- DAMASK_spectral init -+>>>'; flush(6) - write(6,'(/,a)') ' Shanthraj et al., Handbook of Mechanics of Materials, 2019' - write(6,'(a)') ' https://doi.org/10.1007/978-981-10-6855-3_80' + print*, 'Shanthraj et al., Handbook of Mechanics of Materials, 2019' + print*, 'https://doi.org/10.1007/978-981-10-6855-3_80' !-------------------------------------------------------------------------------------------------- ! initialize field solver information @@ -263,19 +263,19 @@ program DAMASK_grid reportAndCheck: if (worldrank == 0) then write (loadcase_string, '(i0)' ) currentLoadCase - write(6,'(/,1x,a,i0)') 'load case: ', currentLoadCase + print'(/,a,i0)', ' load case: ', currentLoadCase if (.not. newLoadCase%followFormerTrajectory) & - write(6,'(2x,a)') 'drop guessing along trajectory' + print*, ' drop guessing along trajectory' if (newLoadCase%deformation%myType == 'l') then do j = 1, 3 if (any(newLoadCase%deformation%maskLogical(j,1:3) .eqv. .true.) .and. & any(newLoadCase%deformation%maskLogical(j,1:3) .eqv. .false.)) errorID = 832 ! each row should be either fully or not at all defined enddo - write(6,'(2x,a)') 'velocity gradient:' + print*, ' velocity gradient:' else if (newLoadCase%deformation%myType == 'f') then - write(6,'(2x,a)') 'deformation gradient at end of load case:' + print*, ' deformation gradient at end of load case:' else - write(6,'(2x,a)') 'deformation gradient rate:' + print*, ' deformation gradient rate:' endif do i = 1, 3; do j = 1, 3 if(newLoadCase%deformation%maskLogical(i,j)) then @@ -289,7 +289,7 @@ program DAMASK_grid newLoadCase%deformation%maskLogical)) errorID = 831 ! exclusive or masking only if (any(newLoadCase%stress%maskLogical .and. transpose(newLoadCase%stress%maskLogical) & .and. (math_I3<1))) errorID = 838 ! no rotation is allowed by stress BC - write(6,'(2x,a)') 'stress / GPa:' + print*, ' stress / GPa:' do i = 1, 3; do j = 1, 3 if(newLoadCase%stress%maskLogical(i,j)) then write(6,'(2x,f12.7)',advance='no') newLoadCase%stress%values(i,j)*1e-9_pReal @@ -305,14 +305,14 @@ program DAMASK_grid write(6,'(2x,a,/,3(3(3x,f12.7,1x)/))',advance='no') 'rotation of loadframe:',& transpose(newLoadCase%rot%asMatrix()) if (newLoadCase%time < 0.0_pReal) errorID = 834 ! negative time increment - write(6,'(2x,a,f0.3)') 'time: ', newLoadCase%time + print'(a,f0.3)', ' time: ', newLoadCase%time if (newLoadCase%incs < 1) errorID = 835 ! non-positive incs count - write(6,'(2x,a,i0)') 'increments: ', newLoadCase%incs + print'(a,i0)', ' increments: ', newLoadCase%incs if (newLoadCase%outputfrequency < 1) errorID = 836 ! non-positive result frequency - write(6,'(2x,a,i0)') 'output frequency: ', newLoadCase%outputfrequency + print'(a,i0)', ' output frequency: ', newLoadCase%outputfrequency if (newLoadCase%restartfrequency < 1) errorID = 839 ! non-positive restart frequency if (newLoadCase%restartfrequency < huge(0)) & - write(6,'(2x,a,i0)') 'restart frequency: ', newLoadCase%restartfrequency + print'(a,i0)', ' restart frequency: ', newLoadCase%restartfrequency if (errorID > 0) call IO_error(error_ID = errorID, ext_msg = loadcase_string) ! exit with error message endif reportAndCheck loadCases = [loadCases,newLoadCase] ! load case is ok, append it @@ -397,8 +397,8 @@ program DAMASK_grid !-------------------------------------------------------------------------------------------------- ! report begin of new step - write(6,'(/,a)') ' ###########################################################################' - write(6,'(1x,a,es12.5,6(a,i0))') & + print'(/,a)', ' ###########################################################################' + print'(1x,a,es12.5,6(a,i0))', & 'Time', time, & 's: Increment ', inc,'/',loadCases(currentLoadCase)%incs,& '-', stepFraction,'/',subStepFactor**cutBackLevel,& @@ -475,7 +475,7 @@ program DAMASK_grid cutBackLevel = cutBackLevel + 1 time = time - timeinc ! rewind time timeinc = timeinc/real(subStepFactor,pReal) ! cut timestep - write(6,'(/,a)') ' cutting back ' + print'(/,a)', ' cutting back ' else ! no more options to continue call IO_warning(850) if (worldrank == 0) close(statUnit) @@ -487,13 +487,13 @@ program DAMASK_grid cutBackLevel = max(0, cutBackLevel - 1) ! try half number of subincs next inc if (all(solres(:)%converged)) then - write(6,'(/,a,i0,a)') ' increment ', totalIncsCounter, ' converged' + print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' converged' else - write(6,'(/,a,i0,a)') ' increment ', totalIncsCounter, ' NOT converged' + print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' NOT converged' endif; flush(6) if (mod(inc,loadCases(currentLoadCase)%outputFrequency) == 0) then ! at output frequency - write(6,'(1/,a)') ' ... writing results to file ......................................' + print'(1/,a)', ' ... writing results to file ......................................' flush(6) call CPFEM_results(totalIncsCounter,time) endif @@ -510,7 +510,7 @@ program DAMASK_grid !-------------------------------------------------------------------------------------------------- ! report summary of whole calculation - write(6,'(/,a)') ' ###########################################################################' + print'(/,a)', ' ###########################################################################' if (worldrank == 0) close(statUnit) call quit(0) ! no complains ;) diff --git a/src/grid/discretization_grid.f90 b/src/grid/discretization_grid.f90 index 276dd566f..576aaea60 100644 --- a/src/grid/discretization_grid.f90 +++ b/src/grid/discretization_grid.f90 @@ -65,7 +65,7 @@ subroutine discretization_grid_init(restart) integer(C_INTPTR_T) :: & devNull, z, z_offset - write(6,'(/,a)') ' <<<+- discretization_grid init -+>>>'; flush(6) + print'(/,a)', ' <<<+- discretization_grid init -+>>>'; flush(6) if(index(interface_geomFile,'.vtr') /= 0) then call readVTR(grid,geomSize,origin,microstructureAt) diff --git a/src/grid/grid_damage_spectral.f90 b/src/grid/grid_damage_spectral.f90 index f0d65a4a6..2a0754c66 100644 --- a/src/grid/grid_damage_spectral.f90 +++ b/src/grid/grid_damage_spectral.f90 @@ -22,42 +22,38 @@ module grid_damage_spectral implicit none private - type, private :: tNumerics + type :: tNumerics integer :: & - itmax !< max number of iterations + itmax !< maximum number of iterations real(pReal) :: & residualStiffness, & !< non-zero residual damage eps_damage_atol, & !< absolute tolerance for damage evolution eps_damage_rtol !< relative tolerance for damage evolution end type tNumerics - type(tNumerics), private :: num -!-------------------------------------------------------------------------------------------------- -! derived types - type(tSolutionParams), private :: params + type(tNumerics) :: num + type(tSolutionParams) :: params !-------------------------------------------------------------------------------------------------- ! PETSc data - SNES, private :: damage_snes - Vec, private :: solution_vec - PetscInt, private :: xstart, xend, ystart, yend, zstart, zend - real(pReal), private, dimension(:,:,:), allocatable :: & + SNES :: damage_snes + Vec :: solution_vec + PetscInt :: xstart, xend, ystart, yend, zstart, zend + real(pReal), dimension(:,:,:), allocatable :: & phi_current, & !< field of current damage phi_lastInc, & !< field of previous damage phi_stagInc !< field of staggered damage !-------------------------------------------------------------------------------------------------- ! reference diffusion tensor, mobility etc. - integer, private :: totalIter = 0 !< total iteration in current increment - real(pReal), dimension(3,3), private :: K_ref - real(pReal), private :: mu_ref + integer :: totalIter = 0 !< total iteration in current increment + real(pReal), dimension(3,3) :: K_ref + real(pReal) :: mu_ref public :: & grid_damage_spectral_init, & grid_damage_spectral_solution, & grid_damage_spectral_forward - private :: & - formResidual contains @@ -77,10 +73,10 @@ subroutine grid_damage_spectral_init character(len=pStringLen) :: & snes_type - write(6,'(/,a)') ' <<<+- grid_spectral_damage init -+>>>' + print'(/,a)', ' <<<+- grid_spectral_damage init -+>>>' - write(6,'(/,a)') ' Shanthraj et al., Handbook of Mechanics of Materials, 2019' - write(6,'(a)') ' https://doi.org/10.1007/978-981-10-6855-3_80' + print*, 'Shanthraj et al., Handbook of Mechanics of Materials, 2019' + print*, 'https://doi.org/10.1007/978-981-10-6855-3_80' !------------------------------------------------------------------------------------------------- ! read numerical parameters and do sanity checks @@ -152,8 +148,6 @@ subroutine grid_damage_spectral_init allocate(phi_stagInc(grid(1),grid(2),grid3), source=1.0_pReal) call VecSet(solution_vec,1.0_pReal,ierr); CHKERRQ(ierr) -!-------------------------------------------------------------------------------------------------- -! damage reference diffusion update call updateReference end subroutine grid_damage_spectral_init @@ -210,10 +204,10 @@ function grid_damage_spectral_solution(timeinc,timeinc_old) result(solution) call VecMin(solution_vec,devNull,phi_min,ierr); CHKERRQ(ierr) call VecMax(solution_vec,devNull,phi_max,ierr); CHKERRQ(ierr) if (solution%converged) & - write(6,'(/,a)') ' ... nonlocal damage converged .....................................' + print'(/,a)', ' ... nonlocal damage converged .....................................' write(6,'(/,a,f8.6,2x,f8.6,2x,e11.4,/)',advance='no') ' Minimum|Maximum|Delta Damage = ',& phi_min, phi_max, stagNorm - write(6,'(/,a)') ' ===========================================================================' + print'(/,a)', ' ===========================================================================' flush(6) end function grid_damage_spectral_solution diff --git a/src/grid/grid_mech_FEM.f90 b/src/grid/grid_mech_FEM.f90 index 748692b3c..3923e1898 100644 --- a/src/grid/grid_mech_FEM.f90 +++ b/src/grid/grid_mech_FEM.f90 @@ -122,7 +122,7 @@ subroutine grid_mech_FEM_init PetscScalar, pointer, dimension(:,:,:,:) :: & u_current,u_lastInc - write(6,'(/,a)') ' <<<+- grid_mech_FEM init -+>>>'; flush(6) + print'(/,a)', ' <<<+- grid_mech_FEM init -+>>>'; flush(6) !----------------------------------------------------------------------------------------------- ! debugging options @@ -130,13 +130,12 @@ subroutine grid_mech_FEM_init debugRotation = debug_grid%contains('rotation') !------------------------------------------------------------------------------------------------- -! read numerical parameter and do sanity checks +! read numerical parameters and do sanity checks num_grid => config_numerics%get('grid',defaultVal=emptyDict) num%eps_div_atol = num_grid%get_asFloat ('eps_div_atol', defaultVal=1.0e-4_pReal) num%eps_div_rtol = num_grid%get_asFloat ('eps_div_rtol', defaultVal=5.0e-4_pReal) num%eps_stress_atol = num_grid%get_asFloat ('eps_stress_atol', defaultVal=1.0e3_pReal) num%eps_stress_rtol = num_grid%get_asFloat ('eps_stress_rtol', defaultVal=0.01_pReal) - num%itmin = num_grid%get_asInt ('itmin',defaultVal=1) num%itmax = num_grid%get_asInt ('itmax',defaultVal=250) @@ -225,7 +224,7 @@ subroutine grid_mech_FEM_init !-------------------------------------------------------------------------------------------------- ! init fields restartRead: if (interface_restartInc > 0) then - write(6,'(/,a,i0,a)') ' reading restart data of increment ', interface_restartInc, ' from file' + print'(/,a,i0,a)', ' reading restart data of increment ', interface_restartInc, ' from file' write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName) @@ -254,7 +253,7 @@ subroutine grid_mech_FEM_init CHKERRQ(ierr) restartRead2: if (interface_restartInc > 0) then - write(6,'(/,a,i0,a)') ' reading more restart data of increment ', interface_restartInc, ' from file' + print'(a,i0,a)', ' reading more restart data of increment ', interface_restartInc, ' from file' call HDF5_read(groupHandle,C_volAvg, 'C_volAvg') call HDF5_read(groupHandle,C_volAvgLastInc,'C_volAvgLastInc') @@ -304,11 +303,11 @@ function grid_mech_FEM_solution(incInfoIn,timeinc,timeinc_old,stress_BC,rotation !-------------------------------------------------------------------------------------------------- ! solve BVP - call SNESsolve(mech_snes,PETSC_NULL_VEC,solution_current,ierr);CHKERRQ(ierr) + call SNESsolve(mech_snes,PETSC_NULL_VEC,solution_current,ierr); CHKERRQ(ierr) !-------------------------------------------------------------------------------------------------- ! check convergence - call SNESGetConvergedReason(mech_snes,reason,ierr);CHKERRQ(ierr) + call SNESGetConvergedReason(mech_snes,reason,ierr); CHKERRQ(ierr) solution%converged = reason > 0 solution%iterationsNeeded = totalIter @@ -353,7 +352,7 @@ subroutine grid_mech_FEM_forward(cutBack,guess,timeinc,timeinc_old,loadCaseTime, F_aimDot = merge(stress_BC%maskFloat*(F_aim-F_aim_lastInc)/timeinc_old, 0.0_pReal, guess) F_aim_lastInc = F_aim - !-------------------------------------------------------------------------------------------------- + !----------------------------------------------------------------------------------------------- ! calculate rate for aim if (deformation_BC%myType=='l') then ! calculate F_aimDot from given L and current F F_aimDot = & @@ -414,7 +413,7 @@ subroutine grid_mech_FEM_restartWrite call DMDAVecGetArrayF90(mech_grid,solution_current,u_current,ierr); CHKERRQ(ierr) call DMDAVecGetArrayF90(mech_grid,solution_lastInc,u_lastInc,ierr); CHKERRQ(ierr) - write(6,'(a)') ' writing solver data required for restart to file'; flush(6) + print*, 'writing solver data required for restart to file'; flush(6) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -476,12 +475,12 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,fnorm,reason,dummy,i !-------------------------------------------------------------------------------------------------- ! report - write(6,'(1/,a)') ' ... reporting .............................................................' - write(6,'(1/,a,f12.2,a,es8.2,a,es9.2,a)') ' error divergence = ', & + print'(1/,a)', ' ... reporting .............................................................' + print'(1/,a,f12.2,a,es8.2,a,es9.2,a)', ' error divergence = ', & err_div/divTol, ' (',err_div,' / m, tol = ',divTol,')' - write(6,'(a,f12.2,a,es8.2,a,es9.2,a)') ' error stress BC = ', & + print'(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' - write(6,'(/,a)') ' ===========================================================================' + print'(/,a)', ' ===========================================================================' flush(6) end subroutine converged @@ -516,7 +515,7 @@ subroutine formResidual(da_local,x_local, & ! begin of new iteration newIteration: if (totalIter <= PETScIter) then totalIter = totalIter + 1 - write(6,'(1x,a,3(a,i0))') trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter+1, '≤', num%itmax + print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter+1, '≤', num%itmax if (debugRotation) & write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) @@ -541,7 +540,7 @@ subroutine formResidual(da_local,x_local, & !-------------------------------------------------------------------------------------------------- ! evaluate constitutive response - call Utilities_constitutiveResponse(P_current,& + call utilities_constitutiveResponse(P_current,& P_av,C_volAvg,devNull, & F,params%timeinc,params%rotation_BC) call MPI_Allreduce(MPI_IN_PLACE,terminallyIll,1,MPI_LOGICAL,MPI_LOR,PETSC_COMM_WORLD,ierr) diff --git a/src/grid/grid_mech_spectral_basic.f90 b/src/grid/grid_mech_spectral_basic.f90 index 9d301b30f..14d317c73 100644 --- a/src/grid/grid_mech_spectral_basic.f90 +++ b/src/grid/grid_mech_spectral_basic.f90 @@ -42,8 +42,7 @@ module grid_mech_spectral_basic type(tNumerics) :: num ! numerics parameters. Better name? - logical, private:: & - debugRotation + logical, private :: debugRotation !-------------------------------------------------------------------------------------------------- ! PETSc data @@ -110,13 +109,13 @@ subroutine grid_mech_spectral_basic_init character(len=pStringLen) :: & fileName - write(6,'(/,a)') ' <<<+- grid_mech_spectral_basic init -+>>>'; flush(6) + print'(/,a)', ' <<<+- grid_mech_spectral_basic init -+>>>'; flush(6) - write(6,'(/,a)') ' Eisenlohr et al., International Journal of Plasticity 46:37–53, 2013' - write(6,'(a)') ' https://doi.org/10.1016/j.ijplas.2012.09.012' + print*, 'Eisenlohr et al., International Journal of Plasticity 46:37–53, 2013' + print*, 'https://doi.org/10.1016/j.ijplas.2012.09.012'//IO_EOL - write(6,'(/,a)') ' Shanthraj et al., International Journal of Plasticity 66:31–45, 2015' - write(6,'(a)') ' https://doi.org/10.1016/j.ijplas.2014.02.006' + print*, 'Shanthraj et al., International Journal of Plasticity 66:31–45, 2015' + print*, 'https://doi.org/10.1016/j.ijplas.2014.02.006' !------------------------------------------------------------------------------------------------- ! debugging options @@ -132,7 +131,6 @@ subroutine grid_mech_spectral_basic_init num%eps_div_rtol = num_grid%get_asFloat ('eps_div_rtol', defaultVal=5.0e-4_pReal) num%eps_stress_atol = num_grid%get_asFloat ('eps_stress_atol',defaultVal=1.0e3_pReal) num%eps_stress_rtol = num_grid%get_asFloat ('eps_stress_rtol',defaultVal=0.01_pReal) - num%itmin = num_grid%get_asInt ('itmin',defaultVal=1) num%itmax = num_grid%get_asInt ('itmax',defaultVal=250) @@ -186,7 +184,7 @@ subroutine grid_mech_spectral_basic_init call DMDAVecGetArrayF90(da,solution_vec,F,ierr); CHKERRQ(ierr) ! places pointer on PETSc data restartRead: if (interface_restartInc > 0) then - write(6,'(/,a,i0,a)') ' reading restart data of increment ', interface_restartInc, ' from file' + print'(/,a,i0,a)', ' reading restart data of increment ', interface_restartInc, ' from file' write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName) @@ -211,7 +209,7 @@ subroutine grid_mech_spectral_basic_init call DMDAVecRestoreArrayF90(da,solution_vec,F,ierr); CHKERRQ(ierr) ! deassociate pointer restartRead2: if (interface_restartInc > 0) then - write(6,'(/,a,i0,a)') ' reading more restart data of increment ', interface_restartInc, ' from file' + print'(a,i0,a)', ' reading more restart data of increment ', interface_restartInc, ' from file' call HDF5_read(groupHandle,C_volAvg, 'C_volAvg') call HDF5_read(groupHandle,C_volAvgLastInc,'C_volAvgLastInc') @@ -377,7 +375,7 @@ subroutine grid_mech_spectral_basic_restartWrite call DMDAVecGetArrayF90(da,solution_vec,F,ierr); CHKERRQ(ierr) - write(6,'(a)') ' writing solver data required for restart to file'; flush(6) + print'(a)', ' writing solver data required for restart to file'; flush(6) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -437,12 +435,12 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,devNull3,reason,dumm !-------------------------------------------------------------------------------------------------- ! report - write(6,'(1/,a)') ' ... reporting .............................................................' - write(6,'(1/,a,f12.2,a,es8.2,a,es9.2,a)') ' error divergence = ', & + print'(1/,a)', ' ... reporting .............................................................' + print'(1/,a,f12.2,a,es8.2,a,es9.2,a)', ' error divergence = ', & err_div/divTol, ' (',err_div,' / m, tol = ',divTol,')' - write(6,'(a,f12.2,a,es8.2,a,es9.2,a)') ' error stress BC = ', & + print'(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' - write(6,'(/,a)') ' ===========================================================================' + print'(/,a)', ' ===========================================================================' flush(6) end subroutine converged @@ -475,7 +473,7 @@ subroutine formResidual(in, F, & ! begin of new iteration newIteration: if (totalIter <= PETScIter) then totalIter = totalIter + 1 - write(6,'(1x,a,3(a,i0))') trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax + print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax if (debugRotation) & write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) diff --git a/src/grid/grid_mech_spectral_polarisation.f90 b/src/grid/grid_mech_spectral_polarisation.f90 index 5414d02a8..f83ebed75 100644 --- a/src/grid/grid_mech_spectral_polarisation.f90 +++ b/src/grid/grid_mech_spectral_polarisation.f90 @@ -123,10 +123,10 @@ subroutine grid_mech_spectral_polarisation_init character(len=pStringLen) :: & fileName - write(6,'(/,a)') ' <<<+- grid_mech_spectral_polarisation init -+>>>'; flush(6) + print'(/,a)', ' <<<+- grid_mech_spectral_polarisation init -+>>>'; flush(6) - write(6,'(/,a)') ' Shanthraj et al., International Journal of Plasticity 66:31–45, 2015' - write(6,'(a)') ' https://doi.org/10.1016/j.ijplas.2014.02.006' + print*, 'Shanthraj et al., International Journal of Plasticity 66:31–45, 2015' + print*, 'https://doi.org/10.1016/j.ijplas.2014.02.006' !------------------------------------------------------------------------------------------------ ! debugging options @@ -134,9 +134,8 @@ subroutine grid_mech_spectral_polarisation_init debugRotation = debug_grid%contains('rotation') !------------------------------------------------------------------------------------------------- -! read numerical parameters +! read numerical parameters and do sanity checks num_grid => config_numerics%get('grid',defaultVal=emptyDict) - num%update_gamma = num_grid%get_asBool ('update_gamma', defaultVal=.false.) num%eps_div_atol = num_grid%get_asFloat ('eps_div_atol', defaultVal=1.0e-4_pReal) num%eps_div_rtol = num_grid%get_asFloat ('eps_div_rtol', defaultVal=5.0e-4_pReal) @@ -207,7 +206,7 @@ subroutine grid_mech_spectral_polarisation_init F_tau => FandF_tau(9:17,:,:,:) restartRead: if (interface_restartInc > 0) then - write(6,'(/,a,i0,a)') ' reading restart data of increment ', interface_restartInc, ' from file' + print'(/,a,i0,a)', ' reading restart data of increment ', interface_restartInc, ' from file' write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName) @@ -236,7 +235,7 @@ subroutine grid_mech_spectral_polarisation_init call DMDAVecRestoreArrayF90(da,solution_vec,FandF_tau,ierr); CHKERRQ(ierr) ! deassociate pointer restartRead2: if (interface_restartInc > 0) then - write(6,'(/,a,i0,a)') ' reading more restart data of increment ', interface_restartInc, ' from file' + print'(a,i0,a)', ' reading more restart data of increment ', interface_restartInc, ' from file' call HDF5_read(groupHandle,C_volAvg, 'C_volAvg') call HDF5_read(groupHandle,C_volAvgLastInc,'C_volAvgLastInc') @@ -434,7 +433,7 @@ subroutine grid_mech_spectral_polarisation_restartWrite F => FandF_tau(0: 8,:,:,:) F_tau => FandF_tau(9:17,:,:,:) - write(6,'(a)') ' writing solver data required for restart to file'; flush(6) + print*, 'writing solver data required for restart to file'; flush(6) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -498,14 +497,14 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,devNull3,reason,dumm !-------------------------------------------------------------------------------------------------- ! report - write(6,'(1/,a)') ' ... reporting .............................................................' - write(6,'(1/,a,f12.2,a,es8.2,a,es9.2,a)') ' error divergence = ', & + print'(1/,a)', ' ... reporting .............................................................' + print'(1/,a,f12.2,a,es8.2,a,es9.2,a)', ' error divergence = ', & err_div/divTol, ' (',err_div, ' / m, tol = ',divTol,')' - write(6, '(a,f12.2,a,es8.2,a,es9.2,a)') ' error curl = ', & + print '(a,f12.2,a,es8.2,a,es9.2,a)', ' error curl = ', & err_curl/curlTol,' (',err_curl,' -, tol = ',curlTol,')' - write(6, '(a,f12.2,a,es8.2,a,es9.2,a)') ' error BC = ', & + print '(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' - write(6,'(/,a)') ' ===========================================================================' + print'(/,a)', ' ===========================================================================' flush(6) end subroutine converged @@ -558,7 +557,7 @@ subroutine formResidual(in, FandF_tau, & ! begin of new iteration newIteration: if (totalIter <= PETScIter) then totalIter = totalIter + 1 - write(6,'(1x,a,3(a,i0))') trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax + print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax if(debugRotation) & write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) diff --git a/src/grid/grid_thermal_spectral.f90 b/src/grid/grid_thermal_spectral.f90 index 5456f40eb..eeff8c9d6 100644 --- a/src/grid/grid_thermal_spectral.f90 +++ b/src/grid/grid_thermal_spectral.f90 @@ -23,20 +23,17 @@ module grid_thermal_spectral implicit none private -!-------------------------------------------------------------------------------------------------- -! derived types - type(tSolutionParams) :: params - type :: tNumerics integer :: & - itmax !< maximum number of iterations + itmax !< maximum number of iterations real(pReal) :: & - eps_thermal_atol, & !< absolute tolerance for thermal equilibrium - eps_thermal_rtol !< relative tolerance for thermal equilibrium + eps_thermal_atol, & !< absolute tolerance for thermal equilibrium + eps_thermal_rtol !< relative tolerance for thermal equilibrium end type tNumerics type(tNumerics) :: num + type(tSolutionParams) :: params !-------------------------------------------------------------------------------------------------- ! PETSc data SNES :: thermal_snes @@ -74,13 +71,13 @@ subroutine grid_thermal_spectral_init class(tNode), pointer :: & num_grid - write(6,'(/,a)') ' <<<+- grid_thermal_spectral init -+>>>' + print'(/,a)', ' <<<+- grid_thermal_spectral init -+>>>' - write(6,'(/,a)') ' Shanthraj et al., Handbook of Mechanics of Materials, 2019' - write(6,'(a)') ' https://doi.org/10.1007/978-981-10-6855-3_80' + print*, 'Shanthraj et al., Handbook of Mechanics of Materials, 2019' + print*, 'https://doi.org/10.1007/978-981-10-6855-3_80' !------------------------------------------------------------------------------------------------- -! read numerical parameter and do sanity checks +! read numerical parameters and do sanity checks num_grid => config_numerics%get('grid',defaultVal=emptyDict) num%itmax = num_grid%get_asInt ('itmax', defaultVal=250) num%eps_thermal_atol = num_grid%get_asFloat ('eps_thermal_atol',defaultVal=1.0e-2_pReal) @@ -94,8 +91,7 @@ subroutine grid_thermal_spectral_init ! set default and user defined options for PETSc call PETScOptionsInsertString(PETSC_NULL_OPTIONS,'-thermal_snes_type ngmres',ierr) CHKERRQ(ierr) - call PETScOptionsInsertString(PETSC_NULL_OPTIONS,& - num_grid%get_asString('petsc_options',defaultVal=''),ierr) + call PETScOptionsInsertString(PETSC_NULL_OPTIONS,num_grid%get_asString('petsc_options',defaultVal=''),ierr) CHKERRQ(ierr) !-------------------------------------------------------------------------------------------------- @@ -110,7 +106,7 @@ subroutine grid_thermal_spectral_init DMDA_STENCIL_BOX, & ! Moore (26) neighborhood around central point grid(1),grid(2),grid(3), & ! global grid 1, 1, worldsize, & - 1, 0, & ! #dof (thermal phase field), ghost boundary width (domain overlap) + 1, 0, & ! #dof (T field), ghost boundary width (domain overlap) [grid(1)],[grid(2)],localK, & ! local grid thermal_grid,ierr) ! handle, error CHKERRQ(ierr) @@ -159,8 +155,6 @@ function grid_thermal_spectral_solution(timeinc,timeinc_old) result(solution) timeinc_old !< increment in time of last increment integer :: i, j, k, cell type(tSolutionState) :: solution - class(tNode), pointer :: & - num_grid PetscInt :: devNull PetscReal :: T_min, T_max, stagNorm, solnNorm @@ -204,10 +198,10 @@ function grid_thermal_spectral_solution(timeinc,timeinc_old) result(solution) call VecMin(solution_vec,devNull,T_min,ierr); CHKERRQ(ierr) call VecMax(solution_vec,devNull,T_max,ierr); CHKERRQ(ierr) if (solution%converged) & - write(6,'(/,a)') ' ... thermal conduction converged ..................................' + print'(/,a)', ' ... thermal conduction converged ..................................' write(6,'(/,a,f8.4,2x,f8.4,2x,f8.4,/)',advance='no') ' Minimum|Maximum|Delta Temperature / K = ',& T_min, T_max, stagNorm - write(6,'(/,a)') ' ===========================================================================' + print'(/,a)', ' ===========================================================================' flush(6) end function grid_thermal_spectral_solution diff --git a/src/grid/spectral_utilities.f90 b/src/grid/spectral_utilities.f90 index 1dc66a23f..764e8adb6 100644 --- a/src/grid/spectral_utilities.f90 +++ b/src/grid/spectral_utilities.f90 @@ -208,7 +208,7 @@ subroutine spectral_utilities_init debugPETSc = debug_grid%contains('petsc') - if(debugPETSc) write(6,'(3(/,a),/)') & + if(debugPETSc) print'(3(/,a),/)', & ' Initializing PETSc with debug options: ', & trim(PETScDebug), & ' add more using the PETSc_Options keyword in numerics.yaml '; flush(6) @@ -280,7 +280,7 @@ subroutine spectral_utilities_init if (pReal /= C_DOUBLE .or. kind(1) /= C_INT) error stop 'C and Fortran datatypes do not match' call fftw_set_timelimit(num_grid%get_asFloat('fftw_timelimit',defaultVal=-1.0_pReal)) - if (debugGeneral) write(6,'(/,a)') ' FFTW initialized'; flush(6) + print*, 'FFTW initialized'; flush(6) !-------------------------------------------------------------------------------------------------- ! MPI allocation @@ -506,7 +506,7 @@ subroutine utilities_fourierGammaConvolution(fieldAim) logical :: err - write(6,'(/,a)') ' ... doing gamma convolution ...............................................' + print'(/,a)', ' ... doing gamma convolution ...............................................' flush(6) !-------------------------------------------------------------------------------------------------- @@ -576,7 +576,7 @@ real(pReal) function utilities_divergenceRMS() integer :: i, j, k, ierr complex(pReal), dimension(3) :: rescaledGeom - write(6,'(/,a)') ' ... calculating divergence ................................................' + print'(/,a)', ' ... calculating divergence ................................................' flush(6) rescaledGeom = cmplx(geomSize/scaledGeomSize,0.0_pReal) @@ -620,7 +620,7 @@ real(pReal) function utilities_curlRMS() complex(pReal), dimension(3,3) :: curl_fourier complex(pReal), dimension(3) :: rescaledGeom - write(6,'(/,a)') ' ... calculating curl ......................................................' + print'(/,a)', ' ... calculating curl ......................................................' flush(6) rescaledGeom = cmplx(geomSize/scaledGeomSize,0.0_pReal) @@ -822,7 +822,7 @@ subroutine utilities_constitutiveResponse(P,P_av,C_volAvg,C_minmaxAvg,& real(pReal) :: dPdF_norm_max, dPdF_norm_min real(pReal), dimension(2) :: valueAndRank !< pair of min/max norm of dPdF to synchronize min/max of dPdF - write(6,'(/,a)') ' ... evaluating constitutive response ......................................' + print'(/,a)', ' ... evaluating constitutive response ......................................' flush(6) materialpoint_F = reshape(F,[3,3,1,product(grid(1:2))*grid3]) ! set materialpoint target F to estimated field @@ -1095,7 +1095,7 @@ subroutine utilities_saveReferenceStiffness fileUnit,ierr if (worldrank == 0) then - write(6,'(a)') ' writing reference stiffness data required for restart to file'; flush(6) + print'(a)', ' writing reference stiffness data required for restart to file'; flush(6) open(newunit=fileUnit, file=getSolverJobName()//'.C_ref',& status='replace',access='stream',action='write',iostat=ierr) if(ierr /=0) call IO_error(100,ext_msg='could not open file '//getSolverJobName()//'.C_ref') diff --git a/src/marc/discretization_marc.f90 b/src/marc/discretization_marc.f90 index b2f5f8905..30d1bd9fc 100644 --- a/src/marc/discretization_marc.f90 +++ b/src/marc/discretization_marc.f90 @@ -70,7 +70,7 @@ subroutine discretization_marc_init class(tNode), pointer :: & num_commercialFEM - write(6,'(/,a)') ' <<<+- discretization_marc init -+>>>'; flush(6) + print'(/,a)', ' <<<+- discretization_marc init -+>>>'; flush(6) !--------------------------------------------------------------------------------- ! read debug parameters diff --git a/src/mesh/DAMASK_mesh.f90 b/src/mesh/DAMASK_mesh.f90 index 2fefe73a9..0ba56bef3 100644 --- a/src/mesh/DAMASK_mesh.f90 +++ b/src/mesh/DAMASK_mesh.f90 @@ -78,7 +78,7 @@ program DAMASK_mesh !-------------------------------------------------------------------------------------------------- ! init DAMASK (all modules) call CPFEM_initAll - write(6,'(/,a)') ' <<<+- DAMASK_FEM init -+>>>'; flush(6) + print'(/,a)', ' <<<+- DAMASK_mesh init -+>>>'; flush(6) !--------------------------------------------------------------------- ! reading field information from numerics file and do sanity checks @@ -208,30 +208,30 @@ program DAMASK_mesh errorID = 0 checkLoadcases: do currentLoadCase = 1, size(loadCases) write (loadcase_string, '(i0)' ) currentLoadCase - write(6,'(1x,a,i6)') 'load case: ', currentLoadCase + print'(a,i0)', ' load case: ', currentLoadCase if (.not. loadCases(currentLoadCase)%followFormerTrajectory) & - write(6,'(2x,a)') 'drop guessing along trajectory' + print'(a)', ' drop guessing along trajectory' do field = 1, nActiveFields select case (loadCases(currentLoadCase)%fieldBC(field)%ID) case(FIELD_MECH_ID) - write(6,'(2x,a)') 'Field '//trim(FIELD_MECH_label) + print'(a)', ' Field '//trim(FIELD_MECH_label) end select do faceSet = 1, mesh_Nboundaries do component = 1, loadCases(currentLoadCase)%fieldBC(field)%nComponents if (loadCases(currentLoadCase)%fieldBC(field)%componentBC(component)%Mask(faceSet)) & - write(6,'(4x,a,i2,a,i2,a,f12.7)') 'Face ', mesh_boundaries(faceSet), & + print'(a,i2,a,i2,a,f12.7)', ' Face ', mesh_boundaries(faceSet), & ' Component ', component, & ' Value ', loadCases(currentLoadCase)%fieldBC(field)% & componentBC(component)%Value(faceSet) enddo enddo enddo - write(6,'(2x,a,f12.6)') 'time: ', loadCases(currentLoadCase)%time + print'(a,f12.6)', ' time: ', loadCases(currentLoadCase)%time if (loadCases(currentLoadCase)%incs < 1) errorID = 835 ! non-positive incs count - write(6,'(2x,a,i5)') 'increments: ', loadCases(currentLoadCase)%incs + print'(a,i5)', ' increments: ', loadCases(currentLoadCase)%incs if (loadCases(currentLoadCase)%outputfrequency < 1) errorID = 836 ! non-positive result frequency - write(6,'(2x,a,i5)') 'output frequency: ', & + print'(a,i5)', ' output frequency: ', & loadCases(currentLoadCase)%outputfrequency if (errorID > 0) call IO_error(error_ID = errorID, ext_msg = loadcase_string) ! exit with error message enddo checkLoadcases @@ -290,8 +290,8 @@ program DAMASK_mesh !-------------------------------------------------------------------------------------------------- ! report begin of new step - write(6,'(/,a)') ' ###########################################################################' - write(6,'(1x,a,es12.5,6(a,i0))')& + print'(/,a)', ' ###########################################################################' + print'(1x,a,es12.5,6(a,i0))',& 'Time', time, & 's: Increment ', inc, '/', loadCases(currentLoadCase)%incs,& '-', stepFraction, '/', subStepFactor**cutBackLevel,& @@ -338,7 +338,7 @@ program DAMASK_mesh cutBack = .False. if(.not. all(solres(:)%converged .and. solres(:)%stagConverged)) then ! no solution found if (cutBackLevel < maxCutBack) then ! do cut back - write(6,'(/,a)') ' cut back detected' + print'(/,a)', ' cut back detected' cutBack = .True. stepFraction = (stepFraction - 1) * subStepFactor ! adjust to new denominator cutBackLevel = cutBackLevel + 1 @@ -360,13 +360,13 @@ program DAMASK_mesh cutBackLevel = max(0, cutBackLevel - 1) ! try half number of subincs next inc if (all(solres(:)%converged)) then - write(6,'(/,a,i0,a)') ' increment ', totalIncsCounter, ' converged' + print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' converged' else - write(6,'(/,a,i0,a)') ' increment ', totalIncsCounter, ' NOT converged' + print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' NOT converged' endif; flush(6) if (mod(inc,loadCases(currentLoadCase)%outputFrequency) == 0) then ! at output frequency - write(6,'(1/,a)') ' ... writing results to file ......................................' + print'(/,a)', ' ... writing results to file ......................................' call CPFEM_results(totalIncsCounter,time) endif @@ -378,7 +378,7 @@ program DAMASK_mesh !-------------------------------------------------------------------------------------------------- ! report summary of whole calculation - write(6,'(/,a)') ' ###########################################################################' + print'(/,a)', ' ###########################################################################' if (worldrank == 0) close(statUnit) call quit(0) ! no complains ;) diff --git a/src/mesh/FEM_quadrature.f90 b/src/mesh/FEM_quadrature.f90 index 65b0bc6fe..4cc5e5468 100644 --- a/src/mesh/FEM_quadrature.f90 +++ b/src/mesh/FEM_quadrature.f90 @@ -37,7 +37,7 @@ contains !-------------------------------------------------------------------------------------------------- subroutine FEM_quadrature_init - write(6,'(/,a)') ' <<<+- FEM_quadrature init -+>>>'; flush(6) + print'(/,a)', ' <<<+- FEM_quadrature init -+>>>'; flush(6) !-------------------------------------------------------------------------------------------------- ! 2D linear diff --git a/src/mesh/FEM_utilities.f90 b/src/mesh/FEM_utilities.f90 index 551a863b6..1e154e533 100644 --- a/src/mesh/FEM_utilities.f90 +++ b/src/mesh/FEM_utilities.f90 @@ -110,7 +110,7 @@ subroutine FEM_utilities_init PetscErrorCode :: ierr - write(6,'(/,a)') ' <<<+- FEM_utilities init -+>>>' + print'(/,a)', ' <<<+- FEM_utilities init -+>>>' num_mesh => config_numerics%get('mesh',defaultVal=emptyDict) structOrder = num_mesh%get_asInt('structOrder', defaultVal = 2) @@ -118,7 +118,7 @@ subroutine FEM_utilities_init debug_mesh => config_debug%get('mesh',defaultVal=emptyList) debugPETSc = debug_mesh%contains('petsc') - if(debugPETSc) write(6,'(3(/,a),/)') & + if(debugPETSc) print'(3(/,a),/)', & ' Initializing PETSc with debug options: ', & trim(PETScDebug), & ' add more using the PETSc_Options keyword in numerics.yaml ' @@ -158,7 +158,7 @@ subroutine utilities_constitutiveResponse(timeinc,P_av,forwardData) PetscErrorCode :: ierr - write(6,'(/,a)') ' ... evaluating constitutive response ......................................' + print'(/,a)', ' ... evaluating constitutive response ......................................' call materialpoint_stressAndItsTangent(.true.,timeinc) ! calculate P field diff --git a/src/mesh/discretization_mesh.f90 b/src/mesh/discretization_mesh.f90 index 54854ce68..b57a4b332 100644 --- a/src/mesh/discretization_mesh.f90 +++ b/src/mesh/discretization_mesh.f90 @@ -83,7 +83,7 @@ subroutine discretization_mesh_init(restart) num_mesh integer :: integrationOrder !< order of quadrature rule required - write(6,'(/,a)') ' <<<+- discretization_mesh init -+>>>' + print'(/,a)', ' <<<+- discretization_mesh init -+>>>' !-------------------------------------------------------------------------------- ! read numerics parameter diff --git a/src/mesh/mesh_mech_FEM.f90 b/src/mesh/mesh_mech_FEM.f90 index 546897c5b..6c8d4667d 100644 --- a/src/mesh/mesh_mech_FEM.f90 +++ b/src/mesh/mesh_mech_FEM.f90 @@ -110,7 +110,7 @@ subroutine FEM_mech_init(fieldBC) class(tNode), pointer :: & num_mesh - write(6,'(/,a)') ' <<<+- FEM_mech init -+>>>'; flush(6) + print'(/,a)', ' <<<+- FEM_mech init -+>>>'; flush(6) !----------------------------------------------------------------------------- ! read numerical parametes and do sanity checks @@ -318,7 +318,7 @@ type(tSolutionState) function FEM_mech_solution( & CHKERRQ(ierr) endif - write(6,'(/,a)') ' ===========================================================================' + print'(/,a)', ' ===========================================================================' flush(6) end function FEM_mech_solution @@ -679,7 +679,7 @@ subroutine FEM_mech_converged(snes_local,PETScIter,xnorm,snorm,fnorm,reason,dumm call SNESConvergedDefault(snes_local,PETScIter,xnorm,snorm,fnorm/divTol,reason,dummy,ierr) CHKERRQ(ierr) if (terminallyIll) reason = SNES_DIVERGED_FUNCTION_DOMAIN - write(6,'(1/,1x,a,a,i0,a,i0,f0.3)') trim(incInfo), & + print'(/,1x,a,a,i0,a,i0,f0.3)', trim(incInfo), & ' @ Iteration ',PETScIter,' mechanical residual norm = ', & int(fnorm/divTol),fnorm/divTol-int(fnorm/divTol) write(6,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& From 0746a2f3a4295a94adf5c54ff2344d7809349299 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 08:33:15 +0200 Subject: [PATCH 19/61] give visual feedback in most tests, this is done manually --- python/damask/util.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/damask/util.py b/python/damask/util.py index a04ee47de..bd3e97534 100644 --- a/python/damask/util.py +++ b/python/damask/util.py @@ -117,6 +117,7 @@ def execute(cmd, initialPath = os.getcwd() myEnv = os.environ if env is None else env os.chdir(wd) + print(f"executing '{cmd}' in '{wd}'") process = subprocess.Popen(shlex.split(cmd), stdout = subprocess.PIPE, stderr = subprocess.PIPE, @@ -128,7 +129,7 @@ def execute(cmd, stdout = stdout.decode('utf-8').replace('\x08','') stderr = stderr.decode('utf-8').replace('\x08','') if process.returncode != 0: - raise RuntimeError(f'{cmd} failed with returncode {process.returncode}') + raise RuntimeError(f"'{cmd}' failed with returncode {process.returncode}") return stdout, stderr From 0f5a5a61aa7f0ebe7e899ec2c3c23294b40bed36 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 08:41:14 +0200 Subject: [PATCH 20/61] pytests simplifies writing of tests --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 555f3e01f..df9a16a89 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 555f3e01f2b5cf43ade1bd48423b890adca21771 +Subproject commit df9a16a89c069a3d1076447fce90d759c45248a3 From 51f43ddc09d0462c8c5844c698702059e63d4117 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 09:24:27 +0200 Subject: [PATCH 21/61] small polishing --- src/material.f90 | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/material.f90 b/src/material.f90 index 835de2fc1..628952129 100644 --- a/src/material.f90 +++ b/src/material.f90 @@ -181,10 +181,10 @@ subroutine material_init(restart) enddo call material_parseMicrostructure - print*, ' Microstructure parsed' + print*, 'Microstructure parsed' call material_parseHomogenization - print*, ' Homogenization parsed' + print*, 'Homogenization parsed' if(homogenization_maxNgrains > size(material_phaseAt,1)) call IO_error(148) @@ -331,7 +331,6 @@ subroutine material_parseMicrostructure CounterPhase, & CounterHomogenization - real(pReal), dimension(:,:), allocatable :: & microstructure_fraction !< vol fraction of each constituent in microstrcuture @@ -342,15 +341,13 @@ subroutine material_parseMicrostructure c, & microstructure_maxNconstituents - real(pReal), dimension(4) :: phase_orientation - homogenization => config_material%get('homogenization') phases => config_material%get('phase') microstructure => config_material%get('microstructure') - allocate(microstructure_Nconstituents(microstructure%length), source = 0) + allocate(microstructure_Nconstituents(microstructure%length),source=0) if(any(discretization_microstructureAt > microstructure%length)) & - call IO_error(155,ext_msg='More microstructures in geometry than sections in material.yaml') + call IO_error(155,ext_msg='More microstructures requested than found in material.yaml') do m = 1, microstructure%length constituentsInMicrostructure => microstructure%get(m) @@ -360,10 +357,11 @@ subroutine material_parseMicrostructure microstructure_maxNconstituents = maxval(microstructure_Nconstituents) allocate(microstructure_fraction(microstructure_maxNconstituents,microstructure%length), source =0.0_pReal) - allocate(material_phaseAt(microstructure_maxNconstituents,discretization_nElem), source =0) allocate(material_orientation0(microstructure_maxNconstituents,discretization_nIP,discretization_nElem)) - allocate(material_homogenizationAt(discretization_nElem)) + + allocate(material_homogenizationAt(discretization_nElem),source=0) allocate(material_homogenizationMemberAt(discretization_nIP,discretization_nElem),source=0) + allocate(material_phaseAt(microstructure_maxNconstituents,discretization_nElem),source=0) allocate(material_phaseMemberAt(microstructure_maxNconstituents,discretization_nIP,discretization_nElem),source=0) allocate(CounterPhase(phases%length),source=0) @@ -386,8 +384,7 @@ subroutine material_parseMicrostructure do c = 1, constituents%length constituent => constituents%get(c) material_phaseAt(c,e) = phases%getIndex(constituent%get_asString('phase')) - phase_orientation = constituent%get_asFloats('orientation') - call material_orientation0(c,i,e)%fromQuaternion(phase_orientation) + call material_orientation0(c,i,e)%fromQuaternion(constituent%get_asFloats('orientation',requiredSize=4)) enddo enddo enddo @@ -413,7 +410,6 @@ subroutine material_parseMicrostructure enddo enddo - end subroutine material_parseMicrostructure From c4ce28e63f99ef7e928a2bdd45bb041fd6c0ad6a Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 09:41:48 +0200 Subject: [PATCH 22/61] untangling --- src/material.f90 | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/material.f90 b/src/material.f90 index 628952129..e531cae83 100644 --- a/src/material.f90 +++ b/src/material.f90 @@ -378,9 +378,9 @@ subroutine material_parseMicrostructure enddo do e = 1, discretization_nElem + constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) + constituents => constituentsInMicrostructure%get('constituents') do i = 1, discretization_nIP - constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) - constituents => constituentsInMicrostructure%get('constituents') do c = 1, constituents%length constituent => constituents%get(c) material_phaseAt(c,e) = phases%getIndex(constituent%get_asString('phase')) @@ -390,24 +390,26 @@ subroutine material_parseMicrostructure enddo do e = 1, discretization_nElem + constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) + material_homogenizationAt(e) = homogenization%getIndex(constituentsInMicrostructure%get_asString('homogenization')) do i = 1, discretization_nIP - constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) - material_homogenizationAt(e) = homogenization%getIndex(constituentsInMicrostructure%get_asString('homogenization')) CounterHomogenization(material_homogenizationAt(e)) = CounterHomogenization(material_homogenizationAt(e)) + 1 material_homogenizationMemberAt(i,e) = CounterHomogenization(material_homogenizationAt(e)) enddo enddo do e = 1, discretization_nElem + constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) + constituents => constituentsInMicrostructure%get('constituents') + do i = 1, discretization_nIP - constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) - constituents => constituentsInMicrostructure%get('constituents') do c = 1, constituents%length CounterPhase(material_phaseAt(c,e)) = & CounterPhase(material_phaseAt(c,e)) + 1 material_phaseMemberAt(c,i,e) = CounterPhase(material_phaseAt(c,e)) enddo enddo + enddo end subroutine material_parseMicrostructure From 201303f35f17c86f1474cda5c0342ca61c9bdbe2 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 10:00:49 +0200 Subject: [PATCH 23/61] clarified logic --- src/material.f90 | 88 +++++++++++++++++++----------------------------- 1 file changed, 34 insertions(+), 54 deletions(-) diff --git a/src/material.f90 b/src/material.f90 index e531cae83..95ce78739 100644 --- a/src/material.f90 +++ b/src/material.f90 @@ -328,88 +328,68 @@ subroutine material_parseMicrostructure homogenization integer, dimension(:), allocatable :: & - CounterPhase, & - CounterHomogenization - - real(pReal), dimension(:,:), allocatable :: & - microstructure_fraction !< vol fraction of each constituent in microstrcuture + counterPhase, & + counterHomogenization + real(pReal) :: & + frac integer :: & e, & i, & m, & c, & - microstructure_maxNconstituents + maxNconstituents - homogenization => config_material%get('homogenization') - phases => config_material%get('phase') microstructure => config_material%get('microstructure') - allocate(microstructure_Nconstituents(microstructure%length),source=0) - if(any(discretization_microstructureAt > microstructure%length)) & call IO_error(155,ext_msg='More microstructures requested than found in material.yaml') + allocate(microstructure_Nconstituents(microstructure%length),source=0) do m = 1, microstructure%length constituentsInMicrostructure => microstructure%get(m) constituents => constituentsInMicrostructure%get('constituents') microstructure_Nconstituents(m) = constituents%length enddo - - microstructure_maxNconstituents = maxval(microstructure_Nconstituents) - allocate(microstructure_fraction(microstructure_maxNconstituents,microstructure%length), source =0.0_pReal) - allocate(material_orientation0(microstructure_maxNconstituents,discretization_nIP,discretization_nElem)) - + maxNconstituents = maxval(microstructure_Nconstituents) + + allocate(material_orientation0(maxNconstituents,discretization_nIP,discretization_nElem)) allocate(material_homogenizationAt(discretization_nElem),source=0) allocate(material_homogenizationMemberAt(discretization_nIP,discretization_nElem),source=0) - allocate(material_phaseAt(microstructure_maxNconstituents,discretization_nElem),source=0) - allocate(material_phaseMemberAt(microstructure_maxNconstituents,discretization_nIP,discretization_nElem),source=0) + allocate(material_phaseAt(maxNconstituents,discretization_nElem),source=0) + allocate(material_phaseMemberAt(maxNconstituents,discretization_nIP,discretization_nElem),source=0) - allocate(CounterPhase(phases%length),source=0) - allocate(CounterHomogenization(homogenization%length),source=0) - - do m = 1, microstructure%length - constituentsInMicrostructure => microstructure%get(m) - constituents => constituentsInMicrostructure%get('constituents') - do c = 1, constituents%length - constituent => constituents%get(c) - microstructure_fraction(c,m) = constituent%get_asFloat('fraction') - enddo - if (dNeq(sum(microstructure_fraction(:,m)),1.0_pReal)) call IO_error(153,ext_msg='constituent') - enddo - - do e = 1, discretization_nElem - constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) - constituents => constituentsInMicrostructure%get('constituents') - do i = 1, discretization_nIP - do c = 1, constituents%length - constituent => constituents%get(c) - material_phaseAt(c,e) = phases%getIndex(constituent%get_asString('phase')) - call material_orientation0(c,i,e)%fromQuaternion(constituent%get_asFloats('orientation',requiredSize=4)) - enddo - enddo - enddo + phases => config_material%get('phase') + allocate(counterPhase(phases%length),source=0) + homogenization => config_material%get('homogenization') + allocate(counterHomogenization(homogenization%length),source=0) do e = 1, discretization_nElem constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) + constituents => constituentsInMicrostructure%get('constituents') + material_homogenizationAt(e) = homogenization%getIndex(constituentsInMicrostructure%get_asString('homogenization')) do i = 1, discretization_nIP - CounterHomogenization(material_homogenizationAt(e)) = CounterHomogenization(material_homogenizationAt(e)) + 1 - material_homogenizationMemberAt(i,e) = CounterHomogenization(material_homogenizationAt(e)) + counterHomogenization(material_homogenizationAt(e)) = counterHomogenization(material_homogenizationAt(e)) + 1 + material_homogenizationMemberAt(i,e) = counterHomogenization(material_homogenizationAt(e)) enddo - enddo - - do e = 1, discretization_nElem - constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) - constituents => constituentsInMicrostructure%get('constituents') - do i = 1, discretization_nIP - do c = 1, constituents%length - CounterPhase(material_phaseAt(c,e)) = & - CounterPhase(material_phaseAt(c,e)) + 1 - material_phaseMemberAt(c,i,e) = CounterPhase(material_phaseAt(c,e)) + frac = 0.0_pReal + do c = 1, constituents%length + constituent => constituents%get(c) + frac = frac + constituent%get_asFloat('fraction') + + material_phaseAt(c,e) = phases%getIndex(constituent%get_asString('phase')) + + do i = 1, discretization_nIP + counterPhase(material_phaseAt(c,e)) = counterPhase(material_phaseAt(c,e)) + 1 + material_phaseMemberAt(c,i,e) = counterPhase(material_phaseAt(c,e)) + + call material_orientation0(c,i,e)%fromQuaternion(constituent%get_asFloats('orientation',requiredSize=4)) enddo + enddo - + if (dNeq(frac,1.0_pReal)) call IO_error(153,ext_msg='constituent') + enddo end subroutine material_parseMicrostructure From c34bf83e35aeb64a852556e8b25a83839fe2ffc8 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 10:27:15 +0200 Subject: [PATCH 24/61] variable names better reflect their content --- src/material.f90 | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/src/material.f90 b/src/material.f90 index 95ce78739..f8e487b66 100644 --- a/src/material.f90 +++ b/src/material.f90 @@ -227,6 +227,7 @@ end subroutine material_init !-------------------------------------------------------------------------------------------------- !> @brief parses the homogenization part from the material configuration +! ToDo: This should be done in homogenization !-------------------------------------------------------------------------------------------------- subroutine material_parseHomogenization @@ -320,10 +321,10 @@ end subroutine material_parseHomogenization !-------------------------------------------------------------------------------------------------- subroutine material_parseMicrostructure - class(tNode), pointer :: microstructure, & !> pointer to microstructure list - constituentsInMicrostructure, & !> pointer to a microstructure list item - constituents, & !> pointer to constituents list - constituent, & !> pointer to each constituent + class(tNode), pointer :: microstructures, & !> list of microstructures + microstructure, & !> microstructure definition + constituents, & !> list of constituents + constituent, & !> constituent definition phases, & homogenization @@ -340,34 +341,35 @@ subroutine material_parseMicrostructure c, & maxNconstituents - microstructure => config_material%get('microstructure') - if(any(discretization_microstructureAt > microstructure%length)) & + microstructures => config_material%get('microstructure') + if(any(discretization_microstructureAt > microstructures%length)) & call IO_error(155,ext_msg='More microstructures requested than found in material.yaml') - allocate(microstructure_Nconstituents(microstructure%length),source=0) - do m = 1, microstructure%length - constituentsInMicrostructure => microstructure%get(m) - constituents => constituentsInMicrostructure%get('constituents') + allocate(microstructure_Nconstituents(microstructures%length),source=0) + do m = 1, microstructures%length + microstructure => microstructures%get(m) + constituents => microstructure%get('constituents') microstructure_Nconstituents(m) = constituents%length enddo maxNconstituents = maxval(microstructure_Nconstituents) - allocate(material_orientation0(maxNconstituents,discretization_nIP,discretization_nElem)) allocate(material_homogenizationAt(discretization_nElem),source=0) allocate(material_homogenizationMemberAt(discretization_nIP,discretization_nElem),source=0) allocate(material_phaseAt(maxNconstituents,discretization_nElem),source=0) allocate(material_phaseMemberAt(maxNconstituents,discretization_nIP,discretization_nElem),source=0) + allocate(material_orientation0(maxNconstituents,discretization_nIP,discretization_nElem)) + phases => config_material%get('phase') allocate(counterPhase(phases%length),source=0) homogenization => config_material%get('homogenization') allocate(counterHomogenization(homogenization%length),source=0) do e = 1, discretization_nElem - constituentsInMicrostructure => microstructure%get(discretization_microstructureAt(e)) - constituents => constituentsInMicrostructure%get('constituents') + microstructure => microstructures%get(discretization_microstructureAt(e)) + constituents => microstructure%get('constituents') - material_homogenizationAt(e) = homogenization%getIndex(constituentsInMicrostructure%get_asString('homogenization')) + material_homogenizationAt(e) = homogenization%getIndex(microstructure%get_asString('homogenization')) do i = 1, discretization_nIP counterHomogenization(material_homogenizationAt(e)) = counterHomogenization(material_homogenizationAt(e)) + 1 material_homogenizationMemberAt(i,e) = counterHomogenization(material_homogenizationAt(e)) @@ -379,7 +381,6 @@ subroutine material_parseMicrostructure frac = frac + constituent%get_asFloat('fraction') material_phaseAt(c,e) = phases%getIndex(constituent%get_asString('phase')) - do i = 1, discretization_nIP counterPhase(material_phaseAt(c,e)) = counterPhase(material_phaseAt(c,e)) + 1 material_phaseMemberAt(c,i,e) = counterPhase(material_phaseAt(c,e)) From 1d2e9324f183913fd8af92d59b3c5e49ef9cd9c0 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 10:50:32 +0200 Subject: [PATCH 25/61] do not rely on 6=STDOUT, 0=STDERR --- src/DAMASK_interface.f90 | 2 +- src/DAMASK_marc.f90 | 2 +- src/IO.f90 | 57 ++++++++++++++++++++++------------------ src/parallelization.f90 | 22 +++++++--------- src/prec.f90 | 2 +- 5 files changed, 44 insertions(+), 41 deletions(-) diff --git a/src/DAMASK_interface.f90 b/src/DAMASK_interface.f90 index 4c3258556..05702a54d 100644 --- a/src/DAMASK_interface.f90 +++ b/src/DAMASK_interface.f90 @@ -14,7 +14,7 @@ #define PETSC_MINOR_MAX 13 module DAMASK_interface - use, intrinsic :: iso_fortran_env + use, intrinsic :: ISO_fortran_env use PETScSys diff --git a/src/DAMASK_marc.f90 b/src/DAMASK_marc.f90 index b6f9436ff..ea7430c6b 100644 --- a/src/DAMASK_marc.f90 +++ b/src/DAMASK_marc.f90 @@ -30,7 +30,7 @@ module DAMASK_interface use prec #if __INTEL_COMPILER >= 1800 - use, intrinsic :: iso_fortran_env, only: & + use, intrinsic :: ISO_fortran_env, only: & compiler_version, & compiler_options #endif diff --git a/src/IO.f90 b/src/IO.f90 index 6da7a10c8..9137372d3 100644 --- a/src/IO.f90 +++ b/src/IO.f90 @@ -6,6 +6,10 @@ !> @brief input/output functions !-------------------------------------------------------------------------------------------------- module IO + use, intrinsic :: ISO_fortran_env, only: & + OUTPUT_UNIT, & + ERROR_UNIT + use prec implicit none @@ -37,7 +41,8 @@ module IO IO_stringAsFloat, & IO_stringAsBool, & IO_error, & - IO_warning + IO_warning, & + OUTPUT_UNIT contains @@ -538,29 +543,29 @@ subroutine IO_error(error_ID,el,ip,g,instance,ext_msg) end select !$OMP CRITICAL (write2out) - write(0,'(/,a)') ' ┌'//IO_DIVIDER//'┐' - write(0,'(a,24x,a,40x,a)') ' │','error', '│' - write(0,'(a,24x,i3,42x,a)') ' │',error_ID, '│' - write(0,'(a)') ' ├'//IO_DIVIDER//'┤' + write(ERROR_UNIT,'(/,a)') ' ┌'//IO_DIVIDER//'┐' + write(ERROR_UNIT,'(a,24x,a,40x,a)') ' │','error', '│' + write(ERROR_UNIT,'(a,24x,i3,42x,a)') ' │',error_ID, '│' + write(ERROR_UNIT,'(a)') ' ├'//IO_DIVIDER//'┤' write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(msg)),',',& max(1,72-len_trim(msg)-4),'x,a)' - write(0,formatString) '│ ',trim(msg), '│' + write(ERROR_UNIT,formatString) '│ ',trim(msg), '│' if (present(ext_msg)) then write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(ext_msg)),',',& max(1,72-len_trim(ext_msg)-4),'x,a)' - write(0,formatString) '│ ',trim(ext_msg), '│' + write(ERROR_UNIT,formatString) '│ ',trim(ext_msg), '│' endif if (present(el)) & - write(0,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' + write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' if (present(ip)) & - write(0,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' + write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' if (present(g)) & - write(0,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' + write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' if (present(instance)) & - write(0,'(a19,1x,i9,44x,a3)') ' │ at instance ',instance, '│' - write(0,'(a,69x,a)') ' │', '│' - write(0,'(a)') ' └'//IO_DIVIDER//'┘' - flush(0) + write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at instance ',instance, '│' + write(ERROR_UNIT,'(a,69x,a)') ' │', '│' + write(ERROR_UNIT,'(a)') ' └'//IO_DIVIDER//'┘' + flush(ERROR_UNIT) call quit(9000+error_ID) !$OMP END CRITICAL (write2out) @@ -623,27 +628,27 @@ subroutine IO_warning(warning_ID,el,ip,g,ext_msg) end select !$OMP CRITICAL (write2out) - write(6,'(/,a)') ' ┌'//IO_DIVIDER//'┐' - write(6,'(a,24x,a,38x,a)') ' │','warning', '│' - write(6,'(a,24x,i3,42x,a)') ' │',warning_ID, '│' - write(6,'(a)') ' ├'//IO_DIVIDER//'┤' + write(ERROR_UNIT,'(/,a)') ' ┌'//IO_DIVIDER//'┐' + write(ERROR_UNIT,'(a,24x,a,38x,a)') ' │','warning', '│' + write(ERROR_UNIT,'(a,24x,i3,42x,a)') ' │',warning_ID, '│' + write(ERROR_UNIT,'(a)') ' ├'//IO_DIVIDER//'┤' write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(msg)),',',& max(1,72-len_trim(msg)-4),'x,a)' - write(6,formatString) '│ ',trim(msg), '│' + write(ERROR_UNIT,formatString) '│ ',trim(msg), '│' if (present(ext_msg)) then write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(ext_msg)),',',& max(1,72-len_trim(ext_msg)-4),'x,a)' - write(6,formatString) '│ ',trim(ext_msg), '│' + write(ERROR_UNIT,formatString) '│ ',trim(ext_msg), '│' endif if (present(el)) & - write(6,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' + write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' if (present(ip)) & - write(6,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' + write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' if (present(g)) & - write(6,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' - write(6,'(a,69x,a)') ' │', '│' - write(6,'(a)') ' └'//IO_DIVIDER//'┘' - flush(6) + write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' + write(ERROR_UNIT,'(a,69x,a)') ' │', '│' + write(ERROR_UNIT,'(a)') ' └'//IO_DIVIDER//'┘' + flush(ERROR_UNIT) !$OMP END CRITICAL (write2out) end subroutine IO_warning diff --git a/src/parallelization.f90 b/src/parallelization.f90 index 341b620c9..3bb1f6af5 100644 --- a/src/parallelization.f90 +++ b/src/parallelization.f90 @@ -3,8 +3,8 @@ !> @brief Inquires variables related to parallelization (openMP, MPI) !-------------------------------------------------------------------------------------------------- module parallelization - use prec - use, intrinsic :: iso_fortran_env + use, intrinsic :: ISO_fortran_env, only: & + OUTPUT_UNIT #ifdef PETSc #include @@ -12,6 +12,8 @@ module parallelization #endif !$ use OMP_LIB + use prec + implicit none private @@ -29,14 +31,14 @@ contains !-------------------------------------------------------------------------------------------------- subroutine parallelization_init - integer :: err, typeSize + integer :: err, typeSize !$ integer :: got_env, DAMASK_NUM_THREADS, threadLevel !$ character(len=6) NumThreadsString #ifdef PETSc PetscErrorCode :: petsc_err #else - print'(/,a)', ' <<<+- parallelization init -+>>>'; flush(6) + print'(/,a)', ' <<<+- parallelization init -+>>>'; flush(OUTPUT_UNIT) #endif #ifdef PETSc @@ -69,14 +71,10 @@ subroutine parallelization_init if (typeSize*8 /= storage_size(0.0_pReal)) error stop 'Mismatch between MPI and DAMASK real' #endif - mainProcess: if (worldrank == 0) then - if (output_unit /= 6) error stop 'STDOUT != 6' - if (error_unit /= 0) error stop 'STDERR != 0' - else mainProcess - close(6) ! disable output for non-master processes (open 6 to rank specific file for debug) - open(6,file='/dev/null',status='replace') ! close(6) alone will leave some temp files in cwd - endif mainProcess - + if (worldrank /= 0) then + close(OUTPUT_UNIT) ! disable output + open(OUTPUT_UNIT,file='/dev/null',status='replace') ! close() alone will leave some temp files in cwd + endif !$ call get_environment_variable(name='DAMASK_NUM_THREADS',value=NumThreadsString,STATUS=got_env) !$ if(got_env /= 0) then diff --git a/src/prec.f90 b/src/prec.f90 index c8700089b..cec4928ba 100644 --- a/src/prec.f90 +++ b/src/prec.f90 @@ -8,7 +8,7 @@ !-------------------------------------------------------------------------------------------------- module prec use, intrinsic :: IEEE_arithmetic - use, intrinsic :: ISO_C_Binding + use, intrinsic :: ISO_C_binding implicit none public From 139eecec0ae6c6b0d72fb0f7b941fdd49f456ef1 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 10:56:41 +0200 Subject: [PATCH 26/61] polishing --- src/DAMASK_interface.f90 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/DAMASK_interface.f90 b/src/DAMASK_interface.f90 index 05702a54d..d34034d0d 100644 --- a/src/DAMASK_interface.f90 +++ b/src/DAMASK_interface.f90 @@ -82,7 +82,7 @@ subroutine DAMASK_interface_init print'(/,a)', ' <<<+- DAMASK_interface init -+>>>' - open(6, encoding='UTF-8') ! for special characters in output + open(OUTPUT_unit, encoding='UTF-8') ! for special characters in output ! http://patorjk.com/software/taag/#p=display&f=Lean&t=DAMASK%203 #ifdef DEBUG @@ -373,7 +373,7 @@ function makeRelativePath(a,b) a_cleaned = rectifyPath(trim(a)//'/') b_cleaned = rectifyPath(b) - do i = 1, min(1024,len_trim(a_cleaned),len_trim(rectifyPath(b_cleaned))) + do i = 1, min(len_trim(a_cleaned),len_trim(rectifyPath(b_cleaned))) if (a_cleaned(i:i) /= b_cleaned(i:i)) exit if (a_cleaned(i:i) == '/') posLastCommonSlash = i enddo @@ -395,7 +395,7 @@ subroutine catchSIGTERM(signal) bind(C) integer(C_INT), value :: signal interface_SIGTERM = .true. - print'(a,i2.2,a)', ' received signal ',signal, ', set SIGTERM=TRUE' + print'(a,i0,a)', ' received signal ',signal, ', set SIGTERM=TRUE' end subroutine catchSIGTERM @@ -420,7 +420,7 @@ subroutine catchSIGUSR1(signal) bind(C) integer(C_INT), value :: signal interface_SIGUSR1 = .true. - print'(a,i2.2,a)', ' received signal ',signal, ', set SIGUSR1=TRUE' + print'(a,i0,a)', ' received signal ',signal, ', set SIGUSR1=TRUE' end subroutine catchSIGUSR1 @@ -445,7 +445,7 @@ subroutine catchSIGUSR2(signal) bind(C) integer(C_INT), value :: signal interface_SIGUSR2 = .true. - print'(a,i2.2,a)', ' received signal ',signal, ', set SIGUSR2=TRUE' + print'(a,i0,a)', ' received signal ',signal, ', set SIGUSR2=TRUE' end subroutine catchSIGUSR2 From d0b5905544ded27703bd7f58fe4d4b726b38a993 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 11:01:43 +0200 Subject: [PATCH 27/61] remaining write(6,...) without advance='no' --- src/constitutive_plastic_nonlocal.f90 | 24 ++++++++++++------------ src/grid/DAMASK_grid.f90 | 5 ++--- src/grid/spectral_utilities.f90 | 2 +- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/constitutive_plastic_nonlocal.f90 b/src/constitutive_plastic_nonlocal.f90 index 9eef17719..81e1887c6 100644 --- a/src/constitutive_plastic_nonlocal.f90 +++ b/src/constitutive_plastic_nonlocal.f90 @@ -741,10 +741,10 @@ module subroutine plastic_nonlocal_dependentState(F, Fp, instance, of, ip, el) if (debugConstitutive%extensive & .and. ((debugConstitutive%element == el .and. debugConstitutive%ip == ip)& .or. .not. debugConstitutive%selective)) then - write(6,'(/,a,i8,1x,i2,1x,i1,/)') '<< CONST >> nonlocal_microstructure at el ip ',el,ip - write(6,'(a,/,12x,12(e10.3,1x))') '<< CONST >> rhoForest', stt%rho_forest(:,of) - write(6,'(a,/,12x,12(f10.5,1x))') '<< CONST >> tauThreshold / MPa', dst%tau_pass(:,of)*1e-6 - write(6,'(a,/,12x,12(f10.5,1x),/)') '<< CONST >> tauBack / MPa', dst%tau_back(:,of)*1e-6 + print'(/,a,i8,1x,i2,1x,i1,/)', '<< CONST >> nonlocal_microstructure at el ip ',el,ip + print'(a,/,12x,12(e10.3,1x))', '<< CONST >> rhoForest', stt%rho_forest(:,of) + print'(a,/,12x,12(f10.5,1x))', '<< CONST >> tauThreshold / MPa', dst%tau_pass(:,of)*1e-6 + print'(a,/,12x,12(f10.5,1x),/)', '<< CONST >> tauBack / MPa', dst%tau_back(:,of)*1e-6 endif #endif @@ -958,8 +958,8 @@ module subroutine plastic_nonlocal_deltaState(Mp,instance,of,ip,el) if (debugConstitutive%extensive & .and. ((debugConstitutive%element == el .and. debugConstitutive%ip == ip)& .or. .not. debugConstitutive%selective)) then - write(6,'(a,/,8(12x,12(e12.5,1x),/))') '<< CONST >> dislocation remobilization', deltaRhoRemobilization(:,1:8) - write(6,'(a,/,10(12x,12(e12.5,1x),/),/)') '<< CONST >> dipole dissociation by stress increase', deltaRhoDipole2SingleStress + print'(a,/,8(12x,12(e12.5,1x),/))', '<< CONST >> dislocation remobilization', deltaRhoRemobilization(:,1:8) + print'(a,/,10(12x,12(e12.5,1x),/),/)', '<< CONST >> dipole dissociation by stress increase', deltaRhoDipole2SingleStress endif #endif @@ -1047,8 +1047,8 @@ module subroutine plastic_nonlocal_dotState(Mp, F, Fp, Temperature,timestep, & if (debugConstitutive%basic & .and. ((debugConstitutive%element == el .and. debugConstitutive%ip == ip) & .or. .not. debugConstitutive%selective)) then - write(6,'(a,/,10(12x,12(e12.5,1x),/))') '<< CONST >> rho / 1/m^2', rhoSgl, rhoDip - write(6,'(a,/,4(12x,12(e12.5,1x),/))') '<< CONST >> gdot / 1/s',gdot + print'(a,/,10(12x,12(e12.5,1x),/))', '<< CONST >> rho / 1/m^2', rhoSgl, rhoDip + print'(a,/,4(12x,12(e12.5,1x),/))', '<< CONST >> gdot / 1/s',gdot endif #endif @@ -1156,8 +1156,8 @@ module subroutine plastic_nonlocal_dotState(Mp, F, Fp, Temperature,timestep, & .or. any(rho(:,dip) + rhoDot(:,9:10) * timestep < -prm%atol_rho)) then #ifdef DEBUG if (debugConstitutive%extensive) then - write(6,'(a,i5,a,i2)') '<< CONST >> evolution rate leads to negative density at el ',el,' ip ',ip - write(6,'(a)') '<< CONST >> enforcing cutback !!!' + print'(a,i5,a,i2)', '<< CONST >> evolution rate leads to negative density at el ',el,' ip ',ip + print'(a)', '<< CONST >> enforcing cutback !!!' endif #endif plasticState(ph)%dotState = IEEE_value(1.0_pReal,IEEE_quiet_NaN) @@ -1268,8 +1268,8 @@ function rhoDotFlux(F,Fp,timestep, instance,of,ip,el) > IPvolume(ip,el) / maxval(IParea(:,ip,el)))) then ! ...with velocity above critical value (we use the reference volume and area for simplicity here) #ifdef DEBUG if (debugConstitutive%extensive) then - write(6,'(a,i5,a,i2)') '<< CONST >> CFL condition not fullfilled at el ',el,' ip ',ip - write(6,'(a,e10.3,a,e10.3)') '<< CONST >> velocity is at ', & + print'(a,i5,a,i2)', '<< CONST >> CFL condition not fullfilled at el ',el,' ip ',ip + print'(a,e10.3,a,e10.3)', '<< CONST >> velocity is at ', & maxval(abs(v0), abs(gdot) > 0.0_pReal & .and. prm%CFLfactor * abs(v0) * timestep & > IPvolume(ip,el) / maxval(IParea(:,ip,el))), & diff --git a/src/grid/DAMASK_grid.f90 b/src/grid/DAMASK_grid.f90 index 341210afc..213322278 100644 --- a/src/grid/DAMASK_grid.f90 +++ b/src/grid/DAMASK_grid.f90 @@ -341,8 +341,7 @@ program DAMASK_grid writeHeader: if (interface_restartInc < 1) then open(newunit=statUnit,file=trim(getSolverJobName())//'.sta',form='FORMATTED',status='REPLACE') write(statUnit,'(a)') 'Increment Time CutbackLevel Converged IterationsNeeded' ! statistics file - if (debug_grid%contains('basic')) & - write(6,'(/,a)') ' header of statistics file written out' + if (debug_grid%contains('basic')) print'(/,a)', ' header of statistics file written out' flush(6) else writeHeader open(newunit=statUnit,file=trim(getSolverJobName())//& @@ -351,7 +350,7 @@ program DAMASK_grid endif writeUndeformed: if (interface_restartInc < 1) then - write(6,'(1/,a)') ' ... writing initial configuration to file ........................' + print'(/,a)', ' ... writing initial configuration to file ........................' call CPFEM_results(0,0.0_pReal) endif writeUndeformed diff --git a/src/grid/spectral_utilities.f90 b/src/grid/spectral_utilities.f90 index 764e8adb6..5e53fe2a5 100644 --- a/src/grid/spectral_utilities.f90 +++ b/src/grid/spectral_utilities.f90 @@ -700,7 +700,7 @@ function utilities_maskedCompliance(rot_BC,mask_stress,C) temp99_real = math_3333to99(rot_BC%rotate(C)) if(debugGeneral) then - write(6,'(/,a)') ' ... updating masked compliance ............................................' + print'(/,a)', ' ... updating masked compliance ............................................' write(6,'(/,a,/,9(9(2x,f12.7,1x)/))',advance='no') ' Stiffness C (load) / GPa =',& transpose(temp99_Real)*1.0e-9_pReal flush(6) From ea426ba47ac160951dffa0206bcac2385b6f8f86 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 11:25:53 +0200 Subject: [PATCH 28/61] fixed test --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index df9a16a89..423e1389b 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit df9a16a89c069a3d1076447fce90d759c45248a3 +Subproject commit 423e1389bdacd72de123049a2cada0ccbbe2fa6f From c108b4df66695824382d6c7d94b1614bc6a26f8f Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 11:41:16 +0200 Subject: [PATCH 29/61] concise description --- src/marc/discretization_marc.f90 | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/marc/discretization_marc.f90 b/src/marc/discretization_marc.f90 index cbfc40995..41f089b52 100644 --- a/src/marc/discretization_marc.f90 +++ b/src/marc/discretization_marc.f90 @@ -1030,10 +1030,9 @@ pure function IPareaNormal(elem,nElem,connectivity,node) IPareaNormal(1:3,f,i,e) = math_cross(nodePos(1:3,2) - nodePos(1:3,1), & nodePos(1:3,3) - nodePos(1:3,1)) case (4) ! 3D 8node - ! for this cell type we get the normal of the quadrilateral face as an average of - ! four normals of triangular subfaces; since the face consists only of two triangles, - ! the sum has to be divided by two; this whole prcedure tries to compensate for - ! probable non-planar cell surfaces + ! Get the normal of the quadrilateral face as the average of four normals of triangular + ! subfaces. Since the face consists only of two triangles, the sum has to be divided + ! by two. This procedure tries to compensate forprobable non-planar cell surfaces IPareaNormal(1:3,f,i,e) = 0.0_pReal do n = 1, m IPareaNormal(1:3,f,i,e) = IPareaNormal(1:3,f,i,e) & From 7cbd422ae38d22b741831663081c66f2c5ae3e06 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Sat, 19 Sep 2020 13:38:32 -0400 Subject: [PATCH 30/61] fixed coprime error when encountering NaN --- python/damask/util.py | 2 +- python/tests/test_util.py | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/python/damask/util.py b/python/damask/util.py index 655f75879..6432ed4e1 100644 --- a/python/damask/util.py +++ b/python/damask/util.py @@ -173,7 +173,7 @@ def scale_to_coprime(v): m = m//reduce(np.gcd,m) with np.errstate(divide='ignore'): - if not np.allclose(v/m,v[0]/m[0]): + if not np.allclose(np.ma.masked_invalid(v/m),v[np.argmax(abs(v))]/m[np.argmax(abs(v))]): raise ValueError(f'Invalid result {m} for input {v}. Insufficient precision?') return m diff --git a/python/tests/test_util.py b/python/tests/test_util.py index c786e0de1..588cc823f 100644 --- a/python/tests/test_util.py +++ b/python/tests/test_util.py @@ -18,16 +18,17 @@ class TestUtil: @pytest.mark.parametrize('input,output', [ - ([2,0],[1,0]), - ([0.5,0.5],[1,1]), + ([0,-2],[0,-1]), + ([-0.5,0.5],[-1,1]), ([1./2.,1./3.],[3,2]), ([2./3.,1./2.,1./3.],[4,3,2]), ]) def test_scale2coprime(self,input,output): + print(util.scale_to_coprime(np.array(input))) assert np.allclose(util.scale_to_coprime(np.array(input)), np.array(output).astype(int)) def test_lackofprecision(self): with pytest.raises(ValueError): - util.scale_to_coprime(np.array([1/3333,1,1])) + util.scale_to_coprime(np.array([1/333.333,1,1])) From 3cc319ef08471ac6a2a6f6dd7f2fb3b34fec92fe Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Sat, 19 Sep 2020 14:30:58 -0400 Subject: [PATCH 31/61] removed debug print statement in test_util --- python/tests/test_util.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/tests/test_util.py b/python/tests/test_util.py index 588cc823f..053045741 100644 --- a/python/tests/test_util.py +++ b/python/tests/test_util.py @@ -25,7 +25,6 @@ class TestUtil: ]) def test_scale2coprime(self,input,output): - print(util.scale_to_coprime(np.array(input))) assert np.allclose(util.scale_to_coprime(np.array(input)), np.array(output).astype(int)) From 3e829eb610b553f9e4f2bda5c8cfeb5a60897f7a Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 22:05:45 +0200 Subject: [PATCH 32/61] improved homogenization test - do actual comparison - avoid line breaks in yaml --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 423e1389b..b743be478 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 423e1389bdacd72de123049a2cada0ccbbe2fa6f +Subproject commit b743be47898365af917ef57686c26a3a750c651b From 42186b9f87f2fd474a581b925ee577455f32ca3b Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 19 Sep 2020 22:08:38 +0200 Subject: [PATCH 33/61] fixed typo --- src/marc/discretization_marc.f90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/marc/discretization_marc.f90 b/src/marc/discretization_marc.f90 index 41f089b52..91aa0106c 100644 --- a/src/marc/discretization_marc.f90 +++ b/src/marc/discretization_marc.f90 @@ -1032,7 +1032,7 @@ pure function IPareaNormal(elem,nElem,connectivity,node) case (4) ! 3D 8node ! Get the normal of the quadrilateral face as the average of four normals of triangular ! subfaces. Since the face consists only of two triangles, the sum has to be divided - ! by two. This procedure tries to compensate forprobable non-planar cell surfaces + ! by two. This procedure tries to compensate for probable non-planar cell surfaces IPareaNormal(1:3,f,i,e) = 0.0_pReal do n = 1, m IPareaNormal(1:3,f,i,e) = IPareaNormal(1:3,f,i,e) & From 5b0b0de6b4018d9678a8a6a8ff38859b9c55d695 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Sun, 20 Sep 2020 12:22:41 -0400 Subject: [PATCH 34/61] assertion reports offense; fixed seeds for spherical and fiber --- python/tests/test_Rotation.py | 99 ++++++++++++++--------------------- 1 file changed, 39 insertions(+), 60 deletions(-) diff --git a/python/tests/test_Rotation.py b/python/tests/test_Rotation.py index 5435895a2..45dfc4f5e 100644 --- a/python/tests/test_Rotation.py +++ b/python/tests/test_Rotation.py @@ -461,7 +461,7 @@ def mul(me, other): if other.shape == (3,): A = me.quaternion[0]**2.0 - np.dot(me.quaternion[1:],me.quaternion[1:]) B = 2.0 * np.dot(me.quaternion[1:],other) - C = 2.0 * _P*me.quaternion[0] + C = 2.0 * _P * me.quaternion[0] return A*other + B*me.quaternion[1:] + C * np.cross(me.quaternion[1:],other) @@ -496,9 +496,8 @@ class TestRotation: o = backward(forward(m)) ok = np.allclose(m,o,atol=atol) if np.isclose(rot.as_quaternion()[0],0.0,atol=atol): - ok = ok or np.allclose(m*-1.,o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.isclose(np.linalg.norm(o),1.0) + ok |= np.allclose(m*-1.,o,atol=atol) + assert ok and np.isclose(np.linalg.norm(o),1.0), f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('forward,backward',[(Rotation._om2qu,Rotation._qu2om), (Rotation._om2eu,Rotation._eu2om), @@ -512,8 +511,7 @@ class TestRotation: m = rot.as_matrix() o = backward(forward(m)) ok = np.allclose(m,o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.isclose(np.linalg.det(o),1.0) + assert ok and np.isclose(np.linalg.det(o),1.0), f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('forward,backward',[(Rotation._eu2qu,Rotation._qu2eu), (Rotation._eu2om,Rotation._om2eu), @@ -531,9 +529,9 @@ class TestRotation: ok = ok or np.allclose(np.where(np.isclose(m,u),m-u,m),np.where(np.isclose(o,u),o-u,o),atol=atol) if np.isclose(m[1],0.0,atol=atol) or np.isclose(m[1],np.pi,atol=atol): sum_phi = np.unwrap([m[0]+m[2],o[0]+o[2]]) - ok = ok or np.isclose(sum_phi[0],sum_phi[1],atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and (np.zeros(3)-1.e-9 <= o).all() and (o <= np.array([np.pi*2.,np.pi,np.pi*2.])+1.e-9).all() + ok |= np.isclose(sum_phi[0],sum_phi[1],atol=atol) + assert ok and (np.zeros(3)-1.e-9 <= o).all() \ + and (o <= np.array([np.pi*2.,np.pi,np.pi*2.])+1.e-9).all(), f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('forward,backward',[(Rotation._ax2qu,Rotation._qu2ax), (Rotation._ax2om,Rotation._om2ax), @@ -548,9 +546,8 @@ class TestRotation: o = backward(forward(m)) ok = np.allclose(m,o,atol=atol) if np.isclose(m[3],np.pi,atol=atol): - ok = ok or np.allclose(m*np.array([-1.,-1.,-1.,1.]),o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.isclose(np.linalg.norm(o[:3]),1.0) and o[3]<=np.pi+1.e-9 + ok |= np.allclose(m*np.array([-1.,-1.,-1.,1.]),o,atol=atol) + assert ok and np.isclose(np.linalg.norm(o[:3]),1.0) and o[3]<=np.pi+1.e-9, f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('forward,backward',[(Rotation._ro2qu,Rotation._qu2ro), #(Rotation._ro2om,Rotation._om2ro), @@ -566,8 +563,7 @@ class TestRotation: o = backward(forward(m)) ok = np.allclose(np.clip(m,None,cutoff),np.clip(o,None,cutoff),atol=atol) ok = ok or np.isclose(m[3],0.0,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.isclose(np.linalg.norm(o[:3]),1.0) + assert ok and np.isclose(np.linalg.norm(o[:3]),1.0), f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('forward,backward',[(Rotation._ho2qu,Rotation._qu2ho), (Rotation._ho2om,Rotation._om2ho), @@ -581,8 +577,7 @@ class TestRotation: m = rot.as_homochoric() o = backward(forward(m)) ok = np.allclose(m,o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.linalg.norm(o) < _R1 + 1.e-9 + assert ok and np.linalg.norm(o) < _R1 + 1.e-9, f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('forward,backward',[(Rotation._cu2qu,Rotation._qu2cu), (Rotation._cu2om,Rotation._om2cu), @@ -598,8 +593,7 @@ class TestRotation: ok = np.allclose(m,o,atol=atol) if np.count_nonzero(np.isclose(np.abs(o),np.pi**(2./3.)*.5)): ok = ok or np.allclose(m*-1.,o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.max(np.abs(o)) < np.pi**(2./3.) * 0.5 + 1.e-9 + assert ok and np.max(np.abs(o)) < np.pi**(2./3.) * 0.5 + 1.e-9, f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('vectorized, single',[(Rotation._qu2om,qu2om), (Rotation._qu2eu,qu2eu), @@ -612,8 +606,7 @@ class TestRotation: vectorized(qu.reshape(qu.shape[0]//2,-1,4)) co = vectorized(qu) for q,c in zip(qu,co): - print(q,c) - assert np.allclose(single(q),c) and np.allclose(single(q),vectorized(q)) + assert np.allclose(single(q),c) and np.allclose(single(q),vectorized(q)), f'{q},{c}' @pytest.mark.parametrize('vectorized, single',[(Rotation._om2qu,om2qu), @@ -625,8 +618,7 @@ class TestRotation: vectorized(om.reshape(om.shape[0]//2,-1,3,3)) co = vectorized(om) for o,c in zip(om,co): - print(o,c) - assert np.allclose(single(o),c) and np.allclose(single(o),vectorized(o)) + assert np.allclose(single(o),c) and np.allclose(single(o),vectorized(o)), f'{o},{c}' @pytest.mark.parametrize('vectorized, single',[(Rotation._eu2qu,eu2qu), (Rotation._eu2om,eu2om), @@ -638,8 +630,7 @@ class TestRotation: vectorized(eu.reshape(eu.shape[0]//2,-1,3)) co = vectorized(eu) for e,c in zip(eu,co): - print(e,c) - assert np.allclose(single(e),c) and np.allclose(single(e),vectorized(e)) + assert np.allclose(single(e),c) and np.allclose(single(e),vectorized(e)), f'{e},{c}' @pytest.mark.parametrize('vectorized, single',[(Rotation._ax2qu,ax2qu), (Rotation._ax2om,ax2om), @@ -651,8 +642,7 @@ class TestRotation: vectorized(ax.reshape(ax.shape[0]//2,-1,4)) co = vectorized(ax) for a,c in zip(ax,co): - print(a,c) - assert np.allclose(single(a),c) and np.allclose(single(a),vectorized(a)) + assert np.allclose(single(a),c) and np.allclose(single(a),vectorized(a)), f'{a},{c}' @pytest.mark.parametrize('vectorized, single',[(Rotation._ro2ax,ro2ax), @@ -663,8 +653,7 @@ class TestRotation: vectorized(ro.reshape(ro.shape[0]//2,-1,4)) co = vectorized(ro) for r,c in zip(ro,co): - print(r,c) - assert np.allclose(single(r),c) and np.allclose(single(r),vectorized(r)) + assert np.allclose(single(r),c) and np.allclose(single(r),vectorized(r)), f'{r},{c}' @pytest.mark.parametrize('vectorized, single',[(Rotation._ho2ax,ho2ax), (Rotation._ho2cu,ho2cu)]) @@ -674,8 +663,7 @@ class TestRotation: vectorized(ho.reshape(ho.shape[0]//2,-1,3)) co = vectorized(ho) for h,c in zip(ho,co): - print(h,c) - assert np.allclose(single(h),c) and np.allclose(single(h),vectorized(h)) + assert np.allclose(single(h),c) and np.allclose(single(h),vectorized(h)), f'{h},{c}' @pytest.mark.parametrize('vectorized, single',[(Rotation._cu2ho,cu2ho)]) def test_cubochoric_vectorization(self,set_of_rotations,vectorized,single): @@ -684,8 +672,7 @@ class TestRotation: vectorized(cu.reshape(cu.shape[0]//2,-1,3)) co = vectorized(cu) for u,c in zip(cu,co): - print(u,c) - assert np.allclose(single(u),c) and np.allclose(single(u),vectorized(u)) + assert np.allclose(single(u),c) and np.allclose(single(u),vectorized(u)), f'{u},{c}' @pytest.mark.parametrize('func',[Rotation.from_axis_angle]) def test_normalization_vectorization(self,func): @@ -703,9 +690,8 @@ class TestRotation: o = Rotation.from_Eulers(rot.as_Eulers(degrees),degrees).as_quaternion() ok = np.allclose(m,o,atol=atol) if np.isclose(rot.as_quaternion()[0],0.0,atol=atol): - ok = ok or np.allclose(m*-1.,o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.isclose(np.linalg.norm(o),1.0) + ok |= np.allclose(m*-1.,o,atol=atol) + assert ok and np.isclose(np.linalg.norm(o),1.0), f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('P',[1,-1]) @pytest.mark.parametrize('normalize',[True,False]) @@ -717,12 +703,12 @@ class TestRotation: o = Rotation.from_axis_angle(rot.as_axis_angle(degrees)*c,degrees,normalize,P).as_Eulers() u = np.array([np.pi*2,np.pi,np.pi*2]) ok = np.allclose(m,o,atol=atol) - ok = ok or np.allclose(np.where(np.isclose(m,u),m-u,m),np.where(np.isclose(o,u),o-u,o),atol=atol) + ok |= np.allclose(np.where(np.isclose(m,u),m-u,m),np.where(np.isclose(o,u),o-u,o),atol=atol) if np.isclose(m[1],0.0,atol=atol) or np.isclose(m[1],np.pi,atol=atol): sum_phi = np.unwrap([m[0]+m[2],o[0]+o[2]]) - ok = ok or np.isclose(sum_phi[0],sum_phi[1],atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and (np.zeros(3)-1.e-9 <= o).all() and (o <= np.array([np.pi*2.,np.pi,np.pi*2.])+1.e-9).all() + ok |= np.isclose(sum_phi[0],sum_phi[1],atol=atol) + assert ok and (np.zeros(3)-1.e-9 <= o).all() \ + and (o <= np.array([np.pi*2.,np.pi,np.pi*2.])+1.e-9).all(), f'{m},{o},{rot.as_quaternion()}' def test_matrix(self,set_of_rotations): for rot in set_of_rotations: @@ -731,8 +717,8 @@ class TestRotation: ok = np.allclose(m,o,atol=atol) if np.isclose(m[3],np.pi,atol=atol): ok = ok or np.allclose(m*np.array([-1.,-1.,-1.,1.]),o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.isclose(np.linalg.norm(o[:3]),1.0) and o[3]<=np.pi+1.e-9 + assert ok and np.isclose(np.linalg.norm(o[:3]),1.0) \ + and o[3]<=np.pi+1.e-9, f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('P',[1,-1]) @pytest.mark.parametrize('normalize',[True,False]) @@ -742,8 +728,7 @@ class TestRotation: m = rot.as_matrix() o = Rotation.from_Rodrigues(rot.as_Rodrigues()*c,normalize,P).as_matrix() ok = np.allclose(m,o,atol=atol) - print(m,o) - assert ok and np.isclose(np.linalg.det(o),1.0) + assert ok and np.isclose(np.linalg.det(o),1.0), f'{m},{o}' @pytest.mark.parametrize('P',[1,-1]) def test_homochoric(self,set_of_rotations,P): @@ -753,8 +738,7 @@ class TestRotation: o = Rotation.from_homochoric(rot.as_homochoric()*P*-1,P).as_Rodrigues() ok = np.allclose(np.clip(m,None,cutoff),np.clip(o,None,cutoff),atol=atol) ok = ok or np.isclose(m[3],0.0,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.isclose(np.linalg.norm(o[:3]),1.0) + assert ok and np.isclose(np.linalg.norm(o[:3]),1.0), f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('P',[1,-1]) def test_cubochoric(self,set_of_rotations,P): @@ -762,8 +746,7 @@ class TestRotation: m = rot.as_homochoric() o = Rotation.from_cubochoric(rot.as_cubochoric()*P*-1,P).as_homochoric() ok = np.allclose(m,o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and np.linalg.norm(o) < (3.*np.pi/4.)**(1./3.) + 1.e-9 + assert ok and np.linalg.norm(o) < (3.*np.pi/4.)**(1./3.) + 1.e-9, f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('P',[1,-1]) @pytest.mark.parametrize('accept_homomorph',[True,False]) @@ -774,9 +757,8 @@ class TestRotation: o = Rotation.from_quaternion(rot.as_quaternion()*c,accept_homomorph,P).as_cubochoric() ok = np.allclose(m,o,atol=atol) if np.count_nonzero(np.isclose(np.abs(o),np.pi**(2./3.)*.5)): - ok = ok or np.allclose(m*-1.,o,atol=atol) - print(m,o,rot.as_quaternion()) - assert ok and o.max() < np.pi**(2./3.)*0.5+1.e-9 + ok |= np.allclose(m*-1.,o,atol=atol) + assert ok and o.max() < np.pi**(2./3.)*0.5+1.e-9, f'{m},{o},{rot.as_quaternion()}' @pytest.mark.parametrize('reciprocal',[True,False]) def test_basis(self,set_of_rotations,reciprocal): @@ -858,8 +840,7 @@ class TestRotation: for rot in set_of_rotations: v = rot.broadcast_to((5,)) @ data for i in range(data.shape[0]): - print(i-data[i]) - assert np.allclose(mul(rot,data[i]),v[i]) + assert np.allclose(mul(rot,data[i]),v[i]), f'{i-data[i]}' @pytest.mark.parametrize('data',[np.random.rand(3), @@ -927,33 +908,31 @@ class TestRotation: @pytest.mark.parametrize('N',[1000,10000,100000]) def test_spherical_component(self,N,sigma): c = Rotation.from_random() - o = Rotation.from_spherical_component(c,sigma,N) + o = Rotation.from_spherical_component(c,sigma,N,seed=N+sigma) _, angles = c.misorientation(o).as_axis_angle(pair=True,degrees=True) angles[::2] *= -1 # flip angle for every second to symmetrize distribution p = stats.normaltest(angles)[1] sigma_out = np.std(angles) - print(f'\np: {p}, sigma ratio {sigma/sigma_out}') - assert (.9 < sigma/sigma_out < 1.1) and p > 0.001 + assert (.9 < sigma/sigma_out < 1.1) and p > 1, f'{sigma/sigma_out},{p}' @pytest.mark.parametrize('sigma',[5,10,15,20]) @pytest.mark.parametrize('N',[1000,10000,100000]) def test_from_fiber_component(self,N,sigma): """https://en.wikipedia.org/wiki/Full_width_at_half_maximum.""" - alpha = np.random.random(2)*np.pi - beta = np.random.random(2)*np.pi + alpha = np.random.random()*2*np.pi,np.arccos(np.random.random()) + beta = np.random.random()*2*np.pi,np.arccos(np.random.random()) f_in_C = np.array([np.sin(alpha[0])*np.cos(alpha[1]), np.sin(alpha[0])*np.sin(alpha[1]), np.cos(alpha[0])]) f_in_S = np.array([np.sin(beta[0] )*np.cos(beta[1] ), np.sin(beta[0] )*np.sin(beta[1] ), np.cos(beta[0] )]) ax = np.append(np.cross(f_in_C,f_in_S), - np.arccos(np.dot(f_in_C,f_in_S))) n = Rotation.from_axis_angle(ax if ax[3] > 0.0 else ax*-1.0 ,normalize=True) # rotation to align fiber axis in crystal and sample system - o = Rotation.from_fiber_component(alpha,beta,np.radians(sigma),N,False) + o = Rotation.from_fiber_component(alpha,beta,np.radians(sigma),N,False,seed=N+sigma) angles = np.arccos(np.clip(np.dot(o@np.broadcast_to(f_in_S,(N,3)),n@f_in_S),-1,1)) dist = np.array(angles) * (np.random.randint(0,2,N)*2-1) p = stats.normaltest(dist)[1] sigma_out = np.degrees(np.std(dist)) - print(f'\np: {p}, sigma ratio {sigma/sigma_out}') - assert (.9 < sigma/sigma_out < 1.1) and p > 0.001 + assert (.9 < sigma/sigma_out < 1.1) and p > 0.001, f'{sigma/sigma_out},{p}' From 5895e740290429dca0a7d8d9e54b63af0920d8c9 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sun, 20 Sep 2020 19:13:54 +0200 Subject: [PATCH 35/61] p is never above 1 1e-4 is quite low, usually we are far above. 1e-3 from https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.normaltest.html is not too far away. --- python/tests/test_Rotation.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python/tests/test_Rotation.py b/python/tests/test_Rotation.py index 45dfc4f5e..3785e8da1 100644 --- a/python/tests/test_Rotation.py +++ b/python/tests/test_Rotation.py @@ -908,13 +908,13 @@ class TestRotation: @pytest.mark.parametrize('N',[1000,10000,100000]) def test_spherical_component(self,N,sigma): c = Rotation.from_random() - o = Rotation.from_spherical_component(c,sigma,N,seed=N+sigma) + o = Rotation.from_spherical_component(c,sigma,N) _, angles = c.misorientation(o).as_axis_angle(pair=True,degrees=True) angles[::2] *= -1 # flip angle for every second to symmetrize distribution p = stats.normaltest(angles)[1] sigma_out = np.std(angles) - assert (.9 < sigma/sigma_out < 1.1) and p > 1, f'{sigma/sigma_out},{p}' + assert (.9 < sigma/sigma_out < 1.1) and p > 1e-4, f'{sigma/sigma_out},{p}' @pytest.mark.parametrize('sigma',[5,10,15,20]) @@ -929,10 +929,10 @@ class TestRotation: ax = np.append(np.cross(f_in_C,f_in_S), - np.arccos(np.dot(f_in_C,f_in_S))) n = Rotation.from_axis_angle(ax if ax[3] > 0.0 else ax*-1.0 ,normalize=True) # rotation to align fiber axis in crystal and sample system - o = Rotation.from_fiber_component(alpha,beta,np.radians(sigma),N,False,seed=N+sigma) + o = Rotation.from_fiber_component(alpha,beta,np.radians(sigma),N,False) angles = np.arccos(np.clip(np.dot(o@np.broadcast_to(f_in_S,(N,3)),n@f_in_S),-1,1)) dist = np.array(angles) * (np.random.randint(0,2,N)*2-1) p = stats.normaltest(dist)[1] sigma_out = np.degrees(np.std(dist)) - assert (.9 < sigma/sigma_out < 1.1) and p > 0.001, f'{sigma/sigma_out},{p}' + assert (.9 < sigma/sigma_out < 1.1) and p > 1.e-4, f'{sigma/sigma_out},{p}' From 6ab88aad2b946dfc2f050f0b7f6ba56c14627668 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sun, 20 Sep 2020 20:45:06 +0200 Subject: [PATCH 36/61] default format for Table is ASCII hence, renamed load_ASCII/save_ASCII to load/save --- PRIVATE | 2 +- processing/legacy/addAPS34IDEstrainCoords.py | 4 ++-- processing/legacy/addCumulative.py | 4 ++-- processing/post/DADF5_postResults.py | 2 +- processing/post/addCompatibilityMismatch.py | 4 ++-- processing/post/addCurl.py | 4 ++-- processing/post/addDerivative.py | 4 ++-- processing/post/addDisplacement.py | 6 +++--- processing/post/addDivergence.py | 4 ++-- processing/post/addEuclideanDistance.py | 4 ++-- processing/post/addGaussian.py | 4 ++-- processing/post/addGradient.py | 4 ++-- processing/post/addOrientations.py | 4 ++-- processing/post/addSchmidfactors.py | 4 ++-- processing/post/permuteData.py | 4 ++-- processing/pre/geom_fromDREAM3D.py | 2 +- processing/pre/geom_fromTable.py | 2 +- processing/pre/geom_fromVoronoiTessellation.py | 4 ++-- processing/pre/geom_grainGrowth.py | 2 +- processing/pre/hybridIA_linODFsampling.py | 2 +- processing/pre/seeds_fromDistribution.py | 4 ++-- processing/pre/seeds_fromGeom.py | 2 +- processing/pre/seeds_fromPokes.py | 2 +- processing/pre/seeds_fromRandom.py | 2 +- python/damask/_colormap.py | 4 ++-- python/damask/_table.py | 4 ++-- python/damask/_test.py | 8 ++++---- python/tests/test_Orientation.py | 4 ++-- python/tests/test_Table.py | 18 +++++++++--------- 29 files changed, 59 insertions(+), 59 deletions(-) diff --git a/PRIVATE b/PRIVATE index 576f3af61..7c543a98e 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 576f3af61c3d893b608809cc91e46647809010f1 +Subproject commit 7c543a98e89840f1f1540c7af8c62a19084dab6e diff --git a/processing/legacy/addAPS34IDEstrainCoords.py b/processing/legacy/addAPS34IDEstrainCoords.py index 8f566b614..465f03e4e 100755 --- a/processing/legacy/addAPS34IDEstrainCoords.py +++ b/processing/legacy/addAPS34IDEstrainCoords.py @@ -42,10 +42,10 @@ rot_to_TSL = damask.Rotation.from_axis_angle([-1,0,0,.75*np.pi]) for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) coord = - table.get(options.frame) coord[:,2] += table.get(options.depth)[:,0] table.add('coord',rot_to_TSL.broadcast_to(coord.shape[0]) @ coord,scriptID+' '+' '.join(sys.argv[1:]))\ - .save_ASCII((sys.stdout if name is None else name),legacy=True) + .save((sys.stdout if name is None else name),legacy=True) diff --git a/processing/legacy/addCumulative.py b/processing/legacy/addCumulative.py index 0d88cc575..3ba527acd 100755 --- a/processing/legacy/addCumulative.py +++ b/processing/legacy/addCumulative.py @@ -39,10 +39,10 @@ if options.labels is None: for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) for label in options.labels: table = table.add('cum_{}({})'.format('prod' if options.product else 'sum',label), np.cumprod(table.get(label),0) if options.product else np.cumsum(table.get(label),0), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name),legacy=True) + table.save((sys.stdout if name is None else name),legacy=True) diff --git a/processing/post/DADF5_postResults.py b/processing/post/DADF5_postResults.py index 0226ad551..02eb72d87 100755 --- a/processing/post/DADF5_postResults.py +++ b/processing/post/DADF5_postResults.py @@ -60,4 +60,4 @@ for filename in options.filenames: os.mkdir(dirname,0o755) file_out = '{}_inc{}.txt'.format(os.path.splitext(os.path.split(filename)[-1])[0], inc[3:].zfill(N_digits)) - table.save_ASCII(os.path.join(dirname,file_out),legacy=True) + table.save(os.path.join(dirname,file_out),legacy=True) diff --git a/processing/post/addCompatibilityMismatch.py b/processing/post/addCompatibilityMismatch.py index 40a1391e0..0e7d3ea42 100755 --- a/processing/post/addCompatibilityMismatch.py +++ b/processing/post/addCompatibilityMismatch.py @@ -172,7 +172,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) F = table.get(options.defgrad).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3)) @@ -191,4 +191,4 @@ for name in filenames: volumeMismatch.reshape(-1,1,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addCurl.py b/processing/post/addCurl.py index 5a5f4c074..699fc945f 100755 --- a/processing/post/addCurl.py +++ b/processing/post/addCurl.py @@ -43,7 +43,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) for label in options.labels: @@ -55,4 +55,4 @@ for name in filenames: curl.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape),order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addDerivative.py b/processing/post/addDerivative.py index 63a5bf73e..99016f4ef 100755 --- a/processing/post/addDerivative.py +++ b/processing/post/addDerivative.py @@ -65,10 +65,10 @@ if options.labels is None: for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) for label in options.labels: table = table.add('d({})/d({})'.format(label,options.coordinates), derivative(table.get(options.coordinates),table.get(label)), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addDisplacement.py b/processing/post/addDisplacement.py index 079bcd970..a6cff86ab 100755 --- a/processing/post/addDisplacement.py +++ b/processing/post/addDisplacement.py @@ -47,7 +47,7 @@ parser.set_defaults(f = 'f', for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) F = table.get(options.f).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3)) @@ -60,7 +60,7 @@ for name in filenames: .add('fluct({}).{}'.format(options.f,options.pos), damask.grid_filters.node_displacement_fluct(size,F).reshape(-1,3,order='F'), scriptID+' '+' '.join(sys.argv[1:]))\ - .save_ASCII((sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt'), legacy=True) + .save((sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt'), legacy=True) else: table.add('avg({}).{}'.format(options.f,options.pos), damask.grid_filters.cell_displacement_avg(size,F).reshape(-1,3,order='F'), @@ -68,4 +68,4 @@ for name in filenames: .add('fluct({}).{}'.format(options.f,options.pos), damask.grid_filters.cell_displacement_fluct(size,F).reshape(-1,3,order='F'), scriptID+' '+' '.join(sys.argv[1:]))\ - .save_ASCII((sys.stdout if name is None else name), legacy=True) + .save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addDivergence.py b/processing/post/addDivergence.py index bc4880788..208a0f7b6 100755 --- a/processing/post/addDivergence.py +++ b/processing/post/addDivergence.py @@ -43,7 +43,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) for label in options.labels: @@ -55,4 +55,4 @@ for name in filenames: div.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape)//3,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addEuclideanDistance.py b/processing/post/addEuclideanDistance.py index 7e99dc3d5..fc43542bd 100755 --- a/processing/post/addEuclideanDistance.py +++ b/processing/post/addEuclideanDistance.py @@ -142,7 +142,7 @@ for i,feature in enumerate(features): for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) neighborhood = neighborhoods[options.neighborhood] @@ -184,4 +184,4 @@ for name in filenames: distance[i,:], scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addGaussian.py b/processing/post/addGaussian.py index 095a17bc2..f00122c63 100755 --- a/processing/post/addGaussian.py +++ b/processing/post/addGaussian.py @@ -63,7 +63,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) damask.grid_filters.coord0_check(table.get(options.pos)) for label in options.labels: @@ -73,4 +73,4 @@ for name in filenames: mode = 'wrap' if options.periodic else 'nearest'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addGradient.py b/processing/post/addGradient.py index 69241598c..d049b65d7 100755 --- a/processing/post/addGradient.py +++ b/processing/post/addGradient.py @@ -43,7 +43,7 @@ if options.labels is None: parser.error('no data column specified.') for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) for label in options.labels: @@ -55,4 +55,4 @@ for name in filenames: grad.reshape(tuple(grid)+(-1,)).reshape(-1,np.prod(shape)*3,order='F'), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addOrientations.py b/processing/post/addOrientations.py index 16f8d62d6..6a02cca08 100755 --- a/processing/post/addOrientations.py +++ b/processing/post/addOrientations.py @@ -110,7 +110,7 @@ R = damask.Rotation.from_axis_angle(np.array(options.labrotation),options.degree for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) if options.eulers is not None: label = options.eulers @@ -147,4 +147,4 @@ for name in filenames: if 'axisangle' in options.output: table = table.add('om({})'.format(label),o.as_axisangle(options.degrees), scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/addSchmidfactors.py b/processing/post/addSchmidfactors.py index beaf18331..8f43308cb 100755 --- a/processing/post/addSchmidfactors.py +++ b/processing/post/addSchmidfactors.py @@ -175,7 +175,7 @@ labels = ['S[{direction[0]:.1g}_{direction[1]:.1g}_{direction[2]:.1g}]' for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) o = damask.Rotation.from_quaternion(table.get(options.quaternion)) @@ -189,4 +189,4 @@ for name in filenames: for i,label in enumerate(labels): table = table.add(label,S[:,i],scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/post/permuteData.py b/processing/post/permuteData.py index 34451404c..073ccfd9f 100755 --- a/processing/post/permuteData.py +++ b/processing/post/permuteData.py @@ -47,7 +47,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) randomSeed = int(os.urandom(4).hex(), 16) if options.randomSeed is None else options.randomSeed # random seed per file rng = np.random.default_rng(randomSeed) @@ -58,4 +58,4 @@ for name in filenames: rng.shuffle(uniques) table = table.set(label,uniques[inverse], scriptID+' '+' '.join(sys.argv[1:])) - table.save_ASCII((sys.stdout if name is None else name), legacy=True) + table.save((sys.stdout if name is None else name), legacy=True) diff --git a/processing/pre/geom_fromDREAM3D.py b/processing/pre/geom_fromDREAM3D.py index 471435766..3faa07a17 100755 --- a/processing/pre/geom_fromDREAM3D.py +++ b/processing/pre/geom_fromDREAM3D.py @@ -154,4 +154,4 @@ for name in filenames: homogenization=options.homogenization,comments=header) damask.util.croak(geom) - geom.save_ASCII(os.path.splitext(name)[0]+'.geom',pack=False) + geom.save_ASCII(os.path.splitext(name)[0]+'.geom',compress=False) diff --git a/processing/pre/geom_fromTable.py b/processing/pre/geom_fromTable.py index 11c0761b5..3d6618bd2 100755 --- a/processing/pre/geom_fromTable.py +++ b/processing/pre/geom_fromTable.py @@ -68,7 +68,7 @@ if options.axes is not None and not set(options.axes).issubset(set(['x','+x','-x for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) table.sort_by(['{}_{}'.format(i,options.pos) for i in range(3,0,-1)]) # x fast, y slow grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) diff --git a/processing/pre/geom_fromVoronoiTessellation.py b/processing/pre/geom_fromVoronoiTessellation.py index a3a54882a..5586d3bc8 100755 --- a/processing/pre/geom_fromVoronoiTessellation.py +++ b/processing/pre/geom_fromVoronoiTessellation.py @@ -171,7 +171,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) size = np.ones(3) origin = np.zeros(3) @@ -228,4 +228,4 @@ for name in filenames: homogenization=options.homogenization,comments=header) damask.util.croak(geom) - geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',pack=False) + geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',compress=False) diff --git a/processing/pre/geom_grainGrowth.py b/processing/pre/geom_grainGrowth.py index dbe1f1a74..5fa0ed0b5 100755 --- a/processing/pre/geom_grainGrowth.py +++ b/processing/pre/geom_grainGrowth.py @@ -172,4 +172,4 @@ for name in filenames: geom = geom.duplicate(microstructure[0:grid_original[0],0:grid_original[1],0:grid_original[2]]) geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:])) - geom.save_ASCII(sys.stdout if name is None else name,pack=False) + geom.save_ASCII(sys.stdout if name is None else name,compress=False) diff --git a/processing/pre/hybridIA_linODFsampling.py b/processing/pre/hybridIA_linODFsampling.py index 01704197e..f99a2dd89 100755 --- a/processing/pre/hybridIA_linODFsampling.py +++ b/processing/pre/hybridIA_linODFsampling.py @@ -234,7 +234,7 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - table = damask.Table.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) + table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) randomSeed = int(os.urandom(4).hex(),16) if options.randomSeed is None else options.randomSeed # random seed per file random.seed(randomSeed) diff --git a/processing/pre/seeds_fromDistribution.py b/processing/pre/seeds_fromDistribution.py index cc72920d3..e1e4726c2 100755 --- a/processing/pre/seeds_fromDistribution.py +++ b/processing/pre/seeds_fromDistribution.py @@ -78,7 +78,7 @@ class myThread (threading.Thread): perturbedSeedsVFile = StringIO() myBestSeedsVFile.seek(0) - perturbedSeedsTable = damask.Table.load_ASCII(myBestSeedsVFile) + perturbedSeedsTable = damask.Table.load(myBestSeedsVFile) coords = perturbedSeedsTable.get('pos') i = 0 for ms,coord in enumerate(coords): @@ -89,7 +89,7 @@ class myThread (threading.Thread): coords[i]=newCoords direction[i]*=2. i+= 1 - perturbedSeedsTable.set('pos',coords).save_ASCII(perturbedSeedsVFile,legacy=True) + perturbedSeedsTable.set('pos',coords).save(perturbedSeedsVFile,legacy=True) #--- do tesselation with perturbed seed file ------------------------------------------------------ perturbedGeomVFile.close() diff --git a/processing/pre/seeds_fromGeom.py b/processing/pre/seeds_fromGeom.py index 4110405d6..962c1dbce 100755 --- a/processing/pre/seeds_fromGeom.py +++ b/processing/pre/seeds_fromGeom.py @@ -65,4 +65,4 @@ for name in filenames: damask.Table(seeds[mask],{'pos':(3,)},comments)\ .add('microstructure',microstructure[mask].astype(int))\ - .save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.seeds',legacy=True) + .save(sys.stdout if name is None else os.path.splitext(name)[0]+'.seeds',legacy=True) diff --git a/processing/pre/seeds_fromPokes.py b/processing/pre/seeds_fromPokes.py index fdff40da3..c804cd285 100755 --- a/processing/pre/seeds_fromPokes.py +++ b/processing/pre/seeds_fromPokes.py @@ -92,5 +92,5 @@ for name in filenames: table = damask.Table(seeds,{'pos':(3,),'microstructure':(1,)},comments) table.set('microstructure',table.get('microstructure').astype(np.int))\ - .save_ASCII(sys.stdout if name is None else \ + .save(sys.stdout if name is None else \ os.path.splitext(name)[0]+f'_poked_{options.N}.seeds',legacy=True) diff --git a/processing/pre/seeds_fromRandom.py b/processing/pre/seeds_fromRandom.py index 8700a4648..451e218aa 100755 --- a/processing/pre/seeds_fromRandom.py +++ b/processing/pre/seeds_fromRandom.py @@ -162,4 +162,4 @@ for name in filenames: else np.random.normal(loc = options.mean, scale = options.sigma, size = options.N) table = table.add('weight',weights) - table.save_ASCII(sys.stdout if name is None else name,legacy=True) + table.save(sys.stdout if name is None else name,legacy=True) diff --git a/python/damask/_colormap.py b/python/damask/_colormap.py index f3065ebc8..fa7d36ec2 100644 --- a/python/damask/_colormap.py +++ b/python/damask/_colormap.py @@ -297,9 +297,9 @@ class Colormap(mpl.colors.ListedColormap): if fhandle is None: with open(self.name.replace(' ','_')+'.txt', 'w') as f: - t.save_ASCII(f) + t.save(f) else: - t.save_ASCII(fhandle) + t.save(fhandle) def save_GOM(self,fname=None): diff --git a/python/damask/_table.py b/python/damask/_table.py index 9789c8be6..431cf1886 100644 --- a/python/damask/_table.py +++ b/python/damask/_table.py @@ -67,7 +67,7 @@ class Table: @staticmethod - def load_ASCII(fname): + def load(fname): """ Load ASCII table file. @@ -344,7 +344,7 @@ class Table: return dup - def save_ASCII(self,fname,legacy=False): + def save(self,fname,legacy=False): """ Save as plain text file. diff --git a/python/damask/_test.py b/python/damask/_test.py index ab4df6d68..5cadc9dfe 100644 --- a/python/damask/_test.py +++ b/python/damask/_test.py @@ -287,9 +287,9 @@ class Test: import numpy as np logging.info('\n '.join(['comparing',File1,File2])) - table = damask.Table.load_ASCII(File1) + table = damask.Table.load(File1) len1 = len(table.comments)+2 - table = damask.Table.load_ASCII(File2) + table = damask.Table.load(File2) len2 = len(table.comments)+2 refArray = np.nan_to_num(np.genfromtxt(File1,missing_values='n/a',skip_header = len1,autostrip=True)) @@ -436,7 +436,7 @@ class Test: if not (isinstance(files, Iterable) and not isinstance(files, str)): # check whether list of files is requested files = [str(files)] - tables = [damask.Table.load_ASCII(filename) for filename in files] + tables = [damask.Table.load(filename) for filename in files] for table in tables: table._label_discrete() @@ -486,7 +486,7 @@ class Test: if len(files) < 2: return True # single table is always close to itself... - tables = [damask.Table.load_ASCII(filename) for filename in files] + tables = [damask.Table.load(filename) for filename in files] columns += [columns[0]]*(len(files)-len(columns)) # extend to same length as files columns = columns[:len(files)] # truncate to same length as files diff --git a/python/tests/test_Orientation.py b/python/tests/test_Orientation.py index 3a7425ddb..669f73e91 100644 --- a/python/tests/test_Orientation.py +++ b/python/tests/test_Orientation.py @@ -106,8 +106,8 @@ class TestOrientation: coords = np.array([(1,i+1) for i,x in enumerate(eu)]) table = Table(eu,{'Eulers':(3,)}) table = table.add('pos',coords) - table.save_ASCII(reference) - assert np.allclose(eu,Table.load_ASCII(reference).get('Eulers')) + table.save(reference) + assert np.allclose(eu,Table.load(reference).get('Eulers')) @pytest.mark.parametrize('lattice',Lattice.lattices) def test_disorientation360(self,lattice): diff --git a/python/tests/test_Table.py b/python/tests/test_Table.py index af940a037..7a86c7fed 100644 --- a/python/tests/test_Table.py +++ b/python/tests/test_Table.py @@ -35,30 +35,30 @@ class TestTable: @pytest.mark.parametrize('mode',['str','path']) def test_write_read(self,default,tmpdir,mode): - default.save_ASCII(tmpdir/'default.txt') + default.save(tmpdir/'default.txt') if mode == 'path': - new = Table.load_ASCII(tmpdir/'default.txt') + new = Table.load(tmpdir/'default.txt') elif mode == 'str': - new = Table.load_ASCII(str(tmpdir/'default.txt')) + new = Table.load(str(tmpdir/'default.txt')) assert all(default.data==new.data) and default.shapes == new.shapes def test_write_read_file(self,default,tmpdir): with open(tmpdir/'default.txt','w') as f: - default.save_ASCII(f) + default.save(f) with open(tmpdir/'default.txt') as f: - new = Table.load_ASCII(f) + new = Table.load(f) assert all(default.data==new.data) and default.shapes == new.shapes def test_write_read_legacy_style(self,default,tmpdir): with open(tmpdir/'legacy.txt','w') as f: - default.save_ASCII(f,legacy=True) + default.save(f,legacy=True) with open(tmpdir/'legacy.txt') as f: - new = Table.load_ASCII(f) + new = Table.load(f) assert all(default.data==new.data) and default.shapes == new.shapes def test_write_invalid_format(self,default,tmpdir): with pytest.raises(TypeError): - default.save_ASCII(tmpdir/'shouldnotbethere.txt',format='invalid') + default.save(tmpdir/'shouldnotbethere.txt',format='invalid') @pytest.mark.parametrize('mode',['str','path']) def test_read_ang(self,reference_dir,mode): @@ -78,7 +78,7 @@ class TestTable: @pytest.mark.parametrize('fname',['datatype-mix.txt','whitespace-mix.txt']) def test_read_strange(self,reference_dir,fname): with open(reference_dir/fname) as f: - Table.load_ASCII(f) + Table.load(f) def test_set(self,default): d = default.set('F',np.zeros((5,3,3)),'set to zero').get('F') From d33507866d3f71a1d450178f8c4ae82811b55212 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sun, 20 Sep 2020 21:50:52 +0200 Subject: [PATCH 37/61] statistically more valid test --- python/tests/test_Rotation.py | 43 ++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/python/tests/test_Rotation.py b/python/tests/test_Rotation.py index 3785e8da1..66cabfbd4 100644 --- a/python/tests/test_Rotation.py +++ b/python/tests/test_Rotation.py @@ -907,32 +907,39 @@ class TestRotation: @pytest.mark.parametrize('sigma',[5,10,15,20]) @pytest.mark.parametrize('N',[1000,10000,100000]) def test_spherical_component(self,N,sigma): - c = Rotation.from_random() - o = Rotation.from_spherical_component(c,sigma,N) - _, angles = c.misorientation(o).as_axis_angle(pair=True,degrees=True) - angles[::2] *= -1 # flip angle for every second to symmetrize distribution + p = [] + for run in range(5): + c = Rotation.from_random() + o = Rotation.from_spherical_component(c,sigma,N) + _, angles = c.misorientation(o).as_axis_angle(pair=True,degrees=True) + angles[::2] *= -1 # flip angle for every second to symmetrize distribution + + p.append(stats.normaltest(angles)[1]) - p = stats.normaltest(angles)[1] sigma_out = np.std(angles) - assert (.9 < sigma/sigma_out < 1.1) and p > 1e-4, f'{sigma/sigma_out},{p}' + p = np.average(p) + assert (.9 < sigma/sigma_out < 1.1) and p > 1e-2, f'{sigma/sigma_out},{p}' @pytest.mark.parametrize('sigma',[5,10,15,20]) @pytest.mark.parametrize('N',[1000,10000,100000]) def test_from_fiber_component(self,N,sigma): - """https://en.wikipedia.org/wiki/Full_width_at_half_maximum.""" - alpha = np.random.random()*2*np.pi,np.arccos(np.random.random()) - beta = np.random.random()*2*np.pi,np.arccos(np.random.random()) + p = [] + for run in range(5): + alpha = np.random.random()*2*np.pi,np.arccos(np.random.random()) + beta = np.random.random()*2*np.pi,np.arccos(np.random.random()) - f_in_C = np.array([np.sin(alpha[0])*np.cos(alpha[1]), np.sin(alpha[0])*np.sin(alpha[1]), np.cos(alpha[0])]) - f_in_S = np.array([np.sin(beta[0] )*np.cos(beta[1] ), np.sin(beta[0] )*np.sin(beta[1] ), np.cos(beta[0] )]) - ax = np.append(np.cross(f_in_C,f_in_S), - np.arccos(np.dot(f_in_C,f_in_S))) - n = Rotation.from_axis_angle(ax if ax[3] > 0.0 else ax*-1.0 ,normalize=True) # rotation to align fiber axis in crystal and sample system + f_in_C = np.array([np.sin(alpha[0])*np.cos(alpha[1]), np.sin(alpha[0])*np.sin(alpha[1]), np.cos(alpha[0])]) + f_in_S = np.array([np.sin(beta[0] )*np.cos(beta[1] ), np.sin(beta[0] )*np.sin(beta[1] ), np.cos(beta[0] )]) + ax = np.append(np.cross(f_in_C,f_in_S), - np.arccos(np.dot(f_in_C,f_in_S))) + n = Rotation.from_axis_angle(ax if ax[3] > 0.0 else ax*-1.0 ,normalize=True) # rotation to align fiber axis in crystal and sample system - o = Rotation.from_fiber_component(alpha,beta,np.radians(sigma),N,False) - angles = np.arccos(np.clip(np.dot(o@np.broadcast_to(f_in_S,(N,3)),n@f_in_S),-1,1)) - dist = np.array(angles) * (np.random.randint(0,2,N)*2-1) + o = Rotation.from_fiber_component(alpha,beta,np.radians(sigma),N,False) + angles = np.arccos(np.clip(np.dot(o@np.broadcast_to(f_in_S,(N,3)),n@f_in_S),-1,1)) + dist = np.array(angles) * (np.random.randint(0,2,N)*2-1) + + p.append(stats.normaltest(dist)[1]) - p = stats.normaltest(dist)[1] sigma_out = np.degrees(np.std(dist)) - assert (.9 < sigma/sigma_out < 1.1) and p > 1.e-4, f'{sigma/sigma_out},{p}' + p = np.average(p) + assert (.9 < sigma/sigma_out < 1.1) and p > 1e-2, f'{sigma/sigma_out},{p}' From 24febcd15b9244d66b033a42ef76d95f29c208bb Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sun, 20 Sep 2020 21:51:09 +0200 Subject: [PATCH 38/61] forgotten rename --- processing/pre/geom_fromMinimalSurface.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/processing/pre/geom_fromMinimalSurface.py b/processing/pre/geom_fromMinimalSurface.py index b64bac417..b52003d79 100755 --- a/processing/pre/geom_fromMinimalSurface.py +++ b/processing/pre/geom_fromMinimalSurface.py @@ -89,4 +89,4 @@ geom=damask.Geom(microstructure,options.size, comments=[scriptID + ' ' + ' '.join(sys.argv[1:])]) damask.util.croak(geom) -geom.save_ASCII(sys.stdout if name is None else name,pack=False) +geom.save_ASCII(sys.stdout if name is None else name,compress=False) From 7bdd44a3d9f9132f2d2b811bb4ec11cd8d9dd424 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sun, 20 Sep 2020 22:04:28 +0200 Subject: [PATCH 39/61] consistent names: default file operations: save/load, non-default save_xx/load_xx --- PRIVATE | 2 +- processing/pre/geom_fromOsteonGeometry.py | 2 +- python/damask/_geom.py | 4 ++-- python/damask/_result.py | 2 +- python/tests/test_Geom.py | 10 +++++----- python/tests/test_Result.py | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/PRIVATE b/PRIVATE index 7c543a98e..bb3011806 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 7c543a98e89840f1f1540c7af8c62a19084dab6e +Subproject commit bb30118067c33a2b8ba3e0f1cee52ca4a0b786d8 diff --git a/processing/pre/geom_fromOsteonGeometry.py b/processing/pre/geom_fromOsteonGeometry.py index c2583d0ed..0b1440d63 100755 --- a/processing/pre/geom_fromOsteonGeometry.py +++ b/processing/pre/geom_fromOsteonGeometry.py @@ -142,4 +142,4 @@ geom = damask.Geom(microstructure.reshape(grid), homogenization=options.homogenization,comments=header) damask.util.croak(geom) -geom.save_ASCII(sys.stdout if name is None else name,pack=False) +geom.save_ASCII(sys.stdout if name is None else name,compress=False) diff --git a/python/damask/_geom.py b/python/damask/_geom.py index be4f596c1..41e1e22da 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -348,7 +348,7 @@ class Geom: @staticmethod - def load_vtr(fname): + def load(fname): """ Read a VTK rectilinear grid. @@ -516,7 +516,7 @@ class Geom: f.write(f'{reps} of {former}\n') - def save_vtr(self,fname,compress=True): + def save(self,fname,compress=True): """ Generates vtk rectilinear grid. diff --git a/python/damask/_result.py b/python/damask/_result.py index 02d0c0abe..5e8a9a9d0 100644 --- a/python/damask/_result.py +++ b/python/damask/_result.py @@ -1100,7 +1100,7 @@ class Result: pool.join() - def write_XDMF(self): + def save_XDMF(self): """ Write XDMF file to directly visualize data in DADF5 file. diff --git a/python/tests/test_Geom.py b/python/tests/test_Geom.py index 12f50be96..dbd2f795b 100644 --- a/python/tests/test_Geom.py +++ b/python/tests/test_Geom.py @@ -75,12 +75,12 @@ class TestGeom: assert geom_equal(default,new) def test_read_write_vtr(self,default,tmpdir): - default.save_vtr(tmpdir/'default') + default.save(tmpdir/'default') for _ in range(10): time.sleep(.2) if os.path.exists(tmpdir/'default.vtr'): break - new = Geom.load_vtr(tmpdir/'default.vtr') + new = Geom.load(tmpdir/'default.vtr') assert geom_equal(new,default) def test_invalid_geom(self,tmpdir): @@ -97,7 +97,7 @@ class TestGeom: time.sleep(.2) if os.path.exists(tmpdir/'no_materialpoint.vtr'): break with pytest.raises(ValueError): - Geom.load_vtr(tmpdir/'no_materialpoint.vtr') + Geom.load(tmpdir/'no_materialpoint.vtr') @pytest.mark.parametrize('compress',[True,False]) @@ -188,11 +188,11 @@ class TestGeom: current = default.clean(stencil,selection,periodic) reference = reference_dir/f'clean_{stencil}_{"+".join(map(str,[None] if selection is None else selection))}_{periodic}' if update and stencil > 1: - current.save_vtr(reference) + current.save(reference) for _ in range(10): time.sleep(.2) if os.path.exists(reference.with_suffix('.vtr')): break - assert geom_equal(Geom.load_vtr(reference) if stencil > 1 else default, + assert geom_equal(Geom.load(reference) if stencil > 1 else default, current ) diff --git a/python/tests/test_Result.py b/python/tests/test_Result.py index c25bf7a4c..68b72badf 100644 --- a/python/tests/test_Result.py +++ b/python/tests/test_Result.py @@ -343,4 +343,4 @@ class TestResult: def test_XDMF(self,tmp_path,single_phase): os.chdir(tmp_path) - single_phase.write_XDMF() + single_phase.save_XDMF() From 783b74966213284bc2de2de213309f127cbf5e06 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sun, 20 Sep 2020 22:25:08 +0200 Subject: [PATCH 40/61] compress instead of pack (same name for vtk/geom) --- processing/pre/geom_fromTable.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/processing/pre/geom_fromTable.py b/processing/pre/geom_fromTable.py index 3d6618bd2..6f2cb5b4d 100755 --- a/processing/pre/geom_fromTable.py +++ b/processing/pre/geom_fromTable.py @@ -105,4 +105,4 @@ for name in filenames: homogenization=options.homogenization,comments=header) damask.util.croak(geom) - geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',pack=False) + geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',compress=False) From ca2f3f9493490fca7e8db63512ac21e54914debb Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Mon, 21 Sep 2020 10:29:07 -0400 Subject: [PATCH 41/61] set_X and add_comments methods now default to out-of-place --- python/damask/_geom.py | 73 ++++++++++++++++++++++----------------- python/tests/test_Geom.py | 26 +++++++++++++- 2 files changed, 67 insertions(+), 32 deletions(-) diff --git a/python/damask/_geom.py b/python/damask/_geom.py index f5dc05f2f..0c9a4d9e4 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -35,11 +35,11 @@ class Geom: Comment lines. """ - self.set_microstructure(microstructure) - self.set_size(size) - self.set_origin(origin) - self.set_homogenization(homogenization) - self.set_comments(comments) + self.set_microstructure(microstructure,inplace=True) + self.set_size(size,inplace=True) + self.set_origin(origin,inplace=True) + self.set_homogenization(homogenization,inplace=True) + self.set_comments(comments,inplace=True) def __repr__(self): @@ -85,17 +85,16 @@ class Geom: raise ValueError('Auto-sizing conflicts with explicit size parameter.') grid_old = self.get_grid() - dup = self.copy() - dup.set_microstructure(microstructure) - dup.set_origin(origin) + dup = self.set_microstructure(microstructure)\ + .set_origin(origin) if comments is not None: - dup.set_comments(comments) + dup.set_comments(comments,inplace=True) if size is not None: - dup.set_size(size) + dup.set_size(size,inplace=True) elif autosize: - dup.set_size(dup.get_grid()/grid_old*self.get_size()) + dup.set_size(dup.get_grid()/grid_old*self.get_size(),inplace=True) return dup @@ -134,7 +133,7 @@ class Geom: return util.return_message(message) - def set_comments(self,comments): + def set_comments(self,comments,inplace=False): """ Replace all existing comments. @@ -144,11 +143,13 @@ class Geom: All comments. """ - self.comments = [] - self.add_comments(comments) + target = self if inplace else self.copy() + target.comments = [] + target.add_comments(comments,inplace=True) + if not inplace: return target - def add_comments(self,comments): + def add_comments(self,comments,inplace=False): """ Append comments to existing comments. @@ -158,10 +159,12 @@ class Geom: New comments. """ - self.comments += [str(c) for c in comments] if isinstance(comments,list) else [str(comments)] + target = self if inplace else self.copy() + target.comments += [str(c) for c in comments] if isinstance(comments,list) else [str(comments)] + if not inplace: return target - def set_microstructure(self,microstructure): + def set_microstructure(self,microstructure,inplace=False): """ Replace the existing microstructure representation. @@ -175,24 +178,26 @@ class Geom: Microstructure indices. """ + target = self if inplace else self.copy() if microstructure is not None: if isinstance(microstructure,np.ma.core.MaskedArray): - self.microstructure = np.where(microstructure.mask, - self.microstructure,microstructure.data) + target.microstructure = np.where(microstructure.mask, + target.microstructure,microstructure.data) else: - self.microstructure = np.copy(microstructure) + target.microstructure = np.copy(microstructure) - if self.microstructure.dtype in np.sctypes['float'] and \ - np.all(self.microstructure == self.microstructure.astype(int).astype(float)): - self.microstructure = self.microstructure.astype(int) + if target.microstructure.dtype in np.sctypes['float'] and \ + np.all(target.microstructure == target.microstructure.astype(int).astype(float)): + target.microstructure = target.microstructure.astype(int) - if len(self.microstructure.shape) != 3: + if len(target.microstructure.shape) != 3: raise ValueError(f'Invalid microstructure shape {microstructure.shape}') - elif self.microstructure.dtype not in np.sctypes['float'] + np.sctypes['int']: + elif target.microstructure.dtype not in np.sctypes['float'] + np.sctypes['int']: raise TypeError(f'Invalid microstructure data type {microstructure.dtype}') + if not inplace: return target - def set_size(self,size): + def set_size(self,size,inplace=False): """ Replace the existing size information. @@ -202,14 +207,16 @@ class Geom: Physical size of the microstructure in meter. """ + target = self if inplace else self.copy() if size is not None: if len(size) != 3 or any(np.array(size) <= 0): raise ValueError(f'Invalid size {size}') else: - self.size = np.array(size) + target.size = np.array(size) + if not inplace: return target - def set_origin(self,origin): + def set_origin(self,origin,inplace=False): """ Replace the existing origin information. @@ -219,14 +226,16 @@ class Geom: Physical origin of the microstructure in meter. """ + target = self if inplace else self.copy() if origin is not None: if len(origin) != 3: raise ValueError(f'Invalid origin {origin}') else: - self.origin = np.array(origin) + target.origin = np.array(origin) + if not inplace: return target - def set_homogenization(self,homogenization): + def set_homogenization(self,homogenization,inplace=False): """ Replace the existing homogenization index. @@ -236,11 +245,13 @@ class Geom: Homogenization index. """ + target = self if inplace else self.copy() if homogenization is not None: if not isinstance(homogenization,int) or homogenization < 1: raise TypeError(f'Invalid homogenization {homogenization}.') else: - self.homogenization = homogenization + target.homogenization = homogenization + if not inplace: return target @property diff --git a/python/tests/test_Geom.py b/python/tests/test_Geom.py index 870cc7469..ff9c80057 100644 --- a/python/tests/test_Geom.py +++ b/python/tests/test_Geom.py @@ -54,11 +54,35 @@ class TestGeom: assert str(default.diff(new)) != '' + def test_set_inplace_outofplace_homogenization(self,default): + default.set_homogenization(123,inplace=True) + outofplace = default.set_homogenization(321,inplace=False) + assert default.get_homogenization() == 123 and outofplace.get_homogenization() == 321 + + + def test_set_inplace_outofplace_microstructure(self,default): + default.set_microstructure(np.arange(72).reshape((2,4,9)),inplace=True) + outofplace = default.set_microstructure(np.arange(72).reshape((8,3,3)),inplace=False) + assert np.array_equal(default.grid,[2,4,9]) and np.array_equal(outofplace.grid,[8,3,3]) + + + def test_set_inplace_outofplace_size(self,default): + default.set_size(np.array([1,2,3]),inplace=True) + outofplace = default.set_size(np.array([3,2,1]),inplace=False) + assert np.array_equal(default.get_size(),[1,2,3]) and np.array_equal(outofplace.get_size(),[3,2,1]) + + + def test_set_inplace_outofplace_comments(self,default): + default.set_comments(['a','and','b'],inplace=True) + outofplace = default.set_comments(['b','or','a'],inplace=False) + assert default.get_comments() == ['a','and','b'] and outofplace.get_comments() == ['b','or','a'] + + @pytest.mark.parametrize('masked',[True,False]) def test_set_microstructure(self,default,masked): old = default.get_microstructure() new = np.random.randint(200,size=default.grid) - default.set_microstructure(np.ma.MaskedArray(new,np.full_like(new,masked))) + default.set_microstructure(np.ma.MaskedArray(new,np.full_like(new,masked)),inplace=True) assert np.all(default.microstructure==(old if masked else new)) From 188905766fc284cdf7b58b427c2da2257c77efc1 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Mon, 21 Sep 2020 11:13:53 -0400 Subject: [PATCH 42/61] removed Geom.get_X() methods in favor of direct property access --- processing/pre/mentat_spectralBox.py | 14 ++-- processing/pre/seeds_fromGeom.py | 2 +- python/damask/_geom.py | 103 ++++++++++----------------- python/tests/test_Geom.py | 30 ++++---- 4 files changed, 60 insertions(+), 89 deletions(-) diff --git a/processing/pre/mentat_spectralBox.py b/processing/pre/mentat_spectralBox.py index 027240044..76649aa1a 100755 --- a/processing/pre/mentat_spectralBox.py +++ b/processing/pre/mentat_spectralBox.py @@ -42,7 +42,7 @@ def output(cmds,locals,dest): else: outFile(str(cmd),locals,dest) - + #------------------------------------------------------------------------------------------------- def init(): return [ @@ -114,7 +114,7 @@ def material(): "*add_geometry_elements", "all_existing", ] - + #------------------------------------------------------------------------------------------------- def geometry(): @@ -127,14 +127,14 @@ def geometry(): "*element_type 7", "all_existing", ] - + #------------------------------------------------------------------------------------------------- def initial_conditions(microstructures): elements = [] element = 0 for id in microstructures: - element += 1 + element += 1 if len(elements) < id: for i in range(id-len(elements)): elements.append([]) @@ -195,9 +195,9 @@ if filenames == []: filenames = [None] for name in filenames: damask.util.report(scriptName,name) - + geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) - microstructure = geom.get_microstructure().flatten(order='F') + microstructure = geom.microstructure.flatten(order='F') cmds = [\ init(), @@ -210,7 +210,7 @@ for name in filenames: '*redraw', '*draw_automatic', ] - + outputLocals = {} if options.port: py_mentat.py_connect('',options.port) diff --git a/processing/pre/seeds_fromGeom.py b/processing/pre/seeds_fromGeom.py index 97550ce13..7773f6f53 100755 --- a/processing/pre/seeds_fromGeom.py +++ b/processing/pre/seeds_fromGeom.py @@ -47,7 +47,7 @@ for name in filenames: damask.util.report(scriptName,name) geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) - microstructure = geom.get_microstructure().reshape((-1,1),order='F') + microstructure = geom.microstructure.reshape((-1,1),order='F') mask = np.logical_and(np.in1d(microstructure,options.whitelist,invert=False) if options.whitelist else \ np.full(geom.grid.prod(),True,dtype=bool), diff --git a/python/damask/_geom.py b/python/damask/_geom.py index 0c9a4d9e4..7e6b6a1d3 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -45,9 +45,9 @@ class Geom: def __repr__(self): """Basic information on geometry definition.""" return util.srepr([ - f'grid a b c: {util.srepr(self.get_grid ()," x ")}', - f'size x y z: {util.srepr(self.get_size ()," x ")}', - f'origin x y z: {util.srepr(self.get_origin()," ")}', + f'grid a b c: {util.srepr(self.grid, " x ")}', + f'size x y z: {util.srepr(self.size, " x ")}', + f'origin x y z: {util.srepr(self.origin," ")}', f'# materialpoints: {self.N_microstructure}', f'max materialpoint: {np.nanmax(self.microstructure)}', ]) @@ -84,7 +84,7 @@ class Geom: if size is not None and autosize: raise ValueError('Auto-sizing conflicts with explicit size parameter.') - grid_old = self.get_grid() + grid_old = self.grid dup = self.set_microstructure(microstructure)\ .set_origin(origin) @@ -94,7 +94,7 @@ class Geom: if size is not None: dup.set_size(size,inplace=True) elif autosize: - dup.set_size(dup.get_grid()/grid_old*self.get_size(),inplace=True) + dup.set_size(dup.grid/grid_old*self.size,inplace=True) return dup @@ -110,17 +110,17 @@ class Geom: """ message = [] - if np.any(other.get_grid() != self.get_grid()): - message.append(util.delete(f'grid a b c: {util.srepr(other.get_grid()," x ")}')) - message.append(util.emph( f'grid a b c: {util.srepr( self.get_grid()," x ")}')) + if np.any(other.grid != self.grid): + message.append(util.delete(f'grid a b c: {util.srepr(other.grid," x ")}')) + message.append(util.emph( f'grid a b c: {util.srepr( self.grid," x ")}')) - if np.any(other.get_size() != self.get_size()): - message.append(util.delete(f'size x y z: {util.srepr(other.get_size()," x ")}')) - message.append(util.emph( f'size x y z: {util.srepr( self.get_size()," x ")}')) + if np.any(other.size != self.size): + message.append(util.delete(f'size x y z: {util.srepr(other.size," x ")}')) + message.append(util.emph( f'size x y z: {util.srepr( self.size," x ")}')) - if np.any(other.get_origin() != self.get_origin()): - message.append(util.delete(f'origin x y z: {util.srepr(other.get_origin()," ")}')) - message.append(util.emph( f'origin x y z: {util.srepr( self.get_origin()," ")}')) + if np.any(other.origin != self.origin): + message.append(util.delete(f'origin x y z: {util.srepr(other.origin," ")}')) + message.append(util.emph( f'origin x y z: {util.srepr( self.origin," ")}')) if other.N_microstructure != self.N_microstructure: message.append(util.delete(f'# materialpoints: {other.N_microstructure}')) @@ -256,7 +256,7 @@ class Geom: @property def grid(self): - return self.get_grid() + return np.asarray(self.microstructure.shape) @property @@ -264,36 +264,6 @@ class Geom: return np.unique(self.microstructure).size - def get_microstructure(self): - """Return the microstructure representation.""" - return np.copy(self.microstructure) - - - def get_size(self): - """Return the physical size in meter.""" - return np.copy(self.size) - - - def get_origin(self): - """Return the origin in meter.""" - return np.copy(self.origin) - - - def get_grid(self): - """Return the grid discretization.""" - return np.asarray(self.microstructure.shape) - - - def get_homogenization(self): - """Return the homogenization index.""" - return self.homogenization - - - def get_comments(self): - """Return the comments.""" - return self.comments[:] - - @staticmethod def from_file(fname): """ @@ -488,13 +458,14 @@ class Geom: Compress geometry with 'x of y' and 'a to b'. """ - header = [f'{len(geom.comments)+4} header'] + geom.comments - header.append('grid a {} b {} c {}'.format(*geom.get_grid())) - header.append('size x {} y {} z {}'.format(*geom.get_size())) - header.append('origin x {} y {} z {}'.format(*geom.get_origin())) - header.append(f'homogenization {geom.get_homogenization()}') + header = [f'{len(geom.comments)+4} header'] + geom.comments \ + +[ 'grid a {} b {} c {}'.format(*geom.grid), + 'size x {} y {} z {}'.format(*geom.size), + 'origin x {} y {} z {}'.format(*geom.origin), + f'homogenization {geom.homogenization}', + ] - grid = geom.get_grid() + grid = geom.grid if pack is None: plain = grid.prod()/geom.N_microstructure < 250 @@ -634,7 +605,7 @@ class Geom: ms = np.ma.MaskedArray(fill_,np.logical_not(mask) if inverse else mask) return self.duplicate(ms, - comments=self.get_comments()+[util.execution_stamp('Geom','add_primitive')], + comments=self.comments+[util.execution_stamp('Geom','add_primitive')], ) @@ -656,7 +627,7 @@ class Geom: raise ValueError(f'Invalid direction {set(directions).difference(valid)} specified.') limits = [None,None] if reflect else [-2,0] - ms = self.get_microstructure() + ms = self.microstructure.copy() if 'z' in directions: ms = np.concatenate([ms,ms[:,:,limits[0]:limits[1]:-1]],2) @@ -666,7 +637,7 @@ class Geom: ms = np.concatenate([ms,ms[limits[0]:limits[1]:-1,:,:]],0) return self.duplicate(ms, - comments=self.get_comments()+[util.execution_stamp('Geom','mirror')], + comments=self.comments+[util.execution_stamp('Geom','mirror')], autosize=True) @@ -688,7 +659,7 @@ class Geom: ms = np.flip(self.microstructure, (valid.index(d) for d in directions if d in valid)) return self.duplicate(ms, - comments=self.get_comments()+[util.execution_stamp('Geom','flip')], + comments=self.comments+[util.execution_stamp('Geom','flip')], ) @@ -706,13 +677,13 @@ class Geom: """ return self.duplicate(ndimage.interpolation.zoom( self.microstructure, - grid/self.get_grid(), + grid/self.grid, output=self.microstructure.dtype, order=0, mode=('wrap' if periodic else 'nearest'), prefilter=False ), - comments=self.get_comments()+[util.execution_stamp('Geom','scale')], + comments=self.comments+[util.execution_stamp('Geom','scale')], ) @@ -745,18 +716,18 @@ class Geom: mode=('wrap' if periodic else 'nearest'), extra_keywords=dict(selection=selection), ).astype(self.microstructure.dtype), - comments=self.get_comments()+[util.execution_stamp('Geom','clean')], + comments=self.comments+[util.execution_stamp('Geom','clean')], ) def renumber(self): """Renumber sorted microstructure indices to 1,...,N.""" - renumbered = np.empty(self.get_grid(),dtype=self.microstructure.dtype) + renumbered = np.empty(self.grid,dtype=self.microstructure.dtype) for i, oldID in enumerate(np.unique(self.microstructure)): renumbered = np.where(self.microstructure == oldID, i+1, renumbered) return self.duplicate(renumbered, - comments=self.get_comments()+[util.execution_stamp('Geom','renumber')], + comments=self.comments+[util.execution_stamp('Geom','renumber')], ) @@ -776,7 +747,7 @@ class Geom: dtype = float if np.isnan(fill) or int(fill) != fill or self.microstructure.dtype==np.float else int Eulers = R.as_Eulers(degrees=True) - microstructure_in = self.get_microstructure() + microstructure_in = self.microstructure.copy() # These rotations are always applied in the reference coordinate system, i.e. (z,x,z) not (z,x',z'') # see https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf @@ -793,7 +764,7 @@ class Geom: return self.duplicate(microstructure_in, origin=origin, - comments=self.get_comments()+[util.execution_stamp('Geom','rotate')], + comments=self.comments+[util.execution_stamp('Geom','rotate')], autosize=True, ) @@ -827,7 +798,7 @@ class Geom: return self.duplicate(canvas, origin=self.origin+offset*self.size/self.grid, - comments=self.get_comments()+[util.execution_stamp('Geom','canvas')], + comments=self.comments+[util.execution_stamp('Geom','canvas')], autosize=True, ) @@ -844,12 +815,12 @@ class Geom: New microstructure indices. """ - substituted = self.get_microstructure() + substituted = self.microstructure.copy() for from_ms,to_ms in zip(from_microstructure,to_microstructure): substituted[self.microstructure==from_ms] = to_ms return self.duplicate(substituted, - comments=self.get_comments()+[util.execution_stamp('Geom','substitute')], + comments=self.comments+[util.execution_stamp('Geom','substitute')], ) @@ -896,5 +867,5 @@ class Geom: microstructure = np.ma.MaskedArray(self.microstructure + offset_, np.logical_not(mask)) return self.duplicate(microstructure, - comments=self.get_comments()+[util.execution_stamp('Geom','vicinity_offset')], + comments=self.comments+[util.execution_stamp('Geom','vicinity_offset')], ) diff --git a/python/tests/test_Geom.py b/python/tests/test_Geom.py index ff9c80057..f82272362 100644 --- a/python/tests/test_Geom.py +++ b/python/tests/test_Geom.py @@ -11,9 +11,9 @@ from damask import util def geom_equal(a,b): - return np.all(a.get_microstructure() == b.get_microstructure()) and \ - np.all(a.get_grid() == b.get_grid()) and \ - np.allclose(a.get_size(), b.get_size()) and \ + return np.all(a.microstructure == b.microstructure) and \ + np.all(a.grid == b.grid) and \ + np.allclose(a.size, b.size) and \ str(a.diff(b)) == str(b.diff(a)) @pytest.fixture @@ -39,9 +39,9 @@ class TestGeom: modified = default.duplicate() elif flavor == 'explicit': modified = default.duplicate( - default.get_microstructure(), - default.get_size(), - default.get_origin() + default.microstructure, + default.size, + default.origin ) print(modified) assert geom_equal(default,modified) @@ -57,7 +57,7 @@ class TestGeom: def test_set_inplace_outofplace_homogenization(self,default): default.set_homogenization(123,inplace=True) outofplace = default.set_homogenization(321,inplace=False) - assert default.get_homogenization() == 123 and outofplace.get_homogenization() == 321 + assert default.homogenization == 123 and outofplace.homogenization == 321 def test_set_inplace_outofplace_microstructure(self,default): @@ -69,18 +69,18 @@ class TestGeom: def test_set_inplace_outofplace_size(self,default): default.set_size(np.array([1,2,3]),inplace=True) outofplace = default.set_size(np.array([3,2,1]),inplace=False) - assert np.array_equal(default.get_size(),[1,2,3]) and np.array_equal(outofplace.get_size(),[3,2,1]) + assert np.array_equal(default.size,[1,2,3]) and np.array_equal(outofplace.size,[3,2,1]) def test_set_inplace_outofplace_comments(self,default): default.set_comments(['a','and','b'],inplace=True) outofplace = default.set_comments(['b','or','a'],inplace=False) - assert default.get_comments() == ['a','and','b'] and outofplace.get_comments() == ['b','or','a'] + assert default.comments == ['a','and','b'] and outofplace.comments == ['b','or','a'] @pytest.mark.parametrize('masked',[True,False]) def test_set_microstructure(self,default,masked): - old = default.get_microstructure() + old = default.microstructure new = np.random.randint(200,size=default.grid) default.set_microstructure(np.ma.MaskedArray(new,np.full_like(new,masked)),inplace=True) assert np.all(default.microstructure==(old if masked else new)) @@ -249,7 +249,7 @@ class TestGeom: modified) def test_renumber(self,default): - microstructure = default.get_microstructure() + microstructure = default.microstructure.copy() for m in np.unique(microstructure): microstructure[microstructure==m] = microstructure.max() + np.random.randint(1,30) modified = default.duplicate(microstructure) @@ -259,7 +259,7 @@ class TestGeom: def test_substitute(self,default): offset = np.random.randint(1,500) - modified = default.duplicate(default.get_microstructure() + offset) + modified = default.duplicate(default.microstructure + offset) assert not geom_equal(modified,default) assert geom_equal(default, modified.substitute(np.arange(default.microstructure.max())+1+offset, @@ -345,9 +345,9 @@ class TestGeom: @pytest.mark.parametrize('periodic',[True,False]) def test_vicinity_offset_invariant(self,default,periodic): - old = default.get_microstructure() - default.vicinity_offset(trigger=[old.max()+1,old.min()-1]) - assert np.all(old==default.microstructure) + offset = default.vicinity_offset(trigger=[default.microstructure.max()+1, + default.microstructure.min()-1]) + assert np.all(offset.microstructure==default.microstructure) @pytest.mark.parametrize('periodic',[True,False]) def test_tessellation_approaches(self,periodic): From e683cbef69dc9439d7b667d61f0cb8ad77f9c6eb Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Mon, 21 Sep 2020 11:30:27 -0400 Subject: [PATCH 43/61] replaced a stray get_grid() in geom_grainGrowth --- processing/pre/geom_grainGrowth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/processing/pre/geom_grainGrowth.py b/processing/pre/geom_grainGrowth.py index 0652d0583..ea9331317 100755 --- a/processing/pre/geom_grainGrowth.py +++ b/processing/pre/geom_grainGrowth.py @@ -64,7 +64,7 @@ for name in filenames: geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) - grid_original = geom.get_grid() + grid_original = geom.grid damask.util.croak(geom) microstructure = np.tile(geom.microstructure,np.where(grid_original == 1, 2,1)) # make one copy along dimensions with grid == 1 grid = np.array(microstructure.shape) From 63f9078f04f24a7d8ce6cd3ba85cf09110c42fcd Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Tue, 22 Sep 2020 12:13:50 +0200 Subject: [PATCH 44/61] don' hardcode output unit replaced remaining write(6,..), flush(6) with write(OUTPUT_UNIT,...), flush(OUTPUT_UNIT) --- src/CPFEM.f90 | 6 ++--- src/CPFEM2.f90 | 2 +- src/DAMASK_marc.f90 | 6 ++--- src/IO.f90 | 2 +- src/base64.f90 | 2 +- src/config.f90 | 8 +++---- src/constitutive.f90 | 2 +- src/constitutive_plastic_disloTungsten.f90 | 2 +- src/constitutive_plastic_dislotwin.f90 | 2 +- src/constitutive_plastic_isotropic.f90 | 2 +- src/constitutive_plastic_kinehardening.f90 | 2 +- src/constitutive_plastic_none.f90 | 2 +- src/constitutive_plastic_nonlocal.f90 | 2 +- src/constitutive_plastic_phenopowerlaw.f90 | 2 +- src/crystallite.f90 | 4 ++-- src/damage_local.f90 | 2 +- src/element.f90 | 2 +- src/homogenization.f90 | 2 +- src/homogenization_mech_RGC.f90 | 28 +++++++++++----------- src/homogenization_mech_isostrain.f90 | 2 +- src/homogenization_mech_none.f90 | 2 +- src/kinematics_cleavage_opening.f90 | 2 +- src/kinematics_slipplane_opening.f90 | 2 +- src/kinematics_thermal_expansion.f90 | 2 +- src/lattice.f90 | 2 +- src/material.f90 | 2 +- src/math.f90 | 2 +- src/results.f90 | 2 +- src/rotations.f90 | 2 +- src/source_damage_anisoBrittle.f90 | 2 +- src/source_damage_anisoDuctile.f90 | 2 +- src/source_damage_isoBrittle.f90 | 2 +- src/source_damage_isoDuctile.f90 | 2 +- src/source_thermal_dissipation.f90 | 2 +- src/source_thermal_externalheat.f90 | 2 +- 35 files changed, 56 insertions(+), 56 deletions(-) diff --git a/src/CPFEM.f90 b/src/CPFEM.f90 index d0fc6413e..09e028f6c 100644 --- a/src/CPFEM.f90 +++ b/src/CPFEM.f90 @@ -106,7 +106,7 @@ subroutine CPFEM_init num_commercialFEM, & debug_CPFEM - print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(6) + print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(OUTPUT_UNIT) allocate(CPFEM_cs( 6,discretization_nIP,discretization_nElem), source= 0.0_pReal) allocate(CPFEM_dcsdE( 6,6,discretization_nIP,discretization_nElem), source= 0.0_pReal) @@ -132,7 +132,7 @@ subroutine CPFEM_init print'(a32,1x,6(i8,1x))', 'CPFEM_cs: ', shape(CPFEM_cs) print'(a32,1x,6(i8,1x))', 'CPFEM_dcsdE: ', shape(CPFEM_dcsdE) print'(a32,1x,6(i8,1x),/)', 'CPFEM_dcsdE_knownGood: ', shape(CPFEM_dcsdE_knownGood) - flush(6) + flush(OUTPUT_UNIT) endif end subroutine CPFEM_init @@ -250,7 +250,7 @@ subroutine CPFEM_general(mode, ffn, ffn1, temperature_inp, dt, elFE, ip, cauchyS '<< CPFEM >> stress/MPa at elFE ip ', elFE, ip, CPFEM_cs(1:6,ip,elCP)*1.0e-6_pReal print'(a,i8,1x,i2,/,6(12x,6(f10.3,1x)/))', & '<< CPFEM >> Jacobian/GPa at elFE ip ', elFE, ip, transpose(CPFEM_dcsdE(1:6,1:6,ip,elCP))*1.0e-9_pReal - flush(6) + flush(OUTPUT_UNIT) endif endif diff --git a/src/CPFEM2.f90 b/src/CPFEM2.f90 index c87f361c2..fc68778c8 100644 --- a/src/CPFEM2.f90 +++ b/src/CPFEM2.f90 @@ -76,7 +76,7 @@ end subroutine CPFEM_initAll !-------------------------------------------------------------------------------------------------- subroutine CPFEM_init - print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(6) + print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(OUTPUT_UNIT) if (interface_restartInc > 0) call crystallite_restartRead diff --git a/src/DAMASK_marc.f90 b/src/DAMASK_marc.f90 index ea7430c6b..c34538ad9 100644 --- a/src/DAMASK_marc.f90 +++ b/src/DAMASK_marc.f90 @@ -265,9 +265,9 @@ subroutine hypela2(d,g,e,de,s,t,dt,ngens,m,nn,kcus,matus,ndi,nshear,disp, & print'(a,i2)', ' Coordinates: ', ncrd print'(a,i12)', ' Nodes: ', nnode print'(a,i1)', ' Deformation gradient: ', itel - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') ' Deformation gradient at t=n:', & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') ' Deformation gradient at t=n:', & transpose(ffn) - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') ' Deformation gradient at t=n+1:', & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') ' Deformation gradient at t=n+1:', & transpose(ffn1) endif @@ -312,7 +312,7 @@ subroutine hypela2(d,g,e,de,s,t,dt,ngens,m,nn,kcus,matus,ndi,nshear,disp, & cycleCounter = -1 ! first calc step increments this to cycle = 0 print'(a,i6,1x,i2)', '<< HYPELA2 >> cutback detected..! ',m(1),nn endif ! convergence treatment end - flush(6) + flush(OUTPUT_UNIT) if (lastLovl /= lovl) then cycleCounter = cycleCounter + 1 diff --git a/src/IO.f90 b/src/IO.f90 index 9137372d3..72eb2011f 100644 --- a/src/IO.f90 +++ b/src/IO.f90 @@ -52,7 +52,7 @@ contains !-------------------------------------------------------------------------------------------------- subroutine IO_init - print'(/,a)', ' <<<+- IO init -+>>>'; flush(6) + print'(/,a)', ' <<<+- IO init -+>>>'; flush(OUTPUT_UNIT) call selfTest diff --git a/src/base64.f90 b/src/base64.f90 index 3a59b7049..c04221f21 100644 --- a/src/base64.f90 +++ b/src/base64.f90 @@ -27,7 +27,7 @@ contains !-------------------------------------------------------------------------------------------------- subroutine base64_init - print'(/,a)', ' <<<+- base64 init -+>>>'; flush(6) + print'(/,a)', ' <<<+- base64 init -+>>>'; flush(OUTPUT_UNIT) call selfTest diff --git a/src/config.f90 b/src/config.f90 index 50d4e96e8..dc395762f 100644 --- a/src/config.f90 +++ b/src/config.f90 @@ -35,7 +35,7 @@ contains !-------------------------------------------------------------------------------------------------- subroutine config_init - print'(/,a)', ' <<<+- config init -+>>>'; flush(6) + print'(/,a)', ' <<<+- config init -+>>>'; flush(OUTPUT_UNIT) call parse_material call parse_numerics @@ -59,7 +59,7 @@ subroutine parse_material inquire(file=fname,exist=fileExists) if(.not. fileExists) call IO_error(100,ext_msg=fname) endif - print*, 'reading '//fname; flush(6) + print*, 'reading '//fname; flush(OUTPUT_UNIT) config_material => YAML_parse_file(fname) end subroutine parse_material @@ -75,7 +75,7 @@ subroutine parse_numerics config_numerics => emptyDict inquire(file='numerics.yaml', exist=fexist) if (fexist) then - print*, 'reading numerics.yaml'; flush(6) + print*, 'reading numerics.yaml'; flush(OUTPUT_UNIT) config_numerics => YAML_parse_file('numerics.yaml') endif @@ -92,7 +92,7 @@ subroutine parse_debug config_debug => emptyDict inquire(file='debug.yaml', exist=fexist) fileExists: if (fexist) then - print*, 'reading debug.yaml'; flush(6) + print*, 'reading debug.yaml'; flush(OUTPUT_UNIT) config_debug => YAML_parse_file('debug.yaml') endif fileExists diff --git a/src/constitutive.f90 b/src/constitutive.f90 index 3b342e3e6..008579214 100644 --- a/src/constitutive.f90 +++ b/src/constitutive.f90 @@ -446,7 +446,7 @@ subroutine constitutive_init call damage_init call thermal_init - print'(/,a)', ' <<<+- constitutive init -+>>>'; flush(6) + print'(/,a)', ' <<<+- constitutive init -+>>>'; flush(OUTPUT_UNIT) constitutive_source_maxSizeDotState = 0 PhaseLoop2:do p = 1,phases%length diff --git a/src/constitutive_plastic_disloTungsten.f90 b/src/constitutive_plastic_disloTungsten.f90 index 2bf4fd48e..eb7297aca 100644 --- a/src/constitutive_plastic_disloTungsten.f90 +++ b/src/constitutive_plastic_disloTungsten.f90 @@ -100,7 +100,7 @@ module function plastic_disloTungsten_init() result(myPlasticity) myPlasticity = plastic_active('disloTungsten') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return print*, 'Cereceda et al., International Journal of Plasticity 78:242–256, 2016' diff --git a/src/constitutive_plastic_dislotwin.f90 b/src/constitutive_plastic_dislotwin.f90 index a25815899..1b52862d4 100644 --- a/src/constitutive_plastic_dislotwin.f90 +++ b/src/constitutive_plastic_dislotwin.f90 @@ -147,7 +147,7 @@ module function plastic_dislotwin_init() result(myPlasticity) myPlasticity = plastic_active('dislotwin') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return print*, 'Ma and Roters, Acta Materialia 52(12):3603–3612, 2004' diff --git a/src/constitutive_plastic_isotropic.f90 b/src/constitutive_plastic_isotropic.f90 index c78d497d6..945c43cad 100644 --- a/src/constitutive_plastic_isotropic.f90 +++ b/src/constitutive_plastic_isotropic.f90 @@ -71,7 +71,7 @@ module function plastic_isotropic_init() result(myPlasticity) myPlasticity = plastic_active('isotropic') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return print*, 'Maiti and Eisenlohr, Scripta Materialia 145:37–40, 2018' diff --git a/src/constitutive_plastic_kinehardening.f90 b/src/constitutive_plastic_kinehardening.f90 index fe17b090e..86c1dc263 100644 --- a/src/constitutive_plastic_kinehardening.f90 +++ b/src/constitutive_plastic_kinehardening.f90 @@ -83,7 +83,7 @@ module function plastic_kinehardening_init() result(myPlasticity) myPlasticity = plastic_active('kinehardening') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return allocate(param(Ninstance)) diff --git a/src/constitutive_plastic_none.f90 b/src/constitutive_plastic_none.f90 index d62a798cc..2b0da4c9f 100644 --- a/src/constitutive_plastic_none.f90 +++ b/src/constitutive_plastic_none.f90 @@ -35,7 +35,7 @@ module function plastic_none_init() result(myPlasticity) enddo Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return do p = 1, phases%length diff --git a/src/constitutive_plastic_nonlocal.f90 b/src/constitutive_plastic_nonlocal.f90 index 81e1887c6..f0b62eb58 100644 --- a/src/constitutive_plastic_nonlocal.f90 +++ b/src/constitutive_plastic_nonlocal.f90 @@ -189,7 +189,7 @@ module function plastic_nonlocal_init() result(myPlasticity) myPlasticity = plastic_active('nonlocal') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) then call geometry_plastic_nonlocal_disable return diff --git a/src/constitutive_plastic_phenopowerlaw.f90 b/src/constitutive_plastic_phenopowerlaw.f90 index b30a4d9df..adb827a02 100644 --- a/src/constitutive_plastic_phenopowerlaw.f90 +++ b/src/constitutive_plastic_phenopowerlaw.f90 @@ -92,7 +92,7 @@ module function plastic_phenopowerlaw_init() result(myPlasticity) myPlasticity = plastic_active('phenopowerlaw') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return allocate(param(Ninstance)) diff --git a/src/crystallite.f90 b/src/crystallite.f90 index 2ee85024b..850b369a2 100644 --- a/src/crystallite.f90 +++ b/src/crystallite.f90 @@ -294,7 +294,7 @@ subroutine crystallite_init print'(a42,1x,i10)', ' # of elements: ', eMax print'(a42,1x,i10)', ' # of integration points/element: ', iMax print'(a42,1x,i10)', 'max # of constituents/integration point: ', cMax - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -1561,7 +1561,7 @@ subroutine crystallite_restartWrite integer(HID_T) :: fileHandle, groupHandle character(len=pStringLen) :: fileName, datasetName - print*, ' writing field and constitutive data required for restart to file';flush(6) + print*, ' writing field and constitutive data required for restart to file';flush(OUTPUT_UNIT) write(fileName,'(a,i0,a)') trim(getSolverJobName())//'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'a') diff --git a/src/damage_local.f90 b/src/damage_local.f90 index 3588010b2..d9c6e2d22 100644 --- a/src/damage_local.f90 +++ b/src/damage_local.f90 @@ -49,7 +49,7 @@ subroutine damage_local_init homog, & homogDamage - print'(/,a)', ' <<<+- damage_local init -+>>>'; flush(6) + print'(/,a)', ' <<<+- damage_local init -+>>>'; flush(OUTPUT_UNIT) !---------------------------------------------------------------------------------------------- ! read numerics parameter and do sanity check diff --git a/src/element.f90 b/src/element.f90 index 3ccc2fb78..2a2e81d00 100644 --- a/src/element.f90 +++ b/src/element.f90 @@ -922,7 +922,7 @@ subroutine tElement_init(self,elemType) self%nIPneighbors = size(self%IPneighbor,1) - print'(/,a)', ' <<<+- element_init -+>>>'; flush(6) + print'(/,a)', ' <<<+- element_init -+>>>'; flush(OUTPUT_UNIT) print*, 'element type: ',self%elemType print*, ' geom type: ',self%geomType diff --git a/src/homogenization.f90 b/src/homogenization.f90 index cc8df77f4..1c2b9bc38 100644 --- a/src/homogenization.f90 +++ b/src/homogenization.f90 @@ -186,7 +186,7 @@ subroutine homogenization_init materialpoint_F = materialpoint_F0 ! initialize to identity allocate(materialpoint_P(3,3,discretization_nIP,discretization_nElem), source=0.0_pReal) - print'(/,a)', ' <<<+- homogenization init -+>>>'; flush(6) + print'(/,a)', ' <<<+- homogenization init -+>>>'; flush(OUTPUT_UNIT) num%nMPstate = num_homogGeneric%get_asInt ('nMPstate', defaultVal=10) num%subStepMinHomog = num_homogGeneric%get_asFloat('subStepMin', defaultVal=1.0e-3_pReal) diff --git a/src/homogenization_mech_RGC.f90 b/src/homogenization_mech_RGC.f90 index cdd7c05dd..d954b0b9f 100644 --- a/src/homogenization_mech_RGC.f90 +++ b/src/homogenization_mech_RGC.f90 @@ -95,7 +95,7 @@ module subroutine mech_RGC_init(num_homogMech) print'(/,a)', ' <<<+- homogenization_mech_rgc init -+>>>' Ninstance = count(homogenization_type == HOMOGENIZATION_RGC_ID) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) print*, 'Tjahjanto et al., International Journal of Material Forming 2(1):939–942, 2009' print*, 'https://doi.org/10.1007/s12289-009-0619-1'//IO_EOL @@ -247,7 +247,7 @@ module subroutine mech_RGC_partitionDeformation(F,avgF,instance,of) print'(1x,3(e15.8,1x))',(F(i,j,iGrain), j = 1,3) enddo print*,' ' - flush(6) + flush(OUTPUT_UNIT) endif #endif enddo @@ -376,7 +376,7 @@ module procedure mech_RGC_updateState '@ grain ',stresLoc(3),' in component ',stresLoc(1),stresLoc(2) print'(a,e15.8,a,i3,a,i2)',' Max residual: ',residMax, & ' @ iface ',residLoc(1),' in direction ',residLoc(2) - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -388,7 +388,7 @@ module procedure mech_RGC_updateState mech_RGC_updateState = .true. #ifdef DEBUG if (debugHomog%extensive .and. prm%of_debug == of) & - print*, '... done and happy'; flush(6) + print*, '... done and happy'; flush(OUTPUT_UNIT) #endif !-------------------------------------------------------------------------------------------------- @@ -416,7 +416,7 @@ module procedure mech_RGC_updateState print'(a,e15.8,/)', ' Volume discrepancy: ', dst%volumeDiscrepancy(of) print'(a,e15.8)', ' Maximum relaxation rate: ', dst%relaxationRate_max(of) print'(a,e15.8,/)', ' Average relaxation rate: ', dst%relaxationRate_avg(of) - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -429,7 +429,7 @@ module procedure mech_RGC_updateState #ifdef DEBUG if (debugHomog%extensive .and. prm%of_debug == of) & - print'(a,/)', ' ... broken'; flush(6) + print'(a,/)', ' ... broken'; flush(OUTPUT_UNIT) #endif return @@ -437,7 +437,7 @@ module procedure mech_RGC_updateState else ! proceed with computing the Jacobian and state update #ifdef DEBUG if (debugHomog%extensive .and. prm%of_debug == of) & - print'(a,/)', ' ... not yet done'; flush(6) + print'(a,/)', ' ... not yet done'; flush(OUTPUT_UNIT) #endif endif @@ -499,7 +499,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(smatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -559,7 +559,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(pmatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -578,7 +578,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(rmatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -593,7 +593,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(jmatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -609,7 +609,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(jnverse(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(6) + flush(OUTPUT_UNIT) endif #endif @@ -625,7 +625,7 @@ module procedure mech_RGC_updateState !$OMP CRITICAL (write2out) print'(a,i3,a,i3,a)',' RGC_updateState: ip ',ip,' | el ',el,' enforces cutback' print'(a,e15.8)',' due to large relaxation change = ',maxval(abs(drelax)) - flush(6) + flush(OUTPUT_UNIT) !$OMP END CRITICAL (write2out) endif @@ -636,7 +636,7 @@ module procedure mech_RGC_updateState print'(1x,2(e15.8,1x))', stt%relaxationVector(i,of) enddo print*,' ' - flush(6) + flush(OUTPUT_UNIT) endif #endif diff --git a/src/homogenization_mech_isostrain.f90 b/src/homogenization_mech_isostrain.f90 index 6c5f50b99..eefb3ad64 100644 --- a/src/homogenization_mech_isostrain.f90 +++ b/src/homogenization_mech_isostrain.f90 @@ -40,7 +40,7 @@ module subroutine mech_isostrain_init print'(/,a)', ' <<<+- homogenization_mech_isostrain init -+>>>' Ninstance = count(homogenization_type == HOMOGENIZATION_ISOSTRAIN_ID) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) allocate(param(Ninstance)) ! one container of parameters per instance diff --git a/src/homogenization_mech_none.f90 b/src/homogenization_mech_none.f90 index d9426ef50..52143a3d2 100644 --- a/src/homogenization_mech_none.f90 +++ b/src/homogenization_mech_none.f90 @@ -21,7 +21,7 @@ module subroutine mech_none_init print'(/,a)', ' <<<+- homogenization_mech_none init -+>>>' Ninstance = count(homogenization_type == HOMOGENIZATION_NONE_ID) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) do h = 1, size(homogenization_type) if (homogenization_type(h) /= HOMOGENIZATION_NONE_ID) cycle diff --git a/src/kinematics_cleavage_opening.f90 b/src/kinematics_cleavage_opening.f90 index d8f25f8b8..37513d0e1 100644 --- a/src/kinematics_cleavage_opening.f90 +++ b/src/kinematics_cleavage_opening.f90 @@ -49,7 +49,7 @@ module function kinematics_cleavage_opening_init(kinematics_length) result(myKin myKinematics = kinematics_active('cleavage_opening',kinematics_length) Ninstance = count(myKinematics) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/kinematics_slipplane_opening.f90 b/src/kinematics_slipplane_opening.f90 index 3b04e37c1..46ff59da5 100644 --- a/src/kinematics_slipplane_opening.f90 +++ b/src/kinematics_slipplane_opening.f90 @@ -52,7 +52,7 @@ module function kinematics_slipplane_opening_init(kinematics_length) result(myKi myKinematics = kinematics_active('slipplane_opening',kinematics_length) Ninstance = count(myKinematics) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/kinematics_thermal_expansion.f90 b/src/kinematics_thermal_expansion.f90 index 652713aa4..d3516862d 100644 --- a/src/kinematics_thermal_expansion.f90 +++ b/src/kinematics_thermal_expansion.f90 @@ -42,7 +42,7 @@ module function kinematics_thermal_expansion_init(kinematics_length) result(myKi myKinematics = kinematics_active('thermal_expansion',kinematics_length) Ninstance = count(myKinematics) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/lattice.f90 b/src/lattice.f90 index d0ac07ed6..ba7631142 100644 --- a/src/lattice.f90 +++ b/src/lattice.f90 @@ -457,7 +457,7 @@ subroutine lattice_init phase, & elasticity - print'(/,a)', ' <<<+- lattice init -+>>>'; flush(6) + print'(/,a)', ' <<<+- lattice init -+>>>'; flush(OUTPUT_UNIT) phases => config_material%get('phase') Nphases = phases%length diff --git a/src/material.f90 b/src/material.f90 index f8e487b66..9bc2bbbc5 100644 --- a/src/material.f90 +++ b/src/material.f90 @@ -164,7 +164,7 @@ subroutine material_init(restart) material_homogenization character(len=pStringLen) :: sectionName - print'(/,a)', ' <<<+- material init -+>>>'; flush(6) + print'(/,a)', ' <<<+- material init -+>>>'; flush(OUTPUT_UNIT) phases => config_material%get('phase') allocate(material_name_phase(phases%length)) diff --git a/src/math.f90 b/src/math.f90 index b835a35b2..63e539e48 100644 --- a/src/math.f90 +++ b/src/math.f90 @@ -91,7 +91,7 @@ subroutine math_init class(tNode), pointer :: & num_generic - print'(/,a)', ' <<<+- math init -+>>>'; flush(6) + print'(/,a)', ' <<<+- math init -+>>>'; flush(OUTPUT_UNIT) num_generic => config_numerics%get('generic',defaultVal=emptyDict) randomSeed = num_generic%get_asInt('random_seed', defaultVal = 0) diff --git a/src/results.f90 b/src/results.f90 index 686183919..6dd84fb78 100644 --- a/src/results.f90 +++ b/src/results.f90 @@ -65,7 +65,7 @@ subroutine results_init(restart) character(len=pStringLen) :: commandLine - print'(/,a)', ' <<<+- results init -+>>>'; flush(6) + print'(/,a)', ' <<<+- results init -+>>>'; flush(OUTPUT_UNIT) print*, 'Diehl et al., Integrating Materials and Manufacturing Innovation 6(1):83–91, 2017' print*, 'https://doi.org/10.1007/s40192-017-0084-5'//IO_EOL diff --git a/src/rotations.f90 b/src/rotations.f90 index 72046a965..723cced61 100644 --- a/src/rotations.f90 +++ b/src/rotations.f90 @@ -104,7 +104,7 @@ contains subroutine rotations_init call quaternions_init - print'(/,a)', ' <<<+- rotations init -+>>>'; flush(6) + print'(/,a)', ' <<<+- rotations init -+>>>'; flush(OUTPUT_UNIT) print*, 'Rowenhorst et al., Modelling and Simulation in Materials Science and Engineering 23:083501, 2015' print*, 'https://doi.org/10.1088/0965-0393/23/8/083501' diff --git a/src/source_damage_anisoBrittle.f90 b/src/source_damage_anisoBrittle.f90 index 6dd58fe5b..5377f3373 100644 --- a/src/source_damage_anisoBrittle.f90 +++ b/src/source_damage_anisoBrittle.f90 @@ -53,7 +53,7 @@ module function source_damage_anisoBrittle_init(source_length) result(mySources) mySources = source_active('damage_anisoBrittle',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_damage_anisoDuctile.f90 b/src/source_damage_anisoDuctile.f90 index 37681a23f..abbd90ca3 100644 --- a/src/source_damage_anisoDuctile.f90 +++ b/src/source_damage_anisoDuctile.f90 @@ -47,7 +47,7 @@ module function source_damage_anisoDuctile_init(source_length) result(mySources) mySources = source_active('damage_anisoDuctile',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_damage_isoBrittle.f90 b/src/source_damage_isoBrittle.f90 index c6d0ada99..45f6abf3a 100644 --- a/src/source_damage_isoBrittle.f90 +++ b/src/source_damage_isoBrittle.f90 @@ -43,7 +43,7 @@ module function source_damage_isoBrittle_init(source_length) result(mySources) mySources = source_active('damage_isoBrittle',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_damage_isoDuctile.f90 b/src/source_damage_isoDuctile.f90 index 1c1c53fd0..e74f187de 100644 --- a/src/source_damage_isoDuctile.f90 +++ b/src/source_damage_isoDuctile.f90 @@ -45,7 +45,7 @@ module function source_damage_isoDuctile_init(source_length) result(mySources) mySources = source_active('damage_isoDuctile',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_thermal_dissipation.f90 b/src/source_thermal_dissipation.f90 index 60fde7f28..307d211b3 100644 --- a/src/source_thermal_dissipation.f90 +++ b/src/source_thermal_dissipation.f90 @@ -41,7 +41,7 @@ module function source_thermal_dissipation_init(source_length) result(mySources) mySources = source_active('thermal_dissipation',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_thermal_externalheat.f90 b/src/source_thermal_externalheat.f90 index e7bfea254..95d994e11 100644 --- a/src/source_thermal_externalheat.f90 +++ b/src/source_thermal_externalheat.f90 @@ -45,7 +45,7 @@ module function source_thermal_externalheat_init(source_length) result(mySources mySources = source_active('thermal_externalheat',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(6) + print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) if(Ninstance == 0) return phases => config_material%get('phase') From 53ce4e07d2d40ec381ada8195bf2e369d8d3a148 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Tue, 22 Sep 2020 13:02:33 +0200 Subject: [PATCH 45/61] forgotten renames in subfolders --- src/grid/DAMASK_grid.f90 | 24 +++++++-------- src/grid/discretization_grid.f90 | 2 +- src/grid/grid_damage_spectral.f90 | 4 +-- src/grid/grid_mech_FEM.f90 | 12 ++++---- src/grid/grid_mech_spectral_basic.f90 | 12 ++++---- src/grid/grid_mech_spectral_polarisation.f90 | 12 ++++---- src/grid/grid_thermal_spectral.f90 | 4 +-- src/grid/spectral_utilities.f90 | 32 ++++++++++---------- src/mesh/DAMASK_mesh.f90 | 6 ++-- src/mesh/FEM_utilities.f90 | 2 +- src/mesh/mesh_mech_FEM.f90 | 8 ++--- 11 files changed, 59 insertions(+), 59 deletions(-) diff --git a/src/grid/DAMASK_grid.f90 b/src/grid/DAMASK_grid.f90 index 213322278..03dfd2e77 100644 --- a/src/grid/DAMASK_grid.f90 +++ b/src/grid/DAMASK_grid.f90 @@ -99,7 +99,7 @@ program DAMASK_grid ! init DAMASK (all modules) call CPFEM_initAll - print'(/,a)', ' <<<+- DAMASK_spectral init -+>>>'; flush(6) + print'(/,a)', ' <<<+- DAMASK_spectral init -+>>>'; flush(OUTPUT_UNIT) print*, 'Shanthraj et al., Handbook of Mechanics of Materials, 2019' print*, 'https://doi.org/10.1007/978-981-10-6855-3_80' @@ -279,11 +279,11 @@ program DAMASK_grid endif do i = 1, 3; do j = 1, 3 if(newLoadCase%deformation%maskLogical(i,j)) then - write(6,'(2x,f12.7)',advance='no') newLoadCase%deformation%values(i,j) + write(OUTPUT_UNIT,'(2x,f12.7)',advance='no') newLoadCase%deformation%values(i,j) else - write(6,'(2x,12a)',advance='no') ' * ' + write(OUTPUT_UNIT,'(2x,12a)',advance='no') ' * ' endif - enddo; write(6,'(/)',advance='no') + enddo; write(OUTPUT_UNIT,'(/)',advance='no') enddo if (any(newLoadCase%stress%maskLogical .eqv. & newLoadCase%deformation%maskLogical)) errorID = 831 ! exclusive or masking only @@ -292,17 +292,17 @@ program DAMASK_grid print*, ' stress / GPa:' do i = 1, 3; do j = 1, 3 if(newLoadCase%stress%maskLogical(i,j)) then - write(6,'(2x,f12.7)',advance='no') newLoadCase%stress%values(i,j)*1e-9_pReal + write(OUTPUT_UNIT,'(2x,f12.7)',advance='no') newLoadCase%stress%values(i,j)*1e-9_pReal else - write(6,'(2x,12a)',advance='no') ' * ' + write(OUTPUT_UNIT,'(2x,12a)',advance='no') ' * ' endif - enddo; write(6,'(/)',advance='no') + enddo; write(OUTPUT_UNIT,'(/)',advance='no') enddo if (any(abs(matmul(newLoadCase%rot%asMatrix(), & transpose(newLoadCase%rot%asMatrix()))-math_I3) > & reshape(spread(tol_math_check,1,9),[ 3,3]))) errorID = 846 ! given rotation matrix contains strain if (any(dNeq(newLoadCase%rot%asMatrix(), math_I3))) & - write(6,'(2x,a,/,3(3(3x,f12.7,1x)/))',advance='no') 'rotation of loadframe:',& + write(OUTPUT_UNIT,'(2x,a,/,3(3(3x,f12.7,1x)/))',advance='no') 'rotation of loadframe:',& transpose(newLoadCase%rot%asMatrix()) if (newLoadCase%time < 0.0_pReal) errorID = 834 ! negative time increment print'(a,f0.3)', ' time: ', newLoadCase%time @@ -342,7 +342,7 @@ program DAMASK_grid open(newunit=statUnit,file=trim(getSolverJobName())//'.sta',form='FORMATTED',status='REPLACE') write(statUnit,'(a)') 'Increment Time CutbackLevel Converged IterationsNeeded' ! statistics file if (debug_grid%contains('basic')) print'(/,a)', ' header of statistics file written out' - flush(6) + flush(OUTPUT_UNIT) else writeHeader open(newunit=statUnit,file=trim(getSolverJobName())//& '.sta',form='FORMATTED', position='APPEND', status='OLD') @@ -405,7 +405,7 @@ program DAMASK_grid write(incInfo,'(4(a,i0))') & 'Increment ',totalIncsCounter,'/',sum(loadCases%incs),& '-', stepFraction,'/',subStepFactor**cutBackLevel - flush(6) + flush(OUTPUT_UNIT) !-------------------------------------------------------------------------------------------------- ! forward fields @@ -489,11 +489,11 @@ program DAMASK_grid print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' converged' else print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' NOT converged' - endif; flush(6) + endif; flush(OUTPUT_UNIT) if (mod(inc,loadCases(currentLoadCase)%outputFrequency) == 0) then ! at output frequency print'(1/,a)', ' ... writing results to file ......................................' - flush(6) + flush(OUTPUT_UNIT) call CPFEM_results(totalIncsCounter,time) endif if (mod(inc,loadCases(currentLoadCase)%restartFrequency) == 0) then diff --git a/src/grid/discretization_grid.f90 b/src/grid/discretization_grid.f90 index 576aaea60..32cd996db 100644 --- a/src/grid/discretization_grid.f90 +++ b/src/grid/discretization_grid.f90 @@ -65,7 +65,7 @@ subroutine discretization_grid_init(restart) integer(C_INTPTR_T) :: & devNull, z, z_offset - print'(/,a)', ' <<<+- discretization_grid init -+>>>'; flush(6) + print'(/,a)', ' <<<+- discretization_grid init -+>>>'; flush(OUTPUT_UNIT) if(index(interface_geomFile,'.vtr') /= 0) then call readVTR(grid,geomSize,origin,microstructureAt) diff --git a/src/grid/grid_damage_spectral.f90 b/src/grid/grid_damage_spectral.f90 index 2a0754c66..3d6a9c431 100644 --- a/src/grid/grid_damage_spectral.f90 +++ b/src/grid/grid_damage_spectral.f90 @@ -205,10 +205,10 @@ function grid_damage_spectral_solution(timeinc,timeinc_old) result(solution) call VecMax(solution_vec,devNull,phi_max,ierr); CHKERRQ(ierr) if (solution%converged) & print'(/,a)', ' ... nonlocal damage converged .....................................' - write(6,'(/,a,f8.6,2x,f8.6,2x,e11.4,/)',advance='no') ' Minimum|Maximum|Delta Damage = ',& + write(OUTPUT_UNIT,'(/,a,f8.6,2x,f8.6,2x,e11.4,/)',advance='no') ' Minimum|Maximum|Delta Damage = ',& phi_min, phi_max, stagNorm print'(/,a)', ' ===========================================================================' - flush(6) + flush(OUTPUT_UNIT) end function grid_damage_spectral_solution diff --git a/src/grid/grid_mech_FEM.f90 b/src/grid/grid_mech_FEM.f90 index 3923e1898..0fcb08480 100644 --- a/src/grid/grid_mech_FEM.f90 +++ b/src/grid/grid_mech_FEM.f90 @@ -122,7 +122,7 @@ subroutine grid_mech_FEM_init PetscScalar, pointer, dimension(:,:,:,:) :: & u_current,u_lastInc - print'(/,a)', ' <<<+- grid_mech_FEM init -+>>>'; flush(6) + print'(/,a)', ' <<<+- grid_mech_FEM init -+>>>'; flush(OUTPUT_UNIT) !----------------------------------------------------------------------------------------------- ! debugging options @@ -413,7 +413,7 @@ subroutine grid_mech_FEM_restartWrite call DMDAVecGetArrayF90(mech_grid,solution_current,u_current,ierr); CHKERRQ(ierr) call DMDAVecGetArrayF90(mech_grid,solution_lastInc,u_lastInc,ierr); CHKERRQ(ierr) - print*, 'writing solver data required for restart to file'; flush(6) + print*, 'writing solver data required for restart to file'; flush(OUTPUT_UNIT) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -481,7 +481,7 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,fnorm,reason,dummy,i print'(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' print'(/,a)', ' ===========================================================================' - flush(6) + flush(OUTPUT_UNIT) end subroutine converged @@ -517,11 +517,11 @@ subroutine formResidual(da_local,x_local, & totalIter = totalIter + 1 print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter+1, '≤', num%itmax if (debugRotation) & - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim =', transpose(F_aim) - flush(6) + flush(OUTPUT_UNIT) endif newIteration !-------------------------------------------------------------------------------------------------- diff --git a/src/grid/grid_mech_spectral_basic.f90 b/src/grid/grid_mech_spectral_basic.f90 index 14d317c73..819e9eded 100644 --- a/src/grid/grid_mech_spectral_basic.f90 +++ b/src/grid/grid_mech_spectral_basic.f90 @@ -109,7 +109,7 @@ subroutine grid_mech_spectral_basic_init character(len=pStringLen) :: & fileName - print'(/,a)', ' <<<+- grid_mech_spectral_basic init -+>>>'; flush(6) + print'(/,a)', ' <<<+- grid_mech_spectral_basic init -+>>>'; flush(OUTPUT_UNIT) print*, 'Eisenlohr et al., International Journal of Plasticity 46:37–53, 2013' print*, 'https://doi.org/10.1016/j.ijplas.2012.09.012'//IO_EOL @@ -375,7 +375,7 @@ subroutine grid_mech_spectral_basic_restartWrite call DMDAVecGetArrayF90(da,solution_vec,F,ierr); CHKERRQ(ierr) - print'(a)', ' writing solver data required for restart to file'; flush(6) + print'(a)', ' writing solver data required for restart to file'; flush(OUTPUT_UNIT) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -441,7 +441,7 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,devNull3,reason,dumm print'(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' print'(/,a)', ' ===========================================================================' - flush(6) + flush(OUTPUT_UNIT) end subroutine converged @@ -475,11 +475,11 @@ subroutine formResidual(in, F, & totalIter = totalIter + 1 print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax if (debugRotation) & - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim =', transpose(F_aim) - flush(6) + flush(OUTPUT_UNIT) endif newIteration !-------------------------------------------------------------------------------------------------- diff --git a/src/grid/grid_mech_spectral_polarisation.f90 b/src/grid/grid_mech_spectral_polarisation.f90 index f83ebed75..021c2291e 100644 --- a/src/grid/grid_mech_spectral_polarisation.f90 +++ b/src/grid/grid_mech_spectral_polarisation.f90 @@ -123,7 +123,7 @@ subroutine grid_mech_spectral_polarisation_init character(len=pStringLen) :: & fileName - print'(/,a)', ' <<<+- grid_mech_spectral_polarisation init -+>>>'; flush(6) + print'(/,a)', ' <<<+- grid_mech_spectral_polarisation init -+>>>'; flush(OUTPUT_UNIT) print*, 'Shanthraj et al., International Journal of Plasticity 66:31–45, 2015' print*, 'https://doi.org/10.1016/j.ijplas.2014.02.006' @@ -433,7 +433,7 @@ subroutine grid_mech_spectral_polarisation_restartWrite F => FandF_tau(0: 8,:,:,:) F_tau => FandF_tau(9:17,:,:,:) - print*, 'writing solver data required for restart to file'; flush(6) + print*, 'writing solver data required for restart to file'; flush(OUTPUT_UNIT) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -505,7 +505,7 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,devNull3,reason,dumm print '(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' print'(/,a)', ' ===========================================================================' - flush(6) + flush(OUTPUT_UNIT) end subroutine converged @@ -559,11 +559,11 @@ subroutine formResidual(in, FandF_tau, & totalIter = totalIter + 1 print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax if(debugRotation) & - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) - write(6,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim =', transpose(F_aim) - flush(6) + flush(OUTPUT_UNIT) endif newIteration !-------------------------------------------------------------------------------------------------- diff --git a/src/grid/grid_thermal_spectral.f90 b/src/grid/grid_thermal_spectral.f90 index eeff8c9d6..b12d67843 100644 --- a/src/grid/grid_thermal_spectral.f90 +++ b/src/grid/grid_thermal_spectral.f90 @@ -199,10 +199,10 @@ function grid_thermal_spectral_solution(timeinc,timeinc_old) result(solution) call VecMax(solution_vec,devNull,T_max,ierr); CHKERRQ(ierr) if (solution%converged) & print'(/,a)', ' ... thermal conduction converged ..................................' - write(6,'(/,a,f8.4,2x,f8.4,2x,f8.4,/)',advance='no') ' Minimum|Maximum|Delta Temperature / K = ',& + write(OUTPUT_UNIT,'(/,a,f8.4,2x,f8.4,2x,f8.4,/)',advance='no') ' Minimum|Maximum|Delta Temperature / K = ',& T_min, T_max, stagNorm print'(/,a)', ' ===========================================================================' - flush(6) + flush(OUTPUT_UNIT) end function grid_thermal_spectral_solution diff --git a/src/grid/spectral_utilities.f90 b/src/grid/spectral_utilities.f90 index 5e53fe2a5..bfd05b6f5 100644 --- a/src/grid/spectral_utilities.f90 +++ b/src/grid/spectral_utilities.f90 @@ -211,7 +211,7 @@ subroutine spectral_utilities_init if(debugPETSc) print'(3(/,a),/)', & ' Initializing PETSc with debug options: ', & trim(PETScDebug), & - ' add more using the PETSc_Options keyword in numerics.yaml '; flush(6) + ' add more using the PETSc_Options keyword in numerics.yaml '; flush(OUTPUT_UNIT) num_grid => config_numerics%get('grid',defaultVal=emptyDict) @@ -280,7 +280,7 @@ subroutine spectral_utilities_init if (pReal /= C_DOUBLE .or. kind(1) /= C_INT) error stop 'C and Fortran datatypes do not match' call fftw_set_timelimit(num_grid%get_asFloat('fftw_timelimit',defaultVal=-1.0_pReal)) - print*, 'FFTW initialized'; flush(6) + print*, 'FFTW initialized'; flush(OUTPUT_UNIT) !-------------------------------------------------------------------------------------------------- ! MPI allocation @@ -507,7 +507,7 @@ subroutine utilities_fourierGammaConvolution(fieldAim) print'(/,a)', ' ... doing gamma convolution ...............................................' - flush(6) + flush(OUTPUT_UNIT) !-------------------------------------------------------------------------------------------------- ! do the actual spectral method calculation (mechanical equilibrium) @@ -577,7 +577,7 @@ real(pReal) function utilities_divergenceRMS() complex(pReal), dimension(3) :: rescaledGeom print'(/,a)', ' ... calculating divergence ................................................' - flush(6) + flush(OUTPUT_UNIT) rescaledGeom = cmplx(geomSize/scaledGeomSize,0.0_pReal) @@ -621,7 +621,7 @@ real(pReal) function utilities_curlRMS() complex(pReal), dimension(3) :: rescaledGeom print'(/,a)', ' ... calculating curl ......................................................' - flush(6) + flush(OUTPUT_UNIT) rescaledGeom = cmplx(geomSize/scaledGeomSize,0.0_pReal) @@ -701,9 +701,9 @@ function utilities_maskedCompliance(rot_BC,mask_stress,C) if(debugGeneral) then print'(/,a)', ' ... updating masked compliance ............................................' - write(6,'(/,a,/,9(9(2x,f12.7,1x)/))',advance='no') ' Stiffness C (load) / GPa =',& + write(OUTPUT_UNIT,'(/,a,/,9(9(2x,f12.7,1x)/))',advance='no') ' Stiffness C (load) / GPa =',& transpose(temp99_Real)*1.0e-9_pReal - flush(6) + flush(OUTPUT_UNIT) endif do i = 1,9; do j = 1,9 @@ -723,9 +723,9 @@ function utilities_maskedCompliance(rot_BC,mask_stress,C) if (debugGeneral .or. errmatinv) then write(formatString, '(i2)') size_reduced formatString = '(/,a,/,'//trim(formatString)//'('//trim(formatString)//'(2x,es9.2,1x)/))' - write(6,trim(formatString),advance='no') ' C * S (load) ', & + write(OUTPUT_UNIT,trim(formatString),advance='no') ' C * S (load) ', & transpose(matmul(c_reduced,s_reduced)) - write(6,trim(formatString),advance='no') ' S (load) ', transpose(s_reduced) + write(OUTPUT_UNIT,trim(formatString),advance='no') ' S (load) ', transpose(s_reduced) if(errmatinv) call IO_error(error_ID=400,ext_msg='utilities_maskedCompliance') endif temp99_real = reshape(unpack(reshape(s_reduced,[size_reduced**2]),reshape(mask,[81]),0.0_pReal),[9,9]) @@ -736,9 +736,9 @@ function utilities_maskedCompliance(rot_BC,mask_stress,C) utilities_maskedCompliance = math_99to3333(temp99_Real) if(debugGeneral) then - write(6,'(/,a,/,9(9(2x,f10.5,1x)/),/)',advance='no') & + write(OUTPUT_UNIT,'(/,a,/,9(9(2x,f10.5,1x)/),/)',advance='no') & ' Masked Compliance (load) * GPa =', transpose(temp99_Real)*1.0e9_pReal - flush(6) + flush(OUTPUT_UNIT) endif end function utilities_maskedCompliance @@ -823,7 +823,7 @@ subroutine utilities_constitutiveResponse(P,P_av,C_volAvg,C_minmaxAvg,& real(pReal), dimension(2) :: valueAndRank !< pair of min/max norm of dPdF to synchronize min/max of dPdF print'(/,a)', ' ... evaluating constitutive response ......................................' - flush(6) + flush(OUTPUT_UNIT) materialpoint_F = reshape(F,[3,3,1,product(grid(1:2))*grid3]) ! set materialpoint target F to estimated field @@ -833,13 +833,13 @@ subroutine utilities_constitutiveResponse(P,P_av,C_volAvg,C_minmaxAvg,& P_av = sum(sum(sum(P,dim=5),dim=4),dim=3) * wgt ! average of P call MPI_Allreduce(MPI_IN_PLACE,P_av,9,MPI_DOUBLE,MPI_SUM,PETSC_COMM_WORLD,ierr) if (debugRotation) & - write(6,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress (lab) / MPa =',& + write(OUTPUT_UNIT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress (lab) / MPa =',& transpose(P_av)*1.e-6_pReal if(present(rotation_BC)) & P_av = rotation_BC%rotate(P_av) - write(6,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& + write(OUTPUT_UNIT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& transpose(P_av)*1.e-6_pReal - flush(6) + flush(OUTPUT_UNIT) dPdF_max = 0.0_pReal dPdF_norm_max = 0.0_pReal @@ -1095,7 +1095,7 @@ subroutine utilities_saveReferenceStiffness fileUnit,ierr if (worldrank == 0) then - print'(a)', ' writing reference stiffness data required for restart to file'; flush(6) + print'(a)', ' writing reference stiffness data required for restart to file'; flush(OUTPUT_UNIT) open(newunit=fileUnit, file=getSolverJobName()//'.C_ref',& status='replace',access='stream',action='write',iostat=ierr) if(ierr /=0) call IO_error(100,ext_msg='could not open file '//getSolverJobName()//'.C_ref') diff --git a/src/mesh/DAMASK_mesh.f90 b/src/mesh/DAMASK_mesh.f90 index 0ba56bef3..acee51394 100644 --- a/src/mesh/DAMASK_mesh.f90 +++ b/src/mesh/DAMASK_mesh.f90 @@ -78,7 +78,7 @@ program DAMASK_mesh !-------------------------------------------------------------------------------------------------- ! init DAMASK (all modules) call CPFEM_initAll - print'(/,a)', ' <<<+- DAMASK_mesh init -+>>>'; flush(6) + print'(/,a)', ' <<<+- DAMASK_mesh init -+>>>'; flush(OUTPUT_UNIT) !--------------------------------------------------------------------- ! reading field information from numerics file and do sanity checks @@ -299,7 +299,7 @@ program DAMASK_mesh write(incInfo,'(4(a,i0))') & 'Increment ',totalIncsCounter,'/',sum(loadCases%incs),& '-',stepFraction, '/', subStepFactor**cutBackLevel - flush(6) + flush(OUTPUT_UNIT) !-------------------------------------------------------------------------------------------------- ! forward fields @@ -363,7 +363,7 @@ program DAMASK_mesh print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' converged' else print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' NOT converged' - endif; flush(6) + endif; flush(OUTPUT_UNIT) if (mod(inc,loadCases(currentLoadCase)%outputFrequency) == 0) then ! at output frequency print'(/,a)', ' ... writing results to file ......................................' diff --git a/src/mesh/FEM_utilities.f90 b/src/mesh/FEM_utilities.f90 index 1e154e533..91e1bd5b6 100644 --- a/src/mesh/FEM_utilities.f90 +++ b/src/mesh/FEM_utilities.f90 @@ -122,7 +122,7 @@ subroutine FEM_utilities_init ' Initializing PETSc with debug options: ', & trim(PETScDebug), & ' add more using the PETSc_Options keyword in numerics.yaml ' - flush(6) + flush(OUTPUT_UNIT) call PetscOptionsClear(PETSC_NULL_OPTIONS,ierr) CHKERRQ(ierr) if(debugPETSc) call PetscOptionsInsertString(PETSC_NULL_OPTIONS,trim(PETSCDEBUG),ierr) diff --git a/src/mesh/mesh_mech_FEM.f90 b/src/mesh/mesh_mech_FEM.f90 index 6c8d4667d..f7a177929 100644 --- a/src/mesh/mesh_mech_FEM.f90 +++ b/src/mesh/mesh_mech_FEM.f90 @@ -110,7 +110,7 @@ subroutine FEM_mech_init(fieldBC) class(tNode), pointer :: & num_mesh - print'(/,a)', ' <<<+- FEM_mech init -+>>>'; flush(6) + print'(/,a)', ' <<<+- FEM_mech init -+>>>'; flush(OUTPUT_UNIT) !----------------------------------------------------------------------------- ! read numerical parametes and do sanity checks @@ -319,7 +319,7 @@ type(tSolutionState) function FEM_mech_solution( & endif print'(/,a)', ' ===========================================================================' - flush(6) + flush(OUTPUT_UNIT) end function FEM_mech_solution @@ -682,9 +682,9 @@ subroutine FEM_mech_converged(snes_local,PETScIter,xnorm,snorm,fnorm,reason,dumm print'(/,1x,a,a,i0,a,i0,f0.3)', trim(incInfo), & ' @ Iteration ',PETScIter,' mechanical residual norm = ', & int(fnorm/divTol),fnorm/divTol-int(fnorm/divTol) - write(6,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& + write(OUTPUT_UNIT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& transpose(P_av)*1.e-6_pReal - flush(6) + flush(OUTPUT_UNIT) end subroutine FEM_mech_converged From 41fbc58c1b0b45c6584e27e1990fcb53be725b60 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Tue, 22 Sep 2020 13:09:12 +0200 Subject: [PATCH 46/61] standard conforming name --- src/CPFEM.f90 | 6 +- src/CPFEM2.f90 | 2 +- src/IO.f90 | 60 ++++++++++---------- src/base64.f90 | 2 +- src/config.f90 | 8 +-- src/constitutive.f90 | 2 +- src/constitutive_plastic_disloTungsten.f90 | 2 +- src/constitutive_plastic_dislotwin.f90 | 2 +- src/constitutive_plastic_isotropic.f90 | 2 +- src/constitutive_plastic_kinehardening.f90 | 2 +- src/constitutive_plastic_none.f90 | 2 +- src/constitutive_plastic_nonlocal.f90 | 2 +- src/constitutive_plastic_phenopowerlaw.f90 | 2 +- src/crystallite.f90 | 4 +- src/damage_local.f90 | 2 +- src/element.f90 | 2 +- src/grid/DAMASK_grid.f90 | 24 ++++---- src/grid/discretization_grid.f90 | 2 +- src/grid/grid_damage_spectral.f90 | 4 +- src/grid/grid_mech_FEM.f90 | 12 ++-- src/grid/grid_mech_spectral_basic.f90 | 12 ++-- src/grid/grid_mech_spectral_polarisation.f90 | 12 ++-- src/grid/grid_thermal_spectral.f90 | 4 +- src/grid/spectral_utilities.f90 | 32 +++++------ src/homogenization.f90 | 2 +- src/homogenization_mech_RGC.f90 | 28 ++++----- src/homogenization_mech_isostrain.f90 | 2 +- src/homogenization_mech_none.f90 | 2 +- src/kinematics_cleavage_opening.f90 | 2 +- src/kinematics_slipplane_opening.f90 | 2 +- src/kinematics_thermal_expansion.f90 | 2 +- src/lattice.f90 | 2 +- src/material.f90 | 2 +- src/math.f90 | 2 +- src/mesh/DAMASK_mesh.f90 | 6 +- src/mesh/FEM_utilities.f90 | 2 +- src/mesh/mesh_mech_FEM.f90 | 8 +-- src/results.f90 | 2 +- src/rotations.f90 | 2 +- src/source_damage_anisoBrittle.f90 | 2 +- src/source_damage_anisoDuctile.f90 | 2 +- src/source_damage_isoBrittle.f90 | 2 +- src/source_damage_isoDuctile.f90 | 2 +- src/source_thermal_dissipation.f90 | 2 +- src/source_thermal_externalheat.f90 | 2 +- 45 files changed, 141 insertions(+), 141 deletions(-) diff --git a/src/CPFEM.f90 b/src/CPFEM.f90 index 09e028f6c..05255e2a1 100644 --- a/src/CPFEM.f90 +++ b/src/CPFEM.f90 @@ -106,7 +106,7 @@ subroutine CPFEM_init num_commercialFEM, & debug_CPFEM - print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(IO_STDOUT) allocate(CPFEM_cs( 6,discretization_nIP,discretization_nElem), source= 0.0_pReal) allocate(CPFEM_dcsdE( 6,6,discretization_nIP,discretization_nElem), source= 0.0_pReal) @@ -132,7 +132,7 @@ subroutine CPFEM_init print'(a32,1x,6(i8,1x))', 'CPFEM_cs: ', shape(CPFEM_cs) print'(a32,1x,6(i8,1x))', 'CPFEM_dcsdE: ', shape(CPFEM_dcsdE) print'(a32,1x,6(i8,1x),/)', 'CPFEM_dcsdE_knownGood: ', shape(CPFEM_dcsdE_knownGood) - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif end subroutine CPFEM_init @@ -250,7 +250,7 @@ subroutine CPFEM_general(mode, ffn, ffn1, temperature_inp, dt, elFE, ip, cauchyS '<< CPFEM >> stress/MPa at elFE ip ', elFE, ip, CPFEM_cs(1:6,ip,elCP)*1.0e-6_pReal print'(a,i8,1x,i2,/,6(12x,6(f10.3,1x)/))', & '<< CPFEM >> Jacobian/GPa at elFE ip ', elFE, ip, transpose(CPFEM_dcsdE(1:6,1:6,ip,elCP))*1.0e-9_pReal - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif endif diff --git a/src/CPFEM2.f90 b/src/CPFEM2.f90 index fc68778c8..fed43ba78 100644 --- a/src/CPFEM2.f90 +++ b/src/CPFEM2.f90 @@ -76,7 +76,7 @@ end subroutine CPFEM_initAll !-------------------------------------------------------------------------------------------------- subroutine CPFEM_init - print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- CPFEM init -+>>>'; flush(IO_STDOUT) if (interface_restartInc > 0) call crystallite_restartRead diff --git a/src/IO.f90 b/src/IO.f90 index 72eb2011f..f9e708ead 100644 --- a/src/IO.f90 +++ b/src/IO.f90 @@ -7,8 +7,8 @@ !-------------------------------------------------------------------------------------------------- module IO use, intrinsic :: ISO_fortran_env, only: & - OUTPUT_UNIT, & - ERROR_UNIT + IO_STDOUT => OUTPUT_UNIT, & + IO_STDERR => ERROR_UNIT use prec @@ -20,7 +20,7 @@ module IO character, parameter, public :: & IO_EOL = new_line('DAMASK'), & !< end of line character IO_COMMENT = '#' - character(len=*), parameter, private :: & + character(len=*), parameter :: & IO_DIVIDER = '───────────────────'//& '───────────────────'//& '───────────────────'//& @@ -42,7 +42,7 @@ module IO IO_stringAsBool, & IO_error, & IO_warning, & - OUTPUT_UNIT + IO_STDOUT contains @@ -52,7 +52,7 @@ contains !-------------------------------------------------------------------------------------------------- subroutine IO_init - print'(/,a)', ' <<<+- IO init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- IO init -+>>>'; flush(IO_STDOUT) call selfTest @@ -543,29 +543,29 @@ subroutine IO_error(error_ID,el,ip,g,instance,ext_msg) end select !$OMP CRITICAL (write2out) - write(ERROR_UNIT,'(/,a)') ' ┌'//IO_DIVIDER//'┐' - write(ERROR_UNIT,'(a,24x,a,40x,a)') ' │','error', '│' - write(ERROR_UNIT,'(a,24x,i3,42x,a)') ' │',error_ID, '│' - write(ERROR_UNIT,'(a)') ' ├'//IO_DIVIDER//'┤' + write(IO_STDERR,'(/,a)') ' ┌'//IO_DIVIDER//'┐' + write(IO_STDERR,'(a,24x,a,40x,a)') ' │','error', '│' + write(IO_STDERR,'(a,24x,i3,42x,a)') ' │',error_ID, '│' + write(IO_STDERR,'(a)') ' ├'//IO_DIVIDER//'┤' write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(msg)),',',& max(1,72-len_trim(msg)-4),'x,a)' - write(ERROR_UNIT,formatString) '│ ',trim(msg), '│' + write(IO_STDERR,formatString) '│ ',trim(msg), '│' if (present(ext_msg)) then write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(ext_msg)),',',& max(1,72-len_trim(ext_msg)-4),'x,a)' - write(ERROR_UNIT,formatString) '│ ',trim(ext_msg), '│' + write(IO_STDERR,formatString) '│ ',trim(ext_msg), '│' endif if (present(el)) & - write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' + write(IO_STDERR,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' if (present(ip)) & - write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' + write(IO_STDERR,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' if (present(g)) & - write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' + write(IO_STDERR,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' if (present(instance)) & - write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at instance ',instance, '│' - write(ERROR_UNIT,'(a,69x,a)') ' │', '│' - write(ERROR_UNIT,'(a)') ' └'//IO_DIVIDER//'┘' - flush(ERROR_UNIT) + write(IO_STDERR,'(a19,1x,i9,44x,a3)') ' │ at instance ',instance, '│' + write(IO_STDERR,'(a,69x,a)') ' │', '│' + write(IO_STDERR,'(a)') ' └'//IO_DIVIDER//'┘' + flush(IO_STDERR) call quit(9000+error_ID) !$OMP END CRITICAL (write2out) @@ -628,27 +628,27 @@ subroutine IO_warning(warning_ID,el,ip,g,ext_msg) end select !$OMP CRITICAL (write2out) - write(ERROR_UNIT,'(/,a)') ' ┌'//IO_DIVIDER//'┐' - write(ERROR_UNIT,'(a,24x,a,38x,a)') ' │','warning', '│' - write(ERROR_UNIT,'(a,24x,i3,42x,a)') ' │',warning_ID, '│' - write(ERROR_UNIT,'(a)') ' ├'//IO_DIVIDER//'┤' + write(IO_STDERR,'(/,a)') ' ┌'//IO_DIVIDER//'┐' + write(IO_STDERR,'(a,24x,a,38x,a)') ' │','warning', '│' + write(IO_STDERR,'(a,24x,i3,42x,a)') ' │',warning_ID, '│' + write(IO_STDERR,'(a)') ' ├'//IO_DIVIDER//'┤' write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(msg)),',',& max(1,72-len_trim(msg)-4),'x,a)' - write(ERROR_UNIT,formatString) '│ ',trim(msg), '│' + write(IO_STDERR,formatString) '│ ',trim(msg), '│' if (present(ext_msg)) then write(formatString,'(a,i6.6,a,i6.6,a)') '(1x,a4,a',max(1,len_trim(ext_msg)),',',& max(1,72-len_trim(ext_msg)-4),'x,a)' - write(ERROR_UNIT,formatString) '│ ',trim(ext_msg), '│' + write(IO_STDERR,formatString) '│ ',trim(ext_msg), '│' endif if (present(el)) & - write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' + write(IO_STDERR,'(a19,1x,i9,44x,a3)') ' │ at element ',el, '│' if (present(ip)) & - write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' + write(IO_STDERR,'(a19,1x,i9,44x,a3)') ' │ at IP ',ip, '│' if (present(g)) & - write(ERROR_UNIT,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' - write(ERROR_UNIT,'(a,69x,a)') ' │', '│' - write(ERROR_UNIT,'(a)') ' └'//IO_DIVIDER//'┘' - flush(ERROR_UNIT) + write(IO_STDERR,'(a19,1x,i9,44x,a3)') ' │ at constituent',g, '│' + write(IO_STDERR,'(a,69x,a)') ' │', '│' + write(IO_STDERR,'(a)') ' └'//IO_DIVIDER//'┘' + flush(IO_STDERR) !$OMP END CRITICAL (write2out) end subroutine IO_warning diff --git a/src/base64.f90 b/src/base64.f90 index c04221f21..2f91334b7 100644 --- a/src/base64.f90 +++ b/src/base64.f90 @@ -27,7 +27,7 @@ contains !-------------------------------------------------------------------------------------------------- subroutine base64_init - print'(/,a)', ' <<<+- base64 init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- base64 init -+>>>'; flush(IO_STDOUT) call selfTest diff --git a/src/config.f90 b/src/config.f90 index dc395762f..b10edf013 100644 --- a/src/config.f90 +++ b/src/config.f90 @@ -35,7 +35,7 @@ contains !-------------------------------------------------------------------------------------------------- subroutine config_init - print'(/,a)', ' <<<+- config init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- config init -+>>>'; flush(IO_STDOUT) call parse_material call parse_numerics @@ -59,7 +59,7 @@ subroutine parse_material inquire(file=fname,exist=fileExists) if(.not. fileExists) call IO_error(100,ext_msg=fname) endif - print*, 'reading '//fname; flush(OUTPUT_UNIT) + print*, 'reading '//fname; flush(IO_STDOUT) config_material => YAML_parse_file(fname) end subroutine parse_material @@ -75,7 +75,7 @@ subroutine parse_numerics config_numerics => emptyDict inquire(file='numerics.yaml', exist=fexist) if (fexist) then - print*, 'reading numerics.yaml'; flush(OUTPUT_UNIT) + print*, 'reading numerics.yaml'; flush(IO_STDOUT) config_numerics => YAML_parse_file('numerics.yaml') endif @@ -92,7 +92,7 @@ subroutine parse_debug config_debug => emptyDict inquire(file='debug.yaml', exist=fexist) fileExists: if (fexist) then - print*, 'reading debug.yaml'; flush(OUTPUT_UNIT) + print*, 'reading debug.yaml'; flush(IO_STDOUT) config_debug => YAML_parse_file('debug.yaml') endif fileExists diff --git a/src/constitutive.f90 b/src/constitutive.f90 index 008579214..62846359d 100644 --- a/src/constitutive.f90 +++ b/src/constitutive.f90 @@ -446,7 +446,7 @@ subroutine constitutive_init call damage_init call thermal_init - print'(/,a)', ' <<<+- constitutive init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- constitutive init -+>>>'; flush(IO_STDOUT) constitutive_source_maxSizeDotState = 0 PhaseLoop2:do p = 1,phases%length diff --git a/src/constitutive_plastic_disloTungsten.f90 b/src/constitutive_plastic_disloTungsten.f90 index eb7297aca..98a9ce2f6 100644 --- a/src/constitutive_plastic_disloTungsten.f90 +++ b/src/constitutive_plastic_disloTungsten.f90 @@ -100,7 +100,7 @@ module function plastic_disloTungsten_init() result(myPlasticity) myPlasticity = plastic_active('disloTungsten') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return print*, 'Cereceda et al., International Journal of Plasticity 78:242–256, 2016' diff --git a/src/constitutive_plastic_dislotwin.f90 b/src/constitutive_plastic_dislotwin.f90 index 1b52862d4..4890316b8 100644 --- a/src/constitutive_plastic_dislotwin.f90 +++ b/src/constitutive_plastic_dislotwin.f90 @@ -147,7 +147,7 @@ module function plastic_dislotwin_init() result(myPlasticity) myPlasticity = plastic_active('dislotwin') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return print*, 'Ma and Roters, Acta Materialia 52(12):3603–3612, 2004' diff --git a/src/constitutive_plastic_isotropic.f90 b/src/constitutive_plastic_isotropic.f90 index 945c43cad..477938145 100644 --- a/src/constitutive_plastic_isotropic.f90 +++ b/src/constitutive_plastic_isotropic.f90 @@ -71,7 +71,7 @@ module function plastic_isotropic_init() result(myPlasticity) myPlasticity = plastic_active('isotropic') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return print*, 'Maiti and Eisenlohr, Scripta Materialia 145:37–40, 2018' diff --git a/src/constitutive_plastic_kinehardening.f90 b/src/constitutive_plastic_kinehardening.f90 index 86c1dc263..55e482db6 100644 --- a/src/constitutive_plastic_kinehardening.f90 +++ b/src/constitutive_plastic_kinehardening.f90 @@ -83,7 +83,7 @@ module function plastic_kinehardening_init() result(myPlasticity) myPlasticity = plastic_active('kinehardening') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return allocate(param(Ninstance)) diff --git a/src/constitutive_plastic_none.f90 b/src/constitutive_plastic_none.f90 index 2b0da4c9f..ab5f32d3f 100644 --- a/src/constitutive_plastic_none.f90 +++ b/src/constitutive_plastic_none.f90 @@ -35,7 +35,7 @@ module function plastic_none_init() result(myPlasticity) enddo Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return do p = 1, phases%length diff --git a/src/constitutive_plastic_nonlocal.f90 b/src/constitutive_plastic_nonlocal.f90 index f0b62eb58..21523161b 100644 --- a/src/constitutive_plastic_nonlocal.f90 +++ b/src/constitutive_plastic_nonlocal.f90 @@ -189,7 +189,7 @@ module function plastic_nonlocal_init() result(myPlasticity) myPlasticity = plastic_active('nonlocal') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) then call geometry_plastic_nonlocal_disable return diff --git a/src/constitutive_plastic_phenopowerlaw.f90 b/src/constitutive_plastic_phenopowerlaw.f90 index adb827a02..8cf63a54d 100644 --- a/src/constitutive_plastic_phenopowerlaw.f90 +++ b/src/constitutive_plastic_phenopowerlaw.f90 @@ -92,7 +92,7 @@ module function plastic_phenopowerlaw_init() result(myPlasticity) myPlasticity = plastic_active('phenopowerlaw') Ninstance = count(myPlasticity) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return allocate(param(Ninstance)) diff --git a/src/crystallite.f90 b/src/crystallite.f90 index 850b369a2..392dba277 100644 --- a/src/crystallite.f90 +++ b/src/crystallite.f90 @@ -294,7 +294,7 @@ subroutine crystallite_init print'(a42,1x,i10)', ' # of elements: ', eMax print'(a42,1x,i10)', ' # of integration points/element: ', iMax print'(a42,1x,i10)', 'max # of constituents/integration point: ', cMax - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -1561,7 +1561,7 @@ subroutine crystallite_restartWrite integer(HID_T) :: fileHandle, groupHandle character(len=pStringLen) :: fileName, datasetName - print*, ' writing field and constitutive data required for restart to file';flush(OUTPUT_UNIT) + print*, ' writing field and constitutive data required for restart to file';flush(IO_STDOUT) write(fileName,'(a,i0,a)') trim(getSolverJobName())//'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'a') diff --git a/src/damage_local.f90 b/src/damage_local.f90 index d9c6e2d22..af2532184 100644 --- a/src/damage_local.f90 +++ b/src/damage_local.f90 @@ -49,7 +49,7 @@ subroutine damage_local_init homog, & homogDamage - print'(/,a)', ' <<<+- damage_local init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- damage_local init -+>>>'; flush(IO_STDOUT) !---------------------------------------------------------------------------------------------- ! read numerics parameter and do sanity check diff --git a/src/element.f90 b/src/element.f90 index 2a2e81d00..722a7fd96 100644 --- a/src/element.f90 +++ b/src/element.f90 @@ -922,7 +922,7 @@ subroutine tElement_init(self,elemType) self%nIPneighbors = size(self%IPneighbor,1) - print'(/,a)', ' <<<+- element_init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- element_init -+>>>'; flush(IO_STDOUT) print*, 'element type: ',self%elemType print*, ' geom type: ',self%geomType diff --git a/src/grid/DAMASK_grid.f90 b/src/grid/DAMASK_grid.f90 index 03dfd2e77..8158996d6 100644 --- a/src/grid/DAMASK_grid.f90 +++ b/src/grid/DAMASK_grid.f90 @@ -99,7 +99,7 @@ program DAMASK_grid ! init DAMASK (all modules) call CPFEM_initAll - print'(/,a)', ' <<<+- DAMASK_spectral init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- DAMASK_spectral init -+>>>'; flush(IO_STDOUT) print*, 'Shanthraj et al., Handbook of Mechanics of Materials, 2019' print*, 'https://doi.org/10.1007/978-981-10-6855-3_80' @@ -279,11 +279,11 @@ program DAMASK_grid endif do i = 1, 3; do j = 1, 3 if(newLoadCase%deformation%maskLogical(i,j)) then - write(OUTPUT_UNIT,'(2x,f12.7)',advance='no') newLoadCase%deformation%values(i,j) + write(IO_STDOUT,'(2x,f12.7)',advance='no') newLoadCase%deformation%values(i,j) else - write(OUTPUT_UNIT,'(2x,12a)',advance='no') ' * ' + write(IO_STDOUT,'(2x,12a)',advance='no') ' * ' endif - enddo; write(OUTPUT_UNIT,'(/)',advance='no') + enddo; write(IO_STDOUT,'(/)',advance='no') enddo if (any(newLoadCase%stress%maskLogical .eqv. & newLoadCase%deformation%maskLogical)) errorID = 831 ! exclusive or masking only @@ -292,17 +292,17 @@ program DAMASK_grid print*, ' stress / GPa:' do i = 1, 3; do j = 1, 3 if(newLoadCase%stress%maskLogical(i,j)) then - write(OUTPUT_UNIT,'(2x,f12.7)',advance='no') newLoadCase%stress%values(i,j)*1e-9_pReal + write(IO_STDOUT,'(2x,f12.7)',advance='no') newLoadCase%stress%values(i,j)*1e-9_pReal else - write(OUTPUT_UNIT,'(2x,12a)',advance='no') ' * ' + write(IO_STDOUT,'(2x,12a)',advance='no') ' * ' endif - enddo; write(OUTPUT_UNIT,'(/)',advance='no') + enddo; write(IO_STDOUT,'(/)',advance='no') enddo if (any(abs(matmul(newLoadCase%rot%asMatrix(), & transpose(newLoadCase%rot%asMatrix()))-math_I3) > & reshape(spread(tol_math_check,1,9),[ 3,3]))) errorID = 846 ! given rotation matrix contains strain if (any(dNeq(newLoadCase%rot%asMatrix(), math_I3))) & - write(OUTPUT_UNIT,'(2x,a,/,3(3(3x,f12.7,1x)/))',advance='no') 'rotation of loadframe:',& + write(IO_STDOUT,'(2x,a,/,3(3(3x,f12.7,1x)/))',advance='no') 'rotation of loadframe:',& transpose(newLoadCase%rot%asMatrix()) if (newLoadCase%time < 0.0_pReal) errorID = 834 ! negative time increment print'(a,f0.3)', ' time: ', newLoadCase%time @@ -342,7 +342,7 @@ program DAMASK_grid open(newunit=statUnit,file=trim(getSolverJobName())//'.sta',form='FORMATTED',status='REPLACE') write(statUnit,'(a)') 'Increment Time CutbackLevel Converged IterationsNeeded' ! statistics file if (debug_grid%contains('basic')) print'(/,a)', ' header of statistics file written out' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) else writeHeader open(newunit=statUnit,file=trim(getSolverJobName())//& '.sta',form='FORMATTED', position='APPEND', status='OLD') @@ -405,7 +405,7 @@ program DAMASK_grid write(incInfo,'(4(a,i0))') & 'Increment ',totalIncsCounter,'/',sum(loadCases%incs),& '-', stepFraction,'/',subStepFactor**cutBackLevel - flush(OUTPUT_UNIT) + flush(IO_STDOUT) !-------------------------------------------------------------------------------------------------- ! forward fields @@ -489,11 +489,11 @@ program DAMASK_grid print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' converged' else print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' NOT converged' - endif; flush(OUTPUT_UNIT) + endif; flush(IO_STDOUT) if (mod(inc,loadCases(currentLoadCase)%outputFrequency) == 0) then ! at output frequency print'(1/,a)', ' ... writing results to file ......................................' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) call CPFEM_results(totalIncsCounter,time) endif if (mod(inc,loadCases(currentLoadCase)%restartFrequency) == 0) then diff --git a/src/grid/discretization_grid.f90 b/src/grid/discretization_grid.f90 index 32cd996db..76739a8d2 100644 --- a/src/grid/discretization_grid.f90 +++ b/src/grid/discretization_grid.f90 @@ -65,7 +65,7 @@ subroutine discretization_grid_init(restart) integer(C_INTPTR_T) :: & devNull, z, z_offset - print'(/,a)', ' <<<+- discretization_grid init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- discretization_grid init -+>>>'; flush(IO_STDOUT) if(index(interface_geomFile,'.vtr') /= 0) then call readVTR(grid,geomSize,origin,microstructureAt) diff --git a/src/grid/grid_damage_spectral.f90 b/src/grid/grid_damage_spectral.f90 index 3d6a9c431..27dc5c1bd 100644 --- a/src/grid/grid_damage_spectral.f90 +++ b/src/grid/grid_damage_spectral.f90 @@ -205,10 +205,10 @@ function grid_damage_spectral_solution(timeinc,timeinc_old) result(solution) call VecMax(solution_vec,devNull,phi_max,ierr); CHKERRQ(ierr) if (solution%converged) & print'(/,a)', ' ... nonlocal damage converged .....................................' - write(OUTPUT_UNIT,'(/,a,f8.6,2x,f8.6,2x,e11.4,/)',advance='no') ' Minimum|Maximum|Delta Damage = ',& + write(IO_STDOUT,'(/,a,f8.6,2x,f8.6,2x,e11.4,/)',advance='no') ' Minimum|Maximum|Delta Damage = ',& phi_min, phi_max, stagNorm print'(/,a)', ' ===========================================================================' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) end function grid_damage_spectral_solution diff --git a/src/grid/grid_mech_FEM.f90 b/src/grid/grid_mech_FEM.f90 index 0fcb08480..e1ceb42b0 100644 --- a/src/grid/grid_mech_FEM.f90 +++ b/src/grid/grid_mech_FEM.f90 @@ -122,7 +122,7 @@ subroutine grid_mech_FEM_init PetscScalar, pointer, dimension(:,:,:,:) :: & u_current,u_lastInc - print'(/,a)', ' <<<+- grid_mech_FEM init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- grid_mech_FEM init -+>>>'; flush(IO_STDOUT) !----------------------------------------------------------------------------------------------- ! debugging options @@ -413,7 +413,7 @@ subroutine grid_mech_FEM_restartWrite call DMDAVecGetArrayF90(mech_grid,solution_current,u_current,ierr); CHKERRQ(ierr) call DMDAVecGetArrayF90(mech_grid,solution_lastInc,u_lastInc,ierr); CHKERRQ(ierr) - print*, 'writing solver data required for restart to file'; flush(OUTPUT_UNIT) + print*, 'writing solver data required for restart to file'; flush(IO_STDOUT) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -481,7 +481,7 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,fnorm,reason,dummy,i print'(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' print'(/,a)', ' ===========================================================================' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) end subroutine converged @@ -517,11 +517,11 @@ subroutine formResidual(da_local,x_local, & totalIter = totalIter + 1 print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter+1, '≤', num%itmax if (debugRotation) & - write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(IO_STDOUT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) - write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(IO_STDOUT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim =', transpose(F_aim) - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif newIteration !-------------------------------------------------------------------------------------------------- diff --git a/src/grid/grid_mech_spectral_basic.f90 b/src/grid/grid_mech_spectral_basic.f90 index 819e9eded..e7fb9bd19 100644 --- a/src/grid/grid_mech_spectral_basic.f90 +++ b/src/grid/grid_mech_spectral_basic.f90 @@ -109,7 +109,7 @@ subroutine grid_mech_spectral_basic_init character(len=pStringLen) :: & fileName - print'(/,a)', ' <<<+- grid_mech_spectral_basic init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- grid_mech_spectral_basic init -+>>>'; flush(IO_STDOUT) print*, 'Eisenlohr et al., International Journal of Plasticity 46:37–53, 2013' print*, 'https://doi.org/10.1016/j.ijplas.2012.09.012'//IO_EOL @@ -375,7 +375,7 @@ subroutine grid_mech_spectral_basic_restartWrite call DMDAVecGetArrayF90(da,solution_vec,F,ierr); CHKERRQ(ierr) - print'(a)', ' writing solver data required for restart to file'; flush(OUTPUT_UNIT) + print'(a)', ' writing solver data required for restart to file'; flush(IO_STDOUT) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -441,7 +441,7 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,devNull3,reason,dumm print'(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' print'(/,a)', ' ===========================================================================' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) end subroutine converged @@ -475,11 +475,11 @@ subroutine formResidual(in, F, & totalIter = totalIter + 1 print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax if (debugRotation) & - write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(IO_STDOUT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) - write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(IO_STDOUT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim =', transpose(F_aim) - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif newIteration !-------------------------------------------------------------------------------------------------- diff --git a/src/grid/grid_mech_spectral_polarisation.f90 b/src/grid/grid_mech_spectral_polarisation.f90 index 021c2291e..5cc7d1602 100644 --- a/src/grid/grid_mech_spectral_polarisation.f90 +++ b/src/grid/grid_mech_spectral_polarisation.f90 @@ -123,7 +123,7 @@ subroutine grid_mech_spectral_polarisation_init character(len=pStringLen) :: & fileName - print'(/,a)', ' <<<+- grid_mech_spectral_polarisation init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- grid_mech_spectral_polarisation init -+>>>'; flush(IO_STDOUT) print*, 'Shanthraj et al., International Journal of Plasticity 66:31–45, 2015' print*, 'https://doi.org/10.1016/j.ijplas.2014.02.006' @@ -433,7 +433,7 @@ subroutine grid_mech_spectral_polarisation_restartWrite F => FandF_tau(0: 8,:,:,:) F_tau => FandF_tau(9:17,:,:,:) - print*, 'writing solver data required for restart to file'; flush(OUTPUT_UNIT) + print*, 'writing solver data required for restart to file'; flush(IO_STDOUT) write(fileName,'(a,a,i0,a)') trim(getSolverJobName()),'_',worldrank,'.hdf5' fileHandle = HDF5_openFile(fileName,'w') @@ -505,7 +505,7 @@ subroutine converged(snes_local,PETScIter,devNull1,devNull2,devNull3,reason,dumm print '(a,f12.2,a,es8.2,a,es9.2,a)', ' error stress BC = ', & err_BC/BCTol, ' (',err_BC, ' Pa, tol = ',BCTol,')' print'(/,a)', ' ===========================================================================' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) end subroutine converged @@ -559,11 +559,11 @@ subroutine formResidual(in, FandF_tau, & totalIter = totalIter + 1 print'(1x,a,3(a,i0))', trim(incInfo), ' @ Iteration ', num%itmin, '≤',totalIter, '≤', num%itmax if(debugRotation) & - write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(IO_STDOUT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim (lab) =', transpose(params%rotation_BC%rotate(F_aim,active=.true.)) - write(OUTPUT_UNIT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & + write(IO_STDOUT,'(/,a,/,3(3(f12.7,1x)/))',advance='no') & ' deformation gradient aim =', transpose(F_aim) - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif newIteration !-------------------------------------------------------------------------------------------------- diff --git a/src/grid/grid_thermal_spectral.f90 b/src/grid/grid_thermal_spectral.f90 index b12d67843..49be5ad7e 100644 --- a/src/grid/grid_thermal_spectral.f90 +++ b/src/grid/grid_thermal_spectral.f90 @@ -199,10 +199,10 @@ function grid_thermal_spectral_solution(timeinc,timeinc_old) result(solution) call VecMax(solution_vec,devNull,T_max,ierr); CHKERRQ(ierr) if (solution%converged) & print'(/,a)', ' ... thermal conduction converged ..................................' - write(OUTPUT_UNIT,'(/,a,f8.4,2x,f8.4,2x,f8.4,/)',advance='no') ' Minimum|Maximum|Delta Temperature / K = ',& + write(IO_STDOUT,'(/,a,f8.4,2x,f8.4,2x,f8.4,/)',advance='no') ' Minimum|Maximum|Delta Temperature / K = ',& T_min, T_max, stagNorm print'(/,a)', ' ===========================================================================' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) end function grid_thermal_spectral_solution diff --git a/src/grid/spectral_utilities.f90 b/src/grid/spectral_utilities.f90 index bfd05b6f5..dc6430c72 100644 --- a/src/grid/spectral_utilities.f90 +++ b/src/grid/spectral_utilities.f90 @@ -211,7 +211,7 @@ subroutine spectral_utilities_init if(debugPETSc) print'(3(/,a),/)', & ' Initializing PETSc with debug options: ', & trim(PETScDebug), & - ' add more using the PETSc_Options keyword in numerics.yaml '; flush(OUTPUT_UNIT) + ' add more using the PETSc_Options keyword in numerics.yaml '; flush(IO_STDOUT) num_grid => config_numerics%get('grid',defaultVal=emptyDict) @@ -280,7 +280,7 @@ subroutine spectral_utilities_init if (pReal /= C_DOUBLE .or. kind(1) /= C_INT) error stop 'C and Fortran datatypes do not match' call fftw_set_timelimit(num_grid%get_asFloat('fftw_timelimit',defaultVal=-1.0_pReal)) - print*, 'FFTW initialized'; flush(OUTPUT_UNIT) + print*, 'FFTW initialized'; flush(IO_STDOUT) !-------------------------------------------------------------------------------------------------- ! MPI allocation @@ -507,7 +507,7 @@ subroutine utilities_fourierGammaConvolution(fieldAim) print'(/,a)', ' ... doing gamma convolution ...............................................' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) !-------------------------------------------------------------------------------------------------- ! do the actual spectral method calculation (mechanical equilibrium) @@ -577,7 +577,7 @@ real(pReal) function utilities_divergenceRMS() complex(pReal), dimension(3) :: rescaledGeom print'(/,a)', ' ... calculating divergence ................................................' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) rescaledGeom = cmplx(geomSize/scaledGeomSize,0.0_pReal) @@ -621,7 +621,7 @@ real(pReal) function utilities_curlRMS() complex(pReal), dimension(3) :: rescaledGeom print'(/,a)', ' ... calculating curl ......................................................' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) rescaledGeom = cmplx(geomSize/scaledGeomSize,0.0_pReal) @@ -701,9 +701,9 @@ function utilities_maskedCompliance(rot_BC,mask_stress,C) if(debugGeneral) then print'(/,a)', ' ... updating masked compliance ............................................' - write(OUTPUT_UNIT,'(/,a,/,9(9(2x,f12.7,1x)/))',advance='no') ' Stiffness C (load) / GPa =',& + write(IO_STDOUT,'(/,a,/,9(9(2x,f12.7,1x)/))',advance='no') ' Stiffness C (load) / GPa =',& transpose(temp99_Real)*1.0e-9_pReal - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif do i = 1,9; do j = 1,9 @@ -723,9 +723,9 @@ function utilities_maskedCompliance(rot_BC,mask_stress,C) if (debugGeneral .or. errmatinv) then write(formatString, '(i2)') size_reduced formatString = '(/,a,/,'//trim(formatString)//'('//trim(formatString)//'(2x,es9.2,1x)/))' - write(OUTPUT_UNIT,trim(formatString),advance='no') ' C * S (load) ', & + write(IO_STDOUT,trim(formatString),advance='no') ' C * S (load) ', & transpose(matmul(c_reduced,s_reduced)) - write(OUTPUT_UNIT,trim(formatString),advance='no') ' S (load) ', transpose(s_reduced) + write(IO_STDOUT,trim(formatString),advance='no') ' S (load) ', transpose(s_reduced) if(errmatinv) call IO_error(error_ID=400,ext_msg='utilities_maskedCompliance') endif temp99_real = reshape(unpack(reshape(s_reduced,[size_reduced**2]),reshape(mask,[81]),0.0_pReal),[9,9]) @@ -736,9 +736,9 @@ function utilities_maskedCompliance(rot_BC,mask_stress,C) utilities_maskedCompliance = math_99to3333(temp99_Real) if(debugGeneral) then - write(OUTPUT_UNIT,'(/,a,/,9(9(2x,f10.5,1x)/),/)',advance='no') & + write(IO_STDOUT,'(/,a,/,9(9(2x,f10.5,1x)/),/)',advance='no') & ' Masked Compliance (load) * GPa =', transpose(temp99_Real)*1.0e9_pReal - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif end function utilities_maskedCompliance @@ -823,7 +823,7 @@ subroutine utilities_constitutiveResponse(P,P_av,C_volAvg,C_minmaxAvg,& real(pReal), dimension(2) :: valueAndRank !< pair of min/max norm of dPdF to synchronize min/max of dPdF print'(/,a)', ' ... evaluating constitutive response ......................................' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) materialpoint_F = reshape(F,[3,3,1,product(grid(1:2))*grid3]) ! set materialpoint target F to estimated field @@ -833,13 +833,13 @@ subroutine utilities_constitutiveResponse(P,P_av,C_volAvg,C_minmaxAvg,& P_av = sum(sum(sum(P,dim=5),dim=4),dim=3) * wgt ! average of P call MPI_Allreduce(MPI_IN_PLACE,P_av,9,MPI_DOUBLE,MPI_SUM,PETSC_COMM_WORLD,ierr) if (debugRotation) & - write(OUTPUT_UNIT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress (lab) / MPa =',& + write(IO_STDOUT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress (lab) / MPa =',& transpose(P_av)*1.e-6_pReal if(present(rotation_BC)) & P_av = rotation_BC%rotate(P_av) - write(OUTPUT_UNIT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& + write(IO_STDOUT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& transpose(P_av)*1.e-6_pReal - flush(OUTPUT_UNIT) + flush(IO_STDOUT) dPdF_max = 0.0_pReal dPdF_norm_max = 0.0_pReal @@ -1095,7 +1095,7 @@ subroutine utilities_saveReferenceStiffness fileUnit,ierr if (worldrank == 0) then - print'(a)', ' writing reference stiffness data required for restart to file'; flush(OUTPUT_UNIT) + print'(a)', ' writing reference stiffness data required for restart to file'; flush(IO_STDOUT) open(newunit=fileUnit, file=getSolverJobName()//'.C_ref',& status='replace',access='stream',action='write',iostat=ierr) if(ierr /=0) call IO_error(100,ext_msg='could not open file '//getSolverJobName()//'.C_ref') diff --git a/src/homogenization.f90 b/src/homogenization.f90 index 1c2b9bc38..0e7f1bf3a 100644 --- a/src/homogenization.f90 +++ b/src/homogenization.f90 @@ -186,7 +186,7 @@ subroutine homogenization_init materialpoint_F = materialpoint_F0 ! initialize to identity allocate(materialpoint_P(3,3,discretization_nIP,discretization_nElem), source=0.0_pReal) - print'(/,a)', ' <<<+- homogenization init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- homogenization init -+>>>'; flush(IO_STDOUT) num%nMPstate = num_homogGeneric%get_asInt ('nMPstate', defaultVal=10) num%subStepMinHomog = num_homogGeneric%get_asFloat('subStepMin', defaultVal=1.0e-3_pReal) diff --git a/src/homogenization_mech_RGC.f90 b/src/homogenization_mech_RGC.f90 index d954b0b9f..f0485b244 100644 --- a/src/homogenization_mech_RGC.f90 +++ b/src/homogenization_mech_RGC.f90 @@ -95,7 +95,7 @@ module subroutine mech_RGC_init(num_homogMech) print'(/,a)', ' <<<+- homogenization_mech_rgc init -+>>>' Ninstance = count(homogenization_type == HOMOGENIZATION_RGC_ID) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) print*, 'Tjahjanto et al., International Journal of Material Forming 2(1):939–942, 2009' print*, 'https://doi.org/10.1007/s12289-009-0619-1'//IO_EOL @@ -247,7 +247,7 @@ module subroutine mech_RGC_partitionDeformation(F,avgF,instance,of) print'(1x,3(e15.8,1x))',(F(i,j,iGrain), j = 1,3) enddo print*,' ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif enddo @@ -376,7 +376,7 @@ module procedure mech_RGC_updateState '@ grain ',stresLoc(3),' in component ',stresLoc(1),stresLoc(2) print'(a,e15.8,a,i3,a,i2)',' Max residual: ',residMax, & ' @ iface ',residLoc(1),' in direction ',residLoc(2) - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -388,7 +388,7 @@ module procedure mech_RGC_updateState mech_RGC_updateState = .true. #ifdef DEBUG if (debugHomog%extensive .and. prm%of_debug == of) & - print*, '... done and happy'; flush(OUTPUT_UNIT) + print*, '... done and happy'; flush(IO_STDOUT) #endif !-------------------------------------------------------------------------------------------------- @@ -416,7 +416,7 @@ module procedure mech_RGC_updateState print'(a,e15.8,/)', ' Volume discrepancy: ', dst%volumeDiscrepancy(of) print'(a,e15.8)', ' Maximum relaxation rate: ', dst%relaxationRate_max(of) print'(a,e15.8,/)', ' Average relaxation rate: ', dst%relaxationRate_avg(of) - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -429,7 +429,7 @@ module procedure mech_RGC_updateState #ifdef DEBUG if (debugHomog%extensive .and. prm%of_debug == of) & - print'(a,/)', ' ... broken'; flush(OUTPUT_UNIT) + print'(a,/)', ' ... broken'; flush(IO_STDOUT) #endif return @@ -437,7 +437,7 @@ module procedure mech_RGC_updateState else ! proceed with computing the Jacobian and state update #ifdef DEBUG if (debugHomog%extensive .and. prm%of_debug == of) & - print'(a,/)', ' ... not yet done'; flush(OUTPUT_UNIT) + print'(a,/)', ' ... not yet done'; flush(IO_STDOUT) #endif endif @@ -499,7 +499,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(smatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -559,7 +559,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(pmatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -578,7 +578,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(rmatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -593,7 +593,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(jmatrix(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -609,7 +609,7 @@ module procedure mech_RGC_updateState print'(1x,100(e11.4,1x))',(jnverse(i,j), j = 1,3*nIntFaceTot) enddo print*,' ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif @@ -625,7 +625,7 @@ module procedure mech_RGC_updateState !$OMP CRITICAL (write2out) print'(a,i3,a,i3,a)',' RGC_updateState: ip ',ip,' | el ',el,' enforces cutback' print'(a,e15.8)',' due to large relaxation change = ',maxval(abs(drelax)) - flush(OUTPUT_UNIT) + flush(IO_STDOUT) !$OMP END CRITICAL (write2out) endif @@ -636,7 +636,7 @@ module procedure mech_RGC_updateState print'(1x,2(e15.8,1x))', stt%relaxationVector(i,of) enddo print*,' ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) endif #endif diff --git a/src/homogenization_mech_isostrain.f90 b/src/homogenization_mech_isostrain.f90 index eefb3ad64..5138afa73 100644 --- a/src/homogenization_mech_isostrain.f90 +++ b/src/homogenization_mech_isostrain.f90 @@ -40,7 +40,7 @@ module subroutine mech_isostrain_init print'(/,a)', ' <<<+- homogenization_mech_isostrain init -+>>>' Ninstance = count(homogenization_type == HOMOGENIZATION_ISOSTRAIN_ID) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) allocate(param(Ninstance)) ! one container of parameters per instance diff --git a/src/homogenization_mech_none.f90 b/src/homogenization_mech_none.f90 index 52143a3d2..3cbec5911 100644 --- a/src/homogenization_mech_none.f90 +++ b/src/homogenization_mech_none.f90 @@ -21,7 +21,7 @@ module subroutine mech_none_init print'(/,a)', ' <<<+- homogenization_mech_none init -+>>>' Ninstance = count(homogenization_type == HOMOGENIZATION_NONE_ID) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) do h = 1, size(homogenization_type) if (homogenization_type(h) /= HOMOGENIZATION_NONE_ID) cycle diff --git a/src/kinematics_cleavage_opening.f90 b/src/kinematics_cleavage_opening.f90 index 37513d0e1..23f348831 100644 --- a/src/kinematics_cleavage_opening.f90 +++ b/src/kinematics_cleavage_opening.f90 @@ -49,7 +49,7 @@ module function kinematics_cleavage_opening_init(kinematics_length) result(myKin myKinematics = kinematics_active('cleavage_opening',kinematics_length) Ninstance = count(myKinematics) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/kinematics_slipplane_opening.f90 b/src/kinematics_slipplane_opening.f90 index 46ff59da5..660483b90 100644 --- a/src/kinematics_slipplane_opening.f90 +++ b/src/kinematics_slipplane_opening.f90 @@ -52,7 +52,7 @@ module function kinematics_slipplane_opening_init(kinematics_length) result(myKi myKinematics = kinematics_active('slipplane_opening',kinematics_length) Ninstance = count(myKinematics) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/kinematics_thermal_expansion.f90 b/src/kinematics_thermal_expansion.f90 index d3516862d..93a48e035 100644 --- a/src/kinematics_thermal_expansion.f90 +++ b/src/kinematics_thermal_expansion.f90 @@ -42,7 +42,7 @@ module function kinematics_thermal_expansion_init(kinematics_length) result(myKi myKinematics = kinematics_active('thermal_expansion',kinematics_length) Ninstance = count(myKinematics) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/lattice.f90 b/src/lattice.f90 index ba7631142..69305c839 100644 --- a/src/lattice.f90 +++ b/src/lattice.f90 @@ -457,7 +457,7 @@ subroutine lattice_init phase, & elasticity - print'(/,a)', ' <<<+- lattice init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- lattice init -+>>>'; flush(IO_STDOUT) phases => config_material%get('phase') Nphases = phases%length diff --git a/src/material.f90 b/src/material.f90 index 9bc2bbbc5..6688a0ae5 100644 --- a/src/material.f90 +++ b/src/material.f90 @@ -164,7 +164,7 @@ subroutine material_init(restart) material_homogenization character(len=pStringLen) :: sectionName - print'(/,a)', ' <<<+- material init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- material init -+>>>'; flush(IO_STDOUT) phases => config_material%get('phase') allocate(material_name_phase(phases%length)) diff --git a/src/math.f90 b/src/math.f90 index 63e539e48..163f4df6a 100644 --- a/src/math.f90 +++ b/src/math.f90 @@ -91,7 +91,7 @@ subroutine math_init class(tNode), pointer :: & num_generic - print'(/,a)', ' <<<+- math init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- math init -+>>>'; flush(IO_STDOUT) num_generic => config_numerics%get('generic',defaultVal=emptyDict) randomSeed = num_generic%get_asInt('random_seed', defaultVal = 0) diff --git a/src/mesh/DAMASK_mesh.f90 b/src/mesh/DAMASK_mesh.f90 index acee51394..bfa8d22ce 100644 --- a/src/mesh/DAMASK_mesh.f90 +++ b/src/mesh/DAMASK_mesh.f90 @@ -78,7 +78,7 @@ program DAMASK_mesh !-------------------------------------------------------------------------------------------------- ! init DAMASK (all modules) call CPFEM_initAll - print'(/,a)', ' <<<+- DAMASK_mesh init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- DAMASK_mesh init -+>>>'; flush(IO_STDOUT) !--------------------------------------------------------------------- ! reading field information from numerics file and do sanity checks @@ -299,7 +299,7 @@ program DAMASK_mesh write(incInfo,'(4(a,i0))') & 'Increment ',totalIncsCounter,'/',sum(loadCases%incs),& '-',stepFraction, '/', subStepFactor**cutBackLevel - flush(OUTPUT_UNIT) + flush(IO_STDOUT) !-------------------------------------------------------------------------------------------------- ! forward fields @@ -363,7 +363,7 @@ program DAMASK_mesh print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' converged' else print'(/,a,i0,a)', ' increment ', totalIncsCounter, ' NOT converged' - endif; flush(OUTPUT_UNIT) + endif; flush(IO_STDOUT) if (mod(inc,loadCases(currentLoadCase)%outputFrequency) == 0) then ! at output frequency print'(/,a)', ' ... writing results to file ......................................' diff --git a/src/mesh/FEM_utilities.f90 b/src/mesh/FEM_utilities.f90 index 91e1bd5b6..4d9786112 100644 --- a/src/mesh/FEM_utilities.f90 +++ b/src/mesh/FEM_utilities.f90 @@ -122,7 +122,7 @@ subroutine FEM_utilities_init ' Initializing PETSc with debug options: ', & trim(PETScDebug), & ' add more using the PETSc_Options keyword in numerics.yaml ' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) call PetscOptionsClear(PETSC_NULL_OPTIONS,ierr) CHKERRQ(ierr) if(debugPETSc) call PetscOptionsInsertString(PETSC_NULL_OPTIONS,trim(PETSCDEBUG),ierr) diff --git a/src/mesh/mesh_mech_FEM.f90 b/src/mesh/mesh_mech_FEM.f90 index f7a177929..de1f0c687 100644 --- a/src/mesh/mesh_mech_FEM.f90 +++ b/src/mesh/mesh_mech_FEM.f90 @@ -110,7 +110,7 @@ subroutine FEM_mech_init(fieldBC) class(tNode), pointer :: & num_mesh - print'(/,a)', ' <<<+- FEM_mech init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- FEM_mech init -+>>>'; flush(IO_STDOUT) !----------------------------------------------------------------------------- ! read numerical parametes and do sanity checks @@ -319,7 +319,7 @@ type(tSolutionState) function FEM_mech_solution( & endif print'(/,a)', ' ===========================================================================' - flush(OUTPUT_UNIT) + flush(IO_STDOUT) end function FEM_mech_solution @@ -682,9 +682,9 @@ subroutine FEM_mech_converged(snes_local,PETScIter,xnorm,snorm,fnorm,reason,dumm print'(/,1x,a,a,i0,a,i0,f0.3)', trim(incInfo), & ' @ Iteration ',PETScIter,' mechanical residual norm = ', & int(fnorm/divTol),fnorm/divTol-int(fnorm/divTol) - write(OUTPUT_UNIT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& + write(IO_STDOUT,'(/,a,/,3(3(2x,f12.4,1x)/))',advance='no') ' Piola--Kirchhoff stress / MPa =',& transpose(P_av)*1.e-6_pReal - flush(OUTPUT_UNIT) + flush(IO_STDOUT) end subroutine FEM_mech_converged diff --git a/src/results.f90 b/src/results.f90 index 6dd84fb78..aec90d7be 100644 --- a/src/results.f90 +++ b/src/results.f90 @@ -65,7 +65,7 @@ subroutine results_init(restart) character(len=pStringLen) :: commandLine - print'(/,a)', ' <<<+- results init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- results init -+>>>'; flush(IO_STDOUT) print*, 'Diehl et al., Integrating Materials and Manufacturing Innovation 6(1):83–91, 2017' print*, 'https://doi.org/10.1007/s40192-017-0084-5'//IO_EOL diff --git a/src/rotations.f90 b/src/rotations.f90 index 723cced61..e19513866 100644 --- a/src/rotations.f90 +++ b/src/rotations.f90 @@ -104,7 +104,7 @@ contains subroutine rotations_init call quaternions_init - print'(/,a)', ' <<<+- rotations init -+>>>'; flush(OUTPUT_UNIT) + print'(/,a)', ' <<<+- rotations init -+>>>'; flush(IO_STDOUT) print*, 'Rowenhorst et al., Modelling and Simulation in Materials Science and Engineering 23:083501, 2015' print*, 'https://doi.org/10.1088/0965-0393/23/8/083501' diff --git a/src/source_damage_anisoBrittle.f90 b/src/source_damage_anisoBrittle.f90 index 5377f3373..7911d6d0a 100644 --- a/src/source_damage_anisoBrittle.f90 +++ b/src/source_damage_anisoBrittle.f90 @@ -53,7 +53,7 @@ module function source_damage_anisoBrittle_init(source_length) result(mySources) mySources = source_active('damage_anisoBrittle',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_damage_anisoDuctile.f90 b/src/source_damage_anisoDuctile.f90 index abbd90ca3..52189c839 100644 --- a/src/source_damage_anisoDuctile.f90 +++ b/src/source_damage_anisoDuctile.f90 @@ -47,7 +47,7 @@ module function source_damage_anisoDuctile_init(source_length) result(mySources) mySources = source_active('damage_anisoDuctile',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_damage_isoBrittle.f90 b/src/source_damage_isoBrittle.f90 index 45f6abf3a..714e71ef1 100644 --- a/src/source_damage_isoBrittle.f90 +++ b/src/source_damage_isoBrittle.f90 @@ -43,7 +43,7 @@ module function source_damage_isoBrittle_init(source_length) result(mySources) mySources = source_active('damage_isoBrittle',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_damage_isoDuctile.f90 b/src/source_damage_isoDuctile.f90 index e74f187de..493183d75 100644 --- a/src/source_damage_isoDuctile.f90 +++ b/src/source_damage_isoDuctile.f90 @@ -45,7 +45,7 @@ module function source_damage_isoDuctile_init(source_length) result(mySources) mySources = source_active('damage_isoDuctile',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_thermal_dissipation.f90 b/src/source_thermal_dissipation.f90 index 307d211b3..5cc740424 100644 --- a/src/source_thermal_dissipation.f90 +++ b/src/source_thermal_dissipation.f90 @@ -41,7 +41,7 @@ module function source_thermal_dissipation_init(source_length) result(mySources) mySources = source_active('thermal_dissipation',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') diff --git a/src/source_thermal_externalheat.f90 b/src/source_thermal_externalheat.f90 index 95d994e11..4a644f53b 100644 --- a/src/source_thermal_externalheat.f90 +++ b/src/source_thermal_externalheat.f90 @@ -45,7 +45,7 @@ module function source_thermal_externalheat_init(source_length) result(mySources mySources = source_active('thermal_externalheat',source_length) Ninstance = count(mySources) - print'(a,i2)', ' # instances: ',Ninstance; flush(OUTPUT_UNIT) + print'(a,i2)', ' # instances: ',Ninstance; flush(IO_STDOUT) if(Ninstance == 0) return phases => config_material%get('phase') From d888c894dff777cfd67c3255fd20021a604dda8e Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Tue, 22 Sep 2020 16:52:23 +0200 Subject: [PATCH 47/61] updated tests --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index b743be478..69371a32f 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit b743be47898365af917ef57686c26a3a750c651b +Subproject commit 69371a32fc375343a92f9f70c5e263502bb0a80b From df6db037f8a81825a5ed349b28fd5f0841e91014 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Tue, 22 Sep 2020 19:10:03 +0200 Subject: [PATCH 48/61] cleaned tests --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 69371a32f..3444f5334 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 69371a32fc375343a92f9f70c5e263502bb0a80b +Subproject commit 3444f5334c1c6c05b781e0e25bbcb658d9ce7c5d From 790d3a742eb98f270a5777ab1fc6972ecde78af6 Mon Sep 17 00:00:00 2001 From: Test User Date: Tue, 22 Sep 2020 20:32:28 +0200 Subject: [PATCH 49/61] [skip ci] updated version information after successful test of v3.0.0-alpha-275-g7801f527f --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index e073be898..a05ebe3cf 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v3.0.0-alpha-245-g5ef761fb9 +v3.0.0-alpha-275-g7801f527f From 05835bacd3bc8ccd4831f8b4d0534658c0fd4100 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Tue, 22 Sep 2020 14:47:08 -0400 Subject: [PATCH 50/61] removed set_X(), duplicate(), and .homogenization; renamed ".microstructure" to ".materials" --- python/damask/_geom.py | 492 ++++++++++++++------------------------ python/tests/test_Geom.py | 144 +++++------ 2 files changed, 246 insertions(+), 390 deletions(-) diff --git a/python/damask/_geom.py b/python/damask/_geom.py index 7e6b6a1d3..b7a7928ca 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -17,29 +17,44 @@ from . import grid_filters class Geom: """Geometry definition for grid solvers.""" - def __init__(self,microstructure,size,origin=[0.0,0.0,0.0],homogenization=1,comments=[]): + def __init__(self,materials,size,origin=[0.0,0.0,0.0],comments=[]): """ - New geometry definition from array of microstructures and size. + New geometry definition from array of materials, size, and origin. Parameters ---------- - microstructure : numpy.ndarray - Microstructure array (3D) + materials : numpy.ndarray + Material index array (3D). size : list or numpy.ndarray - Physical size of the microstructure in meter. + Physical size of the geometry in meter. origin : list or numpy.ndarray, optional - Physical origin of the microstructure in meter. - homogenization : int, optional - Homogenization index. + Physical origin of the geometry in meter. comments : list of str, optional Comment lines. """ - self.set_microstructure(microstructure,inplace=True) - self.set_size(size,inplace=True) - self.set_origin(origin,inplace=True) - self.set_homogenization(homogenization,inplace=True) - self.set_comments(comments,inplace=True) + if len(materials.shape) != 3: + raise ValueError(f'Invalid materials shape {materials.shape}.') + elif materials.dtype not in np.sctypes['float'] + np.sctypes['int']: + raise TypeError(f'Invalid materials data type {materials.dtype}.') + else: + self.materials = np.copy(materials) + + if self.materials.dtype in np.sctypes['float'] and \ + np.all(self.materials == self.materials.astype(int).astype(float)): + self.materials = self.materials.astype(int) + + if len(size) != 3 or any(np.array(size) <= 0): + raise ValueError(f'Invalid size {size}.') + else: + self.size = np.array(size) + + if len(origin) != 3: + raise ValueError(f'Invalid origin {origin}.') + else: + self.origin = np.array(origin) + + self.comments = [str(c) for c in comments] if isinstance(comments,list) else [str(comments)] def __repr__(self): @@ -48,8 +63,8 @@ class Geom: f'grid a b c: {util.srepr(self.grid, " x ")}', f'size x y z: {util.srepr(self.size, " x ")}', f'origin x y z: {util.srepr(self.origin," ")}', - f'# materialpoints: {self.N_microstructure}', - f'max materialpoint: {np.nanmax(self.microstructure)}', + f'# materialpoints: {self.N_materials}', + f'max materialpoint: {np.nanmax(self.materials)}', ]) @@ -63,42 +78,6 @@ class Geom: return self.__copy__() - def duplicate(self,microstructure=None,size=None,origin=None,comments=None,autosize=False): - """ - Create a duplicate having updated microstructure, size, and origin. - - Parameters - ---------- - microstructure : numpy.ndarray, optional - Microstructure array (3D). - size : list or numpy.ndarray, optional - Physical size of the microstructure in meter. - origin : list or numpy.ndarray, optional - Physical origin of the microstructure in meter. - comments : list of str, optional - Comment lines. - autosize : bool, optional - Ignore size parameter and rescale according to change of grid points. - - """ - if size is not None and autosize: - raise ValueError('Auto-sizing conflicts with explicit size parameter.') - - grid_old = self.grid - dup = self.set_microstructure(microstructure)\ - .set_origin(origin) - - if comments is not None: - dup.set_comments(comments,inplace=True) - - if size is not None: - dup.set_size(size,inplace=True) - elif autosize: - dup.set_size(dup.grid/grid_old*self.size,inplace=True) - - return dup - - def diff(self,other): """ Report property differences of self relative to other. @@ -114,154 +93,33 @@ class Geom: message.append(util.delete(f'grid a b c: {util.srepr(other.grid," x ")}')) message.append(util.emph( f'grid a b c: {util.srepr( self.grid," x ")}')) - if np.any(other.size != self.size): + if not np.allclose(other.size,self.size): message.append(util.delete(f'size x y z: {util.srepr(other.size," x ")}')) message.append(util.emph( f'size x y z: {util.srepr( self.size," x ")}')) - if np.any(other.origin != self.origin): + if not np.allclose(other.origin,self.origin): message.append(util.delete(f'origin x y z: {util.srepr(other.origin," ")}')) message.append(util.emph( f'origin x y z: {util.srepr( self.origin," ")}')) - if other.N_microstructure != self.N_microstructure: - message.append(util.delete(f'# materialpoints: {other.N_microstructure}')) - message.append(util.emph( f'# materialpoints: { self.N_microstructure}')) + if other.N_materials != self.N_materials: + message.append(util.delete(f'# materialpoints: {other.N_materials}')) + message.append(util.emph( f'# materialpoints: { self.N_materials}')) - if np.nanmax(other.microstructure) != np.nanmax(self.microstructure): - message.append(util.delete(f'max materialpoint: {np.nanmax(other.microstructure)}')) - message.append(util.emph( f'max materialpoint: {np.nanmax( self.microstructure)}')) + if np.nanmax(other.materials) != np.nanmax(self.materials): + message.append(util.delete(f'max materialpoint: {np.nanmax(other.materials)}')) + message.append(util.emph( f'max materialpoint: {np.nanmax( self.materials)}')) return util.return_message(message) - def set_comments(self,comments,inplace=False): - """ - Replace all existing comments. - - Parameters - ---------- - comments : list of str - All comments. - - """ - target = self if inplace else self.copy() - target.comments = [] - target.add_comments(comments,inplace=True) - if not inplace: return target - - - def add_comments(self,comments,inplace=False): - """ - Append comments to existing comments. - - Parameters - ---------- - comments : list of str - New comments. - - """ - target = self if inplace else self.copy() - target.comments += [str(c) for c in comments] if isinstance(comments,list) else [str(comments)] - if not inplace: return target - - - def set_microstructure(self,microstructure,inplace=False): - """ - Replace the existing microstructure representation. - - The complete microstructure is replaced (indcluding grid definition), - unless a masked array is provided in which case the grid dimensions - need to match and masked entries are not replaced. - - Parameters - ---------- - microstructure : numpy.ndarray or numpy.ma.core.MaskedArray of shape (:,:,:) - Microstructure indices. - - """ - target = self if inplace else self.copy() - if microstructure is not None: - if isinstance(microstructure,np.ma.core.MaskedArray): - target.microstructure = np.where(microstructure.mask, - target.microstructure,microstructure.data) - else: - target.microstructure = np.copy(microstructure) - - if target.microstructure.dtype in np.sctypes['float'] and \ - np.all(target.microstructure == target.microstructure.astype(int).astype(float)): - target.microstructure = target.microstructure.astype(int) - - if len(target.microstructure.shape) != 3: - raise ValueError(f'Invalid microstructure shape {microstructure.shape}') - elif target.microstructure.dtype not in np.sctypes['float'] + np.sctypes['int']: - raise TypeError(f'Invalid microstructure data type {microstructure.dtype}') - if not inplace: return target - - - def set_size(self,size,inplace=False): - """ - Replace the existing size information. - - Parameters - ---------- - size : list or numpy.ndarray - Physical size of the microstructure in meter. - - """ - target = self if inplace else self.copy() - if size is not None: - if len(size) != 3 or any(np.array(size) <= 0): - raise ValueError(f'Invalid size {size}') - else: - target.size = np.array(size) - if not inplace: return target - - - def set_origin(self,origin,inplace=False): - """ - Replace the existing origin information. - - Parameters - ---------- - origin : list or numpy.ndarray - Physical origin of the microstructure in meter. - - """ - target = self if inplace else self.copy() - if origin is not None: - if len(origin) != 3: - raise ValueError(f'Invalid origin {origin}') - else: - target.origin = np.array(origin) - if not inplace: return target - - - def set_homogenization(self,homogenization,inplace=False): - """ - Replace the existing homogenization index. - - Parameters - ---------- - homogenization : int - Homogenization index. - - """ - target = self if inplace else self.copy() - if homogenization is not None: - if not isinstance(homogenization,int) or homogenization < 1: - raise TypeError(f'Invalid homogenization {homogenization}.') - else: - target.homogenization = homogenization - if not inplace: return target - - @property def grid(self): - return np.asarray(self.microstructure.shape) + return np.asarray(self.materials.shape) @property - def N_microstructure(self): - return np.unique(self.microstructure).size + def N_materials(self): + return np.unique(self.materials).size @staticmethod @@ -301,12 +159,10 @@ class Geom: size = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']]) elif key == 'origin': origin = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']]) - elif key == 'homogenization': - homogenization = int(items[1]) else: comments.append(line.strip()) - microstructure = np.empty(grid.prod()) # initialize as flat array + materials = np.empty(grid.prod()) # initialize as flat array i = 0 for line in content[header_length:]: items = line.split('#')[0].split() @@ -318,16 +174,16 @@ class Geom: abs(int(items[2])-int(items[0]))+1,dtype=float) else: items = list(map(float,items)) else: items = list(map(float,items)) - microstructure[i:i+len(items)] = items + materials[i:i+len(items)] = items i += len(items) if i != grid.prod(): raise TypeError(f'Invalid file: expected {grid.prod()} entries, found {i}') - if not np.any(np.mod(microstructure,1) != 0.0): # no float present - microstructure = microstructure.astype('int') + if not np.any(np.mod(materials,1) != 0.0): # no float present + materials = materials.astype('int') - return Geom(microstructure.reshape(grid,order='F'),size,origin,homogenization,comments) + return Geom(materials.reshape(grid,order='F'),size,origin,comments) @staticmethod @@ -365,7 +221,7 @@ class Geom: grid : int numpy.ndarray of shape (3) Number of grid points in x,y,z direction. size : list or numpy.ndarray of shape (3) - Physical size of the microstructure in meter. + Physical size of the geometry in meter. seeds : numpy.ndarray of shape (:,3) Position of the seed points in meter. All points need to lay within the box. weights : numpy.ndarray of shape (seeds.shape[0]) @@ -389,16 +245,17 @@ class Geom: result = pool.map_async(partial(Geom._find_closest_seed,seeds_p,weights_p), [coord for coord in coords]) pool.close() pool.join() - microstructure = np.array(result.get()) + materials = np.array(result.get()) if periodic: - microstructure = microstructure.reshape(grid*3) - microstructure = microstructure[grid[0]:grid[0]*2,grid[1]:grid[1]*2,grid[2]:grid[2]*2]%seeds.shape[0] + materials = materials.reshape(grid*3) + materials = materials[grid[0]:grid[0]*2,grid[1]:grid[1]*2,grid[2]:grid[2]*2]%seeds.shape[0] else: - microstructure = microstructure.reshape(grid) + materials = materials.reshape(grid) - return Geom(microstructure+1,size,homogenization=1, - comments=util.execution_stamp('Geom','from_Laguerre_tessellation'), + return Geom(materials = materials+1, + size = size, + comments = util.execution_stamp('Geom','from_Laguerre_tessellation'), ) @@ -412,7 +269,7 @@ class Geom: grid : int numpy.ndarray of shape (3) Number of grid points in x,y,z direction. size : list or numpy.ndarray of shape (3) - Physical size of the microstructure in meter. + Physical size of the geometry in meter. seeds : numpy.ndarray of shape (:,3) Position of the seed points in meter. All points need to lay within the box. periodic : Boolean, optional @@ -421,10 +278,11 @@ class Geom: """ coords = grid_filters.cell_coord0(grid,size).reshape(-1,3) KDTree = spatial.cKDTree(seeds,boxsize=size) if periodic else spatial.cKDTree(seeds) - devNull,microstructure = KDTree.query(coords) + devNull,materials = KDTree.query(coords) - return Geom(microstructure.reshape(grid)+1,size,homogenization=1, - comments=util.execution_stamp('Geom','from_Voronoi_tessellation'), + return Geom(materials = materials.reshape(grid)+1, + size = size, + comments = util.execution_stamp('Geom','from_Voronoi_tessellation'), ) @@ -462,21 +320,21 @@ class Geom: +[ 'grid a {} b {} c {}'.format(*geom.grid), 'size x {} y {} z {}'.format(*geom.size), 'origin x {} y {} z {}'.format(*geom.origin), - f'homogenization {geom.homogenization}', + 'homogenization 1', ] grid = geom.grid if pack is None: - plain = grid.prod()/geom.N_microstructure < 250 + plain = grid.prod()/geom.N_materials < 250 else: plain = not pack if plain: - format_string = '%g' if geom.microstructure.dtype in np.sctypes['float'] else \ - '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(geom.microstructure))))) + format_string = '%g' if geom.materials.dtype in np.sctypes['float'] else \ + '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(geom.materials))))) np.savetxt(fname, - geom.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T, + geom.materials.reshape([grid[0],np.prod(grid[1:])],order='F').T, header='\n'.join(header), fmt=format_string, comments='') else: try: @@ -487,7 +345,7 @@ class Geom: compressType = None former = start = -1 reps = 0 - for current in geom.microstructure.flatten('F'): + for current in geom.materials.flatten('F'): if abs(current - former) == 1 and (start - current) == reps*(former - current): compressType = 'to' reps += 1 @@ -532,7 +390,7 @@ class Geom: """ v = VTK.from_rectilinearGrid(geom.grid,geom.size,geom.origin) - v.add(geom.microstructure.flatten(order='F'),'materialpoint') + v.add(geom.materials.flatten(order='F'),'materialpoint') v.add_comments(geom.comments) if fname: @@ -575,11 +433,11 @@ class Geom: 0 gives octahedron (|x|^(2^0) + |y|^(2^0) + |z|^(2^0) < 1) 1 gives a sphere (|x|^(2^1) + |y|^(2^1) + |z|^(2^1) < 1) fill : int, optional - Fill value for primitive. Defaults to microstructure.max() + 1. + Fill value for primitive. Defaults to materials.max() + 1. R : damask.Rotation, optional Rotation of primitive. Defaults to no rotation. inverse : Boolean, optional - Retain original microstructure within primitive and fill outside. + Retain original materials within primitive and fill outside. Defaults to False. periodic : Boolean, optional Repeat primitive over boundaries. Defaults to True. @@ -601,22 +459,23 @@ class Geom: if periodic: # translate back to center mask = np.roll(mask,((c-np.ones(3)*.5)*self.grid).astype(int),(0,1,2)) - fill_ = np.full_like(self.microstructure,np.nanmax(self.microstructure)+1 if fill is None else fill) - ms = np.ma.MaskedArray(fill_,np.logical_not(mask) if inverse else mask) + fill_ = np.full_like(self.materials,np.nanmax(self.materials)+1 if fill is None else fill) - return self.duplicate(ms, - comments=self.comments+[util.execution_stamp('Geom','add_primitive')], - ) + return Geom(materials = np.where(np.logical_not(mask) if inverse else mask, self.materials,fill_), + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','add_primitive')], + ) def mirror(self,directions,reflect=False): """ - Mirror microstructure along given directions. + Mirror geometry along given directions. Parameters ---------- directions : iterable containing str - Direction(s) along which the microstructure is mirrored. + Direction(s) along which the geometry is mirrored. Valid entries are 'x', 'y', 'z'. reflect : bool, optional Reflect (include) outermost layers. Defaults to False. @@ -627,28 +486,30 @@ class Geom: raise ValueError(f'Invalid direction {set(directions).difference(valid)} specified.') limits = [None,None] if reflect else [-2,0] - ms = self.microstructure.copy() + ms = self.materials.copy() - if 'z' in directions: - ms = np.concatenate([ms,ms[:,:,limits[0]:limits[1]:-1]],2) - if 'y' in directions: - ms = np.concatenate([ms,ms[:,limits[0]:limits[1]:-1,:]],1) if 'x' in directions: ms = np.concatenate([ms,ms[limits[0]:limits[1]:-1,:,:]],0) + if 'y' in directions: + ms = np.concatenate([ms,ms[:,limits[0]:limits[1]:-1,:]],1) + if 'z' in directions: + ms = np.concatenate([ms,ms[:,:,limits[0]:limits[1]:-1]],2) - return self.duplicate(ms, - comments=self.comments+[util.execution_stamp('Geom','mirror')], - autosize=True) + return Geom(materials = ms, + size = self.size/self.grid*np.asarray(ms.shape), + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','mirror')], + ) def flip(self,directions): """ - Flip microstructure along given directions. + Flip geometry along given directions. Parameters ---------- directions : iterable containing str - Direction(s) along which the microstructure is flipped. + Direction(s) along which the geometry is flipped. Valid entries are 'x', 'y', 'z'. """ @@ -656,16 +517,18 @@ class Geom: if not set(directions).issubset(valid): raise ValueError(f'Invalid direction {set(directions).difference(valid)} specified.') - ms = np.flip(self.microstructure, (valid.index(d) for d in directions if d in valid)) + ms = np.flip(self.materials, (valid.index(d) for d in directions if d in valid)) - return self.duplicate(ms, - comments=self.comments+[util.execution_stamp('Geom','flip')], - ) + return Geom(materials = ms, + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','flip')], + ) def scale(self,grid,periodic=True): """ - Scale microstructure to new grid. + Scale geometry to new grid. Parameters ---------- @@ -675,21 +538,23 @@ class Geom: Assume geometry to be periodic. Defaults to True. """ - return self.duplicate(ndimage.interpolation.zoom( - self.microstructure, - grid/self.grid, - output=self.microstructure.dtype, - order=0, - mode=('wrap' if periodic else 'nearest'), - prefilter=False - ), - comments=self.comments+[util.execution_stamp('Geom','scale')], - ) + return Geom(materials = ndimage.interpolation.zoom( + self.materials, + grid/self.grid, + output=self.materials.dtype, + order=0, + mode=('wrap' if periodic else 'nearest'), + prefilter=False + ), + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','scale')], + ) def clean(self,stencil=3,selection=None,periodic=True): """ - Smooth microstructure by selecting most frequent index within given stencil at each location. + Smooth geometry by selecting most frequent material index within given stencil at each location. Parameters ---------- @@ -709,83 +574,87 @@ class Geom: else: return me - return self.duplicate(ndimage.filters.generic_filter( - self.microstructure, - mostFrequent, - size=(stencil if selection is None else stencil//2*2+1,)*3, - mode=('wrap' if periodic else 'nearest'), - extra_keywords=dict(selection=selection), - ).astype(self.microstructure.dtype), - comments=self.comments+[util.execution_stamp('Geom','clean')], - ) + return Geom(materials = ndimage.filters.generic_filter( + self.materials, + mostFrequent, + size=(stencil if selection is None else stencil//2*2+1,)*3, + mode=('wrap' if periodic else 'nearest'), + extra_keywords=dict(selection=selection), + ).astype(self.materials.dtype), + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','clean')], + ) def renumber(self): - """Renumber sorted microstructure indices to 1,...,N.""" - renumbered = np.empty(self.grid,dtype=self.microstructure.dtype) - for i, oldID in enumerate(np.unique(self.microstructure)): - renumbered = np.where(self.microstructure == oldID, i+1, renumbered) + """Renumber sorted material indices to 1,...,N.""" + renumbered = np.empty(self.grid,dtype=self.materials.dtype) + for i, oldID in enumerate(np.unique(self.materials)): + renumbered = np.where(self.materials == oldID, i+1, renumbered) - return self.duplicate(renumbered, - comments=self.comments+[util.execution_stamp('Geom','renumber')], - ) + return Geom(materials = renumbered, + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','renumber')], + ) def rotate(self,R,fill=None): """ - Rotate microstructure (pad if required). + Rotate geometry (pad if required). Parameters ---------- R : damask.Rotation - Rotation to apply to the microstructure. + Rotation to apply to the geometry. fill : int or float, optional - Microstructure index to fill the corners. Defaults to microstructure.max() + 1. + Material index to fill the corners. Defaults to materials.max() + 1. """ - if fill is None: fill = np.nanmax(self.microstructure) + 1 - dtype = float if np.isnan(fill) or int(fill) != fill or self.microstructure.dtype==np.float else int + if fill is None: fill = np.nanmax(self.materials) + 1 + dtype = float if np.isnan(fill) or int(fill) != fill or self.materials.dtype==np.float else int Eulers = R.as_Eulers(degrees=True) - microstructure_in = self.microstructure.copy() + materials_in = self.materials.copy() # These rotations are always applied in the reference coordinate system, i.e. (z,x,z) not (z,x',z'') # see https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf for angle,axes in zip(Eulers[::-1], [(0,1),(1,2),(0,1)]): - microstructure_out = ndimage.rotate(microstructure_in,angle,axes,order=0, + materials_out = ndimage.rotate(materials_in,angle,axes,order=0, prefilter=False,output=dtype,cval=fill) - if np.prod(microstructure_in.shape) == np.prod(microstructure_out.shape): + if np.prod(materials_in.shape) == np.prod(materials_out.shape): # avoid scipy interpolation errors for rotations close to multiples of 90° - microstructure_in = np.rot90(microstructure_in,k=np.rint(angle/90.).astype(int),axes=axes) + materials_in = np.rot90(materials_in,k=np.rint(angle/90.).astype(int),axes=axes) else: - microstructure_in = microstructure_out + materials_in = materials_out - origin = self.origin-(np.asarray(microstructure_in.shape)-self.grid)*.5 * self.size/self.grid + origin = self.origin-(np.asarray(materials_in.shape)-self.grid)*.5 * self.size/self.grid - return self.duplicate(microstructure_in, - origin=origin, - comments=self.comments+[util.execution_stamp('Geom','rotate')], - autosize=True, - ) + return Geom(materials = materials_in, + size = self.size/self.grid*np.asarray(materials_in.shape), + origin = origin, + comments = self.comments+[util.execution_stamp('Geom','rotate')], + ) def canvas(self,grid=None,offset=None,fill=None): """ - Crop or enlarge/pad microstructure. + Crop or enlarge/pad geometry. Parameters ---------- grid : numpy.ndarray of shape (3) Number of grid points in x,y,z direction. offset : numpy.ndarray of shape (3) - Offset (measured in grid points) from old to new microstructure[0,0,0]. + Offset (measured in grid points) from old to new geometry [0,0,0]. fill : int or float, optional - Microstructure index to fill the background. Defaults to microstructure.max() + 1. + Material index to fill the background. Defaults to materials.max() + 1. """ if offset is None: offset = 0 - if fill is None: fill = np.nanmax(self.microstructure) + 1 - dtype = float if int(fill) != fill or self.microstructure.dtype in np.sctypes['float'] else int + if fill is None: fill = np.nanmax(self.materials) + 1 + dtype = float if int(fill) != fill or self.materials.dtype in np.sctypes['float'] else int canvas = np.full(self.grid if grid is None else grid,fill,dtype) @@ -794,39 +663,41 @@ class Geom: ll = np.clip(-offset, 0,np.minimum( grid,self.grid-offset)) ur = np.clip(-offset+self.grid,0,np.minimum( grid,self.grid-offset)) - canvas[ll[0]:ur[0],ll[1]:ur[1],ll[2]:ur[2]] = self.microstructure[LL[0]:UR[0],LL[1]:UR[1],LL[2]:UR[2]] + canvas[ll[0]:ur[0],ll[1]:ur[1],ll[2]:ur[2]] = self.materials[LL[0]:UR[0],LL[1]:UR[1],LL[2]:UR[2]] - return self.duplicate(canvas, - origin=self.origin+offset*self.size/self.grid, - comments=self.comments+[util.execution_stamp('Geom','canvas')], - autosize=True, - ) + return Geom(materials = canvas, + size = self.size/self.grid*np.asarray(canvas.shape), + origin = self.origin+offset*self.size/self.grid, + comments = self.comments+[util.execution_stamp('Geom','canvas')], + ) - def substitute(self,from_microstructure,to_microstructure): + def substitute(self,from_materials,to_materials): """ - Substitute microstructure indices. + Substitute material indices. Parameters ---------- - from_microstructure : iterable of ints - Microstructure indices to be substituted. - to_microstructure : iterable of ints - New microstructure indices. + from_materials : iterable of ints + Material indices to be substituted. + to_materials : iterable of ints + New material indices. """ - substituted = self.microstructure.copy() - for from_ms,to_ms in zip(from_microstructure,to_microstructure): - substituted[self.microstructure==from_ms] = to_ms + substituted = self.materials.copy() + for from_ms,to_ms in zip(from_materials,to_materials): + substituted[self.materials==from_ms] = to_ms - return self.duplicate(substituted, - comments=self.comments+[util.execution_stamp('Geom','substitute')], - ) + return Geom(materials = substituted, + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','substitute')], + ) def vicinity_offset(self,vicinity=1,offset=None,trigger=[],periodic=True): """ - Offset microstructure index of points in the vicinity of xxx. + Offset material index of points in the vicinity of xxx. Different from themselves (or listed as triggers) within a given (cubic) vicinity, i.e. within the region close to a grain/phase boundary. @@ -835,14 +706,14 @@ class Geom: Parameters ---------- vicinity : int, optional - Voxel distance checked for presence of other microstructure. + Voxel distance checked for presence of other materials. Defaults to 1. offset : int, optional - Offset (positive or negative) to tag microstructure indices, - defaults to microstructure.max() + 1. + Offset (positive or negative) to tag material indices, + defaults to materials.max() + 1. trigger : list of ints, optional - List of microstructure indices triggering a change. - Defaults to [], meaning that different neigboors trigger a change. + List of material indices that trigger a change. + Defaults to [], meaning that any different neighbor triggers a change. periodic : Boolean, optional Assume geometry to be periodic. Defaults to True. @@ -858,14 +729,15 @@ class Geom: trigger = list(trigger) return np.any(np.in1d(stencil,np.array(trigger))) - offset_ = np.nanmax(self.microstructure) if offset is None else offset - mask = ndimage.filters.generic_filter(self.microstructure, + offset_ = np.nanmax(self.materials) if offset is None else offset + mask = ndimage.filters.generic_filter(self.materials, tainted_neighborhood, size=1+2*vicinity, mode='wrap' if periodic else 'nearest', extra_keywords={'trigger':trigger}) - microstructure = np.ma.MaskedArray(self.microstructure + offset_, np.logical_not(mask)) - return self.duplicate(microstructure, - comments=self.comments+[util.execution_stamp('Geom','vicinity_offset')], - ) + return Geom(materials = np.where(mask, self.materials + offset_,self.materials), + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','vicinity_offset')], + ) diff --git a/python/tests/test_Geom.py b/python/tests/test_Geom.py index f82272362..809aee2f9 100644 --- a/python/tests/test_Geom.py +++ b/python/tests/test_Geom.py @@ -11,8 +11,8 @@ from damask import util def geom_equal(a,b): - return np.all(a.microstructure == b.microstructure) and \ - np.all(a.grid == b.grid) and \ + return np.all(a.materials == b.materials) and \ + np.all(a.grid == b.grid) and \ np.allclose(a.size, b.size) and \ str(a.diff(b)) == str(b.diff(a)) @@ -33,64 +33,21 @@ def reference_dir(reference_dir_base): class TestGeom: - @pytest.mark.parametrize('flavor',['plain','explicit']) - def test_duplicate(self,default,flavor): - if flavor == 'plain': - modified = default.duplicate() - elif flavor == 'explicit': - modified = default.duplicate( - default.microstructure, - default.size, - default.origin - ) - print(modified) - assert geom_equal(default,modified) - def test_diff_equal(self,default): assert str(default.diff(default)) == '' + def test_diff_not_equal(self,default): - new = Geom(default.microstructure[1:,1:,1:]+1,default.size*.9,np.ones(3)-default.origin,comments=['modified']) + new = Geom(default.materials[1:,1:,1:]+1,default.size*.9,np.ones(3)-default.origin,comments=['modified']) assert str(default.diff(new)) != '' - def test_set_inplace_outofplace_homogenization(self,default): - default.set_homogenization(123,inplace=True) - outofplace = default.set_homogenization(321,inplace=False) - assert default.homogenization == 123 and outofplace.homogenization == 321 - - - def test_set_inplace_outofplace_microstructure(self,default): - default.set_microstructure(np.arange(72).reshape((2,4,9)),inplace=True) - outofplace = default.set_microstructure(np.arange(72).reshape((8,3,3)),inplace=False) - assert np.array_equal(default.grid,[2,4,9]) and np.array_equal(outofplace.grid,[8,3,3]) - - - def test_set_inplace_outofplace_size(self,default): - default.set_size(np.array([1,2,3]),inplace=True) - outofplace = default.set_size(np.array([3,2,1]),inplace=False) - assert np.array_equal(default.size,[1,2,3]) and np.array_equal(outofplace.size,[3,2,1]) - - - def test_set_inplace_outofplace_comments(self,default): - default.set_comments(['a','and','b'],inplace=True) - outofplace = default.set_comments(['b','or','a'],inplace=False) - assert default.comments == ['a','and','b'] and outofplace.comments == ['b','or','a'] - - - @pytest.mark.parametrize('masked',[True,False]) - def test_set_microstructure(self,default,masked): - old = default.microstructure - new = np.random.randint(200,size=default.grid) - default.set_microstructure(np.ma.MaskedArray(new,np.full_like(new,masked)),inplace=True) - assert np.all(default.microstructure==(old if masked else new)) - - def test_write_read_str(self,default,tmpdir): default.to_file(str(tmpdir/'default.geom'),format='ASCII') new = Geom.from_file(str(tmpdir/'default.geom')) assert geom_equal(default,new) + def test_write_read_file(self,default,tmpdir): with open(tmpdir/'default.geom','w') as f: default.to_file(f,format='ASCII',pack=True) @@ -98,6 +55,7 @@ class TestGeom: new = Geom.from_file(f) assert geom_equal(default,new) + def test_write_as_ASCII(self,default,tmpdir): with open(tmpdir/'str.geom','w') as f: f.write(default.as_ASCII()) @@ -105,6 +63,7 @@ class TestGeom: new = Geom.from_file(f) assert geom_equal(default,new) + def test_read_write_vtr(self,default,tmpdir): default.to_file(tmpdir/'default',format='vtr') for _ in range(10): @@ -114,6 +73,7 @@ class TestGeom: new = Geom.from_vtr(tmpdir/'default.vtr') assert geom_equal(new,default) + def test_invalid_geom(self,tmpdir): with open('invalid_file','w') as f: f.write('this is not a valid header') @@ -121,6 +81,7 @@ class TestGeom: with pytest.raises(TypeError): Geom.from_file(f) + def test_invalid_vtr(self,tmpdir): v = VTK.from_rectilinearGrid(np.random.randint(5,10,3)*2,np.random.random(3) + 1.0) v.to_file(tmpdir/'no_materialpoint.vtr') @@ -137,36 +98,38 @@ class TestGeom: new = Geom.from_file(tmpdir/'default.geom') assert geom_equal(new,default) - def test_invalid_combination(self,default): - with pytest.raises(ValueError): - default.duplicate(default.microstructure[1:,1:,1:],size=np.ones(3), autosize=True) def test_invalid_size(self,default): with pytest.raises(ValueError): - default.duplicate(default.microstructure[1:,1:,1:],size=np.ones(2)) + Geom(default.materials[1:,1:,1:], + size=np.ones(2)) + def test_invalid_origin(self,default): with pytest.raises(ValueError): - default.duplicate(default.microstructure[1:,1:,1:],origin=np.ones(4)) + Geom(default.materials[1:,1:,1:], + size=np.ones(3), + origin=np.ones(4)) - def test_invalid_microstructure_size(self,default): - microstructure = np.ones((3,3)) + + def test_invalid_materials_shape(self,default): + materials = np.ones((3,3)) with pytest.raises(ValueError): - default.duplicate(microstructure) + Geom(materials, + size=np.ones(3)) - def test_invalid_microstructure_type(self,default): - microstructure = np.random.randint(1,300,(3,4,5))==1 - with pytest.raises(TypeError): - default.duplicate(microstructure) - def test_invalid_homogenization(self,default): + def test_invalid_materials_type(self,default): + materials = np.random.randint(1,300,(3,4,5))==1 with pytest.raises(TypeError): - default.set_homogenization(homogenization=0) + Geom(materials) + def test_invalid_write_format(self,default): with pytest.raises(TypeError): default.to_file(format='invalid') + @pytest.mark.parametrize('directions,reflect',[ (['x'], False), (['x','y','z'],True), @@ -182,6 +145,7 @@ class TestGeom: assert geom_equal(Geom.from_file(reference), modified) + @pytest.mark.parametrize('directions',[(1,2,'y'),('a','b','x'),[1]]) def test_mirror_invalid(self,default,directions): with pytest.raises(ValueError): @@ -203,13 +167,16 @@ class TestGeom: assert geom_equal(Geom.from_file(reference), modified) + def test_flip_invariant(self,default): assert geom_equal(default,default.flip([])) + @pytest.mark.parametrize('direction',[['x'],['x','y']]) def test_flip_double(self,default,direction): assert geom_equal(default,default.flip(direction).flip(direction)) + @pytest.mark.parametrize('directions',[(1,2,'y'),('a','b','x'),[1]]) def test_flip_invalid(self,default,directions): with pytest.raises(ValueError): @@ -231,6 +198,7 @@ class TestGeom: current ) + @pytest.mark.parametrize('grid',[ (10,11,10), [10,13,10], @@ -248,22 +216,29 @@ class TestGeom: assert geom_equal(Geom.from_file(reference), modified) + def test_renumber(self,default): - microstructure = default.microstructure.copy() - for m in np.unique(microstructure): - microstructure[microstructure==m] = microstructure.max() + np.random.randint(1,30) - modified = default.duplicate(microstructure) + materials = default.materials.copy() + for m in np.unique(materials): + materials[materials==m] = materials.max() + np.random.randint(1,30) + modified = Geom(materials, + default.size, + default.origin) assert not geom_equal(modified,default) assert geom_equal(default, modified.renumber()) + def test_substitute(self,default): offset = np.random.randint(1,500) - modified = default.duplicate(default.microstructure + offset) + modified = Geom(default.materials + offset, + default.size, + default.origin) assert not geom_equal(modified,default) assert geom_equal(default, - modified.substitute(np.arange(default.microstructure.max())+1+offset, - np.arange(default.microstructure.max())+1)) + modified.substitute(np.arange(default.materials.max())+1+offset, + np.arange(default.materials.max())+1)) + @pytest.mark.parametrize('axis_angle',[np.array([1,0,0,86.7]), np.array([0,1,0,90.4]), np.array([0,0,1,90]), np.array([1,0,0,175]),np.array([0,-1,0,178]),np.array([0,0,1,180])]) @@ -273,6 +248,7 @@ class TestGeom: modified.rotate(Rotation.from_axis_angle(axis_angle,degrees=True)) assert geom_equal(default,modified) + @pytest.mark.parametrize('Eulers',[[32.0,68.0,21.0], [0.0,32.0,240.0]]) def test_rotate(self,default,update,reference_dir,Eulers): @@ -283,11 +259,13 @@ class TestGeom: assert geom_equal(Geom.from_file(reference), modified) + def test_canvas(self,default): grid = default.grid grid_add = np.random.randint(0,30,(3)) modified = default.canvas(grid + grid_add) - assert np.all(modified.microstructure[:grid[0],:grid[1],:grid[2]] == default.microstructure) + assert np.all(modified.materials[:grid[0],:grid[1],:grid[2]] == default.materials) + @pytest.mark.parametrize('center1,center2',[(np.random.random(3)*.5,np.random.random()*8), (np.random.randint(4,8,(3)),np.random.randint(9,12,(3)))]) @@ -300,13 +278,14 @@ class TestGeom: np.random.rand()*4, np.random.randint(20)]) def test_add_primitive_shift(self,center1,center2,diameter,exponent): - """Same volume fraction for periodic microstructures and different center.""" + """Same volume fraction for periodic geometries and different center.""" o = np.random.random(3)-.5 g = np.random.randint(8,32,(3)) s = np.random.random(3)+.5 G_1 = Geom(np.ones(g,'i'),s,o).add_primitive(diameter,center1,exponent) G_2 = Geom(np.ones(g,'i'),s,o).add_primitive(diameter,center2,exponent) - assert np.count_nonzero(G_1.microstructure!=2) == np.count_nonzero(G_2.microstructure!=2) + assert np.count_nonzero(G_1.materials!=2) == np.count_nonzero(G_2.materials!=2) + @pytest.mark.parametrize('center',[np.random.randint(4,10,(3)), np.random.randint(2,10), @@ -323,6 +302,7 @@ class TestGeom: G_2 = Geom(np.ones(g,'i'),[1.,1.,1.]).add_primitive(.3,center,1,fill,Rotation.from_Eulers(eu),inverse,periodic=periodic) assert geom_equal(G_1,G_2) + @pytest.mark.parametrize('trigger',[[1],[]]) def test_vicinity_offset(self,trigger): offset = np.random.randint(2,4) @@ -341,13 +321,15 @@ class TestGeom: geom = Geom(m,np.random.rand(3)).vicinity_offset(vicinity,offset,trigger=trigger) - assert np.all(m2==geom.microstructure) + assert np.all(m2==geom.materials) + @pytest.mark.parametrize('periodic',[True,False]) def test_vicinity_offset_invariant(self,default,periodic): - offset = default.vicinity_offset(trigger=[default.microstructure.max()+1, - default.microstructure.min()-1]) - assert np.all(offset.microstructure==default.microstructure) + offset = default.vicinity_offset(trigger=[default.materials.max()+1, + default.materials.min()-1]) + assert np.all(offset.materials==default.materials) + @pytest.mark.parametrize('periodic',[True,False]) def test_tessellation_approaches(self,periodic): @@ -359,6 +341,7 @@ class TestGeom: Laguerre = Geom.from_Laguerre_tessellation(grid,size,seeds,np.ones(N_seeds),periodic) assert geom_equal(Laguerre,Voronoi) + def test_Laguerre_weights(self): grid = np.random.randint(10,20,3) size = np.random.random(3) + 1.0 @@ -368,17 +351,18 @@ class TestGeom: ms = np.random.randint(1, N_seeds+1) weights[ms-1] = np.random.random() Laguerre = Geom.from_Laguerre_tessellation(grid,size,seeds,weights,np.random.random()>0.5) - assert np.all(Laguerre.microstructure == ms) + assert np.all(Laguerre.materials == ms) + @pytest.mark.parametrize('approach',['Laguerre','Voronoi']) def test_tessellate_bicrystal(self,approach): grid = np.random.randint(5,10,3)*2 size = grid.astype(np.float) seeds = np.vstack((size*np.array([0.5,0.25,0.5]),size*np.array([0.5,0.75,0.5]))) - microstructure = np.ones(grid) - microstructure[:,grid[1]//2:,:] = 2 + materials = np.ones(grid) + materials[:,grid[1]//2:,:] = 2 if approach == 'Laguerre': geom = Geom.from_Laguerre_tessellation(grid,size,seeds,np.ones(2),np.random.random()>0.5) elif approach == 'Voronoi': geom = Geom.from_Voronoi_tessellation(grid,size,seeds, np.random.random()>0.5) - assert np.all(geom.microstructure == microstructure) + assert np.all(geom.materials == materials) From 997f7dfa0565b43be41ce148d8dfd10ee86d760b Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Tue, 22 Sep 2020 20:03:41 -0400 Subject: [PATCH 51/61] removed Geom.homogenization from shell scripts --- PRIVATE | 2 +- processing/pre/geom_fromDREAM3D.py | 8 +-- processing/pre/geom_fromMinimalSurface.py | 6 -- processing/pre/geom_fromOsteonGeometry.py | 8 +-- processing/pre/geom_fromTable.py | 9 +-- .../pre/geom_fromVoronoiTessellation.py | 7 +- processing/pre/geom_grainGrowth.py | 66 ++++++++++--------- processing/pre/seeds_fromDistribution.py | 46 ++++++------- processing/pre/seeds_fromGeom.py | 2 +- processing/pre/seeds_fromPokes.py | 8 +-- 10 files changed, 69 insertions(+), 93 deletions(-) diff --git a/PRIVATE b/PRIVATE index fa2885da8..86f77da4a 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit fa2885da8604c3ac46f64670393f04678dd1f45b +Subproject commit 86f77da4aec6cb52bbcc2724f00a6cf6a7dc6e91 diff --git a/processing/pre/geom_fromDREAM3D.py b/processing/pre/geom_fromDREAM3D.py index 3faa07a17..daf7d2ab9 100755 --- a/processing/pre/geom_fromDREAM3D.py +++ b/processing/pre/geom_fromDREAM3D.py @@ -52,16 +52,11 @@ parser.add_option('-q', '--quaternion', type = 'string', metavar='string', help = 'name of the dataset containing pointwise/average orientation as quaternion [%default]') -parser.add_option('--homogenization', - dest = 'homogenization', - type = 'int', metavar = 'int', - help = 'homogenization index to be used [%default]') parser.set_defaults(pointwise = 'CellData', quaternion = 'Quats', phase = 'Phases', microstructure = 'FeatureIds', - homogenization = 1, ) (options, filenames) = parser.parse_args() @@ -150,8 +145,7 @@ for name in filenames: header = [scriptID + ' ' + ' '.join(sys.argv[1:])]\ + config_header - geom = damask.Geom(microstructure,size,origin, - homogenization=options.homogenization,comments=header) + geom = damask.Geom(microstructure,size,origin,comments=header) damask.util.croak(geom) geom.save_ASCII(os.path.splitext(name)[0]+'.geom',compress=False) diff --git a/processing/pre/geom_fromMinimalSurface.py b/processing/pre/geom_fromMinimalSurface.py index b52003d79..83d1a3684 100755 --- a/processing/pre/geom_fromMinimalSurface.py +++ b/processing/pre/geom_fromMinimalSurface.py @@ -52,10 +52,6 @@ parser.add_option('-p', '--periods', dest = 'periods', type = 'int', metavar = 'int', help = 'number of repetitions of unit cell [%default]') -parser.add_option('--homogenization', - dest = 'homogenization', - type = 'int', metavar = 'int', - help = 'homogenization index to be used [%default]') parser.add_option('--m', dest = 'microstructure', type = 'int', nargs = 2, metavar = 'int int', @@ -66,7 +62,6 @@ parser.set_defaults(type = minimal_surfaces[0], periods = 1, grid = (16,16,16), size = (1.0,1.0,1.0), - homogenization = 1, microstructure = (1,2), ) @@ -85,7 +80,6 @@ microstructure = np.where(options.threshold < surface[options.type](x,y,z), options.microstructure[1],options.microstructure[0]) geom=damask.Geom(microstructure,options.size, - homogenization=options.homogenization, comments=[scriptID + ' ' + ' '.join(sys.argv[1:])]) damask.util.croak(geom) diff --git a/processing/pre/geom_fromOsteonGeometry.py b/processing/pre/geom_fromOsteonGeometry.py index 0b1440d63..2f9de712d 100755 --- a/processing/pre/geom_fromOsteonGeometry.py +++ b/processing/pre/geom_fromOsteonGeometry.py @@ -57,10 +57,6 @@ parser.add_option('-w', '--omega', dest='omega', type='float', metavar = 'float', help='rotation angle around normal of osteon [%default]') -parser.add_option( '--homogenization', - dest='homogenization', - type='int', metavar = 'int', - help='homogenization index to be used [%default]') parser.set_defaults(canal = 25e-6, osteon = 100e-6, @@ -70,7 +66,7 @@ parser.set_defaults(canal = 25e-6, amplitude = 60, size = (300e-6,300e-6), grid = (512,512), - homogenization = 1) + ) (options,filename) = parser.parse_args() @@ -139,7 +135,7 @@ header = [scriptID + ' ' + ' '.join(sys.argv[1:])]\ + config_header geom = damask.Geom(microstructure.reshape(grid), size,-size/2, - homogenization=options.homogenization,comments=header) + comments=header) damask.util.croak(geom) geom.save_ASCII(sys.stdout if name is None else name,compress=False) diff --git a/processing/pre/geom_fromTable.py b/processing/pre/geom_fromTable.py index 6f2cb5b4d..a0de6a4c5 100755 --- a/processing/pre/geom_fromTable.py +++ b/processing/pre/geom_fromTable.py @@ -44,14 +44,9 @@ parser.add_option('--axes', dest = 'axes', type = 'string', nargs = 3, metavar = ' '.join(['string']*3), help = 'orientation coordinate frame in terms of position coordinate frame [+x +y +z]') -parser.add_option('--homogenization', - dest = 'homogenization', - type = 'int', metavar = 'int', - help = 'homogenization index to be used [%default]') -parser.set_defaults(homogenization = 1, - pos = 'pos', +parser.set_defaults(pos = 'pos', ) (options,filenames) = parser.parse_args() @@ -102,7 +97,7 @@ for name in filenames: header = [scriptID + ' ' + ' '.join(sys.argv[1:])]\ + config_header geom = damask.Geom(microstructure,size,origin, - homogenization=options.homogenization,comments=header) + comments=header) damask.util.croak(geom) geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',compress=False) diff --git a/processing/pre/geom_fromVoronoiTessellation.py b/processing/pre/geom_fromVoronoiTessellation.py index 5586d3bc8..aee79cc05 100755 --- a/processing/pre/geom_fromVoronoiTessellation.py +++ b/processing/pre/geom_fromVoronoiTessellation.py @@ -142,10 +142,6 @@ group.add_option('--without-config', dest = 'config', action = 'store_false', help = 'omit material configuration header') -group.add_option('--homogenization', - dest = 'homogenization', - type = 'int', metavar = 'int', - help = 'homogenization index to be used [%default]') group.add_option('--phase', dest = 'phase', type = 'int', metavar = 'int', @@ -157,7 +153,6 @@ parser.set_defaults(pos = 'pos', weight = 'weight', microstructure = 'microstructure', eulers = 'euler', - homogenization = 1, phase = 1, cpus = 2, laguerre = False, @@ -225,7 +220,7 @@ for name in filenames: header = [scriptID + ' ' + ' '.join(sys.argv[1:])]\ + config_header geom = damask.Geom(indices.reshape(grid),size,origin, - homogenization=options.homogenization,comments=header) + comments=header) damask.util.croak(geom) geom.save_ASCII(sys.stdout if name is None else os.path.splitext(name)[0]+'.geom',compress=False) diff --git a/processing/pre/geom_grainGrowth.py b/processing/pre/geom_grainGrowth.py index 88e75a841..a573a9fed 100755 --- a/processing/pre/geom_grainGrowth.py +++ b/processing/pre/geom_grainGrowth.py @@ -41,7 +41,7 @@ parser.add_option('-N', '--iterations', help = 'curvature flow iterations [%default]') parser.add_option('-i', '--immutable', action = 'extend', dest = 'immutable', metavar = '', - help = 'list of immutable microstructure indices') + help = 'list of immutable material indices') parser.add_option('--ndimage', dest = 'ndimage', action='store_true', help = 'use ndimage.gaussian_filter in lieu of explicit FFT') @@ -66,13 +66,13 @@ for name in filenames: grid_original = geom.grid damask.util.croak(geom) - microstructure = np.tile(geom.microstructure,np.where(grid_original == 1, 2,1)) # make one copy along dimensions with grid == 1 - grid = np.array(microstructure.shape) + materials = np.tile(geom.materials,np.where(grid_original == 1, 2,1)) # make one copy along dimensions with grid == 1 + grid = np.array(materials.shape) # --- initialize support data --------------------------------------------------------------------- -# store a copy the initial microstructure to find locations of immutable indices - microstructure_original = np.copy(microstructure) +# store a copy of the initial material indices to find locations of immutable indices + materials_original = np.copy(materials) if not options.ndimage: X,Y,Z = np.mgrid[0:grid[0],0:grid[1],0:grid[2]] @@ -88,14 +88,14 @@ for name in filenames: for smoothIter in range(options.N): - interfaceEnergy = np.zeros(microstructure.shape,dtype=np.float32) + interfaceEnergy = np.zeros(materials.shape,dtype=np.float32) for i in (-1,0,1): for j in (-1,0,1): for k in (-1,0,1): # assign interfacial energy to all voxels that have a differing neighbor (in Moore neighborhood) interfaceEnergy = np.maximum(interfaceEnergy, - getInterfaceEnergy(microstructure,np.roll(np.roll(np.roll( - microstructure,i,axis=0), j,axis=1), k,axis=2))) + getInterfaceEnergy(materials,np.roll(np.roll(np.roll( + materials,i,axis=0), j,axis=1), k,axis=2))) # periodically extend interfacial energy array by half a grid size in positive and negative directions periodic_interfaceEnergy = np.tile(interfaceEnergy,(3,3,3))[grid[0]//2:-grid[0]//2, @@ -129,13 +129,13 @@ for name in filenames: iterations = int(round(options.d*2.))-1),# fat boundary periodic_bulkEnergy[grid[0]//2:-grid[0]//2, # retain filled energy on fat boundary... grid[1]//2:-grid[1]//2, - grid[2]//2:-grid[2]//2], # ...and zero everywhere else + grid[2]//2:-grid[2]//2], # ...and zero everywhere else 0.)).astype(np.complex64) * gauss).astype(np.float32) periodic_diffusedEnergy = np.tile(diffusedEnergy,(3,3,3))[grid[0]//2:-grid[0]//2, grid[1]//2:-grid[1]//2, - grid[2]//2:-grid[2]//2] # periodically extend the smoothed bulk energy + grid[2]//2:-grid[2]//2] # periodically extend the smoothed bulk energy # transform voxels close to interface region @@ -143,33 +143,35 @@ for name in filenames: return_distances = False, return_indices = True) # want index of closest bulk grain - periodic_microstructure = np.tile(microstructure,(3,3,3))[grid[0]//2:-grid[0]//2, - grid[1]//2:-grid[1]//2, - grid[2]//2:-grid[2]//2] # periodically extend the microstructure + periodic_materials = np.tile(materials,(3,3,3))[grid[0]//2:-grid[0]//2, + grid[1]//2:-grid[1]//2, + grid[2]//2:-grid[2]//2] # periodically extend the geometry - microstructure = periodic_microstructure[index[0], - index[1], - index[2]].reshape(2*grid)[grid[0]//2:-grid[0]//2, - grid[1]//2:-grid[1]//2, - grid[2]//2:-grid[2]//2] # extent grains into interface region + materials = periodic_materials[index[0], + index[1], + index[2]].reshape(2*grid)[grid[0]//2:-grid[0]//2, + grid[1]//2:-grid[1]//2, + grid[2]//2:-grid[2]//2] # extent grains into interface region - # replace immutable microstructures with closest mutable ones - index = ndimage.morphology.distance_transform_edt(np.in1d(microstructure,options.immutable).reshape(grid), + # replace immutable materials with closest mutable ones + index = ndimage.morphology.distance_transform_edt(np.in1d(materials,options.immutable).reshape(grid), return_distances = False, return_indices = True) - microstructure = microstructure[index[0], - index[1], - index[2]] + materials = materials[index[0], + index[1], + index[2]] - immutable = np.zeros(microstructure.shape, dtype=np.bool) - # find locations where immutable microstructures have been in original structure + immutable = np.zeros(materials.shape, dtype=np.bool) + # find locations where immutable materials have been in original structure for micro in options.immutable: - immutable += microstructure_original == micro + immutable += materials_original == micro - # undo any changes involving immutable microstructures - microstructure = np.where(immutable, microstructure_original,microstructure) + # undo any changes involving immutable materials + materials = np.where(immutable, materials_original,materials) - geom = geom.duplicate(microstructure[0:grid_original[0],0:grid_original[1],0:grid_original[2]]) - geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:])) - - geom.save_ASCII(sys.stdout if name is None else name,compress=False) + damask.Geom(materials = materials[0:grid_original[0],0:grid_original[1],0:grid_original[2]], + size = geom.size, + origin = geom.origin, + comments = geom.comments + [scriptID + ' ' + ' '.join(sys.argv[1:])], + )\ + .save_ASCII(sys.stdout if name is None else name,compress=False) diff --git a/processing/pre/seeds_fromDistribution.py b/processing/pre/seeds_fromDistribution.py index e1e4726c2..030f3d6fa 100755 --- a/processing/pre/seeds_fromDistribution.py +++ b/processing/pre/seeds_fromDistribution.py @@ -30,7 +30,7 @@ class myThread (threading.Thread): def run(self): global bestSeedsUpdate global bestSeedsVFile - global nMicrostructures + global nMaterials global delta global points global target @@ -70,7 +70,7 @@ class myThread (threading.Thread): selectedMs = [] direction = [] for i in range(NmoveGrains): - selectedMs.append(random.randrange(1,nMicrostructures)) + selectedMs.append(random.randrange(1,nMaterials)) direction.append((np.random.random()-0.5)*delta) @@ -101,11 +101,11 @@ class myThread (threading.Thread): #--- evaluate current seeds file ------------------------------------------------------------------ perturbedGeom = damask.Geom.load_ASCII(perturbedGeomVFile) - myNmicrostructures = len(np.unique(perturbedGeom.microstructure)) - currentData=np.bincount(perturbedGeom.microstructure.ravel())[1:]/points + myNmaterials = len(np.unique(perturbedGeom.materials)) + currentData=np.bincount(perturbedGeom.materials.ravel())[1:]/points currentError=[] currentHist=[] - for i in range(nMicrostructures): # calculate the deviation in all bins per histogram + for i in range(nMaterials): # calculate the deviation in all bins per histogram currentHist.append(np.histogram(currentData,bins=target[i]['bins'])[0]) currentError.append(np.sqrt(np.square(np.array(target[i]['histogram']-currentHist[i])).sum())) @@ -117,12 +117,12 @@ class myThread (threading.Thread): bestMatch = match #--- count bin classes with no mismatch ---------------------------------------------------------------------- myMatch=0 - for i in range(nMicrostructures): + for i in range(nMaterials): if currentError[i] > 0.0: break myMatch = i+1 - if myNmicrostructures == nMicrostructures: - for i in range(min(nMicrostructures,myMatch+options.bins)): + if myNmaterials == nMaterials: + for i in range(min(nMaterials,myMatch+options.bins)): if currentError[i] > target[i]['error']: # worse fitting, next try randReset = True break @@ -141,25 +141,25 @@ class myThread (threading.Thread): for line in perturbedSeedsVFile: currentSeedsFile.write(line) bestSeedsVFile.write(line) - for j in range(nMicrostructures): # save new errors for all bins + for j in range(nMaterials): # save new errors for all bins target[j]['error'] = currentError[j] if myMatch > match: # one or more new bins have no deviation damask.util.croak( 'Stage {:d} cleared'.format(myMatch)) match=myMatch sys.stdout.flush() break - if i == min(nMicrostructures,myMatch+options.bins)-1: # same quality as before: take it to keep on moving + if i == min(nMaterials,myMatch+options.bins)-1: # same quality as before: take it to keep on moving bestSeedsUpdate = time.time() perturbedSeedsVFile.seek(0) bestSeedsVFile.close() bestSeedsVFile = StringIO() bestSeedsVFile.writelines(perturbedSeedsVFile.readlines()) - for j in range(nMicrostructures): + for j in range(nMaterials): target[j]['error'] = currentError[j] randReset = True else: #--- not all grains are tessellated - damask.util.croak('Thread {:d}: Microstructure mismatch ({:d} microstructures mapped)'\ - .format(self.threadID,myNmicrostructures)) + damask.util.croak('Thread {:d}: Material mismatch ({:d} material indices mapped)'\ + .format(self.threadID,myNmaterials)) randReset = True @@ -217,10 +217,10 @@ points = np.array(options.grid).prod().astype('float') # ----------- calculate target distribution and bin edges targetGeom = damask.Geom.load_ASCII(os.path.splitext(os.path.basename(options.target))[0]+'.geom') -nMicrostructures = len(np.unique(targetGeom.microstructure)) -targetVolFrac = np.bincount(targetGeom.microstructure.flatten())/targetGeom.grid.prod().astype(np.float) +nMaterials = len(np.unique(targetGeom.materials)) +targetVolFrac = np.bincount(targetGeom.materials.flatten())/targetGeom.grid.prod().astype(np.float) target = [] -for i in range(1,nMicrostructures+1): +for i in range(1,nMaterials+1): targetHist,targetBins = np.histogram(targetVolFrac,bins=i) #bin boundaries target.append({'histogram':targetHist,'bins':targetBins}) @@ -233,7 +233,7 @@ else: bestSeedsVFile.write(damask.util.execute('seeds_fromRandom'+\ ' -g '+' '.join(list(map(str, options.grid)))+\ ' -r {:d}'.format(options.randomSeed)+\ - ' -N '+str(nMicrostructures))[0]) + ' -N '+str(nMaterials))[0]) bestSeedsUpdate = time.time() # ----------- tessellate initial seed file to get and evaluate geom file @@ -244,11 +244,11 @@ initialGeomVFile.write(damask.util.execute('geom_fromVoronoiTessellation '+ initialGeomVFile.seek(0) initialGeom = damask.Geom.load_ASCII(initialGeomVFile) -if len(np.unique(targetGeom.microstructure)) != nMicrostructures: - damask.util.croak('error. Microstructure count mismatch') +if len(np.unique(targetGeom.materials)) != nMaterials: + damask.util.croak('error. Material count mismatch') -initialData = np.bincount(initialGeom.microstructure.flatten())/points -for i in range(nMicrostructures): +initialData = np.bincount(initialGeom.materials.flatten())/points +for i in range(nMaterials): initialHist = np.histogram(initialData,bins=target[i]['bins'])[0] target[i]['error']=np.sqrt(np.square(np.array(target[i]['histogram']-initialHist)).sum()) @@ -257,13 +257,13 @@ if target[0]['error'] > 0.0: target[0]['error'] *=((target[0]['bins'][0]-np.min(initialData))**2.0+ (target[0]['bins'][1]-np.max(initialData))**2.0)**0.5 match=0 -for i in range(nMicrostructures): +for i in range(nMaterials): if target[i]['error'] > 0.0: break match = i+1 if options.maxseeds < 1: - maxSeeds = len(np.unique(initialGeom.microstructure)) + maxSeeds = len(np.unique(initialGeom.materials)) else: maxSeeds = options.maxseeds diff --git a/processing/pre/seeds_fromGeom.py b/processing/pre/seeds_fromGeom.py index 99e7c0ca9..de95b439d 100755 --- a/processing/pre/seeds_fromGeom.py +++ b/processing/pre/seeds_fromGeom.py @@ -61,7 +61,7 @@ for name in filenames: 'grid\ta {}\tb {}\tc {}'.format(*geom.grid), 'size\tx {}\ty {}\tz {}'.format(*geom.size), 'origin\tx {}\ty {}\tz {}'.format(*geom.origin), - 'homogenization\t{}'.format(geom.homogenization)] + ] damask.Table(seeds[mask],{'pos':(3,)},comments)\ .add('material',materials[mask].astype(int))\ diff --git a/processing/pre/seeds_fromPokes.py b/processing/pre/seeds_fromPokes.py index c804cd285..ff9d250fc 100755 --- a/processing/pre/seeds_fromPokes.py +++ b/processing/pre/seeds_fromPokes.py @@ -76,7 +76,7 @@ for name in filenames: g[2] = k + offset[2] g %= geom.grid seeds[n,0:3] = (g+0.5)/geom.grid # normalize coordinates to box - seeds[n, 3] = geom.microstructure[g[0],g[1],g[2]] + seeds[n, 3] = geom.materials[g[0],g[1],g[2]] if options.x: g[0] += 1 if options.y: g[1] += 1 n += 1 @@ -88,9 +88,9 @@ for name in filenames: 'grid\ta {}\tb {}\tc {}'.format(*geom.grid), 'size\tx {}\ty {}\tz {}'.format(*geom.size), 'origin\tx {}\ty {}\tz {}'.format(*geom.origin), - 'homogenization\t{}'.format(geom.homogenization)] + ] - table = damask.Table(seeds,{'pos':(3,),'microstructure':(1,)},comments) - table.set('microstructure',table.get('microstructure').astype(np.int))\ + table = damask.Table(seeds,{'pos':(3,),'material':(1,)},comments) + table.set('material',table.get('material').astype(np.int))\ .save(sys.stdout if name is None else \ os.path.splitext(name)[0]+f'_poked_{options.N}.seeds',legacy=True) From 0850b4166b27bf439954be793dc1281ccd09d444 Mon Sep 17 00:00:00 2001 From: Test User Date: Wed, 23 Sep 2020 13:24:00 +0200 Subject: [PATCH 52/61] [skip ci] updated version information after successful test of v3.0.0-alpha-292-g14bfaa60c --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index a05ebe3cf..75b7b823b 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v3.0.0-alpha-275-g7801f527f +v3.0.0-alpha-292-g14bfaa60c From 0cbb419b26647dcb6ba6a9e64464695b40f8ae26 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Wed, 23 Sep 2020 09:43:29 -0400 Subject: [PATCH 53/61] PRIVATE/testint/pytest grid missed some renaming of microstructure --> materials --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 86f77da4a..c7accae52 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 86f77da4aec6cb52bbcc2724f00a6cf6a7dc6e91 +Subproject commit c7accae5211531f4282285620df909b74fadd4af From a145f317bfcafb89fda98b4b0fed0e94d9d60c2f Mon Sep 17 00:00:00 2001 From: Test User Date: Wed, 23 Sep 2020 15:59:18 +0200 Subject: [PATCH 54/61] [skip ci] updated version information after successful test of v3.0.0-alpha-301-gc31482b1c --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index a05ebe3cf..63a86fac9 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v3.0.0-alpha-275-g7801f527f +v3.0.0-alpha-301-gc31482b1c From cfeec531780f9ce2d04cbac438b9f514f4cf83d8 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Wed, 23 Sep 2020 21:08:42 +0200 Subject: [PATCH 55/61] dataset is called 'material', not 'materialpoint' avoid infinite loop in case it is not found --- src/grid/discretization_grid.f90 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/grid/discretization_grid.f90 b/src/grid/discretization_grid.f90 index 276dd566f..271f766e2 100644 --- a/src/grid/discretization_grid.f90 +++ b/src/grid/discretization_grid.f90 @@ -366,9 +366,8 @@ subroutine readVTR(grid,geomSize,origin,microstructure) gotCellData = .true. startPos = endPos + 2_pI64 do while (index(fileContent(startPos:endPos),'',kind=pI64) == 0_pI64) - endPos = startPos + index(fileContent(startPos:),IO_EOL,kind=pI64) - 2_pI64 if(index(fileContent(startPos:endPos),'',kind=pI64) /= 0_pI64) then gotCoordinates = .true. From 8c83566b71ff0f83049817584a44a58842d975cb Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Wed, 23 Sep 2020 21:10:10 +0200 Subject: [PATCH 56/61] suppress warning we already handle the invalid FPE --- python/damask/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/damask/util.py b/python/damask/util.py index 6432ed4e1..0a9303dce 100644 --- a/python/damask/util.py +++ b/python/damask/util.py @@ -172,7 +172,7 @@ def scale_to_coprime(v): m = (np.array(v) * reduce(lcm, map(lambda x: int(get_square_denominator(x)),v)) ** 0.5).astype(np.int) m = m//reduce(np.gcd,m) - with np.errstate(divide='ignore'): + with np.errstate(invalid='ignore'): if not np.allclose(np.ma.masked_invalid(v/m),v[np.argmax(abs(v))]/m[np.argmax(abs(v))]): raise ValueError(f'Invalid result {m} for input {v}. Insufficient precision?') From fa413efcbb88942145cc8e96bd34d7fbfe298727 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Wed, 23 Sep 2020 21:25:14 +0200 Subject: [PATCH 57/61] microstructure -> material --- PRIVATE | 2 +- src/grid/discretization_grid.f90 | 38 +++++++++++++++----------------- src/marc/discretization_marc.f90 | 32 +++++++++++++-------------- 3 files changed, 35 insertions(+), 37 deletions(-) diff --git a/PRIVATE b/PRIVATE index c7accae52..ff07e6d60 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit c7accae5211531f4282285620df909b74fadd4af +Subproject commit ff07e6d60bffff734572d46ab1dec1c2280dc4fe diff --git a/src/grid/discretization_grid.f90 b/src/grid/discretization_grid.f90 index 271f766e2..e3c31c345 100644 --- a/src/grid/discretization_grid.f90 +++ b/src/grid/discretization_grid.f90 @@ -56,7 +56,7 @@ subroutine discretization_grid_init(restart) myGrid !< domain grid of this process integer, dimension(:), allocatable :: & - microstructureAt + materialAt integer :: & j, & @@ -68,9 +68,9 @@ subroutine discretization_grid_init(restart) write(6,'(/,a)') ' <<<+- discretization_grid init -+>>>'; flush(6) if(index(interface_geomFile,'.vtr') /= 0) then - call readVTR(grid,geomSize,origin,microstructureAt) + call readVTR(grid,geomSize,origin,materialAt) else - call readGeom(grid,geomSize,origin,microstructureAt) + call readGeom(grid,geomSize,origin,materialAt) endif print'(/,a,3(i12 ))', ' grid a b c: ', grid @@ -102,10 +102,9 @@ subroutine discretization_grid_init(restart) !-------------------------------------------------------------------------------------------------- ! general discretization - microstructureAt = microstructureAt(product(grid(1:2))*grid3Offset+1: & - product(grid(1:2))*(grid3Offset+grid3)) ! reallocate/shrink in case of MPI + materialAt = materialAt(product(grid(1:2))*grid3Offset+1:product(grid(1:2))*(grid3Offset+grid3)) ! reallocate/shrink in case of MPI - call discretization_init(microstructureAt, & + call discretization_init(materialAt, & IPcoordinates0(myGrid,mySize,grid3Offset), & Nodes0(myGrid,mySize,grid3Offset),& merge((grid(1)+1) * (grid(2)+1) * (grid3+1),& ! write bottom layer @@ -147,7 +146,7 @@ end subroutine discretization_grid_init !> @details important variables have an implicit "save" attribute. Therefore, this function is ! supposed to be called only once! !-------------------------------------------------------------------------------------------------- -subroutine readGeom(grid,geomSize,origin,microstructure) +subroutine readGeom(grid,geomSize,origin,material) integer, dimension(3), intent(out) :: & grid ! grid (across all processes!) @@ -155,7 +154,7 @@ subroutine readGeom(grid,geomSize,origin,microstructure) geomSize, & ! size (across all processes!) origin ! origin (across all processes!) integer, dimension(:), intent(out), allocatable :: & - microstructure + material character(len=:), allocatable :: rawData character(len=65536) :: line @@ -167,7 +166,7 @@ subroutine readGeom(grid,geomSize,origin,microstructure) startPos, endPos, & myStat, & l, & !< line counter - c, & !< counter for # microstructures in line + c, & !< counter for # materials in line o, & !< order of "to" packing e, & !< "element", i.e. spectral collocation point i, j @@ -266,7 +265,7 @@ subroutine readGeom(grid,geomSize,origin,microstructure) if(any(geomSize < 0.0_pReal)) & call IO_error(error_ID = 842, ext_msg='size (readGeom)') - allocate(microstructure(product(grid)), source = -1) ! too large in case of MPI (shrink later, not very elegant) + allocate(material(product(grid)), source = -1) ! too large in case of MPI (shrink later, not very elegant) !-------------------------------------------------------------------------------------------------- ! read and interpret content @@ -281,18 +280,18 @@ subroutine readGeom(grid,geomSize,origin,microstructure) noCompression: if (chunkPos(1) /= 3) then c = chunkPos(1) - microstructure(e:e+c-1) = [(IO_intValue(line,chunkPos,i+1), i=0, c-1)] + material(e:e+c-1) = [(IO_intValue(line,chunkPos,i+1), i=0, c-1)] else noCompression compression: if (IO_lc(IO_stringValue(line,chunkPos,2)) == 'of') then c = IO_intValue(line,chunkPos,1) - microstructure(e:e+c-1) = [(IO_intValue(line,chunkPos,3),i = 1,IO_intValue(line,chunkPos,1))] + material(e:e+c-1) = [(IO_intValue(line,chunkPos,3),i = 1,IO_intValue(line,chunkPos,1))] else if (IO_lc(IO_stringValue(line,chunkPos,2)) == 'to') then compression c = abs(IO_intValue(line,chunkPos,3) - IO_intValue(line,chunkPos,1)) + 1 o = merge(+1, -1, IO_intValue(line,chunkPos,3) > IO_intValue(line,chunkPos,1)) - microstructure(e:e+c-1) = [(i, i = IO_intValue(line,chunkPos,1),IO_intValue(line,chunkPos,3),o)] + material(e:e+c-1) = [(i, i = IO_intValue(line,chunkPos,1),IO_intValue(line,chunkPos,3),o)] else compression c = chunkPos(1) - microstructure(e:e+c-1) = [(IO_intValue(line,chunkPos,i+1), i=0, c-1)] + material(e:e+c-1) = [(IO_intValue(line,chunkPos,i+1), i=0, c-1)] endif compression endif noCompression @@ -308,7 +307,7 @@ end subroutine readGeom !> @brief Parse vtk rectilinear grid (.vtr) !> @details https://vtk.org/Wiki/VTK_XML_Formats !-------------------------------------------------------------------------------------------------- -subroutine readVTR(grid,geomSize,origin,microstructure) +subroutine readVTR(grid,geomSize,origin,material) integer, dimension(3), intent(out) :: & grid ! grid (across all processes!) @@ -316,7 +315,7 @@ subroutine readVTR(grid,geomSize,origin,microstructure) geomSize, & ! size (across all processes!) origin ! origin (across all processes!) integer, dimension(:), intent(out), allocatable :: & - microstructure + material character(len=:), allocatable :: fileContent, dataType, headerType logical :: inFile,inGrid,gotCoordinates,gotCellData,compressed @@ -364,7 +363,6 @@ subroutine readVTR(grid,geomSize,origin,microstructure) else if(index(fileContent(startPos:endPos),'',kind=pI64) /= 0_pI64) then gotCellData = .true. - startPos = endPos + 2_pI64 do while (index(fileContent(startPos:endPos),'',kind=pI64) == 0_pI64) if(index(fileContent(startPos:endPos),' nElems) call IO_error(602,ext_msg='element') @@ -103,7 +103,7 @@ subroutine discretization_marc_init call buildIPcoordinates(IP_reshaped,reshape(connectivity_cell,[elem%NcellNodesPerCell,& elem%nIPs*nElems]),node0_cell) - call discretization_init(microstructureAt,& + call discretization_init(materialAt,& IP_reshaped,& node0_cell) @@ -172,7 +172,7 @@ end subroutine writeGeometry !-------------------------------------------------------------------------------------------------- !> @brief Read mesh from marc input file !-------------------------------------------------------------------------------------------------- -subroutine inputRead(elem,node0_elem,connectivity_elem,microstructureAt) +subroutine inputRead(elem,node0_elem,connectivity_elem,materialAt) type(tElement), intent(out) :: elem real(pReal), dimension(:,:), allocatable, intent(out) :: & @@ -180,7 +180,7 @@ subroutine inputRead(elem,node0_elem,connectivity_elem,microstructureAt) integer, dimension(:,:), allocatable, intent(out) :: & connectivity_elem integer, dimension(:), allocatable, intent(out) :: & - microstructureAt + materialAt integer :: & fileFormatVersion, & @@ -226,9 +226,9 @@ subroutine inputRead(elem,node0_elem,connectivity_elem,microstructureAt) connectivity_elem = inputRead_connectivityElem(nElems,elem%nNodes,inputFile) - call inputRead_microstructure(microstructureAt, & - nElems,elem%nNodes,nameElemSet,mapElemSet,& - initialcondTableStyle,inputFile) + call inputRead_material(materialAt, & + nElems,elem%nNodes,nameElemSet,mapElemSet,& + initialcondTableStyle,inputFile) end subroutine inputRead @@ -675,13 +675,13 @@ end function inputRead_connectivityElem !-------------------------------------------------------------------------------------------------- -!> @brief Store microstructure ID +!> @brief Store material ID !-------------------------------------------------------------------------------------------------- -subroutine inputRead_microstructure(microstructureAt,& - nElem,nNodes,nameElemSet,mapElemSet,initialcondTableStyle,fileContent) +subroutine inputRead_material(materialAt,& + nElem,nNodes,nameElemSet,mapElemSet,initialcondTableStyle,fileContent) integer, dimension(:), allocatable, intent(out) :: & - microstructureAt + materialAt integer, intent(in) :: & nElem, & nNodes, & !< number of nodes per element @@ -696,7 +696,7 @@ subroutine inputRead_microstructure(microstructureAt,& integer :: i,j,t,sv,myVal,e,nNodesAlreadyRead,l,k,m - allocate(microstructureAt(nElem),source=0) + allocate(materialAt(nElem),source=0) do l = 1, size(fileContent) chunkPos = IO_stringPos(fileContent(l)) @@ -715,7 +715,7 @@ subroutine inputRead_microstructure(microstructureAt,& contInts = continuousIntValues(fileContent(l+k+m+1:),nElem,nameElemSet,mapElemSet,size(nameElemSet)) ! get affected elements do i = 1,contInts(1) e = mesh_FEM2DAMASK_elem(contInts(1+i)) - microstructureAt(e) = myVal + materialAt(e) = myVal enddo if (initialcondTableStyle == 0) m = m + 1 enddo @@ -723,9 +723,9 @@ subroutine inputRead_microstructure(microstructureAt,& endif enddo - if(any(microstructureAt < 1)) call IO_error(180) + if(any(materialAt < 1)) call IO_error(180) -end subroutine inputRead_microstructure +end subroutine inputRead_material !-------------------------------------------------------------------------------------------------- From 8c8db5b99f0364c860c458b2c4df65ca74ee3a37 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Wed, 23 Sep 2020 17:27:15 -0400 Subject: [PATCH 58/61] switched "Geom.materials" to "Geom.material" --- processing/pre/geom_grainGrowth.py | 40 ++-- processing/pre/mentat_spectralBox.py | 12 +- processing/pre/seeds_fromDistribution.py | 14 +- processing/pre/seeds_fromGeom.py | 8 +- processing/pre/seeds_fromPokes.py | 2 +- python/damask/_geom.py | 234 ++++++++++++----------- python/tests/test_Geom.py | 52 ++--- 7 files changed, 182 insertions(+), 180 deletions(-) diff --git a/processing/pre/geom_grainGrowth.py b/processing/pre/geom_grainGrowth.py index a573a9fed..b5793f703 100755 --- a/processing/pre/geom_grainGrowth.py +++ b/processing/pre/geom_grainGrowth.py @@ -66,13 +66,13 @@ for name in filenames: grid_original = geom.grid damask.util.croak(geom) - materials = np.tile(geom.materials,np.where(grid_original == 1, 2,1)) # make one copy along dimensions with grid == 1 - grid = np.array(materials.shape) + material = np.tile(geom.material,np.where(grid_original == 1, 2,1)) # make one copy along dimensions with grid == 1 + grid = np.array(material.shape) # --- initialize support data --------------------------------------------------------------------- # store a copy of the initial material indices to find locations of immutable indices - materials_original = np.copy(materials) + material_original = np.copy(material) if not options.ndimage: X,Y,Z = np.mgrid[0:grid[0],0:grid[1],0:grid[2]] @@ -88,14 +88,14 @@ for name in filenames: for smoothIter in range(options.N): - interfaceEnergy = np.zeros(materials.shape,dtype=np.float32) + interfaceEnergy = np.zeros(material.shape,dtype=np.float32) for i in (-1,0,1): for j in (-1,0,1): for k in (-1,0,1): # assign interfacial energy to all voxels that have a differing neighbor (in Moore neighborhood) interfaceEnergy = np.maximum(interfaceEnergy, - getInterfaceEnergy(materials,np.roll(np.roll(np.roll( - materials,i,axis=0), j,axis=1), k,axis=2))) + getInterfaceEnergy(material,np.roll(np.roll(np.roll( + material,i,axis=0), j,axis=1), k,axis=2))) # periodically extend interfacial energy array by half a grid size in positive and negative directions periodic_interfaceEnergy = np.tile(interfaceEnergy,(3,3,3))[grid[0]//2:-grid[0]//2, @@ -143,33 +143,33 @@ for name in filenames: return_distances = False, return_indices = True) # want index of closest bulk grain - periodic_materials = np.tile(materials,(3,3,3))[grid[0]//2:-grid[0]//2, - grid[1]//2:-grid[1]//2, - grid[2]//2:-grid[2]//2] # periodically extend the geometry + periodic_material = np.tile(material,(3,3,3))[grid[0]//2:-grid[0]//2, + grid[1]//2:-grid[1]//2, + grid[2]//2:-grid[2]//2] # periodically extend the geometry - materials = periodic_materials[index[0], - index[1], - index[2]].reshape(2*grid)[grid[0]//2:-grid[0]//2, - grid[1]//2:-grid[1]//2, - grid[2]//2:-grid[2]//2] # extent grains into interface region + material = periodic_material[index[0], + index[1], + index[2]].reshape(2*grid)[grid[0]//2:-grid[0]//2, + grid[1]//2:-grid[1]//2, + grid[2]//2:-grid[2]//2] # extent grains into interface region # replace immutable materials with closest mutable ones - index = ndimage.morphology.distance_transform_edt(np.in1d(materials,options.immutable).reshape(grid), + index = ndimage.morphology.distance_transform_edt(np.in1d(material,options.immutable).reshape(grid), return_distances = False, return_indices = True) - materials = materials[index[0], + material = material[index[0], index[1], index[2]] - immutable = np.zeros(materials.shape, dtype=np.bool) + immutable = np.zeros(material.shape, dtype=np.bool) # find locations where immutable materials have been in original structure for micro in options.immutable: - immutable += materials_original == micro + immutable += material_original == micro # undo any changes involving immutable materials - materials = np.where(immutable, materials_original,materials) + material = np.where(immutable, material_original,material) - damask.Geom(materials = materials[0:grid_original[0],0:grid_original[1],0:grid_original[2]], + damask.Geom(material = material[0:grid_original[0],0:grid_original[1],0:grid_original[2]], size = geom.size, origin = geom.origin, comments = geom.comments + [scriptID + ' ' + ' '.join(sys.argv[1:])], diff --git a/processing/pre/mentat_spectralBox.py b/processing/pre/mentat_spectralBox.py index 98703219f..7d78cb973 100755 --- a/processing/pre/mentat_spectralBox.py +++ b/processing/pre/mentat_spectralBox.py @@ -100,7 +100,7 @@ def mesh(r,d): #------------------------------------------------------------------------------------------------- -def material(): +def materials(): return [\ "*new_mater standard", "*mater_option general:state:solid", @@ -130,10 +130,10 @@ def geometry(): #------------------------------------------------------------------------------------------------- -def initial_conditions(materials): +def initial_conditions(material): elements = [] element = 0 - for id in materials: + for id in material: element += 1 if len(elements) < id: for i in range(id-len(elements)): @@ -197,14 +197,14 @@ for name in filenames: damask.util.report(scriptName,name) geom = damask.Geom.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) - materials = geom.materials.flatten(order='F') + material = geom.material.flatten(order='F') cmds = [\ init(), mesh(geom.grid,geom.size), - material(), + materials(), geometry(), - initial_conditions(materials), + initial_conditions(material), '*identify_sets', '*show_model', '*redraw', diff --git a/processing/pre/seeds_fromDistribution.py b/processing/pre/seeds_fromDistribution.py index 030f3d6fa..48f803d29 100755 --- a/processing/pre/seeds_fromDistribution.py +++ b/processing/pre/seeds_fromDistribution.py @@ -101,8 +101,8 @@ class myThread (threading.Thread): #--- evaluate current seeds file ------------------------------------------------------------------ perturbedGeom = damask.Geom.load_ASCII(perturbedGeomVFile) - myNmaterials = len(np.unique(perturbedGeom.materials)) - currentData=np.bincount(perturbedGeom.materials.ravel())[1:]/points + myNmaterials = len(np.unique(perturbedGeom.material)) + currentData = np.bincount(perturbedGeom.material.ravel())[1:]/points currentError=[] currentHist=[] for i in range(nMaterials): # calculate the deviation in all bins per histogram @@ -217,8 +217,8 @@ points = np.array(options.grid).prod().astype('float') # ----------- calculate target distribution and bin edges targetGeom = damask.Geom.load_ASCII(os.path.splitext(os.path.basename(options.target))[0]+'.geom') -nMaterials = len(np.unique(targetGeom.materials)) -targetVolFrac = np.bincount(targetGeom.materials.flatten())/targetGeom.grid.prod().astype(np.float) +nMaterials = len(np.unique(targetGeom.material)) +targetVolFrac = np.bincount(targetGeom.material.flatten())/targetGeom.grid.prod().astype(np.float) target = [] for i in range(1,nMaterials+1): targetHist,targetBins = np.histogram(targetVolFrac,bins=i) #bin boundaries @@ -244,10 +244,10 @@ initialGeomVFile.write(damask.util.execute('geom_fromVoronoiTessellation '+ initialGeomVFile.seek(0) initialGeom = damask.Geom.load_ASCII(initialGeomVFile) -if len(np.unique(targetGeom.materials)) != nMaterials: +if len(np.unique(targetGeom.material)) != nMaterials: damask.util.croak('error. Material count mismatch') -initialData = np.bincount(initialGeom.materials.flatten())/points +initialData = np.bincount(initialGeom.material.flatten())/points for i in range(nMaterials): initialHist = np.histogram(initialData,bins=target[i]['bins'])[0] target[i]['error']=np.sqrt(np.square(np.array(target[i]['histogram']-initialHist)).sum()) @@ -263,7 +263,7 @@ for i in range(nMaterials): if options.maxseeds < 1: - maxSeeds = len(np.unique(initialGeom.materials)) + maxSeeds = len(np.unique(initialGeom.material)) else: maxSeeds = options.maxseeds diff --git a/processing/pre/seeds_fromGeom.py b/processing/pre/seeds_fromGeom.py index de95b439d..b8d74b651 100755 --- a/processing/pre/seeds_fromGeom.py +++ b/processing/pre/seeds_fromGeom.py @@ -47,11 +47,11 @@ for name in filenames: damask.util.report(scriptName,name) geom = damask.Geom.load_ASCII(StringIO(''.join(sys.stdin.read())) if name is None else name) - materials = geom.materials.reshape((-1,1),order='F') + material = geom.material.reshape((-1,1),order='F') - mask = np.logical_and(np.in1d(materials,options.whitelist,invert=False) if options.whitelist else \ + mask = np.logical_and(np.in1d(material,options.whitelist,invert=False) if options.whitelist else \ np.full(geom.grid.prod(),True,dtype=bool), - np.in1d(materials,options.blacklist,invert=True) if options.blacklist else \ + np.in1d(material,options.blacklist,invert=True) if options.blacklist else \ np.full(geom.grid.prod(),True,dtype=bool)) seeds = damask.grid_filters.cell_coord0(geom.grid,geom.size).reshape(-1,3,order='F') @@ -64,5 +64,5 @@ for name in filenames: ] damask.Table(seeds[mask],{'pos':(3,)},comments)\ - .add('material',materials[mask].astype(int))\ + .add('material',material[mask].astype(int))\ .save(sys.stdout if name is None else os.path.splitext(name)[0]+'.seeds',legacy=True) diff --git a/processing/pre/seeds_fromPokes.py b/processing/pre/seeds_fromPokes.py index ff9d250fc..887d76392 100755 --- a/processing/pre/seeds_fromPokes.py +++ b/processing/pre/seeds_fromPokes.py @@ -76,7 +76,7 @@ for name in filenames: g[2] = k + offset[2] g %= geom.grid seeds[n,0:3] = (g+0.5)/geom.grid # normalize coordinates to box - seeds[n, 3] = geom.materials[g[0],g[1],g[2]] + seeds[n, 3] = geom.material[g[0],g[1],g[2]] if options.x: g[0] += 1 if options.y: g[1] += 1 n += 1 diff --git a/python/damask/_geom.py b/python/damask/_geom.py index 86d11b9be..6af265021 100644 --- a/python/damask/_geom.py +++ b/python/damask/_geom.py @@ -15,13 +15,13 @@ from . import grid_filters class Geom: """Geometry definition for grid solvers.""" - def __init__(self,materials,size,origin=[0.0,0.0,0.0],comments=[]): + def __init__(self,material,size,origin=[0.0,0.0,0.0],comments=[]): """ - New geometry definition from array of materials, size, and origin. + New geometry definition from array of material, size, and origin. Parameters ---------- - materials : numpy.ndarray + material : numpy.ndarray Material index array (3D). size : list or numpy.ndarray Physical size of the geometry in meter. @@ -31,16 +31,16 @@ class Geom: Comment lines. """ - if len(materials.shape) != 3: - raise ValueError(f'Invalid materials shape {materials.shape}.') - elif materials.dtype not in np.sctypes['float'] + np.sctypes['int']: - raise TypeError(f'Invalid materials data type {materials.dtype}.') + if len(material.shape) != 3: + raise ValueError(f'Invalid material shape {material.shape}.') + elif material.dtype not in np.sctypes['float'] + np.sctypes['int']: + raise TypeError(f'Invalid material data type {material.dtype}.') else: - self.materials = np.copy(materials) + self.material = np.copy(material) - if self.materials.dtype in np.sctypes['float'] and \ - np.all(self.materials == self.materials.astype(int).astype(float)): - self.materials = self.materials.astype(int) + if self.material.dtype in np.sctypes['float'] and \ + np.all(self.material == self.material.astype(int).astype(float)): + self.material = self.material.astype(int) if len(size) != 3 or any(np.array(size) <= 0): raise ValueError(f'Invalid size {size}.') @@ -62,7 +62,7 @@ class Geom: f'size x y z: {util.srepr(self.size, " x ")}', f'origin x y z: {util.srepr(self.origin," ")}', f'# materials: {self.N_materials}', - f'max material: {np.nanmax(self.materials)}', + f'max material: {np.nanmax(self.material)}', ]) @@ -103,21 +103,21 @@ class Geom: message.append(util.delete(f'# materials: {other.N_materials}')) message.append(util.emph( f'# materials: { self.N_materials}')) - if np.nanmax(other.materials) != np.nanmax(self.materials): - message.append(util.delete(f'max material: {np.nanmax(other.materials)}')) - message.append(util.emph( f'max material: {np.nanmax( self.materials)}')) + if np.nanmax(other.material) != np.nanmax(self.material): + message.append(util.delete(f'max material: {np.nanmax(other.material)}')) + message.append(util.emph( f'max material: {np.nanmax( self.material)}')) return util.return_message(message) @property def grid(self): - return np.asarray(self.materials.shape) + return np.asarray(self.material.shape) @property def N_materials(self): - return np.unique(self.materials).size + return np.unique(self.material).size @staticmethod @@ -160,7 +160,7 @@ class Geom: else: comments.append(line.strip()) - materials = np.empty(grid.prod()) # initialize as flat array + material = np.empty(grid.prod()) # initialize as flat array i = 0 for line in content[header_length:]: items = line.split('#')[0].split() @@ -172,16 +172,16 @@ class Geom: abs(int(items[2])-int(items[0]))+1,dtype=float) else: items = list(map(float,items)) else: items = list(map(float,items)) - materials[i:i+len(items)] = items + material[i:i+len(items)] = items i += len(items) if i != grid.prod(): raise TypeError(f'Invalid file: expected {grid.prod()} entries, found {i}') - if not np.any(np.mod(materials,1) != 0.0): # no float present - materials = materials.astype('int') + if not np.any(np.mod(material,1) != 0.0): # no float present + material = material.astype('int') - return Geom(materials.reshape(grid,order='F'),size,origin,comments) + return Geom(material.reshape(grid,order='F'),size,origin,comments) @staticmethod @@ -200,9 +200,11 @@ class Geom: comments = v.get_comments() grid = np.array(v.vtk_data.GetDimensions())-1 bbox = np.array(v.vtk_data.GetBounds()).reshape(3,2).T - size = bbox[1] - bbox[0] - return Geom(v.get('material').reshape(grid,order='F'),size,bbox[0],comments=comments) + return Geom(material = v.get('material').reshape(grid,order='F'), + size = bbox[1] - bbox[0], + origin = bbox[0], + comments=comments) @staticmethod @@ -243,17 +245,17 @@ class Geom: result = pool.map_async(partial(Geom._find_closest_seed,seeds_p,weights_p), [coord for coord in coords]) pool.close() pool.join() - materials = np.array(result.get()) + material = np.array(result.get()) if periodic: - materials = materials.reshape(grid*3) - materials = materials[grid[0]:grid[0]*2,grid[1]:grid[1]*2,grid[2]:grid[2]*2]%seeds.shape[0] + material = material.reshape(grid*3) + material = material[grid[0]:grid[0]*2,grid[1]:grid[1]*2,grid[2]:grid[2]*2]%seeds.shape[0] else: - materials = materials.reshape(grid) + material = material.reshape(grid) - return Geom(materials = materials+1, - size = size, - comments = util.execution_stamp('Geom','from_Laguerre_tessellation'), + return Geom(material = material+1, + size = size, + comments = util.execution_stamp('Geom','from_Laguerre_tessellation'), ) @@ -276,11 +278,11 @@ class Geom: """ coords = grid_filters.cell_coord0(grid,size).reshape(-1,3) KDTree = spatial.cKDTree(seeds,boxsize=size) if periodic else spatial.cKDTree(seeds) - devNull,materials = KDTree.query(coords) + devNull,material = KDTree.query(coords) - return Geom(materials = materials.reshape(grid)+1, - size = size, - comments = util.execution_stamp('Geom','from_Voronoi_tessellation'), + return Geom(material = material.reshape(grid)+1, + size = size, + comments = util.execution_stamp('Geom','from_Voronoi_tessellation'), ) @@ -311,10 +313,10 @@ class Geom: plain = not compress if plain: - format_string = '%g' if self.materials.dtype in np.sctypes['float'] else \ - '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(self.materials))))) + format_string = '%g' if self.material.dtype in np.sctypes['float'] else \ + '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(self.material))))) np.savetxt(fname, - self.materials.reshape([grid[0],np.prod(grid[1:])],order='F').T, + self.material.reshape([grid[0],np.prod(grid[1:])],order='F').T, header='\n'.join(header), fmt=format_string, comments='') else: try: @@ -325,7 +327,7 @@ class Geom: compressType = None former = start = -1 reps = 0 - for current in self.materials.flatten('F'): + for current in self.material.flatten('F'): if abs(current - former) == 1 and (start - current) == reps*(former - current): compressType = 'to' reps += 1 @@ -370,7 +372,7 @@ class Geom: """ v = VTK.from_rectilinearGrid(self.grid,self.size,self.origin) - v.add(self.materials.flatten(order='F'),'material') + v.add(self.material.flatten(order='F'),'material') v.add_comments(self.comments) v.save(fname if str(fname).endswith('.vtr') else str(fname)+'.vtr',parallel=False,compress=compress) @@ -402,7 +404,7 @@ class Geom: 0 gives octahedron (|x|^(2^0) + |y|^(2^0) + |z|^(2^0) < 1) 1 gives a sphere (|x|^(2^1) + |y|^(2^1) + |z|^(2^1) < 1) fill : int, optional - Fill value for primitive. Defaults to materials.max() + 1. + Fill value for primitive. Defaults to material.max() + 1. R : damask.Rotation, optional Rotation of primitive. Defaults to no rotation. inverse : Boolean, optional @@ -428,12 +430,12 @@ class Geom: if periodic: # translate back to center mask = np.roll(mask,((c-np.ones(3)*.5)*self.grid).astype(int),(0,1,2)) - fill_ = np.full_like(self.materials,np.nanmax(self.materials)+1 if fill is None else fill) + fill_ = np.full_like(self.material,np.nanmax(self.material)+1 if fill is None else fill) - return Geom(materials = np.where(np.logical_not(mask) if inverse else mask, self.materials,fill_), - size = self.size, - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','add_primitive')], + return Geom(material = np.where(np.logical_not(mask) if inverse else mask, self.material,fill_), + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','add_primitive')], ) @@ -455,19 +457,19 @@ class Geom: raise ValueError(f'Invalid direction {set(directions).difference(valid)} specified.') limits = [None,None] if reflect else [-2,0] - ms = self.materials.copy() + mat = self.material.copy() if 'x' in directions: - ms = np.concatenate([ms,ms[limits[0]:limits[1]:-1,:,:]],0) + mat = np.concatenate([mat,mat[limits[0]:limits[1]:-1,:,:]],0) if 'y' in directions: - ms = np.concatenate([ms,ms[:,limits[0]:limits[1]:-1,:]],1) + mat = np.concatenate([mat,mat[:,limits[0]:limits[1]:-1,:]],1) if 'z' in directions: - ms = np.concatenate([ms,ms[:,:,limits[0]:limits[1]:-1]],2) + mat = np.concatenate([mat,mat[:,:,limits[0]:limits[1]:-1]],2) - return Geom(materials = ms, - size = self.size/self.grid*np.asarray(ms.shape), - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','mirror')], + return Geom(material = mat, + size = self.size/self.grid*np.asarray(mat.shape), + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','mirror')], ) @@ -486,12 +488,12 @@ class Geom: if not set(directions).issubset(valid): raise ValueError(f'Invalid direction {set(directions).difference(valid)} specified.') - ms = np.flip(self.materials, (valid.index(d) for d in directions if d in valid)) + mat = np.flip(self.material, (valid.index(d) for d in directions if d in valid)) - return Geom(materials = ms, - size = self.size, - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','flip')], + return Geom(material = mat, + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','flip')], ) @@ -507,17 +509,17 @@ class Geom: Assume geometry to be periodic. Defaults to True. """ - return Geom(materials = ndimage.interpolation.zoom( - self.materials, + return Geom(material = ndimage.interpolation.zoom( + self.material, grid/self.grid, - output=self.materials.dtype, + output=self.material.dtype, order=0, mode=('wrap' if periodic else 'nearest'), prefilter=False ), - size = self.size, - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','scale')], + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','scale')], ) @@ -543,29 +545,29 @@ class Geom: else: return me - return Geom(materials = ndimage.filters.generic_filter( - self.materials, + return Geom(material = ndimage.filters.generic_filter( + self.material, mostFrequent, size=(stencil if selection is None else stencil//2*2+1,)*3, mode=('wrap' if periodic else 'nearest'), extra_keywords=dict(selection=selection), - ).astype(self.materials.dtype), - size = self.size, - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','clean')], + ).astype(self.material.dtype), + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','clean')], ) def renumber(self): """Renumber sorted material indices to 1,...,N.""" - renumbered = np.empty(self.grid,dtype=self.materials.dtype) - for i, oldID in enumerate(np.unique(self.materials)): - renumbered = np.where(self.materials == oldID, i+1, renumbered) + renumbered = np.empty(self.grid,dtype=self.material.dtype) + for i, oldID in enumerate(np.unique(self.material)): + renumbered = np.where(self.material == oldID, i+1, renumbered) - return Geom(materials = renumbered, - size = self.size, - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','renumber')], + return Geom(material = renumbered, + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','renumber')], ) @@ -578,32 +580,32 @@ class Geom: R : damask.Rotation Rotation to apply to the geometry. fill : int or float, optional - Material index to fill the corners. Defaults to materials.max() + 1. + Material index to fill the corners. Defaults to material.max() + 1. """ - if fill is None: fill = np.nanmax(self.materials) + 1 - dtype = float if np.isnan(fill) or int(fill) != fill or self.materials.dtype==np.float else int + if fill is None: fill = np.nanmax(self.material) + 1 + dtype = float if np.isnan(fill) or int(fill) != fill or self.material.dtype==np.float else int Eulers = R.as_Eulers(degrees=True) - materials_in = self.materials.copy() + material_in = self.material.copy() # These rotations are always applied in the reference coordinate system, i.e. (z,x,z) not (z,x',z'') # see https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf for angle,axes in zip(Eulers[::-1], [(0,1),(1,2),(0,1)]): - materials_out = ndimage.rotate(materials_in,angle,axes,order=0, + material_out = ndimage.rotate(material_in,angle,axes,order=0, prefilter=False,output=dtype,cval=fill) - if np.prod(materials_in.shape) == np.prod(materials_out.shape): + if np.prod(material_in.shape) == np.prod(material_out.shape): # avoid scipy interpolation errors for rotations close to multiples of 90° - materials_in = np.rot90(materials_in,k=np.rint(angle/90.).astype(int),axes=axes) + material_in = np.rot90(material_in,k=np.rint(angle/90.).astype(int),axes=axes) else: - materials_in = materials_out + material_in = material_out - origin = self.origin-(np.asarray(materials_in.shape)-self.grid)*.5 * self.size/self.grid + origin = self.origin-(np.asarray(material_in.shape)-self.grid)*.5 * self.size/self.grid - return Geom(materials = materials_in, - size = self.size/self.grid*np.asarray(materials_in.shape), - origin = origin, - comments = self.comments+[util.execution_stamp('Geom','rotate')], + return Geom(material = material_in, + size = self.size/self.grid*np.asarray(material_in.shape), + origin = origin, + comments = self.comments+[util.execution_stamp('Geom','rotate')], ) @@ -618,12 +620,12 @@ class Geom: offset : numpy.ndarray of shape (3) Offset (measured in grid points) from old to new geometry [0,0,0]. fill : int or float, optional - Material index to fill the background. Defaults to materials.max() + 1. + Material index to fill the background. Defaults to material.max() + 1. """ if offset is None: offset = 0 - if fill is None: fill = np.nanmax(self.materials) + 1 - dtype = float if int(fill) != fill or self.materials.dtype in np.sctypes['float'] else int + if fill is None: fill = np.nanmax(self.material) + 1 + dtype = float if int(fill) != fill or self.material.dtype in np.sctypes['float'] else int canvas = np.full(self.grid if grid is None else grid,fill,dtype) @@ -632,35 +634,35 @@ class Geom: ll = np.clip(-offset, 0,np.minimum( grid,self.grid-offset)) ur = np.clip(-offset+self.grid,0,np.minimum( grid,self.grid-offset)) - canvas[ll[0]:ur[0],ll[1]:ur[1],ll[2]:ur[2]] = self.materials[LL[0]:UR[0],LL[1]:UR[1],LL[2]:UR[2]] + canvas[ll[0]:ur[0],ll[1]:ur[1],ll[2]:ur[2]] = self.material[LL[0]:UR[0],LL[1]:UR[1],LL[2]:UR[2]] - return Geom(materials = canvas, - size = self.size/self.grid*np.asarray(canvas.shape), - origin = self.origin+offset*self.size/self.grid, - comments = self.comments+[util.execution_stamp('Geom','canvas')], + return Geom(material = canvas, + size = self.size/self.grid*np.asarray(canvas.shape), + origin = self.origin+offset*self.size/self.grid, + comments = self.comments+[util.execution_stamp('Geom','canvas')], ) - def substitute(self,from_materials,to_materials): + def substitute(self,from_material,to_material): """ Substitute material indices. Parameters ---------- - from_materials : iterable of ints + from_material : iterable of ints Material indices to be substituted. - to_materials : iterable of ints + to_material : iterable of ints New material indices. """ - substituted = self.materials.copy() - for from_ms,to_ms in zip(from_materials,to_materials): - substituted[self.materials==from_ms] = to_ms + substituted = self.material.copy() + for from_ms,to_ms in zip(from_material,to_material): + substituted[self.material==from_ms] = to_ms - return Geom(materials = substituted, - size = self.size, - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','substitute')], + return Geom(material = substituted, + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','substitute')], ) @@ -679,7 +681,7 @@ class Geom: Defaults to 1. offset : int, optional Offset (positive or negative) to tag material indices, - defaults to materials.max() + 1. + defaults to material.max() + 1. trigger : list of ints, optional List of material indices that trigger a change. Defaults to [], meaning that any different neighbor triggers a change. @@ -698,15 +700,15 @@ class Geom: trigger = list(trigger) return np.any(np.in1d(stencil,np.array(trigger))) - offset_ = np.nanmax(self.materials) if offset is None else offset - mask = ndimage.filters.generic_filter(self.materials, + offset_ = np.nanmax(self.material) if offset is None else offset + mask = ndimage.filters.generic_filter(self.material, tainted_neighborhood, size=1+2*vicinity, mode='wrap' if periodic else 'nearest', extra_keywords={'trigger':trigger}) - return Geom(materials = np.where(mask, self.materials + offset_,self.materials), - size = self.size, - origin = self.origin, - comments = self.comments+[util.execution_stamp('Geom','vicinity_offset')], + return Geom(material = np.where(mask, self.material + offset_,self.material), + size = self.size, + origin = self.origin, + comments = self.comments+[util.execution_stamp('Geom','vicinity_offset')], ) diff --git a/python/tests/test_Geom.py b/python/tests/test_Geom.py index 961d28713..ac4a8eac3 100644 --- a/python/tests/test_Geom.py +++ b/python/tests/test_Geom.py @@ -11,8 +11,8 @@ from damask import util def geom_equal(a,b): - return np.all(a.materials == b.materials) and \ - np.all(a.grid == b.grid) and \ + return np.all(a.material == b.material) and \ + np.all(a.grid == b.grid) and \ np.allclose(a.size, b.size) and \ str(a.diff(b)) == str(b.diff(a)) @@ -38,7 +38,7 @@ class TestGeom: def test_diff_not_equal(self,default): - new = Geom(default.materials[1:,1:,1:]+1,default.size*.9,np.ones(3)-default.origin,comments=['modified']) + new = Geom(default.material[1:,1:,1:]+1,default.size*.9,np.ones(3)-default.origin,comments=['modified']) assert str(default.diff(new)) != '' @@ -93,28 +93,28 @@ class TestGeom: def test_invalid_size(self,default): with pytest.raises(ValueError): - Geom(default.materials[1:,1:,1:], + Geom(default.material[1:,1:,1:], size=np.ones(2)) def test_invalid_origin(self,default): with pytest.raises(ValueError): - Geom(default.materials[1:,1:,1:], + Geom(default.material[1:,1:,1:], size=np.ones(3), origin=np.ones(4)) def test_invalid_materials_shape(self,default): - materials = np.ones((3,3)) + material = np.ones((3,3)) with pytest.raises(ValueError): - Geom(materials, + Geom(material, size=np.ones(3)) def test_invalid_materials_type(self,default): - materials = np.random.randint(1,300,(3,4,5))==1 + material = np.random.randint(1,300,(3,4,5))==1 with pytest.raises(TypeError): - Geom(materials) + Geom(material) @pytest.mark.parametrize('directions,reflect',[ @@ -205,10 +205,10 @@ class TestGeom: def test_renumber(self,default): - materials = default.materials.copy() - for m in np.unique(materials): - materials[materials==m] = materials.max() + np.random.randint(1,30) - modified = Geom(materials, + material = default.material.copy() + for m in np.unique(material): + material[material==m] = material.max() + np.random.randint(1,30) + modified = Geom(material, default.size, default.origin) assert not geom_equal(modified,default) @@ -218,13 +218,13 @@ class TestGeom: def test_substitute(self,default): offset = np.random.randint(1,500) - modified = Geom(default.materials + offset, + modified = Geom(default.material + offset, default.size, default.origin) assert not geom_equal(modified,default) assert geom_equal(default, - modified.substitute(np.arange(default.materials.max())+1+offset, - np.arange(default.materials.max())+1)) + modified.substitute(np.arange(default.material.max())+1+offset, + np.arange(default.material.max())+1)) @pytest.mark.parametrize('axis_angle',[np.array([1,0,0,86.7]), np.array([0,1,0,90.4]), np.array([0,0,1,90]), @@ -251,7 +251,7 @@ class TestGeom: grid = default.grid grid_add = np.random.randint(0,30,(3)) modified = default.canvas(grid + grid_add) - assert np.all(modified.materials[:grid[0],:grid[1],:grid[2]] == default.materials) + assert np.all(modified.material[:grid[0],:grid[1],:grid[2]] == default.material) @pytest.mark.parametrize('center1,center2',[(np.random.random(3)*.5,np.random.random()*8), @@ -271,7 +271,7 @@ class TestGeom: s = np.random.random(3)+.5 G_1 = Geom(np.ones(g,'i'),s,o).add_primitive(diameter,center1,exponent) G_2 = Geom(np.ones(g,'i'),s,o).add_primitive(diameter,center2,exponent) - assert np.count_nonzero(G_1.materials!=2) == np.count_nonzero(G_2.materials!=2) + assert np.count_nonzero(G_1.material!=2) == np.count_nonzero(G_2.material!=2) @pytest.mark.parametrize('center',[np.random.randint(4,10,(3)), @@ -308,14 +308,14 @@ class TestGeom: geom = Geom(m,np.random.rand(3)).vicinity_offset(vicinity,offset,trigger=trigger) - assert np.all(m2==geom.materials) + assert np.all(m2==geom.material) @pytest.mark.parametrize('periodic',[True,False]) def test_vicinity_offset_invariant(self,default,periodic): - offset = default.vicinity_offset(trigger=[default.materials.max()+1, - default.materials.min()-1]) - assert np.all(offset.materials==default.materials) + offset = default.vicinity_offset(trigger=[default.material.max()+1, + default.material.min()-1]) + assert np.all(offset.material==default.material) @pytest.mark.parametrize('periodic',[True,False]) @@ -338,7 +338,7 @@ class TestGeom: ms = np.random.randint(1, N_seeds+1) weights[ms-1] = np.random.random() Laguerre = Geom.from_Laguerre_tessellation(grid,size,seeds,weights,np.random.random()>0.5) - assert np.all(Laguerre.materials == ms) + assert np.all(Laguerre.material == ms) @pytest.mark.parametrize('approach',['Laguerre','Voronoi']) @@ -346,10 +346,10 @@ class TestGeom: grid = np.random.randint(5,10,3)*2 size = grid.astype(np.float) seeds = np.vstack((size*np.array([0.5,0.25,0.5]),size*np.array([0.5,0.75,0.5]))) - materials = np.ones(grid) - materials[:,grid[1]//2:,:] = 2 + material = np.ones(grid) + material[:,grid[1]//2:,:] = 2 if approach == 'Laguerre': geom = Geom.from_Laguerre_tessellation(grid,size,seeds,np.ones(2),np.random.random()>0.5) elif approach == 'Voronoi': geom = Geom.from_Voronoi_tessellation(grid,size,seeds, np.random.random()>0.5) - assert np.all(geom.materials == materials) + assert np.all(geom.material == material) From fd70a038455a8ca12d7fa9c0396f27411c134caf Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Thu, 24 Sep 2020 06:59:48 +0200 Subject: [PATCH 59/61] test with consistent name 'material' --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index b48fdd1f1..45fc8ce40 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit b48fdd1f167ed22ae9deabe44ae31c73ff5a6c1d +Subproject commit 45fc8ce405de938e3ee17958a504cfa1820a7ed7 From e6ae5c9b6d9263e3fe440e227b1fe81d9ee9fe81 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Thu, 24 Sep 2020 08:14:14 +0200 Subject: [PATCH 60/61] failed test due to missing rename --- PRIVATE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PRIVATE b/PRIVATE index 45fc8ce40..2550bf655 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit 45fc8ce405de938e3ee17958a504cfa1820a7ed7 +Subproject commit 2550bf655aebe61ce459718323ba38b1ac205a7f From 0f64954300684b96646ffbce2fc7287fbc8718f8 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Thu, 24 Sep 2020 09:36:19 +0200 Subject: [PATCH 61/61] whitespace adjustment --- src/grid/discretization_grid.f90 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/grid/discretization_grid.f90 b/src/grid/discretization_grid.f90 index 09b3774aa..b226c3d0e 100644 --- a/src/grid/discretization_grid.f90 +++ b/src/grid/discretization_grid.f90 @@ -415,8 +415,8 @@ subroutine readVTR(grid,geomSize,origin,material) if(.not. allocated(material)) call IO_error(error_ID = 844, ext_msg='material data not found') if(size(material) /= product(grid)) call IO_error(error_ID = 844, ext_msg='size(material)') - if(any(geomSize<=0)) call IO_error(error_ID = 844, ext_msg='size') - if(any(grid<1)) call IO_error(error_ID = 844, ext_msg='grid') + if(any(geomSize<=0)) call IO_error(error_ID = 844, ext_msg='size') + if(any(grid<1)) call IO_error(error_ID = 844, ext_msg='grid') contains