text:
# -*- coding: utf-8 -*-
"""

"""
import abc
import functools
from scipy.optimize import minimize_scalar
import skrf as rf
from passive_auto_design.special import u0, eps0

class LumpedElement(metaclass=abc.ABCMeta):
    """
    class of standard lumped element, to be inherited by all lumped elements
    """

    def __init__(self, freq, z0):
        self._par = {}
        self.ref = None
        self.line = rf.media.DefinedGammaZ0(freq, z0=z0)

    @property
    def par(self):
        """
        Returns
        -------
        Dictionary
            Parameters of the lumped component.

        """
        return self._par

    @par.setter
    def par(self, key_pair):
        self._par.update(key_pair)

    def set_x_with_y(self, x_key, y_key, y_value):
        """
        set the value of the X_key for a Y_value of the Y_key
        """
        minimize_scalar(self.__cost, args=(x_key, y_key, y_value))

    @functools.lru_cache()
    def __cost(self, x_value, x_key, y_key, y_value):
        self.par = {x_key: x_value}
        if isinstance(y_value, float):
            self.par = {y_key: y_value}
            return abs(self.calc_ref_value() - self.par[self.ref])
        err = 0
        for y_val in y_value:
            self.par = {y_key: y_val}
            err += abs(self.calc_ref_value() - self.par[self.ref])
        return err

    @abc.abstractmethod
    def calc_ref_value(self):
        """
        Definition of the behavioral equation of the lumped element.
        Returns
        -------
        Value of self.par[self.ref] calculated with the other value in self.par.

        """
        raise NotImplementedError

class Resistor(LumpedElement):
    """
    class describing a resistor behavior
    """

    def __init__(self, freq, section=1e-3, length=1, rho=1e-15, z0=50):
        LumpedElement.__init__(self, freq, z0)
        self.par = {
            "section": section,
            "length": length,
            "rho": rho,
        }
        self.ref = "res"
        self.par.update({"res": self.calc_ref_value()})
        self.sp = self.line.resistor(self.par[self.ref])

    def calc_ref_value(self):
        return self.par["rho"] * self.par["length"] / self.par["section"]

class Capacitor(LumpedElement):
    """
    class describing a capacitor behavior
    """

    def __init__(self, freq, area=1e-6, dist=1e-3, eps_r=1, z0=50):
        LumpedElement.__init__(self, freq, z0)
        self.ref = "cap"
        self.par = {
            "eps_r": eps_r,
            "area": area,
            "dist": dist,
        }
        self.par.update({"cap": self.calc_ref_value()})
        self.sp = self.line.capacitor(self.par[self.ref])

    def calc_ref_value(self):
        return eps0 * self.par["eps_r"] * self.par["area"] / self.par["dist"]

class Inductor(LumpedElement):
    """
    class describing a inductor behavior
    """

    def __init__(self, freq, d_i=100e-6, n_turn=1, width=3e-6, gap=1e-6, z0=50):
        LumpedElement.__init__(self, freq, z0)
        self.ref = "ind"
        self.par = {
            "d_i": d_i,
            "n_turn": n_turn,
            "width": width,
            "gap": gap,
            "k_1": 1.265,
            "k_2": 2.093,
        }
        self.par.update({"ind": self.calc_ref_value()})
        self.sp = self.line.inductor(self.par[self.ref])

    def calc_ref_value(self):
        outer_diam = (
            self.par["d_i"]
            + 2 * self.par["n_turn"] * self.par["width"]
            + 2 * (self.par["n_turn"] - 1) * self.par["gap"]
        )
        self.par.update({"d_o": outer_diam})
        rho = (self.par["d_i"] + outer_diam) / 2
        density = (outer_diam - self.par["d_i"]) / (outer_diam + self.par["d_i"])
        return (
            self.par["k_1"]
            * u0
            * self.par["n_turn"] ** 2
            * rho
            / (1 + self.par["k_2"] * density)
        )

class Mutual(LumpedElement):
    """
    class describing a mutual inductor behavior
    """

    def __init__(self, freq, ind1, ind2, z0=50):
        self.ref = "k"
        LumpedElement.__init__(self, freq, z0)
        self.ind1 = ind1
        self.ind2 = ind2
        self.par = {"cpl_eq": 1}
        self.par.update({"k": self.calc_ref_value()})

    def calc_ref_value(self):
        cpl = self.par["cpl_eq"]
        return cpl * (
            min(self.ind1.par["d_o"], self.ind2.par["d_o"])
            - max(self.ind1.par["d_i"], self.ind2.par["d_i"])
        )

max_stars_repo_name: Patarimi/PassiveAutoDesign

max_issues_repo_name: Patarimi/PassiveAutoDesign

max_forks_repo_name: Patarimi/PassiveAutoDesign

reason: from scipy


text:
# from wikiart import CannyThreshold
import os
import argparse
import cv2
import numpy as np
# import matplotlib.pyplot as plt

def CannyThreshold(filename, low_threshold=75, upper_threshold=250):
    # img = cv2.imread(filename)
    # Works with unicode image paths
    img = cv2.imdecode(np.fromfile(filename, dtype=np.uint8),
                   cv2.IMREAD_UNCHANGED)
    imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_blur = cv2.GaussianBlur(imgray, (5,5), 0)
    edges = cv2.Canny(img_blur, low_threshold, upper_threshold)
    # ret, thresh = cv2.threshold(edges, 200, 255, cv2.THRESH_BINARY)
    # at last, swap blacks and whites
    return cv2.bitwise_not(edges)

def procesDir(src, dst, verbose):
    dst = os.path.join(os.getcwd(), dst)
    src = os.path.join(os.getcwd(), src)

    for dirpath, dirnames, filenames in os.walk(src):
        for idx, filename in enumerate(filenames):
            fullpath = os.path.join(dirpath, filename)
            if verbose: print("Processing " + filename, end= "...")

            try:
                # Try applying edge detection algo
                edges = CannyThreshold(fullpath)
                # Write new image
                cv2.imwrite(os.path.join(dst, filename), edges)
            except:
                if verbose: print("Failed to process image")
                break

            if not verbose: print("\r", f"Processed {(idx+1)/len(filenames)*100:.1f}%", end="", sep="")
            if verbose: print("Succeded")

    print("\nDone")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--source")
    parser.add_argument("-d", "--destiny")
    parser.add_argument("-v", "--verbose")
    args = parser.parse_args()

    if args.source is not None and args.destiny is not None:
        print("Processing images...")
        procesDir(args.source, args.destiny, args.verbose)
    else:
        raise Exception("Not enough arguments")

ext: py

reason: import numpy


text:
#!/usr/bin/env python
"""
Test module for linear boundary value problems (serial)

This module solves equations of the form

.. math::

  \nabla \cdot \left( a(x) \nabla u \right) = f(x)

"""
from __future__ import print_function
from __future__ import absolute_import
from builtins import zip
from builtins import object
from proteus.iproteus import *
import os
import numpy as np
import pytest
from petsc4py import PETSc
from . import poisson_het_2d_p
from . import poisson_het_2d_c0pk_n
from . import poisson_het_2d_dgpk_n

femSpaces=['c0p1','c0p2','dgp1','dgp2']
bcTypes=['weak','strong']
solverTypes=['direct','iterative']
cases =[]
for f in femSpaces:
    for b in bcTypes:
        for s in solverTypes:
            cases.append((f,b,s))

class TestPoisson2D(object):

    @classmethod
    def setup_class(cls):
        pass

    @classmethod
    def teardown_class(cls):
        pass

    def setup_method(self,method):
        self.aux_names = []
        reload(poisson_het_2d_p)
        self.meshdir = os.path.dirname(os.path.abspath(__file__))

    def teardown_method(self,method):
        filenames = []
        for aux_name in self.aux_names:
            filenames.extend([aux_name+'.'+ext for ext in ['h5','xmf']])
        filenames.append('proteus.log')
        for f in filenames:
            if os.path.exists(f):
                try:
                    os.remove(f)
                except OSError as e:
                    print ("Error: %s - %s" %(e.filename,e.strerror))
            else:
                pass

    @pytest.mark.parametrize("femSpace,bcType,solverType", cases)
    def test_poisson(self,femSpace,bcType,solverType):
        reload(poisson_het_2d_p)
        pList = [poisson_het_2d_p]
        if femSpace in ['c0p1','c0p2']:
            reload(poisson_het_2d_c0pk_n)
            nList = [poisson_het_2d_c0pk_n]
            if femSpace is 'c0p1':
                nList[0].femSpaces[0]  = default_n.C0_AffineLinearOnSimplexWithNodalBasis
            else:
                nList[0].femSpaces[0]  = default_n.C0_AffineQuadraticOnSimplexWithNodalBasis
            if bcType is 'strong':
                nList[0].numericalFluxType = nList[0].Exterior_StrongFlux
        if femSpace in ['dgp1','dgp2']:
            reload(poisson_het_2d_dgpk_n)
            nList = [poisson_het_2d_dgpk_n]
            if femSpace is 'dgp1':
                nList[0].femSpaces[0]  = default_n.DG_AffineLinearOnSimplexWithNodalBasis
            else:
                nList[0].femSpaces[0]  = default_n.DG_AffineQuadraticOnSimplexWithNodalBasis
            if bcType is 'strong':
                nList[0].numericalFluxType.useStrongDirichletConstraints=True
        nList[0].nnx=nList[0].nny=nList[0].nn=51
        reload(default_so)
        so = default_so
        so.name = pList[0].name = "poisson_2d_{0}_{1}_{2}_pe{3}".format(femSpace, bcType,solverType,repr(comm.size()))
        reload(default_s)
        so.sList=[default_s]
        opts.logLevel=7
        opts.verbose=True
        opts.profile=True
        opts.gatherArchive=True
        nList[0].linearSolver=default_n.KSP_petsc4py
        nList[0].multilevelLinearSolver=default_n.KSP_petsc4py
        OptDB = nList[0].OptDB
        soln_name = so.name
        if solverType is 'direct':
            OptDB.clear()
            OptDB.setValue('ksp_type','preonly')
            OptDB.setValue('pc_type','lu')
            OptDB.setValue('pc_factor_mat_solver_package','superlu_dist')
        else:
            OptDB.clear()
            OptDB.setValue('ksp_type','cg')
            OptDB.setValue('pc_asm_type','basic')
            OptDB.setValue('pc_asm_overlap',2)
            OptDB.setValue('sub_ksp_type','preonly')
            OptDB.setValue('sub_pc_type','lu')
            OptDB.setValue('sub_pc_factor_type','superlu')
        ns = NumericalSolution.NS_base(so,pList,nList,so.sList,opts)
        ns.calculateSolution(soln_name)
        np.testing.assert_almost_equal(ns.modelList[0].levelModelList[-1].u[0].dof,
                                       ns.modelList[0].levelModelList[-1].u_analytical[0][0],
                                       decimal=4)
        self.aux_names.append(pList[0].name)
        del ns

    def test_2dm(self,use_strong_constraints=False,nLevels=3):
        reload(poisson_het_2d_p)
        reload(poisson_het_2d_c0pk_n)
        poisson_het_2d_p.meshfile=os.path.join(self.meshdir,'square4x4')
        assert os.path.isfile(poisson_het_2d_p.meshfile+'.3dm'), "could not find meshfile {0}".format(poisson_het_2d_p.meshfile+'.3dm')
        poisson_het_2d_p.x0 = (0.0,0.0,0.)
        poisson_het_2d_p.L  = (1.,1.,1.)
        poisson_het_2d_c0pk_n.nLevels = nLevels
        pList = [poisson_het_2d_p]
        nList = [poisson_het_2d_c0pk_n]
        reload(default_so)
        so = default_so
        so.name = pList[0].name = "poisson_2d_c0p1_2dm"+"pe"+repr(comm.size())
        reload(default_s)
        so.sList=[default_s]
        opts.logLevel=7
        opts.verbose=True
        opts.profile=True
        opts.gatherArchive=True
        nList[0].femSpaces[0]  = default_n.C0_AffineLinearOnSimplexWithNodalBasis
        nList[0].linearSolver=default_n.KSP_petsc4py
        nList[0].multilevelLinearSolver=default_n.KSP_petsc4py
        nList[0].numericalFluxType = default_n.Advection_DiagonalUpwind_Diffusion_SIPG_exterior
        soln_name = 'poisson_2d_c0p1_2dm'
        if use_strong_constraints == True:
            nList[0].numericalFluxType = nList[0].Exterior_StrongFlux
        soln_name = 'poisson_2d_c0p1_strong_dirichlet'
        #nList[0].linearSolver=default_n.LU
        #nList[0].multilevelLinearSolver=default_n.LU
        ns = NumericalSolution.NS_base(so,pList,nList,so.sList,opts)
        ns.calculateSolution(soln_name)
        self.aux_names.append(pList[0].name)
        del ns

@pytest.mark.parametrize("use_weak_dirichlet", [False,True])
def test_load_vector_use_weak(use_weak_dirichlet):
    from . import poisson_het_2d_p
    reload(poisson_het_2d_p)
    from . import poisson_het_2d_c0pk_n
    pList = [poisson_het_2d_p]
    nList = [poisson_het_2d_c0pk_n]
    reload(default_so)
    so = default_so
    so.name = pList[0].name = "poisson_2d_c0p1"+"pe"+repr(comm.size())
    reload(default_s)
    so.sList=[default_s]
    opts.logLevel=7
    opts.verbose=True
    opts.profile=True
    opts.gatherArchive=True
    nList[0].femSpaces[0]  = default_n.C0_AffineLinearOnSimplexWithNodalBasis
    nList[0].linearSolver=default_n.LU
    nList[0].multilevelLinearSolver=default_n.LU
    if use_weak_dirichlet:
        nList[0].linearSolver=default_n.KSP_petsc4py
        nList[0].multilevelLinearSolver=default_n.KSP_petsc4py
        nList[0].numericalFluxType = default_n.Advection_DiagonalUpwind_Diffusion_SIPG_exterior
    OptDB = nList[0].OptDB
    soln_name = so.name
    OptDB.clear()
    OptDB.setValue('ksp_type','bcgsl')
    OptDB.setValue('pc_type','asm')
    OptDB.setValue('pc_asm_type','basic')
    OptDB.setValue('pc_asm_overlap',2)
    OptDB.setValue('sub_ksp_type','preonly')
    OptDB.setValue('sub_pc_type','lu')
    OptDB.setValue('sub_pc_factor_type','superlu')
    ns = NumericalSolution.NS_base(so,pList,nList,so.sList,opts)
    ns.calculateSolution('poisson_2d_c0p1')
    #test load vector calculation in a crude way
    #see if sum over test functions of residual is same as the sum over the test functions of the load vector
    #should be if have strong bc's and no other terms in residual besides stiffness and load
    #transport model on the final grid
    finest_model = ns.modelList[0].levelModelList[-1]
    #cheating a little bit to get the global test space dimension from the global trial space
    nr = finest_model.u[0].femSpace.dim
    r = np.zeros((nr,),'d')
    f = np.zeros((nr,),'d')
    utmp = np.zeros((nr,),'d')
    finest_model.getResidual(utmp,r)
    finest_model.getLoadVector(f)
    del ns
    np.testing.assert_almost_equal(r,f)

if __name__ == '__main__':
    pass

max_stars_repo_name: acatwithacomputer/proteus

max_issues_repo_name: acatwithacomputer/proteus

max_forks_repo_name: acatwithacomputer/proteus