@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@rate_limited()<EOL>def get_managed_policy_document(policy_arn, policy_metadata=None, client=None, **kwargs):

if not policy_metadata:<EOL><INDENT>policy_metadata = client.get_policy(PolicyArn=policy_arn)<EOL><DEDENT>policy_document = client.get_policy_version(PolicyArn=policy_arn,<EOL>VersionId=policy_metadata['<STR_LIT>']['<STR_LIT>'])<EOL>return policy_document['<STR_LIT>']['<STR_LIT>']<EOL>

Retrieve the currently active (i.e. 'default') policy version document for a policy.

    :param policy_arn:
    :param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux.
                            This is used to prevent unnecessary API calls to get the initial policy default version id.
    :param client:
    :param kwargs:
    :return:


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@paginated('<STR_LIT>')<EOL>@rate_limited()<EOL>def list_groups_for_user(user_name, client=None, **kwargs):

return client.list_groups_for_user(UserName=user_name, **kwargs)<EOL>

Lists the IAM groups that is attached to a given IAM user.


return client.get_group(**kwargs)<EOL>

Fetch the paginated users attached to the group.


return [x for x in getattr( getattr( conn, kwargs.pop('<STR_LIT>') ),<EOL>kwargs.pop('<STR_LIT>'))(**kwargs)]<EOL>


@registry.register(flag=FLAGS.INTERNET_GATEWAY, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_internet_gateway(vpc, **conn):

result = {}<EOL>ig_result = describe_internet_gateways(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>if ig_result:<EOL><INDENT>result.update({<EOL>"<STR_LIT>": ig_result[<NUM_LIT:0>]["<STR_LIT>"][<NUM_LIT:0>]["<STR_LIT>"],<EOL>"<STR_LIT>": ig_result[<NUM_LIT:0>]["<STR_LIT>"],<EOL>"<STR_LIT>": ig_result[<NUM_LIT:0>].get("<STR_LIT>", [])<EOL>})<EOL><DEDENT>return result<EOL>

Gets the Internet Gateway details about a VPC


@modify_output<EOL>def get_vpc(vpc_id, flags=FLAGS.ALL, **conn):

<EOL>if not conn.get("<STR_LIT>"):<EOL><INDENT>raise CloudAuxException({"<STR_LIT:message>": "<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>": vpc_id})<EOL><DEDENT>if not conn.get("<STR_LIT>"):<EOL><INDENT>raise CloudAuxException({"<STR_LIT:message>": "<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>": vpc_id})<EOL><DEDENT>start = {<EOL>'<STR_LIT>': "<STR_LIT>".format(region=conn["<STR_LIT>"],<EOL>account=conn["<STR_LIT>"],<EOL>vpc_id=vpc_id),<EOL>'<STR_LIT:id>': vpc_id<EOL>}<EOL>return registry.build_out(flags, start_with=start, pass_datastructure=True, **conn)<EOL>

Orchestrates all the calls required to fully fetch details about a VPC:

{
    "Arn": ...,
    "Region": ...,
    "Name": ...,
    "Id": ...,
    "Tags: ...,
    "VpcPeeringConnections": ...,
    "ClassicLink": ...,
    "DhcpOptionsId": ...,
    "InternetGateway": ...,
    "IsDefault": ...,
    "CidrBlock": ...,
    "CidrBlockAssociationSet": ...,
    "Ipv6CidrBlockAssociationSet": ...,
    "InstanceTenancy": ...,
    "RouteTables": ...,
    "NetworkAcls": ...,
    "FlowLogs": ...,
    "Subnets": ...,
    "Attributes": ...,
    "FlowLogs": ...,
    "_version": 1
}

:param vpc_id: The ID of the VPC
:param flags:
:param conn:
:return:


@registry.register(flag=FLAGS.ROUTE_TABLES, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_route_tables(vpc, **conn):

route_tables = describe_route_tables(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>rt_ids = []<EOL>for r in route_tables:<EOL><INDENT>rt_ids.append(r["<STR_LIT>"])<EOL><DEDENT>return rt_ids<EOL>


@registry.register(flag=FLAGS.NETWORK_ACLS, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_network_acls(vpc, **conn):

route_tables = describe_network_acls(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>nacl_ids = []<EOL>for r in route_tables:<EOL><INDENT>nacl_ids.append(r["<STR_LIT>"])<EOL><DEDENT>return nacl_ids<EOL>


@registry.register(flag=FLAGS.FLOW_LOGS, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_vpc_flow_logs(vpc, **conn):

fl_result = describe_flow_logs(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>fl_ids = []<EOL>for fl in fl_result:<EOL><INDENT>fl_ids.append(fl["<STR_LIT>"])<EOL><DEDENT>return fl_ids<EOL>


@modify_output<EOL>def get_load_balancer(load_balancer, flags=FLAGS.ALL ^ FLAGS.POLICY_TYPES, **conn):

<EOL>try:<EOL><INDENT>basestring<EOL><DEDENT>except NameError as _:<EOL><INDENT>basestring = str<EOL><DEDENT>if isinstance(load_balancer, basestring):<EOL><INDENT>load_balancer = dict(LoadBalancerName=load_balancer)<EOL><DEDENT>return registry.build_out(flags, start_with=load_balancer, pass_datastructure=True, **conn)<EOL>

Fully describes an ELB.

:param loadbalancer: Could be an ELB Name or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerName'.
:param flags: Flags describing which sections should be included in the return value. Default is FLAGS.ALL minus FLAGS.POLICY_TYPES.
:return: Returns a dictionary describing the ELB with the fields described in the flags parameter.


policy_name = policy['<STR_LIT>']<EOL>ret = {}<EOL>ret['<STR_LIT:type>'] = policy['<STR_LIT>']<EOL>attrs = policy['<STR_LIT>']<EOL>if ret['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>return policy_name, ret<EOL><DEDENT>attributes = dict()<EOL>for attr in attrs:<EOL><INDENT>attributes[attr['<STR_LIT>']] = attr['<STR_LIT>']<EOL><DEDENT>ret['<STR_LIT>'] = dict()<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>'] = attributes.get('<STR_LIT>', None)<EOL>non_ciphers = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>]<EOL>ciphers = []<EOL>for cipher in attributes:<EOL><INDENT>if attributes[cipher] == '<STR_LIT:true>' and cipher not in non_ciphers:<EOL><INDENT>ciphers.append(cipher)<EOL><DEDENT><DEDENT>ciphers.sort()<EOL>ret['<STR_LIT>'] = ciphers<EOL>return policy_name, ret<EOL>

Policies returned from boto3 are massive, ugly, and difficult to read.
This method flattens and reformats the policy.

:param policy: Result from invoking describe_load_balancer_policies(...)
:return: Returns a tuple containing policy_name and the reformatted policy dict.


@modify_output<EOL>def get_image(image_id, flags=FLAGS.ALL, **conn):

image = dict(ImageId=image_id)<EOL>conn['<STR_LIT>'] = conn.get('<STR_LIT>', '<STR_LIT>')<EOL>return registry.build_out(flags, image, **conn)<EOL>

Orchestrates all the calls required to fully build out an EC2 Image (AMI, AKI, ARI)

{
    "Architecture": "x86_64",
    "Arn": "arn:aws:ec2:us-east-1::image/ami-11111111",
    "BlockDeviceMappings": [],
    "CreationDate": "2013-07-11T16:04:06.000Z",
    "Description": "...",
    "Hypervisor": "xen",
    "ImageId": "ami-11111111",
    "ImageLocation": "111111111111/...",
    "ImageType": "machine",
    "KernelId": "aki-88888888",
    "LaunchPermissions": [],
    "Name": "...",
    "OwnerId": "111111111111",
    "ProductCodes": [],
    "Public": false,
    "RamdiskId": {},
    "RootDeviceName": "/dev/sda1",
    "RootDeviceType": "ebs",
    "SriovNetSupport": "simple",
    "State": "available",
    "Tags": [],
    "VirtualizationType": "hvm",
    "_version": 1
}

:param image_id: str ami id
:param flags: By default, set to ALL fields
:param conn: dict containing enough information to make a connection to the desired account.
Must at least have 'assume_role' key.
:return: dict containing a fully built out image.


@modify_output<EOL>def get_elbv2(alb, flags=FLAGS.ALL, **conn):

<EOL>try:<EOL><INDENT>basestring<EOL><DEDENT>except NameError as _:<EOL><INDENT>basestring = str<EOL><DEDENT>if isinstance(alb, basestring):<EOL><INDENT>from cloudaux.orchestration.aws.arn import ARN<EOL>alb_arn = ARN(alb)<EOL>if alb_arn.error:<EOL><INDENT>alb = dict(LoadBalancerName=alb)<EOL><DEDENT>else:<EOL><INDENT>alb = dict(LoadBalancerArn=alb)<EOL><DEDENT><DEDENT>return registry.build_out(flags, start_with=alb, pass_datastructure=True, **conn)<EOL>

Fully describes an ALB (ELBv2).

:param alb: Could be an ALB Name, ALB ARN, or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerArn'.
:param flags: Flags describing which sections should be included in the return value. Default is FLAGS.ALL.
:return: Returns a dictionary describing the ALB with the fields described in the flags parameter.


if item.get(default):<EOL><INDENT>return item.get(default)<EOL><DEDENT>if item.get('<STR_LIT>'):<EOL><INDENT>arn = item.get('<STR_LIT>')<EOL>item_arn = ARN(arn)<EOL>if item_arn.error:<EOL><INDENT>raise CloudAuxException('<STR_LIT>'.format(arn=arn))<EOL><DEDENT>return item_arn.parsed_name<EOL><DEDENT>raise MissingFieldException('<STR_LIT>'.format(input=item))<EOL>

Given a possibly sparsely populated item dictionary, try to retrieve the item name.
First try the default field.  If that doesn't exist, try to parse the from the ARN.
:param item: dict containing (at the very least) item_name and/or arn
:return: item name


arn = ARN(arn)<EOL>if arn.error:<EOL><INDENT>raise CloudAuxException('<STR_LIT>'.format(arn=arn))<EOL><DEDENT>return dict(<EOL>account_number=arn.account_number,<EOL>)<EOL>

Extracts the account number from an ARN.
:param arn: Amazon ARN containing account number.
:return: dictionary with a single account_number key that can be merged with an existing
connection dictionary containing fields such as assume_role, session_name, region.


@registry.register(flag=FLAGS.INLINE_POLICIES, key='<STR_LIT>')<EOL>def get_inline_policies(group, **conn):

policy_list = list_group_policies(group['<STR_LIT>'])<EOL>policy_documents = {}<EOL>for policy in policy_list:<EOL><INDENT>policy_documents[policy] = get_group_policy_document(group['<STR_LIT>'], policy, **conn)<EOL><DEDENT>return policy_documents<EOL>


@modify_output<EOL>def get_group(group, flags=FLAGS.BASE | FLAGS.INLINE_POLICIES | FLAGS.MANAGED_POLICIES, **conn):

if not group.get('<STR_LIT>'):<EOL><INDENT>raise MissingFieldException('<STR_LIT>')<EOL><DEDENT>group = modify(group, output='<STR_LIT>')<EOL>_conn_from_args(group, conn)<EOL>return registry.build_out(flags, start_with=group, pass_datastructure=True, **conn)<EOL>

Orchestrates all the calls required to fully build out an IAM Group in the following format:

{
    "Arn": ...,
    "GroupName": ...,
    "Path": ...,
    "GroupId": ...,
    "CreateDate": ...,  # str
    "InlinePolicies": ...,
    "ManagedPolicies": ...,  # These are just the names of the Managed Policies.
    "Users": ...,  # False by default -- these are just the names of the users.
    "_version": 1
}

:param flags: By default, Users is disabled. This is somewhat expensive as it has to call the `get_group` call
              multiple times.
:param group: dict MUST contain the GroupName and also a combination of either the ARN or the account_number.
:param output: Determines whether keys should be returned camelized or underscored.
:param conn: dict containing enough information to make a connection to the desired account.
             Must at least have 'assume_role' key.
:return: dict containing fully built out Group.


@registry.register(flag=FLAGS.USERS, key='<STR_LIT>')<EOL>def get_users(group, **conn):

group_details = get_group_api(group['<STR_LIT>'], **conn)<EOL>user_list = []<EOL>for user in group_details.get('<STR_LIT>', []):<EOL><INDENT>user_list.append(user['<STR_LIT>'])<EOL><DEDENT>return user_list<EOL>

Gets a list of the usernames that are a part of this group.


base_fields = frozenset(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>needs_base = False<EOL>for field in base_fields:<EOL><INDENT>if field not in role:<EOL><INDENT>needs_base = True<EOL>break<EOL><DEDENT><DEDENT>if needs_base:<EOL><INDENT>role_name = _get_name_from_structure(role, '<STR_LIT>')<EOL>role = CloudAux.go('<STR_LIT>', RoleName=role_name, **conn)<EOL>role = role['<STR_LIT>']<EOL><DEDENT>role.update(dict(CreateDate=get_iso_string(role['<STR_LIT>'])))<EOL>role['<STR_LIT>'] = <NUM_LIT:3><EOL>return role<EOL>

Determine whether the boto get_role call needs to be made or if we already have all that data
in the role object.
:param role: dict containing (at the very least) role_name and/or arn.
:param conn: dict containing enough information to make a connection to the desired account.
:return: Camelized dict describing role containing all all base_fields.


@modify_output<EOL>def get_role(role, flags=FLAGS.ALL, **conn):

role = modify(role, output='<STR_LIT>')<EOL>_conn_from_args(role, conn)<EOL>return registry.build_out(flags, start_with=role, pass_datastructure=True, **conn)<EOL>

Orchestrates all the calls required to fully build out an IAM Role in the following format:

{
    "Arn": ...,
    "AssumeRolePolicyDocument": ...,
    "CreateDate": ...,  # str
    "InlinePolicies": ...,
    "InstanceProfiles": ...,
    "ManagedPolicies": ...,
    "Path": ...,
    "RoleId": ...,
    "RoleName": ...,
    "Tags": {},
    "_version": 3
}

:param role: dict containing (at the very least) role_name and/or arn.
:param output: Determines whether keys should be returned camelized or underscored.
:param conn: dict containing enough information to make a connection to the desired account.
Must at least have 'assume_role' key.
:return: dict containing a fully built out role.


def get_all_users(flags=FLAGS.ACCESS_KEYS | FLAGS.MFA_DEVICES | FLAGS.LOGIN_PROFILE | FLAGS.SIGNING_CERTIFICATES,<EOL>**conn):

users = []<EOL>account_users = get_account_authorization_details('<STR_LIT>', **conn)<EOL>for user in account_users:<EOL><INDENT>temp_user = {<EOL>'<STR_LIT>': user['<STR_LIT>'],<EOL>'<STR_LIT>': get_iso_string(user['<STR_LIT>']),<EOL>'<STR_LIT>': user['<STR_LIT>'],<EOL>'<STR_LIT>': user['<STR_LIT>'],<EOL>'<STR_LIT>': [<EOL>{<EOL>"<STR_LIT:name>": x['<STR_LIT>'],<EOL>"<STR_LIT>": x['<STR_LIT>']<EOL>} for x in user['<STR_LIT>']<EOL>],<EOL>'<STR_LIT>': user['<STR_LIT>'],<EOL>'<STR_LIT>': user['<STR_LIT>'],<EOL>'<STR_LIT>': user['<STR_LIT>']<EOL>}<EOL>user = modify(temp_user, output='<STR_LIT>')<EOL>_conn_from_args(user, conn)<EOL>users.append(registry.build_out(flags, start_with=user, pass_datastructure=True, **conn))<EOL><DEDENT>return users<EOL>

Returns a list of Users represented as dictionary below:

{
    "Arn": ...,
    "AccessKeys": ...,
    "CreateDate": ...,  # str
    "InlinePolicies": ...,
    "ManagedPolicies": ...,
    "MFADevices": ...,
    "Path": ...,
    "UserId": ...,
    "UserName": ...,
    "SigningCerts": ...
}

:param flags:
:param conn: dict containing enough information to make a connection to the desired account.
:return: list of dicts containing fully built out user.


@modify_output<EOL>def get_server_certificate(server_certificate, flags=FLAGS.BASE, **conn):

if not server_certificate.get('<STR_LIT>'):<EOL><INDENT>raise MissingFieldException('<STR_LIT>')<EOL><DEDENT>server_certificate = modify(server_certificate, output='<STR_LIT>')<EOL>_conn_from_args(server_certificate, conn)<EOL>return registry.build_out(flags, start_with=server_certificate, pass_datastructure=True, **conn)<EOL>

Orchestrates all the calls required to fully build out an IAM User in the following format:

{
    "Arn": ...,
    "ServerCertificateName": ...,
    "Path": ...,
    "ServerCertificateId": ...,
    "UploadDate": ...,  # str
    "Expiration": ...,  # str
    "CertificateBody": ...,
    "CertificateChain": ...,
    "_version": 1
}

:param flags: By default, Users is disabled. This is somewhat expensive as it has to call the
              `get_server_certificate` call multiple times.
:param server_certificate: dict MUST contain the ServerCertificateName and also a combination of
                           either the ARN or the account_number.
:param output: Determines whether keys should be returned camelized or underscored.
:param conn: dict containing enough information to make a connection to the desired account.
             Must at least have 'assume_role' key.
:return: dict containing fully built out Server Certificate.


_item = {}<EOL>for k,v in inspect.getmembers(item, lambda a:not(inspect.isroutine(a))):<EOL><INDENT>if not k.startswith('<STR_LIT:_>') and not k in ignore_list:<EOL><INDENT>_item[k] = v<EOL><DEDENT><DEDENT>return sub_dict(_item)<EOL>

API versioning for each OpenStack service is independent. Generically capture
    the public members (non-routine and non-private) of the OpenStack SDK objects.

Note the lack of the modify_output decorator. Preserving the field naming allows
    us to reconstruct objects and orchestrate from stored items.


r = []<EOL>for i in l:<EOL><INDENT>if type(i) in prims:<EOL><INDENT>r.append(i)<EOL><DEDENT>elif type(i) is list:<EOL><INDENT>r.append(sub_list(i))<EOL><DEDENT>elif type(i) is dict:<EOL><INDENT>r.append(sub_dict(i))<EOL><DEDENT>else:<EOL><INDENT>r.append(str(i))<EOL><DEDENT><DEDENT>r = sorted(r)<EOL>return r<EOL>

Recursively walk a data-structure sorting any lists along the way.
Any unknown types get mapped to string representation

:param l: list
:return: sorted list, where any child lists are also sorted.


result = dict()<EOL>for key in item:<EOL><INDENT>result[func(key)] = item[key]<EOL><DEDENT>return result<EOL>

Modifies each item.keys() string based on the func passed in.
Often used with inflection's camelize or underscore methods.

:param item: dictionary representing item to be modified
:param func: function to run on each key string
:return: dictionary where each key has been modified by func.


if output == '<STR_LIT>':<EOL><INDENT>return _modify(item, camelize)<EOL><DEDENT>elif output == '<STR_LIT>':<EOL><INDENT>return _modify(item, underscore)<EOL><DEDENT>

Calls _modify and either passes the inflection.camelize method or the inflection.underscore method.

:param item: dictionary representing item to be modified
:param output: string 'camelized' or 'underscored'
:return:


def call(self, function_expr, **kwargs):

if '<STR_LIT:.>' in function_expr:<EOL><INDENT>tech, service_type, function_name = function_expr.split('<STR_LIT:.>')<EOL><DEDENT>else:<EOL><INDENT>tech = self.conn_details.get('<STR_LIT>')<EOL>service_type = self.conn_details.get('<STR_LIT>', '<STR_LIT>')<EOL>function_name = function_expr<EOL><DEDENT>@sts_conn(tech, service_type=service_type)<EOL>def wrapped_method(function_name, **nargs):<EOL><INDENT>service_type = nargs.pop(nargs.pop('<STR_LIT>', '<STR_LIT>'))<EOL>return getattr(service_type, function_name)(**nargs)<EOL><DEDENT>kwargs.update(self.conn_details)<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>del kwargs['<STR_LIT>']<EOL><DEDENT>return wrapped_method(function_name, **kwargs)<EOL>

cloudaux = CloudAux(
    **{'account_number': '000000000000',
       'assume_role': 'role_name',
       'session_name': 'testing',
       'region': 'us-east-1',
       'tech': 'kms',
       'service_type': 'client'
    })

cloudaux.call("list_aliases")
cloudaux.call("kms.client.list_aliases")


return input.replace(tzinfo=None, microsecond=<NUM_LIT:0>).isoformat() + '<STR_LIT>'<EOL>

Strips out the microseconds from datetime objects, and returns a proper ISO-format UTC string.

    :param input: Datetime object.
    :returns string: A datetime ISO format string with


if '<STR_LIT:.>' in function_expr:<EOL><INDENT>tech, service_type, function_name = function_expr.split('<STR_LIT:.>')<EOL><DEDENT>else:<EOL><INDENT>tech = kwargs.pop('<STR_LIT>')<EOL>service_type = kwargs.get('<STR_LIT>')<EOL>function_name = function_expr<EOL><DEDENT>@sts_conn(tech, service_type=service_type)<EOL>def wrapped_method(function_name, **nargs):<EOL><INDENT>service_type = nargs.pop(nargs.pop('<STR_LIT>', '<STR_LIT>'))<EOL>return getattr(service_type, function_name)(**nargs)<EOL><DEDENT>return wrapped_method(function_name, **kwargs)<EOL>

CloudAux.go(
    'list_aliases',
    **{
        'account_number': '000000000000',
        'assume_role': 'role_name',
        'session_name': 'cloudaux',
        'region': 'us-east-1',
        'tech': 'kms',
        'service_type': 'client'
    })

CloudAux.go(
    'kms.client.list_aliases',
    **{
        'account_number': '000000000000',
        'assume_role': 'role_name',
        'session_name': 'cloudaux',
        'region': 'us-east-1'
    })


def _update_cache_stats(self, key, result):

if result is None:<EOL><INDENT>self._CACHE_STATS['<STR_LIT>'].setdefault(key,<EOL>{'<STR_LIT>': <NUM_LIT:0>, '<STR_LIT>': <NUM_LIT:0>, '<STR_LIT>': <NUM_LIT:0>})<EOL><DEDENT>else:<EOL><INDENT>self._CACHE_STATS['<STR_LIT>'][key][result] +=<NUM_LIT:1><EOL><DEDENT>

Update the cache stats.

If no cache-result is specified, we iniitialize the key.
Otherwise, we increment the correct cache-result.

Note the behavior for expired.  A client can be expired and the key
still exists.


if key in self._CACHE_STATS:<EOL><INDENT>return self._CACHE_STATS['<STR_LIT>'][key]<EOL><DEDENT>else:<EOL><INDENT>return self._CACHE_STATS['<STR_LIT>']<EOL><DEDENT>


def insert(self, key, obj, future_expiration_minutes=<NUM_LIT:15>):

expiration_time = self._calculate_expiration(future_expiration_minutes)<EOL>self._CACHE[key] = (expiration_time, obj)<EOL>return True<EOL>

Insert item into cache.

:param key: key to look up in cache.
:type key: ``object``

:param obj: item to store in cache.
:type obj: varies

:param future_expiration_minutes: number of minutes item is valid
:type param: ``int``

:returns: True
:rtype: ``bool``


def get(self, key, delete_if_expired=True):

self._update_cache_stats(key, None)<EOL>if key in self._CACHE:<EOL><INDENT>(expiration, obj) = self._CACHE[key]<EOL>if expiration > self._now():<EOL><INDENT>self._update_cache_stats(key, '<STR_LIT>')<EOL>return obj<EOL><DEDENT>else:<EOL><INDENT>if delete_if_expired:<EOL><INDENT>self.delete(key)<EOL>self._update_cache_stats(key, '<STR_LIT>')<EOL>return None<EOL><DEDENT><DEDENT><DEDENT>self._update_cache_stats(key, '<STR_LIT>')<EOL>return None<EOL>

Retrieve key from Cache.

:param key: key to look up in cache.
:type key: ``object``

:param delete_if_expired: remove value from cache if it is expired.
                          Default is True.
:type delete_if_expired: ``bool``

:returns: value from cache or None
:rtype: varies or None


details = GOOGLE_CLIENT_MAP.get(service, None)<EOL>if details:<EOL><INDENT>return [details]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Return clients available for this service.

:param service: Google Cloud service name. Examples: 'iam', 'gce'.
:type service: ``str``

:return: list of dictionaries describing the clients available.
:rtype: ``list``


def _gcp_client(project, mod_name, pkg_name, key_file=None, http_auth=None,<EOL>user_agent=None):

client = None<EOL>if http_auth is None:<EOL><INDENT>http_auth = _googleauth(key_file=key_file, user_agent=user_agent)<EOL><DEDENT>try:<EOL><INDENT>google_module = importlib.import_module('<STR_LIT:.>' + mod_name,<EOL>package=pkg_name)<EOL>client = google_module.Client(use_GAX=USE_GAX, project=project,<EOL>http=http_auth)<EOL><DEDENT>except ImportError as ie:<EOL><INDENT>import_err = '<STR_LIT>' % (pkg_name, mod_name)<EOL>raise ImportError(import_err)<EOL><DEDENT>except TypeError:<EOL><INDENT>client = google_module.Client(project=project, http=http_auth)<EOL><DEDENT>if user_agent and hasattr(client, '<STR_LIT>'):<EOL><INDENT>client.user_agent = user_agent<EOL><DEDENT>return client<EOL>

Private GCP client builder.

:param project: Google Cloud project string.
:type project: ``str``

:param mod_name: Module name to load.  Should be found in sys.path.
:type mod_name: ``str``

:param pkg_name: package name that mod_name is part of.  Default is 'google.cloud' .
:type pkg_name: ``str``

:param key_file: Default is None.
:type key_file: ``str`` or None

:param http_auth: httplib2 authorized client. Default is None.
:type http_auth: :class: `HTTPLib2`

:param user_agent: User Agent string to use in requests. Default is None.
:type http_auth: ``str`` or None

:return: GCP client
:rtype: ``object``


return _gcp_client(project=kwargs['<STR_LIT>'], mod_name=kwargs['<STR_LIT>'],<EOL>pkg_name=kwargs.get('<STR_LIT>', '<STR_LIT>'),<EOL>key_file=kwargs.get('<STR_LIT>', None),<EOL>http_auth=kwargs.get('<STR_LIT:http>', None),<EOL>user_agent=kwargs.get('<STR_LIT>', None))<EOL>


def _googleauth(key_file=None, scopes=[], user_agent=None):

if key_file:<EOL><INDENT>if not scopes:<EOL><INDENT>scopes = DEFAULT_SCOPES<EOL><DEDENT>creds = ServiceAccountCredentials.from_json_keyfile_name(key_file,<EOL>scopes=scopes)<EOL><DEDENT>else:<EOL><INDENT>creds = GoogleCredentials.get_application_default()<EOL><DEDENT>http = Http()<EOL>if user_agent:<EOL><INDENT>http = set_user_agent(http, user_agent)<EOL><DEDENT>http_auth = creds.authorize(http)<EOL>return http_auth<EOL>

Google http_auth helper.

If key_file is not specified, default credentials will be used.

If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES

:param key_file: path to key file to use. Default is None
:type key_file: ``str``

:param scopes: scopes to set.  Default is DEFAUL_SCOPES
:type scopes: ``list``

:param user_agent: User Agent string to use in requests. Default is None.
:type http_auth: ``str`` or None

:return: HTTPLib2 authorized client.
:rtype: :class: `HTTPLib2`


return gce_list(service=client.firewalls(),<EOL>**kwargs)<EOL>


bucket = get_bucket(**kwargs)<EOL>if bucket:<EOL><INDENT>return bucket.get_blob(kwargs['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Retrieve object from Bucket.

:param Bucket: name of bucket
:type Bucket: ``str``

:returns: object from bucket or None
:rtype ``object`` or None


bucket = client.lookup_bucket(kwargs['<STR_LIT>'])<EOL>return bucket<EOL>

Get bucket object.

:param client: client object to use.
:type client: Google Cloud Storage client

:returns: Bucket object
:rtype: ``object``


user_agent = kwargs.get('<STR_LIT>', None)<EOL>if not user_agent:<EOL><INDENT>return get_user_agent_default()<EOL><DEDENT>return user_agent<EOL>

If there is a useragent, find it.

Look in the keywords for user_agent. If not found,
return get_user_agent_default


from cloudaux.gcp.decorators import _GCP_STATS<EOL>return _GCP_STATS<EOL>

Retrieve stats, such as function timings.


def service_list(service=None, key_name=None, **kwargs):

resp_list = []<EOL>req = service.list(**kwargs)<EOL>while req is not None:<EOL><INDENT>resp = req.execute()<EOL>if key_name and key_name in resp:<EOL><INDENT>resp_list.extend(resp[key_name])<EOL><DEDENT>else:<EOL><INDENT>resp_list.append(resp)<EOL><DEDENT>if hasattr(service, '<STR_LIT>'):<EOL><INDENT>req = service.list_next(previous_request=req,<EOL>previous_response=resp)<EOL><DEDENT>else:<EOL><INDENT>req = None<EOL><DEDENT><DEDENT>return resp_list<EOL>


from cloudaux.gcp.decorators import _GCP_CACHE<EOL>return _GCP_CACHE.get_access_details(key=key)<EOL>


def gce_list_aggregated(service=None, key_name='<STR_LIT:name>', **kwargs):

resp_list = []<EOL>req = service.aggregatedList(**kwargs)<EOL>while req is not None:<EOL><INDENT>resp = req.execute()<EOL>for location, item in resp['<STR_LIT>'].items():<EOL><INDENT>if key_name in item:<EOL><INDENT>resp_list.extend(item[key_name])<EOL><DEDENT><DEDENT>req = service.aggregatedList_next(previous_request=req,<EOL>previous_response=resp)<EOL><DEDENT>return resp_list<EOL>

General aggregated list function for the GCE service.


def _build_key(func_name, args, kwargs):

return "<STR_LIT>" % (func_name, args, kwargs)<EOL>


def decorator(f):<EOL><INDENT>@wraps(f)<EOL>def decorated_function(*args, **kwargs):<EOL><INDENT>start_time = time.time()<EOL>result = f(*args, **kwargs)<EOL>end_time = time.time()<EOL>strkey = _build_key(f.__name__, args, kwargs)<EOL>_GCP_STATS.setdefault(strkey, []).append(end_time - start_time)<EOL>return result<EOL><DEDENT>return decorated_function<EOL><DEDENT>return decorator<EOL>

Collect stats

Specifically, time function calls
:returns: function response
:rtype: varies


service_account=kwargs.pop('<STR_LIT>')<EOL>kwargs['<STR_LIT:name>'] = service_account<EOL>return service_list(client.projects().serviceAccounts().keys(),<EOL>key_name='<STR_LIT>', **kwargs)<EOL>


service_account=kwargs.pop('<STR_LIT>')<EOL>resp = client.projects().serviceAccounts().get(<EOL>name=service_account).execute()<EOL>return resp<EOL>


def write_backreferences(seen_backrefs, gallery_conf,<EOL>target_dir, fname, snippet):

example_file = os.path.join(target_dir, fname)<EOL>backrefs = scan_used_functions(example_file, gallery_conf)<EOL>for backref in backrefs:<EOL><INDENT>include_path = os.path.join(gallery_conf['<STR_LIT>'],<EOL>'<STR_LIT>' % backref)<EOL>seen = backref in seen_backrefs<EOL>with open(include_path, '<STR_LIT:a>' if seen else '<STR_LIT:w>') as ex_file:<EOL><INDENT>if not seen:<EOL><INDENT>heading = '<STR_LIT>' % backref<EOL>ex_file.write(heading + '<STR_LIT:\n>')<EOL>ex_file.write('<STR_LIT>' * len(heading) + '<STR_LIT:\n>')<EOL><DEDENT>ex_file.write(_thumbnail_div(target_dir, fname, snippet,<EOL>is_backref=True))<EOL>seen_backrefs.add(backref)<EOL><DEDENT><DEDENT>

Writes down back reference files, which include a thumbnail list
    of examples using a certain module


parts = module_name.split('<STR_LIT:.>')<EOL>short_name = module_name<EOL>for i in range(len(parts) - <NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>short_name = '<STR_LIT:.>'.join(parts[:i])<EOL>try:<EOL><INDENT>exec('<STR_LIT>' % (short_name, obj_name))<EOL><DEDENT>except ImportError:<EOL><INDENT>short_name = '<STR_LIT:.>'.join(parts[:(i + <NUM_LIT:1>)])<EOL>break<EOL><DEDENT><DEDENT>return short_name<EOL>


def save_figures(image_path, fig_count, gallery_conf):

figure_list = []<EOL>fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers()<EOL>for fig_mngr in fig_managers:<EOL><INDENT>fig = plt.figure(fig_mngr.num)<EOL>kwargs = {}<EOL>to_rgba = matplotlib.colors.colorConverter.to_rgba<EOL>for attr in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>fig_attr = getattr(fig, '<STR_LIT>' + attr)()<EOL>default_attr = matplotlib.rcParams['<STR_LIT>' + attr]<EOL>if to_rgba(fig_attr) != to_rgba(default_attr):<EOL><INDENT>kwargs[attr] = fig_attr<EOL><DEDENT><DEDENT>current_fig = image_path.format(fig_count + fig_mngr.num)<EOL>fig.savefig(current_fig, **kwargs)<EOL>figure_list.append(current_fig)<EOL><DEDENT>if gallery_conf.get('<STR_LIT>', False):<EOL><INDENT>from mayavi import mlab<EOL>e = mlab.get_engine()<EOL>last_matplotlib_fig_num = len(figure_list)<EOL>total_fig_num = last_matplotlib_fig_num + len(e.scenes)<EOL>mayavi_fig_nums = range(last_matplotlib_fig_num, total_fig_num)<EOL>for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums):<EOL><INDENT>current_fig = image_path.format(mayavi_fig_num)<EOL>mlab.savefig(current_fig, figure=scene)<EOL>scale_image(current_fig, current_fig, <NUM_LIT>, <NUM_LIT>)<EOL>figure_list.append(current_fig)<EOL><DEDENT>mlab.close(all=True)<EOL><DEDENT>return figure_list<EOL>

Save all open matplotlib figures of the example code-block

    Parameters
    ----------
    image_path : str
        Path where plots are saved (format string which accepts figure number)
    fig_count : int
        Previous figure number count. Figure number add from this number

    Returns
    -------
    list of strings containing the full path to each figure


with open(filename) as f:<EOL><INDENT>content = f.read()<EOL><DEDENT>node = ast.parse(content)<EOL>if not isinstance(node, ast.Module):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>".format(node.__class__.__name__))<EOL><DEDENT>if node.body and isinstance(node.body[<NUM_LIT:0>], ast.Expr) andisinstance(node.body[<NUM_LIT:0>].value, ast.Str):<EOL><INDENT>docstring_node = node.body[<NUM_LIT:0>]<EOL>docstring = docstring_node.value.s<EOL>rest = content.split('<STR_LIT:\n>', docstring_node.lineno)[-<NUM_LIT:1>]<EOL>return docstring, rest<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>.format(filename))<EOL><DEDENT>

Separate `filename` content between docstring and the rest

    Strongly inspired from ast.get_docstring.

    Returns
    -------
    docstring: str
        docstring of `filename`
    rest: str
        `filename` content without the docstring


def generate_file_rst(fname, target_dir, src_dir, gallery_conf):

src_file = os.path.join(src_dir, fname)<EOL>example_file = os.path.join(target_dir, fname)<EOL>shutil.copyfile(src_file, example_file)<EOL>image_dir = os.path.join(target_dir, '<STR_LIT>')<EOL>if not os.path.exists(image_dir):<EOL><INDENT>os.makedirs(image_dir)<EOL><DEDENT>base_image_name = os.path.splitext(fname)[<NUM_LIT:0>]<EOL>image_fname = '<STR_LIT>' + base_image_name + '<STR_LIT>'<EOL>image_path = os.path.join(image_dir, image_fname)<EOL>script_blocks = split_code_and_text_blocks(example_file)<EOL>amount_of_code = sum([len(bcontent)<EOL>for blabel, bcontent in script_blocks<EOL>if blabel == '<STR_LIT:code>'])<EOL>if _plots_are_current(example_file, image_path):<EOL><INDENT>return amount_of_code<EOL><DEDENT>time_elapsed = <NUM_LIT:0><EOL>ref_fname = example_file.replace(os.path.sep, '<STR_LIT:_>')<EOL>example_rst = """<STR_LIT>""".format(ref_fname)<EOL>example_nb = Notebook(fname, target_dir)<EOL>filename_pattern = gallery_conf.get('<STR_LIT>')<EOL>if re.search(filename_pattern, src_file) and gallery_conf['<STR_LIT>']:<EOL><INDENT>example_globals = {'<STR_LIT>': '<STR_LIT>'}<EOL>fig_count = <NUM_LIT:0><EOL>is_example_notebook_like = len(script_blocks) > <NUM_LIT:2><EOL>for blabel, bcontent in script_blocks:<EOL><INDENT>if blabel == '<STR_LIT:code>':<EOL><INDENT>code_output, rtime, fig_count = execute_script(bcontent,<EOL>example_globals,<EOL>image_path,<EOL>fig_count,<EOL>src_file,<EOL>gallery_conf)<EOL>time_elapsed += rtime<EOL>example_nb.add_code_cell(bcontent)<EOL>if is_example_notebook_like:<EOL><INDENT>example_rst += codestr2rst(bcontent) + '<STR_LIT:\n>'<EOL>example_rst += code_output<EOL><DEDENT>else:<EOL><INDENT>example_rst += code_output<EOL>example_rst += codestr2rst(bcontent) + '<STR_LIT:\n>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>example_rst += text2string(bcontent) + '<STR_LIT:\n>'<EOL>example_nb.add_markdown_cell(text2string(bcontent))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for blabel, bcontent in script_blocks:<EOL><INDENT>if blabel == '<STR_LIT:code>':<EOL><INDENT>example_rst += codestr2rst(bcontent) + '<STR_LIT:\n>'<EOL>example_nb.add_code_cell(bcontent)<EOL><DEDENT>else:<EOL><INDENT>example_rst += bcontent + '<STR_LIT:\n>'<EOL>example_nb.add_markdown_cell(text2string(bcontent))<EOL><DEDENT><DEDENT><DEDENT>save_thumbnail(image_path, base_image_name, gallery_conf)<EOL>time_m, time_s = divmod(time_elapsed, <NUM_LIT>)<EOL>example_nb.save_file()<EOL>with open(os.path.join(target_dir, base_image_name + '<STR_LIT>'), '<STR_LIT:w>') as f:<EOL><INDENT>example_rst += CODE_DOWNLOAD.format(time_m, time_s, fname,<EOL>example_nb.file_name)<EOL>f.write(example_rst)<EOL><DEDENT>return amount_of_code<EOL>

Generate the rst file for a given example.

        Returns the amout of code (in characters) of the corresponding
        files.


with open(src_file, '<STR_LIT:r>') as src_data:<EOL><INDENT>src_content = src_data.read()<EOL>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>src_content = src_content.encode('<STR_LIT:utf-8>')<EOL><DEDENT>src_md5 = hashlib.md5(src_content).hexdigest()<EOL><DEDENT>return src_md5<EOL>


app.add_config_value('<STR_LIT>', True, '<STR_LIT:html>')<EOL>app.add_config_value('<STR_LIT>', False, '<STR_LIT:html>')<EOL>app.add_config_value('<STR_LIT>', gallery_conf, '<STR_LIT:html>')<EOL>app.add_stylesheet('<STR_LIT>')<EOL>app.connect('<STR_LIT>', generate_gallery_rst)<EOL>app.connect('<STR_LIT>', embed_code_links)<EOL>


try:<EOL><INDENT>plot_gallery = eval(app.builder.config.plot_gallery)<EOL><DEDENT>except TypeError:<EOL><INDENT>plot_gallery = bool(app.builder.config.plot_gallery)<EOL><DEDENT>gallery_conf.update(app.config.sphinx_gallery_conf)<EOL>gallery_conf.update(plot_gallery=plot_gallery)<EOL>gallery_conf.update(abort_on_example_error=app.builder.config.abort_on_example_error)<EOL>app.config.sphinx_gallery_conf = gallery_conf<EOL>app.config.html_static_path.append(glr_path_static())<EOL>clean_gallery_out(app.builder.outdir)<EOL>examples_dirs = gallery_conf['<STR_LIT>']<EOL>gallery_dirs = gallery_conf['<STR_LIT>']<EOL>if not isinstance(examples_dirs, list):<EOL><INDENT>examples_dirs = [examples_dirs]<EOL><DEDENT>if not isinstance(gallery_dirs, list):<EOL><INDENT>gallery_dirs = [gallery_dirs]<EOL><DEDENT>mod_examples_dir = os.path.relpath(gallery_conf['<STR_LIT>'],<EOL>app.builder.srcdir)<EOL>seen_backrefs = set()<EOL>for examples_dir, gallery_dir in zip(examples_dirs, gallery_dirs):<EOL><INDENT>examples_dir = os.path.relpath(examples_dir,<EOL>app.builder.srcdir)<EOL>gallery_dir = os.path.relpath(gallery_dir,<EOL>app.builder.srcdir)<EOL>for workdir in [examples_dir, gallery_dir, mod_examples_dir]:<EOL><INDENT>if not os.path.exists(workdir):<EOL><INDENT>os.makedirs(workdir)<EOL><DEDENT><DEDENT>fhindex = open(os.path.join(gallery_dir, '<STR_LIT>'), '<STR_LIT:w>')<EOL>fhindex.write(generate_dir_rst(examples_dir, gallery_dir, gallery_conf,<EOL>seen_backrefs))<EOL>for directory in sorted(os.listdir(examples_dir)):<EOL><INDENT>if os.path.isdir(os.path.join(examples_dir, directory)):<EOL><INDENT>src_dir = os.path.join(examples_dir, directory)<EOL>target_dir = os.path.join(gallery_dir, directory)<EOL>fhindex.write(generate_dir_rst(src_dir, target_dir,<EOL>gallery_conf,<EOL>seen_backrefs))<EOL><DEDENT><DEDENT>fhindex.flush()<EOL><DEDENT>

Generate the Main examples gallery reStructuredText

    Start the sphinx-gallery configuration and recursively scan the examples
    directories in order to populate the examples gallery


code_cell = {<EOL>"<STR_LIT>": "<STR_LIT:code>",<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": {"<STR_LIT>": False},<EOL>"<STR_LIT>": [],<EOL>"<STR_LIT:source>": [code.strip()]<EOL>}<EOL>self.work_notebook["<STR_LIT>"].append(code_cell)<EOL>

Add a code cell to the notebook

        Parameters
        ----------
        code : str
            Cell content


fname_idx = None<EOL>full_name = cobj['<STR_LIT>'] + '<STR_LIT:.>' + cobj['<STR_LIT:name>']<EOL>if full_name in self._searchindex['<STR_LIT>']:<EOL><INDENT>value = self._searchindex['<STR_LIT>'][full_name]<EOL>if isinstance(value, dict):<EOL><INDENT>value = value[next(iter(value.keys()))]<EOL><DEDENT>fname_idx = value[<NUM_LIT:0>]<EOL><DEDENT>elif cobj['<STR_LIT>'] in self._searchindex['<STR_LIT>']:<EOL><INDENT>value = self._searchindex['<STR_LIT>'][cobj['<STR_LIT>']]<EOL>if cobj['<STR_LIT:name>'] in value.keys():<EOL><INDENT>fname_idx = value[cobj['<STR_LIT:name>']][<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if fname_idx is not None:<EOL><INDENT>fname = self._searchindex['<STR_LIT>'][fname_idx] + '<STR_LIT>'<EOL>if self._is_windows:<EOL><INDENT>fname = fname.replace('<STR_LIT:/>', '<STR_LIT:\\>')<EOL>link = os.path.join(self.doc_url, fname)<EOL><DEDENT>else:<EOL><INDENT>link = posixpath.join(self.doc_url, fname)<EOL><DEDENT>if hasattr(link, '<STR_LIT>'):<EOL><INDENT>link = link.decode('<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL><DEDENT>if link in self._page_cache:<EOL><INDENT>html = self._page_cache[link]<EOL><DEDENT>else:<EOL><INDENT>html = get_data(link, self.gallery_dir)<EOL>self._page_cache[link] = html<EOL><DEDENT>comb_names = [cobj['<STR_LIT>'] + '<STR_LIT:.>' + cobj['<STR_LIT:name>']]<EOL>if self.extra_modules_test is not None:<EOL><INDENT>for mod in self.extra_modules_test:<EOL><INDENT>comb_names.append(mod + '<STR_LIT:.>' + cobj['<STR_LIT:name>'])<EOL><DEDENT><DEDENT>url = False<EOL>if hasattr(html, '<STR_LIT>'):<EOL><INDENT>html = html.decode('<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL><DEDENT>for comb_name in comb_names:<EOL><INDENT>if hasattr(comb_name, '<STR_LIT>'):<EOL><INDENT>comb_name = comb_name.decode('<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL><DEDENT>if comb_name in html:<EOL><INDENT>url = link + u'<STR_LIT:#>' + comb_name<EOL><DEDENT><DEDENT>link = url<EOL><DEDENT>else:<EOL><INDENT>link = False<EOL><DEDENT>return link<EOL>


if url.startswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>resp = urllib.urlopen(url)<EOL>encoding = resp.headers.dict.get('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>resp = urllib.request.urlopen(url)<EOL>encoding = resp.headers.get('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>data = resp.read()<EOL>if encoding == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>elif encoding == '<STR_LIT>':<EOL><INDENT>data = StringIO(data)<EOL>data = gzip.GzipFile(fileobj=data).read()<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>with open(url, '<STR_LIT:r>') as fid:<EOL><INDENT>data = fid.read()<EOL><DEDENT><DEDENT>return data<EOL>

Helper function to get data over http or from a local file


full_name = cobj['<STR_LIT>'] + '<STR_LIT:.>' + cobj['<STR_LIT:name>']<EOL>link = self._link_cache.get(full_name, None)<EOL>if link is None:<EOL><INDENT>link = self._get_link(cobj)<EOL>self._link_cache[full_name] = link<EOL><DEDENT>if link is False or link is None:<EOL><INDENT>return None<EOL><DEDENT>if self.relative:<EOL><INDENT>link = os.path.relpath(link, start=this_url)<EOL>if self._is_windows:<EOL><INDENT>link = link.replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL><DEDENT>link = link[<NUM_LIT:3>:]<EOL><DEDENT>return link<EOL>

Resolve the link to the documentation, returns None if not found

        Parameters
        ----------
        cobj : dict
            Dict with information about the "code object" for which we are
            resolving a link.
            cobi['name'] : function or class name (str)
            cobj['module_short'] : shortened module name (str)
            cobj['module'] : module name (str)
        this_url: str
            URL of the current page. Needed to construct relative URLs
            (only used if relative=True in constructor).

        Returns
        -------
        link : str | None
            The link (URL) to the documentation.


<EOL>if hasattr(searchindex, '<STR_LIT>'):<EOL><INDENT>searchindex = searchindex.decode('<STR_LIT>')<EOL><DEDENT>query = '<STR_LIT>'<EOL>pos = searchindex.find(query)<EOL>if pos < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>sel = _select_block(searchindex[pos:], '<STR_LIT:{>', '<STR_LIT:}>')<EOL>objects = _parse_dict_recursive(sel)<EOL>query = '<STR_LIT>'<EOL>pos = searchindex.find(query)<EOL>if pos < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>filenames = searchindex[pos + len(query) + <NUM_LIT:1>:]<EOL>filenames = filenames[:filenames.find('<STR_LIT:]>')]<EOL>filenames = [f.strip('<STR_LIT:">') for f in filenames.split('<STR_LIT:U+002C>')]<EOL>return filenames, objects<EOL>

Parse a Sphinx search index

    Parameters
    ----------
    searchindex : str
        The Sphinx search index (contents of searchindex.js)

    Returns
    -------
    filenames : list of str
        The file names parsed from the search index.
    objects : dict
        The objects parsed from the search index.


def corrmtx(x_input, m, method='<STR_LIT>'):

valid_methods = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']<EOL>if method not in valid_methods:<EOL><INDENT>raise ValueError("<STR_LIT>" % valid_methods)<EOL><DEDENT>from scipy.linalg import toeplitz<EOL>N = len(x_input)<EOL>if isinstance(x_input, list):<EOL><INDENT>x = numpy.array(x_input)<EOL><DEDENT>else:<EOL><INDENT>x = x_input.copy()<EOL><DEDENT>if x.dtype == complex:<EOL><INDENT>complex_type = True<EOL><DEDENT>else:<EOL><INDENT>complex_type = False<EOL><DEDENT>if method in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>Lp = toeplitz(x[<NUM_LIT:0>:m], [<NUM_LIT:0>]*(m+<NUM_LIT:1>))<EOL><DEDENT>Tp = toeplitz(x[m:N], x[m::-<NUM_LIT:1>])<EOL>if method in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>Up = toeplitz([<NUM_LIT:0>]*(m+<NUM_LIT:1>), numpy.insert(x[N:N-m-<NUM_LIT:1>:-<NUM_LIT:1>],<NUM_LIT:0>,<NUM_LIT:0>))<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>if complex_type == True:<EOL><INDENT>C = numpy.zeros((N+m, m+<NUM_LIT:1>), dtype=complex)<EOL><DEDENT>else:<EOL><INDENT>C = numpy.zeros((N+m, m+<NUM_LIT:1>))<EOL><DEDENT>for i in range(<NUM_LIT:0>, m):<EOL><INDENT>C[i] = Lp[i]<EOL><DEDENT>for i in range(m, N):<EOL><INDENT>C[i] = Tp[i-m]<EOL><DEDENT>for i in range(N, N+m):<EOL><INDENT>C[i] = Up[i-N]<EOL><DEDENT><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>if complex_type == True:<EOL><INDENT>C = numpy.zeros((N, m+<NUM_LIT:1>), dtype=complex)<EOL><DEDENT>else:<EOL><INDENT>C = numpy.zeros((N, m+<NUM_LIT:1>))<EOL><DEDENT>for i in range(<NUM_LIT:0>, m):<EOL><INDENT>C[i] = Lp[i]<EOL><DEDENT>for i in range(m, N):<EOL><INDENT>C[i] = Tp[i-m]<EOL><DEDENT><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>if complex_type == True:<EOL><INDENT>C = numpy.zeros((N, m+<NUM_LIT:1>), dtype=complex)<EOL><DEDENT>else:<EOL><INDENT>C = numpy.zeros((N, m+<NUM_LIT:1>))<EOL><DEDENT>for i in range(<NUM_LIT:0>, N-m):<EOL><INDENT>C[i] = Tp[i]<EOL><DEDENT>for i in range(N-m, N):<EOL><INDENT>C[i] = Up[i-N+m]<EOL><DEDENT><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return Tp<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>if complex_type == True:<EOL><INDENT>C = numpy.zeros((<NUM_LIT:2>*(N-m), m+<NUM_LIT:1>), dtype=complex)<EOL><DEDENT>else:<EOL><INDENT>C = numpy.zeros((<NUM_LIT:2>*(N-m), m+<NUM_LIT:1>))<EOL><DEDENT>for i in range(<NUM_LIT:0>, N-m):<EOL><INDENT>C[i] = Tp[i]<EOL><DEDENT>Tp = numpy.fliplr(Tp.conj())<EOL>for i in range(N-m, <NUM_LIT:2>*(N-m)):<EOL><INDENT>C[i] = Tp[i-N+m]<EOL><DEDENT><DEDENT>return C<EOL>

r"""Correlation matrix

    This function is used by PSD estimator functions. It generates
    the correlation matrix from a correlation data set and a maximum lag.

    :param array x: autocorrelation samples (1D)
    :param int m: the maximum lag

    Depending on the choice of the method, the correlation matrix has different
    sizes, but the number of rows is always m+1.

    Method can be :

    * 'autocorrelation': (default) X is the (n+m)-by-(m+1) rectangular Toeplitz
      matrix derived using prewindowed and postwindowed data.
    * 'prewindowed': X is the n-by-(m+1) rectangular Toeplitz matrix derived
      using prewindowed data only.
    * 'postwindowed': X is the n-by-(m+1) rectangular Toeplitz matrix that
      derived using postwindowed data only.
    * 'covariance': X is the (n-m)-by-(m+1) rectangular Toeplitz matrix
      derived using nonwindowed data.
    * 'modified': X is the 2(n-m)-by-(m+1) modified rectangular Toeplitz
      matrix that generates an autocorrelation estimate for the length n data
      vector x, derived using forward and backward prediction error estimates.

    :return:
        * the autocorrelation matrix
        * R, the (m+1)-by-(m+1) autocorrelation matrix estimate ``R= X'*X``.

    .. rubric:: Algorithm details:

    The **autocorrelation** matrix is a :math:`(N+p) \times (p+1)` rectangular Toeplilz
    data matrix:

    .. math:: X_p = \begin{pmatrix}L_p\\T_p\\Up\end{pmatrix}

    where the lower triangular :math:`p \times (p+1)` matrix :math:`L_p` is

    .. math:: L_p =
        \begin{pmatrix}
        x[1]     &  \cdots     & 0     & 0        \\
        \vdots    &  \ddots     & \vdots & \vdots    \\
        x[p]     &  \cdots     & x[1]  & 0
        \end{pmatrix}

    where the rectangular :math:`(N-p) \times (p+1)` matrix :math:`T_p` is

    .. math:: T_p =
        \begin{pmatrix}
        x[p+1]     &  \cdots    & x[1]        \\
        \vdots    &  \ddots     & \vdots    \\
        x[N-p]     &  \cdots    & x[p+1]        \\
        \vdots    &  \ddots     & \vdots    \\
        x[N]     &  \cdots      & x[N-p]
        \end{pmatrix}

    and where the upper triangular :math:`p \times (p+1)` matrix :math:`U_p` is

    .. math:: U_p =
        \begin{pmatrix}
        0         &  x[N]      & \cdots     & x[N-p+1]        \\
        \vdots    &  \vdots    & \ddots & \vdots    \\
        0         &  0         & \cdots  & x[N]
        \end{pmatrix}

    From this definition, the prewindowed matrix is

    .. math:: X_p = \begin{pmatrix}L_p\\T_p\end{pmatrix}

    the postwindowed matrix is

    .. math:: X_p = \begin{pmatrix}T_p\\U_p\end{pmatrix}

    the covariance matrix is:

    .. math:: X_p = \begin{pmatrix}T_p\end{pmatrix}

    and the modified covariance matrix is:

    .. math:: X_p = \begin{pmatrix}T_p\\T_p^*\end{pmatrix}


def CORRELATION(x, y=None, maxlags=None, norm='<STR_LIT>'):

assert norm in ['<STR_LIT>','<STR_LIT>', '<STR_LIT>', None]<EOL>x = np.array(x)<EOL>if y is None:<EOL><INDENT>y = x<EOL><DEDENT>else:<EOL><INDENT>y = np.array(y)<EOL><DEDENT>N = max(len(x), len(y))<EOL>if len(x) < N:<EOL><INDENT>x = y.copy()<EOL>x.resize(N)<EOL><DEDENT>if len(y) < N:<EOL><INDENT>y = y.copy()<EOL>y.resize(N)<EOL><DEDENT>if maxlags is None:<EOL><INDENT>maxlags = N - <NUM_LIT:1><EOL><DEDENT>assert maxlags < N, '<STR_LIT>'<EOL>realdata = np.isrealobj(x) and np.isrealobj(y)<EOL>if realdata == True:<EOL><INDENT>r = np.zeros(maxlags, dtype=float)<EOL><DEDENT>else:<EOL><INDENT>r = np.zeros(maxlags, dtype=complex)<EOL><DEDENT>if norm == '<STR_LIT>':<EOL><INDENT>rmsx = pylab_rms_flat(x)<EOL>rmsy = pylab_rms_flat(y)<EOL><DEDENT>for k in range(<NUM_LIT:0>, maxlags+<NUM_LIT:1>):<EOL><INDENT>nk = N - k - <NUM_LIT:1><EOL>if realdata == True:<EOL><INDENT>sum = <NUM_LIT:0><EOL>for j in range(<NUM_LIT:0>, nk+<NUM_LIT:1>):<EOL><INDENT>sum = sum + x[j+k] * y[j]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>sum = <NUM_LIT:0.> + <NUM_LIT><EOL>for j in range(<NUM_LIT:0>, nk+<NUM_LIT:1>):<EOL><INDENT>sum = sum + x[j+k] * y[j].conjugate()<EOL><DEDENT><DEDENT>if k == <NUM_LIT:0>:<EOL><INDENT>if norm in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>r0 = sum/float(N)<EOL><DEDENT>elif norm is None:<EOL><INDENT>r0 = sum<EOL><DEDENT>else:<EOL><INDENT>r0 =  <NUM_LIT:1.><EOL><DEDENT><DEDENT>else:<EOL><INDENT>if norm == '<STR_LIT>':<EOL><INDENT>r[k-<NUM_LIT:1>] = sum / float(N-k)<EOL><DEDENT>elif norm == '<STR_LIT>':<EOL><INDENT>r[k-<NUM_LIT:1>] = sum / float(N)<EOL><DEDENT>elif norm is None:<EOL><INDENT>r[k-<NUM_LIT:1>] = sum<EOL><DEDENT>elif norm == '<STR_LIT>':<EOL><INDENT>r[k-<NUM_LIT:1>] =  sum/(rmsx*rmsy)/float(N)<EOL><DEDENT><DEDENT><DEDENT>r = np.insert(r, <NUM_LIT:0>, r0)<EOL>return r<EOL>

r"""Correlation function

    This function should give the same results as :func:`xcorr` but it
    returns the positive lags only. Moreover the algorithm does not use
    FFT as compared to other algorithms.

    :param array x: first data array of length N
    :param array y: second data array of length N. If not specified, computes the
        autocorrelation.
    :param int maxlags: compute cross correlation between [0:maxlags]
        when maxlags is not specified, the range of lags is [0:maxlags].
    :param str norm: normalisation in ['biased', 'unbiased', None, 'coeff']

        * *biased*   correlation=raw/N,
        * *unbiased* correlation=raw/(N-`|lag|`)
        * *coeff*    correlation=raw/(rms(x).rms(y))/N
        * None       correlation=raw

    :return:
        * a numpy.array correlation sequence,  r[1,N]
        * a float for the zero-lag correlation,  r[0]

    The *unbiased* correlation has the form:

    .. math::

        \hat{r}_{xx} = \frac{1}{N-m}T \sum_{n=0}^{N-m-1} x[n+m]x^*[n] T

    The *biased* correlation differs by the front factor only:

    .. math::

        \check{r}_{xx} = \frac{1}{N}T \sum_{n=0}^{N-m-1} x[n+m]x^*[n] T

    with :math:`0\leq m\leq N-1`.

    .. doctest::

        >>> from spectrum import CORRELATION
        >>> x = [1,2,3,4,5]
        >>> res = CORRELATION(x,x, maxlags=0, norm='biased')
        >>> res[0]
        11.0

    .. note:: this function should be replaced by :func:`xcorr`.

    .. seealso:: :func:`xcorr`


def xcorr(x, y=None, maxlags=None, norm='<STR_LIT>'):

N = len(x)<EOL>if y is None:<EOL><INDENT>y = x<EOL><DEDENT>assert len(x) == len(y), '<STR_LIT>'<EOL>if maxlags is None:<EOL><INDENT>maxlags = N-<NUM_LIT:1><EOL>lags = np.arange(<NUM_LIT:0>, <NUM_LIT:2>*N-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>assert maxlags <= N, '<STR_LIT>'<EOL>lags = np.arange(N-maxlags-<NUM_LIT:1>, N+maxlags)<EOL><DEDENT>res = np.correlate(x, y, mode='<STR_LIT>')<EOL>if norm == '<STR_LIT>':<EOL><INDENT>Nf = float(N)<EOL>res = res[lags] / float(N)    <EOL><DEDENT>elif norm == '<STR_LIT>':<EOL><INDENT>res = res[lags] / (float(N)-abs(np.arange(-N+<NUM_LIT:1>, N)))[lags]<EOL><DEDENT>elif norm == '<STR_LIT>':<EOL><INDENT>Nf = float(N)<EOL>rms = pylab_rms_flat(x) * pylab_rms_flat(y)<EOL>res = res[lags] / rms / Nf<EOL><DEDENT>else:<EOL><INDENT>res = res[lags]<EOL><DEDENT>lags = np.arange(-maxlags, maxlags+<NUM_LIT:1>)<EOL>return res, lags<EOL>

Cross-correlation using numpy.correlate

    Estimates the cross-correlation (and autocorrelation) sequence of a random
    process of length N. By default, there is no normalisation and the output
    sequence of the cross-correlation has a length 2*N+1.

    :param array x: first data array of length N
    :param array y: second data array of length N. If not specified, computes the
        autocorrelation.
    :param int maxlags: compute cross correlation between [-maxlags:maxlags]
        when maxlags is not specified, the range of lags is [-N+1:N-1].
    :param str option: normalisation in ['biased', 'unbiased', None, 'coeff']

    The true cross-correlation sequence is

    .. math:: r_{xy}[m] = E(x[n+m].y^*[n]) = E(x[n].y^*[n-m])

    However, in practice, only a finite segment of one realization of the
    infinite-length random process is available.

    The correlation is estimated using numpy.correlate(x,y,'full').
    Normalisation is handled by this function using the following cases:

        * 'biased': Biased estimate of the cross-correlation function
        * 'unbiased': Unbiased estimate of the cross-correlation function
        * 'coeff': Normalizes the sequence so the autocorrelations at zero
           lag is 1.0.

    :return:
        * a numpy.array containing the cross-correlation sequence (length 2*N-1)
        * lags vector

    .. note:: If x and y are not the same length, the shorter vector is
        zero-padded to the length of the longer vector.

    .. rubric:: Examples

    .. doctest::

        >>> from spectrum import xcorr
        >>> x = [1,2,3,4,5]
        >>> c, l = xcorr(x,x, maxlags=0, norm='biased')
        >>> c
        array([ 11.])

    .. seealso:: :func:`CORRELATION`.


if n <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>x = numpy.linspace(lb, ub, n)<EOL>psi = (<NUM_LIT:1.>-x**<NUM_LIT>) * (<NUM_LIT>/(numpy.sqrt(<NUM_LIT>)*pi**<NUM_LIT>)) * numpy.exp(-x**<NUM_LIT:2>/<NUM_LIT>)<EOL>return psi<EOL>

r"""Generate the mexican hat wavelet

    The Mexican wavelet is:

    .. math:: w[x] = \cos{5x}  \exp^{-x^2/2}

    :param lb: lower bound
    :param ub: upper bound
    :param int n: waveform data samples
    :return: the waveform

    .. plot::
        :include-source:
        :width: 80%

        from spectrum import mexican
        from pylab import plot
        plot(mexican(0, 10, 100))


if n <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>x = numpy.linspace(lb, ub, n)<EOL>psi = numpy.cos(<NUM_LIT:5>*x) * numpy.exp(-x**<NUM_LIT:2>/<NUM_LIT>)<EOL>return psi<EOL>

r"""Generate the Morlet waveform

    The Morlet waveform is defined as follows:

    .. math:: w[x] = \cos{5x}  \exp^{-x^2/2}

    :param lb: lower bound
    :param ub: upper bound
    :param int n: waveform data samples

    .. plot::
        :include-source:
        :width: 80%

        from spectrum import morlet
        from pylab import plot
        plot(morlet(0,10,100))


d = abs(len(b)-len(a))<EOL>if d != <NUM_LIT:0>:<EOL><INDENT>if len(a) > len(b):<EOL><INDENT>try:<EOL><INDENT>b.extend([<NUM_LIT:0.>]*d)<EOL><DEDENT>except:<EOL><INDENT>b = np.append(b, [<NUM_LIT:0>]*d)<EOL><DEDENT><DEDENT>elif len(b)>len(a):<EOL><INDENT>try:<EOL><INDENT>a.extend([<NUM_LIT:0.>]*d)<EOL><DEDENT>except:<EOL><INDENT>a = np.append(a, [<NUM_LIT:0>]*d)<EOL><DEDENT><DEDENT>return b,a<EOL><DEDENT>else:<EOL><INDENT>return b,a<EOL><DEDENT>

Given two list or arrays, pad with zeros the shortest array

    :param b: list or array
    :param a: list or array

    .. doctest::

        >>> from spectrum.transfer import eqtflength
        >>> a = [1,2]
        >>> b = [1,2,3,4]
        >>> a, b, = eqtflength(a,b)


import scipy.signal<EOL>b, a = scipy.signal.zpk2tf(z, p, k)<EOL>return b, a<EOL>

r"""Return polynomial transfer function representation from zeros and poles

    :param ndarray z: Zeros of the transfer function.
    :param ndarray p: Poles of the transfer function.
    :param float k: System gain.

    :return:
        b : ndarray Numerator polynomial.
        a : ndarray Numerator and denominator polynomials.

    :func:`zpk2tf` forms transfer function polynomials from the zeros, poles, and gains
    of a system in factored form.

    zpk2tf(z,p,k) finds a rational transfer function

    .. math:: \frac{B(s)}{A(s)} = \frac{b_1 s^{n-1}+\dots b_{n-1}s+b_n}{a_1 s^{m-1}+\dots a_{m-1}s+a_m}

    given a system in factored transfer function form

    .. math:: H(s) = \frac{Z(s)}{P(s)} = k \frac{(s-z_1)(s-z_2)\dots(s-z_m)}{(s-p_1)(s-p_2)\dots(s-p_n)}

    with p being the pole locations, and z the zero locations, with as many.
    The gains for each numerator transfer function are in vector k.
    The zeros and poles must be real or come in complex conjugate pairs.
    The polynomial denominator coefficients are returned in row vector a and
    the polynomial numerator coefficients are returned in matrix b, which has
    as many rows as there are columns of z.

    Inf values can be used as place holders in z if some columns have fewer zeros than others.

    .. note:: wrapper of scipy function zpk2tf


from numpy import bartlett<EOL>return bartlett(N)<EOL>

r"""Bartlett window (wrapping of numpy.bartlett) also known as Fejer

    :param int N: window length

    The Bartlett window is defined as

    .. math:: w(n) = \frac{2}{N-1} \left(
              \frac{N-1}{2} - \left|n - \frac{N-1}{2}\right|
              \right)

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'bartlett')

    .. seealso:: numpy.bartlett, :func:`create_window`, :class:`Window`.


from numpy import hanning<EOL>return hanning(N)<EOL>

r"""Hann window (or Hanning). (wrapping of numpy.bartlett)

    :param int N: window length

    The Hanning window is also known as the Cosine Bell. Usually, it is called
    Hann window, to avoid confusion with the Hamming window.

    .. math:: w(n) =  0.5\left(1- \cos\left(\frac{2\pi n}{N-1}\right)\right)
               \qquad 0 \leq n \leq M-1

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'hanning')

    .. seealso:: numpy.hanning, :func:`create_window`, :class:`Window`.


import scipy.signal<EOL>return scipy.signal.chebwin(N, attenuation)<EOL>

Cheb window

    :param N: window length

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'chebwin', attenuation=50)

    .. seealso:: scipy.signal.chebwin, :func:`create_window`, :class:`Window`


n = linspace(-N/<NUM_LIT>, (N)/<NUM_LIT>, N)<EOL>w = <NUM_LIT:1.>/(<NUM_LIT:1.>+ (alpha*n/(N/<NUM_LIT>))**<NUM_LIT:2>)<EOL>return w<EOL>

r"""Cauchy tapering window

    :param int N: window length
    :param float alpha: parameter of the poisson window

    .. math:: w(n) = \frac{1}{1+\left(\frac{\alpha*n}{N/2}\right)**2}

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'cauchy', alpha=3)
        window_visu(64, 'cauchy', alpha=4)
        window_visu(64, 'cauchy', alpha=5)

    .. seealso:: :func:`window_poisson`, :func:`window_hann`


def window_kaiser(N, beta=<NUM_LIT>, method='<STR_LIT>'):

if N == <NUM_LIT:1>:<EOL><INDENT>return ones(<NUM_LIT:1>)<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>from numpy import kaiser<EOL>return kaiser(N, beta)<EOL><DEDENT>else:<EOL><INDENT>return _kaiser(N, beta)<EOL><DEDENT>

r"""Kaiser window

    :param N: window length
    :param beta: kaiser parameter (default is 8.6)

    To obtain a Kaiser window that designs an FIR filter with
    sidelobe attenuation of :math:`\alpha` dB, use the following :math:`\beta` where
    :math:`\beta = \pi \alpha`.

    .. math::

        w_n = \frac{I_0\left(\pi\alpha\sqrt{1-\left(\frac{2n}{M}-1\right)^2}\right)} {I_0(\pi \alpha)}

    where

      * :math:`I_0` is the zeroth order Modified Bessel function of the first kind.
      * :math:`\alpha` is a real number that determines the shape of the
        window. It determines the trade-off between main-lobe width and side
        lobe level.
      * the length of the sequence is N=M+1.

    The Kaiser window can approximate many other windows by varying
    the :math:`\beta` parameter:

    ===== ========================
    beta  Window shape
    ===== ========================
    0     Rectangular
    5     Similar to a Hamming
    6     Similar to a Hanning
    8.6   Similar to a Blackman
    ===== ========================

    .. plot::
        :width: 80%
        :include-source:

        from pylab import plot, legend, xlim
        from spectrum import window_kaiser
        N = 64
        for beta in [1,2,4,8,16]:
            plot(window_kaiser(N, beta), label='beta='+str(beta))
        xlim(0,N)
        legend()

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'kaiser', beta=8.)

    .. seealso:: numpy.kaiser, :func:`spectrum.window.create_window`


N = len(data)<EOL>return N * np.sum(data**<NUM_LIT:2>) / np.sum(data)**<NUM_LIT:2><EOL>

r"""Computes the equivalent noise bandwidth

    .. math:: ENBW = N \frac{\sum_{n=1}^{N} w_n^2}{\left(\sum_{n=1}^{N} w_n \right)^2}

    .. doctest::

        >>> from spectrum import create_window, enbw
        >>> w = create_window(64, 'rectangular')
        >>> enbw(w)
        1.0

    The following table contains the ENBW values for some of the
    implemented windows in this module (with N=16384). They have been
    double checked against litterature (Source: [Harris]_, [Marple]_).

    If not present, it means that it has not been checked.

    =================== ============ =============
    name                 ENBW        litterature
    =================== ============ =============
    rectangular         1.           1.
    triangle            1.3334       1.33
    Hann                1.5001       1.5
    Hamming             1.3629       1.36
    blackman            1.7268       1.73
    kaiser              1.7
    blackmanharris,4    2.004        2.
    riesz               1.2000       1.2
    riemann             1.32         1.3
    parzen              1.917        1.92
    tukey 0.25          1.102        1.1
    bohman              1.7858       1.79
    poisson 2           1.3130       1.3
    hanningpoisson 0.5  1.609        1.61
    cauchy              1.489        1.48
    lanczos             1.3
    =================== ============ =============


if N == <NUM_LIT:1>:<EOL><INDENT>return ones(<NUM_LIT:1>)<EOL><DEDENT>n = arange(<NUM_LIT:0>, N)<EOL>N1 = N - <NUM_LIT:1.><EOL>w = a0 -a1*cos(<NUM_LIT>*pi*n / N1) + a2*cos(<NUM_LIT>*pi*n / N1) - a3*cos(<NUM_LIT>*pi*n / N1)<EOL>return w<EOL>

a common internal function to some window functions with 4 coeffs

    For the blackmna harris for instance, the results are identical to octave if N is odd
    but not for even values...if n =0 whatever N is, the w(0) must be equal to a0-a1+a2-a3, which
    is the case here, but not in octave...


def plot_frequencies(self, mindB=None, maxdB=None, norm=True):

from pylab import plot, title, xlim, grid, ylim, xlabel, ylabel<EOL>self.compute_response(norm=norm)<EOL>plot(self.frequencies, self.response)<EOL>title("<STR_LIT>" % (self.enbw))<EOL>ylabel('<STR_LIT>')<EOL>xlabel('<STR_LIT>')<EOL>xlim(-<NUM_LIT:0.5>, <NUM_LIT:0.5>)<EOL>y0, y1 = ylim()<EOL>if mindB:<EOL><INDENT>y0 = mindB<EOL><DEDENT>if maxdB is not None:<EOL><INDENT>y1 = maxdB<EOL><DEDENT>else:<EOL><INDENT>y1 = max(self.response)<EOL><DEDENT>ylim(y0, y1)<EOL>grid(True)<EOL>

Plot the window in the frequency domain

        :param mindB: change the default lower y bound
        :param maxdB: change the default upper lower bound
        :param bool norm: if True, normalise the frequency response.

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.plot_frequencies()


a0 = <NUM_LIT><EOL>a1 = <NUM_LIT><EOL>a2 = <NUM_LIT><EOL>a3 = <NUM_LIT><EOL>return _coeff4(N, a0, a1, a2, a3)<EOL>

r"""Blackman Nuttall window

    returns a minimum, 4-term Blackman-Harris window. The window is minimum in the sense that its maximum sidelobes are minimized.
    The coefficients for this window differ from the Blackman-Harris window coefficients and produce slightly lower sidelobes.

    :param N: window length

    .. math:: w(n) = a_0 - a_1 \cos\left(\frac{2\pi n}{N-1}\right)+ a_2 \cos\left(\frac{4\pi n}{N-1}\right)- a_3 \cos\left(\frac{6\pi n}{N-1}\right)

    with :math:`a_0 = 0.3635819`, :math:`a_1 = 0.4891775`, :math:`a_2=0.1365995` and :math:`0_3=.0106411`

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'blackman_nuttall', mindB=-80)

    .. seealso:: :func:`spectrum.window.create_window`
    .. seealso:: :func:`create_window`, :class:`Window`


n = linspace(-N/<NUM_LIT>, (N)/<NUM_LIT>, N)<EOL>w = sin(n/float(N)*<NUM_LIT>*pi) / (n / float(N)*<NUM_LIT>*pi)<EOL>return w<EOL>

r"""Riemann tapering window

    :param int N: window length

    .. math:: w(n) = 1 - \left| \frac{n}{N/2}  \right|^2

    with :math:`-N/2 \leq n \leq N/2`.

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'riesz')

    .. seealso:: :func:`create_window`, :class:`Window`


w1 = window_hann(N)<EOL>w2 = window_poisson(N, alpha=alpha)<EOL>return w1*w2<EOL>

r"""Hann-Poisson tapering window

    This window is constructed as the product of the Hanning and Poisson
    windows. The parameter **alpha** is the Poisson parameter.

    :param int N: window length
    :param float alpha: parameter of the poisson window

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'poisson_hanning', alpha=0.5)
        window_visu(64, 'poisson_hanning', alpha=1)
        window_visu(64, 'poisson_hanning')

    .. seealso:: :func:`window_poisson`, :func:`window_hann`


print(self)<EOL>

Print object information such as length and name


if N == <NUM_LIT:1>:<EOL><INDENT>return ones(<NUM_LIT:1>)<EOL><DEDENT>n = arange(<NUM_LIT:0>, N)<EOL>a0 = <NUM_LIT><EOL>a1 = <NUM_LIT><EOL>a2 = <NUM_LIT><EOL>win = a0 -  a1 *abs(n/(N-<NUM_LIT:1.>)-<NUM_LIT:0.5>) -a2 * cos(<NUM_LIT:2>*pi*n/(N-<NUM_LIT:1.>))<EOL>return win<EOL>

r"""Bartlett-Hann window

    :param N: window length

    .. math:: w(n) = a_0 + a_1 \left| \frac{n}{N-1} -\frac{1}{2}\right| - a_2 \cos \left( \frac{2\pi n}{N-1} \right)

    with :math:`a_0 = 0.62`, :math:`a_1 = 0.48` and :math:`a_2=0.38`

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'bartlett_hann')

    .. seealso:: :func:`create_window`, :class:`Window`


def plot_time_freq(self, mindB=-<NUM_LIT:100>, maxdB=None, norm=True,<EOL>yaxis_label_position="<STR_LIT:right>"):

from pylab import subplot, gca<EOL>subplot(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:1>)<EOL>self.plot_window()<EOL>subplot(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>)<EOL>self.plot_frequencies(mindB=mindB, maxdB=maxdB, norm=norm)<EOL>if yaxis_label_position=="<STR_LIT:left>":<EOL><INDENT>try: tight_layout()<EOL>except: pass<EOL><DEDENT>else:<EOL><INDENT>ax = gca()<EOL>ax.yaxis.set_label_position("<STR_LIT:right>")<EOL><DEDENT>

Plotting method to plot both time and frequency domain results.

        See :meth:`plot_frequencies` for the optional arguments.

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.plot_time_freq()


from scipy.special import iv as besselI<EOL>m = n - <NUM_LIT:1><EOL>k = arange(<NUM_LIT:0>, m)<EOL>k = <NUM_LIT> * beta / m * sqrt (k * (m - k))<EOL>w = besselI (<NUM_LIT:0>, k) / besselI (<NUM_LIT:0>, beta)<EOL>return w<EOL>

Independant Kaiser window

    For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, "Discrete-Time Signal Processing".

    The continuous version of width n centered about x=0 is:

    .. note:: 2 times slower than scipy.kaiser


return ones(N)<EOL>

r"""Kaiser window

    :param N: window length

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'rectangle')


x = linspace(-<NUM_LIT:1>, <NUM_LIT:1>, N)<EOL>w = (<NUM_LIT:1.>-abs(x)) * cos(pi*abs(x)) + <NUM_LIT:1.>/pi * sin(pi*abs(x))<EOL>return w<EOL>

r"""Bohman tapering window

    :param N: window length

    .. math:: w(n) = (1-|x|) \cos (\pi |x|) + \frac{1}{\pi} \sin(\pi |x|)

    where x is a length N vector of linearly spaced values between
    -1 and 1.

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'bohman')

    .. seealso:: :func:`create_window`, :class:`Window`


from pylab import plot, xlim, grid, title, ylabel, axis<EOL>x = linspace(<NUM_LIT:0>, <NUM_LIT:1>, self.N)<EOL>xlim(<NUM_LIT:0>, <NUM_LIT:1>)<EOL>plot(x, self.data)<EOL>grid(True)<EOL>title('<STR_LIT>' % (self.name.capitalize(), self.N))<EOL>ylabel('<STR_LIT>')<EOL>axis([<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT>])<EOL>

Plot the window in the time domain

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.plot_window()


results = rlevinson(poly, efinal)<EOL>return results[<NUM_LIT:0>]<EOL>

Convert prediction filter polynomial to autocorrelation sequence

    :param array poly: the AR parameters
    :param efinal: an estimate of the final error
    :return: the autocorrelation  sequence in complex format.

    .. doctest::

        >>> from numpy import array
        >>> from spectrum import poly2ac
        >>> poly = [ 1. ,  0.38 , -0.05]
        >>> efinal = 4.1895
        >>> poly2ac(poly, efinal)
        array([ 5.00+0.j, -2.00+0.j,  1.01-0.j])


<EOL>a = numpy.array(a)<EOL>if a[<NUM_LIT:0>] != <NUM_LIT:1>:<EOL><INDENT>a/=a[<NUM_LIT:0>]<EOL><DEDENT>if max(numpy.abs(numpy.roots(a))) >= <NUM_LIT:1.0>:<EOL><INDENT>error('<STR_LIT>');<EOL><DEDENT>p  = len(a)-<NUM_LIT:1>   <EOL>a1 = numpy.concatenate((a, numpy.array([<NUM_LIT:0>])))<EOL>a2 = a1[-<NUM_LIT:1>::-<NUM_LIT:1>]<EOL>P1 = a1 - a2        <EOL>Q1 = a1 + a2        <EOL>if p%<NUM_LIT:2>: <EOL><INDENT>P, r = deconvolve(P1,[<NUM_LIT:1>, <NUM_LIT:0> ,-<NUM_LIT:1>])<EOL>Q = Q1<EOL><DEDENT>else:          <EOL><INDENT>P, r = deconvolve(P1, [<NUM_LIT:1>, -<NUM_LIT:1>])<EOL>Q, r = deconvolve(Q1, [<NUM_LIT:1>,  <NUM_LIT:1>])<EOL><DEDENT>rP  = numpy.roots(P)<EOL>rQ  = numpy.roots(Q)<EOL>aP  = numpy.angle(rP[<NUM_LIT:1>::<NUM_LIT:2>])<EOL>aQ  = numpy.angle(rQ[<NUM_LIT:1>::<NUM_LIT:2>])<EOL>lsf = sorted(numpy.concatenate((-aP,-aQ)))<EOL>return lsf<EOL>

Prediction polynomial to line spectral frequencies.

    converts the prediction polynomial specified by A,
    into the corresponding line spectral frequencies, LSF.
    normalizes the prediction polynomial by A(1).

    .. doctest::

        >>> from spectrum import poly2lsf
        >>> a = [1.0000,  0.6149, 0.9899, 0.0000 ,0.0031, -0.0082]
        >>> lsf = poly2lsf(a)
        >>> lsf =  array([0.7842, 1.5605, 1.8776, 1.8984, 2.3593])

    .. seealso:: lsf2poly, poly2rc, poly2qc, rc2is


assert numpy.isrealobj(g), '<STR_LIT>'<EOL>return -numpy.tanh(-numpy.array(g)/<NUM_LIT:2>)<EOL>

Convert log area ratios to reflection coefficients.

    :param g:  log area ratios
    :returns: the reflection coefficients

    .. seealso: :func:`rc2lar`, :func:`poly2rc`, :func:`ac2rc`, :func:`is2rc`.

    :References:
       [1] J. Makhoul, "Linear Prediction: A Tutorial Review," Proc. IEEE,  Vol.63, No.4, pp.561-580, Apr 1975.


assert numpy.isrealobj(k), '<STR_LIT>'<EOL>if max(numpy.abs(k)) >= <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return (<NUM_LIT:2>/numpy.pi)*numpy.arcsin(k)<EOL>

Convert reflection coefficients to inverse sine parameters.

    :param k: reflection coefficients
    :return: inverse sine parameters

    .. seealso:: :func:`is2rc`, :func:`rc2poly`, :func:`rc2acC`, :func:`rc2lar`.

    Reference: J.R. Deller, J.G. Proakis, J.H.L. Hansen, "Discrete-Time
       Processing of Speech Signals", Prentice Hall, Section 7.4.5.


<EOL>lsf = numpy.array(lsf)<EOL>if max(lsf) > numpy.pi or min(lsf) < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>p = len(lsf) <EOL>z  = numpy.exp(<NUM_LIT> * lsf)<EOL>rQ = z[<NUM_LIT:0>::<NUM_LIT:2>]<EOL>rP = z[<NUM_LIT:1>::<NUM_LIT:2>]<EOL>rQ = numpy.concatenate((rQ, rQ.conjugate()))<EOL>rP = numpy.concatenate((rP, rP.conjugate()))<EOL>Q  = numpy.poly(rQ);<EOL>P  = numpy.poly(rP);<EOL>if p%<NUM_LIT:2>:<EOL><INDENT>P1 = numpy.convolve(P, [<NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>])<EOL>Q1 = Q<EOL><DEDENT>else:<EOL><INDENT>P1 = numpy.convolve(P, [<NUM_LIT:1>, -<NUM_LIT:1>])<EOL>Q1 = numpy.convolve(Q, [<NUM_LIT:1>,  <NUM_LIT:1>])<EOL><DEDENT>a = <NUM_LIT> * (P1+Q1)<EOL>return a[<NUM_LIT:0>:-<NUM_LIT:1>:<NUM_LIT:1>]<EOL>

Convert line spectral frequencies to prediction filter coefficients

    returns a vector a containing the prediction filter coefficients from a vector lsf of line spectral frequencies.

    .. doctest::

        >>> from spectrum import lsf2poly
        >>> lsf = [0.7842 ,   1.5605  ,  1.8776 ,   1.8984,    2.3593]
        >>> a = lsf2poly(lsf)

    # array([  1.00000000e+00,   6.14837835e-01,   9.89884967e-01,
    # 9.31594056e-05,   3.13713832e-03,  -8.12002261e-03 ])

    .. seealso:: poly2lsf, rc2poly, ac2poly, rc2is


assert numpy.isrealobj(k), '<STR_LIT>'<EOL>if max(numpy.abs(k)) >= <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return -<NUM_LIT:2> * numpy.arctanh(-numpy.array(k))<EOL>

Convert reflection coefficients to log area ratios.

    :param k: reflection coefficients
    :return: inverse sine parameters

    The log area ratio is defined by G = log((1+k)/(1-k)) , where the K
    parameter is the reflection coefficient.

    .. seealso:: :func:`lar2rc`, :func:`rc2poly`, :func:`rc2ac`, :func:`rc2ic`.

    :References:
       [1] J. Makhoul, "Linear Prediction: A Tutorial Review," Proc. IEEE, Vol.63, No.4, pp.561-580, Apr 1975.


return numpy.sin(numpy.array(inv_sin)*numpy.pi/<NUM_LIT:2>)<EOL>

Convert inverse sine parameters to reflection coefficients.

    :param inv_sin: inverse sine parameters
    :return: reflection coefficients

    .. seealso::  :func:`rc2is`, :func:`poly2rc`, :func:`ac2rc`, :func:`lar2rc`.

    :Reference: J.R. Deller, J.G. Proakis, J.H.L. Hansen,
        "Discrete-Time Processing of Speech Signals", Prentice Hall, Section 7.4.5.


<EOL>self.__name = None<EOL>self.name = name<EOL>self.__N = N<EOL>self.__rho = <NUM_LIT:0><EOL>self.__k = None<EOL>self.__old_data = None<EOL>self.__data = None<EOL>self.__norm = True<EOL>

Create a criteria object

        :param name: a string or list of strings containing valid criteria
            method's name
        :param int N: size of the data sample.


from numpy import log<EOL>mdl = N* log(rho) + k * log(N)<EOL>return mdl<EOL>

r"""Minimum Description Length

    .. math:: MDL(k) = N log \rho_k + p \log N

    :validation: results


from numpy import log, array<EOL>p = k  <EOL>res = log(rho) + <NUM_LIT> * (p+<NUM_LIT:1>) / (N-p-<NUM_LIT:2>)<EOL>return res<EOL>

r"""corrected Akaike information criterion

    .. math:: AICc(k) = log(\rho_k) + 2 \frac{k+1}{N-k-2}

    :validation: double checked versus octave.


import numpy as np<EOL>kmdl = []<EOL>n = len(s)<EOL>for k in range(<NUM_LIT:0>, n-<NUM_LIT:1>):<EOL><INDENT>ak = <NUM_LIT:1.>/(n-k) * np.sum(s[k+<NUM_LIT:1>:])<EOL>gk = np.prod(s[k+<NUM_LIT:1>:]**(<NUM_LIT:1.>/(n-k)))<EOL>kmdl.append( -(n-k)*N * np.log(gk/ak) + <NUM_LIT:0.5>*k*(<NUM_LIT>*n-k)*np.log(N))<EOL><DEDENT>return kmdl<EOL>

r"""MDL order-selection using eigen values

    :param s: a list of `p` sorted eigen values
    :param N: the size of the input data. To be defined precisely.

    :return:
        * an array containing the AIC values

    .. math:: MDL(k) = (n-k)N \ln \frac{g(k)}{a(k)} + 0.5k(2n-k) log(N)

    .. seealso:: :func:`aic_eigen` for details

    :References:
        * [Marple]_ Chap 13,
        * [Wax]_


from numpy import zeros, arange<EOL>cat = zeros(len(rho))<EOL>for p in arange(<NUM_LIT:1>, len(rho)+<NUM_LIT:1>):<EOL><INDENT>rho_p = float(N)/(N-p)*rho[p-<NUM_LIT:1>]<EOL>s = <NUM_LIT:0><EOL>for j in range(<NUM_LIT:1>, p+<NUM_LIT:1>):<EOL><INDENT>rho_j = float(N)/(N-j)*rho[j-<NUM_LIT:1>]<EOL>s = s + <NUM_LIT:1.>/rho_j<EOL><DEDENT>cat[p-<NUM_LIT:1>] = s/float(N) - <NUM_LIT:1.>/rho_p<EOL><DEDENT>return cat<EOL>

r"""Criterion Autoregressive Transfer Function :

    .. math::  CAT(k) = \frac{1}{N} \sum_{i=1}^k \frac{1}{\rho_i} - \frac{\rho_i}{\rho_k}

    .. todo:: validation


from numpy import log, array<EOL>p = k<EOL>res = log(rho) + p/N/(N-p) + (<NUM_LIT>-(p+<NUM_LIT>)/N) * (p+<NUM_LIT:1.>) / (N-p-<NUM_LIT>)<EOL>return res<EOL>

r"""approximate corrected Kullback information

    .. math:: AKICc(k) = log(rho_k) + \frac{p}{N*(N-k)} + (3-\frac{k+2}{N})*\frac{k+1}{N-k-2}


def __call__(self, rho=None, k=None, N=None, norm=True):

self.__norm = norm<EOL>if N is not None:<EOL><INDENT>self.N = N<EOL><DEDENT>if rho is not None:<EOL><INDENT>self.rho = rho<EOL><DEDENT>if k is not None:<EOL><INDENT>self.__k = k<EOL><DEDENT>self.__norm = norm<EOL>f = eval(self.name)<EOL>self.data = f(self.N, self.rho, self.k)<EOL>if self.old_data is not None and self.data is not None:<EOL><INDENT>if self.data > self.old_data:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return True<EOL>

Call the criteria function correspondign to :attr:`name`.


def __init__(self, data, sampling=<NUM_LIT:1.>, ar_order=None, ma_order=None,<EOL>lag=-<NUM_LIT:1>, NFFT=None, detrend=None, scale_by_freq=True):

super(ParametricSpectrum, self).__init__(data, sampling=sampling,<EOL>NFFT=NFFT,<EOL>scale_by_freq=scale_by_freq,<EOL>detrend=detrend)<EOL>if ar_order is None and ma_order is None:<EOL><INDENT>raise errors.SpectrumARMAError<EOL><DEDENT>self.__ar_order = ar_order<EOL>self.__ma_order = ma_order<EOL>self.ar_order = ar_order<EOL>self.ma_order = ma_order<EOL>self.lag = lag<EOL>self.__ar = None<EOL>self.__ma = None<EOL>self.__reflection = None<EOL>self.__rho = None<EOL>

**Constructor**

        See the class documentation for the parameters.

        .. rubric:: Additional attributes to those inherited
            from :class:`Spectrum`:

        * :attr:`ar_order`, the ar order of the PSD estimates
        * :attr:`ma_order`, the ar order of the PSD estimates


return list(self.centerdc_gen())<EOL>

Return the two-sided frequency range as a list (see
        :meth:`centerdc_gen` for details).


def __init__(self, data, data_y=None, sampling=<NUM_LIT:1.>,<EOL>detrend=None, scale_by_freq=True, NFFT=None):

<EOL>self.__data = None<EOL>self.__data_y = None<EOL>self.__sampling = None<EOL>self.__detrend = None<EOL>self.__scale_by_freq = None<EOL>self.__sides = None<EOL>self.__N = None<EOL>self.__NFFT = None<EOL>self.__df = None<EOL>self.__datatype = None<EOL>self.__psd = None<EOL>self.__method = None<EOL>self.data = data<EOL>if data_y is not None:<EOL><INDENT>self.data_y = data_y<EOL><DEDENT>self.sampling = sampling<EOL>self.sides = '<STR_LIT:default>'<EOL>self._range = Range(self.__data.size, sampling) <EOL>self.modified = True<EOL>self.sampling = sampling<EOL>self.scale_by_freq = scale_by_freq<EOL>self.NFFT = NFFT<EOL>self.method = self.__class__<EOL>

**Constructor**

        .. rubric:: Attributes:

        From the input parameters, the following attributes are set:

          * :attr:`data` (updates :attr:`N`, :attr:`df`, :attr:`datatype`)
          * :attr:`data_y` used for cross PSD only (correlogram)
          * :attr:`detrend`
          * :attr:`sampling` (updates :attr:`df`)
          * :attr:`scale_by_freq`
          * :attr:`NFFT` (reset :attr:`sides`, :attr:`df`)

        The following read-only attributes are set during the initialisation:

          * :attr:`datatype`
          * :attr:`df`
          * :attr:`N`

        And finally, additional read-write attributes are available:

          * :attr:`psd`: used to store the PSD data array, which size depends
            on :attr:`sides` i.e., one-sided for real data and two-sided for
            the complex data.
          * :attr:`sides`: if set, changed the :attr:`psd`.


if sides == self.sides:<EOL><INDENT>return self.__psd<EOL><DEDENT>if self.datatype == '<STR_LIT>':<EOL><INDENT>assert sides != '<STR_LIT>',"<STR_LIT>"<EOL><DEDENT>if self.sides == '<STR_LIT>':<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>if sides == '<STR_LIT>':<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>newpsd = numpy.concatenate((self.psd[<NUM_LIT:0>:-<NUM_LIT:1>]/<NUM_LIT>, list(reversed(self.psd[<NUM_LIT:0>:-<NUM_LIT:1>]/<NUM_LIT>))))<EOL>newpsd[-<NUM_LIT:1>] = self.psd[-<NUM_LIT:1>]<EOL>newpsd[<NUM_LIT:0>] *= <NUM_LIT><EOL><DEDENT>elif sides == '<STR_LIT>':<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>P0 = self.psd[<NUM_LIT:0>]<EOL>P1 = self.psd[-<NUM_LIT:1>]<EOL>newpsd = numpy.concatenate((self.psd[-<NUM_LIT:1>:<NUM_LIT:0>:-<NUM_LIT:1>]/<NUM_LIT>, self.psd[<NUM_LIT:0>:-<NUM_LIT:1>]/<NUM_LIT>))<EOL>newpsd[<NUM_LIT:0>] = P1<EOL><DEDENT><DEDENT>elif self.sides == '<STR_LIT>':<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>if sides == '<STR_LIT>':<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>midN = (len(self.psd)-<NUM_LIT:2>) / <NUM_LIT:2><EOL>newpsd = numpy.array(self.psd[<NUM_LIT:0>:int(midN)+<NUM_LIT:2>]*<NUM_LIT:2>)<EOL>newpsd[<NUM_LIT:0>] /= <NUM_LIT:2><EOL>newpsd[-<NUM_LIT:1>] = self.psd[-<NUM_LIT:1>]<EOL><DEDENT>elif sides == '<STR_LIT>':<EOL><INDENT>newpsd = stools.twosided_2_centerdc(self.psd)<EOL><DEDENT><DEDENT>elif self.sides == '<STR_LIT>': <EOL><INDENT>logging.debug('<STR_LIT>')<EOL>if sides == '<STR_LIT>':<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>midN = int(len(self.psd) / <NUM_LIT:2>)<EOL>P1 = self.psd[<NUM_LIT:0>]<EOL>newpsd = numpy.append(self.psd[midN:]*<NUM_LIT:2>, P1)<EOL><DEDENT>elif sides == '<STR_LIT>':<EOL><INDENT>newpsd = stools.centerdc_2_twosided(self.psd)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return newpsd<EOL>

This function returns the PSD in the **sides** format

        :param str sides: the PSD format in ['onesided', 'twosided', 'centerdc']
        :return: the expected PSD.

        .. doctest::

            from spectrum import *
            p = pcovar(marple_data, 15)
            centerdc_psd = p.get_converted_psd('centerdc')

        .. note:: this function does not change the object, in particular, it
            does not change the :attr:`psd` attribute. If you want to change
            the psd on the fly, change the attribute :attr:`sides`.


<EOL>if sides is None:<EOL><INDENT>sides = self.sides<EOL><DEDENT>if sides not in self._sides_choices:<EOL><INDENT>raise errors.SpectrumChoiceError(sides, self._sides_choices)<EOL><DEDENT>if sides == '<STR_LIT>':<EOL><INDENT>return self._range.onesided()<EOL><DEDENT>if sides == '<STR_LIT>':<EOL><INDENT>return self._range.twosided()<EOL><DEDENT>if sides == '<STR_LIT>':<EOL><INDENT>return self._range.centerdc()<EOL><DEDENT>

Return the frequency vector according to :attr:`sides`


for a in range(<NUM_LIT:0>, self.N):<EOL><INDENT>yield a * self.df<EOL><DEDENT>

Returns the twosided frequency range as a generator

        ::

            >>> print(list(Range(8).centerdc_gen()))
            [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]


def plot(self, filename=None, norm=False, ylim=None,<EOL>sides=None,  **kargs):

import pylab<EOL>from pylab import ylim as plt_ylim<EOL>_ = self.psd<EOL>if sides is not None:<EOL><INDENT>if sides not in self._sides_choices:<EOL><INDENT>raise errors.SpectrumChoiceError(sides, self._sides_choices)<EOL><DEDENT><DEDENT>if sides is None or sides == self.sides:<EOL><INDENT>frequencies = self.frequencies()<EOL>psd = self.psd<EOL>sides = self.sides<EOL><DEDENT>elif sides is not None:<EOL><INDENT>if self.datatype == '<STR_LIT>':<EOL><INDENT>if sides == '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>logging.debug("<STR_LIT>")<EOL>frequencies = self.frequencies(sides=sides)<EOL>psd = self.get_converted_psd(sides)<EOL><DEDENT>if len(psd) != len(frequencies):<EOL><INDENT>raise ValueError("<STR_LIT>" % (len(psd), len(frequencies)))<EOL><DEDENT>if '<STR_LIT>' in list(kargs.keys()):<EOL><INDENT>save_ax = pylab.gca()<EOL>pylab.sca(kargs['<STR_LIT>'])<EOL>rollback = True<EOL>del kargs['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>rollback = False<EOL><DEDENT>if norm:<EOL><INDENT>pylab.plot(frequencies, <NUM_LIT:10> * stools.log10(psd/max(psd)),  **kargs)<EOL><DEDENT>else:<EOL><INDENT>pylab.plot(frequencies, <NUM_LIT:10> * stools.log10(psd),**kargs)<EOL><DEDENT>pylab.xlabel('<STR_LIT>')<EOL>pylab.ylabel('<STR_LIT>')<EOL>pylab.grid(True)<EOL>if ylim:<EOL><INDENT>plt_ylim(ylim)<EOL><DEDENT>if sides == '<STR_LIT>':<EOL><INDENT>pylab.xlim(<NUM_LIT:0>, self.sampling/<NUM_LIT>)<EOL><DEDENT>elif sides == '<STR_LIT>':<EOL><INDENT>pylab.xlim(<NUM_LIT:0>, self.sampling)<EOL><DEDENT>elif sides == '<STR_LIT>':<EOL><INDENT>pylab.xlim(-self.sampling/<NUM_LIT>, self.sampling/<NUM_LIT>)<EOL><DEDENT>if filename:<EOL><INDENT>pylab.savefig(filename)<EOL><DEDENT>if rollback:<EOL><INDENT>pylab.sca(save_ax)<EOL><DEDENT>del psd, frequencies<EOL>

a simple plotting routine to plot the PSD versus frequency.

        :param str filename: save the figure into a file
        :param norm: False by default. If True, the PSD is normalised.
        :param ylim: readjust the y range .
        :param sides: if not provided, :attr:`sides` is used. See :attr:`sides`
            for details.
        :param kargs: any optional argument accepted by :func:`pylab.plot`.

        .. plot::
            :width: 80%
            :include-source:

            from spectrum import *
            p = Periodogram(marple_data)
            p.plot(norm=True, marker='o')


assert len(x) >= order, "<STR_LIT>"<EOL>x = np.array(x)<EOL>N = len(x)<EOL>r0 = sum(abs(x)**<NUM_LIT>)<EOL>r1 = abs(x[<NUM_LIT:0>])**<NUM_LIT:2><EOL>rN = abs(x[N-<NUM_LIT:1>])**<NUM_LIT:2><EOL>pf = r0 - r1<EOL>pb = r0 - rN<EOL>delta = <NUM_LIT:1.> - r1 / r0<EOL>gamma = <NUM_LIT:1.> - rN / r0<EOL>c = np.zeros(N, dtype=complex)<EOL>d = np.zeros(N, dtype=complex)<EOL>r = np.zeros(N, dtype=complex)<EOL>af = np.zeros(N, dtype=complex)<EOL>ab = np.zeros(N, dtype=complex)<EOL>c[<NUM_LIT:0>] = x[N-<NUM_LIT:1>].conjugate() / r0<EOL>d[<NUM_LIT:0>] = x[<NUM_LIT:0>].conjugate() / r0<EOL>if order == <NUM_LIT:0>:<EOL><INDENT>pf = r0 / float(N)<EOL>pb = pf<EOL>return af, pf, ab, pb, <NUM_LIT:0><EOL><DEDENT>pbv = []<EOL>for m in range(<NUM_LIT:0>, order+<NUM_LIT:1>):<EOL><INDENT>logging.debug('<STR_LIT>', m)<EOL>logging.debug(c[<NUM_LIT:0>:<NUM_LIT:2>])<EOL>logging.debug(d[<NUM_LIT:0>:<NUM_LIT:2>])<EOL>r1 = <NUM_LIT:1.>/pf<EOL>r2 = <NUM_LIT:1.>/pb<EOL>r3 = <NUM_LIT:1.>/delta<EOL>r4 = <NUM_LIT:1.>/gamma<EOL>temp = <NUM_LIT:0.>+<NUM_LIT><EOL>for k in range(m+<NUM_LIT:1>, N):<EOL><INDENT>temp = temp + x[k]*x[k-m-<NUM_LIT:1>].conjugate()<EOL><DEDENT>r[m] =  temp.conjugate()<EOL>theta = x[<NUM_LIT:0>] * c[m]<EOL>if m == <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>for k in range(<NUM_LIT:0>, m):<EOL><INDENT>theta = theta + x[m-k] * c[k]                   <EOL>r[k] = r[k] - x[N-m-<NUM_LIT:1>] * x[N-m+k].conjugate() <EOL>temp = temp + af[m-k-<NUM_LIT:1>] * r[k].conjugate()<EOL><DEDENT><DEDENT>"""<STR_LIT>"""<EOL>c1 = -temp * r2<EOL>c2 = -r1 * temp.conjugate()<EOL>c3 = theta * r3<EOL>c4 = r4 *theta.conjugate()<EOL>af[m] = c1                    <EOL>ab[m] = c2                    <EOL>save = c[m]<EOL>c[m] = save + c3*d[m]<EOL>d[m] = d[m] + c4*save<EOL>if m == <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>for k in range(<NUM_LIT:0>, m):<EOL><INDENT>save = af[k]<EOL>af[k] = save + c1 * ab[m-k-<NUM_LIT:1>] <EOL>ab[m-k-<NUM_LIT:1>] = ab[m-k-<NUM_LIT:1>] + c2 * save   <EOL>save = c[k]<EOL>c[k] = save + c3*d[k]       <EOL>d[k] = d[k] + c4*save       <EOL><DEDENT><DEDENT>r5 = temp.real**<NUM_LIT:2> + temp.imag**<NUM_LIT:2><EOL>pf = pf - r5*r2         <EOL>pb = pb - r5*r1         <EOL>r5 = theta.real**<NUM_LIT:2> + theta.imag**<NUM_LIT:2><EOL>delta = delta - r5*r4               <EOL>gamma = gamma - r5*r3               <EOL>if m != order-<NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>pf = pf / float(N-m-<NUM_LIT:1>)<EOL>pb = pb / float(N-m-<NUM_LIT:1>)<EOL>break<EOL><DEDENT>if pf > <NUM_LIT:0> and pb > <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>ValueError("<STR_LIT>")<EOL><DEDENT>if (delta > <NUM_LIT:0.> and delta <=<NUM_LIT:1> and gamma > <NUM_LIT:0.> and gamma <=<NUM_LIT:1>):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>ValueError("<STR_LIT>")<EOL><DEDENT>r1 = <NUM_LIT:1.>/pf<EOL>r2 = <NUM_LIT:1.>/pb<EOL>r3 = <NUM_LIT:1.>/delta<EOL>r4 = <NUM_LIT:1.>/gamma<EOL>ef = x[m+<NUM_LIT:1>]<EOL>eb = x[(N-<NUM_LIT:1>)-m-<NUM_LIT:1>]<EOL>for k in range(<NUM_LIT:0>,m+<NUM_LIT:1>):<EOL><INDENT>ef = ef + af[k] * x[m-k]             <EOL>eb = eb + ab[k] * x[N-m+k-<NUM_LIT:1>]                   <EOL><DEDENT>c1 = ef*r3<EOL>c2 = eb*r4<EOL>c3 = eb.conjugate() * r2<EOL>c4 = ef.conjugate() * r1<EOL>for k in range(m, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>save = af[k]<EOL>af[k] = save + c1 * d[k]                    <EOL>d[k+<NUM_LIT:1>] = d[k] + c4 * save                    <EOL>save = ab[k]<EOL>ab[k] = save + c2 * c[m-k]                 <EOL>c[m-k] = c[m-k] + c3 * save              <EOL><DEDENT>c[m+<NUM_LIT:1>] = c3<EOL>d[<NUM_LIT:0>] = c4<EOL>r5 = ef.real**<NUM_LIT:2> + ef.imag**<NUM_LIT:2><EOL>pf = pf - r5 * r3                              <EOL>delta = delta-r5 * r1                        <EOL>r5 = eb.real**<NUM_LIT:2> + eb.imag**<NUM_LIT:2><EOL>pb = pb - r5 * r4                              <EOL>gamma = gamma-r5*r2                        <EOL>pbv.append(pb)<EOL>if (pf > <NUM_LIT:0.> and pb > <NUM_LIT:0.>):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>ValueError("<STR_LIT>")<EOL><DEDENT>if (delta > <NUM_LIT:0.> and delta <= <NUM_LIT:1.>) and (gamma > <NUM_LIT:0.> and gamma <= <NUM_LIT:1.>):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return af, pf, ab, pb, pbv<EOL>

r"""Estimate AR model parameters using covariance method

    This implementation is based on [Marple]_. This code is far more
    complicated and slower than :func:`arcovar` function, which is now the official version.
    See :func:`arcovar` for a detailed description of Covariance method.

    This function should be used in place of arcovar only if order<=4, for
    which :func:`arcovar` does not work.

    Fast algorithm for the solution of the covariance least squares normal
    equations from Marple.

    :param array X:  Array of complex data samples
    :param int oder: Order of linear prediction model

    :return:
        * AF   - Array of complex forward linear prediction coefficients
        * PF   - Real forward linear prediction variance at order IP
        * AB   - Array of complex backward linear prediction coefficients
        * PB   - Real backward linear prediction variance at order IP
        * PV   - store linear prediction coefficients

    .. note:: this code and the original code in Marple diverge for ip>10.
        it seems that this is related to single precision used with
        complex type in fortran whereas numpy uses double precision for
        complex type.

    :validation: the AR parameters are the same as those returned by
        a completely different function :func:`arcovar`.

    :References: [Marple]_


from spectrum import corrmtx<EOL>import scipy.linalg<EOL>X = corrmtx(x, order, '<STR_LIT>')<EOL>Xc = np.matrix(X[:, <NUM_LIT:1>:])<EOL>X1 = np.array(X[:, <NUM_LIT:0>])<EOL>a, _residues, _rank, _singular_values = scipy.linalg.lstsq(-Xc, X1)<EOL>Cz = np.dot(X1.conj().transpose(), Xc)<EOL>e = np.dot(X1.conj().transpose(), X1) + np.dot(Cz, a)<EOL>assert e.imag < <NUM_LIT>, '<STR_LIT>'<EOL>e = float(e.real) <EOL>return a, e<EOL>

r"""Simple and fast implementation of the covariance AR estimate

    This code is 10 times faster than :func:`arcovar_marple` and more importantly
    only 10 lines of code, compared to a 200 loc for :func:`arcovar_marple`

    :param array X:  Array of complex data samples
    :param int oder: Order of linear prediction model

    :return:
        * a - Array of complex forward linear prediction coefficients
        * e - error

    The covariance method fits a Pth order autoregressive (AR) model to the
    input signal, which is assumed to be the output of
    an AR system driven by white noise. This method minimizes the forward
    prediction error in the least-squares sense. The output vector
    contains the normalized estimate of the AR system parameters

    The white noise input variance estimate is also returned.

    If is the power spectral density of y(n), then:

    .. math:: \frac{e}{\left| A(e^{jw}) \right|^2} = \frac{e}{\left| 1+\sum_{k-1}^P a(k)e^{-jwk}\right|^2}

    Because the method characterizes the input data using an all-pole model,
    the correct choice of the model order p is important.

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import arcovar, marple_data, arma2psd
        from pylab import plot, log10, linspace, axis

        ar_values, error = arcovar(marple_data, 15)
        psd = arma2psd(ar_values, sides='centerdc')
        plot(linspace(-0.5, 0.5, len(psd)), 10*log10(psd/max(psd)))
        axis([-0.5, 0.5, -60, 0])

    .. seealso:: :class:`pcovar`

    :validation: the AR parameters are the same as those returned by
        a completely different function :func:`arcovar_marple`.

    :References: [Mathworks]_


def speriodogram(x, NFFT=None, detrend=True, sampling=<NUM_LIT:1.>,<EOL>scale_by_freq=True, window='<STR_LIT>', axis=<NUM_LIT:0>):

x = np.array(x)<EOL>if x.ndim == <NUM_LIT:1>:<EOL><INDENT>axis = <NUM_LIT:0><EOL>r = x.shape[<NUM_LIT:0>]<EOL>w = Window(r, window)   <EOL>w = w.data<EOL><DEDENT>elif x.ndim == <NUM_LIT:2>:<EOL><INDENT>logging.debug('<STR_LIT>')<EOL>[r, c] = x.shape<EOL>w = np.array([Window(r, window).data for this in range(c)]).reshape(r,c) <EOL><DEDENT>if NFFT is None:<EOL><INDENT>NFFT = len(x)<EOL><DEDENT>isreal = np.isrealobj(x)<EOL>if detrend == True:<EOL><INDENT>m = np.mean(x, axis=axis)<EOL><DEDENT>else:<EOL><INDENT>m = <NUM_LIT:0><EOL><DEDENT>if isreal == True:<EOL><INDENT>if x.ndim == <NUM_LIT:2>:<EOL><INDENT>res =  (abs (rfft (x*w - m, NFFT, axis=<NUM_LIT:0>))) ** <NUM_LIT> / r<EOL><DEDENT>else:<EOL><INDENT>res =  (abs (rfft (x*w - m, NFFT, axis=-<NUM_LIT:1>))) ** <NUM_LIT> / r<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if x.ndim == <NUM_LIT:2>:<EOL><INDENT>res =  (abs (fft (x*w - m, NFFT, axis=<NUM_LIT:0>))) ** <NUM_LIT> / r<EOL><DEDENT>else:<EOL><INDENT>res =  (abs (fft (x*w - m, NFFT, axis=-<NUM_LIT:1>))) ** <NUM_LIT> / r<EOL><DEDENT><DEDENT>if scale_by_freq is True:<EOL><INDENT>df = sampling / float(NFFT)<EOL>res*= <NUM_LIT:2> * np.pi / df<EOL><DEDENT>if x.ndim == <NUM_LIT:1>:<EOL><INDENT>return res.transpose()<EOL><DEDENT>else:<EOL><INDENT>return res<EOL><DEDENT>

Simple periodogram, but matrices accepted.

    :param x: an array or matrix of data samples.
    :param NFFT: length of the data before FFT is computed (zero padding)
    :param bool detrend: detrend the data before co,puteing the FFT
    :param float sampling: sampling frequency of the input :attr:`data`.

    :param scale_by_freq:
    :param str window:

    :return: 2-sided PSD if complex data, 1-sided if real.

    if a matrix is provided (using numpy.matrix), then a periodogram
    is computed for each row. The returned matrix has the same shape as the input
    matrix.

    The mean of the input data is also removed from the data before computing
    the psd.

    .. plot::
        :width: 80%
        :include-source:

        from pylab import grid, semilogy
        from spectrum import data_cosine, speriodogram
        data = data_cosine(N=1024, A=0.1, sampling=1024, freq=200)
        semilogy(speriodogram(data, detrend=False, sampling=1024), marker='o')
        grid(True)

    .. plot::
        :width: 80%
        :include-source:

        import numpy
        from spectrum import speriodogram, data_cosine
        from pylab import figure, semilogy, figure ,imshow
        # create N data sets and make the frequency dependent on the time
        N = 100
        m = numpy.concatenate([data_cosine(N=1024, A=0.1, sampling=1024, freq=x)
            for x in range(1, N)]);
        m.resize(N, 1024)
        res = speriodogram(m)
        figure(1)
        semilogy(res)
        figure(2)
        imshow(res.transpose(), aspect='auto')

    .. todo:: a proper spectrogram class/function that takes care of normalisation


def __init__(self, data, sampling=<NUM_LIT:1.>,<EOL>window='<STR_LIT>', NFFT=None, scale_by_freq=False,<EOL>detrend=None):

super(Periodogram, self).__init__(data,<EOL>window=window,<EOL>sampling=sampling,<EOL>NFFT=NFFT,<EOL>scale_by_freq=scale_by_freq,<EOL>detrend=detrend)<EOL>

**Periodogram Constructor**

        :param array data: input data (list or numpy.array)
        :param float sampling: sampling frequency of the input :attr:`data`.
        :param str window: a tapering window. See :class:`~spectrum.window.Window`.
        :param int NFFT: total length of the final data sets (padded with zero
            if needed; default is 4096)
        :param bool scale_by_freq:
        :param str detrend: