File size: 13,271 Bytes
2200060
 
 
 
 
 
 
 
 
 
b68dcad
 
2200060
b68dcad
 
2200060
 
b68dcad
2200060
 
 
 
3591396
 
 
2200060
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ab1145
 
2200060
 
 
 
3ab1145
 
 
 
 
 
 
 
 
2200060
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca1362c
2200060
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca1362c
2200060
 
 
 
 
eafa610
 
 
 
 
 
 
ca1362c
eafa610
 
 
be8288e
2200060
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98e78c1
025f222
2200060
 
 
 
b68dcad
2200060
 
 
 
 
 
 
 
 
 
 
98e78c1
aa69b47
98e78c1
 
aa69b47
98e78c1
 
aa69b47
98e78c1
 
7759c3d
aa69b47
98e78c1
 
 
3a063df
98e78c1
 
 
 
3a063df
191f79c
98e78c1
 
e2db460
2200060
728bce4
 
 
18bef21
728bce4
18bef21
 
 
 
 
 
 
728bce4
e2db460
83c071f
e2db460
 
 
 
 
 
 
b68dcad
ef755bb
e2db460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5975ed
e2db460
 
 
 
 
 
 
 
e5e43e2
e2db460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5e43e2
83c071f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# For neural networks
import keras
# For random calculations
import numpy

# Disable eager execution because its bad
from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()

# Start a session for checking calculations and stuff
#  import tensorflow as tf
# sess = tf.compat.v1.Session()

# from keras import backend as K
# K.set_session(sess)

# Do you want it loud? 
# VERBOSE = 1

# This function loads a fuckton of data
def load_data():
    # Open all the files we downloaded at the beginning and take out hte good bits
    curves = numpy.load('data_curves.npz')['curves']
    geometry = numpy.load('data_geometry.npz')['geometry']
    constants = numpy.load('constants.npz')
    S = constants['S']
    N = constants['N']
    D = constants['D']
    F = constants['F']
    G = constants['G']

    # Some of the good bits need additional processining
    new_curves = numpy.zeros((S*N, D * F))
    for i, curveset in enumerate(curves):
        new_curves[i, :] = curveset.T.flatten() / 1000000

    new_geometry = numpy.zeros((S*N, G * G * G))
    for i, geometryset in enumerate(geometry):
        new_geometry[i, :] = geometryset.T.flatten()

    # Return good bits to user
    return curves, geometry, S, N, D, F, G, new_curves, new_geometry
    
import gradio
import pandas

curves, geometry, S, N, D, F, G, new_curves, new_geometry = load_data()

class Network(object):

  def __init__(self, structure, weights):
      # Instantiate variables
      self.curves = curves
      self.new_curves = new_curves
      self.geometry = geometry
      self.new_geometry = new_geometry
      self.S = S
      self.N = N
      self.D = D
      self.F = F
      self.G = G

      # Load network
      with open(structure, 'r') as file:
          self.network = keras.models.model_from_json(file.read())
          self.network.load_weights(weights)

  def analysis(self, idx=None):
      print(idx)

      if idx is None:
          idx = numpy.random.randint(1, self.S * self.N)
      else:
        idx = int(idx)

      # Get the input
      data_input = self.new_geometry[idx:(idx+1), :]
      other_data_input = data_input.reshape((self.G, self.G, self.G), order='F')

      # Get the outputs
      predicted_output = self.network.predict(data_input)
      true_output = self.new_curves[idx].reshape((3, self.F))
      predicted_output = predicted_output.reshape((3, self.F))

      f = numpy.linspace(0.05, 2.0, 64)
      fd = pandas.DataFrame(f).rename(columns={0: "Frequency"})
      df_pred = pandas.DataFrame(predicted_output.transpose()).rename(columns={0: "Surge", 1: "Heave", 2: "Pitch"})
      df_true = pandas.DataFrame(true_output.transpose()).rename(columns={0: "Surge", 1: "Heave", 2: "Pitch"})

      # return idx, other_data_input, true_output, predicted_output
      return pandas.concat([fd, df_pred], axis=1), pandas.concat([fd, df_true], axis=1)

  def synthesis(self, idx=None):
      print(idx)

      if idx is None:
          idx = numpy.random.randint(1, self.S * self.N)
      else:
        idx = int(idx)

      # Get the input
      data_input = self.new_curves[idx:(idx+1), :]
      other_data_input = data_input.reshape((3, self.F))

      # Get the outputs
      predicted_output = self.network.predict(data_input)
      true_output = self.new_geometry[idx].reshape((self.G, self.G, self.G), order='F')
      predicted_output = predicted_output.reshape((self.G, self.G, self.G), order='F')

      # return idx, other_data_input, true_output, predicted_output
      return predicted_output, true_output
      
  
  def synthesis_from_spectrum(self, other_data_input):
      # Get the input
      data_input = other_data_input.reshape((1, 3*self.F))
 
      # Get the outputs
      predicted_output = self.network.predict(data_input)
      predicted_output = predicted_output.reshape((self.G, self.G, self.G), order='F')

      # return idx, other_data_input, true_output, predicted_output
      return predicted_output

  def get_geometry(self, idx=None):

      if idx is None:
          idx = numpy.random.randint(1, self.S * self.N)
      else:
        idx = int(idx)

      idx = int(idx)

      # Get the input
      data_input = self.new_geometry[idx:(idx+1), :]
      other_data_input = data_input.reshape((self.G, self.G, self.G), order='F')

      # return idx, other_data_input, true_output, predicted_output
      return other_data_input


  def get_performance(self, idx=None):

      if idx is None:
          idx = numpy.random.randint(1, self.S * self.N)
      else:
        idx = int(idx)

      idx = int(idx)

      # Get the input
      data_input = self.new_curves[idx:(idx+1), :]
      other_data_input = data_input.reshape((3, self.F))

      f = numpy.linspace(0.05, 2.0, 64)
      fd = pandas.DataFrame(f).rename(columns={0: "Frequency"})
      df_pred = pandas.DataFrame(other_data_input.transpose()).rename(columns={0: "Surge", 1: "Heave", 2: "Pitch"})
      table = pandas.concat([fd, df_pred], axis=1)

      return table



import plotly.graph_objects as go


def plotly_fig(values):
    X, Y, Z = numpy.mgrid[0:1:32j, 0:1:32j, 0:1:32j]
    fig = go.Figure(data=go.Volume(
        x=X.flatten(),
        y=Y.flatten(),
        z=Z.flatten(),
        value=values.flatten(),
        isomin=-0.1,
        isomax=0.8,
        opacity=0.1, # needs to be small to see through all surfaces
        surface_count=21, # needs to be a large number for good volume rendering
        ))
    return fig 

value_net = Network("16forward_structure.json", "16forward_weights.h5")

def performance(index):
    return value_net.get_performance(index)

def geometry(index):
    values = value_net.get_geometry(index)
    return plotly_fig(values)

def simple_analysis(index): 
    forward_net = Network("16forward_structure.json", "16forward_weights.h5")  
    return forward_net.analysis(index)

def simple_synthesis(index):
    inverse_net = Network("16inverse_structure.json", "16inverse_weights.h5")
    pred, true = inverse_net.synthesis(index)
    return plotly_fig(pred), plotly_fig(true)
    
def synthesis_from_spectrum(df):
    inverse_net = Network("16inverse_structure.json", "16inverse_weights.h5")
    pred = inverse_net.synthesis_from_spectrum(df.to_numpy()[:, 1:])
    return plotly_fig(pred)
   

    

def change_textbox(choice):
    if choice == "cylinder":
        return [gradio.Slider.update(visible=True), gradio.Slider.update(visible=False), gradio.Slider.update(visible=True), gradio.Slider.update(visible=False)]
    elif choice == "sphere":
        return [gradio.Slider.update(visible=False), gradio.Slider.update(visible=False), gradio.Slider.update(visible=True), gradio.Slider.update(visible=False)]
    elif choice == "box":
        return [gradio.Slider.update(visible=True), gradio.Slider.update(visible=True), gradio.Slider.update(visible=False), gradio.Slider.update(visible=True)]
    elif choice == "wedge":
        return [gradio.Slider.update(visible=True), gradio.Slider.update(visible=True), gradio.Slider.update(visible=False), gradio.Slider.update(visible=True)]
    elif choice == "cone":
        return [gradio.Slider.update(visible=True), gradio.Slider.update(visible=False), gradio.Slider.update(visible=True), gradio.Slider.update(visible=False)]

   
with gradio.Blocks() as demo:
    with gradio.Accordion("✨ Read about the ML model here! ✨", open=False):
        with gradio.Row():
            with gradio.Column():
                gradio.Markdown("# Toward the Rapid Design of Engineered Systems Through Deep Neural Networks")
                gradio.HTML("Christopher McComb, Carnegie Mellon University")
                gradio.Markdown("Additive manufacturing is advantageous for producing lightweight components while maintaining function and form. This ability has been bolstered by the introduction of unit lattice cells and the gradation of those cells. In cases where loading varies throughout a part, it may be necessary to use multiple lattice cell types, also known as multi-lattice structures. In such structures, abrupt transitions between geometries may cause stress concentrations, making the boundary a primary failure point; thus, transition regions should be created between each lattice cell type. Although computational approaches have been proposed, smooth transition regions are still difficult to intuit and design, especially between lattices of drastically different geometries. This work demonstrates and assesses a method for using variational autoencoders to automate the creation of transitional lattice cells. In particular, the work focuses on identifying the relationships that exist within the latent space produced by the variational autoencoder. Through computational experimentation, it was found that the smoothness of transition regions was higher when the endpoints were located closer together in the latent space.")
            with gradio.Column():
                download = gradio.HTML("<a href=\"https://huggingface.co/spaces/cmudrc/wecnet/resolve/main/McComb2019_Chapter_TowardTheRapidDesignOfEngineer.pdf\" style=\"width: 60%; display: block; margin: auto;\"><img src=\"https://huggingface.co/spaces/cmudrc/wecnet/resolve/main/coverpage.png\"></a>")
    
    with gradio.Tab("Analysis"):
        with gradio.Tab("Spectrum from Dataset"):                    
            with gradio.Row():
                with gradio.Column():
                    num = gradio.Number(42, label="data index")
                    btn1 = gradio.Button("Select")    
                with gradio.Column():
                    geo = gradio.Plot(label="Geometry")
        
            with gradio.Row():
                btn2 = gradio.Button("Estimate Spectrum")
        
            with gradio.Row():
              with gradio.Column():
                  pred = gradio.Timeseries(x="Frequency", y=['Surge', 'Heave', 'Pitch'], label="Predicted")
        
              with gradio.Column():
                  true = gradio.Timeseries(x="Frequency", y=['Surge', 'Heave', 'Pitch'], label="True")
        
            btn1.click(fn=geometry, inputs=[num], outputs=[geo])
            btn2.click(fn=simple_analysis, inputs=[num], outputs=[pred, true])
            
        with gradio.Tab("Spectrum from DataFrame"):
            with gradio.Row():
                perf = gradio.Timeseries(x="Frequency", y=['Surge', 'Heave', 'Pitch'], label="Performance")
        
            with gradio.Row():
                btn2 = gradio.Button("Synthesize Geometry")
        
            with gradio.Row():
                pred = gradio.Plot(label="Predicted")
        
            btn2.click(fn=synthesis_from_spectrum, inputs=[perf], outputs=[pred])
    
    with gradio.Tab("Synthesis"):        
        with gradio.Tab("Geometry from Dataset"):                    
            with gradio.Row():
                with gradio.Column():
                    num = gradio.Number(42, label="data index")
                    btn1 = gradio.Button("Select")    
                with gradio.Column():
                    perf = gradio.Timeseries(x="Frequency", y=['Surge', 'Heave', 'Pitch'], label="Performance")
        
            with gradio.Row():
                btn2 = gradio.Button("Synthesize Geometry")
        
            with gradio.Row():
              with gradio.Column():
                  pred = gradio.Plot(label="Predicted")
        
              with gradio.Column():
                  true = gradio.Plot(label="True")
        
            btn1.click(fn=performance, inputs=[num], outputs=[perf])
            btn2.click(fn=simple_synthesis, inputs=[num], outputs=[pred, true])
        with gradio.Tab("Geometry from Parameters"):
            with gradio.Row():
                with gradio.Column():
                    radio = gradio.Radio(
                        ["box", "cone", "cylinder", "sphere", "wedge"], label="What kind of shape would you like to generate?", value="box"
                    )
                    height = gradio.Slider(label="Height", interactive=True, minimum=3.0, maximum=10.0, value=6.5)
                    width = gradio.Slider(label="Width", interactive=True, minimum=3.0, maximum=10.0, value=6.5)
                    diameter = gradio.Slider(label="Diameter", interactive=True, minimum=3.0, maximum=10.0, value=6.5, visible=False)
                    length = gradio.Slider(label="Length", interactive=True, minimum=3.0, maximum=10.0, value=6.5)
                
                    radio.change(fn=change_textbox, inputs=radio, outputs=[height, width, diameter, length])
                  
                with gradio.Column():
                    geo = gradio.Plot(label="Geometry")
        
            with gradio.Row():
                btn2 = gradio.Button("Estimate Spectrum")
        
            with gradio.Row():
              with gradio.Column():
                  pred = gradio.Timeseries(x="Frequency", y=['Surge', 'Heave', 'Pitch'], label="Predicted")
        
              with gradio.Column():
                  true = gradio.Timeseries(x="Frequency", y=['Surge', 'Heave', 'Pitch'], label="True")
        
            btn1.click(fn=geometry, inputs=[num], outputs=[geo])
            btn2.click(fn=simple_analysis, inputs=[num], outputs=[pred, true])
    
demo.launch()