iam-git / WellMet (public) (License: MIT) (since 2021-08-31) (hash sha1)
WellMet is pure Python framework for spatial structural reliability analysis. Or, more specifically, for "failure probability estimation and detection of failure surfaces by adaptive sequential decomposition of the design domain".

/candybox.py (441664a465885f76786e9a259015983579217d09) (7266 bytes) (mode 100644) (type blob)

#!/usr/bin/env python
# coding: utf-8

"""
 we need to go deeper...
 больше ящиков богу ящиков!

 chce se ještě někam ukladat meta infa od blackboxů 
 K tomu využijme pitonovskej dak tajping a zkusíme strčit tohle mezi
 f-modelem a normálním SampleBoxem. Snad to postačí.
 Když ne - bude třeba šecko překopat.
 (však do souboru CandyBox zatím nepůjde - k tomu je potřeba podpora Readeru.)
"""

# Nechce se mi tahnout do projektu Pandas jako rekuajred dependensi,
# ale ani já sam pořadně nerozumím proč 
# asi proto, že se spíše jedná o pomocnou boční "sekondari" funkcionalitu
try:
    import pandas as pd
except ImportError:
    print("CandyBox: error of import Pandas. CandyBox will work in Pandas-free mode")



class CandyBox:

    def __new__(cls, sample_object, df=None, **kwargs):
        """
        Jedname tvrdě - není-li vstup konzistentní, 
        tak tenhle box vůbec nevytvaříme
        """
        cb = super().__new__(cls)
        cb.sampling_plan = sample_object
        
        if df is not None:
            cb.df = df
        else:
            # obalime čísly
            for key in kwargs:
                if not hasattr(kwargs[key], '__getitem__'):
                    kwargs[key] = (kwargs[key],)
                
                
            try:
                cb.df = pd.DataFrame(kwargs)
            except NameError: # if there is no "pandas as pd"
                cb.kwargs = kwargs
        if cb.consistency_check():
            return cb
        else:
            raise ValueError("Sample and given values hasn't the same length. Zkrátka, do sebe nepatří")
            
        
    
        
#    def __str__(cb):
#       # if pandas
#       if 'df' in cb.__dict__:
#           return 'CandyBox: %s' % cb.df
#       # if not
#       else:
#           return 'CandyBox: %s' % cb.kwargs
        
    def __repr__(cb):
        # if pandas
        if 'df' in cb.__dict__:
            # df je na svědomi pandas
            return 'CandyBox(%s, df=%s)' % (repr(cb.sampling_plan), repr(cb.df))
        # if not
        else:
            return 'CandyBox(%s, **%s)' % (repr(cb.sampling_plan), repr(cb.kwargs))
        
    def __len__(cb):
        return len(cb.sampling_plan)
        
        
    def __call__(cb, *args, **kwargs):
        # Houston, we've got a problem...
        # call meaning is different for underlaying f_models and upper Boxes
        # but SampleBox will call in asssumption of f_model under
        return cb.sampling_plan(*args, **kwargs)
    
        
    def __getitem__(cb, slice):
        # if pandas
        if 'df' in cb.__dict__:
            df = cb.df.iloc[slice]
            # нельзя так просто взять и накраить DataFrame
            # pandas zlobí (o kousek víc jak numpy)
            if not isinstance(df, pd.DataFrame):
                # pravděpodobně když se nám vrátí serie, tak bude interpretována jako sloup
                # fakt mi nic spolehlivějšího nenapadá
                df = pd.DataFrame(df).T
            return CandyBox(cb.sampling_plan[slice], df=df)
        # if not
        else:
            sliced_dict = dict()
            for key in cb.kwargs:
                # nechám na uživateli, co vloží do slovníku a jak to bude slajsiť
                sliced_dict[key] = cb.kwargs[key][slice] 
            return CandyBox(cb.sampling_plan[slice], **sliced_dict)
        
        
        
    def __getattr__(cb, attr):
        # branime sa rekurzii
        # defend against recursion
        if attr == 'sampling_plan':
            raise AttributeError
            
        # hledáme obraceně
        # nejdřív se zeptame f_model,
        # teprve když ten nič nemá  
        # mrkneme atribut u sebe
        try:
            return getattr(cb.sampling_plan, attr)
        except AttributeError:
            return cb._lookup(attr)
            
    def _lookup(cb, attr):
        # if pandas
        if 'df' in cb.__dict__:
            if attr in cb.df:
                return cb.df[attr]
            else: # implicitně pandas hodí KeyError, kterej nechcem
                raise AttributeError
        
        # if not
        elif attr in cb.kwargs:
            value = cb.kwargs[attr]
            if len(cb)==len(value):
                return cb.kwargs[attr]
            else:
                # у нас есть дата, но мы их вам недадим)
                # zde ať bude KeyError
                raise KeyError("CandyBox: well, we have some data, but they are not consistent, so we haven't")
                
        else: # implicitně slovníky (stejně jako pandas) hazej KeyError, kterej nechcem
            raise AttributeError
            
        
        
    def add_sample(cb, input):
        """
        hlavní požadavek - jsou-li samply uspěšně sjednoceny,
        tak ty blbé zbytky nesmejí mi hodit chybu!
        котлеты - отдельно, мухи - отдельно
        """
        
        # čo to je za vstup?
        sweety_input = hasattr(input, 'sampling_plan')
            
        #
        # котлеты
        #
        # nechcu zde try-catch blok
        if sweety_input:
            cb.sampling_plan.add_sample(input.sampling_plan)
        else:
            cb.sampling_plan.add_sample(input)
        
        
        # мухи
        if sweety_input:
            # if pandas
            if 'df' in cb.__dict__:
                #if 'df' in input.__dict__: # jen pro formu kontrola
                # pandas musí mít i tamtenhle objekt, žejo?
                cb.df = cb.df.append(input.df, ignore_index=True)
            # if not
            else:
                # zjednodušený join
                sample_len = len(cb.sampling_plan)
                for key in cb.kwargs:
                    if key in input.kwargs:
                        cb.kwargs[key] = (*cb.kwargs[key], *input.kwargs[key])
                    else:
                        fill_len = sample_len - len(cb.kwargs[key])
                        full = (None for __ in range(fill_len))
                        cb.kwargs[key] = (*cb.kwargs[key], *full)
                
                
        else: # nesladký vstup
            sample_len = len(cb.sampling_plan)
            # if pandas
            if 'df' in cb.__dict__:
                fill_len = sample_len - len(cb.df)
                full_df = pd.DataFrame(index=range(fill_len))
                cb.df = cb.df.append(full_df, ignore_index=True)
            # if not
            else:
                for key in cb.kwargs:
                    fill_len = sample_len - len(cb.kwargs[key])
                    full = (None for __ in range(fill_len))
                    cb.kwargs[key] = (*cb.kwargs[key], *full)

                
     # we'll see, if .new_sample will be needed
    #def new_sample(cb, input): pass
        
    def consistency_check(cb):
        # řvat na celé město nebudeme
        # if pandas
        if 'df' in cb.__dict__:
            return len(cb.sampling_plan)==len(cb.df)
        # if not
        else:
            sample_len = len(cb.sampling_plan)
            return all(sample_len == len(cb.kwargs[key]) for key in cb.kwargs)


Mode Type Size Ref File
100644 blob 11744 9fdf445de3ce04c9c28d9cf78a18d830b54703ab IS_stat.py
100644 blob 6 0916b75b752887809bac2330f3de246c42c245cd __init__.py
100644 blob 26851 b0ccb9c800e0fd7ecb869b0e052b387f77868382 blackbox.py
100644 blob 7266 441664a465885f76786e9a259015983579217d09 candybox.py
100644 blob 17034 221ae6f21b8244d7e9ed9863ed8108f9d58317ef estimation.py
100644 blob 18416 dc3be53fec074c8de2b32c8ebc5c684e19bcb2b6 f_models.py
100644 blob 28874 d8521ed3cc7d9f32c63335fb60c2df206c14525f g_models.py
100644 blob 2718 5d721d117448dbb96c554ea8f0e4651ffe9ac457 gp_plot.py
100644 blob 10489 1f6dd06a036fdc4ba6a7e6d61ac0b84e8ad3a4c1 mplot.py
100644 blob 896 14e91bd579c101f1c85bc892af0ab1a196a165a0 plot.py
100644 blob 2807 1feb1d43e90e027f35bbd0a6730ab18501cef63a plotly_plot.py
100644 blob 14307 b6a7545356e45f9abd98af3a9411f3e2437d17b0 qt_plot.py
100644 blob 6251 fc18a41a14682b505a10a2947cfd6fdbea4c59cd reader.py
100644 blob 4228 278bfa08534fcbdf58652edf636fb700395a5f1d samplebox.py
100644 blob 5553 bac994ae58f1df80c7f8b3f33955af5402f5a4f3 sball.py
100644 blob 21563 c9f8f898feec1fbcb76061bb3df981ce6e455049 whitebox.py
Hints:
Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://rocketgit.com/user/iam-git/WellMet

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@ssh.rocketgit.com/user/iam-git/WellMet

Clone this repository using git:
git clone git://git.rocketgit.com/user/iam-git/WellMet

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a merge request:
... clone the repository ...
... make some changes and some commits ...
git push origin main