INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Gets a list of all ports on OVS instance. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl list-ports <bridge>
def get_port_name_list(self): """ Gets a list of all ports on OVS instance. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl list-ports <bridge> """ command = ovs_vsctl.VSCtlCommand('list-ports', (self.br_name, )) self.run_comman...
Creates a bonded port. :param name: Port name to be created :param ifaces: List of interfaces containing at least 2 interfaces :param bond_mode: Bonding mode (active-backup, balance-tcp or balance-slb) :param lacp: LACP mode (active, passive or off)
def add_bond(self, name, ifaces, bond_mode=None, lacp=None): """ Creates a bonded port. :param name: Port name to be created :param ifaces: List of interfaces containing at least 2 interfaces :param bond_mode: Bonding mode (active-backup, balance-tcp or...
Creates a tunnel port. :param name: Port name to be created :param tunnel_type: Type of tunnel (gre or vxlan) :param remote_ip: Remote IP address of tunnel :param local_ip: Local IP address of tunnel :param key: Key of GRE or VNI of VxLAN :param ofport: Requested OpenFlo...
def add_tunnel_port(self, name, tunnel_type, remote_ip, local_ip=None, key=None, ofport=None): """ Creates a tunnel port. :param name: Port name to be created :param tunnel_type: Type of tunnel (gre or vxlan) :param remote_ip: Remote IP address of tunnel ...
Creates a GRE tunnel port. See the description of ``add_tunnel_port()``.
def add_gre_port(self, name, remote_ip, local_ip=None, key=None, ofport=None): """ Creates a GRE tunnel port. See the description of ``add_tunnel_port()``. """ self.add_tunnel_port(name, 'gre', remote_ip, local_ip=local_ip, key=k...
Creates a VxLAN tunnel port. See the description of ``add_tunnel_port()``.
def add_vxlan_port(self, name, remote_ip, local_ip=None, key=None, ofport=None): """ Creates a VxLAN tunnel port. See the description of ``add_tunnel_port()``. """ self.add_tunnel_port(name, 'vxlan', remote_ip, local_ip=local_i...
Deletes a port on OVS instance. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl del-port <bridge> <port>
def del_port(self, port_name): """ Deletes a port on OVS instance. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl del-port <bridge> <port> """ command = ovs_vsctl.VSCtlCommand('del-port', (self.br_name, port_name)) self.run_com...
Sets a Qos rule and creates Queues on the given port.
def set_qos(self, port_name, type='linux-htb', max_rate=None, queues=None): """ Sets a Qos rule and creates Queues on the given port. """ queues = queues if queues else [] command_qos = ovs_vsctl.VSCtlCommand( 'set-qos', [port_name, type, max_rate]) ...
Deletes the Qos rule on the given port.
def del_qos(self, port_name): """ Deletes the Qos rule on the given port. """ command = ovs_vsctl.VSCtlCommand( 'del-qos', [port_name]) self.run_command([command])
calculate checksum of IP pseudo header IPv4 pseudo header UDP RFC768 TCP RFC793 3.1 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | source address | +--------+--------+--------+--------+ | destination address | +--------...
def checksum_ip(ipvx, length, payload): """ calculate checksum of IP pseudo header IPv4 pseudo header UDP RFC768 TCP RFC793 3.1 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | source address | +--------+--------+--------+--------+ ...
Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0.
def fletcher_checksum(data, offset): """ Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0. """ c0 = 0 c1 = 0 pos = 0 length = len(data) data = bytearray(da...
create an instance. returns EventVRRPConfigReply(instance.name, interface, config) on success. returns EventVRRPConfigReply(None, interface, config) on failure.
def vrrp_config(app, interface, config): """create an instance. returns EventVRRPConfigReply(instance.name, interface, config) on success. returns EventVRRPConfigReply(None, interface, config) on failure. """ config_request = vrrp_event.EventVRRPConfigRequest(interface, config) config_re...
shutdown the instance.
def vrrp_shutdown(app, instance_name): """shutdown the instance. """ shutdown_request = vrrp_event.EventVRRPShutdownRequest(instance_name) app.send_event(vrrp_event.VRRP_MANAGER_NAME, shutdown_request)
transmit a packet from the switch. this is internal use only. data is str-like, a packet to send.
def vrrp_transmit(app, monitor_name, data): """transmit a packet from the switch. this is internal use only. data is str-like, a packet to send. """ transmit_request = vrrp_event.EventVRRPTransmitRequest(data) app.send_event(monitor_name, transmit_request)
list instances. returns EventVRRPListReply([VRRPInstance]).
def vrrp_list(app, instance_name=None): """list instances. returns EventVRRPListReply([VRRPInstance]). """ list_request = vrrp_event.EventVRRPListRequest(instance_name) list_request.dst = vrrp_event.VRRP_MANAGER_NAME return app.send_request(list_request)
change configuration of an instance. None means no change.
def vrrp_config_change(app, instance_name, priority=None, advertisement_interval=None, preempt_mode=None, accept_mode=None): """change configuration of an instance. None means no change. """ config_change = vrrp_event.EventVRRPConfigChangeRequest( in...
Returns an object which is generated from a buffer including the expression of the wire protocol of the flow match.
def parser(cls, buf, offset): """ Returns an object which is generated from a buffer including the expression of the wire protocol of the flow match. """ match = OFPMatch() type_, length = struct.unpack_from('!HH', buf, offset) match.type = type_ match.le...
Outputs the expression of the wire protocol of the flow match into the buf. Returns the output length.
def serialize(self, buf, offset): """ Outputs the expression of the wire protocol of the flow match into the buf. Returns the output length. """ fields = [ofproto.oxm_from_user(k, uv) for (k, uv) in self._fields2] hdr_pack_str = '!HH' fi...
Returns a dict expressing the flow match.
def to_jsondict(self): """ Returns a dict expressing the flow match. """ body = {"oxm_fields": [ofproto.oxm_to_jsondict(k, uv) for k, uv in self._fields2], "length": self.length, "type": self.type} return {self.__clas...
Returns an object which is generated from a dict. Exception raises: KeyError -- Unknown match field is defined in dict
def from_jsondict(cls, dict_): """ Returns an object which is generated from a dict. Exception raises: KeyError -- Unknown match field is defined in dict """ fields = [ofproto.oxm_from_jsondict(f) for f in dict_['oxm_fields']] return OFPMatch(_o...
Returns an object which is generated from a buffer including the expression of the wire protocol of the flow stats.
def parser(cls, buf, offset): """ Returns an object which is generated from a buffer including the expression of the wire protocol of the flow stats. """ stats = OFPStats() reserved, length = struct.unpack_from('!HH', buf, offset) stats.length = length #...
Outputs the expression of the wire protocol of the flow stats into the buf. Returns the output length.
def serialize(self, buf, offset): """ Outputs the expression of the wire protocol of the flow stats into the buf. Returns the output length. """ fields = [ofproto.oxs_from_user(k, uv) for (k, uv) in self.fields] hdr_pack_str = '!HH' fiel...
Returns a dict expressing the flow stats.
def to_jsondict(self): """ Returns a dict expressing the flow stats. """ body = {"oxs_fields": [ofproto.oxs_to_jsondict(k, uv) for k, uv in self.fields], "length": self.length} return {self.__class__.__name__: body}
Returns an object which is generated from a dict. Exception raises: KeyError -- Unknown stats field is defined in dict
def from_jsondict(cls, dict_): """ Returns an object which is generated from a dict. Exception raises: KeyError -- Unknown stats field is defined in dict """ fields = [ofproto.oxs_from_jsondict(f) for f in dict_['oxs_fields']] return OFPStats(_o...
Parse an ovs-ofctl style action string and return a list of jsondict representations of OFPInstructionActions, which can then be passed to ofproto_parser.ofp_instruction_from_jsondict. Please note that this is for making transition from ovs-ofctl easier. Please consider using OFPAction constructors whe...
def ofp_instruction_from_str(ofproto, action_str): """ Parse an ovs-ofctl style action string and return a list of jsondict representations of OFPInstructionActions, which can then be passed to ofproto_parser.ofp_instruction_from_jsondict. Please note that this is for making transition from ovs-ofc...
Tokenize an argument portion of ovs-ofctl style action string.
def tokenize_ofp_instruction_arg(arg): """ Tokenize an argument portion of ovs-ofctl style action string. """ arg_re = re.compile("[^,()]*") try: rest = arg result = [] while len(rest): m = arg_re.match(rest) if m.end(0) == len(rest): r...
Convert an ovs-ofctl style NXM_/OXM_ field name to a ryu match field name.
def nxm_field_name_to_ryu(field): """ Convert an ovs-ofctl style NXM_/OXM_ field name to a ryu match field name. """ if field.endswith("_W"): field = field[:-2] prefix = field[:7] field = field[7:].lower() mapped_result = None if prefix == 'NXM_NX_': mapped_result = ...
Converts Zebra protocol message instance to Zebra protocol service event instance. If corresponding event class is not defined, returns None. :param zclient: Zebra client instance. :param msg: Zebra protocol message. :return: Zebra protocol service event.
def message_to_event(zclient, msg): """ Converts Zebra protocol message instance to Zebra protocol service event instance. If corresponding event class is not defined, returns None. :param zclient: Zebra client instance. :param msg: Zebra protocol message. :return: Zebra protocol service e...
Convert an ovs-ofctl field name to ryu equivalent.
def ofp_ofctl_field_name_to_ryu(field): """Convert an ovs-ofctl field name to ryu equivalent.""" mapped = _OXM_FIELD_OFCTL_ALIASES.get(field) if mapped: return mapped if field.endswith("_dst"): mapped = _OXM_FIELD_OFCTL_ALIASES.get(field[:-3] + "src") if mapped: retur...
Remove all attributes that are used for putting this node on this type of list.
def node_del_attrs(self, node): """Remove all attributes that are used for putting this node on this type of list. """ try: delattr(node, self.next_name) delattr(node, self.prev_name) except AttributeError: pass
Returns True if this node is on *some* list. A node is not on any list if it is linked to itself, or if it does not have the next and/prev attributes at all.
def node_is_on_list(self, node): """Returns True if this node is on *some* list. A node is not on any list if it is linked to itself, or if it does not have the next and/prev attributes at all. """ next = self.node_next(node) if next == node or next is None: ...
Insert the new node after node.
def node_insert_after(self, node, new_node): """Insert the new node after node.""" assert(not self.node_is_on_list(new_node)) assert(node is not new_node) next = self.node_next(node) assert(next is not None) self.node_set_next(node, new_node) self.node_set_prev(...
Insert the new node before node.
def node_insert_before(self, node, new_node): """Insert the new node before node.""" assert(not self.node_is_on_list(new_node)) assert(node is not new_node) prev = self.node_prev(node) assert(prev is not None) self.node_set_prev(node, new_node) self.node_set_nex...
Updates RT filters for each peer. Should be called if a new RT Nlri's have changed based on the setting. Currently only used by `Processor` to update the RT filters after it has processed a RT destination. If RT filter has changed for a peer we call RT filter change handler.
def update_rtfilters(self): """Updates RT filters for each peer. Should be called if a new RT Nlri's have changed based on the setting. Currently only used by `Processor` to update the RT filters after it has processed a RT destination. If RT filter has changed for a peer we cal...
Handles update of peer RT filter. Parameters: - `peer`: (Peer) whose RT filter has changed. - `new_rts`: (set) of new RTs that peer is interested in. - `old_rts`: (set) of RTs that peers is no longer interested in.
def _on_update_rt_filter(self, peer, new_rts, old_rts): """Handles update of peer RT filter. Parameters: - `peer`: (Peer) whose RT filter has changed. - `new_rts`: (set) of new RTs that peer is interested in. - `old_rts`: (set) of RTs that peers is no longer interest...
Returns neighbor's RT filter (permit/allow filter based on RT). Walks RT filter tree and computes current RT filters for each peer that have advertised RT NLRIs. Returns: dict of peer, and `set` of rts that a particular neighbor is interested in.
def _compute_rtfilter_map(self): """Returns neighbor's RT filter (permit/allow filter based on RT). Walks RT filter tree and computes current RT filters for each peer that have advertised RT NLRIs. Returns: dict of peer, and `set` of rts that a particular neighbor is ...
Handler of new connection requests on bgp server port. Checks if new connection request is valid and starts new instance of protocol.
def start_protocol(self, socket): """Handler of new connection requests on bgp server port. Checks if new connection request is valid and starts new instance of protocol. """ assert socket peer_addr, peer_port = self.get_remotename(socket) peer = self._peer_manag...
Decide the port of the side near a root bridge. It is compared by the following priorities. 1. root path cost 2. designated bridge ID value 3. designated port ID value
def compare_root_path(path_cost1, path_cost2, bridge_id1, bridge_id2, port_id1, port_id2): """ Decide the port of the side near a root bridge. It is compared by the following priorities. 1. root path cost 2. designated bridge ID value ...
Check received BPDU is superior to currently held BPDU by the following comparison. - root bridge ID value - root path cost - designated bridge ID value - designated port ID value - times
def compare_bpdu_info(my_priority, my_times, rcv_priority, rcv_times): """ Check received BPDU is superior to currently held BPDU by the following comparison. - root bridge ID value - root path cost - designated bridge ID value - designated port I...
DESIGNATED_PORT/NON_DESIGNATED_PORT: change status to DISABLE. ROOT_PORT: change status to DISABLE and recalculate STP.
def link_down(self, ofp_port): """ DESIGNATED_PORT/NON_DESIGNATED_PORT: change status to DISABLE. ROOT_PORT: change status to DISABLE and recalculate STP. """ port = self.ports[ofp_port.port_no] init_stp_flg = bool(port.role is ROOT_PORT) port.down(PORT_STATE_DISABLE, msg_in...
Re-calculation of spanning tree.
def recalculate_spanning_tree(self, init=True): """ Re-calculation of spanning tree. """ # All port down. for port in self.ports.values(): if port.state is not PORT_STATE_DISABLE: port.down(PORT_STATE_BLOCK, msg_init=init) # Send topology change event. ...
Update tree roles. - Root bridge: all port is DESIGNATED_PORT. - Non root bridge: select one ROOT_PORT and some DESIGNATED_PORT, and the other port is set to NON_DESIGNATED_PORT.
def _spanning_tree_algorithm(self): """ Update tree roles. - Root bridge: all port is DESIGNATED_PORT. - Non root bridge: select one ROOT_PORT and some DESIGNATED_PORT, and the other port is set to NON_DESIGNATED_PORT.""" port_rol...
ROOT_PORT is the nearest port to a root bridge. It is determined by the cost of path, etc.
def _select_root_port(self): """ ROOT_PORT is the nearest port to a root bridge. It is determined by the cost of path, etc. """ root_port = None for port in self.ports.values(): root_msg = (self.root_priority if root_port is None else root_port.de...
DESIGNATED_PORT is a port of the side near the root bridge of each link. It is determined by the cost of each path, etc same as ROOT_PORT.
def _select_designated_port(self, root_port): """ DESIGNATED_PORT is a port of the side near the root bridge of each link. It is determined by the cost of each path, etc same as ROOT_PORT. """ d_ports = [] root_msg = root_port.designated_priority for port in self...
A port is started in the state of LISTEN.
def up(self, role, root_priority, root_times): """ A port is started in the state of LISTEN. """ self.port_priority = root_priority self.port_times = root_times state = (PORT_STATE_LISTEN if self.config_enable else PORT_STATE_DISABLE) self._change_role(role) ...
A port will be in the state of DISABLE or BLOCK, and be stopped.
def down(self, state, msg_init=False): """ A port will be in the state of DISABLE or BLOCK, and be stopped. """ assert (state is PORT_STATE_DISABLE or state is PORT_STATE_BLOCK) if not self.config_enable: return if msg_init: self.des...
Port state machine. Change next status when timer is exceeded or _change_status() method is called.
def _state_machine(self): """ Port state machine. Change next status when timer is exceeded or _change_status() method is called.""" role_str = {ROOT_PORT: 'ROOT_PORT ', DESIGNATED_PORT: 'DESIGNATED_PORT ', NON_DESIGNATED_PORT...
Set send_tc_flg to send Topology Change BPDU.
def transmit_tc_bpdu(self): """ Set send_tc_flg to send Topology Change BPDU. """ if not self.send_tc_flg: timer = datetime.timedelta(seconds=self.port_times.max_age + self.port_times.forward_delay) self.send_tc_timer = datetime.datetime.tod...
Send Topology Change Ack BPDU.
def transmit_ack_bpdu(self): """ Send Topology Change Ack BPDU. """ ack_flags = 0b10000001 bpdu_data = self._generate_config_bpdu(ack_flags) self.ofctl.send_packet_out(self.ofport.port_no, bpdu_data)
Check if flags are set on this packet. returns boolean if all passed flags is set Example:: >>> pkt = tcp.tcp(bits=(tcp.TCP_SYN | tcp.TCP_ACK)) >>> pkt.has_flags(tcp.TCP_SYN, tcp.TCP_ACK) True
def has_flags(self, *flags): """Check if flags are set on this packet. returns boolean if all passed flags is set Example:: >>> pkt = tcp.tcp(bits=(tcp.TCP_SYN | tcp.TCP_ACK)) >>> pkt.has_flags(tcp.TCP_SYN, tcp.TCP_ACK) True """ mask = sum(...
Parses user-flags file and loads it to register user defined options.
def _parse_user_flags(): """ Parses user-flags file and loads it to register user defined options. """ try: idx = list(sys.argv).index('--user-flags') user_flags_file = sys.argv[idx + 1] except (ValueError, IndexError): user_flags_file = '' if user_flags_file and os.path...
Generate instance of GRE class with information for NVGRE (RFC7637). :param version: Version. :param vsid: Virtual Subnet ID. :param flow_id: FlowID. :return: Instance of GRE class with information for NVGRE.
def nvgre(version=0, vsid=0, flow_id=0): """ Generate instance of GRE class with information for NVGRE (RFC7637). :param version: Version. :param vsid: Virtual Subnet ID. :param flow_id: FlowID. :return: Instance of GRE class with information for NVGRE. """ # NVGRE header # 0 1 2 ...
This function instanticates an appropriate OpenFlow message class from the given JSON style dictionary. The objects created by following two code fragments are equivalent. Code A:: jsonstr = '{ "OFPSetConfig": { "flags": 0, "miss_send_len": 128 } }' jsondict = json.loads(jsonstr) o...
def ofp_msg_from_jsondict(dp, jsondict): """ This function instanticates an appropriate OpenFlow message class from the given JSON style dictionary. The objects created by following two code fragments are equivalent. Code A:: jsonstr = '{ "OFPSetConfig": { "flags": 0, "miss_send_len": 128 ...
This function is intended to be used with ryu.lib.ofctl_string.ofp_instruction_from_str. It is very similar to ofp_msg_from_jsondict, but works on a list of OFPInstructions/OFPActions. It also encapsulates OFPAction into OFPInstructionActions, as >OF1.0 OFPFlowMod requires that. This function t...
def ofp_instruction_from_jsondict(dp, jsonlist, encap=True): """ This function is intended to be used with ryu.lib.ofctl_string.ofp_instruction_from_str. It is very similar to ofp_msg_from_jsondict, but works on a list of OFPInstructions/OFPActions. It also encapsulates OFPAction into OFPInstruc...
Enable TCP-MD5 on the given socket. :param s: Socket :param addr: Associated address. On some platforms, this has no effect. :param key: Key. On some platforms, this has no effect.
def set_tcp_md5sig(s, addr, key): """Enable TCP-MD5 on the given socket. :param s: Socket :param addr: Associated address. On some platforms, this has no effect. :param key: Key. On some platforms, this has no effect. """ impls = { 'FreeBSD': _set_tcp_md5sig_bsd, 'Linux': _set...
Registers a new address to initiate connection to switch. Registers a new IP address and port pair of switch to let ryu.controller.controller.OpenFlowController to try to initiate connection to switch. :param addr: A tuple of (host, port) pair of switch. :param interval: Interval in seconds to try...
def register_switch_address(addr, interval=None): """ Registers a new address to initiate connection to switch. Registers a new IP address and port pair of switch to let ryu.controller.controller.OpenFlowController to try to initiate connection to switch. :param addr: A tuple of (host, port) p...
Unregister the given switch address. Unregisters the given switch address to let ryu.controller.controller.OpenFlowController stop trying to initiate connection to switch. :param addr: A tuple of (host, port) pair of switch.
def unregister_switch_address(addr): """ Unregister the given switch address. Unregisters the given switch address to let ryu.controller.controller.OpenFlowController stop trying to initiate connection to switch. :param addr: A tuple of (host, port) pair of switch. """ ofp_handler = ap...
Apply default formatting for help messages :param quick_helps: list of tuples containing help info
def default_help_formatter(quick_helps): """Apply default formatting for help messages :param quick_helps: list of tuples containing help info """ ret = '' for line in quick_helps: cmd_path, param_hlp, cmd_hlp = line ret += ' '.join(cmd_path) + ' ' if param_hlp: ...
Override this method to provide custom formatting of cli response.
def cli_resp_formatter(cls, resp): """Override this method to provide custom formatting of cli response. """ if not resp.value: return '' if resp.status == STATUS_OK: if type(resp.value) in (str, bool, int, float, six.text_type): return str(resp....
Filter response of action. Used to make printed results more specific :param action_resp: named tuple (CommandsResponse) containing response from action. :param filter_params: params used after '|' specific for given filter :return: filtered response.
def filter_resp(self, action_resp, filter_params): """Filter response of action. Used to make printed results more specific :param action_resp: named tuple (CommandsResponse) containing response from action. :param filter_params: params used after '|' specific for given filt...
Shows help for this command and it's sub-commands.
def question_mark(self): """Shows help for this command and it's sub-commands. """ ret = [] if self.param_help_msg or len(self.subcommands) == 0: ret.append(self._quick_help()) if len(self.subcommands) > 0: for k, _ in sorted(self.subcommands.items()): ...
:param nested: True if help is requested directly for this command and False when help is requested for a list of possible completions.
def _quick_help(self, nested=False): """:param nested: True if help is requested directly for this command and False when help is requested for a list of possible completions. """ if nested: return self.command_path(), None, self.help_msg ...
Adds an interface record into Zebra protocol service database. The arguments are similar to "ip link add" command of iproute2. :param session: Session instance connecting to database. :param name: Name of interface. :param type_: Type of interface. 'loopback' or 'ethernet'. :param lladdr: Link lay...
def ip_link_add(session, name, type_='loopback', lladdr='00:00:00:00:00:00'): """ Adds an interface record into Zebra protocol service database. The arguments are similar to "ip link add" command of iproute2. :param session: Session instance connecting to database. :param name: Name of interface. ...
Deletes an interface record from Zebra protocol service database. The arguments are similar to "ip link delete" command of iproute2. :param session: Session instance connecting to database. :param name: Name of interface. :return: Name of interface which was deleted. None if failed.
def ip_link_delete(session, name): """ Deletes an interface record from Zebra protocol service database. The arguments are similar to "ip link delete" command of iproute2. :param session: Session instance connecting to database. :param name: Name of interface. :return: Name of interface which ...
Adds an IP address to interface record identified with the given "ifname". The arguments are similar to "ip address add" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. :param ifaddr: IPv4 or IPv6 address. :return: Instance of record ...
def ip_address_add(session, ifname, ifaddr): """ Adds an IP address to interface record identified with the given "ifname". The arguments are similar to "ip address add" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. :param ifadd...
Deletes an IP address from interface record identified with the given "ifname". The arguments are similar to "ip address delete" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. :param ifaddr: IPv4 or IPv6 address. :return: Instanc...
def ip_address_delete(session, ifname, ifaddr): """ Deletes an IP address from interface record identified with the given "ifname". The arguments are similar to "ip address delete" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. ...
split string into list of strings by specified number.
def _split_str(s, n): """ split string into list of strings by specified number. """ length = len(s) return [s[i:i + n] for i in range(0, length, n)]
Generates a dict of system parameters used throughout a simulation. Parameters ---------- meta : dict meta dict either generated from a TMY file using readtmy2 or readtmy3, or a dict containing at least the following fields: =============== ====== ==================== ...
def systemdef(meta, surface_tilt, surface_azimuth, albedo, modules_per_string, strings_per_inverter): ''' Generates a dict of system parameters used throughout a simulation. Parameters ---------- meta : dict meta dict either generated from a TMY file using readtmy2 or ...
Determine the incidence angle modifier using the ASHRAE transmission model. ashraeiam calculates the incidence angle modifier as developed in [1], and adopted by ASHRAE (American Society of Heating, Refrigeration, and Air Conditioning Engineers) [2]. The model has been used by model programs such a...
def ashraeiam(aoi, b=0.05): ''' Determine the incidence angle modifier using the ASHRAE transmission model. ashraeiam calculates the incidence angle modifier as developed in [1], and adopted by ASHRAE (American Society of Heating, Refrigeration, and Air Conditioning Engineers) [2]. The model ha...
Determine the incidence angle modifier using refractive index, extinction coefficient, and glazing thickness. physicaliam calculates the incidence angle modifier as described in De Soto et al. "Improvement and validation of a model for photovoltaic array performance", section 3. The calculation is base...
def physicaliam(aoi, n=1.526, K=4., L=0.002): ''' Determine the incidence angle modifier using refractive index, extinction coefficient, and glazing thickness. physicaliam calculates the incidence angle modifier as described in De Soto et al. "Improvement and validation of a model for photovolt...
Calculates five parameter values for the single diode equation at effective irradiance and cell temperature using the De Soto et al. model described in [1]. The five values returned by calcparams_desoto can be used by singlediode to calculate an IV curve. Parameters ---------- effective_irradia...
def calcparams_desoto(effective_irradiance, temp_cell, alpha_sc, a_ref, I_L_ref, I_o_ref, R_sh_ref, R_s, EgRef=1.121, dEgdT=-0.0002677, irrad_ref=1000, temp_ref=25): ''' Calculates five parameter values for the single diode equation at effect...
Calculates five parameter values for the single diode equation at effective irradiance and cell temperature using the CEC model described in [1]. The CEC model differs from the De soto et al. model [3] by the parameter Adjust. The five values returned by calcparams_cec can be used by singlediode to calc...
def calcparams_cec(effective_irradiance, temp_cell, alpha_sc, a_ref, I_L_ref, I_o_ref, R_sh_ref, R_s, Adjust, EgRef=1.121, dEgdT=-0.0002677, irrad_ref=1000, temp_ref=25): ''' Calculates five parameter values for the single diode equation at effective ...
Calculates five parameter values for the single diode equation at effective irradiance and cell temperature using the PVsyst v6 model described in [1,2,3]. The five values returned by calcparams_pvsyst can be used by singlediode to calculate an IV curve. Parameters ---------- effective_irradian...
def calcparams_pvsyst(effective_irradiance, temp_cell, alpha_sc, gamma_ref, mu_gamma, I_L_ref, I_o_ref, R_sh_ref, R_sh_0, R_s, cells_in_series, R_sh_exp=5.5, EgRef=1.121, ...
Retrieve latest module and inverter info from a local file or the SAM website. This function will retrieve either: * CEC module database * Sandia Module database * CEC Inverter database * Anton Driesse Inverter database and return it as a pandas DataFrame. Parameters ...
def retrieve_sam(name=None, path=None): ''' Retrieve latest module and inverter info from a local file or the SAM website. This function will retrieve either: * CEC module database * Sandia Module database * CEC Inverter database * Anton Driesse Inverter database a...
The Sandia PV Array Performance Model (SAPM) generates 5 points on a PV module's I-V curve (Voc, Isc, Ix, Ixx, Vmp/Imp) according to SAND2004-3535. Assumes a reference cell temperature of 25 C. Parameters ---------- effective_irradiance : numeric Effective irradiance (suns). temp_cell ...
def sapm(effective_irradiance, temp_cell, module): ''' The Sandia PV Array Performance Model (SAPM) generates 5 points on a PV module's I-V curve (Voc, Isc, Ix, Ixx, Vmp/Imp) according to SAND2004-3535. Assumes a reference cell temperature of 25 C. Parameters ---------- effective_irradiance...
Estimate cell and module temperatures per the Sandia PV Array Performance Model (SAPM, SAND2004-3535), from the incident irradiance, wind speed, ambient temperature, and SAPM module parameters. Parameters ---------- poa_global : float or Series Total incident irradiance in W/m^2. w...
def sapm_celltemp(poa_global, wind_speed, temp_air, model='open_rack_cell_glassback'): ''' Estimate cell and module temperatures per the Sandia PV Array Performance Model (SAPM, SAND2004-3535), from the incident irradiance, wind speed, ambient temperature, and SAPM module parameter...
Calculate cell temperature using an emperical heat loss factor model as implemented in PVsyst. The heat loss factors provided through the 'model_params' argument represent the combined effect of convection, radiation and conduction, and their values are experimentally determined. Parameters --...
def pvsyst_celltemp(poa_global, temp_air, wind_speed=1.0, eta_m=0.1, alpha_absorption=0.9, model_params='freestanding'): """ Calculate cell temperature using an emperical heat loss factor model as implemented in PVsyst. The heat loss factors provided through the 'model_params' argum...
Calculates the SAPM spectral loss coefficient, F1. Parameters ---------- airmass_absolute : numeric Absolute airmass module : dict-like A dict, Series, or DataFrame defining the SAPM performance parameters. See the :py:func:`sapm` notes section for more details. Re...
def sapm_spectral_loss(airmass_absolute, module): """ Calculates the SAPM spectral loss coefficient, F1. Parameters ---------- airmass_absolute : numeric Absolute airmass module : dict-like A dict, Series, or DataFrame defining the SAPM performance parameters. See the :...
Calculates the SAPM angle of incidence loss coefficient, F2. Parameters ---------- aoi : numeric Angle of incidence in degrees. Negative input angles will return zeros. module : dict-like A dict, Series, or DataFrame defining the SAPM performance parameters. See the :py...
def sapm_aoi_loss(aoi, module, upper=None): """ Calculates the SAPM angle of incidence loss coefficient, F2. Parameters ---------- aoi : numeric Angle of incidence in degrees. Negative input angles will return zeros. module : dict-like A dict, Series, or DataFrame defin...
Calculates the SAPM effective irradiance using the SAPM spectral loss and SAPM angle of incidence loss functions. Parameters ---------- poa_direct : numeric The direct irradiance incident upon the module. poa_diffuse : numeric The diffuse irradiance incident on module. airmass...
def sapm_effective_irradiance(poa_direct, poa_diffuse, airmass_absolute, aoi, module, reference_irradiance=1000): """ Calculates the SAPM effective irradiance using the SAPM spectral loss and SAPM angle of incidence loss functions. Parameters ---------- poa_direct ...
Solve the single-diode model to obtain a photovoltaic IV curve. Singlediode solves the single diode equation [1] .. math:: I = IL - I0*[exp((V+I*Rs)/(nNsVth))-1] - (V + I*Rs)/Rsh for ``I`` and ``V`` when given ``IL, I0, Rs, Rsh,`` and ``nNsVth (nNsVth = n*Ns*Vth)`` which are described later....
def singlediode(photocurrent, saturation_current, resistance_series, resistance_shunt, nNsVth, ivcurve_pnts=None, method='lambertw'): """ Solve the single-diode model to obtain a photovoltaic IV curve. Singlediode solves the single diode equation [1] .. math:: ...
Given the single diode equation coefficients, calculates the maximum power point (MPP). Parameters ---------- photocurrent : numeric photo-generated current [A] saturation_current : numeric diode reverse saturation current [A] resistance_series : numeric series resitance...
def max_power_point(photocurrent, saturation_current, resistance_series, resistance_shunt, nNsVth, method='brentq'): """ Given the single diode equation coefficients, calculates the maximum power point (MPP). Parameters ---------- photocurrent : numeric photo-generat...
Device voltage at the given device current for the single diode model. Uses the single diode model (SDM) as described in, e.g., Jain and Kapoor 2004 [1]. The solution is per Eq 3 of [1] except when resistance_shunt=numpy.inf, in which case the explict solution for voltage is used. Ideal device pa...
def v_from_i(resistance_shunt, resistance_series, nNsVth, current, saturation_current, photocurrent, method='lambertw'): ''' Device voltage at the given device current for the single diode model. Uses the single diode model (SDM) as described in, e.g., Jain and Kapoor 2004 [1]. The so...
Device current at the given device voltage for the single diode model. Uses the single diode model (SDM) as described in, e.g., Jain and Kapoor 2004 [1]. The solution is per Eq 2 of [1] except when resistance_series=0, in which case the explict solution for current is used. Ideal device parameter...
def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage, saturation_current, photocurrent, method='lambertw'): ''' Device current at the given device voltage for the single diode model. Uses the single diode model (SDM) as described in, e.g., Jain and Kapoor 2004 [1]. The so...
r''' Converts DC power and voltage to AC power using Sandia's Grid-Connected PV Inverter model. Determines the AC power output of an inverter given the DC voltage, DC power, and appropriate Sandia Grid-Connected Photovoltaic Inverter Model parameters. The output, ac_power, is clipped at the max...
def snlinverter(v_dc, p_dc, inverter): r''' Converts DC power and voltage to AC power using Sandia's Grid-Connected PV Inverter model. Determines the AC power output of an inverter given the DC voltage, DC power, and appropriate Sandia Grid-Connected Photovoltaic Inverter Model parameters. The ...
r''' Converts DC power and voltage to AC power using Anton Driesse's Grid-Connected PV Inverter efficiency model Parameters ---------- v_dc : numeric A scalar or pandas series of DC voltages, in volts, which are provided as input to the inverter. If Vdc and Pdc are vectors, they mus...
def adrinverter(v_dc, p_dc, inverter, vtol=0.10): r''' Converts DC power and voltage to AC power using Anton Driesse's Grid-Connected PV Inverter efficiency model Parameters ---------- v_dc : numeric A scalar or pandas series of DC voltages, in volts, which are provided as input...
Scales the voltage, current, and power of the DataFrames returned by :py:func:`singlediode` and :py:func:`sapm`. Parameters ---------- data: DataFrame Must contain columns `'v_mp', 'v_oc', 'i_mp' ,'i_x', 'i_xx', 'i_sc', 'p_mp'`. voltage: numeric, default 1 The amount by whic...
def scale_voltage_current_power(data, voltage=1, current=1): """ Scales the voltage, current, and power of the DataFrames returned by :py:func:`singlediode` and :py:func:`sapm`. Parameters ---------- data: DataFrame Must contain columns `'v_mp', 'v_oc', 'i_mp' ,'i_x', 'i_xx', 'i...
r""" Implements NREL's PVWatts DC power model [1]_: .. math:: P_{dc} = \frac{G_{poa eff}}{1000} P_{dc0} ( 1 + \gamma_{pdc} (T_{cell} - T_{ref})) Parameters ---------- g_poa_effective: numeric Irradiance transmitted to the PV cells in units of W/m**2. To be fully consistent...
def pvwatts_dc(g_poa_effective, temp_cell, pdc0, gamma_pdc, temp_ref=25.): r""" Implements NREL's PVWatts DC power model [1]_: .. math:: P_{dc} = \frac{G_{poa eff}}{1000} P_{dc0} ( 1 + \gamma_{pdc} (T_{cell} - T_{ref})) Parameters ---------- g_poa_effective: numeric Irradiance...
r""" Implements NREL's PVWatts system loss model [1]_: .. math:: L_{total}(\%) = 100 [ 1 - \Pi_i ( 1 - \frac{L_i}{100} ) ] All parameters must be in units of %. Parameters may be array-like, though all array sizes must match. Parameters ---------- soiling: numeric, default 2 ...
def pvwatts_losses(soiling=2, shading=3, snow=0, mismatch=2, wiring=2, connections=0.5, lid=1.5, nameplate_rating=1, age=0, availability=3): r""" Implements NREL's PVWatts system loss model [1]_: .. math:: L_{total}(\%) = 100 [ 1 - \Pi_i ( 1 - \frac{L_i}{100} ...
r""" Implements NREL's PVWatts inverter model [1]_. .. math:: \eta = \frac{\eta_{nom}}{\eta_{ref}} (-0.0162\zeta - \frac{0.0059}{\zeta} + 0.9858) .. math:: P_{ac} = \min(\eta P_{dc}, P_{ac0}) where :math:`\zeta=P_{dc}/P_{dc0}` and :math:`P_{dc0}=P_{ac0}/\eta_{nom}`. Parameters ...
def pvwatts_ac(pdc, pdc0, eta_inv_nom=0.96, eta_inv_ref=0.9637): r""" Implements NREL's PVWatts inverter model [1]_. .. math:: \eta = \frac{\eta_{nom}}{\eta_{ref}} (-0.0162\zeta - \frac{0.0059}{\zeta} + 0.9858) .. math:: P_{ac} = \min(\eta P_{dc}, P_{ac0}) where :math:`\zeta=P_{...
Get the angle of incidence on the system. Parameters ---------- solar_zenith : float or Series. Solar zenith angle. solar_azimuth : float or Series. Solar azimuth angle. Returns ------- aoi : Series The angle of incidence
def get_aoi(self, solar_zenith, solar_azimuth): """Get the angle of incidence on the system. Parameters ---------- solar_zenith : float or Series. Solar zenith angle. solar_azimuth : float or Series. Solar azimuth angle. Returns ------- ...
Determine the incidence angle modifier using ``self.module_parameters['b']``, ``aoi``, and the :py:func:`ashraeiam` function. Uses default arguments if keys not in module_parameters. Parameters ---------- aoi : numeric The angle of incidence in degrees. ...
def ashraeiam(self, aoi): """ Determine the incidence angle modifier using ``self.module_parameters['b']``, ``aoi``, and the :py:func:`ashraeiam` function. Uses default arguments if keys not in module_parameters. Parameters ---------- aoi : numeric ...
Determine the incidence angle modifier using ``aoi``, ``self.module_parameters['K']``, ``self.module_parameters['L']``, ``self.module_parameters['n']``, and the :py:func:`physicaliam` function. Uses default arguments if keys not in module_parameters. Parameters ...
def physicaliam(self, aoi): """ Determine the incidence angle modifier using ``aoi``, ``self.module_parameters['K']``, ``self.module_parameters['L']``, ``self.module_parameters['n']``, and the :py:func:`physicaliam` function. Uses default arguments if key...
Use the :py:func:`calcparams_desoto` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance : numeric The irradiance (W/m2) that is converted to photocurrent. ...
def calcparams_desoto(self, effective_irradiance, temp_cell, **kwargs): """ Use the :py:func:`calcparams_desoto` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradi...
Use the :py:func:`calcparams_cec` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance : numeric The irradiance (W/m2) that is converted to photocurrent. te...
def calcparams_cec(self, effective_irradiance, temp_cell, **kwargs): """ Use the :py:func:`calcparams_cec` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance :...
Use the :py:func:`calcparams_pvsyst` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance : numeric The irradiance (W/m2) that is converted to photocurrent. ...
def calcparams_pvsyst(self, effective_irradiance, temp_cell): """ Use the :py:func:`calcparams_pvsyst` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance : num...
Use the :py:func:`sapm` function, the input parameters, and ``self.module_parameters`` to calculate Voc, Isc, Ix, Ixx, Vmp/Imp. Parameters ---------- poa_direct : Series The direct irradiance incident upon the module (W/m^2). poa_diffuse : Series ...
def sapm(self, effective_irradiance, temp_cell, **kwargs): """ Use the :py:func:`sapm` function, the input parameters, and ``self.module_parameters`` to calculate Voc, Isc, Ix, Ixx, Vmp/Imp. Parameters ---------- poa_direct : Series The direct irradia...
Uses :py:func:`sapm_celltemp` to calculate module and cell temperatures based on ``self.racking_model`` and the input parameters. Parameters ---------- See pvsystem.sapm_celltemp for details Returns ------- See pvsystem.sapm_celltemp for details
def sapm_celltemp(self, irrad, wind, temp): """Uses :py:func:`sapm_celltemp` to calculate module and cell temperatures based on ``self.racking_model`` and the input parameters. Parameters ---------- See pvsystem.sapm_celltemp for details Returns ------- ...
Use the :py:func:`sapm_effective_irradiance` function, the input parameters, and ``self.module_parameters`` to calculate effective irradiance. Parameters ---------- poa_direct : numeric The direct irradiance incident upon the module. poa_diffuse : numeric ...
def sapm_effective_irradiance(self, poa_direct, poa_diffuse, airmass_absolute, aoi, reference_irradiance=1000): """ Use the :py:func:`sapm_effective_irradiance` function, the input parameters, and ``self.module_parameters`` to c...
Uses :py:func:`pvsyst_celltemp` to calculate module temperatures based on ``self.racking_model`` and the input parameters. Parameters ---------- See pvsystem.pvsyst_celltemp for details Returns ------- See pvsystem.pvsyst_celltemp for details
def pvsyst_celltemp(self, poa_global, temp_air, wind_speed=1.0): """Uses :py:func:`pvsyst_celltemp` to calculate module temperatures based on ``self.racking_model`` and the input parameters. Parameters ---------- See pvsystem.pvsyst_celltemp for details Returns ...
Use the :py:func:`first_solar_spectral_correction` function to calculate the spectral loss modifier. The model coefficients are specific to the module's cell type, and are determined by searching for one of the following keys in self.module_parameters (in order): 'first_solar_spectra...
def first_solar_spectral_loss(self, pw, airmass_absolute): """ Use the :py:func:`first_solar_spectral_correction` function to calculate the spectral loss modifier. The model coefficients are specific to the module's cell type, and are determined by searching for one of the follo...