Calculate losses per line with PF result data
    
    Parameters
    ----------
    network : :class:`pypsa.Network
        Overall container of PyPSA
    s0 : series
        apparent power of line
    i0 : series
        current of line
    -------
421623
def calc_line_losses(network):
    

    # Line losses
    # calculate apparent power S = sqrt(p² + q²) [in MW]
    s0_lines = ((network.lines_t.p0**2 + network.lines_t.q0**2).
                apply(np.sqrt))
    # calculate current I = S / U [in A]
    i0_lines = np.multiply(s0_lines, 1000000) / \
        np.multiply(network.lines.v_nom, 1000)
    # calculate losses per line and timestep network.\
    # lines_t.line_losses = I² * R [in MW]
    network.lines_t.losses = np.divide(i0_lines**2 * network.lines.r, 1000000)
    # calculate total losses per line [in MW]
    network.lines = network.lines.assign(
        losses=np.sum(network.lines_t.losses).values)

    # Transformer losses
    # https://books.google.de/books?id=0glcCgAAQBAJ&pg=PA151&lpg=PA151&dq=
    # wirkungsgrad+transformator+1000+mva&source=bl&ots=a6TKhNfwrJ&sig=
    # r2HCpHczRRqdgzX_JDdlJo4hj-k&hl=de&sa=X&ved=
    # 0ahUKEwib5JTFs6fWAhVJY1AKHa1cAeAQ6AEIXjAI#v=onepage&q=
    # wirkungsgrad%20transformator%201000%20mva&f=false
    # Crastan, Elektrische Energieversorgung, p.151
    # trafo 1000 MVA: 99.8 %
    network.transformers = network.transformers.assign(
        losses=np.multiply(network.transformers.s_nom, (1 - 0.998)).values)

    # calculate total losses (possibly enhance with adding these values
    # to network container)
    losses_total = sum(network.lines.losses) + sum(network.transformers.losses)
    print("Total lines losses for all snapshots [MW]:", round(losses_total, 2))
    losses_costs = losses_total * np.average(network.buses_t.marginal_price)
    print("Total costs for these losses [EUR]:", round(losses_costs, 2))

    return
1100694
def cublasStpsv(handle, uplo, trans, diag, n, AP, x, incx):
    
    
    status = _libcublas.cublasStpsv_v2(handle, 
                                       _CUBLAS_FILL_MODE[uplo], 
                                       _CUBLAS_OP[trans], 
                                       _CUBLAS_DIAG[diag], 
                                       n, int(AP), int(x), incx)
    cublasCheckStatus(status)
677674
def calculate_Y(sub_network,skip_pre=False):
    """"""

    if not skip_pre:
        calculate_dependent_values(sub_network.network)

    if sub_network.network.sub_networks.at[sub_network.name,"carrier"] != "AC":
        logger.warning("Non-AC networks not supported for Y!")
        return

    branches = sub_network.branches()
    buses_o = sub_network.buses_o

    network = sub_network.network

    #following leans heavily on pypower.makeYbus
    #Copyright Richard Lincoln, Ray Zimmerman, BSD-style licence

    num_branches = len(branches)
    num_buses = len(buses_o)

    y_se = 1/(branches["r_pu"] + 1.j*branches["x_pu"])

    y_sh = branches["g_pu"]+ 1.j*branches["b_pu"]

    tau = branches["tap_ratio"].fillna(1.)

    #catch some transformers falsely set with tau = 0 by pypower
    tau[tau==0] = 1.

    #define the HV tap ratios
    tau_hv = pd.Series(1.,branches.index)
    tau_hv[branches.tap_side==0] = tau[branches.tap_side==0]

    #define the LV tap ratios
    tau_lv = pd.Series(1.,branches.index)
    tau_lv[branches.tap_side==1] = tau[branches.tap_side==1]


    phase_shift = np.exp(1.j*branches["phase_shift"].fillna(0.)*np.pi/180.)

    #build the admittance matrix elements for each branch
    Y11 = (y_se + 0.5*y_sh)/tau_lv**2
    Y10 = -y_se/tau_lv/tau_hv/phase_shift
    Y01 = -y_se/tau_lv/tau_hv/np.conj(phase_shift)
    Y00 = (y_se + 0.5*y_sh)/tau_hv**2

    #bus shunt impedances
    b_sh = network.shunt_impedances.b_pu.groupby(network.shunt_impedances.bus).sum().reindex(buses_o, fill_value = 0.)
    g_sh = network.shunt_impedances.g_pu.groupby(network.shunt_impedances.bus).sum().reindex(buses_o, fill_value = 0.)
    Y_sh = g_sh + 1.j*b_sh

    #get bus indices
    bus0 = buses_o.get_indexer(branches.bus0)
    bus1 = buses_o.get_indexer(branches.bus1)

    #connection matrices
    C0 = csr_matrix((ones(num_branches), (np.arange(num_branches), bus0)), (num_branches, num_buses))
    C1 = csr_matrix((ones(num_branches), (np.arange(num_branches), bus1)), (num_branches, num_buses))

    #build Y{0,1} such that Y{0,1} * V is the vector complex branch currents

    i = r_[np.arange(num_branches), np.arange(num_branches)]
    sub_network.Y0 = csr_matrix((r_[Y00,Y01],(i,r_[bus0,bus1])), (num_branches,num_buses))
    sub_network.Y1 = csr_matrix((r_[Y10,Y11],(i,r_[bus0,bus1])), (num_branches,num_buses))

    #now build bus admittance matrix
    sub_network.Y = C0.T * sub_network.Y0 + C1.T * sub_network.Y1 + \
       csr_matrix((Y_sh, (np.arange(num_buses), np.arange(num_buses))))
339026
def get_linedata(self, sort_names=False):
        
        if not self.pflow.solved:
            logger.error('Power flow not solved when getting line data.')
            return tuple([False] * 7)
        idx = self.Line.idx
        fr = self.Line.bus1
        to = self.Line.bus2

        Sloss = self.Line.S1 + self.Line.S2

        Pfr = list(self.Line.S1.real())
        Qfr = list(self.Line.S1.imag())
        Pto = list(self.Line.S2.real())
        Qto = list(self.Line.S2.imag())

        Ploss = list(Sloss.real())
        Qloss = list(Sloss.imag())

        if sort_names:
            ret = (list(x) for x in zip(*sorted(
                zip(idx, fr, to, Pfr, Qfr, Pto, Qto, Ploss, Qloss),
                key=itemgetter(0))))
        else:
            ret = idx, fr, to, Pfr, Qfr, Pto, Qto, Ploss, Qloss

        return ret
486232
def packet_loss(self):
        ''''''
        if self.mav_count == 0:
            return 0
        return (100.0*self.mav_loss)/(self.mav_count+self.mav_loss)
164215
def apply_transformer_t_model(network):
    """"""

    z_series = network.transformers.r_pu + 1j*network.transformers.x_pu
    y_shunt = network.transformers.g_pu + 1j*network.transformers.b_pu

    ts_b = (network.transformers.model == "t") & (y_shunt != 0.)

    if ts_b.zsum() == 0:
        return

    za,zb,zc = wye_to_delta(z_series.loc[ts_b]/2,z_series.loc[ts_b]/2,1/y_shunt.loc[ts_b])

    network.transformers.loc[ts_b,"r_pu"] = zc.real
    network.transformers.loc[ts_b,"x_pu"] = zc.imag
    network.transformers.loc[ts_b,"g_pu"] = (2/za).real
    network.transformers.loc[ts_b,"b_pu"] = (2/za).imag
673475
def get_loss(config: LossConfig) -> 'Loss':
    
    if config.name == C.CROSS_ENTROPY:
        return CrossEntropyLoss(config,
                                output_names=[C.SOFTMAX_OUTPUT_NAME],
                                label_names=[C.TARGET_LABEL_NAME])
    else:
        raise ValueError("unknown loss name: %s" % config.name)
250924
def build_loss_maps(self, losses, clp, stats=()):
        
        array = numpy.zeros((len(clp), len(losses)), F32)
        for r, ls in enumerate(losses):
            if len(ls) < 2:
                continue
            for c, poe in enumerate(clp):
                array[c, r] = conditional_loss_ratio(ls, self.poes, poe)
        return self.pair(array, stats)
1057483
def calc_PnPs(counts):
    
    if counts['pos non-syn'] == 0 or counts['pos syn'] == 0:
        return 'n/a'
    NonSyn = float(counts['obs non-syn'])/float(counts['pos non-syn'])
    Syn    = float(counts['obs syn'])    /float(counts['pos syn'])
    if Syn == 0:
        return 'n/a'
    return NonSyn/Syn
982672
def inspectSpatialPoolerStats(sp, inputVectors, saveFigPrefix=None):
  
  numInputVector, inputSize = inputVectors.shape
  numColumns = np.prod(sp.getColumnDimensions())

  outputColumns = np.zeros((numInputVector, numColumns), dtype=uintType)
  inputOverlap = np.zeros((numInputVector, numColumns), dtype=uintType)

  connectedCounts = np.zeros((numColumns, ), dtype=uintType)
  sp.getConnectedCounts(connectedCounts)

  winnerInputOverlap = np.zeros(numInputVector)
  for i in range(numInputVector):
    sp.compute(inputVectors[i][:], False, outputColumns[i][:])
    inputOverlap[i][:] = sp.getOverlaps()
    activeColumns = np.where(outputColumns[i][:] > 0)[0]
    if len(activeColumns) > 0:
      winnerInputOverlap[i] = np.mean(
        inputOverlap[i][np.where(outputColumns[i][:] > 0)[0]])
  avgInputOverlap = np.mean(inputOverlap, 0)

  entropy = calculateEntropy(outputColumns)
  activationProb = np.mean(outputColumns.astype(realDType), 0)

  dutyCycleDist, binEdge = np.histogram(activationProb,
                                        bins=10, range=[-0.005, 0.095])
  dutyCycleDist = dutyCycleDist.astype('float32') / np.sum(dutyCycleDist)
  binCenter = (binEdge[1:] + binEdge[:-1])/2

  fig, axs = plt.subplots(2, 2)
  axs[0, 0].hist(connectedCounts)
  axs[0, 0].set_xlabel('# Connected Synapse')

  axs[0, 1].hist(winnerInputOverlap)
  axs[0, 1].set_xlabel('# winner input overlap')

  axs[1, 0].bar(binEdge[:-1]+0.001, dutyCycleDist, width=.008)
  axs[1, 0].set_xlim([-0.005, .1])
  axs[1, 0].set_xlabel('Activation Frequency')
  axs[1, 0].set_title('Entropy: {}'.format(entropy))

  axs[1, 1].plot(connectedCounts, activationProb, '.')
  axs[1, 1].set_xlabel('connection #')
  axs[1, 1].set_ylabel('activation freq')
  plt.tight_layout()

  if saveFigPrefix is not None:
    plt.savefig('figures/{}_network_stats.pdf'.format(saveFigPrefix))
  return fig
700007
def __sum(self, line):
        
        splitted_line = line.split()
        try:
            ret = sum(map(int, splitted_line[1:(self.cpu_number + 1)]))
        except ValueError:
            # Correct issue #1007 on some conf (Raspberry Pi with Raspbian)
            ret = 0
        return ret
121221
def get_loss(self, pred: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol:
        
        labels = mx.sym.reshape(labels, shape=(-1, 1))
        loss_value = self.loss_config.length_task_weight / 2 * mx.sym.square(pred - labels)
        loss_value = mx.sym.MakeLoss(data=loss_value,
                                     normalization='batch',
                                     name=self.name)
        return loss_value
1003200
def assign_bus_results(grid, bus_data):
    

    # iterate of nodes and assign voltage obtained from power flow analysis
    for node in grid._graph.nodes():
        # check if node is connected to graph
        if (node not in grid.graph_isolated_nodes()
            and not isinstance(node,
                               LVLoadAreaCentreDing0)):
            if isinstance(node, LVStationDing0):
                node.voltage_res = bus_data.loc[node.pypsa_id, 'v_mag_pu']
            elif isinstance(node, (LVStationDing0, LVLoadAreaCentreDing0)):
                if node.lv_load_area.is_aggregated:
                    node.voltage_res = bus_data.loc[node.pypsa_id, 'v_mag_pu']
            elif not isinstance(node, CircuitBreakerDing0):
                node.voltage_res = bus_data.loc[node.pypsa_id, 'v_mag_pu']
            else:
                logger.warning("Object {} has been skipped while importing "
                               "results!")
1186925
def loss_dt_list(self, dtype=F32):
        
        loss_types = self.all_cost_types
        dts = [(str(lt), dtype) for lt in loss_types]
        return dts
897625
def ppo_loss(policy_net_apply,
             new_policy_params,
             old_policy_params,
             value_net_apply,
             value_net_params,
             padded_observations,
             padded_actions,
             padded_rewards,
             reward_mask,
             gamma=0.99,
             lambda_=0.95,
             epsilon=0.2):
  """"""
  B, T = padded_rewards.shape  # pylint: disable=invalid-name
  assert (B, T + 1) == padded_observations.shape[:2]
  assert (B, T) == padded_actions.shape
  assert (B, T) == padded_rewards.shape
  assert (B, T) == reward_mask.shape

  # Compute predicted values and predicted log-probs and hand it over to
  # `ppo_loss_given_predictions`.

  # (B, T+1, 1)
  predicted_values = value_net_apply(padded_observations, value_net_params)
  assert (B, T + 1, 1) == predicted_values.shape

  # log_probab_actions_{old,new} are both (B, T+1, A)
  log_probab_actions_old = policy_net_apply(padded_observations,
                                            old_policy_params)
  log_probab_actions_new = policy_net_apply(padded_observations,
                                            new_policy_params)
  assert (B, T + 1) == log_probab_actions_old.shape[:2]
  assert (B, T + 1) == log_probab_actions_new.shape[:2]
  assert log_probab_actions_old.shape[-1] == log_probab_actions_new.shape[-1]

  return ppo_loss_given_predictions(log_probab_actions_new,
                                    log_probab_actions_old,
                                    predicted_values,
                                    padded_actions,
                                    padded_rewards,
                                    reward_mask,
                                    gamma=gamma,
                                    lambda_=lambda_,
                                    epsilon=epsilon)
765632
def build(self, losses_by_event, stats=()):
        
        P, R = len(self.return_periods), len(self.weights)
        L = len(self.loss_dt.names)
        array = numpy.zeros((P, R, L), F32)
        for r in losses_by_event:
            num_events = self.num_events[r]
            losses = losses_by_event[r]
            for l, lt in enumerate(self.loss_dt.names):
                ls = losses[:, l].flatten()  # flatten only in ucerf
                # NB: do not use squeeze or the gmf_ebrisk tests will break
                lbp = losses_by_period(
                    ls, self.return_periods, num_events, self.eff_time)
                array[:, r, l] = lbp
        return self.pair(array, stats)
187202
def infer_batch(self, dataloader):
        
        sum_losses = 0
        len_losses = 0
        for input_data, input_label in dataloader:
            data = gluon.utils.split_and_load(input_data, self.ctx, even_split=False)
            label = gluon.utils.split_and_load(input_label, self.ctx, even_split=False)
            sum_losses, len_losses = self.infer(data, label)
            sum_losses += sum_losses
            len_losses += len_losses

        return sum_losses, len_losses