Skip to content

Latest commit

 

History

History
161 lines (111 loc) · 2.9 KB

File metadata and controls

161 lines (111 loc) · 2.9 KB

Python


Pythonic

  • Exchange variables

    Good

    a = 1
    b = 2
    tmp = a
    a = b
    b = tmp

    Better

    a, b = b, a

PYTHONPATH

For example, one has a code named my_func.py contains resuable functions (e.g., FUNCTION_1, FUNCTION_2, ...).

For example, if one want to use FUNCTION_1 from my_func.py in any other code,

  • old way

    If my_func.py does not exist in current working directory,

    • copy my_func.py to current working directory;

    • in new code, from my_func import FUNCTION_1.

  • new way

    • put my_func.py under a directory, e.g., /Users/hchen/code/reuse/python;

    • in ~/.bashrc (or ~/.bash_profile), add

      export PYTHONPATH="${PYTHONPATH}:/Users/hchen/code/reuse/python"

      then

      source ~/.bashrc
      
    • now in new code, from my_func import FUNCTION_1.


  • Change font to Times New Roman

    • On Mac

      After Microsoft Office has been installed, simply add Times New Roman to font.serif and font.sans-serif in matplotlibrc file.

      It will look something like:

      font.serif      : Times New Roman, DejaVu Serif, Bitstream Vera Serif ...
      font.sans-serif : Times New Roman, DejaVu Sans, Bitstream Vera Sans ...
      
    • On Linux

      dotfiles

  • Plotting GeoTIFF

    • pyplot.imshow is the fastest way if the RGB array is large.
  • Turn off scientific notation and offset of x/y labels

    ax.get_xaxis().get_major_formatter().set_scientific(False)
    ax.get_yaxis().get_major_formatter().set_scientific(False)
    
    ax.get_xaxis().get_major_formatter().set_useOffset(False)
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    

How to use it?

import cartopy

Draw a map

import cartopy.crs as ccrs

Assume we have the following functions,

def FUNCTION_1(a):
    print(a**2)

def FUNCTION_2(a, b):
    print(a+b)



Use 8 processors to run FUNCTION_1 by passing 0, 1, 2, ..., 7 to a to the function.

import multiprocessing as mp

statements = np.arange(8)

pool = mp.Pool(processes=8)
pool.outputs = pool.map(FUNCTION_1, statements)
pool.close()
pool.join()



Use 8 processors to run FUNCTION_2 by passing 0, 1, 2, ..., 7 to a and 7, 6, 5, ..., 0 to b to the function.

First we need to modify Function_2 to

def FUNCTION_2(args):
    a, b = args
    print(a+b)

Then

import multiprocessing as mp

a = np.arange(8)
b = np.arange(8)[::-1]

statements = zip(a, b)

pool = mp.Pool(processes=8)
pool.outputs = pool.map(FUNCTION_2, statements)
pool.close()
pool.join()