Fork me on GitHub

latex 测试

高斯粗糙面的均方根斜率可以表示为均方根高度和相关长度的函数:

matlab编码规范学习

命名约定

变量

变量名应该记录它们的含义或用途。

1
wage = hourlyRate * nHours

从小写开始用混合大小写命名变量名

以大写开头的名称通常是为类型或者结构体保留的。

很短的变量名可以是大写的,如果它们在常规用法中是大写的,并且不太可能成为复合变量名的一部分。

例如在特定领域,杨氏模量的E,可能会被误导为e。

有些程序员喜欢用下划线来分隔复合变量名的各个部分。

这种方式虽然易于阅读,但在其他语言中并不常用来命名变量。

在图形标题、标签和图例的变量名中使用下划线的另一个考虑因素是,MATLAB中的Tex解释器将把下划线转换为下标来读取,因此需要为每个文本字符串应用参数/值对进行设置,即‘Interpreter’,’none’。

具有大作用域的变量应该具有有意义的命名,作用域小的变量可以有简短的命名

在实践中,大多数变量都应该具有有意义的名字。

在某些条件下,应保留使用简短的命名,以澄清陈述的结构或与预期的通用性相一致。

python风格规范学习

分号

规则

不要在行尾加分号, 也不要用分号将两条命令放在同一行.

行长度

规则

每行不超过80个字符,但有几个例外:

1.长的导入模块语句

2.注释里的URL,路径以及其他的一些长标记

3.不便于换行,不包含空格的模块级字符串常量,比如url或者路径

除非是在 with 语句需要三个以上的上下文管理器的情况下,否则不要使用反斜杠连接行.

Python会将 圆括号, 中括号和花括号中的行隐式的连接起来 , 你可以利用这个特点.

如果需要, 你可以在表达式外围增加一对额外的圆括号.

1
2
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong'):

如果一个文本字符串在一行放不下, 可以使用圆括号来实现隐式行连接:

1
2
x = ('This will build a very long long '
'long long long long long long string')

在注释中,如果必要,将长的URL放在一行上。
正确样例:(可以Ctrl+鼠标左键打开网址)

1
2
# See details at
# http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html

错误样例:(网址不连续直接打不开)

1
2
3
# See details at
# http://www.example.com/us/developer/documentation/api/content/\
# v2.0/csv_file_name_extension_full_specification.html

当 with 表达式需要使用三个及其以上的上下文管理器时,可以使用反斜杠换行.

若只需要两个,请使用嵌套的with.
正确样例1:

1
2
3
4
5
6
# 注意三个上下文管理器都要采取相同缩进
# place_order比with多一个缩进(不和前几行对齐)
with very_long_first_expression_function() as spam, \
very_long_second_expression_function() as beans, \
third_thing() as eggs:
place_order(eggs, beans, spam, beans)

正确样例2:

1
2
3
4
# 每个嵌套多一个缩进
with very_long_first_expression_function() as spam:
with very_long_second_expression_function() as beans:
place_order(beans, spam)

错误样例2:

1
2
3
with VeryLongFirstExpressionFunction() as spam, \
VeryLongSecondExpressionFunction() as beans:
PlaceOrder(eggs, beans, spam, beans)

括号

规则

宁缺毋滥的使用括号

除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号.

不过在元组两边使用括号是可以的.

正确样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if foo:
bar()
while x:
x = bar()
if x and y:
bar()
if not x:
bar()
# 对一个单元素元组可以(x,)的形式强调它的元组属性
onesie=(foo,)
return foo
return spam,beans
return (spam,beans) # 注意这边返回的是元组,所以用括号
for (x,y) in dict.items():
bar()

错误样例:

1
2
3
4
5
6
# 容易误以为是函数
if (x):
bar()
if not(x):
bar()
return (foo)

但我个人认为在做数值计算的时候,如果必须要使用比较长的表达式时,

可以适当增加括号防止运算顺序出问题。

缩进

规则

用4个空格来缩进代码

绝对不要用tab, 也不要tab和空格混用.

对于行连接的情况, 你应该要么垂直对齐换行的元素(见 行长度 部分的示例),

或者使用4空格的悬挂式缩进(这时第一行不应该有参数):

正确样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 使用分隔符对齐
foo = long_function_name(var1, var2,
var3, var4)

# 在字典中使用分隔符对齐
foo = {
long_dictionary_key: value1 +
value2,
}

# 四空格悬挂式缩进
foo = long_function_name(
var1,var2,var3,
var4)

# 字典中的四空格悬挂式缩进
foo = {
long_dictionary_key:
long_dictionary_value,
}

错误样例:

1
2
3
4
5
6
7
8
9
10
11
12
# 不对齐
foo = long_function_name(var1, var2,
var3, var4)
# 两格的缩进
foo = long_function_name(
var1, var2, var3,
var4
)
# 字典中不使用悬挂式缩进
foo = {long_dictionary_key:
long_dictionary_value,
}

序列元素尾部逗号

规则

仅当 ], ), } 和末位元素不在同一行时,推荐使用序列元素尾部逗号

正确示例:

1
2
3
4
5
6
7
golomb3 = [0, 1, 3]
golomb4 = [
0,
1,
4,
6,
]

空行

规则

顶级定义之间空两行, 比如函数或者类定义. 方法定义, 类定义与第一个方法之间, 都应该空一行.

函数或方法中, 某些地方要是你觉得合适, 就空一行.

空格

规则

括号内不要有空格.

正确样例:

1
spam(ham[1], {eggs: 2}, [])

错误样例:

1
spam( ham[ 1 ], { eggs: 2 }, [ ] )

不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾).

正确样例:

1
2
3
if x == 4:
print(x, y)
x, y = y, x

错误样例:

1
2
3
if x == 4 :
print(x , y)
x , y = y , x

参数列表, 索引或切片的左括号前不应加空格.

正确样例:

1
2
spam(1)
dict['key'] = list[index]

错误样例:

1
2
spam (1)
dict ['key'] = list [index]

在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not).

至于算术操作符两边的空格该如何使用, 需要你自己好好判断.

不过两侧务必要保持一致.

正确样例:

1
2
3
x == 1
x = x + 1
x = x+1

错误样例:

1
2
x<1
x =x +1

当 = 用于指示关键字参数或默认参数值时, 不要在其两侧使用空格.

但若存在类型注释的时候,需要在 = 周围使用空格.

正确样例:

1
2
3
4
5
def complex(real, imag=0.0):
return magic(r=real,i=imag)

def complex(real, imag: float = 0.0):
return magic(r=real,i=imag)

错误样例:

1
2
3
4
def complex(real, imag = 0.0): 
return magic(r = real, i = imag)
def complex(real, imag: float=0.0):
return Magic(r = real, i = imag)

不要用空格来垂直对齐多行间的标记, 因为这会成为维护的负担(适用于:, #, =等):

正确样例:

1
2
3
4
5
6
7
foo = 1000  # comment
long_name = 2 # comment that should not be aligned

dictionary = {
"foo": 1,
"long_name": 2,
}

错误样例:

1
2
3
4
5
6
7
foo       = 1000  # comment
long_name = 2 # comment that should not be aligned

dictionary = {
"foo" : 1,
"long_name": 2,
}

Shebang

规则

! 先用于帮助内核找到Python解释器, 但是在导入模块时, 将会被忽略.

因此只有被直接执行的文件中才有必要加入 #! .

注释

文档字符串

Python有一种独一无二的的注释方式: 使用文档字符串.

文档字符串是包、模块、类或函数里的第一个语句.

这些字符串可以通过对象的 doc 成员被自动提取, 并且被pydoc所用.

我们对文档字符串的惯例是使用三重双引号”””( PEP-257 ).

一个文档字符串应该这样组织: 首先是一行以句号, 问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行).

接着是一个空行. 再接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐.

模块

每个文件应该包含一个许可样板.

根据项目使用的许可(例如, Apache 2.0, BSD, LGPL, GPL), 选择合适的样板.

其开头应是对模块内容和用法的描述.

正确样例:

1
2
3
4
5
6
7
8
9
10
11
12
"""A one line summary of the module or program, terminated by a period.

Leave one blank line. The rest of this docstring should contain an
overall description of the module or program. Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.

Typical usage example:

foo = ClassFoo()
bar = foo.FunctionBar()
"""

函数和方法

下文所指的函数,包括函数, 方法, 以及生成器.

一个函数必须要有文档字符串, 除非它满足以下条件:

1.外部不可见;2.非常短小;3.简单明了;

文档字符串应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述”怎么做”, 除非是一些复杂的算法. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 对于复杂的代码, 在代码旁边加注释会比使用文档字符串更有意义. 覆盖基类的子类方法应有一个类似 See base class 的简单注释来指引读者到基类方法的文档注释.若重载的子类方法和基类方法有很大不同,那么注释中应该指明这些信息.

关于函数的几个方面应该在特定的小节中进行描述记录,这几个方面如下文所述.

每节应该以一个标题行开始. 标题行以冒号结尾.

除标题行外, 节的其他内容应被缩进2个空格.

Args:

列出每个参数的名字, 并在名字后使用一个冒号和一个空格, 分隔对该参数的描述.
如果描述太长超过了单行80字符,使用2或者4个空格的悬挂缩进(与文件其他部分保持一致). 
描述应该包括所需的类型和含义. 如果一个函数接受*foo(可变长度参数列表)或者**bar (任意关键字参数), 应该详细列出*foo和**bar.

Returns: (或者 Yields: 用于生成器):

描述返回值的类型和语义. 如果函数返回None, 这一部分可以省略.

Raises:

列出与接口有关的所有异常.

正确样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def fetch_smalltable_rows(table_handle: smalltable.Table,
keys: Sequence[Union[bytes, str]],
require_all_keys: bool = False,
) -> Mapping[bytes, Tuple[str]]:
"""Fetches rows from a Smalltable.

Retrieves rows pertaining to the given keys from the Table instance
represented by table_handle. String keys will be UTF-8 encoded.

Args:
table_handle: An open smalltable.Table instance.
keys: A sequence of strings representing the key of each table
row to fetch. String keys will be UTF-8 encoded.
require_all_keys: Optional; If require_all_keys is True only
rows with values set for all keys will be returned.

Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:

{b'Serak': ('Rigel VII', 'Preparer'),
b'Zim': ('Irk', 'Invader'),
b'Lrrr': ('Omicron Persei 8', 'Emperor')}

Returned keys are always bytes. If a key from the keys argument is
missing from the dictionary, then that row was not found in the
table (and require_all_keys must have been False).

Raises:
IOError: An error occurred accessing the smalltable.
"""

在 Args: 上进行换行也是可以的:

正确样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def fetch_smalltable_rows(table_handle: smalltable.Table,
keys: Sequence[Union[bytes, str]],
require_all_keys: bool = False,
) -> Mapping[bytes, Tuple[str]]:
"""Fetches rows from a Smalltable.

Retrieves rows pertaining to the given keys from the Table instance
represented by table_handle. String keys will be UTF-8 encoded.

Args:
table_handle:
An open smalltable.Table instance.
keys:
A sequence of strings representing the key of each table row to
fetch. String keys will be UTF-8 encoded.
require_all_keys:
Optional; If require_all_keys is True only rows with values set
for all keys will be returned.

Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:

{b'Serak': ('Rigel VII', 'Preparer'),
b'Zim': ('Irk', 'Invader'),
b'Lrrr': ('Omicron Persei 8', 'Emperor')}

Returned keys are always bytes. If a key from the keys argument is
missing from the dictionary, then that row was not found in the
table (and require_all_keys must have been False).

Raises:
IOError: An error occurred accessing the smalltable.
"""

类的注释

类应该在其定义下有一个用于描述该类的文档字符串.

如果你的类有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段.

并且应该遵守和函数参数相同的格式.

正确样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class SampleClass(object):
"""Summary of class here.

Longer class information....
Longer class information....

Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""

def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0

def public_method(self):
"""Performs operation blah."""

块注释和行注释

最需要写注释的是代码中那些技巧性的部分.

如果你在下次 代码审查 的时候必须解释一下, 那么你应该现在就给它写注释.

对于复杂的操作, 应该在其操作开始前写上若干行注释.

对于不是一目了然的代码, 应在其行尾添加注释.

正确样例:

1
2
3
4
5
6
# We use a weighted dictionary search to find out where i is in
# the array. We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.

if i & (i-1) == 0: # True if i is 0 or a power of 2.

为了提高可读性, 注释应该至少离开代码2个空格.

另一方面, 绝不要描述代码. 假设阅读代码的人比你更懂Python, 他只是不知道你的代码要做什么.

错误样例:

1
2
# BAD COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1

标点符号,拼写和语法

规则

注意标点符号,拼写和语法

注释应有适当的大写和标点,句子应该尽量完整.对于诸如在行尾上的较短注释,可以不那么正式,但是也应该尽量保持风格一致.

规则

如果一个类不继承自其它类, 就显式的从object继承. 嵌套类也一样.(除非是为了和 python2 兼容)

正确样例:

1
2
3
4
5
6
7
8
9
10
11
12
class SampleClass(object):
pass


class OuterClass(object):

class InnerClass(object):
pass


class ChildClass(ParentClass):
"""已从另一个类显式继承。"""

错误样例:

1
2
3
4
5
6
7
8
class SampleClass:
pass


class OuterClass:

class InnerClass:
pass

继承自 object 是为了使属性(properties)正常工作, 并且这样可以保护你的代码, 使其不受 PEP-3000 的一个特殊的潜在不兼容性影响.

字符串

规则

即使参数都是字符串, 使用%操作符或者格式化方法格式化字符串.

不过也不能一概而论, 你需要在+和%之间好好判定.

正确样例:

1
2
3
4
5
x = a + b
x = '%s, %s!' % (imperative, expletive)
x = '{},{}!'.format(name, n)
x = 'name: %s; score: %d' % (name, n)
x = 'name: {}; score: {}'.format(name, n)

错误样例:

1
2
3
4
x = '%s%s' % (a, b)  # use + in this case
x = '{}{}'.format(a, b) # use + in this case
x = imperative + ', ' + expletive + '!'
x = 'name: ' + name + '; score: ' + str(n)

避免在循环中用+和+=操作符来累加字符串. 由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间.

作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 .join 连接列表. (也可以将每个子串写入一个 cStringIO.StringIO 缓存中.)

正确样例:

1
2
3
4
5
items = ['<table>']
for last_name, first_name in employee_list:
item.append('<tr><td>%s, %s<td></tr>' % (last_name, first_name))
item.append('</table>')
employee_table = ''.join(items)

错误样例:

1
2
3
4
employee_table = '<table>'
for last_name, first_name in employee_list:
employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
employee_table += '</table>'

在同一个文件中, 保持使用字符串引号的一致性.

使用单引号’或者双引号”之一用以引用字符串, 并在同一文件中沿用.

在字符串内可以使用另外一种引号, 以避免在字符串中使用.

正确样例:

1
2
3
Python('Why are you hiding your eyes?')
Gollum("I'm scared of lint errors.")
Narrator('"Good!" thought a happy Python reviewer.')

错误样例:

1
2
3
Python("Why are you hiding your eyes?")
Gollum('The lint. It burns. It burns us.')
Gollum("Always the great lint. Watching. Watching.")

为多行字符串使用三重双引号”””而非三重单引号’’’.

当且仅当项目中使用单引号’来引用字符串时, 才可能会使用三重’’’为非文档字符串的多行字符串来标识引用. 文档字符串必须使用三重双引号”””.

多行字符串不应随着代码其他部分缩进的调整而发生位置移动.

如果需要避免在字符串中嵌入额外的空间,可以使用串联的单行字符串或者使用 textwrap.dedent() 来删除每行多余的空间.

错误样例:

1
2
3
long_string = """This is pretty ugly.
Don't do this.
"""

正确样例1:

1
2
3
4
5
6
7
8
long_string = """This is fine if your use case can accept
extraneous leading spaces."""

long_string = ("And this is fine if you cannot accept\n" +
"extraneous leading spaces.")

long_string = ("And this too is fine if you cannot accept\n"
"extraneous leading spaces.")

正确样例2:

1
2
3
4
5
import textwrap

long_string = textwrap.dedent("""\
This is also fine, because textwrap.dedent()
will collapse common leading spaces in each line.""")

文件和sockets

规则

在文件和sockets结束时, 显式的关闭它.

除文件外, sockets或其他类似文件的对象在没有必要的情况下打开, 会有许多副作用

推荐使用 “with”语句 以管理文件:

正确样例:

1
2
3
with open('hello.txt') as hello_file:
for line in hello_file:
print(line)

对于不支持使用”with”语句的类似文件的对象,使用 contextlib.closing():
正确样例:

1
2
3
4
5
import contextlib

with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
for line in front_page:
print(line)

TODO注释

规则

为临时代码使用TODO注释, 它是一种短期解决方案.

TODO注释应该在所有开头处包含”TODO”字符串, 紧跟着是用括号括起来的你的名字, email地址或其它标识符.

然后是一个可选的冒号. 接着必须有一行注释, 解释要做什么.

主要目的是为了有一个统一的TODO格式, 这样添加注释的人就可以搜索到(并可以按需提供更多细节).

写了TODO注释并不保证写的人会亲自解决问题.

当你写了一个TODO, 请注上你的名字.

如果你的TODO是”将来做某事”的形式, 那么请确保你包含了一个指定的日期(“2009年11月解决”)或者一个特定的事件(“等到所有的客户都可以处理XML请求就移除这些代码”).

1
2
# TODO(kl@gmail.com): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.

导入格式

每个导入应该独占一行, typing 的导入除外

导入总应该放在文件顶部, 位于模块注释和文档字符串之后, 模块全局变量和常量之前. 导入应该按照从最通用到最不通用的顺序分组:

future导入

future“目的是把下一个版本的特性导入到当前版本

future语句必须在靠近模块开头的位置出现。只有以下内容可以放在future语句之前。

1、模块的文档字符串

2、注释

3、空行

4、其他future语句

1
2
3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

标准库导入

1
import sys

第三方库导入

1
import tensorflow as tf

本地代码子包导入

1
from otherproject.ai import mind

示例

每种分组中, 应该根据每个模块的完整包路径按字典序排序, 忽略大小写.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# __future__导入
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# 标准库
import collections
import queue
import sys

# 第三方库
from absl import app
from absl import flags
import bs4
import cryptography
import tensorflow as tf

# 本地代码子包导入
from book.genres import scifi
from myproject.backend import huxley
from myproject.backend.hgwells import time_machine
from myproject.backend.state_machine import main_loop
from otherproject.ai import body
from otherproject.ai import mind
from otherproject.ai import soul

# Older style code may have these imports down here instead:
#from myproject.backend.hgwells import time_machine
#from myproject.backend.state_machine import main_loop

语句

规则

通常每个语句应该独占一行.不过, 如果测试结果与测试语句在一行放得下, 你也可以将它们放在同一行.

如果是if语句, 只有在没有else时才能这样做.

特别地, 绝不要对 try/except 这样做, 因为try和except不能放在同一行.

正确样例:

1
if foo: bar(foo)

错误样例:

1
2
3
4
5
6
7
8
9
if foo: bar(foo)
else: baz(foo)

try: bar(foo)
except ValueError: baz(foo)

try:
bar(foo)
except ValueError: baz(foo)

访问控制

规则

在Python中, 对于琐碎又不太重要的访问函数, 你应该直接使用公有变量来取代它们, 这样可以避免额外的函数调用开销.

当添加更多功能时, 你可以用属性(property)来保持语法的一致性.

另一方面, 如果访问更复杂, 或者变量的访问开销很显著, 那么你应该使用像 get_foo() 和 set_foo() 这样的函数调用.

如果之前的代码行为允许通过属性(property)访问, 那么就不要将新的访问函数与属性绑定.

这样, 任何试图通过老方法访问变量的代码就没法运行, 使用者也就会意识到复杂性发生了变化.

命名

规则

模块名写法: module_name ;包名写法: package_name ;类名: ClassName ;方法名: method_name ;异常名: ExceptionName ;函数名: function_name ;全局常量名: GLOBAL_CONSTANT_NAME ;全局变量名: global_var_name ;实例名: instance_var_name ;函数参数名: function_parameter_name ;局部变量名: local_var_name .

函数名,变量名和文件名应该是描述性的,尽量避免缩写,特别要避免使用非项目人员不清楚难以理解的缩写,不要通过删除单词中的字母来进行缩写.

始终使用 .py 作为文件后缀名,不要用破折号.

应该避免的名称

1.单字符名称, 除了计数器和迭代器,作为 try/except 中异常声明的 e,作为 with 语句中文件句柄的 f.

2.包/模块名中的连字符(-)

3.双下划线开头并结尾的名称(Python保留, 例如init)

命名约定

1.所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的.

2.用单下划线(_)开头表示模块变量或函数是protected的(使用from module import *时不会包含).

3.用双下划线(__)开头的实例变量或方法表示类内私有.

4.将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块.

5.对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 但是模块名应该用小写加下划线的方式(如lower_with_under.py).

尽管已经有很多现存的模块使用类似于CapWords.py这样的命名, 但现在已经不鼓励这样做, 因为如果模块名碰巧和类名一致, 这会让人困扰.

文件名

所有python脚本文件都应该以 .py 为后缀名且不包含 -.若是需要一个无后缀名的可执行文件,可以使用软联接或者包含 exec “$0.py” “$@” 的bash脚本.

Python之父Guido推荐的规范

详见https://zh-google-styleguide.readthedocs.io/en/stable/google-python-styleguide/python_style_rules/#section-1

Main

规则

即使是一个打算被用作脚本的文件, 也应该是可导入的. 并且简单的导入不应该导致这个脚本的主功能(main functionality)被执行, 这是一种副作用. 主功能应该放在一个main()函数中.

1
2
在Python中, pydoc以及单元测试要求模块必须是可导入的. 
你的代码应该在执行主程序前总是检查 if __name__ == '__main__' , 这样当模块被导入时主程序就不会被执行.

若使用 absl, 请使用 app.run :

1
2
3
4
5
6
7
8
from absl import app

def main(argv):
# process non-flag arguments
...

if __name__ == '__main__':
app.run(main)

否则使用:

1
2
3
4
5
def main():
...

if __name__ == '__main__':
main()

函数长度

规则

推荐函数功能尽量集中,简单,小巧

不对函数长度做硬性限制.但是若一个函数超过了40行,推荐考虑一下是否可以在不损害程序结构的情况下对其进行分解.

因为即使现在长函数运行良好,但几个月后可能会有人修改它并添加一些新的行为,这容易产生难以发现的bug.保持函数的简练,使其更加容易阅读和修改.

当遇到一些很长的函数时,若发现调试比较困难或是想在其他地方使用函数的一部分功能,不妨考虑将这个长函数进行拆分.

类型注释

通用规则

1.请先熟悉下 ‘PEP-484 https://www.python.org/dev/peps/pep-0484/

2.对于方法,仅在必要时才对 self 或 cls 注释

3.若对类型没有任何显示,请使用 Any

4.无需注释模块中的所有函数

python语言规范学习

导入

规则

仅对包和模块使用导入,而不单独导入函数或者类。’typing’模块例外。

导入时不要使用相对名称. 即使模块在同一个包中, 也要使用完整包名.

这能帮助你避免无意间导入一个包两次.

优点

命名空间管理约定十分简单. 每个标识符的源都用一种一致的方式指示.

x.Obj表示Obj对象定义在模块x中.

缺点

模块名仍可能冲突. 有些模块名太长, 不太方便.

实现方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 1.使用 import x 来导入包和模块.
# python自带的包一般使用这种方式
import math

# 2.使用 from x import y
# 其中x是包前缀, y是不带前缀的模块名.
from mpl_toolkits.basemap import Basemap

# 3.使用 from x import y as z
# 如果两个要导入的模块都叫做y或者y太长了.
from matplotlib import pyplot as plt
# 其实plt用第二种方式导入更多

# 4.仅当缩写 z 是通用缩写时才可使用 import y as z.
import numpy as np

规则

使用模块的全路径名来导入每个模块

所有的新代码都应该用完整包名来导入每个模块.

优点

避免模块名冲突或是因非预期的模块搜索路径导致导入错误. 查找包更容易.

缺点

部署代码变难, 因为你必须复制包层次.

实现样例

正确样例1:

1
2
3
4
5
# 在代码中引用完整名称 absl.flags (详细情况).
import absl.flags
from doctor.who import jodie

FLAGS = absl.flags.FLAGS

正确样例2:

1
2
3
4
5
# 在代码中仅引用模块名 flags (常见情况).
from absl import flags
from doctor.who import jodie

FLAGS = flags.FLAGS

错误样例:

1
2
3
# 没能清晰指示出作者想要导入的模块和最终被导入的模块.
# 实际导入的模块将取决于 sys.path.
import jodie

不应假定主入口脚本所在的目录就在 sys.path 中,虽然这种情况是存在的。

当主入口脚本所在目录不在 sys.path 中时,代码将假设 import jodie 是

导入的一个第三方库或者是一个名为 jodie 的顶层包,而不是本地的 jodie.py

异常

规则

异常是一种跳出代码块的正常控制流来处理错误或者其它异常条件的方式.

允许使用异常, 但必须小心

CMOD5模型的matlab实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
%% 数据准备
clear
clc
%% 模型系数准备
global c
c=zeros(1,28);
c(1:13)=[-0.318004,-1.416264,0.006174,-0.058233,0.001851,0.023727,0.071528,0.016858,4.889050,-0.541012,-1.762694,0.487292,-0.058692];
c(14:18)=[0.128558,0.010419,0.08296,0.032500,16.730787];
c(19:28)=[1.466281,7.358231,13.328972,-9.012029,0.999416,2.52457,-0.524396,0.407859,2.227098,-0.306554];
v=0:0.1:20;
theta=30;psai=0;p=1.6;
sigma0=zeros(2,length(v));
for i=1:length(v)
sigma0(1,i)=sigma0_hh(v(i),psai,theta,p);
end
c(1:13)=[-0.688,-0.793,0.338,-0.173,0,0.004,0.111,0.0162,6.34,2.57,-2.18,0.4,-0.6];
c(14:18)=[0.045,0.007,0.33,0.012,22];
c(19:28)=[1.95,3,8.39,-3.44,1.36,5.35,1.99,0.29,3.8,1.53];
%网站上Fortran程序的参数
%cmod5n(5.0,0.0,45.0) = 0.00872497 这是程序给出的一个参考结果
%c=[-0.6878, -0.7957, 0.3380, -0.1728, 0.0000, 0.0040, 0.1103, 0.0159, 6.7329, 2.7713, -2.2885, 0.4971, -0.7250, 0.0450, 0.0066, 0.3222, 0.0120, 22.7000, 2.0813, 3.0000, 8.3659, -3.3428, 1.3236, 6.2437, 2.3893, 0.3249, 4.1590, 1.6930];
for i=1:length(v)
sigma0(2,i)=sigma0_vv(v(i),psai,theta,p);
end
res=sigma0_vv(5,0,45,p);
%% 修饰区
plot(v,sigma0(1,:),'b',v,sigma0(2,:),'r','LineWidth',1.5);
xlabel('wind speed(m/s)');
ylabel('\sigma_0');
legend('CMOD5-HH','CMOD5-VV')
figure
plot(v,std2dB(sigma0(1,:)),'b',v,std2dB(sigma0(2,:)),'r','LineWidth',1.5);
xlabel('wind speed(m/s)');
ylabel('\sigma_0(dB)');
legend('CMOD5-HH','CMOD5-VV')
figure
plot(v,std2dB(sigma0(2,:)./sigma0(1,:)),'LineWidth',1.5);
xlabel('wind speed(m/s)');
ylabel('PR(dB)');
%% 核心函数
function res=sigma0_vv(v,psai,theta,p)
res=B0(v,theta)*(1+B1(v,theta)*cosd(psai)+B2(v,theta)*cosd(2*psai))^p;
end

function res=sigma0_hh(v,psai,theta,p)
res=(B0(v,theta)*(1+B1(v,theta)*cosd(psai)+B2(v,theta)*cosd(2*psai)))^p;
end

function res=std2dB(sigma0)
res=10*log10(sigma0);
end
%% B0函数群
function res=B0(v,theta)
x=(theta-40)/25;
res=(10^(a0(x)+a1(x)*v))*(f(v,theta)^gamma(x));
end

function res=f(v,theta)
x=(theta-40)/25;
s=a2(x)*v;
s_0=s0(x);
if s<s_0
res=((s/s_0)^alpha(s_0))*g(s_0);
else
res=g(s);
end
end

function res=g(s)
res=1/(1+exp(-s));
end

function res=alpha(s0)
res=s0*(1-g(s0));
end

%% 只和x有关的函数
function res=a0(x)
global c
temp1=c(1:4);
temp2=ones(4,1);
for i=2:4
temp2(i)=temp2(i-1)*x;
end
res=temp1*temp2;
end

function res=a1(x)
global c
res=c(5)+c(6)*x;
end

function res=a2(x)
global c
res=c(7)+c(8)*x;
end

function res=gamma(x)
global c
temp1=c(9:11);temp2=ones(3,1);
for i=2:3
temp2(i)=temp2(i-1)*x;
end
res=temp1*temp2;
end

function res=s0(x)
global c
res=c(12)+c(13)*x;
end

function res=v0(x)
global c
temp1=c(21:23);temp2=ones(3,1);
for i=2:3
temp2(i)=temp2(i-1)*x;
end
res=temp1*temp2;
end

function res=d1(x)
global c
temp1=c(24:26);temp2=ones(3,1);
for i=2:3
temp2(i)=temp2(i-1)*x;
end
res=temp1*temp2;
end

function res=d2(x)
global c
res=c(27)+c(28)*x;
end
%% B1
function res=B1(v,theta)
global c
x=(theta-40)/25;
temp1=c(14)*(1+x)-c(15)*v*(0.5+x-tanh(4*(x+c(16)+c(17)*v)));
temp2=1+exp(0.34*(v-c(18)));
res=temp1/temp2;
end

function res=B2(v,theta)
x=(theta-40)/25;
res=(-d1(x)+d2(x)*v2(v,theta))*exp(-v2(v,theta));
end

function res=v2(v,theta)
global c
x=(theta-40)/25;
y=(v+v0(x))/v0(x);
y0=c(19);n=c(20);
a=y0-(y0-1)/n;
b=1/(n*((y0-1)^(n-1)));
if y<y0
res=a+b*((y-1)^n);
else
res=y;
end
end

关于sentinel-2数据处理的若干技巧.md

关于sentinel-2数据处理的若干技巧

写在前面

随着九月份数学建模国赛的结束,我的竞赛生涯也算是告一段落了。
虽然最后获得了省二的成绩,但是我已经不打算参加了。
一是因为这个比赛过于纯粹,二是也确实没时间了。往后我的精力会主要放在科研上。

1、数据处理的目的

由于我主要是做微波遥感这块,所以对于sentinel-2的处理会较为粗糙。
我主要是想通过sentinel-2图像寻找加拿大北部海区的融池,并且将sentinel-2的数据导出为nc文件供后续处理。
数据处理使用SNAP 9.0。

2、数据读取

可以采用两种方式:直接打开zip文件和打开xml文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
function varargout = fig2(varargin)
% FIG2 MATLAB code for fig2.fig
% FIG2, by itself, creates a new FIG2 or raises the existing
% singleton*.
%
% H = FIG2 returns the handle to a new FIG2 or the handle to
% the existing singleton*.
%
% FIG2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in FIG2.M with the given input arguments.
%
% FIG2('Property','Value',...) creates a new FIG2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before fig2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to fig2_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help fig2

% Last Modified by GUIDE v2.5 20-May-2022 19:49:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @fig2_OpeningFcn, ...
'gui_OutputFcn', @fig2_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before fig2 is made visible.
function fig2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to fig2 (see VARARGIN)

% Choose default command line output for fig2
handles.output = hObject;
global DS1102U
DS1102U = visa('NI', 'USB0::0x1AB1::0x0588::DS1EV193800455::INSTR');
fopen(DS1102U); %打开已创建的 VISA 对象 [此处为相关功能语句]
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes fig2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = fig2_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pb1.
function pb1_Callback(hObject, eventdata, handles)
% hObject handle to pb1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DS1102U
fprintf(DS1102U,':RUN');
fprintf(DS1102U,'*IDN?');%设置命令
IDN=fscanf(DS1102U);
set(handles.ed1,'String',IDN);

% --- Executes on button press in pb2.
function pb2_Callback(hObject, eventdata, handles)
% hObject handle to pb2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DS1102U
fprintf(DS1102U,':STOP');


% --- Executes on button press in pb3.
function pb3_Callback(hObject, eventdata, handles)
% hObject handle to pb3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DS1102U
fprintf(DS1102U,':AUTO');
N=DS1102U.InputBufferSize;
fprintf(DS1102U,':wav:data?');
[data,len]=fread(DS1102U,N);
wave=data(12:end);
plot(handles.axes1,wave);
% 获取 VPP
fprintf(DS1102U,':MEASure:VPP?');
vpp=fscanf(DS1102U);
set(handles.ed3,'String',vpp/2);
% 获取采样频率
fprintf(DS1102U,':MEASure:FREQuency?');
Fs=fscanf(DS1102U);
set(handles.ed2,'String',Fs);

function ed1_Callback(hObject, eventdata, handles)
% hObject handle to ed1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ed1 as text
% str2double(get(hObject,'String')) returns contents of ed1 as a double


% --- Executes during object creation, after setting all properties.
function ed1_CreateFcn(hObject, eventdata, handles)
% hObject handle to ed1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end



function ed2_Callback(hObject, eventdata, handles)
% hObject handle to ed2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ed2 as text
% str2double(get(hObject,'String')) returns contents of ed2 as a double


% --- Executes during object creation, after setting all properties.
function ed2_CreateFcn(hObject, eventdata, handles)
% hObject handle to ed2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end



function ed3_Callback(hObject, eventdata, handles)
% hObject handle to ed3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ed3 as text
% str2double(get(hObject,'String')) returns contents of ed3 as a double


% --- Executes during object creation, after setting all properties.
function ed3_CreateFcn(hObject, eventdata, handles)
% hObject handle to ed3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pb4.
function pb4_Callback(hObject, eventdata, handles)
% hObject handle to pb4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DS1102U
fclose(DS1102U);
delete(DS1102U);


% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes1

lower_bound的小技巧

契机

在做导弹拦截这题的时候发现自己不太会用lower_bound和upper_bound,所以写一篇文章备忘。

常规用法

1
2
3
//以下都需要在不下降序列中用
lower_bound(f,f+n,a[i]); //返回f中大于等于a[i]的第一个数
upper_bound(f,f+n,a[i]); //返回f中大于a[i]的第一个数

在不上升序列中用

1
2
3
lower_bound(f,f+n,a[i],greater<int>()); //返回f中大于等于a[i]的第一个数
upper_bound(f,f+n,a[i],greater<int>()); //返回f中大于a[i]的第一个数
//当然greater也可以换成自己写的比较函数
  • Copyrights © 2022-2024 CPY
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信