--- title: Utilities keywords: fastai sidebar: home_sidebar summary: "This includes generally useful functions, including running PowerShell commands from Python." description: "This includes generally useful functions, including running PowerShell commands from Python." nb_path: "Utilities.ipynb" ---
{% raw %}
{% endraw %} {% raw %}

  Index 
  XmlElementTree 
  StaticPlots 
  InteractivePlots 
  Utilities● 
  StructureIO 
  Widgets 
  MainAPI 

{% endraw %} {% raw %}
{% endraw %} {% raw %}

get_file_size[source]

get_file_size(path)

Return file size

{% endraw %} {% raw %}

set_dir[source]

set_dir(path)

work in some directory and come back

{% endraw %} {% raw %}
{% endraw %} {% raw %}
get_file_size('Utilities.ipynb')
'110.44 KB'
{% endraw %} {% raw %}

interpolate_data[source]

interpolate_data(x, y, n=10, k=3)

  • Returns interpolated xnew,ynew. If two points are same, it will add 0.1*min(dx>0) to compensate it.
  • Parameters

    • x: 1D array of size p,
    • y: ndarray of size pqr,....
    • n: Number of points to add between two given points.
    • k: Polynomial order to interpolate.
  • Only axis 0 will be interpolated. If you want general interploation, use from scipy.interpolate import make_interp_spline, BSpline

  • General Usage: K(p),E(p,q) input from bandstructure.

    • Knew,Enew= interpolate_data(K,E,n=10,k=3). cubic interploation
{% endraw %} {% raw %}
{% endraw %} {% raw %}

ps2py[source]

ps2py(ps_command='Get-ChildItem', exec_type='-Command', path_to_ps='powershell.exe')

  • Captures powershell output in python.
  • Parameters
    • ps_command: enclose ps_command in ' ' or " ".
    • exec_type : type of execution, default '-Command', could be '-File'.
    • path_to_ps: path to powerhell.exe if not added to PATH variables.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

ps2std[source]

ps2std(ps_command='Get-ChildItem', exec_type='-Command', path_to_ps='powershell.exe')

  • Prints powershell output in python std.
  • Parameters
    • ps_command: enclose ps_command in ' ' or " ".
    • exec_type: type of execution, default '-Command', could be '-File'.
    • path_to_ps: path to powerhell.exe if not added to PATH variables.
{% endraw %} {% raw %}
{% endraw %}
  • ps2std only outputs returns of powershell to python std.
  • ps2py's return could be manipulated in python.
{% raw %}
ps2std(ps_command='(Get-Process)[0..4]')
NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
------    -----      -----     ------      --  -- -----------
21     6.93       3.78       0.36   15160   1 AcrobatNotificationClient
5     1.36       5.41       0.00    6484   0 AggregatorHost
17     5.74      15.44       0.00    5424   0 AppHelperCap
24    23.79      43.61       2.78    3756   1 ApplicationFrameHost
19     4.37      17.84       0.00    5132   0 armsvc
{% endraw %} {% raw %}
pp=ps2py(ps_command='(Get-Process)[0..4]')
pp
['NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName',
 '------    -----      -----     ------      --  -- -----------',
 '21     6.93       3.78       0.36   15160   1 AcrobatNotificationClient',
 '5     1.36       5.41       0.00    6484   0 AggregatorHost',
 '17     5.74      15.44       0.00    5424   0 AppHelperCap',
 '24    23.79      43.61       2.78    3756   1 ApplicationFrameHost',
 '19     4.37      17.84       0.00    5132   0 armsvc']
{% endraw %} {% raw %}

get_child_items[source]

get_child_items(path='E:\\Research\\pivotpy', depth=None, recursive=True, include=None, exclude=None, filesOnly=False, dirsOnly=False)

  • Returns selected directories/files recursively from a parent directory.
  • Parameters
    • path : path to a parent directory, default is "."
    • depth : int, subdirectories depth to get recursively, default is None to list all down.
    • recursive : If False, only list current directory items, if True,list all items recursively down the file system.
    • include: Default is None and includes everything. String of patterns separated by | to keep, could be a regular expression.
    • exclude: Default is None and removes nothing. String of patterns separated by | to drop,could be a regular expression.
    • filesOnly : Boolean, if True, returns only files.
    • dirsOnly : Boolean, if True, returns only directories.
  • Returns
    • GLOB : Tuple (children,parent), children is list of selected directories/files and parent is given path. Access by index of by get_child_items().{children,path}.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
items = get_child_items(path="../",dirsOnly=True,include='Current',exclude='')
print(items.parent)
items.children
E:\Research
[]
{% endraw %} {% raw %}

prevent_overwrite[source]

prevent_overwrite(path)

Prevents overwiting as file/directory by adding numbers in given file/directory path.

{% endraw %} {% raw %}
{% endraw %} {% raw %}

class color[source]

color()

{% endraw %} {% raw %}
{% endraw %}
  • pivotpy.g_utils.color contains following attributes:
    color.r --> red
    color.rb --> red-bold
    color.g --> green
    color.gb --> green-bold
    color.b --> blue
    color.bb --> blue-bold
    color.y --> yellow
    color.yb --> yellow-bold
    color.m --> magenta
    color.mb --> magenta-bold
    color.c --> cyan
    color.cb --> cyan-bold
  • Usage: print(color.r('This is red'))
{% raw %}

class EncodeFromNumpy[source]

EncodeFromNumpy(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) :: JSONEncoder

  • Serializes python/Numpy objects via customizing json encoder.
  • Usage
    • json.dumps(python_dict, cls=EncodeFromNumpy) to get json string.
    • json.dump(*args, cls=EncodeFromNumpy) to create a file.json.
{% endraw %} {% raw %}

class DecodeToNumpy[source]

DecodeToNumpy(*args, **kwargs) :: JSONDecoder

  • Deserilizes JSON object to Python/Numpy's objects.
  • Usage
    • json.loads(json_string,cls=DecodeToNumpy) from string, use json.load() for file.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
import json
import pivotpy as pp
vr=pp.Vasprun(path = "E:/Research/graphene_example/ISPIN_2/bands/vasprun.xml" ,skipk=88,elim=[0,5]).data
print("ORIGINAL DATA : {}\n".format(vr.poscar.to_dict()))
s=json.dumps(vr.poscar.to_dict(), cls=EncodeFromNumpy)
print("JSON STRING : {}\n".format(s))
s2 = json.loads(s, cls=DecodeToNumpy)
print("RETRIEVED DATA : {}".format(s2))
ORIGINAL DATA : {'SYSTEM': 'C2', 'volume': 105.49324928, 'basis': array([[ 2.468031,  0.      ,  0.      ],
       [-1.234015,  2.137377,  0.      ],
       [ 0.      ,  0.      , 19.998293]]), 'rec_basis': array([[0.4051813 , 0.2339315 , 0.        ],
       [0.        , 0.46786318, 0.        ],
       [0.        , 0.        , 0.05000427]]), 'positions': array([[0.333333, 0.666667, 0.      ],
       [0.666667, 0.333333, 0.      ]]), 'labels': ['C 1', 'C 2'], 'unique': {'C': range(0, 2)}}

JSON STRING : {"SYSTEM": "C2", "volume": 105.49324928, "basis": {"_kind_": "ndarray", "_value_": [[2.468031, 0.0, 0.0], [-1.234015, 2.137377, 0.0], [0.0, 0.0, 19.998293]]}, "rec_basis": {"_kind_": "ndarray", "_value_": [[0.4051813, 0.2339315, 0.0], [0.0, 0.46786318, 0.0], [0.0, 0.0, 0.05000427]]}, "positions": {"_kind_": "ndarray", "_value_": [[0.333333, 0.666667, 0.0], [0.666667, 0.333333, 0.0]]}, "labels": ["C 1", "C 2"], "unique": {"C": {"_kind_": "range", "_value_": [0, 2]}}}

RETRIEVED DATA : {'SYSTEM': 'C2', 'volume': 105.49324928, 'basis': array([[ 2.468031,  0.      ,  0.      ],
       [-1.234015,  2.137377,  0.      ],
       [ 0.      ,  0.      , 19.998293]]), 'rec_basis': array([[0.4051813 , 0.2339315 , 0.        ],
       [0.        , 0.46786318, 0.        ],
       [0.        , 0.        , 0.05000427]]), 'positions': array([[0.333333, 0.666667, 0.      ],
       [0.666667, 0.333333, 0.      ]]), 'labels': ['C 1', 'C 2'], 'unique': {'C': range(0, 2)}}
{% endraw %} {% raw %}

nav_links(current_index=0, doc_url='https://massgh.github.io/pivotpy/', items=['Index', 'XmlElementTree', 'StaticPlots', 'InteractivePlots', 'Utilities', 'StructureIO', 'Widgets', 'MainAPI'], horizontal=False, out_string=False)

{% endraw %} {% raw %}
{% endraw %} {% raw %}

export_outcar[source]

export_outcar(path=None)

  • Read potential at ionic sites from OUTCAR.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

export_potential[source]

export_potential(locpot=None, e=True, m=False)

  • Returns Data from LOCPOT and similar structure files like CHG. Loads only single set out of 2/4 magnetization data to avoid performance/memory cost while can load electrostatic and one set of magnetization together.
  • Parameters
    • locpot: path/to/LOCPOT or similar stuructured file like CHG. LOCPOT is auto picked in CWD.
    • e : Electric potential/charge density. Default is True.
    • m : Magnetization density m. Default is False. If True, picks m for spin polarized case, and m_x for non-colinear case. Additionally it can take 'x','y' and 'z' in case of non-colinear calculations.
  • Exceptions
    • Would raise index error if magnetization density set is not present in LOCPOT/CHG in case m is not False.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

transform_color[source]

transform_color(arr, s=1, c=1, b=0, mixing_matrix=None)

  • Color transformation such as brightness, contrast, saturation and mixing of an input color array. c = -1 would invert color,keeping everything else same.
  • Parameters
    • arr: input array, a single RGB/RGBA color or an array with inner most dimension equal to 3 or 4. e.g. [[[0,1,0,1],[0,0,1,1]]].
    • c : contrast, default is 1. Can be a float in [-1,1].
    • s : saturation, default is 1. Can be a float in [-1,1]. If s = 0, you get a gray scale image.
    • b : brightness, default is 0. Can be a float in [-1,1] or list of three brightnesses for RGB components.
    • mixing_matrix: A 3x3 matrix to mix RGB values, such as pp.color_matrix.

Recoloring Rainmeter

{% endraw %} {% raw %}
{% endraw %} {% raw %}
import matplotlib.pyplot as plt,pivotpy as pp 
axs = pp.get_axes(nrows=2,ncols=2,figsize=(4.5,2.5))
carr = [[[1,0,0,1],[0,1,0,1],[0,0,1,1]]]
axs[0,0].imshow(transform_color(arr=carr))
axs[0,1].imshow(transform_color(s=0,arr=carr))
axs[1,0].imshow(transform_color(b=[-0.5,0,0],arr=carr))
axs[1,1].imshow(transform_color(arr=carr,mixing_matrix=pp.color_matrix[:,:3]))
for ax,txt in zip(axs.ravel(),['original','s = 0','b = [-0.5,0,0]','mixing_matrix']):
    ax.set_title(txt)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
_ = plt.gcf().suptitle('transform_color(arr,s,c,b,mixing_matrix)',color='b',fontweight='bold')
2022-02-12T20:54:57.382292 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %} {% raw %}

  Index 
  XmlElementTree 
  StaticPlots 
  InteractivePlots 
  Utilities● 
  StructureIO 
  Widgets 
  MainAPI 

{% endraw %}