text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

struct NetworkingV1beta1Api <: SwaggerApi
    client::Swagger.Client
end

function _swaggerinternal_createNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", IoK8sApiNetworkingV1beta1Ingress, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

create an Ingress
Param: namespace::String (required)
Param: body::IoK8sApiNetworkingV1beta1Ingress (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiNetworkingV1beta1Ingress
"""
function createNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_createNetworkingV1beta1NamespacedIngress(_api, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function createNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_createNetworkingV1beta1NamespacedIngress(_api, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_deleteNetworkingV1beta1CollectionNamespacedIngress(_api::NetworkingV1beta1Api, namespace::String; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents)  # type Bool
    Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

delete collection of Ingress
Param: namespace::String (required)
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: __continue__::String
Param: dryRun::String
Param: fieldSelector::String
Param: gracePeriodSeconds::Int32
Param: labelSelector::String
Param: limit::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteNetworkingV1beta1CollectionNamespacedIngress(_api::NetworkingV1beta1Api, namespace::String; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteNetworkingV1beta1CollectionNamespacedIngress(_api, namespace; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function deleteNetworkingV1beta1CollectionNamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, namespace::String; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteNetworkingV1beta1CollectionNamespacedIngress(_api, namespace; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_deleteNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents)  # type Bool
    Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

delete an Ingress
Param: name::String (required)
Param: namespace::String (required)
Param: pretty::String
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: dryRun::String
Param: gracePeriodSeconds::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteNetworkingV1beta1NamespacedIngress(_api, name, namespace; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function deleteNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteNetworkingV1beta1NamespacedIngress(_api, name, namespace; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_getNetworkingV1beta1APIResources(_api::NetworkingV1beta1Api; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1APIResourceList, "/apis/networking.k8s.io/v1beta1/", ["BearerToken"])
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"] : [_mediaType])
    return _ctx
end

"""

get available resources
Return: IoK8sApimachineryPkgApisMetaV1APIResourceList
"""
function getNetworkingV1beta1APIResources(_api::NetworkingV1beta1Api; _mediaType=nothing)
    _ctx = _swaggerinternal_getNetworkingV1beta1APIResources(_api; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function getNetworkingV1beta1APIResources(_api::NetworkingV1beta1Api, response_stream::Channel; _mediaType=nothing)
    _ctx = _swaggerinternal_getNetworkingV1beta1APIResources(_api; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_listNetworkingV1beta1IngressForAllNamespaces(_api::NetworkingV1beta1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiNetworkingV1beta1IngressList, "/apis/networking.k8s.io/v1beta1/ingresses", ["BearerToken"])
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

list or watch objects of kind Ingress
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApiNetworkingV1beta1IngressList
"""
function listNetworkingV1beta1IngressForAllNamespaces(_api::NetworkingV1beta1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listNetworkingV1beta1IngressForAllNamespaces(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function listNetworkingV1beta1IngressForAllNamespaces(_api::NetworkingV1beta1Api, response_stream::Channel; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listNetworkingV1beta1IngressForAllNamespaces(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_listNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, namespace::String; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiNetworkingV1beta1IngressList, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses", ["BearerToken"])
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

list or watch objects of kind Ingress
Param: namespace::String (required)
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApiNetworkingV1beta1IngressList
"""
function listNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, namespace::String; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listNetworkingV1beta1NamespacedIngress(_api, namespace; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function listNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, namespace::String; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listNetworkingV1beta1NamespacedIngress(_api, namespace; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_patchNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiNetworkingV1beta1Ingress, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_param(_ctx.query, "force", force)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
    return _ctx
end

"""

partially update the specified Ingress
Param: name::String (required)
Param: namespace::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiNetworkingV1beta1Ingress
"""
function patchNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchNetworkingV1beta1NamespacedIngress(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function patchNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchNetworkingV1beta1NamespacedIngress(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_patchNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiNetworkingV1beta1Ingress, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses/{name}/status", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_param(_ctx.query, "force", force)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
    return _ctx
end

"""

partially update status of the specified Ingress
Param: name::String (required)
Param: namespace::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiNetworkingV1beta1Ingress
"""
function patchNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchNetworkingV1beta1NamespacedIngressStatus(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function patchNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchNetworkingV1beta1NamespacedIngressStatus(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_readNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiNetworkingV1beta1Ingress, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses/{name}", ["BearerToken"])
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "exact", exact)  # type Bool
    Swagger.set_param(_ctx.query, "export", __export__)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

read the specified Ingress
Param: name::String (required)
Param: namespace::String (required)
Param: pretty::String
Param: exact::Bool
Param: __export__::Bool
Return: IoK8sApiNetworkingV1beta1Ingress
"""
function readNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readNetworkingV1beta1NamespacedIngress(_api, name, namespace; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function readNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readNetworkingV1beta1NamespacedIngress(_api, name, namespace; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_readNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, name::String, namespace::String; pretty=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiNetworkingV1beta1Ingress, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses/{name}/status", ["BearerToken"])
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

read status of the specified Ingress
Param: name::String (required)
Param: namespace::String (required)
Param: pretty::String
Return: IoK8sApiNetworkingV1beta1Ingress
"""
function readNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, name::String, namespace::String; pretty=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readNetworkingV1beta1NamespacedIngressStatus(_api, name, namespace; pretty=pretty, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function readNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String; pretty=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readNetworkingV1beta1NamespacedIngressStatus(_api, name, namespace; pretty=pretty, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_replaceNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiNetworkingV1beta1Ingress, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

replace the specified Ingress
Param: name::String (required)
Param: namespace::String (required)
Param: body::IoK8sApiNetworkingV1beta1Ingress (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiNetworkingV1beta1Ingress
"""
function replaceNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceNetworkingV1beta1NamespacedIngress(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function replaceNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceNetworkingV1beta1NamespacedIngress(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_replaceNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiNetworkingV1beta1Ingress, "/apis/networking.k8s.io/v1beta1/namespaces/{namespace}/ingresses/{name}/status", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

replace status of the specified Ingress
Param: name::String (required)
Param: namespace::String (required)
Param: body::IoK8sApiNetworkingV1beta1Ingress (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiNetworkingV1beta1Ingress
"""
function replaceNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceNetworkingV1beta1NamespacedIngressStatus(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function replaceNetworkingV1beta1NamespacedIngressStatus(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceNetworkingV1beta1NamespacedIngressStatus(_api, name, namespace, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_watchNetworkingV1beta1IngressListForAllNamespaces(_api::NetworkingV1beta1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/networking.k8s.io/v1beta1/watch/ingresses", ["BearerToken"])
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

watch individual changes to a list of Ingress. deprecated: use the 'watch' parameter with a list operation instead.
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchNetworkingV1beta1IngressListForAllNamespaces(_api::NetworkingV1beta1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchNetworkingV1beta1IngressListForAllNamespaces(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function watchNetworkingV1beta1IngressListForAllNamespaces(_api::NetworkingV1beta1Api, response_stream::Channel; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchNetworkingV1beta1IngressListForAllNamespaces(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_watchNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/networking.k8s.io/v1beta1/watch/namespaces/{namespace}/ingresses/{name}", ["BearerToken"])
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

watch changes to an object of kind Ingress. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter.
Param: name::String (required)
Param: namespace::String (required)
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, name::String, namespace::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchNetworkingV1beta1NamespacedIngress(_api, name, namespace; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function watchNetworkingV1beta1NamespacedIngress(_api::NetworkingV1beta1Api, response_stream::Channel, name::String, namespace::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchNetworkingV1beta1NamespacedIngress(_api, name, namespace; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_watchNetworkingV1beta1NamespacedIngressList(_api::NetworkingV1beta1Api, namespace::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/networking.k8s.io/v1beta1/watch/namespaces/{namespace}/ingresses", ["BearerToken"])
    Swagger.set_param(_ctx.path, "namespace", namespace)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

watch individual changes to a list of Ingress. deprecated: use the 'watch' parameter with a list operation instead.
Param: namespace::String (required)
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchNetworkingV1beta1NamespacedIngressList(_api::NetworkingV1beta1Api, namespace::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchNetworkingV1beta1NamespacedIngressList(_api, namespace; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function watchNetworkingV1beta1NamespacedIngressList(_api::NetworkingV1beta1Api, response_stream::Channel, namespace::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchNetworkingV1beta1NamespacedIngressList(_api, namespace; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

export createNetworkingV1beta1NamespacedIngress, deleteNetworkingV1beta1CollectionNamespacedIngress, deleteNetworkingV1beta1NamespacedIngress, getNetworkingV1beta1APIResources, listNetworkingV1beta1IngressForAllNamespaces, listNetworkingV1beta1NamespacedIngress, patchNetworkingV1beta1NamespacedIngress, patchNetworkingV1beta1NamespacedIngressStatus, readNetworkingV1beta1NamespacedIngress, readNetworkingV1beta1NamespacedIngressStatus, replaceNetworkingV1beta1NamespacedIngress, replaceNetworkingV1beta1NamespacedIngressStatus, watchNetworkingV1beta1IngressListForAllNamespaces, watchNetworkingV1beta1NamespacedIngress, watchNetworkingV1beta1NamespacedIngressList


text:
# unfished
add_theme(:ggplot2_base,
    bglegend = _invisible,
    fg       = :white,
    fglegend = _invisible,
    fgguide  = :black)

add_theme(:ggplot2,
          base = :ggplot2_base,
          bginside = :lightgray,
          fg       = :lightgray,
          fgtext   = :gray,
          fglegend = :gray,
          fgguide  = :black)

add_theme(:ggplot2_grey, base = :ggplot2)

add_theme(:ggplot2_bw,
          base = :ggplot2_base,
          bginside = :white,
          fg       = :black,
          fgtext   = :lightgray,
          fglegend = :lightgray,
          fgguide  = :black)

ext: jl


text:
"""Cooley-Tukey FFT algorithm."""
function coolfft(x::Array{T,1}) where {T<:AbstractFloat}

    y1 = Complex{T}[]
    y2 = Complex{T}[]

    n = length(x)
    if n == 1
        return x
    end

    y_even = coolfft(x[1:2:end])
    y_odd = coolfft(x[2:2:end])

    w = one(T)
    for k in 1:Int(n/2)
        push!(y1, y_even[k] + w*y_odd[k])
        push!(y2, y_even[k] - w*y_odd[k])
        w = w*wn(T,n)
    end

    return vcat(y1,y2)
end

""" Twiddle factors computed with Float64 and converted back."""
function wn(::Type{T},n::Int) where {T<:AbstractFloat}
    return Complex{T}(exp(-2*π*im/n))
end


text:
abstract type BoundaryCondition{T} end
Base.eltype(::Type{<:BoundaryCondition{T}}) where {T} = T
Base.eltype(a::BoundaryCondition) = eltype(typeof(a))

struct Neumman{T} <: BoundaryCondition{T}
    x::T
end
@inline flux(a::A) where {A<:Neumman} = a.x

struct Dirichlet{T} <: BoundaryCondition{T}
    x::T
end
@inline val(a::A) where A<:Dirichlet = a.x

function flux_dirichlet(a::Dirichlet,bfc,bfn,k,bccenter,Tc)
    Tf = val(a)
    AfoLac = (bfn⋅bfn)/(bfn⋅(bfc - bccenter))
    qf = k*(Tf-Tc)*AfoLac
    return qf
end

struct FieldAtBoundary{T,BcondType,VecType}
    Tc::Vector{T}
    bf2c::Vector{BFace2Cell}
    bt::Vector{UInt}
    bcond::BcondType
    bfc::Vector{VecType}
    bccenter::Vector{VecType}
    bfn::Vector{VecType}
end

function FieldAtBoundary(Tc,mesh,bcond)
    FieldAtBoundary{eltype(Tc),typeof(bcond),eltype(mesh.nodes)}(Tc,mesh.f2cloops.bf2c,mesh.f2cloops.bft,bcond,mesh.f2cloops.bfc, mesh.f2cloops.bccenter,mesh.f2cloops.bfn)
end

@inline Base.@propagate_inbounds function Base.getindex(fab::FieldAtBoundary,i)
    j = fab.bf2c[i][1]
    a = fab.bcond[fab.bt[i]]
    return typeof(a) <: Dirichlet ? val(a) : fab.Tc[j] + ((fab.bfc[i] - fab.bccenter[i])⋅fab.bfn[i])*flux(a)/norm(fab.bfn[i])
end

function boundary_conditions(d::Dict)
    btypes = d[:BCs]
    bcond = ()
    for el in btypes
        if el[1] == :value
            b = Dirichlet(el[2])
        elseif el[1] == :grad
            b = Neumman(el[2])
        end
        bcond = (bcond...,b)
    end
    return bcond
end

function uboundary_conditions(d::Dict)
    btypes = d[:uBCs]
    bcond = ()
    for el in btypes
        if el[1] == :value
            b = Dirichlet(el[2])
        elseif el[1] == :grad
            b = Neumman(el[2])
        end
        bcond = (bcond...,b)
    end
    return bcond
end

function grad_type(bcond)
    b = eltype(bcond[1])
    if b <: Number
        return Vec2D{b}
    elseif b <: Vec2D
        return Ten2D{Float64}
    end
end


text:
import LinearAlgebra: Matrix, AbstractMatrix, Array,
    transpose, adjoint, diag, mul!, _modify!, MulAddMul
import Base: size, similar,
    +, -, *, /, ==,
    conj, copy, real, imag,
    require_one_based_indexing, getindex

struct SkewTridiagonal{T,V<:AbstractVector{T}} <: AbstractMatrix{T}
    ev::V                        # subdiagonal
    function SkewTridiagonal{T,V}(ev) where {T,V<:AbstractVector{T}}
        require_one_based_indexing(ev)
        new{T,V}(ev)
    end
end

SkewTridiagonal(ev::V) where {T,V<:AbstractVector{T}} = SkewTridiagonal{T}(ev)
SkewTridiagonal{T}(ev::V) where {T,V<:AbstractVector{T}} = SkewTridiagonal{T,V}(ev)
SkewTridiagonal{T}(ev::AbstractVector) where {T} =
    SkewTridiagonal(convert(AbstractVector{T}, ev)::AbstractVector{T})

function SkewTridiagonal(A::AbstractMatrix)
    if all(iszero.(diag(A,0))) && diag(A,1) == -diag(A,-1)
        SkewTridiagonal(diag(A,-1))
    else
        throw(ArgumentError("matrix is not skew-symmetric; cannot convert to SkewTridiagonal"))
    end
end

SkewTridiagonal{T,V}(S::SkewTridiagonal{T,V}) where {T,V<:AbstractVector{T}} = S
SkewTridiagonal{T,V}(S::SkewTridiagonal) where {T,V<:AbstractVector{T}} =
    SkewTridiagonal(convert(V, S.ev)::V)
SkewTridiagonal{T}(S::SkewTridiagonal{T}) where {T} = S
SkewTridiagonal{T}(S::SkewTridiagonal) where {T} =
    SkewTridiagonal(convert(AbstractVector{T}, S.ev)::AbstractVector{T})
SkewTridiagonal(S::SkewTridiagonal) = S

AbstractMatrix{T}(S::SkewTridiagonal) where {T} =
    SkewTridiagonal(convert(AbstractVector{T}, S.ev)::AbstractVector{T})

function Matrix{T}(M::SkewTridiagonal) where T
    n = size(M, 1)
    Mf = zeros(T, n, n)
    @inbounds begin
        @simd for i = 1:n-1
            Mf[i+1,i] = M.ev[i]
            Mf[i,i+1] = -M.ev[i]
        end
    end
    return Mf
end
Matrix(M::SkewTridiagonal{T}) where {T} = Matrix{T}(M)
Array(M::SkewTridiagonal) = Matrix(M)

size(A::SkewTridiagonal) = (length(A.ev)+1, length(A.ev)+1)
function size(A::SkewTridiagonal, d::Integer)
    if d < 1
        throw(ArgumentError("dimension must be ≥ 1, got $d"))
    elseif d<=2
        return length(A.ev)+1
    else
        return 1
    end
end

similar(S::SkewTridiagonal, ::Type{T}) where {T} = SkewTridiagonal(similar(S.ev, T))

#Elementary operations
for func in (:conj, :copy, :real, :imag)
    @eval ($func)(M::SkewTridiagonal) = SkewTridiagonal(($func)(M.ev))
end

transpose(S::SkewTridiagonal) = -S
adjoint(S::SkewTridiagonal{<:Real}) = -S
adjoint(S::SkewTridiagonal) = Adjoint(-S)
Base.copy(S::Adjoint{<:Any,<:SkewTridiagonal}) = SkewTridiagonal(-copy.(adjoint.(S.parent.ev)))
Base.copy(S::Transpose{<:Any,<:SkewTridiagonal}) = SkewTridiagonal(-copy.(transpose.(S.parent.ev)))

function diag(M::SkewTridiagonal, n::Integer=0)
    # every branch call similar(..., ::Int) to make sure the
    # same vector type is returned independent of n
    absn = abs(n)
    if absn==1
        v = copyto!(similar(M.ev, length(M.ev)), M.ev)
        n == 1 && lmul!(-1, v)
        return v
    elseif absn <= size(M,1)
        return fill!(similar(M.ev, size(M,1)-absn), 0)
    else
        throw(ArgumentError(string("requested diagonal, $n, must be at least $(-size(M, 1)) ",
            "and at most $(size(M, 2)) for an $(size(M, 1))-by-$(size(M, 2)) matrix")))
    end
end

+(A::SkewTridiagonal, B::SkewTridiagonal) = SkewTridiagonal(A.ev+B.ev)
-(A::SkewTridiagonal, B::SkewTridiagonal) = SkewTridiagonal(A.ev-B.ev)
-(A::SkewTridiagonal) = SkewTridiagonal(-A.ev)
*(A::SkewTridiagonal, B::Number) = SkewTridiagonal(A.ev*B)
*(B::Number, A::SkewTridiagonal) = A*B
/(A::SkewTridiagonal, B::Number) = SkewTridiagonal(A.ev/B)
==(A::SkewTridiagonal, B::SkewTridiagonal) = (A.ev==B.ev)

@inline mul!(A::StridedVecOrMat, B::SkewTridiagonal, C::StridedVecOrMat,
             alpha::Number, beta::Number) =
                 _mul!(A, B, C, MulAddMul(alpha, beta))

@inline function _mul!(C::StridedVecOrMat, S::SkewTridiagonal, B::StridedVecOrMat,
                       _add::MulAddMul)
    m, n = size(B, 1), size(B, 2)
    if !(m == size(S, 1) == size(C, 1))
        throw(DimensionMismatch("A has first dimension $(size(S,1)), B has $(size(B,1)), C has $(size(C,1)) but all must match"))
    end
    if n != size(C, 2)
        throw(DimensionMismatch("second dimension of B, $n, doesn't match second dimension of C, $(size(C,2))"))
    end

    if m == 0
        return C
    elseif iszero(_add.alpha)
        return _rmul_or_fill!(C, _add.beta)
    end

    β = S.ev
    @inbounds begin
        for j = 1:n
            x₊ = B[1, j]
            x₀ = zero(x₊)
            # If m == 1 then β[1] is out of bounds
            β₀ = m > 1 ? zero(β[1]) : zero(eltype(β))
            for i = 1:m - 1
                x₋, x₀, x₊ = x₀, x₊, B[i + 1, j]
                β₋, β₀ = β₀, β[i]
                _modify!(_add, β₋*x₋ - β₀*x₊, C, (i, j))
            end
            _modify!(_add, β₀*x₀, C, (m, j))
        end
    end

    return C
end

###################
# Generic methods #
###################

## structured matrix methods ##
function Base.replace_in_print_matrix(A::SkewTridiagonal, i::Integer, j::Integer, s::AbstractString)
    i==j-1||i==j+1 ? s : Base.replace_with_centered_mark(s)
end

function getindex(A::SkewTridiagonal{T}, i::Integer, j::Integer) where T
    if !(1 <= i <= size(A,2) && 1 <= j <= size(A,2))
        throw(BoundsError(A, (i,j)))
    end
    if i == j + 1
        return A.ev[j]
    elseif i + 1 == j
        return -A.ev[i]
    else
        return zero(T)
    end
end


text:
using Interpolations
using Plots
plotly()

# Example
A_x = 1.:2.:40.
A = [log(x) for x in A_x]
itp = interpolate(A, BSpline(Cubic(Line(OnGrid()))))

sitp = scale(itp, A_x)

sitp(3.0)
sitp(3.5)

x = convert(Vector{Float64}, range(1.0, 39.0, step=0.25))
ỹ = sitp.(x)
y = log.(x)
plot(x, ỹ)
plot!(x, y)

# parametric-splines
t = 0:0.1:1
x = sin.(2pi*t)
y = cos.(2pi*t)
A = hcat(x,y)

itp = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnGrid()))), NoInterp())), t, 1:2)
tfine = 0:0.01:1
xs, ys = [itp(t, 1) for t in tfine], [itp(t,2) for t in tfine]

scatter(x, y, label="knots")
plot!(xs, ys, label="spline")

itp1 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnCell()))), NoInterp())), t, 1:2)
xs1, ys1 = [itp1(t, 1) for t in tfine], [itp1(t,2) for t in tfine]
plot!(xs1, ys1, label="spline2")

itp2 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Periodic(OnCell()))), NoInterp())), t, 1:2)
xs2, ys2 = [itp2(t, 1) for t in tfine], [itp2(t,2) for t in tfine]
plot!(xs2, ys2, label="spline3")

# itp3 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Free(OnCell()))), NoInterp())), t, 1:2)
# xs3, ys3 = [itp3(t, 1) for t in tfine], [itp3(t,2) for t in tfine]
# plot!(xs3, ys3, label="spline3")
#
# itp4 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Free(OnGrid()))), NoInterp())), t, 1:2)
# xs4, ys4 = [itp4(t, 1) for t in tfine], [itp4(t,2) for t in tfine]
# plot!(xs4, ys4, label="spline4")
#
# itp5 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Reflect(OnGrid()))), NoInterp())), t, 1:2)
# xs5, ys5 = [itp5(t, 1) for t in tfine], [itp5(t,2) for t in tfine]
# plot!(xs5, ys5, label="spline5")

# parametric-splines 2
t = [0.0, 1/6, 1/6, 2/6, 3/6, 3/6, 4/6, 5/6, 5/6, 1.0]
x = [0.0, -2.0, -2.0, -3.0, -4.0, -4.0, 0.25, 4.5, 4.5, 0.0]
y = [0.0, -2.0, -2.0, 0.0, -2.0, -2.0, 0.0, -2.0, -2.0, 0.0]
A = hcat(x,y)

itp = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnGrid()))), NoInterp())), t, 1:2)
tfine = 0:0.01:1
xs, ys = [itp(t, 1) for t in tfine], [itp(t,2) for t in tfine]

scatter(x, y, label="knots")
plot!(xs, ys, label="spline")

itp1 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Natural(OnCell()))), NoInterp())), t, 1:2)
xs1, ys1 = [itp1(t, 1) for t in tfine], [itp1(t,2) for t in tfine]
plot!(xs1, ys1, label="spline2")

itp2 = Interpolations.scale(interpolate(A, (BSpline(Cubic(Periodic(OnCell()))), NoInterp())), t, 1:2)
xs2, ys2 = [itp2(t, 1) for t in tfine], [itp2(t,2) for t in tfine]
plot!(xs2, ys2, label="spline3")

using BSplines

basis = BSplines.BSplineBasis(4, 0:5)
plot(basis)
spl = BSplines.approximate(sin, basis)
plot(1:5, spl)
plot(spl, 1,3)
plot(spl)

f1 = Function(spl)
f2 = Function(spl, Derivative(1))
f3 = Function(spl, Derivative(2))
plot([f1, f2, f3])

basis2 = BSplineBasis(3, [1, 2, 3, 4, 5, 5, 6, 7, 8])
plot(basis2)
BSplines.knots(basis2)
b = bsplines(basis2, 3.5)

# splines consist of b-spline basis and a coefficient vector of the same length
t = [0, 1, 2, 3, 4, 5]
points = [0 0; 1 0; 1 1; 0 1; 0 2; 1 2];
x = points[:,1]
y = points[:,2]
plot(t,x); scatter!(t,x)
plot(t,y); scatter!(t,y)
plot(x,y); scatter!(x,y)

basis = averagebasis(3, t)
xspline = BSplines.interpolate(basis, t, x)
plot(t, xspline); scatter!(t, x)
yspline = BSplines.interpolate(basis, t, y)
plot(t, yspline); scatter!(t, y)
xapprox = xspline.(range(0, 5.0; length=100))
yapprox = yspline.(range(0.0, 5.0; length=100))
plot(xapprox, yapprox); scatter!(x,y)

# 3-d splines
t = [0, 1, 2, 3, 4, 5]
points = [0 0 0; 1 0 0; 1 1 0; 0 1 0; 0 2 0; 1 2 0];
x = points[:,1]
y = points[:,2]
z = points[:,3]
plot(t,x); scatter!(t,x)
plot(t,y); scatter!(t,y)
plot(t,z); scatter!(t,z)
plot3d(x,y,z); scatter3d!(x,y,z)

basis = averagebasis(3,t)
xspline = BSplines.interpolate(basis, t, x)
plot(xspline); scatter!(t,x)
yspline = BSplines.interpolate(basis, t, y)
plot(yspline); scatter!(t,y)
zspline = BSplines.interpolate(basis, t, z)
plot(zspline); scatter!(t,z)
xapprox = xspline.(range(0, 5.0; length=100))
yapprox = yspline.(range(0.0, 5.0; length=100))
zapprox = zspline.(range(0.0, 5.0; length=100))
plot3d(xapprox, yapprox, zapprox)
scatter3d!(x,y,z)

# get the derivatives
xdis = Function(xspline)
xvel = Function(xspline, Derivative(1))
xacc = Function(xspline, Derivative(2))
plot([xdis, xvel, xacc], labels=["disp","vel", "acc"])

ydis = Function(yspline)
yvel = Function(yspline, Derivative(1))
yacc = Function(yspline, Derivative(2))
# yjerk = Function(yspline, Derivative(3))
plot([ydis, yvel, yacc], labels=["disp","vel", "acc"])

zdis = Function(zspline)
zvel = Function(zspline, Derivative(1))
zacc = Function(zspline, Derivative(2))
plot([zdis, zvel, zacc], labels=["disp","vel", "acc"])

# try a 3-d path
t = [0, 1, 2, 3, 4]
points = [0 0 0; 0 0.5 -2; 1 1 0; 2 1.5 -2; 0 0 0];
x = points[:,1]
y = points[:,2]
z = points[:,3]
plot(t,x); scatter!(t,x)
plot(t,y); scatter!(t,y)
plot(t,z); scatter!(t,z)
plot3d(x,y,z); scatter3d!(x,y,z)

basis = averagebasis(3,t)
xspline = BSplines.interpolate(basis, t, x)
plot(xspline); scatter!(t,x)
yspline = BSplines.interpolate(basis, t, y)
plot(yspline); scatter!(t,y)
zspline = BSplines.interpolate(basis, t, z)
plot(zspline); scatter!(t,z)
xapprox = xspline.(range(0, 5.0; length=100))
yapprox = yspline.(range(0.0, 5.0; length=100))
zapprox = zspline.(range(0.0, 5.0; length=100))
plot3d(xapprox, yapprox, zapprox)
scatter3d!(x,y,z)

# try another basis with stops at -2 points
t = [0, 1, 2, 3, 4]
points = [0 0 0; 0 0.5 -2; 1 1 0; 2 1.5 -2; 0 0 0];
x = points[:,1]
y = points[:,2]
z = points[:,3]
plotly()
p1 = plot(t,x, label="x"); scatter!(t,x, label=:none)
p2 = plot(t,y, label="y", linecolor=:green); scatter!(t,y, label=:none)
p3 = plot(t,z, label="z", linecolor=:purple); scatter!(t,z, label="Via Points")
plt = plot(p1, p2, p3, layout=(3,1), legend=:outertopright)
p4 = plot3d(x,y,z, xlabel="x", ylabel="y", zlabel="z", label=:none); scatter3d!(x,y,z, markersize=2, label=:none)
plt2 = plot(plt, p4, layout=(1,2))

plotly()
basis = averagebasis(3, t)
basis = BSplines.BSplineBasis(4, [0.0, 1.0, 1.0, 2.0, 3.0, 3.0, 4.0]) # BEAUTIFUL!
# basis = averagebasis(4, t)
# basis = BSplines.BSplineBasis(3, [0.0, 0.0, 1.0, 1.0, 1.5, 2.5, 4.0, 4.0])
# basis = BSplines.BSplineBasis(4, [0.0, 0.0, 1.0, 1.0, 3.0, 3.0, 4.0, 4.0]) # BEAUTIFUL!
# basis = BSplines.BSplineBasis(4, [0.0, 0.0, 1.0, 3.0, 4.0, 4.0]) # BEAUTIFUL!
xspline = BSplines.interpolate(basis, t, x)
p1 = plot(xspline, label="x"); scatter!(t,x, label=:none)
yspline = BSplines.interpolate(basis, t, y)
p2 = plot(yspline, label="y", linecolor=:green); scatter!(t,y, label=:none)
zspline = BSplines.interpolate(basis, t, z)
p3 = plot(zspline, label="z", linecolor=:purple); scatter!(t,z, label="Via Points")
plt = plot(p1, p2, p3, layout=(3,1), legend=:outertopright)
xapprox = xspline.(range(0.0, 4.0; length=401))
yapprox = yspline.(range(0.0, 4.0; length=401))
zapprox = zspline.(range(0.0, 4.0; length=401))
p4 = plot3d(xapprox, yapprox, zapprox, xlabel="x", ylabel="y", zlabel="z", label=:none); scatter3d!(x,y,z, markersize=2, label=:none)
plt2 = plot(plt, p4, layout=(1,2))

plot(basis, legend=:none, title="Trajectory Basis Functions")

# get the derivatives
xdis = Function(xspline)
xvel = Function(xspline, Derivative(1))
xacc = Function(xspline, Derivative(2))

ydis = Function(yspline)
yvel = Function(yspline, Derivative(1))
yacc = Function(yspline, Derivative(2))

zdis = Function(zspline)
zvel = Function(zspline, Derivative(1))
zacc = Function(zspline, Derivative(2))

max_stars_repo_name: zborffs/Delta

max_issues_repo_name: zborffs/Delta

max_forks_repo_name: zborffs/Delta


text:
include("ThetisSupport.jl")
println(ThetisSupport.bar(convert(Cint, 4)))

max_stars_repo_name: AkillesAILimited/Thetis

max_issues_repo_name: AkillesAILimited/Thetis

max_forks_repo_name: AkillesAILimited/Thetis


text:
using BinDeps

@BinDeps.setup

# make sure the system one is not taken, it maybe doesn't have the header files
libgmp = library_dependency("dummy_libgmp")

GMP_VERSION = "6.1.0"

if false # these are binary-only distributions
@windows_only begin
    using WinRPM
    provides(WinRPM.RPM, "libgmp", libgmp, os = :Windows)
end
provides(AptGet, "libgmp-dev", libgmp)

provides(Yum, "gmp", libgmp)

provides(Pacman, "gmp", libgmp)
end

@osx ? begin
    using Homebrew
    provides(Homebrew.HB, "gmp", libgmp, os = :Darwin)
    prefix = Homebrew.prefix()
end : begin
    provides(Sources, URI("https://gmplib.org/download/gmp/gmp-"*GMP_VERSION*".tar.bz2"), libgmp)
    provides(BuildProcess, Autotools(libtarget = ".libs/libgmp.la"), libgmp)
    prefix = joinpath(Pkg.dir(string(current_module())),"deps","usr")
end

try
    @BinDeps.install Dict(:libgmp => :libgmp)
catch LoadError
end

pathfile = open(joinpath(splitdir(Base.source_path())[1],"path.jl"), "w")
println(pathfile,"# automatically generated")
println(pathfile,"prefix = \"$prefix\"")
close(pathfile)


text:
import PipeLayout: uniq_flow, flow_path_decomp, reorient_fwdflow

@testset "compute unique flow on trees" begin
    nodes = [Node(i,i) for i in 1:6]
    n = length(nodes)

    @testset "everything fine (H net)" begin
        arcs = [Arc(1,3), Arc(2,3), Arc(3,4), Arc(4,5), Arc(4,6)]
        d = [-2.0, -4.0, 0.0, 0.0, 3.0, 3.0]
        q = uniq_flow(Topology(nodes, arcs), d)
        @test length(q) == length(arcs)
        @test q ≈ [-d[1], -d[2], d[5] + d[6], d[5], d[6]]
    end

    @testset "everything fine (H net with Steiner nodes)" begin
        arcs = [Arc(1,3), Arc(2,3), Arc(3,4), Arc(4,5), Arc(4,6)]
        topo = Topology(nodes, arcs)

        d = [-2.0, -4.0, 3.0, 3.0]
        terms = nodes[[1, 2, 5, 6]]
        inst = Instance(terms, d, fill(Bounds(1, 2), 4), [Diameter(1, 1)])

        q = uniq_flow(inst, topo)
        @test length(q) == length(arcs)
        @test q ≈ [-d[1], -d[2], d[3] + d[4], d[3], d[4]]
    end

    @testset "everything fine (FST with 4 terms + 2 stein)" begin
        arcs = [Arc(5,6), Arc(5,1), Arc(2,5), Arc(3,6), Arc(6,4)]
        topo = Topology(nodes, arcs)
        d = [400.0, -600.0, 600.0, -400.0, 0.0, 0.0]

        q = uniq_flow(topo, d)
        @test length(q) == length(arcs)
        @test q ≈ [200, 400, 600, -600, -400]
    end

    @testset "wrong topology" begin
        arcs = [Arc(1,2), Arc(2,3), Arc(3,4), Arc(4,5), Arc(5,6), Arc(1,6)]
        d = [-2.0, -4.0, 0.0, 0.0, 3.0, 3.0]
        @test_throws ArgumentError uniq_flow(Topology(nodes, arcs), d)
    end

    @testset "unbalanced demand" begin
        arcs = [Arc(1,3), Arc(2,3), Arc(3,4), Arc(4,5), Arc(4,6)]
        d = fill(1.0, 6)
        @test_throws ArgumentError uniq_flow(Topology(nodes, arcs), d)
    end

    @testset "dimension mismatch" begin
        arcs = [Arc(1,2), Arc(2,3), Arc(3,4), Arc(4,5), Arc(5,6)]
        d = [-2.0, -4.0, 0.0, 0.0, 3.0, 3.0, 1.0]
        @test_throws ArgumentError uniq_flow(Topology(nodes, arcs), d)
    end
end

@testset "reorient arcs for forward flow" begin
    # star with arcs going to center
    nodes = [Node(i,i) for i=1:4]
    arcs = [Arc(i,4) for i=1:3]
    topo = Topology(nodes, arcs)

    @testset "nothing changes for zero flow" begin
        rotopo = reorient_fwdflow(topo, fill(0.0, 4))
        @test rotopo.nodes == topo.nodes
        @test rotopo.arcs == topo.arcs
    end

    @testset "change arcs leading to sink" begin
        rotopo = reorient_fwdflow(topo, [-1.0, 1.0, 0.0, 0.0])
        @test rotopo.nodes == topo.nodes
        @test rotopo.arcs[1] == topo.arcs[1] # source
        @test rotopo.arcs[2].tail == topo.arcs[2].head # sink
        @test rotopo.arcs[2].head == topo.arcs[2].tail # sink
        @test rotopo.arcs[3] == topo.arcs[3] # innode
    end
end

@testset "decompose positive arc flow in paths" begin
    @testset "on a simple tree" begin
        topo = Topology([Node(0,0), Node(1,0), Node(2,0), Node(1,1)],
                        [Arc(1,2), Arc(2,3), Arc(2,4)])
        arcflow = [3.0, 2.0, 1.0]

        paths, pathflows = flow_path_decomp(topo, arcflow)
        @test length(paths) == 2
        @test length(pathflows) == 2
        @test paths[1] == [Arc(1,2), Arc(2,3)]
        @test pathflows[1] ≈ 2.0
        @test paths[2] == [Arc(1,2), Arc(2,4)]
        @test pathflows[2] ≈ 1.0
    end

    @testset "on a grid with flow on subtree" begin
        # ()-1-()-6-
        # 2    7
        # ()-4-()-10-
        grid = RegGrid{2,3,4}(50.0)
        topo = gridtopology(grid)
        nnodes, narcs = length(topo.nodes), length(topo.arcs)
        arcflow = fill(0.0, narcs)
        arcflow[1] = 3.0
        arcflow[6] = 2.0
        arcflow[7] = 1.0

        paths, pathflows = flow_path_decomp(topo, arcflow)
        @test length(paths) == 2
        @test length(pathflows) == 2
        @test paths[1] == [topo.arcs[1], topo.arcs[6]]
        @test pathflows[1] ≈ 2.0
        @test paths[2] == [topo.arcs[1], topo.arcs[7]]
        @test pathflows[2] ≈ 1.0
    end
end


text:
function derivative(ex::Constant, wrt::Variable)
    return Constant( default_variable_value() )
end

function derivative(ex::Variable, wrt::Variable)
    T   = typeof(wrt.value)
    val = default_variable_value()
    if ex == wrt
        val = one(T)
    end
    return Constant(val)
end

function derivative(ex::SymbolicExpression, wrt::Variable)

    if is_unary_operator(ex.head)
        der_ex = __derivative_unary(ex, wrt)
    elseif is_binary_operator(ex.head)
        der_ex = __derivative_binary(ex, wrt)
    else
        error("not implemented yet")
        # er_ex = __derivative_k_ary(ex, wrt)
    end

    return der_ex
end

function __derivative_unary(ex::SymbolicExpression, wrt::Variable)

    # dy/dz = sin(x)
    # dy/dz = cos(x) * dx/dz
    #
    # derivative of the arguments
    # derivative of the function itself

    arg = ex.args[1]
    der_arg = derivative(arg, wrt)

    sym = ex.head

    if is_sin_operator(sym)
        der_ex = der_arg * cos(arg)

    elseif is_cos_operator(sym)
        der_ex = -der_arg * sin(arg)

    elseif is_tan_operator(sym)
        der_ex = der_arg / (cos(arg) * cos(args))

    elseif is_sqrt_operator(sym)
        der_ex = der_arg / sqrt(arg)

    elseif is_cbrt_operator(sym)
        der_ex = der_arg * 1/3 * arg^(-2/3)

    elseif is_exp_operator(sym)
        der_ex = der_arg * exp(arg)

    elseif is_log_operator(sym)
        der_ex = der_arg / arg

    elseif is_log2_operator(sym)
        der_ex = der_arg / (arg * log(2))

    elseif is_log10_operator(sym)
        der_ex = der_arg / (arg * log(10))

    elseif is_abs_operator(sym)
        der_ex = der_arg * sign(arg)

    elseif is_sign_operator(sym)
        der_ex = Constant(0.0)

    else
        error("not implemented yet")
    end

    return der_ex
end

function __derivative_binary(ex::SymbolicExpression, wrt::Variable)

    sym = ex.head

    if is_plus_operator(sym) || is_product_operator(sym)
        # der_ex = der_left_arg + der_right_arg
        # der_ex = der_left_arg * right_arg + left_arg * der_right_arg

        df(expr) = derivative(expr, wrt)
        der_args = map(df, ex.args)

        if is_plus_operator(sym)
            return reduce(+, der_args)
        end

        L = length(ex.args)
        if L == 2
            left_arg      = ex.args[1]
            right_arg     = ex.args[2]
            der_left_arg  = der_args[1]
            der_right_arg = der_args[2]

            return der_left_arg * right_arg + left_arg * der_right_arg
        else
            der_ex = der_args[1] * reduce(*, ex.args[2:end])
            for ii = 2:L
                # left   = reduce(*, ex.args[1:ii-1])
                # right  = reduce(*, ex.args[ii+1:end])
                args      = [ex.args[1:ii-1]; der_args[ii]; ex.args[ii+1:end]]
                left_expr = SymbolicExpression(:*, args...)
                der_ex    = der_ex + left_expr # left * der_args[ii] * right
            end
            return der_ex
        end
    end

    L = length(ex.args)
    if is_minus_operator(sym) && L == 1
        der_right_arg = derivative(ex.args[1], wrt)
        der_ex = -der_right_arg
        return der_ex
    end

    left_arg  = ex.args[1]
    right_arg = ex.args[2]

    der_left_arg  = derivative(left_arg, wrt)
    der_right_arg = derivative(right_arg, wrt)

    if is_minus_operator(sym)
        der_ex = der_left_arg - der_right_arg

    elseif is_divide_operator(sym)
        der_ex = (der_left_arg * right_arg - left_arg * der_right_arg) / (right_arg * right_arg)

    elseif is_power_operator(sym)
        # most complicated expression
        der_ex = ex * (der_left_arg * right_arg / left_arg + der_right_arg * log(left_arg))

    else
        error("not implemented yet")
    end

    return der_ex
end

function gradient(
    ex::S,
    wrt_vec::A) where {
        S <: Union{Constant, Variable, SymbolicExpression},
        A <: AbstractArray}

    L = length(wrt_vec)
    g = Vector{Any}(undef, L)

    for ii = 1:L
        g[ii] = symbolics.derivative(ex, wrt_vec[ii])
    end

    return g
end

function jacobian(
    ex_vec::S,
    wrt_vec::A) where {
        S <: AbstractArray,
        A <: AbstractArray}

    n_row = length(ex_vec)
    n_col = length(wrt_vec)
    jac   = Matrix{Any}(undef, n_row, n_col)

    for ii = 1:n_row
        ex = ex_vec[ii]
        for jj = 1:n_col
            jac[ii, jj] = symbolics.derivative(ex, wrt_vec[jj])
        end
    end

    return jac
end

max_stars_repo_name: HomoModelicus/julia

max_issues_repo_name: HomoModelicus/julia

max_forks_repo_name: HomoModelicus/julia


text:
"""
Set of common widget callbacks, in response to specific input events.

Each field documents when and in which context the callback may be called.
"""
Base.@kwdef struct WidgetCallbacks <: Callbacks
    """
    A mouse button was pressed.
    """
    on_mouse_button_pressed  = nothing
    """
    A mouse button was released.
    """
    on_mouse_button_released = nothing
    """
    The pointer moves in the widget.
    """
    on_pointer_move          = nothing
    """
    The pointer enters the widget area.
    """
    on_pointer_enter         = nothing
    """
    The pointer leaves the widget area.
    """
    on_pointer_leave         = nothing
    """
    A key was pressed. Note that some key combinations can be reserved by the OS, so they don't trigger the corresponding event. On Ubuntu 20.04, this is for example the case with some combinations of the form alt+fkey such as alt+f4.
    """
    on_key_pressed           = nothing
    """
    A key was released.
    """
    on_key_released          = nothing
    """
    A drag operation was detected.
    """
    on_drag                  = nothing
    """
    A drop operation was detected.
    """
    on_drop                  = nothing
    """
    A hover operation was detected.
    """
    on_hover                 = nothing
    """
    A double click occured.
    """
    on_double_click          = nothing
end


text:
using JUDI, FFTW, JLD2, Random, LinearAlgebra, Statistics

Random.seed!(1234)

using ArgParse
include("../utils/parse_cmd.jl")
parsed_args = parse_commandline()
L = parsed_args["nv"]
nsrc = parsed_args["nsrc"]
snr = parsed_args["snr"]

JLD2.@load "/scratch/data/dobs$(L)vint$(nsrc)nsrcnoisefree.jld2" dobs_stack q_stack

scale = 10^(-snr/20)

noise_stack = deepcopy(dobs_stack)

for i = 1:length(noise_stack)
    for j = 1:noise_stack[i].nsrc
        e = randn(Float32,size(dobs_stack[i].data[j]))
        noise_stack[i].data[j] = real.(ifft(fft(e).*fft(q_stack[i].data[j])))
    end
end

noise_stack = noise_stack/norm(noise_stack)*scale*norm(dobs_stack)

if snr < 50 #input > 50 dB SNR to not add noise
    dobs_stack = dobs_stack + noise_stack
end

JLD2.@save "/scratch/data/dobs$(L)vint$(nsrc)nsrc.jld2" dobs_stack q_stack


text:
### A Pluto.jl notebook ###
# v0.12.21

using Markdown
using InteractiveUtils

# ╔═╡ 62f36be0-64cf-11eb-0b86-9d4b55165cbf
begin
	using PlutoUI
	using NativeSVG
end

# ╔═╡ 46a00ea0-64cd-11eb-3e3f-b7cfa00d69ce
md"""# Variables, Expressions, and Statements

One of the most powerful features of a programming language is the ability to manipulate *variables*. A variable is a name that refers to a value."""

# ╔═╡ 63956320-64cd-11eb-30d5-b1f23c40108f
md"""## Assignment Statements

An assignment statement creates a new variable and gives it a value:

```julia
julia> message = "And now for something completely different"
"And now for something completely different"
julia> n = 17
17
julia> π_val = 3.141592653589793
3.141592653589793
```

This example makes three assignments. The first assigns a string to a new variable named `message`, the second assigns the integer `17` to `n`, and the third assigns the
(approximate) value of π to `π_val` (**`\pi TAB`**).

A common way to represent variables on paper is to write the name of each with an arrow pointing to its value. This kind of figure is called a *state diagram* because it shows what state each of the variables is in (think of it as the variable’s state of mind). Figure 2-1 shows the result of the previous example.
"""

# ╔═╡ 58ba9f20-64d1-11eb-30e7-71ec2290f593
Drawing(width=720, height=110) do
    rect(x=110, y=10, width=500, height=90, fill="rgb(242, 242, 242)", stroke="black")
	text(x=180, y=30, font_family="JuliaMono, monospace", text_anchor="end", font_size="0.85rem", font_weight=600) do
		str("message")
	end
	text(x=190, y=30, font_family="JuliaMono, monospace", font_size="0.85rem", font_weight=600) do
		str("->")
	end
	text(x=220, y=30, font_family="JuliaMono, monospace", font_size="0.85rem", font_weight=600) do
		str("\"And now for something completely different\"")
	end
	text(x=180, y=60, font_family="JuliaMono, monospace", text_anchor="end", font_size="0.85rem", font_weight=600) do
		str("n")
	end
	text(x=190, y=60, font_family="JuliaMono, monospace", font_size="0.85rem", font_weight=600) do
		str("->")
	end
	text(x=220, y=60, font_family="JuliaMono, monospace", font_size="0.85rem", font_weight=600) do
		str("17")
	end
	text(x=180, y=90, font_family="JuliaMono, monospace", text_anchor="end", font_size="0.85rem", font_weight=600) do
		str("π_val")
	end
	text(x=190, y=90, font_family="JuliaMono, monospace", font_size="0.85rem", font_weight=600) do
		str("->")
	end
	text(x=220, y=90, font_family="JuliaMono, monospace", font_size="0.85rem", font_weight=600) do
		str("3.141592653589793")
	end
end

# ╔═╡ 7f908a10-64d6-11eb-1629-9179dc49bad7
md"""
*Figure 2-1. State diagram.*
"""

# ╔═╡ 5cb86662-64e1-11eb-0c04-41643ac1fc94
md"""
!!! languages
    Both the C programming language and Python use also the symbol `=` as assignment operator.

    In the C Programming Language, you have to specify the type as a *declaration* before the name of the variable:
    ```c
    char[] message = "And now for something completely different";
    int n = 17;
    double pi = 3.141592653589793;
    ```
    or you can separate declaration from assignment:
    ```c
    int n;
    n = 17;
    ```

    Python:
    ```python
    >>> message = 'And now for something completely different'
    >>> n = 17
    >>> pi = 3.141592653589793
    ```
"""

# ╔═╡ 60d71100-64ce-11eb-2a71-dd40eded5474
md"""## Variable Names

Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.

Variable names can be as long as you like. They can contain almost all Unicode characters (see [“Characters”]()), but they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only lowercase for variable names.

Unicode characters can be entered via tab completion of LaTeX-like abbreviations in
the Julia REPL.

The underscore character, `_`, can appear in a name. It is often used in names with multiple words, such as `your_name` or `airspeed_of_unladen_swallow`.

If you give a variable an illegal name, you get a syntax error:

```julia
julia> 76trombones = "big parade"
ERROR: syntax: "76" is not a valid function argument name
julia> more@ = 1000000
ERROR: syntax: extra token "@" after end of expression
julia> struct = "Advanced Theoretical Zymurgy"
ERROR: syntax: unexpected "="
```

`76trombones` is illegal because it begins with a number. `more@` is illegal because it contains an illegal character, `@`. But what’s wrong with `struct`?

It turns out that `struct` is one of Julia’s keywords. The REPL uses *keywords* to recognize the structure of the program, and they cannot be used as variable names.

Julia has these keywords:

```
abstract  type      baremodule  begin       break      catch
const     continue  do          else        elseif     end
export    finally   for         false       function   global
if        import    in          let         local      macro
module    mutable   primitive   type        quote      return
true      try       using       struct      where      while
```

You don’t have to memorize this list. In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, you’ll know."""

# ╔═╡ 14697060-64d8-11eb-105d-d39759df9d42
md"""## Expressions and Statements
An *expression* is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:

```julia
julia> 42
42
julia> n
17
julia> n + 25
42
```

When you type an expression at the prompt, the REPL *evaluates* it, which means that it finds the value of the expression. In this example, `n` has the value `17` and `n + 25` has the value `42`.

A *statement* is a unit of code that has an effect, like creating a variable or displaying a value:

```julia
julia> n = 17
17
julia> println(n)
17
```

The first line here is an assignment statement that gives a value to `n`. The second line is a print statement that displays the value of `n`.

When you type a statement, the REPL *executes* it, which means that it does whatever
the statement says.
"""

# ╔═╡ 567fc950-64dc-11eb-22e2-df958738bfff
md"""## Script Mode

So far we have run Julia in *interactive mode*, which means that you interact directly with the REPL. Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy.

The alternative is to save code in a file called a *script* and then run Julia in *script mode* to execute the script. By convention, Julia scripts have names that end with *.jl*.

If you know how to create and run a script on your computer, you are ready to go. Otherwise I recommend installing Visual Studio Code. Open a text file, write the script, and save the file with a *.jl* extension. The script can be executed in a terminal with the command **`julia name_of_the_script.jl`**.

Because Julia provides both modes, you can test bits of code in interactive mode before you put them in a script. But there are differences between interactive mode and script mode that can be confusing.

For example, if you are using Julia as a calculator, you might type:

```julia
julia> miles = 26.2
26.2
julia> miles * 1.61
42.182
```

The first line assigns a value to `miles` and displays the value. The second line is an expression, so the REPL evaluates it and displays the result. It turns out that a mara thon is about 42 kilometers.

But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Julia actually evaluates the expression, but it doesn’t display the value unless you tell it to:

```julia
miles = 26.2
println(miles * 1.61)
```

This behavior can be confusing at first.

A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.

For example, the script:

```julia
println(1)
x = 2
println(x)
```

produces the output:

```
1
2
```

The assignment statement produces no output.
"""

# ╔═╡ ff42a18e-64e4-11eb-0d79-b139fff2bcfd
md"""
!!! languages
    The C programming language has no script mode. All statements have to be in a file:
    ```c
    #include <stdio.h>

    int main(void)
    {
        printf("%i\n", 1);
        int x = 2;
        printf("%i\n", x);
    }
    ```
"""

# ╔═╡ 9f56ada0-64dd-11eb-2689-89413775adb1
md"""#### Exercise 2-1

To check your understanding, type the following statements in the Julia REPL and see
what they do:

```julia
5
x = 5
x + 1
```

Now put the same statements in a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again.
"""

# ╔═╡ c95baab0-64dd-11eb-00c7-af9957ec1614
md"""## Operator Precedence

When an expression contains more than one operator, the order of evaluation depends on the *operator precedence*. For mathematical operators, Julia follows mathematical convention. The acronym *PEMDAS* is a useful way to remember the rules:

* *P*arentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are evaluated
first, `2*(3-1)` is `4`, and `(1+1)^(5-2)` is `8`. You can also use parentheses to make an expression easier to read, as in `(minute * 100) / 60`, even if it doesn’t change the result.
* *E*xponentiation has the next highest precedence, so `1+2^3` is `9`, not `27`, and `2*3^2` is `18`, not `36`.
* *M*ultiplication and *D*ivision have higher precedence than *A*ddition and *S*ubtraction. So, `2*3-1` is `5`, not `4`, and `6+4/2` is `8`, not `5`.
* Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression `degrees / 2 * π`, the division happens first and the result is multiplied by π. To divide by 2π, you can use parentheses, or write `degrees / 2 / π` or `degrees / 2π`.

!!! tip
    I don’t work very hard to remember the precedence of operators. If I can’t tell by looking at the expression, I use parentheses to make it obvious.
"""

# ╔═╡ d619bb60-64de-11eb-3d7b-572676f08d00
md"""## String Operations

In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:

```julia
"2" - "1"
"eggs" / "easy"
"third" + "a charm"
```

But there are two exceptions, `*` and `^`.

The `*` operator performs *string concatenation*, which means it joins the strings by linking them end-to-end. For example:

```julia
julia> first_str = "throat"
"throat"
julia> second_str = "warbler"
"warbler"
julia> first_str * second_str
"throatwarbler"
```

The `^` operator also works on strings; it performs repetition. For example, `"Spam"^3` is `"SpamSpamSpam"`. If one of the values is a string, the other has to be an integer.

This use of `*` and `^` makes sense by analogy with multiplication and exponentiation.
Just as ``4^3`` is equivalent to ``4\cdot4\cdot4``, we expect `"Spam"^3` to be the same as `"Spam"*"Spam"*"Spam"`, and it is.
"""

# ╔═╡ 0579eaa0-64e0-11eb-3fba-211e3857675f
md"""
!!! languages
    Python uses the `+` and the `*` operator to perform string concatenation and repetition:

    ```python
    >>> first_str = 'throat'
    >>> second_str = 'warbler'
    >>> first_str + second_str
    'throatwarbler'
    >>> 'spam'*3
    'spamspamspam'
    ```
"""

# ╔═╡ 68695430-64df-11eb-2c75-bd24a518cceb
md"""## Comments

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called *comments*, and they start with the `#` symbol:

```julia
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
```

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

```julia
percentage = (minute * 100) / 60 # percentage of an hour
```

Everything from the `#` to the end of the line is ignored—it has no effect on the execution of the program.

Comments are most useful when they document nonobvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why.

This comment is redundant with the code and useless:

```julia
v = 5 # assign 5 to v
```

This comment contains useful information that is not in the code:

```julia
v = 5 # velocity in meters/second
```

!!! warning
    Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a trade-off.
"""

# ╔═╡ e11055b0-64e3-11eb-2bdd-6702d0a3fe84
md"""
!!! languages
    Comments in the C programming language start with `//`:
    ```c
    // compute the percentage of the hour that has elapsed
    double percentage = (minute * 100) / 60;
    percentage = (minute * 100) / 60; // percentage of an hour
    ```

    Python uses also the `#` symbol to start a comment:
    ```python
    # compute the percentage of the hour that has elapsed
    percentage = (minute * 100) / 60 # percentage of an hour
    ```
"""

# ╔═╡ d42b0690-64e5-11eb-16c8-e96f57c5dab8
md"""## Debugging

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly:

* *Syntax error*:
  “Syntax” refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so `(1 + 2)` is legal, but `8)` is a syntax error.

  If there is a syntax error anywhere in your program, Julia displays an error message and quits, and you will not be able to run the program. During the first few weeks of your programming career, you might spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster.

* *Runtime error*:
  The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened.

  Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a while before you encounter one.

* *Semantic error*:
  The third type of error is “semantic,” which means related to meaning. If there is a semantic error in your program, it will run without generating error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

  Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.
"""

# ╔═╡ c40b1b50-64e6-11eb-24ce-33b1cc5c6d0d
md"""## Glossary

*variable*:
A name that refers to a value.

*assignment*:
A statement that assigns a value to a variable.

*state diagram*:
A graphical representation of a set of variables and the values they refer to.

*keyword*:
A reserved word that is used to parse a program; you cannot use keywords like
`if`, `function`, and `while` as variable names.

*expression*:
A combination of variables, operators, and values that represents a single result.

*evaluate*:
To simplify an expression by performing the operations in order to yield a single value.

*statement*:
A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.

*execute*:
To run a statement and do what it says.

*interactive mode*:
A way of using the Julia REPL by typing code at the prompt.

*script mode*:
A way of using Julia to read code from a script and run it.

*script*:
A program stored in a file.

*operator precedence*:
Rules governing the order in which expressions involving multiple mathematical operators and operands are evaluated.

*concatenate*:
To join two strings end-to-end.

*comment*:
Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.

*syntax error*:
An error in a program that makes it impossible to parse (and therefore impossible to interpret).

*runtime error* or *exception*:
An error that is detected while the program is running.

*semantics*:
The meaning of a program.

*semantic error*:
An error in a program that makes it do something other than what the programmer intended.
"""

# ╔═╡ 763c5320-64e7-11eb-16e0-1bdc148f2e24
md"""## Exercises

#### Exercise 2-2

Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong.

1. We’ve seen that `n = 42` is legal. What about `42 = n`?
2. How about `x = y = 1`?
3. In some languages every statement ends with a semicolon, `;`. What happens if you put a semicolon at the end of a Julia statement?
4. What if you put a period at the end of a statement?
5. In math notation you can multiply ``x`` and ``y`` like this: ``xy``. What happens if you try that in Julia? What about `5x`?
"""

# ╔═╡ c3de97a2-64e7-11eb-077e-a1692cd76929
md"""#### Exercise 2-3

Practice using the Julia REPL as a calculator:

1. The volume of a sphere with radius ``r`` is ``\frac{4}{3}\pi r^3``. What is the volume of a sphere with radius 5?
2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
3. If I leave my house at 6:52 a.m. and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
"""

# ╔═╡ Cell order:
# ╟─62f36be0-64cf-11eb-0b86-9d4b55165cbf
# ╟─46a00ea0-64cd-11eb-3e3f-b7cfa00d69ce
# ╟─63956320-64cd-11eb-30d5-b1f23c40108f
# ╠═58ba9f20-64d1-11eb-30e7-71ec2290f593
# ╟─7f908a10-64d6-11eb-1629-9179dc49bad7
# ╟─5cb86662-64e1-11eb-0c04-41643ac1fc94
# ╟─60d71100-64ce-11eb-2a71-dd40eded5474
# ╟─14697060-64d8-11eb-105d-d39759df9d42
# ╟─567fc950-64dc-11eb-22e2-df958738bfff
# ╟─ff42a18e-64e4-11eb-0d79-b139fff2bcfd
# ╟─9f56ada0-64dd-11eb-2689-89413775adb1
# ╟─c95baab0-64dd-11eb-00c7-af9957ec1614
# ╟─d619bb60-64de-11eb-3d7b-572676f08d00
# ╟─0579eaa0-64e0-11eb-3fba-211e3857675f
# ╟─68695430-64df-11eb-2c75-bd24a518cceb
# ╟─e11055b0-64e3-11eb-2bdd-6702d0a3fe84
# ╟─d42b0690-64e5-11eb-16c8-e96f57c5dab8
# ╟─c40b1b50-64e6-11eb-24ce-33b1cc5c6d0d
# ╟─763c5320-64e7-11eb-16e0-1bdc148f2e24
# ╟─c3de97a2-64e7-11eb-077e-a1692cd76929


text:
mutable struct Snake{T, R} <: AbstractGridWorld
    world::GridWorldBase{Tuple{Agent, Wall, Body, Food}}
    agent_pos::CartesianIndex{2}
    reward::T
    rng::R
    body::DS.Queue{CartesianIndex{2}}
    food_reward::T
    food_pos::CartesianIndex{2}
    terminal_reward::T
    terminal_penalty::T
    done::Bool
end

@generate_getters(Snake)
@generate_setters(Snake)

function Snake(; T = Float32, height = 8, width = 8, rng = Random.GLOBAL_RNG)
    objects = (AGENT, WALL, BODY, FOOD)
    world = GridWorldBase(objects, height, width)

    room = Room(CartesianIndex(1, 1), height, width)
    place_room!(world, room)

    food_pos = CartesianIndex(height - 1, width - 1)
    world[FOOD, food_pos] = true

    agent_pos = CartesianIndex(2, 2)
    world[AGENT, agent_pos] = true

    body = DS.Queue{CartesianIndex{2}}()
    DS.enqueue!(body, agent_pos)
    world[BODY, agent_pos] = true

    reward = zero(T)
    food_reward = one(T)
    terminal_reward = convert(T, height * width)
    terminal_penalty = convert(T, -height * width)
    done = false

    env = Snake(world, agent_pos, reward, rng, body, food_reward, food_pos, terminal_reward, terminal_penalty, done)

    RLBase.reset!(env)

    return env
end

RLBase.state_space(env::Snake, ::RLBase.Observation, ::RLBase.DefaultPlayer) = nothing
const SNAKE_LAYERS = SA.SVector(2, 3, 4)
RLBase.state(env::Snake, ::RLBase.Observation, ::RLBase.DefaultPlayer) = get_grid(get_world(env), get_agent_pos(env), get_half_size(env), SNAKE_LAYERS)

RLBase.action_space(env::Snake, player::RLBase.DefaultPlayer) = UNDIRECTED_NAVIGATION_ACTIONS
RLBase.reward(env::Snake, ::RLBase.DefaultPlayer) = get_reward(env)
RLBase.is_terminated(env::Snake) = get_done(env)

function RLBase.reset!(env::Snake{T}) where {T}
    world = get_world(env)
    rng = get_rng(env)
    body = get_body(env)

    world[AGENT, get_agent_pos(env)] = false
    world[FOOD, get_food_pos(env)] = false

    for i in 1:length(body)
        pos = DS.dequeue!(body)
        world[BODY, pos] = false
    end

    new_food_pos = rand(rng, pos -> !any(@view world[:, pos]), env)
    set_food_pos!(env, new_food_pos)
    world[FOOD, new_food_pos] = true

    new_agent_pos = rand(rng, pos -> !any(@view world[:, pos]), env)
    set_agent_pos!(env, new_agent_pos)
    world[AGENT, new_agent_pos] = true

    DS.enqueue!(body, new_agent_pos)
    world[BODY, new_agent_pos] = true

    set_reward!(env, zero(T))
    set_done!(env, false)

    return nothing
end

function (env::Snake{T})(action::AbstractMoveAction) where {T}
    world = get_world(env)
    height = get_height(env)
    width = get_width(env)
    rng = get_rng(env)
    body = get_body(env)

    agent_pos = get_agent_pos(env)
    dest = move(action, agent_pos)

    if (world[WALL, dest] || world[BODY, dest])
        set_reward!(env, get_terminal_penalty(env))
        set_done!(env, true)
    elseif world[FOOD, dest]
        world[AGENT, agent_pos] = false
        set_agent_pos!(env, dest)
        world[AGENT, dest] = true

        DS.enqueue!(body, dest)
        world[BODY, dest] = true

        world[FOOD, dest] = false

        if length(body) == (height - 2) * (width - 2)
            set_reward!(env, get_food_reward(env) + get_terminal_reward(env))
            set_done!(env, true)
        else
            new_food_pos = rand(rng, pos -> !any(@view world[:, pos]), env, max_try = 100 * height * width)
            set_food_pos!(env, new_food_pos)
            world[FOOD, new_food_pos] = true

            set_reward!(env, get_food_reward(env))
            set_done!(env, false)
        end
    else
        world[AGENT, agent_pos] = false
        set_agent_pos!(env, dest)
        world[AGENT, dest] = true

        DS.enqueue!(body, dest)
        world[BODY, dest] = true

        last_pos = DS.dequeue!(body)
        world[BODY, last_pos] = false

        set_reward!(env, zero(T))
        set_done!(env, false)
    end

    return nothing
end


text:
const count = [0]
const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]

function walk(y, x, h, w, grid, len, next)
    if y == 0 || y == h || x == 0 || x == w
        count[1] += 2
        return
    end
    t = y * (w + 1) + x
    grid[t + 1] += UInt8(1)
    grid[len - t + 1] += UInt8(1)
    for i in 1:4
        if grid[t + next[i] + 1] == 0
            walk(y + dir[i][1], x + dir[i][2], h, w, grid, len, next)
        end
    end
    grid[t + 1] -= 1
    grid[len - t + 1] -= 1
end

function cutrectangle(hh, ww, recur)
    if isodd(hh)
        h, w = ww, hh
    else
        h, w = hh, ww
    end
    if isodd(h)
        return 0
    elseif w == 1
        return 1
    elseif w == 2
        return h
    elseif h == 2
        return w
    end
    cy = div(h, 2)
    cx = div(w, 2)
    len = (h + 1) * (w + 1)
    grid = zeros(UInt8, len)
    len -= 1
    next = [-1, -w - 1, 1, w + 1]
    if recur
        count[1] = 0
    end
    for x in cx + 1:w - 1
        t = cy * (w + 1) + x
        grid[t + 1] = 1
        grid[len - t + 1] = 1
        walk(cy - 1, x, h, w, grid, len, next)
    end
    count[1] += 1
    if h == w
        count[1] *= 2
    elseif iseven(w) && recur
        cutrectangle(w, h, false)
    end
    return count[1]
end

function runtest()
    for y in 1:10, x in 1:y
        if iseven(x) || iseven(y)
            println("$y x $x: $(cutrectangle(y, x, true))")
        end
    end
end

runtest()

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
using Quon, Test

cp = tait_copy()
contract_boundary_vertices!(cp, [1], [3])
@test plot(cp) !== nothing

rx0 = tait_rx(π*im)
contract_boundary_vertices!(rx0, [1], [6])
@test plot(Quon.simple_connected_planar_graph(rx0.g)[1]) !== nothing
@test plot(rx0) !== nothing

rz = tait_rz(im*pi)
contract!(rz, tait_rz(0.0*im))
@test plot(rz) !== nothing

contract_boundary_vertices!(rz, [1], [10])
@test plot(rz) !== nothing
rz = tait_rz(im*pi)
rx = tait_rx(im*pi)
contract!(rz, rx)
plot(rz)
@test plot(tensor_product!(rz, tait_id())) !== nothing

h = tait_hadamard()
id = tait_id()
c = tait_copy()
tensor_product!(id, h)
@test plot(id) !== nothing
contract!(c, id)
@test plot(c) !== nothing

c = contract!(tait_copy(), tait_copy(), [2, 3], [1, 3])
@test plot(c) !== nothing

s2 = contract!(tait_swap(), tait_swap())
s2.locations[26] = (1.0, 4.0)
s2.locations[29] = (3.0, 4.0)
s2.locations[25] = (2.0, 4.0)
s2.locations[33] = (2.0, 5.0)
s2.locations[30] = (1.0, 6.0)
s2.locations[34] = (2.0, 6.0)
s2.locations[32] = (3.0, 6.0)
s2.locations[27] = (1.0, 7.0)
s2.locations[31] = (2.0, 7.0)
s2.locations[28] = (3.0, 7.0)
s2.locations[19] = (0.0, 8.0)
s2.locations[23] = (2.0, 8.0)
s2.locations[20] = (4.0, 8.0)
st_hs = Dict(
    1 => (3, -π/4),
    8 => (50, -π/2),
    4 => (21, -3π/4),
    9 => (4, 3π/4),
    16 => (55, 0),
    12 => (22, π/4),
    13 => (29, 0),
    17 => (46, 0),
    15 => (41, 0),
    26 => (40, π/4),
    14 => (37, π/2),
    29 => (100, -π/4),
    25 => (34, π/2),
    22 => (26, π/4),
    24 => (24, π/4),
    33 => (111, 0),
    30 => (85, 0),
    34 => (102, 0),
    32 => (97, 0),
    27 => (66, -3π/4),
    28 => (72, -π/4),
    23 => (90, π/2),
    19 => (65, π/4),
    20 => (71, 3π/4)
)
@test plot(s2; backend = :compose, start_hes = st_hs) !== nothing
@test plot(s2; scale = 3) !== nothing


text:
using Test
using FactorLoadingMatrices
using LinearAlgebra

@testset "LoadingMatrices" begin
    nx = 5
    nfactor = 3
    nnz = ((2nx + 1) * nfactor - nfactor^2) ÷ 2

    @testset "NNZ" begin
        @test nnz == nnz_loading(nx, nfactor)
        @test_throws ArgumentError nnz_loading(nx, nx+1)
    end

    @testset "Matrix" begin
        values = ones(nnz_loading(nx, nfactor))
        L = loading_matrix(values, nx, nfactor)
        @test_throws ArgumentError loading_matrix(values[2:end], nx, nfactor)
        @test_throws ArgumentError loading_matrix(values, nx+1, nfactor)
        @test size(L) == (nx, nfactor)

        k = 1
        for i in 1:nfactor
            @test all(L[i:nx, i] .== values[k:k+nx-i])
            k = k + nx-i
        end

        for i in 1:nx, j in 1:nfactor
            if j > i
                @test L[i, j] ≈ 0
            end
        end
    end

    @testset "Varimax" begin
        values = ones(nnz_loading(nx, nfactor))
        L = loading_matrix(values, nx, nfactor)
        @test norm(varimax(L)) ≈ norm(L)
    end
end