<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Examples of neural reparamterization for structural optimization
In the paper, we run every optimization for 1000 steps and focus on the largest problems. These are pretty slow to run, so to keep this notebook interactive we'll focus on smaller examples trained for fewer steps.
Step1:  MBB Beam (Figure 2 from paper)
Note that we tweaked the CNN model slightly original version of the paper, which results in a slightly worse design in this particular case.
See the updated figure in our latest revision on OpenReview.net.
Step2:  If desired, designs can also be converted into PIL.Image objects with the pipeline_utils.image_from_design utility. This is convenient for exporting single frames or creating GIFs
Step3:  This produces the following movie of the optimization process
Step4:  Now, the CNN-LBFGS model performs best
Step5:  Multistory building
Step6:  For fun, we'll examine designs at different time-steps.
Step7:  Thin support bridge
<ASSISTANT_TASK:>
Python Code:
# Install dependencies with pip. Only run this once.
! pip install -q tf-nightly git+https://github.com/google-research/neural-structural-optimization.git
# Copyright 2019 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from IPython import display
from PIL import Image
import seaborn
import matplotlib.pyplot as plt
import xarray
import pandas as pd
from neural_structural_optimization import pipeline_utils
from neural_structural_optimization import problems
from neural_structural_optimization import models
from neural_structural_optimization import topo_api
from neural_structural_optimization import train
def train_all(problem, max_iterations, cnn_kwargs=None):
    args = topo_api.specified_task(problem)
    if cnn_kwargs is None:
        cnn_kwargs = {}
    model = models.PixelModel(args=args)
    ds_mma = train.method_of_moving_asymptotes(model, max_iterations)
    model = models.PixelModel(args=args)
    ds_oc = train.optimality_criteria(model, max_iterations)
    model = models.PixelModel(args=args)
    ds_pix = train.train_lbfgs(model, max_iterations)
    model = models.CNNModel(args=args, **cnn_kwargs)
    ds_cnn = train.train_lbfgs(model, max_iterations)
    dims = pd.Index(['cnn-lbfgs', 'mma', 'oc', 'pixel-lbfgs'], name='model')
    return xarray.concat([ds_cnn, ds_mma, ds_oc, ds_pix], dim=dims)
Explanation: Examples of neural reparamterization for structural optimization
In the paper, we run every optimization for 1000 steps and focus on the largest problems. These are pretty slow to run, so to keep this notebook interactive we'll focus on smaller examples trained for fewer steps.
End of explanation
problem = problems.mbb_beam(height=20, width=60)
max_iterations = 200
# can't upscale by exactly 8x for a 60x20 design region, so upscale by
# only 4x instead
%time ds = train_all(problem, max_iterations, cnn_kwargs=dict(resizes=(1, 1, 2, 2, 1)))
ds
ds.loss.transpose().to_pandas().cummin().loc[:200].plot(linewidth=2)
plt.ylim(215, 260)
plt.ylabel('Compliance (loss)')
plt.xlabel('Optimization step')
seaborn.despine()
ds.design.sel(step=200).plot.imshow(
    col='model', x='x', y='y', size=2, aspect=2.5, col_wrap=2,
    yincrease=False, add_colorbar=False, cmap='Greys')
Explanation: MBB Beam (Figure 2 from paper)
Note that we tweaked the CNN model slightly original version of the paper, which results in a slightly worse design in this particular case.
See the updated figure in our latest revision on OpenReview.net.
End of explanation
def save_gif_movie(images, path, duration=200, loop=0, **kwargs):
    images[0].save(path, save_all=True, append_images=images[1:],
                   duration=duration, loop=loop, **kwargs)
images = [
    pipeline_utils.image_from_design(design, problem)
    for design in ds.design.sel(model='cnn-lbfgs')[:100]
]
save_gif_movie([im.resize((5*120, 5*20)) for im in images], 'movie.gif')
Explanation: If desired, designs can also be converted into PIL.Image objects with the pipeline_utils.image_from_design utility. This is convenient for exporting single frames or creating GIFs:
End of explanation
problem = problems.PROBLEMS_BY_NAME['mbb_beam_192x64_0.4']
max_iterations = 100
%time ds = train_all(problem, max_iterations)
Explanation: This produces the following movie of the optimization process:
<img src="https://github.com/google-research/neural-structural-optimization/raw/master/notebooks/movie.gif" />
MBB beam with a larger grid
End of explanation
ds.loss.transpose().to_pandas().cummin().loc[:200].plot(linewidth=2)
plt.ylim(230, 330)
plt.ylabel('Compliance (loss)')
plt.xlabel('Optimization step')
seaborn.despine()
# the pixel-lbfgs does not run for the full 100 steps (it terminates
# early due to reaching a local minima), so use fill() to forward fill
# to the last valid design.
ds.design.ffill('step').sel(step=100).plot.imshow(
    col='model', x='x', y='y', size=2, aspect=2.5, col_wrap=2,
    yincrease=False, add_colorbar=False, cmap='Greys')
plt.suptitle(problem.name, y=1.02);
Explanation: Now, the CNN-LBFGS model performs best:
End of explanation
problem = problems.PROBLEMS_BY_NAME['multistory_building_64x128_0.4']
max_iterations = 100  # keep things fast
%time ds = train_all(problem, max_iterations)
ds.loss.transpose().to_pandas().cummin().loc[:100].plot(linewidth=2)
plt.ylim(40, 100)
plt.ylabel('Compliance (loss)')
plt.xlabel('Optimization step')
seaborn.despine()
plt.suptitle(problem.name);
Explanation: Multistory building
End of explanation
ds.design.sel(step=[0, 1, 2, 5, 10, 20, 50, 100]).plot.imshow(
    row='model', col='step', x='x', y='y', size=2, aspect=0.5,
    yincrease=False, add_colorbar=False, cmap='Greys')
plt.subplots_adjust(wspace=0.1, hspace=0.05)
plt.suptitle(problem.name, y=1.02);
Explanation: For fun, we'll examine designs at different time-steps.
End of explanation
# we really need more iterations to see the CNN-LBFGS method dominate
problem = problems.PROBLEMS_BY_NAME['thin_support_bridge_128x128_0.2']
max_iterations = 200
%time ds = train_all(problem, max_iterations)
ds.loss.transpose().to_pandas().cummin().plot(linewidth=2)
plt.ylim(70, 120)
plt.ylabel('Compliance (loss)')
plt.xlabel('Optimization step')
seaborn.despine()
plt.suptitle(problem.name);
(xarray.concat([ds.design, ds.design.sel(x=slice(None, None, -1))] * 2, dim='x')
 .sel(step=200)
 .plot.imshow(
    col='model', x='x', y='y', size=2.5, aspect=2, col_wrap=2,
    yincrease=False, add_colorbar=False, cmap='Greys'))
plt.suptitle(problem.name, y=1.02);
Explanation: Thin support bridge
End of explanation
<END_TASK>