Ejemplo n.º 1
0
def create_mom_rot_vs_alt_form():
    k_rot = 1000.0e2
    psi = 0.4
    h_eff = 3.0
    l_in = 3.0

    n_cap = 3000.
    nrs = [1.5, 2, 3, 5., 10]
    for nr in nrs:
        n_load = n_cap / nr
        m_cap = n_load * l_in / 2 * (1 - n_load / n_cap)
        moms = np.linspace(0.001, 0.99 * m_cap, 40)
        rots = []
        rots_alt = []

        for mom in moms:
            rots.append(
                eqdes.nonlinear_foundation.calc_fd_rot_via_millen_et_al_2020(
                    k_rot, l_in, n_load, n_cap, psi, mom, h_eff))
            rots_alt.append(
                eqdes.nonlinear_foundation.
                calc_fd_rot_via_millen_et_al_2020_alt_form(
                    k_rot, l_in, n_load, n_cap, psi, mom, h_eff))

        plt.plot(rots, moms, c=cbox(0))
        plt.plot(rots_alt, moms, ls='--', c=cbox(1))
    plt.show()
Ejemplo n.º 2
0
def run_example(show=0):
    import o3seespy as o3

    osi = None

    if show:
        import matplotlib.pyplot as plt
        bf, sps = plt.subplots(nrows=2)
        peak_strains = [0.0005, 0.0001, 0.0007]
        peak_strains = np.array([0.0005, 0.0001, 0.0007]) * 1
        esig_v0 = 100.0e3
        cohesion = 15.0e3
        sigma_y = np.sqrt(3) * cohesion
        rho = 0.0


        # NOTE DP model defines failure as R=c*cos(phi) + p*sin(phi), whereas meyerhof uses p*tan(phi)
        print('rho: ', rho)
        print('sigma_y: ', sigma_y)
        msig = esig_v0
        poissons_ratio = 0.3
        g_mod = 30.0e6
        unit_dry_mass = 1.6e3
        bulk_mod = 2 * g_mod * (1 + poissons_ratio) / (3 * (1 - 2 * poissons_ratio))

        etypes = ['implicit', 'explicit_difference']  # , 'central_difference'
        # etypes =['central_difference']
        for i, etype in enumerate(etypes):
            e_mod = 2 * g_mod * (1 + poissons_ratio)
            # mat = o3.nd_material.ElasticIsotropic(osi, e_mod=e_mod, nu=poissons_ratio, rho=unit_dry_mass)
            mat = o3.nd_material.DruckerPrager(osi, bulk_mod, g_mod, sigma_y, rho, 0, 0, 0, 0, 0, 0, theta=0.0,
                                               density=unit_dry_mass, p_atm=101.0e3)
            stime = timeit.timeit()
            ss, es, vp, hp, time, error = run_ts_custom_strain(mat, esig_v0=esig_v0, strains=peak_strains, osi=osi,
                                                 target_d_inc=1.0e-4, nl=True, etype=etype)
            etime = timeit.timeit()

            data = {'ss': ss, 'es': es, 'vp': vp, 'hp': hp}
            dfo = pd.DataFrame.from_dict(data)

            sps[0].plot(es, ss, label=f'{etype}', c=cbox(i), ls=lsbox(i))
            sps[1].plot(time, ss, label=f'{etype}', c=cbox(i), ls=lsbox(i))

        import o3soil.drivers.two_d as d2d
        mat = o3.nd_material.DruckerPrager(osi, bulk_mod, g_mod, sigma_y, rho, 0, 0, 0, 0, 0, 0, theta=0.0,
                                           density=unit_dry_mass, p_atm=101.0e3)
        # mat = o3.nd_material.ElasticIsotropic(osi, e_mod=e_mod, nu=poissons_ratio, rho=unit_dry_mass)
        stress, strain, v_eff, h_eff, exit_code = d2d.run_2d_strain_driver(osi, mat, esig_v0=esig_v0,
                                                                           disps=peak_strains,
                                                                           handle='warn', verbose=0,
                                                                           target_d_inc=0.00001)

        sps[0].plot(strain, stress, c='r')
        # sps[1].plot(strain[1:], stress[1:] / strain[1:], c='r')
        sps[0].legend()
        sps[1].legend()

        plt.show()
Ejemplo n.º 3
0
def rotation_settlement(sp):
    sp.yaxis.grid(True)
    sp.xaxis.grid(True)
    tools.clean_chart(sp)
    xlim = max(abs(sp.get_xlim()[0]), abs(sp.get_xlim()[1]))
    sp.set_xlim([-xlim, xlim])
    sp.set_ylim([(sp.get_ylim()[0]), (sp.get_ylim()[1])])
    # plot origin
    sp.plot([-xlim, xlim], [0, 0], c=cbox('dark gray'), zorder=-1)
    sp.plot([0, 0], [(sp.get_ylim()[0]), (sp.get_ylim()[1])], c=cbox('dark gray'), zorder=-2)
    sp.tick_params(axis="both", which="both", bottom=True, top=False,
                   labelbottom=True, left=True, right=False, labelleft=True)
Ejemplo n.º 4
0
def create():
    """
    Run an SDOF using three different damping options

    """
    dtypes = ['rot_dashpot', 'horz_dashpot', 'rayleigh']
    # dtypes = ['rayleigh']
    lss = ['-', '--', ':']

    bd = sm.SDOFBuilding()
    bd.mass_eff = 120.0e3
    bd.h_eff = 10.0
    bd.t_fixed = 0.7
    bd.xi = 0.2  # use high damping to evaluate performance of diff damping options
    bd.inputs += ['xi']
    l_ph = 0.2

    record_filename = 'test_motion_dt0p01.txt'
    asig = eqsig.load_asig(ap.MODULE_DATA_PATH + 'gms/' + record_filename, m=0.5)

    bf, sps = plt.subplots(nrows=3, figsize=(5, 8))

    for c, dtype in enumerate(dtypes):

        outputs = get_response(bd, asig, dtype=dtype, l_ph=l_ph)
        # Time series plots
        sps[0].plot(outputs['time'], outputs['deck_accel'] / 9.8, c=cbox(c), lw=0.7, label=dtype, ls=lss[c])
        sps[1].plot(outputs['hinge_rotation'] * 1e3, outputs['col_moment'] / 1e3, c=cbox(c), label=dtype, ls=lss[c])
        sps[2].plot(outputs['rel_deck_disp'] * 1e3, outputs['col_shear'] / 1e3, c=cbox(c), label=dtype, ls=lss[c])
        if dtype == 'rot_dashpot':
            sps[1].plot(outputs['hinge_rotation'] * 1e3, (outputs['col_moment'] - outputs['dashpot_force'][:, 2] / 2) / 1e3, c='r', label=dtype)
            sps[2].plot(outputs['rel_deck_disp'] * 1e3, (outputs['col_shear'] - 3. / 2. * outputs['dashpot_force'][:, 2] / bd.h_eff) / 1e3, c='r', label=dtype)

    sps[0].set_ylabel('Deck accel. [g]', fontsize=7)
    sps[0].set_xlabel('Time [s]')
    ef.text_at_rel_pos(sps[1], 0.1, 0.9, 'Column hinge')
    sps[1].set_xlabel('Rotation [mrad]')
    sps[1].set_ylabel('Moment [kNm]')
    sps[1].set_ylabel('Shear [kN]')
    sps[1].set_xlabel('Disp. [mm]')

    ef.revamp_legend(sps[0])

    ef.xy(sps[0], x_origin=True)
    ef.xy(sps[0], x_axis=True, y_axis=True)

    bf.tight_layout()
    name = __file__.replace('.py', '')
    name = name.split("fig_")[-1]
    bf.savefig(f'figures/{name}.png', dpi=90)
    plt.show()
Ejemplo n.º 5
0
def run_example(show=0):
    import o3seespy as o3

    osi = None

    if show:
        import matplotlib.pyplot as plt
        bf, sps = plt.subplots(nrows=2)
        peak_strains = [0.0005, 0.0001, 0.0007]
        peak_strains = np.array([0.0005, 0.0001, 0.0007]) * 1
        esig_v0 = 100.0e3
        poissons_ratio = 0.3
        g_mod = 30.0e6
        unit_dry_mass = 1.6e3
        etypes = [
            'implicit', 'newmark_explicit', 'explicit_difference',
            'central_difference'
        ]
        # etypes = ['implicit']
        for i, etype in enumerate(etypes):
            e_mod = 2 * g_mod * (1 + poissons_ratio)
            mat = o3.nd_material.ElasticIsotropic(osi,
                                                  e_mod=e_mod,
                                                  nu=poissons_ratio,
                                                  rho=unit_dry_mass)
            stime = timeit.timeit()
            ss, es, vp, hp, time, error = run_ts_custom_strain(
                mat,
                esig_v0=esig_v0,
                strains=peak_strains,
                osi=osi,
                target_d_inc=1.0e-4,
                nl=True,
                dss=True,
                etype=etype)
            etime = timeit.timeit()
            atime = etime - stime
            # ss /= 1e3
            data = {'ss': ss, 'es': es, 'vp': vp, 'hp': hp}
            dfo = pd.DataFrame.from_dict(data)

            sps[0].plot(es, ss, label=f'{etype}', c=cbox(i), ls=lsbox(i))
            sps[1].plot(time, ss, label=f'{etype}', c=cbox(i), ls=lsbox(i))
        ylims = np.array(sps[0].get_ylim())
        sps[0].plot(ylims / g_mod, ylims, c='k', ls=':', lw=0.7)
        sps[0].legend()
        sps[1].legend()

        plt.show()
Ejemplo n.º 6
0
def create(save=0, show=0):

    bf, subplot = plt.subplots(figsize=(ops.TWO_COL, 4))
    subplot.plot([0], [0], label="", c=cbox(0))

    subplot.set_xlabel('Period [s]')
    # subplot.set_xscale('log')
    subplot.set_ylabel('Disp. Response [m]')
    ef.xy(subplot, x_origin=True, y_origin=True)
    ef.revamp_legend(subplot, loc="upper left", prop={'size': 9})

    bf.tight_layout()
    name = __file__.replace('.py', '')
    name = name.split("figure_")[-1]
    extension = ""
    if save:
        bf.savefig(ap.PUB_FIG_PATH + name + extension + ops.PUB_FIG_FILE_TYPE,
                   dpi=ops.PUB_FIG_DPI)
        if ops.PUB_DOCUMENT_TYPE == "latex":
            para = ef.latex_for_figure(ap.FIG_FOLDER,
                                       name=ap.PUB_FIG_PATH + name + extension,
                                       ftype=ops.PUB_FIG_FILE_TYPE)
            print(para)
    if show:
        plt.show()
Ejemplo n.º 7
0
def test_basic_xy():
    x = np.linspace(0, 10, 50)
    y = x ** 2
    big_fig = plt.figure()
    sf = big_fig.add_subplot(111)
    sf.plot(x, y, label="test", c=cbox(2))
    esfp.xy(sf)
Ejemplo n.º 8
0
def pack_plotting_kwargs(ccbox, lls):
    kwargs = {}
    if lls is not None:
        kwargs["ls"] = lsbox(lls)
    if ccbox is not None:
        kwargs["c"] = cbox(ccbox)
    return kwargs
Ejemplo n.º 9
0
def transfer_function(sp, **kwargs):
    """
    Prepare a transfer function plot
    :param sp:
    :param kwargs:
    :return:
    """

    x_grid = kwargs.get('x_grid', True)
    y_grid = kwargs.get('y_grid', True)
    ratio = kwargs.get('ratio', False)

    if x_grid:
        sp.yaxis.grid(True, c=(0.9, 0.9, 0.9))
    if y_grid:
        sp.xaxis.grid(True, c=(0.9, 0.9, 0.9))

    lines = sp.get_lines()
    for line in lines:
        z_value = line.get_zorder()
        line.set_zorder(z_value + 100)
    tools.clean_chart(sp)
    sp.tick_params(axis="both", which="both", bottom=True, top=False,
                   labelbottom=True, left=True, right=False, labelleft=True)
    xlim = sp.get_xlim()
    ylim = sp.get_ylim()
    # set to xy origin:
    sp.set_xlim([0, xlim[1]])
    sp.set_ylim([0, ylim[1]])

    if ratio:
        xlim = sp.get_xlim()
        sp.plot(xlim, [1, 1], c=cbox('dark gray'), lw=0.7, zorder=50)
Ejemplo n.º 10
0
    def updater(self):

        if self.i == len(self.time) - 1:
            if not self.timer.isActive():
                self.timer.stop()
                # self.timer = 0  # allow looping if using stepper.
            else:
                self.timer.stop()
            return
        if self.ele_c is not None:
            return self.updater_w_ele_c()

        if self.node_c is not None:
            blist = np.array(self.node_brush_list)[self.node_bis[self.i]]
            # TODO: try using ScatterPlotWidget and colorMap
            if self.show_nodes:
                self.node_points_plot.setData(self.x[self.i], self.y[self.i], brush='g', symbol='o', symbolBrush=blist)
        elif self.show_nodes:
            self.node_points_plot.setData(self.x[self.i], self.y[self.i], brush='g', symbol='o')
        for i, mat in enumerate(self.mat2node_tags):
            nl = len(self.ele2node_tags[self.mat2ele[mat][0]])
            if nl == 2:
                pen = 'b'
            else:
                pen = 'w'

            brush = pg.mkBrush(cbox(i, as255=True, alpha=80))
            ele_x_coords = self.x[self.i][self.mat2node_tags[mat] - 1]
            ele_y_coords = (self.y[self.i])[self.mat2node_tags[mat] - 1]
            ele_x_coords = np.insert(ele_x_coords, len(ele_x_coords[0]), ele_x_coords[:, 0], axis=1).flatten()
            ele_y_coords = np.insert(ele_y_coords, len(ele_y_coords[0]), ele_y_coords[:, 0], axis=1).flatten()
            self.ele_lines_plot[mat].setData(ele_x_coords, ele_y_coords, pen=pen, connect=self.ele_connects[mat].flatten(),
                                         fillLevel='enclosed', fillBrush=brush)
        self.plotItem.setTitle(f"Time: {self.time[self.i]:.4g}s")
        self.i = self.i + 1
Ejemplo n.º 11
0
def skip_plot():
    import matplotlib.pyplot as plt
    accsig = eqsig.load_asig(conftest.TEST_DATA_DIR + 'test_motion_dt0p01.txt')
    accsig = eqsig.AccSignal(accsig.values[100:], accsig.dt)
    travel_times = np.linspace(0, 2, 44)
    travel_times = np.array([0.2, 0.5])
    stt = 0.0
    cases_w_s = eqsig.surface.calc_cum_abs_surface_energy(accsig,
                                                          travel_times,
                                                          nodal=True,
                                                          up_red=1,
                                                          down_red=1,
                                                          stt=stt,
                                                          trim=True,
                                                          start=True)
    # plt.plot(tshifts, cases[:, -1])
    # plt.plot(tshifts, expected_cases[:, -1])
    from bwplot import cbox
    plt.plot(accsig.time, cases_w_s[0], c=cbox(0))
    plt.plot(accsig.time, cases_w_s[1], c='r')
    cases = eqsig.surface.calc_cum_abs_surface_energy(accsig,
                                                      travel_times,
                                                      nodal=True,
                                                      up_red=1,
                                                      down_red=1,
                                                      stt=stt,
                                                      trim=True,
                                                      start=False)
    plt.plot(accsig.time, cases[0], c=cbox(1), ls='--')
    plt.plot(accsig.time, cases[1], c=cbox(1), ls='--')
    plt.plot(accsig.time + (stt - travel_times[0]), cases[0], c='k', ls=':')
    plt.plot(accsig.time + (stt - travel_times[1]), cases[1], c='k', ls=':')
    case_interp_0 = np.interp(accsig.time + (stt - travel_times[0]),
                              accsig.time, cases_w_s[0])
    diff0 = np.sum(abs(case_interp_0 - cases[0])) / cases[0][-1]
    assert np.isclose(diff0, 0., atol=5.0e-3), diff0
    case_interp_1 = np.interp(accsig.time + (stt - travel_times[1]),
                              accsig.time, cases_w_s[1])
    diff1 = np.sum(abs(case_interp_1 - cases[1])) / cases[1][-1]
    assert np.isclose(diff1, 0., atol=5.0e-3), diff1
    case_interp_2 = np.interp(accsig.time,
                              accsig.time + (stt - travel_times[2]),
                              cases_w_s[2])
    diff2 = np.sum(abs(case_interp_2 - cases[2])) / cases[2][-1]
    assert np.isclose(diff2, 0., atol=5.0e-3), diff2

    plt.show()
Ejemplo n.º 12
0
def plot_acc_sig_as_fa_spectrum(acc_sig, **kwargs):
    """
    Plots the Fourier amplitude spectrum

    :param acc_sig: eqsig.AccSignal Object
    :param kwargs:
    :return:
    """
    plot_on = kwargs.get('plot_on', False)
    legend_off = kwargs.get('legend_off', False)
    smooth = kwargs.get('smooth', False)

    info_str = kwargs.get('info_str', '')

    label = kwargs.get('label', acc_sig.label)

    log_off = kwargs.get('log_off', False)
    title = kwargs.get(
        'title', 'Fourier amplitude acceleration spectrums \n' + info_str)

    band = kwargs.get('band', 40)
    sub_plot = kwargs.get('sub_plot', 0)
    ccbox = kwargs.get('ccbox', 'auto')

    if smooth is False:
        spectrum = abs(acc_sig.fa_spectrum)
        frequencies = acc_sig.fa_frequencies

    else:

        acc_sig.generate_smooth_fa_spectrum(band=band)
        spectrum = abs(acc_sig.smooth_fa_spectrum)
        frequencies = acc_sig.smooth_fa_frequencies

    if sub_plot == 0:
        sub_plot = plt.figure().add_subplot(111)
    else:
        plot_on = 0
    if ccbox == "auto":
        ccbox = len(sub_plot.lines)
    acc_sig.ccbox = ccbox

    sub_plot.plot(frequencies, spectrum, label=label, c=cbox(ccbox), lw=0.7)

    sub_plot.set_xscale('log')
    if log_off is not True:
        sub_plot.set_yscale('log')
    sub_plot.set_xlabel('Frequency [Hz]')
    sub_plot.set_ylabel('Fourier Amplitude [m/s2]')

    if title is not False:
        sub_plot.set_title(title)
    if legend_off is False:
        sub_plot.legend(loc='upper left', prop={'size': 8})
    if plot_on == 1:
        plt.show()
    else:
        return sub_plot
Ejemplo n.º 13
0
def clean_chart(ax):
    """
    Removes extra lines of axes and tick marks from chart.
    """
    edges = ['top', 'bottom', 'right', 'left']
    ax.tick_params(color=cbox('dark gray'))
    for edge in edges:
        ax.spines[edge].set_color(cbox('dark gray'))
        ax.spines[edge].set_linewidth(0.4)
    ax.yaxis.label.set_color(cbox('dark gray'))
    ax.xaxis.label.set_color(cbox('dark gray'))
    ax.tick_params(axis='x',
                   colors=(0.05, 0.05, 0.05),
                   width=0.5,
                   which='major',
                   top=True)
    ax.tick_params(axis='y',
                   colors=(0.05, 0.05, 0.05),
                   width=0.5,
                   which='major',
                   left=True)
Ejemplo n.º 14
0
def run():
    xi = 0.03

    sl = sm.Soil()
    vs = 250.
    unit_mass = 1700.0
    sl.g_mod = vs**2 * unit_mass
    sl.poissons_ratio = 0.3
    sl.unit_dry_weight = unit_mass * 9.8
    sl.xi = xi  # for linear analysis

    sl_base = sm.Soil()
    vs = 350.
    unit_mass = 1700.0
    sl_base.g_mod = vs**2 * unit_mass
    sl_base.poissons_ratio = 0.3
    sl_base.unit_dry_weight = unit_mass * 9.8
    sl_base.xi = xi  # for linear analysis
    soil_profile = sm.SoilProfile()
    soil_profile.add_layer(0, sl)
    soil_profile.add_layer(10., sl_base)
    soil_profile.height = 20.0
    gm_scale_factor = 1.0

    import matplotlib.pyplot as plt
    from bwplot import cbox
    bf, sps = plt.subplots(ncols=3, figsize=(6, 8))

    ys = site_response(soil_profile, static=0)
    sps[0].plot(ys, c=cbox(0))
    ys = site_response(soil_profile, static=1)
    sps[0].plot(ys, c=cbox(1))

    sps[0].legend(prop={'size': 6})
    name = __file__.replace('.py', '')
    name = name.split("fig_")[-1]
    bf.suptitle(name)
    bf.savefig(f'figs/{name}.png', dpi=90)
    plt.show()
Ejemplo n.º 15
0
def hysteresis(sp):
    sp.yaxis.grid(True)
    sp.xaxis.grid(True)
    tools.clean_chart(sp)
    ylim = max(abs(sp.get_ylim()[0]), abs(sp.get_ylim()[1]))
    sp.set_ylim([-ylim, ylim])
    xlimits = sp.get_xlim()
    xlims = [0, 0]
    for x in range(len(xlimits)):
        if abs(xlimits[x]) > 0.999 and abs(xlimits[x]) < 1.0001:
            xlims[x] = 0
            print('found culprit')
        else:
            xlims[x] = xlimits[x]
    print('xlims: ', xlims)
    xlim = max(abs(xlims[0]), abs(xlims[1]))
    sp.set_xlim([-xlim, xlim])
    # plot origin
    sp.plot([-xlim, xlim], [0, 0], c=cbox('dark gray'), zorder=-1)
    sp.plot([0, 0], [-ylim, ylim], c=cbox('dark gray'), zorder=-2)
    sp.tick_params(axis="both", which="both", bottom=True, top=False,
                   labelbottom=True, left=True, right=False, labelleft=True)
Ejemplo n.º 16
0
    def init_model(self, coords, ele2node_tags=None):
        self.x_coords = np.array(coords)[:, 0]
        self.y_coords = np.array(coords)[:, 1]

        if ele2node_tags is not None:
            self.ele2node_tags = ele2node_tags
            self.mat2node_tags = {}
            if self.selected_nodes is not None:
                self.renumber_nodes_and_eles()
            for ele in self.ele2node_tags:
                self.ele2node_tags[ele] = np.array(self.ele2node_tags[ele])
            if not len(self.mat2ele):  # then arrange by node len
                for ele in self.ele2node_tags:
                    n = len(self.ele2node_tags[ele]) # - 1
                    if f'{n}-all' not in self.mat2ele:
                        self.mat2ele[f'{n}-all'] = []
                    self.mat2ele[f'{n}-all'].append(ele)

            for i, mat in enumerate(self.mat2ele):
                self.mat2ele[mat] = np.array(self.mat2ele[mat], dtype=int)
                eles = self.mat2ele[mat]
                # TODO: handle when mats assigned to eles of different node lens - not common by can be 8-node and 4-n
                self.mat2node_tags[mat] = np.array([self.ele2node_tags[ele] for ele in eles], dtype=int)
                ele_x_coords = self.x_coords[self.mat2node_tags[mat] - 1]
                ele_y_coords = self.y_coords[self.mat2node_tags[mat] - 1]
                ele_x_coords = np.insert(ele_x_coords, len(ele_x_coords[0]), ele_x_coords[:, 0], axis=1)
                ele_y_coords = np.insert(ele_y_coords, len(ele_y_coords[0]), ele_y_coords[:, 0], axis=1)
                connect = np.ones_like(ele_x_coords, dtype=np.ubyte)
                connect[:, -1] = 0
                ele_x_coords = ele_x_coords.flatten()
                ele_y_coords = ele_y_coords.flatten()
                self.ele_connects[mat] = connect
                nl = len(self.ele2node_tags[eles[0]])
                if nl == 2:
                    pen = 'b'
                else:
                    pen = 'w'
                brush = pg.mkBrush(cbox(i, as255=True, alpha=80))
                self.ele_lines_plot[mat] = self.win.plot(ele_x_coords, ele_y_coords, pen=pen,
                                                              connect=self.ele_connects[mat].flatten(), fillLevel='enclosed',
                                                              fillBrush=brush)
        if self.show_nodes:
            self.node_points_plot = self.win.plot([], pen=None,
                                                       symbolBrush=(255, 0, 0), symbolSize=5, symbolPen=None)
            self.node_points_plot.setData(self.x_coords, self.y_coords)
        self.win.autoRange(padding=0.05)  # TODO: depends on xmag
        self.win.disableAutoRange()
Ejemplo n.º 17
0
def xy(sp, **kwargs):
    matplotlib.rcParams['lines.linewidth'] = 1.2
    x_origin = kwargs.get('x_origin', False)
    y_origin = kwargs.get('y_origin', False)
    x_axis = kwargs.get('x_axis', False)
    y_axis = kwargs.get('y_axis', False)
    parity = kwargs.get('parity', False)
    x_grid = kwargs.get('x_grid', False)
    y_grid = kwargs.get('y_grid', False)
    ratio = kwargs.get('ratio', False)
    if x_grid:
        sp.yaxis.grid(True, c=cbox('light gray'), zorder=-500, ls="--")
    if y_grid:
        sp.xaxis.grid(True, c=cbox('light gray'), zorder=-600, ls="--")
    sp.set_axisbelow(True)
    tools.clean_chart(sp)
    sp.tick_params(axis="both", which="both", top=False,
                   right=False)
    xlim = sp.get_xlim()
    ylim = sp.get_ylim()
    if x_origin:
        sp.set_xlim([0, xlim[1]])
    if y_origin:
        sp.set_ylim([0, ylim[1]])
    xlim = sp.get_xlim()
    ylim = sp.get_ylim()
    if x_axis:
        sp.axhline(0, c=cbox('dark gray'), zorder=0.6, lw=0.85)
    if y_axis:
        sp.axvline(0, c=cbox('dark gray'), zorder=0.55, lw=0.85)
    if ratio:
        sp.plot(xlim, [1, 1], c=cbox('dark gray'), zorder=-3)
    if parity:
        botlim = min(xlim[0], ylim[0])
        toplim = min(xlim[1], ylim[1])
        sp.plot([botlim, toplim], [botlim, toplim], c=cbox('mid gray'), zorder=-2)
        if parity == 2:
            if botlim == 0.0:
                xs = np.linspace(botlim, toplim, 2)
            else:
                xs = np.logspace(np.log10(botlim), np.log10(toplim), 30)
            sp.fill_between(xs, xs * 0.5, xs * 2, facecolor=cbox('mid gray'),
                            zorder=-3, alpha=0.3)
Ejemplo n.º 18
0
def time_series(sp, **kwargs):
    balance = kwargs.get('balance', False)
    x_axis = kwargs.get('x_axis', True)
    x_origin = kwargs.get('x_origin', False)
    y_origin = kwargs.get('y_origin', False)
    sp.yaxis.grid(True)
    tools.clean_chart(sp)
    xlim = sp.get_xlim()
    ylim = sp.get_ylim()
    if x_origin:
        sp.set_xlim([0, xlim[1]])
    if y_origin:
        sp.set_ylim([0, ylim[1]])
    if x_axis:
        sp.plot(sp.get_xlim(), [0, 0], c=cbox('dark gray'), ls='--', zorder=-1, lw=0.7)
    if balance:
        ylim = max(abs(sp.get_ylim()[0]), abs(sp.get_ylim()[1]))
        sp.set_ylim([-ylim, ylim])
    sp.tick_params(axis="both", which="both", bottom=True, top=False,
                   labelbottom=True, left=True, right=False, labelleft=True)
    tools.trim_ticks(sp, balance=balance)
    if balance:
        ylim = max(abs(sp.get_ylim()[0]), abs(sp.get_ylim()[1]))
        sp.set_ylim([-ylim, ylim])
Ejemplo n.º 19
0
def run(show=0, export=0):
    sl = sm.Soil()

    vs = 160.
    unit_mass = 1700.0
    sl.cohesion = 58.0e3
    sl.phi = 0.0
    sl.g_mod = vs ** 2 * unit_mass
    sl.poissons_ratio = 0.0
    sl.phi = 0.0
    sl.unit_dry_weight = unit_mass * 9.8
    sl.strain_peak = 0.1  # set additional parameter required for PIMY model
    sl.xi = 0.03  # for linear analysis
    assert np.isclose(vs, sl.get_shear_vel(saturated=False))
    soil_profile = sm.SoilProfile()
    soil_profile.add_layer(0, sl)

    sl = sm.Soil()
    vs = 400.
    unit_mass = 1700.0
    sl.g_mod = vs ** 2 * unit_mass
    sl.poissons_ratio = 0.0
    sl.cohesion = 395.0e3
    sl.phi = 0.0
    sl.unit_dry_weight = unit_mass * 9.8
    sl.strain_peak = 0.1  # set additional parameter required for PIMY model
    sl.xi = 0.03  # for linear analysis
    soil_profile.add_layer(9.5, sl)
    soil_profile.height = 20.0
    ecp_out = sm.Output()
    ecp_out.add_to_dict(soil_profile)
    if export:
        import json
        ofile = open('ecp.json', 'w')
        ofile.write(json.dumps(ecp_out.to_dict(), indent=4))
        ofile.close()
    from tests.conftest import TEST_DATA_DIR

    record_path = TEST_DATA_DIR
    record_filename = 'test_motion_dt0p01.txt'
    dt = 0.01
    rec = np.loadtxt(record_path + record_filename) / 2
    acc_signal = eqsig.AccSignal(rec, dt)

    outputs = site_response(soil_profile, acc_signal, linear=0)
    tot_acc = np.sum(abs(outputs['rel_accel']))
    assert np.isclose(tot_acc, 515.76262984), tot_acc  # v3.1.0.11
    resp_dt = outputs['time'][2] - outputs['time'][1]
    surf_sig = eqsig.AccSignal(outputs['rel_accel'], resp_dt)

    if show:
        lw = 0.7
        import matplotlib.pyplot as plt
        from bwplot import cbox
        bf, sps = plt.subplots(nrows=3)

        # linear analysis with pysra
        od = run_pysra(soil_profile, acc_signal, odepths=np.array([0.0, 2.0]))
        pysra_sig = eqsig.AccSignal(od['ACCX_d0'], acc_signal.dt)

        sps[0].plot(acc_signal.time, acc_signal.values, c='k', lw=lw)
        sps[0].plot(surf_sig.time, surf_sig.values, c=cbox(0), lw=lw)
        sps[0].plot(acc_signal.time, pysra_sig.values, c=cbox(1), lw=lw)

        sps[1].plot(acc_signal.fa_frequencies, abs(acc_signal.fa_spectrum), c='k', label='Input', lw=lw)
        sps[1].plot(surf_sig.fa_frequencies, abs(surf_sig.fa_spectrum), c=cbox(0), label='O3', lw=lw)
        sps[1].plot(pysra_sig.fa_frequencies, abs(pysra_sig.fa_spectrum), c=cbox(1), label='pysra', lw=lw)
        sps[1].set_xlim([0, 20])
        h = surf_sig.smooth_fa_spectrum / acc_signal.smooth_fa_spectrum
        sps[2].plot(surf_sig.smooth_fa_frequencies, h, c=cbox(0))
        pysra_h = pysra_sig.smooth_fa_spectrum / acc_signal.smooth_fa_spectrum
        sps[2].plot(pysra_sig.smooth_fa_frequencies, pysra_h, c=cbox(1))
        # o3_nl_h = nl_surf_sig.smooth_fa_spectrum / acc_signal.smooth_fa_spectrum
        # sps[2].plot(nl_surf_sig.smooth_fa_frequencies, o3_nl_h, c=cbox(2))
        sps[2].axhline(1, c='k', ls='--')
        sps[1].legend()
        plt.show()
        print(outputs)
def run_example(show=0):
    import o3seespy as o3

    osi = None

    if show:
        import matplotlib.pyplot as plt
        bf, sps = plt.subplots(nrows=2)
        peak_strains = [0.0005, 0.0001, 0.0007]
        peak_strains = np.array([0.0005, 0.0001, 0.0007]) * 1
        esig_v0 = 100.0e3
        cohesion = 15.0e3
        sigma_y = np.sqrt(3) * cohesion
        rho = 0.0


        # NOTE DP model defines failure as R=c*cos(phi) + p*sin(phi), whereas meyerhof uses p*tan(phi)
        print('rho: ', rho)
        print('sigma_y: ', sigma_y)
        msig = esig_v0
        poissons_ratio = 0.3
        g_mod = 30.0e6
        unit_dry_mass = 1.6e3
        bulk_mod = 2 * g_mod * (1 + poissons_ratio) / (3 * (1 - 2 * poissons_ratio))

        sl = lq.num.models.PM4Sand()
        unit_mass = 15471. / 9.8
        esig_v0 = 100.0e3
        ref_press = 100.e3
        sl.phi = 33.0
        g_mod = 31.8e6
        sl.poissons_ratio = 0.3
        sl.set_g0_mod_at_v_eff_stress(esig_v0, g_mod, plane_strain=1)
        sl.g0_mod = 316.
        # sl.h_po = 4.
        sl.h_po = 0.833
        sl.relative_density = 0.405
        print('G_mod: ', g_mod)
        sl.unit_dry_weight = unit_mass * 9.8
        sl.specific_gravity = 2.65

        # etypes = ['explicit_difference', 'central_difference']
        etypes = ['implicit']
        etypes = []
        # etypes =['central_difference']
        for i, etype in enumerate(etypes):
            mat = o3.nd_material.PM4Sand(osi, sl.relative_density, sl.g0_mod, sl.h_po, nu=sl.poissons_ratio,
                                         den=sl.unit_dry_mass, p_atm=101.0e3, a_do=0.001)

            stime = timeit.timeit()
            ss, es, vp, hp, time, error = run_ts_custom_strain(mat, esig_v0=esig_v0, strains=peak_strains, osi=osi,
                                                 target_d_inc=1.0e-4, nl=True, etype=etype)
            etime = timeit.timeit()

            data = {'ss': ss, 'es': es, 'vp': vp, 'hp': hp}
            dfo = pd.DataFrame.from_dict(data)

            sps[0].plot(es, ss, label=f'{etype}', c=cbox(i), ls=lsbox(i))
            sps[1].plot(time, ss, label=f'{etype}', c=cbox(i), ls=lsbox(i))

        import o3soil.drivers.two_d as d2d
        # mat = o3.nd_material.DruckerPrager(osi, bulk_mod, g_mod, sigma_y, rho, 0, 0, 0, 0, 0, 0, theta=0.0,
        #                                    density=unit_dry_mass, p_atm=101.0e3)
        # mat = o3.nd_material.ElasticIsotropic(osi, e_mod=e_mod, nu=poissons_ratio, rho=unit_dry_mass)
        mat = o3.nd_material.PM4Sand(osi, sl.relative_density, sl.g0_mod, sl.h_po, nu=sl.poissons_ratio,
                                     den=sl.unit_dry_mass, p_atm=101.0e3)
        stress, strain, v_eff, h_eff, exit_code = d2d.run_2d_strain_driver(osi, mat, esig_v0=esig_v0,
                                                                           disps=peak_strains,
                                                                           handle='warn', verbose=0,
                                                                           target_d_inc=0.00001)

        sps[0].plot(strain, stress, c='r', lw=0.5, ls='--')
        # sps[1].plot(strain[1:], stress[1:] / strain[1:], c='r')
        sps[0].legend()
        sps[1].legend()

        plt.show()
Ejemplo n.º 21
0
import numpy as np
import pyqtgraph as pg
from bwplot import cbox
from pyqtgraph.Qt import QtGui, QtCore

plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: Legend')
plt.addLegend()

x = [3, 5, 5, 3, 3, 7, 9, 9, 7, 7, 7]
y = [2, 2, 4, 4, 2, 6, 6, 7, 7, 6, 6]
connect = np.array([1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0])

pen = 'w'
brush = pg.mkBrush(cbox(0, as255=True, alpha=80))

c = plt.plot(x,
             y,
             pen='w',
             connect=connect,
             fillBrush=brush,
             fillLevel='enclosed',
             name="fillLevel='enclosed'")

x = [13, 15, 15, 13, 13, 17, 19, 19, 17, 17, 17]
c = plt.plot(x,
             y,
             pen='y',
             connect=connect,
             fillBrush='r',
             fillLevel=0,
def run():
    sl = sm.Soil()
    sl.type = 'pimy'
    vs = 160.
    unit_mass = 1700.0
    sl.cohesion = 58.0e3
    sl.phi = 0.0
    sl.g_mod = vs**2 * unit_mass
    sl.poissons_ratio = 0.0
    sl.phi = 0.0
    sl.unit_dry_weight = unit_mass * 9.8
    sl.specific_gravity = 2.65
    sl.strain_peak = 0.1  # set additional parameter required for PIMY model
    sl.xi = 0.03  # for linear analysis
    sl.sra_type = 'hyperbolic'
    assert np.isclose(vs, sl.get_shear_vel(saturated=False))
    soil_profile = sm.SoilProfile()
    soil_profile.add_layer(0, sl)

    sl = sm.Soil()
    sl.type = 'pimy'
    vs = 400.
    unit_mass = 1700.0
    sl.g_mod = vs**2 * unit_mass
    sl.poissons_ratio = 0.0
    sl.cohesion = 395.0e3
    sl.phi = 0.0
    sl.unit_dry_weight = unit_mass * 9.8
    sl.specific_gravity = 2.65
    sl.strain_peak = 0.1  # set additional parameter required for PIMY model
    sl.xi = 0.03  # for linear analysis
    sl.sra_type = 'hyperbolic'
    soil_profile.add_layer(9.5, sl)
    soil_profile.height = 20.0
    ecp_out = sm.Output()
    ecp_out.add_to_dict(soil_profile)
    ofile = open('ecp.json', 'w')
    ofile.write(json.dumps(ecp_out.to_dict(), indent=4))
    ofile.close()

    record_path = TEST_DATA_DIR
    record_filename = 'short_motion_dt0p01.txt'
    in_sig = eqsig.load_asig(record_filename)

    # linear analysis with pysra
    od = run_pysra(soil_profile, in_sig, odepths=np.array([0.0, 2.0]))
    pysra_sig = eqsig.AccSignal(od['ACCX_d0'], in_sig.dt)

    outputs = o3soil.sra.site_response(soil_profile, in_sig)
    resp_dt = outputs['time'][2] - outputs['time'][1]
    surf_sig = eqsig.AccSignal(outputs['ACCX'][0], resp_dt)

    o3_surf_vals = np.interp(pysra_sig.time, surf_sig.time, surf_sig.values)

    show = 1

    if show:
        import matplotlib.pyplot as plt
        from bwplot import cbox

        bf, sps = plt.subplots(nrows=3)

        sps[0].plot(in_sig.time, in_sig.values, c='k', label='Input')
        sps[0].plot(pysra_sig.time, o3_surf_vals, c=cbox(0), label='o3')
        sps[0].plot(pysra_sig.time, pysra_sig.values, c=cbox(1), label='pysra')

        sps[1].plot(in_sig.fa_frequencies, abs(in_sig.fa_spectrum), c='k')
        sps[1].plot(surf_sig.fa_frequencies,
                    abs(surf_sig.fa_spectrum),
                    c=cbox(0))
        sps[1].plot(pysra_sig.fa_frequencies,
                    abs(pysra_sig.fa_spectrum),
                    c=cbox(1))
        sps[1].set_xlim([0, 20])
        h = surf_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(surf_sig.smooth_fa_frequencies, h, c=cbox(0))
        pysra_h = pysra_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(pysra_sig.smooth_fa_frequencies, pysra_h, c=cbox(1))
        sps[2].axhline(1, c='k', ls='--')
        sps[0].plot(pysra_sig.time, (o3_surf_vals - pysra_sig.values) * 10,
                    c='r',
                    label='Error x10')
        sps[0].legend()
        plt.show()

    assert np.isclose(o3_surf_vals, pysra_sig.values, atol=0.01,
                      rtol=100).all()
Ejemplo n.º 23
0
def plot_acc_sig_as_response_spectrum(acc_sig,
                                      legend_off=False,
                                      label="",
                                      xaxis="frequency",
                                      sub_plot=None,
                                      response_type='acceleration',
                                      ccbox="auto",
                                      xlog=True,
                                      title=False):
    """
    Plot a response spectrum

    :param acc_sig: eqsig.AccSignal Object
    :param legend_off: bool, no legend
    :param label: str, legend label
    :param xaxis: str, 'frequency' or 'time'
    :param sub_plot: matplotlib.pyplot.subplot object
    :param response_type: str, 'acceleration' or 'velocity' or 'displacement'
    :param ccbox: int, cbox number
    :param title: str, plot title
    :return:
    """
    acc_sig.generate_response_spectrum()
    plot_on = 1

    if label == "":
        label = acc_sig.label

    if response_type == 'acceleration':
        response = acc_sig.s_a
        y_label = 'Spectral acceleration [$m/s^2$]'
    elif response_type == 'velocity':
        response = acc_sig.s_v
        y_label = 'Spectral velocity [$m/s$]'
    elif response_type == 'displacement':
        response = acc_sig.s_d
        y_label = 'Spectral displacement [$m$]'
    else:
        raise NotImplementedError
    if sub_plot is None:
        sub_plot = plt.figure().add_subplot(111)
    else:
        plot_on = 0
    if xaxis == "time":
        x_para = acc_sig.response_times
    else:
        x_para = 1 / acc_sig.response_times

    if ccbox == "auto":
        ccbox = len(sub_plot.lines)
    acc_sig.ccbox = ccbox

    sub_plot.plot(x_para,
                  response,
                  label=label,
                  c=cbox(0 + acc_sig.ccbox),
                  lw=0.7)

    if xlog:
        sub_plot.set_xscale('log')

    if xaxis == "period":
        sub_plot.set_xlabel('Time period [s]')
        sub_plot.set_xlim([0, acc_sig.response_times[-1]])
    else:
        sub_plot.set_xlabel('Frequency [Hz]')
    sub_plot.set_ylabel(y_label)

    if title is not False:
        sub_plot.set_title(title)

    if legend_off is False:
        sub_plot.legend(loc='upper left', prop={'size': 8})
    if plot_on == 1:
        plt.show()
    else:
        return sub_plot
Ejemplo n.º 24
0
def plot_acc_sig_as_time_series(acc_sig, **kwargs):
    """
    Plots a time series

    :param acc_sig: eqsig.AccSignal Object
    :param kwargs:
    :return:
    """
    plot_on = kwargs.get('plot_on', False)
    legend_off = kwargs.get('legend_off', False)
    info_str = kwargs.get('info_str', '')
    motion_type = kwargs.get('motion_type', 'acceleration')

    y_label = kwargs.get('y_label', motion_type.title())
    x_label = kwargs.get('x_label', 'Time [s]')
    y_limits = kwargs.get('y_limits', False)
    label = kwargs.get('label', acc_sig.label)
    sub_plot = kwargs.get('sub_plot', 0)
    window = kwargs.get('window', [0, -1])
    ccbox = kwargs.get('ccbox', "auto")  # else integer

    cut_index = np.array([0, len(acc_sig.values)])
    if window[0] != 0:
        cut_index[0] = int(window[0] / acc_sig.dt)
    if window[1] != -1:
        cut_index[1] = int(window[1] / acc_sig.dt)

    if sub_plot == 0:
        sub_plot = plt.figure().add_subplot(111)
    else:
        plot_on = 0
    if ccbox == "auto":
        ccbox = len(sub_plot.lines)

    if motion_type == "acceleration":
        motion = acc_sig.values[cut_index[0]:cut_index[1]]
        balance = True
    elif motion_type == "velocity":
        motion = acc_sig.velocity[cut_index[0]:cut_index[1]]
        balance = True
    elif motion_type == "displacement":
        motion = acc_sig.displacement[cut_index[0]:cut_index[1]]
        balance = False
    elif motion_type == "custom":
        motion = acc_sig.values[cut_index[0]:cut_index[1]]
        balance = False
    else:
        raise NotImplementedError

    t0 = acc_sig.dt * (np.linspace(0, (len(motion) + 1),
                                   (len(motion))) + cut_index[0])
    sub_plot.plot(t0, motion, label=label, c=cbox(0 + ccbox), lw=0.7)
    esfp.time_series(sub_plot, balance=balance)

    if x_label is not False:
        sub_plot.set_xlabel(x_label)
    sub_plot.set_ylabel(y_label)
    if info_str != '':
        stitle = 'Time series \n' + info_str
        sub_plot.set_title(stitle)
    if y_limits is not False:
        sub_plot.set_ylim(y_limits)

    x_limits = [0, t0[-1]]
    sub_plot.set_xlim(x_limits)
    if not legend_off:
        sub_plot.legend(loc='upper right', prop={'size': 8})
    if plot_on == 1:
        plt.show()
    else:
        return sub_plot
Ejemplo n.º 25
0
def plot_acc_sig_as_transfer_function(base_acc_sig, acc_sigs, **kwargs):
    """
    Plots the transfer function between the base values and a list of other motions

    :param base_acc_sig: eqsig.AccSignal object
    :param acc_sigs: A list of eqsig.AccSignal objects
    :param kwargs:
    :return:
    """
    plot_on = kwargs.get('plot_on', False)
    legend_off = kwargs.get('legend_off', False)
    smooth = kwargs.get('smooth', False)
    info_str = kwargs.get('info_str', '')
    base_label = kwargs.get('label', base_acc_sig.label)
    log_off = kwargs.get('log_off', False)
    title = kwargs.get('title', 'Transfer function \n' + info_str)
    band = kwargs.get('band', 40)
    sub_plot = kwargs.get('sub_plot', 0)
    ccbox = kwargs.get('ccbox', 'auto')

    if smooth is False:
        base_spectrum = abs(base_acc_sig.fa_spectrum)
        base_frequencies = base_acc_sig.fa_frequencies
    else:
        base_acc_sig.generate_smooth_fa_spectrum(band=band)
        base_spectrum = abs(base_acc_sig.smooth_fa_spectrum)
        base_frequencies = base_acc_sig.smooth_fa_frequencies

    if sub_plot == 0:
        sub_plot = plt.figure().add_subplot(111)
    else:
        plot_on = 0
    if ccbox == "auto":
        ccbox = len(sub_plot.lines)

    for rec in acc_sigs:
        if smooth is False:
            if rec.dt != base_acc_sig.dt or len(rec.values) != len(
                    base_acc_sig.values):
                raise SignalProcessingError(
                    "Motion lengths and timestep do not match. "
                    "Cannot build non-smooth spectrum")
            spectrum = abs(rec.fa_spectrum)
        else:
            rec.reset_smooth_spectrum(freq_range=base_acc_sig.freq_range)
            rec.generate_smooth_fa_spectrum(band=band)
            spectrum = abs(rec.smooth_fa_spectrum)

        sub_plot.plot(base_frequencies,
                      spectrum / base_spectrum,
                      label=rec.label,
                      c=cbox(ccbox),
                      lw=0.7)

    sub_plot.set_xscale('log')
    if log_off is not True:
        sub_plot.set_yscale('log')
    sub_plot.set_xlabel('Frequency [Hz]')
    sub_plot.set_ylabel('Transfer function from %s' % base_label)

    if title is not False:
        sub_plot.set_title(title)
    if legend_off is False:
        sub_plot.legend(loc='upper left', prop={'size': 8})
    if plot_on == 1:
        plt.show()
    else:
        return sub_plot
Ejemplo n.º 26
0
def run():
    soil_profile = sm.SoilProfile()
    soil_profile.height = 30.0
    xi = 0.03

    sl = sm.Soil()
    vs = 250.
    unit_mass = 1700.0
    sl.g_mod = vs**2 * unit_mass
    sl.poissons_ratio = 0.3
    sl.unit_dry_weight = unit_mass * 9.8
    sl.xi = xi  # for linear analysis
    soil_profile.add_layer(0, sl)

    sl_base = sm.Soil()
    vs = 350.
    unit_mass = 1700.0
    sl_base.g_mod = vs**2 * unit_mass
    sl_base.poissons_ratio = 0.3
    sl_base.unit_dry_weight = unit_mass * 9.8
    sl_base.xi = xi  # for linear analysis
    soil_profile.add_layer(19., sl_base)
    soil_profile.height = 20.0
    gm_scale_factor = 1.5
    record_filename = 'short_motion_dt0p01.txt'
    in_sig = eqsig.load_asig(ap.MODULE_DATA_PATH + 'gms/' + record_filename,
                             m=gm_scale_factor)

    # analysis with pysra
    od = lq.sra.run_pysra(soil_profile,
                          in_sig,
                          odepths=np.array([0.0]),
                          wave_field='within')
    pysra_sig = eqsig.AccSignal(od['ACCX'][0], in_sig.dt)

    # Implicit analysis with O3
    outputs_imp = site_response(soil_profile,
                                in_sig,
                                freqs=(0.5, 10),
                                xi=xi,
                                analysis_dt=0.001)
    resp_dt = outputs_imp['time'][2] - outputs_imp['time'][1]
    surf_sig_imp = eqsig.AccSignal(outputs_imp['ACCX'][0], resp_dt)

    # Explicit analysis with O3
    outputs_exp = site_response(soil_profile,
                                in_sig,
                                freqs=(0.5, 10),
                                xi=xi,
                                analysis_dt=0.0001,
                                use_explicit=1)
    resp_dt = outputs_exp['time'][2] - outputs_exp['time'][1]
    surf_sig = eqsig.AccSignal(outputs_exp['ACCX'][0], resp_dt)

    show = 1

    if show:
        import matplotlib.pyplot as plt
        from bwplot import cbox

        in_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
        surf_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
        pysra_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
        surf_sig_imp.smooth_fa_frequencies = in_sig.fa_frequencies[1:]

        bf, sps = plt.subplots(nrows=3)

        sps[0].plot(in_sig.time, in_sig.values, c='k', label='Input')
        sps[0].plot(pysra_sig.time, pysra_sig.values, c=cbox(1), label='pysra')
        sps[0].plot(surf_sig_imp.time,
                    surf_sig_imp.values,
                    c=cbox(0),
                    label='o3-imp')
        sps[0].plot(surf_sig.time,
                    surf_sig.values,
                    c=cbox(2),
                    label='o3-exp',
                    ls='--')

        sps[1].plot(in_sig.fa_frequencies, abs(in_sig.fa_spectrum), c='k')
        sps[1].plot(pysra_sig.fa_frequencies,
                    abs(pysra_sig.fa_spectrum),
                    c=cbox(1))
        sps[1].plot(surf_sig_imp.fa_frequencies,
                    abs(surf_sig_imp.fa_spectrum),
                    c=cbox(0))
        sps[1].plot(surf_sig.fa_frequencies,
                    abs(surf_sig.fa_spectrum),
                    c=cbox(2),
                    ls='--')
        sps[1].set_xlim([0, 20])
        pysra_h = pysra_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(pysra_sig.smooth_fa_frequencies, pysra_h, c=cbox(1))

        h = surf_sig_imp.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(in_sig.smooth_fa_frequencies, h, c=cbox(0))
        h = surf_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(surf_sig.smooth_fa_frequencies, h, c=cbox(2), ls='--')

        sps[2].axhline(1, c='k', ls='--')

        sps[0].legend()
        plt.show()
Ejemplo n.º 27
0
def run():
    soil_profile = sm.SoilProfile()
    soil_profile.height = 30.0
    xi = 0.03

    sl = sm.Soil()
    sl.o3_type = 'lin'  # Use linear soil model
    vs = 250.
    unit_mass = 1700.0
    sl.g_mod = vs**2 * unit_mass
    sl.poissons_ratio = 0.3
    sl.unit_dry_weight = unit_mass * 9.8
    sl.xi = xi  # for linear analysis
    soil_profile.add_layer(0, sl)

    sl_base = sm.Soil()
    vs = 350.
    unit_mass = 1700.0
    sl_base.g_mod = vs**2 * unit_mass
    sl_base.poissons_ratio = 0.3
    sl_base.unit_dry_weight = unit_mass * 9.8
    sl_base.xi = xi  # for linear analysis
    soil_profile.add_layer(10., sl_base)
    soil_profile.height = 20.0
    gm_scale_factor = 1.5
    record_filename = 'short_motion_dt0p01.txt'
    in_sig = eqsig.load_asig(ap.MODULE_DATA_PATH + 'gms/' + record_filename,
                             m=gm_scale_factor)

    # analysis with pysra
    od = lq.sra.run_pysra(soil_profile,
                          in_sig,
                          odepths=np.array([0.0]),
                          wave_field='outcrop')
    pysra_sig = eqsig.AccSignal(od['ACCX'][0], in_sig.dt)
    freqs = (0.5, 10)

    # outputs_imp = site_response(soil_profile, in_sig, freqs=(0.5, 10), xi=xi, analysis_dt=0.001)
    # resp_dt = outputs_imp['time'][2] - outputs_imp['time'][1]
    # surf_sig_imp = eqsig.AccSignal(outputs_imp['ACCX'][0], resp_dt)

    outputs_exp = site_response(soil_profile,
                                in_sig,
                                freqs=freqs,
                                xi=xi,
                                analysis_dt=0.0001,
                                use_explicit=1)
    resp_dt = outputs_exp['time'][2] - outputs_exp['time'][1]
    surf_sig = eqsig.AccSignal(outputs_exp['ACCX'][0], resp_dt)
    surf_sig_imp = surf_sig

    show = 1

    if show:
        import matplotlib.pyplot as plt
        from bwplot import cbox

        in_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
        surf_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
        pysra_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
        surf_sig_imp.smooth_fa_frequencies = in_sig.fa_frequencies[1:]

        bf, sps = plt.subplots(nrows=3)

        sps[0].plot(in_sig.time, in_sig.values, c='k', label='Input')
        sps[0].plot(pysra_sig.time, pysra_sig.values, c=cbox(1), label='pysra')
        sps[0].plot(surf_sig_imp.time,
                    surf_sig_imp.values,
                    c=cbox(0),
                    label='o3-imp')
        sps[0].plot(surf_sig.time,
                    surf_sig.values,
                    c=cbox(2),
                    label='o3-exp',
                    ls='--')

        sps[1].plot(in_sig.fa_frequencies, abs(in_sig.fa_spectrum), c='k')
        sps[1].plot(pysra_sig.fa_frequencies,
                    abs(pysra_sig.fa_spectrum),
                    c=cbox(1))
        sps[1].plot(surf_sig_imp.fa_frequencies,
                    abs(surf_sig_imp.fa_spectrum),
                    c=cbox(0))
        sps[1].plot(surf_sig.fa_frequencies,
                    abs(surf_sig.fa_spectrum),
                    c=cbox(2),
                    ls='--')
        sps[1].set_xlim([0, 20])
        pysra_h = pysra_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(pysra_sig.smooth_fa_frequencies, pysra_h, c=cbox(1))

        h = surf_sig_imp.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(in_sig.smooth_fa_frequencies, h, c=cbox(0))
        h = surf_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(surf_sig.smooth_fa_frequencies, h, c=cbox(2), ls='--')

        omega_1 = 2 * np.pi * freqs[0]
        omega_2 = 2 * np.pi * freqs[1]
        a0 = 2 * xi * omega_1 * omega_2 / (omega_1 + omega_2)
        a1 = 2 * xi / (omega_1 + omega_2)

        xi_min, fmin = lq.num.flac.calc_rayleigh_damping_params(f1=freqs[0],
                                                                f2=freqs[1],
                                                                d=xi)
        omega_min = 2 * np.pi * fmin
        alpha = xi_min * 2 * np.pi * fmin  # mass proportional term
        beta = xi_min / omega_min  # stiffness proportional term
        fs = np.logspace(-1, 1.3, 30)
        omgs = 2 * np.pi * fs
        xi_vals = 0.5 * (alpha / omgs + beta * omgs)
        sps[2].plot(fs, xi_vals * 100, c='k')
        sps[2].axhline(1, c='k', ls='--')
        sps[2].set_ylim([0, 2])
        sps[0].legend()
        plt.show()
Ejemplo n.º 28
0
def run():
    forder = 1.0e3
    sl = sm.Soil()
    sl.o3_type = 'pimy'
    vs = 100.
    xi = 0.03
    unit_mass = 1700.0
    sl.cohesion = 120.0e3
    sl.phi = 0.0
    sl.g_mod = vs ** 2 * unit_mass
    sl.poissons_ratio = 0.0
    sl.unit_dry_weight = unit_mass * 9.8
    sl.specific_gravity = 2.65
    sl.xi = 0.03  # for linear analysis
    sl.xi_min = 0.03  # for eqlin analysis
    sl.peak_strain = 0.1

    sl.o3_mat = o3.nd_material.PressureIndependMultiYield(None, 2, unit_mass / forder, sl.g_mod / forder,
                                                          sl.bulk_mod / forder, sl.cohesion / forder, 0.1,
                                                          0.0, 101.0e3 / forder, 0.0, 25)

    assert np.isclose(vs, sl.get_shear_vel(saturated=False))
    soil_profile = sm.SoilProfile()
    soil_profile.add_layer(0, sl)

    sl_base = sm.Soil()
    sl_base.o3_type = 'pimy'
    vs = 150.
    unit_mass = 1700.0
    sl_base.g_mod = vs ** 2 * unit_mass
    sl_base.poissons_ratio = 0.0
    sl_base.cohesion = 120.0e3
    sl_base.phi = 0.0
    sl_base.unit_dry_weight = unit_mass * 9.8
    sl_base.specific_gravity = 2.65
    sl_base.xi = xi  # for linear analysis
    sl_base.xi_min = 0.03  # for eqlin analysis
    sl_base.peak_strain = 0.1
    e_mod = 2 * sl_base.g_mod * (1 + sl_base.poissons_ratio)
    sl_base.o3_mat = o3.nd_material.PressureIndependMultiYield(None, 2, unit_mass / forder, sl_base.g_mod / forder,
                                                          sl_base.bulk_mod / forder, sl_base.cohesion / forder, 0.1, 0.0,
                                                          101.0e3 / forder, 0.0, 25)
    soil_profile.add_layer(5.1, sl_base)
    soil_profile.height = 10.0
    gm_scale_factor = 0.5
    record_filename = 'short_motion_dt0p01.txt'
    in_sig = eqsig.load_asig(ap.MODULE_DATA_PATH + 'gms/' + record_filename, m=gm_scale_factor)

    # analysis with pysra
    sl.sra_type = 'hyperbolic'
    sl_base.sra_type = 'hyperbolic'
    od = lq.sra.run_pysra(soil_profile, in_sig, odepths=np.array([0.0]), wave_field='within')
    pysra_sig = eqsig.AccSignal(od['ACCX'][0], in_sig.dt)

    import matplotlib.pyplot as plt
    from bwplot import cbox
    bf, sps = plt.subplots(nrows=3, figsize=(6, 8))

    in_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
    pysra_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
    sps[0].plot(in_sig.time, in_sig.values, c='k', label='Input')
    sps[0].plot(pysra_sig.time, pysra_sig.values, c='r', label='pysra')
    sps[1].plot(in_sig.fa_frequencies, abs(in_sig.fa_spectrum), c='k')
    sps[1].semilogx(pysra_sig.fa_frequencies, abs(pysra_sig.fa_spectrum), c='r')
    pysra_h = pysra_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
    sps[2].semilogx(pysra_sig.smooth_fa_frequencies, pysra_h, c='r')

    # analysis with O3
    etypes = ['implicit', 'explicit_difference', 'central_difference', 'newmark_explicit']
    # etypes = ['central_difference']
    # etypes = ['implicit', 'explicit_difference']
    ls = ['-', '--', ':', '-.']

    for i, etype in enumerate(etypes):
        outputs_exp = site_response(soil_profile, in_sig, freqs=(0.5, 10), xi=xi, etype=etype, forder=forder,
                                    rec_dt=in_sig.dt, analysis_time=in_sig.time[-1] + 3)
        resp_dt = (outputs_exp['time'][-1] - outputs_exp['time'][0]) / (len(outputs_exp['time']) - 1)
        abs_surf_sig = outputs_exp['ACCX'][0] + np.interp(np.arange(len(outputs_exp['ACCX'][0])) * resp_dt, in_sig.time,
                                                          in_sig.values)
        surf_sig = eqsig.AccSignal(abs_surf_sig, resp_dt)

        surf_sig.smooth_fa_frequencies = in_sig.fa_frequencies[1:]
        sps[0].plot(surf_sig.time, surf_sig.values, c=cbox(i), label=etype, ls=ls[i])
        sps[1].plot(surf_sig.fa_frequencies, abs(surf_sig.fa_spectrum), c=cbox(i), ls=ls[i])
        h = surf_sig.smooth_fa_spectrum / in_sig.smooth_fa_spectrum
        sps[2].plot(surf_sig.smooth_fa_frequencies, h, c=cbox(i), ls=ls[i])

    sps[2].axhline(1, c='k', ls='--')

    sps[0].legend(prop={'size': 6})
    name = __file__.replace('.py', '')
    name = name.split("fig_")[-1]
    bf.suptitle(name)
    bf.savefig(f'figs/{name}.png', dpi=90)
    plt.show()
Ejemplo n.º 29
0
    sl.phi = 33.

    sl.permeability = 1.0e-9
    sl.p_atm = 101.0e3
    strain_inc = 5.e-6
    csr = 0.16
    etypes = ['explicit_difference', 'central_difference']
    etypes = ['implicit', 'central_difference']
    bf, sps = plt.subplots(nrows=2)
    for ee, etype in enumerate(etypes):
        stress, strain, ppt, disps = run_pm4sand_et(sl,
                                                    csr=csr,
                                                    n_lim=20,
                                                    strain_limit=0.03,
                                                    esig_v0=esig_v0,
                                                    strain_inc=strain_inc,
                                                    k0=k0,
                                                    etype=etype)

        sps[0].plot(stress, label='shear', c=cbox(ee))
        sps[0].plot(ppt, label='PPT', c=cbox(ee))
        sps[1].plot(strain, stress, label=etype, c=cbox(ee))

    sps[0].set_xlabel('Time [s]')
    sps[0].set_ylabel('Stress [kPa]')
    sps[1].set_xlabel('Strain')
    sps[1].set_ylabel('Stress [kPa]')
    sps[0].legend()
    sps[1].legend()
    plt.show()
Ejemplo n.º 30
0
def plot_finite_element_mesh_onto_plot(plotItem, femesh, win=None, ele_c=None, label='', alpha=255, pw=0.7, copts=None,
                                      ):
    """
    Plots a finite element mesh object

    :param win:
    :param femesh:
    :param ele_c: array_like or str or None
        Specifies how he elements are colored, if None the color based on soil index,
        if str, the str must must a soil property and the color is scaled based on the value of the property
        if array_like, if shape of soil_grid, then color scale based on value,
        if array_like, if shape[:2] == soil_grid.shape(), and shape[2:]==3, then last axis interpreted as color values
    :param pw: pen width
    :return:
    """
    if copts is None:
        copts = {}

    cscheme = copts.setdefault('scheme', 'red2yellow')
    cbal = copts.setdefault('bal', 0)
    cunits = copts.setdefault('units', '')
    cinc = copts.setdefault('inc', None)
    white_mid = copts.setdefault('white_mid', False)
    crange = copts.setdefault('crange', None)
    palpha = copts.setdefault('palpha', 80)
    pen_col = copts.setdefault('pen_col', None)
    leg_pen = copts.setdefault('leg_pen', 'w')

    x_all = femesh.x_nodes
    y_all = femesh.y_nodes
    x_inds = []
    y_inds = []
    if hasattr(y_all[0], '__len__'):  # can either have varying y-coordinates or single set
        n_y = len(y_all[0])
    else:
        n_y = 0
    ed = {}
    cd = {}
    active_eles = np.where(femesh.soil_grid != femesh.inactive_value)
    for xx in range(len(femesh.soil_grid)):
        x_ele = [xx, xx + 1, xx + 1, xx, xx]
        x_inds += x_ele * (n_y - 1)
        for yy in range(len(femesh.soil_grid[xx])):
            sl_ind = femesh.soil_grid[xx][yy]
            if sl_ind == femesh.inactive_value:
                sl_ind = -1
            elif ele_c is not None:
                sl_ind = 1
            if sl_ind not in ed:
                ed[sl_ind] = [[], []]

            y_ele = [yy + xx * n_y, yy + (xx + 1) * n_y, yy + 1 + (xx + 1) * n_y, yy + 1 + xx * n_y, yy + xx * n_y]
            ed[sl_ind][0].append(x_ele)
            ed[sl_ind][1].append(y_ele)
            if ele_c is not None:
                if sl_ind not in cd:
                    cd[sl_ind] = []
                cd[sl_ind].append(ele_c[xx][yy])
            y_inds += y_ele
    ele_bis = {}
    if ele_c is not None:
        if len(ele_c.shape) == 2:
            sch_cols = np.array(colors.get_colors(cscheme))
            ecol = len(sch_cols)
            brush_list = [pg.mkColor(colors.color_by_index(cscheme, i, as255=True, alpha=alpha)) for i in range(ecol)]
            if crange is None:
                if cbal:
                    mabs = np.max(abs(ele_c[active_eles]))
                    y_max = mabs
                    y_min = -mabs
                else:
                    y_max = np.max(ele_c[active_eles])
                    y_min = np.min(ele_c[active_eles])
                if cinc:
                    y_max = np.ceil(y_max / cinc) * cinc
                    y_min = np.floor(y_min / cinc) * cinc
            else:
                y_min = crange[0]
                if y_min is None:
                    y_min = np.min(ele_c[active_eles])
                y_max = crange[1]
                if y_max is None:
                    y_max = np.max(ele_c[active_eles])
            inc = (y_max - y_min) * 0.001

            for sl_ind in cd:
                cd[sl_ind] = np.clip(cd[sl_ind], y_min, y_max)
                if inc == 0.0:
                    ele_bis[sl_ind] = int(ecol / 2) * np.ones_like(cd[sl_ind], dtype=int)
                else:
                    ele_bis[sl_ind] = (cd[sl_ind] - y_min) / (y_max + inc - y_min) * ecol
                    ele_bis[sl_ind] = np.array(ele_bis[sl_ind], dtype=int)
        elif len(ele_c.shape) == 3:
            pass
        else:
            raise ValueError('ele_c must be same dimensions as soil_grid')
    yc = y_all.flatten()
    xc = x_all.flatten()
    if len(xc) == len(yc):  # then it is vary_xy
        for item in ed:
            ed[item][0] = ed[item][1]

    for sl_ind in ed:
        ed[sl_ind][0] = np.array(ed[sl_ind][0])
        ed[sl_ind][1] = np.array(ed[sl_ind][1])
        if sl_ind < 0:
            pen = pg.mkPen([200, 200, 200, 10], width=pw)
        else:
            if pen_col is None:
                pen = pg.mkPen([200, 200, 200, palpha], width=pw)
            else:
                pen = pg.mkPen(pen_col, width=pw)
            if ele_c is not None:

                if len(ele_c.shape) == 3:  # colors directly specified

                    # brushes = np.array(brush_list)[ele_bis[sl_ind]]
                    brushes_col = ele_c[active_eles]
                    brushes = np.array([pg.mkColor(col) for col in brushes_col])  # TODO: v. slow
                    # eles_x_coords = xc[ed[sl_ind][0]]
                    # eles_y_coords = yc[ed[sl_ind][1]]
                    # ele_ind = ele
                    # item = color_grid.ColorGrid(eles_x_coords, eles_y_coords, brushes)
                else:
                    brushes = np.array(brush_list)[ele_bis[sl_ind]]
                eles_x_coords = xc[ed[sl_ind][0]]
                eles_y_coords = yc[ed[sl_ind][1]]
                item = color_grid.ColorGrid(eles_x_coords, eles_y_coords, brushes, pen_col=pen_col)
                plotItem.addItem(item)
            else:
                ed[sl_ind][0] = np.array(ed[sl_ind][0]).flatten()
                ed[sl_ind][1] = np.array(ed[sl_ind][1]).flatten()
                if sl_ind < 0:
                    brush = pg.mkBrush([255, 255, 255, 20])
                else:
                    brush = pg.mkColor(cbox(sl_ind, as255=True, alpha=alpha))
                ele_x_coords = xc[ed[sl_ind][0]]
                # ele_x_coords = xc[ed[sl_ind][1]]
                ele_y_coords = yc[ed[sl_ind][1]]
                ele_connects = np.array([1, 1, 1, 1, 0] * int(len(ed[sl_ind][0]) / 5))
                plotItem.plot(ele_x_coords, ele_y_coords, pen=pen,
                                  connect=ele_connects, fillLevel='enclosed',
                                  fillBrush=brush)

    if ele_c is not None and len(ele_c.shape) != 3:
        lut = np.zeros((155, 3), dtype=np.ubyte)
        lut[:, 0] = np.arange(100, 255)
        lut = np.array([colors.color_by_index(cscheme, i, as255=True) for i in range(ecol)], dtype=int)
        a_inds = np.where(femesh.soil_grid != femesh.inactive_value)
        leg_copts = {
            'leg_pen': leg_pen
        }
        o3ptools.add_color_bar(win, plotItem, lut, vmin=y_min, vmax=y_max,
                               label=label, n_cols=ecol, units=cunits, bal=cbal, copts=leg_copts)

    return win.plotItem