Post power flow computation of series device flow
502373
def _compile_seriesflow(self):
        """"""
        string = '"""\n'
        for device, pflow, series in zip(self.devices, self.pflow,
                                         self.series):
            if pflow and series:
                string += 'system.' + device + '.seriesflow(system.dae)\n'
        string += '\n'
        string += '"""'
        self.seriesflow = compile(eval(string), '', 'exec')
601528
def post_process_data(self, voltage=None, incremental_capacity=None,
                          voltage_step=None):
        """"""

        logging.debug("post-processing data")

        if voltage is None:
            voltage = self.voltage_processed
            incremental_capacity = self.incremental_capacity
            voltage_step = self.voltage_inverted_step

        if self.post_smoothing:
            logging.debug(" - post smoothing (gaussian)")
            logging.debug(f"    * using voltage fwhm: {self.voltage_fwhm}")
            points_fwhm = int(self.voltage_fwhm / voltage_step)

            sigma = np.amax([1, points_fwhm / 2])

            self.incremental_capacity = gaussian_filter1d(
                incremental_capacity, sigma=sigma, order=self.gaussian_order,
                mode=self.gaussian_mode,
                cval=self.gaussian_cval,
                truncate=self.gaussian_truncate
            )

        if self.normalize:
            logging.debug(" - normalizing")
            area = simps(incremental_capacity, voltage)
            self.incremental_capacity = incremental_capacity * self.normalizing_factor / abs(area)

        fixed_range = False
        if isinstance(self.fixed_voltage_range, np.ndarray):
            fixed_range = True
        else:
            if self.fixed_voltage_range:
                fixed_range = True
        if fixed_range:
            logging.debug(" - using fixed voltage range (interpolating)")
            v1, v2, number_of_points = self.fixed_voltage_range
            v = np.linspace(v1, v2, number_of_points)
            f = interp1d(x=self.voltage_processed, y=self.incremental_capacity,
                         kind=self.interpolation_method, bounds_error=False,
                         fill_value=np.NaN)

            self.incremental_capacity = f(v)
            self.voltage_processed = v
579980
def _q_iteration(self, Q, Bpp_solver, Vm, Va, pq):
        
        dVm = -Bpp_solver.solve(Q)

        # Update voltage.
        Vm[pq] = Vm[pq] + dVm
        V = Vm * exp(1j * Va)

        return V, Vm, Va
180217
def power_on(self, si, logger, session, vm_uuid, resource_fullname):
        
        logger.info('retrieving vm by uuid: {0}'.format(vm_uuid))
        vm = self.pv_service.find_by_uuid(si, vm_uuid)

        if vm.summary.runtime.powerState == 'poweredOn':
            logger.info('vm already powered on')
            task_result = 'Already powered on'
        else:
            logger.info('powering on vm')
            task = vm.PowerOn()
            task_result = self.synchronous_task_waiter.wait_for_task(task=task,
                                                                     logger=logger,
                                                                     action_name='Power On')

        return task_result
1096040
def _update_extended(self, system):
        """"""
        if self.system.pflow.solved is False:
            logger.warning(
                'Cannot update extended summary. Power flow not solved.')
            return

        Sloss = sum(system.Line.S1 + system.Line.S2)
        self.extended.update({
            'Ptot':
            sum(system.PV.pmax) + sum(system.SW.pmax),  # + sum(system.SW.pmax)
            'Pon':
            sum(mul(system.PV.u, system.PV.pmax)),
            'Pg':
            sum(system.Bus.Pg),
            'Qtot_min':
            sum(system.PV.qmin) + sum(system.SW.qmin),
            'Qtot_max':
            sum(system.PV.qmax) + sum(system.SW.qmax),
            'Qon_min':
            sum(mul(system.PV.u, system.PV.qmin)),
            'Qon_max':
            sum(mul(system.PV.u, system.PV.qmax)),
            'Qg':
            round(sum(system.Bus.Qg), 5),
            'Pl':
            round(sum(system.PQ.p), 5),
            'Ql':
            round(sum(system.PQ.q), 5),
            'Psh':
            0.0,
            'Qsh':
            round(sum(system.PQ.q) - sum(system.Bus.Ql), 5),
            'Ploss':
            round(Sloss.real, 5),
            'Qloss':
            round(Sloss.imag, 5),
            'Pch':
            round(sum(system.Line.Pchg1 + system.Line.Pchg2), 5),
            'Qch':
            round(sum(system.Line.Qchg1 + system.Line.Qchg2), 5),
        })
1131370
def init(self):
        
        system = self.system
        config = self.config
        dae = self.system.dae
        if system.pflow.solved is False:
            return

        t, s = elapsed()

        # Assign indices for post-powerflow device variables
        system.xy_addr1()

        # Assign variable names for bus injections and line flows if enabled
        system.varname.resize_for_flows()
        system.varname.bus_line_names()

        # Reshape dae to retain power flow solutions
        system.dae.init1()

        # Initialize post-powerflow device variables
        for device, init1 in zip(system.devman.devices, system.call.init1):
            if init1:
                system.__dict__[device].init1(system.dae)

        # compute line and area flow
        if config.compute_flows:
            dae.init_fg()
            self.compute_flows()  # TODO: move to PowerSystem

        t, s = elapsed(t)

        if system.dae.n:
            logger.debug('Dynamic models initialized in {:s}.'.format(s))
        else:
            logger.debug('No dynamic model loaded.')

        # system.dae flags initialize
        system.dae.factorize = True
        system.dae.mu = 1.0
        system.dae.kg = 0.0
1104739
def getChargingVoltage(self):
    """"""
    command = '$GG'
    currentAndVoltage = self.sendCommand(command)
    volts = float(currentAndVoltage[2])/1000
    return volts
1346022
def f_ac_power(inverter, v_mp, p_mp):
    
    return pvlib.pvsystem.snlinverter(v_mp, p_mp, inverter).flatten()
577455
def calculate_B_H(sub_network,skip_pre=False):
    """"""

    network = sub_network.network

    if not skip_pre:
        calculate_dependent_values(network)
        find_bus_controls(sub_network)

    if network.sub_networks.at[sub_network.name,"carrier"] == "DC":
        attribute="r_pu_eff"
    else:
        attribute="x_pu_eff"

    #following leans heavily on pypower.makeBdc

    #susceptances
    b = 1./np.concatenate([(c.df.loc[c.ind, attribute]).values \
                           for c in sub_network.iterate_components(network.passive_branch_components)])


    if np.isnan(b).any():
        logger.warning("Warning! Some series impedances are zero - this will cause a singularity in LPF!")
    b_diag = csr_matrix((b, (r_[:len(b)], r_[:len(b)])))

    #incidence matrix
    sub_network.K = sub_network.incidence_matrix(busorder=sub_network.buses_o)

    sub_network.H = b_diag*sub_network.K.T

    #weighted Laplacian
    sub_network.B = sub_network.K * sub_network.H


    sub_network.p_branch_shift = -b*np.concatenate([(c.df.loc[c.ind, "phase_shift"]).values*np.pi/180. if c.name == "Transformer"
                                                    else np.zeros((len(c.ind),))
                                                    for c in sub_network.iterate_components(network.passive_branch_components)])

    sub_network.p_bus_shift = sub_network.K * sub_network.p_branch_shift
1218098
def cublasDtpsv(handle, uplo, trans, diag, n, AP, x, incx):
    

    status = _libcublas.cublasDtpsv_v2(handle, 
                                       _CUBLAS_FILL_MODE[uplo], 
                                       _CUBLAS_OP[trans], 
                                       _CUBLAS_DIAG[diag], 
                                       n, int(AP), int(x), incx)
    cublasCheckStatus(status)
227301
def merged_series(cls, *series, **kwargs):
        ''''''
        router, backend = cls.check_router(None, *series)
        if backend:
            target = router.register(cls(), backend)
            router.session().add(target)
            target._merge(*series, **kwargs)
            backend = target.backend
            return backend.execute(
                backend.structure(target).irange_and_delete(),
                target.load_data)
1028987
def _branch_flow_dc(self, branches, Bf, Pfinj, base_mva):
        
        # Indexes of constrained lines.
        il = array([i for i,l in enumerate(branches) if 0.0 < l.rate_a < 1e10])
        lpf = -Inf * ones(len(il))
        rate_a = array([l.rate_a / base_mva for l in branches])
        upf = rate_a[il] - Pfinj[il]
        upt = rate_a[il] + Pfinj[il]

        Pf = LinearConstraint("Pf",  Bf[il, :], lpf, upf, ["Va"])
        Pt = LinearConstraint("Pt", -Bf[il, :], lpf, upt, ["Va"])

        return Pf, Pt
793273
def pf_solution(self, Ybus, Yf, Yt, V):
        
        buses = self.connected_buses
        branches = self.online_branches
        generators = self.online_generators

        self.reset()
        self.index_buses()
        self.index_branches()

        Va = angle(V)
        Vm = abs(V)
        for i, b in enumerate(buses):
            b.v_angle = Va[i] * 180.0 / pi
            b.v_magnitude = Vm[i]

        # Update Qg for all gens and Pg for swing bus.
#        gbus = [g.bus._i for g in generators]
        refgen = [i for i, g in enumerate(generators)
                  if g.bus.type == REFERENCE]

        # Compute total injected bus powers.
#        Sg = V[gbus] * conj(Ybus[gbus, :] * V)
        Sg = V * conj(Ybus * V)


        # Update Qg for all generators.
#        for i in gbus:
#            g = generators[i]
        for g in generators:
            # inj Q + local Qd
            g.q = Sg.imag[g.bus._i] * self.base_mva + g.bus.q_demand

        # At this point any buses with more than one generator will have
        # the total Q dispatch for the bus assigned to each generator. This
        # must be split between them. We do it first equally, then in proportion
        # to the reactive range of the generator.
        if generators:
            pass

        # Update Pg for swing bus.
        for i in refgen:
            g = generators[i]
            # inj P + local Pd
            g.p = Sg.real[i] * self.base_mva + g.bus.p_demand

        # More than one generator at the ref bus subtract off what is generated
        # by other gens at this bus.
        if len(refgen) > 1:
            pass

        br = [l._i for l in branches]
        f_idx = [l.from_bus._i for l in branches]
        t_idx = [l.to_bus._i for l in branches]

        Sf = V[f_idx] * conj(Yf[br, :] * V) * self.base_mva
        St = V[t_idx] * conj(Yt[br, :] * V) * self.base_mva

        # Complex power at "from" bus.
        for i, l in enumerate(branches):
            l.p_from = Sf[i].real
            l.q_from = Sf[i].imag
            l.p_to = St[i].real
            l.q_to = St[i].imag
304444
def set_power(self, sid, state):
    """"""
    sid_mask = 0x01 << (sid - 1)
    return self.set_power_mask(sid_mask, state)
1313700
private static Circuit getCircuitGroups(String group, Collection<String> neighborGroups)
    {
        final Collection<String> set = new HashSet<>(neighborGroups);
        final Circuit circuit;
        if (set.size() > 1)
        {
            final Iterator<String> iterator = set.iterator();
            final String groupIn = iterator.next();
            final String groupOut = iterator.next();
            final CircuitType type = getCircuitType(group, neighborGroups);

            if (groupIn.equals(group))
            {
                circuit = new Circuit(type, group, groupOut);
            }
            else
            {
                circuit = new Circuit(type, group, groupIn);
            }
        }
        else
        {
            circuit = null;
        }
        return circuit;
    }
1161594
private static int computeCapacity(final int expectedSize) {
        if (expectedSize == 0) {
            return 1;
        }
        final int capacity   = (int) InternalFastMath.ceil(expectedSize / LOAD_FACTOR);
        final int powerOfTwo = Integer.highestOneBit(capacity);
        if (powerOfTwo == capacity) {
            return capacity;
        }
        return nextPowerOfTwo(capacity);
    }
543473
def get_consumption(self, deviceid, timerange="10"):
        
        tranges = ("10", "24h", "month", "year")
        if timerange not in tranges:
            raise ValueError(
                "Unknown timerange. Possible values are: {0}".format(tranges)
            )

        url = self.base_url + "/net/home_auto_query.lua"
        response = self.session.get(url, params={
            'sid': self.sid,
            'command': 'EnergyStats_{0}'.format(timerange),
            'id': deviceid,
            'xhr': 0,
        }, timeout=15)
        response.raise_for_status()

        data = response.json()
        result = {}

        # Single result values
        values_map = {
            'MM_Value_Amp': 'mm_value_amp',
            'MM_Value_Power': 'mm_value_power',
            'MM_Value_Volt': 'mm_value_volt',

            'EnStats_average_value': 'enstats_average_value',
            'EnStats_max_value': 'enstats_max_value',
            'EnStats_min_value': 'enstats_min_value',
            'EnStats_timer_type': 'enstats_timer_type',

            'sum_Day': 'sum_day',
            'sum_Month': 'sum_month',
            'sum_Year': 'sum_year',
        }
        for avm_key, py_key in values_map.items():
            result[py_key] = int(data[avm_key])

        # Stats counts
        count = int(data["EnStats_count"])
        watt_values = [None for i in range(count)]
        volt_values = [None for i in range(count)]
        for i in range(1, count + 1):
            watt_values[i - 1] = int(data["EnStats_watt_value_{}".format(i)])
            volt_values[i - 1] = int(data["EnStats_volt_value_{}".format(i)])

        result['watt_values'] = watt_values
        result['volt_values'] = volt_values

        return result