Checks the seismic depths for physical consistency
        :param float upper_depth:
            Upper seismogenic depth (km)

        :param float lower_depth:
            Lower seismogenic depth (km)
762784
def _check_seismogenic_depths(self, upper_depth, lower_depth):
        '''
        
        '''
        # Simple check on depths
        if upper_depth:
            if upper_depth < 0.:
                raise ValueError('Upper seismogenic depth must be greater than'
                                 ' or equal to 0.0!')
            else:
                self.upper_depth = upper_depth
        else:
            self.upper_depth = 0.0

        if not lower_depth:
            raise ValueError('Lower seismogenic depth must be defined for '
                             'simple fault source!')
        if lower_depth < self.upper_depth:
            raise ValueError('Lower seismogenic depth must take a greater'
                             ' value than upper seismogenic depth')

        self.lower_depth = lower_depth
3793
def RMSError(self):
        
        tss = 0.0
        size = 0
        for layer in self.layers:
            if layer.type == 'Output':
                tss += layer.TSSError()
                size += layer.size
        return math.sqrt( tss / size )
143136
function calcultateDepths(depths, callback) {
    if (depths.parentDepth) {
        // if a depth of the links doesn't exist : assign the parehtDepth +1
        // if not, this link has been already found in the past => don't update its depth
        if (! depths.linkDepth) {
            depths.linkDepth = depths.parentDepth + 1;
        }
    }
    else {
        depths.parentDepth = 0;
        depths.linkDepth = 1;
    }
    callback(null, depths);
}
704825
def convert_simpleFaultSource(self, node):
        
        geom = node.simpleFaultGeometry
        msr = valid.SCALEREL[~node.magScaleRel]()
        fault_trace = self.geo_line(geom)
        mfd = self.convert_mfdist(node)
        with context(self.fname, node):
            try:
                hypo_list = valid.hypo_list(node.hypoList)
            except AttributeError:
                hypo_list = ()
            try:
                slip_list = valid.slip_list(node.slipList)
            except AttributeError:
                slip_list = ()
            simple = source.SimpleFaultSource(
                source_id=node['id'],
                name=node['name'],
                tectonic_region_type=node.attrib.get('tectonicRegion'),
                mfd=mfd,
                rupture_mesh_spacing=self.rupture_mesh_spacing,
                magnitude_scaling_relationship=msr,
                rupture_aspect_ratio=~node.ruptAspectRatio,
                upper_seismogenic_depth=~geom.upperSeismoDepth,
                lower_seismogenic_depth=~geom.lowerSeismoDepth,
                fault_trace=fault_trace,
                dip=~geom.dip,
                rake=~node.rake,
                temporal_occurrence_model=self.get_tom(node),
                hypo_list=hypo_list,
                slip_list=slip_list)
        return simple
1353783
def main_plates(sdat):
    """"""
    # calculating averaged horizontal surface velocity
    # needed for redimensionalisation
    ilast = sdat.rprof.index.levels[0][-1]
    rlast = sdat.rprof.loc[ilast]
    nprof = 0
    uprof_averaged = rlast.loc[:, 'vhrms'] * 0
    for step in sdat.walk.filter(rprof=True):
        uprof_averaged += step.rprof['vhrms']
        nprof += 1
    uprof_averaged /= nprof
    radius = rlast['r'].values
    if sdat.par['boundaries']['air_layer']:
        dsa = sdat.par['boundaries']['air_thickness']
        isurf = np.argmin(abs(radius - radius[-1] + dsa))
        vrms_surface = uprof_averaged.iloc[isurf]
        isurf = np.argmin(abs((1 - dsa) - radius))
        isurf -= 4  # why different isurf for the rest?
    else:
        isurf = -1
        vrms_surface = uprof_averaged.iloc[isurf]

    with misc.InchoateFiles(8, 'plates') as fids:
        fids.fnames = ['plate_velocity', 'distance_subd', 'continents',
                       'flux', 'topography', 'age', 'velderiv', 'velocity']
        fids[0].write('#  it  time  ph_trench vel_trench age_trench\n')
        fids[1].write('#  it      time   time [My]   distance     '
                      'ph_trench     ph_cont  age_trench [My]\n')

        istart, iend = None, None
        for step in sdat.walk.filter(fields=['T']):
            # could check other fields too
            timestep = step.isnap
            istart = timestep if istart is None else istart
            iend = timestep
            print('Treating snapshot', timestep)

            rcmb = step.geom.rcmb
            # topography
            fname = sdat.filename('sc', timestep=timestep, suffix='.dat')
            topo = np.genfromtxt(str(fname))
            # rescaling topography!
            if sdat.par['boundaries']['air_layer']:
                topo[:, 1] = topo[:, 1] / (1. - dsa)

            time = step.geom.ti_ad * vrms_surface *\
                conf.scaling.ttransit / conf.scaling.yearins / 1.e6
            trenches, ridges, agetrenches, _, _ =\
                detect_plates(step, vrms_surface, fids, time)
            plot_plates(step, time, vrms_surface, trenches, ridges,
                        agetrenches, topo, fids)

            # prepare for continent plotting
            concfld = step.fields['c'][0, :, :, 0]
            continentsfld = np.ma.masked_where(
                concfld < 3, concfld)  # plotting continents, to-do
            continentsfld = continentsfld / continentsfld

            temp = step.fields['T'][0, :, :, 0]
            tgrad = (temp[:, isurf - 1] - temp[:, isurf]) /\
                (step.geom.r_coord[isurf] - step.geom.r_coord[isurf - 1])

            io_surface(timestep, time, fids[2], concfld[:-1, isurf])
            io_surface(timestep, time, fids[3], tgrad)
            io_surface(timestep, time, fids[4], topo[:, 1])
            if 'age' in conf.plates.plot:
                io_surface(timestep, time, fids[5],
                           step.fields['age'][0, :, isurf, 0])

            # plot viscosity field with position of trenches and ridges
            etamin, _ = sdat.scale(1e-2, 'Pa')
            etamax, _ = sdat.scale(sdat.par['viscosity']['eta_max'], 'Pa')
            fig, axis, _, _ = field.plot_scalar(step, 'eta',
                                                vmin=etamin, vmax=etamax)

            # plotting continents
            field.plot_scalar(step, 'c', continentsfld, axis, False,
                              cmap='cool_r', vmin=0, vmax=0)
            cmap2 = plt.cm.ocean
            cmap2.set_over('m')

            # plotting velocity vectors
            field.plot_vec(axis, step, 'v')

            # Annotation with time and step
            axis.text(1., 0.9, str(round(time, 0)) + ' My',
                      transform=axis.transAxes)
            axis.text(1., 0.1, str(timestep),
                      transform=axis.transAxes)

            # Put arrow where ridges and trenches are
            plot_plate_limits_field(axis, rcmb, ridges, trenches)

            misc.saveplot(fig, 'eta', timestep, close=False)

            # Zoom
            if conf.plates.zoom is not None:
                if not 0 <= conf.plates.zoom <= 360:
                    raise error.InvalidZoomError(conf.plates.zoom)
                if 45 < conf.plates.zoom <= 135:
                    ladd, radd, uadd, dadd = 0.8, 0.8, 0.05, 0.1
                elif 135 < conf.plates.zoom <= 225:
                    ladd, radd, uadd, dadd = 0.05, 0.1, 0.8, 0.8
                elif 225 < conf.plates.zoom <= 315:
                    ladd, radd, uadd, dadd = 0.8, 0.8, 0.1, 0.05
                else:  # >315 or <=45
                    ladd, radd, uadd, dadd = 0.1, 0.05, 0.8, 0.8
                xzoom = (rcmb + 1) * np.cos(np.radians(conf.plates.zoom))
                yzoom = (rcmb + 1) * np.sin(np.radians(conf.plates.zoom))
                axis.set_xlim(xzoom - ladd, xzoom + radd)
                axis.set_ylim(yzoom - dadd, yzoom + uadd)
                misc.saveplot(fig, 'etazoom', timestep, close=False)
            plt.close(fig)

            # plot stress field with position of trenches and ridges
            if 'str' in conf.plates.plot:
                fig, axis, _, _ = field.plot_scalar(step, 'sII',
                                                    vmin=0, vmax=300)

                # Annotation with time and step
                axis.text(1., 0.9, str(round(time, 0)) + ' My',
                          transform=axis.transAxes)
                axis.text(1., 0.1, str(timestep),
                          transform=axis.transAxes)

                # Put arrow where ridges and trenches are
                plot_plate_limits_field(axis, rcmb, ridges, trenches)

                misc.saveplot(fig, 's', timestep, close=False)

                # Zoom
                if conf.plates.zoom is not None:
                    axis.set_xlim(xzoom - ladd, xzoom + radd)
                    axis.set_ylim(yzoom - dadd, yzoom + uadd)
                    misc.saveplot(fig, 'szoom', timestep, close=False)
                plt.close(fig)

                # calculate stresses in the lithosphere
                lithospheric_stress(step, trenches, ridges, time)

            # plotting the principal deviatoric stress field
            if 'sx' in conf.plates.plot:
                fig, axis, _, _ = field.plot_scalar(step, 'sII',
                                                    alpha=0.1)

                # plotting continents
                field.plot_scalar(step, 'c', continentsfld, axis, False,
                                  cmap='cool_r', vmin=0, vmax=0)
                cmap2 = plt.cm.ocean
                cmap2.set_over('m')

                # plotting principal deviatoric stress
                field.plot_vec(axis, step, 'sx')

                # Annotation with time and step
                axis.text(1., 0.9, str(round(time, 0)) + ' My',
                          transform=axis.transAxes)
                axis.text(1., 0.1, str(timestep),
                          transform=axis.transAxes)

                # Put arrow where ridges and trenches are
                plot_plate_limits_field(axis, rcmb, ridges, trenches)

                misc.saveplot(fig, 'sx', timestep)

        # determine names of files
        ptn = misc.out_name('{}_{}_{}')
        stem = ptn.format(fids.fnames[0], istart, iend)
        idx = 0
        fmt = '{}.dat'
        while pathlib.Path(fmt.format(stem, idx)).is_file():
            fmt = '{}_{}.dat'
            idx += 1
        fids.fnames = [fmt.format(ptn.format(fname, istart, iend), idx)
                       for fname in fids.fnames]
1124641
def cur_depth_level(self):
        
        cur_level = self.initial_depth
        if not self.am_i_main_thread:
            cur_level += len(self.get_tasks(thread_name='MainThread'))

        return cur_level + len(self.tasks)
518592
def _check_segment_cohesion(self):
        

        if self.n_seg != len(self.segments):
            raise ValueError("Length of segments must match the 'n_seg' field")

        for i in range(n_seg):
            s = self.segments[i]

            # If segment 0 is a layout specification record, check that its file names are all == '~''
            if i == 0 and self.seg_len[0] == 0:
                for file_name in s.file_name:
                    if file_name != '~':
                        raise ValueError("Layout specification records must have all file_names named '~'")

            # Sampling frequencies must all match the one in the master header
            if s.fs != self.fs:
                raise ValueError("The 'fs' in each segment must match the overall record's 'fs'")

            # Check the signal length of the segment against the corresponding seg_len field
            if s.sig_len != self.seg_len[i]:
                raise ValueError('The signal length of segment '+str(i)+' does not match the corresponding segment length')

            totalsig_len = totalsig_len + getattr(s, 'sig_len')
572473
def _compute_faulting_style_term(self, C, rup):
        
        # ranges of rake values for each faulting mechanism are specified in
        # table 2, page 75
        return (C['a12'] * float(rup.rake > 30 and rup.rake < 150) +
                C['a13'] * float(rup.rake > -120 and rup.rake < -60))
1005808
def derive_depth(self, depth):
        
        cls = type(self)
        # We use ordinals to avoid thunk materialization.
        return cls(
            self[0],
            self[1],
            self[2],
            self[3],
            self[4],
            depth
        )
860824
def add_rup_params(self, rupture):
        
        for param in self.REQUIRES_RUPTURE_PARAMETERS:
            if param == 'mag':
                value = rupture.mag
            elif param == 'strike':
                value = rupture.surface.get_strike()
            elif param == 'dip':
                value = rupture.surface.get_dip()
            elif param == 'rake':
                value = rupture.rake
            elif param == 'ztor':
                value = rupture.surface.get_top_edge_depth()
            elif param == 'hypo_lon':
                value = rupture.hypocenter.longitude
            elif param == 'hypo_lat':
                value = rupture.hypocenter.latitude
            elif param == 'hypo_depth':
                value = rupture.hypocenter.depth
            elif param == 'width':
                value = rupture.surface.get_width()
            else:
                raise ValueError('%s requires unknown rupture parameter %r' %
                                 (type(self).__name__, param))
            setattr(rupture, param, value)
799303
def _compute_imt1100(self, imt, sites, rup, dists):
        
        vs30_1100 = np.zeros_like(sites.vs30) + 1100
        vs30_star, _ = self._compute_vs30_star_factor(imt, vs30_1100)
        C = self.COEFFS[imt]
        mean = (self._compute_base_term(C, rup, dists) +
                self._compute_faulting_style_term(C, rup) +
                self._compute_hanging_wall_term(C, dists, rup) +
                self._compute_top_of_rupture_depth_term(C, rup) +
                self._compute_large_distance_term(C, dists, rup) +
                self._compute_soil_depth_term(C, imt, sites.z1pt0, vs30_1100) +
                # this is the site response term in case of vs30=1100
                ((C['a10'] + C['b'] * self.CONSTS['n']) *
                np.log(vs30_star / C['VLIN'])))

        return mean
1338102
def _get_soil_depth_term(self, C, z1pt0, vs30):
        
        # Get reference z1pt0
        z1ref = self._get_z1pt0ref(vs30)
        # Get z1pt0
        z10 = copy.deepcopy(z1pt0)
        # This is used for the calculation of the motion on reference rock
        idx = z1pt0 < 0
        z10[idx] = z1ref[idx]
        factor = np.log((z10 + 0.01) / (z1ref + 0.01))
        # Here we use a linear interpolation as suggested in the 'Application
        # guidelines' at page 1044
        # Above 700 m/s the trend is flat, but we extend the Vs30 range to
        # 6,000 m/s (basically the upper limit for mantle shear wave velocity
        # on earth) to allow extrapolation without throwing an error.
        f2 = interpolate.interp1d(
            [0.0, 150, 250, 400, 700, 1000, 6000],
            [C['a43'], C['a43'], C['a44'], C['a45'], C['a46'], C['a46'],
             C['a46']],
            kind='linear')
        return f2(vs30) * factor
687923
def _compute_style_of_faulting_term(self, C, rup):
        
        frv, fnm = self._get_fault_type_dummy_variables(rup.rake)

        if frv > 0.:
            # Top of rupture depth term only applies to reverse faults
            if rup.ztor < 1.:
                ffltz = rup.ztor
            else:
                ffltz = 1.
        else:
            ffltz = 0.
        return (C['c7'] * frv * ffltz) + (C['c8'] * fnm)
923049
def _validate_key(self, key):
        
        if key == () and len(self.kdims) == 0: return ()
        key = util.wrap_tuple(key)
        assert len(key) == len(self.kdims)
        for ind, val in enumerate(key):
            kdim = self.kdims[ind]
            low, high = util.max_range([kdim.range, kdim.soft_range])
            if util.is_number(low) and util.isfinite(low):
                if val < low:
                    raise KeyError("Key value %s below lower bound %s"
                                   % (val, low))
            if util.is_number(high) and util.isfinite(high):
                if val > high:
                    raise KeyError("Key value %s above upper bound %s"
                                   % (val, high))
799223
def _apply_uncertainty_to_geometry(self, source, value):
        
        if self.uncertainty_type == 'simpleFaultDipRelative':
            source.modify('adjust_dip', dict(increment=value))
        elif self.uncertainty_type == 'simpleFaultDipAbsolute':
            source.modify('set_dip', dict(dip=value))
        elif self.uncertainty_type == 'simpleFaultGeometryAbsolute':
            trace, usd, lsd, dip, spacing = value
            source.modify(
                'set_geometry',
                dict(fault_trace=trace, upper_seismogenic_depth=usd,
                     lower_seismogenic_depth=lsd, dip=dip, spacing=spacing))
        elif self.uncertainty_type == 'complexFaultGeometryAbsolute':
            edges, spacing = value
            source.modify('set_geometry', dict(edges=edges, spacing=spacing))
        elif self.uncertainty_type == 'characteristicFaultGeometryAbsolute':
            source.modify('set_geometry', dict(surface=value))
263757
def _parse_input_loc(block, profile, **kwargs):
    """"""
    layer, wave_field = parse_fixed_width(2 * [(5, int)], block)

    return profile.location(
        motion.WaveField[wave_field],
        index=(layer - 1), )
1056330
def check_geophysical_vars_fill_value(self, ds):
        '''
        
        '''
        results = []
        for geo_var in get_geophysical_variables(ds):
            results.append(
                self._has_var_attr(ds, geo_var, '_FillValue', '_FillValue', BaseCheck.MEDIUM),
            )
        return results