Return the total head loss from major and minor losses in a pipe.

    This equation applies to both laminar and turbulent flows.
435648
def headloss(FlowRate, Diam, Length, Nu, PipeRough, KMinor):
    
    #Inputs do not need to be checked here because they are checked by
    #functions this function calls.
    return (headloss_fric(FlowRate, Diam, Length, Nu, PipeRough).magnitude
            + headloss_exp(FlowRate, Diam, KMinor).magnitude)
1026146
def diam_pipeminor(FlowRate, HeadLossExpans, KMinor):
    
    #Checking input validity
    ut.check_range([FlowRate, ">0", "Flow rate"], [KMinor, ">=0", "K minor"],
                   [HeadLossExpans, ">0", "Headloss due to expansion"])
    return (np.sqrt(4 * FlowRate / np.pi)
            * (KMinor / (2 * gravity.magnitude * HeadLossExpans)) ** (1/4)
            )
180227
def headloss_weir(FlowRate, Width):
    """"""
    #Checking input validity
    ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"])
    return (((3/2) * FlowRate
             / (con.VC_ORIFICE_RATIO * np.sqrt(2 * gravity.magnitude) * Width)
             ) ** (2/3))
884310
def _twofilter_smoothing_ON(self, t, ti, info, phi, lwinfo, return_ess,
                               modif_forward, modif_info):
        
        if modif_info is not None:
            lwinfo += modif_info
        Winfo = rs.exp_and_normalise(lwinfo)
        I = rs.multinomial(Winfo)
        if modif_forward is not None:
            lw = self.wgt[t].lw + modif_forward
            W = rs.exp_and_normalise(lw)
        else:
            W = self.wgt[t].W
        J = rs.multinomial(W)
        log_omega = self.model.logpt(t + 1, self.X[t][J], info.hist.X[ti][I])
        if modif_forward is not None:
            log_omega -= modif_forward[J]
        if modif_info is not None:
            log_omega -= modif_info[I]
        Om = rs.exp_and_normalise(log_omega)
        est = np.average(phi(self.X[t][J], info.hist.X[ti][I]), axis=0,
                         weights=Om)
        if return_ess:
            return (est, 1. / np.sum(Om**2))
        else:
            return est
879965
def average_sharded_losses(sharded_losses):
  
  losses = {}
  for loss_name in sorted(sharded_losses[0]):
    all_shards = [shard_losses[loss_name] for shard_losses in sharded_losses]
    if isinstance(all_shards[0], tuple):
      sharded_num, sharded_den = zip(*all_shards)
      mean_loss = (
          tf.add_n(sharded_num) / tf.maximum(
              tf.cast(1.0, sharded_den[0].dtype), tf.add_n(sharded_den)))
    else:
      mean_loss = tf.reduce_mean(all_shards)

    losses[loss_name] = mean_loss
  return losses
967165
def drain_K(self):
        
        drain_K = minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_EXIT_K_MINOR
        return drain_K
89595
def get_monitor_value(self):
        ""
        if self.monitor=='trn_loss' and len(self.learn.recorder.losses) == 0: return None
        elif len(self.learn.recorder.val_losses) == 0: return None
        values = {'train_loss':self.learn.recorder.losses[-1].cpu().numpy(),
                  'valid_loss':self.learn.recorder.val_losses[-1]}
        if values['valid_loss'] is None: return
        if self.learn.recorder.metrics:
            for m, n in zip(self.learn.recorder.metrics[-1],self.learn.recorder.names[3:-1]):
                values[n] = m
        if values.get(self.monitor) is None:
            warn(f'{self.__class__} conditioned on metric `{self.monitor}` which is not available. Available metrics are: {", ".join(map(str, self.learn.recorder.names[1:-1]))}')
        return values.get(self.monitor)
1298373
def deductible(self, loss_type, dummy=None):
        
        val = self.calc(loss_type, self.deductibles, self.area, self.number)
        if self.calc.deduct_abs:  # convert to relative value
            return val / self.calc(loss_type, self.values,
                                   self.area, self.number)
        else:
            return val
666712
def prob(self, pw):
        
        return float(self._T.get(pw, 0)) / self._T[TOTALF_W]
1289027
def max_linear_flow(Diam, HeadlossCDC, Ratio_Error, KMinor):
    
    flow = (pc.area_circle(Diam)).magnitude * np.sqrt((2 * Ratio_Error * HeadlossCDC * pc.gravity)/ KMinor)
    return flow.magnitude
742045
def headloss_fric_general(Area, PerimWetted, Vel, Length, Nu, PipeRough):
    
    #Checking input validity - inputs not checked here are checked by
    #functions this function calls.
    ut.check_range([Length, ">0", "Length"])
    return (fric_general(Area, PerimWetted, Vel, Nu, PipeRough) * Length
            / (4 * radius_hydraulic_general(Area, PerimWetted).magnitude)
            * Vel**2 / (2*gravity.magnitude)
            )
696295
def mean_velocity(self, tol=0.05, Lx=None):
        '''
        
        '''
        dx = None
        dt = None
        p = None
        ind = None
        t_end = None

        if self.area == 0:
            return dict(dx=dx, dt=dt, p=p, ind=ind, t_end=t_end)

        x = self.x_position(Lx=Lx)

        # find the first and last valid indices
        ind_start = mlab.find(x.mask==False)[0]
        ind_last = mlab.find(x.mask==False)[-1]

        # if the original x value is within tol % of the final x value, include
        # all samples
        if x[ind_start] > (1 - tol) * x[ind_last] or x[ind_last] < 0:
            ind_stop = ind_last
        else: # otherwise, stop when x reaches (1 - tol) % of it's final value
            ind_stop = mlab.find(x > (1 - tol) * x[ind_last])[0]

        ind = [ind_start, ind_stop]

        # if we have at least 2 valid samples
        if len(ind) >=2:
            dx = np.diff(x[ind])[0]
            dt = np.diff(self.time[ind])[0] # ms

            # suppress polyfit warnings
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                # fit a line to the data
                p = np.polyfit(self.time[ind[0]:ind[1]], x[ind[0]:ind[1]], 1)

            # find time when the the line intercepts x[ind_last]
            ind_stop = mlab.find(self.time > \
                                 (x[ind_last] - p[1]) / p[0])
            if len(ind_stop):
                t_end = self.time[ind_stop[0]]
            else:
                t_end = self.time[-1]
        return dict(dx=dx, dt=dt, p=p, ind=ind, t_end=t_end)
877992
def area_pipe_min(self):
        """"""
        return (self.safety_factor * self.q / self.vel_critical).to(u.cm**2)
1257413
def _l_cv_and_skew(self, catchment):
        
        z = self._dimensionless_flows(catchment)
        l1, l2, t3 = lm.lmom_ratios(z, nmom=3)
        return l2 / l1, t3
795437
def add_loss(self, loss, name=None):
    """"""
    self.bookkeeper.add_loss(loss, name=name)
    return Loss(self.bookkeeper, tensor=loss, name=name)
103158
def solve(self, lam):
        ''''''
        s = weighted_graphtf_poisson(self.nnodes, self.obs, lam,
                                 self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz,
                                 self.Dk.row.astype('int32'), self.Dk.col.astype('int32'), self.Dk.data.astype('double'),
                                 self.maxsteps, self.converge,
                                 self.beta, self.u)
        self.steps.append(s)
        return self.beta
77901
def W_min_HS_ratio(self):
        
        return ((self.HS_RATIO_MIN * self.Q / self.downstream_H) *
               (self.BAFFLE_K /
                (2 * self.downstream_H * pc.viscosity_kinematic(self.temp) * self.vel_grad_avg ** 2)) ** (1/3)
               ).to(u.cm)