示例#1
0
def main():
    N = 1000
    instances_names = [
        "kroA100.tsp", "kroB100.tsp", "kroA200.tsp", "kroB200.tsp"
    ]
    opt_filenames = [
        "kroA100_opt.txt", "kroB100_opt.txt", "kroA200_opt.txt",
        "kroB200_opt.txt"
    ]

    for instance_name, filename in zip(instances_names, opt_filenames):
        instance = ut.load(f'instances/{instance_name}')
        distances = ut.calc_distance_matrix(instance)
        # global_convex.generate_optimums(f'optimums/{filename}', N, distances)
        global_convex.global_convex(f'optimums/{filename}', distances)
示例#2
0
import xlwt

from utilites import dump, load

года = [str(_) for _ in range(2009, 2017)]
_in = load('data/structured_data.json')["По регионам"]

регионы = list(_in.keys())
отрасли = list(load('data/structured_data.json')["По отраслям"].keys())

wb = xlwt.Workbook()

for год in года:
    Общая_занятость_в_регионе = {}
    Число_занятых_в_стране = 0

    for регион in регионы:
        Σ = 0
        for отрасль in отрасли:
            try:
                Σ += _in[регион][отрасль][год]
            except KeyError:
                Σ += 0
                print(регион, отрасль, год)

        Общая_занятость_в_регионе.update({регион: Σ})
        Число_занятых_в_стране += Σ

    Общая_занятость_в_отрасли = {}

    for отрасль in отрасли:
示例#3
0
# Даниил Курушин [email protected]
from utilites import dump, load, graph

from stage1 import download_data, convert_data, form_matrix
from stage2 import *
from stage3 import *
from stage4 import *
from stage5 import *

URL = "http://www.gks.ru/wps/wcm/connect/rosstat_main/rosstat/ru/statistics/accounts/"

if __name__ == '__main__':
    end = False
    while not end:
        try:
            xlsx_file = load('data/xlsx_file.json')
            dict_data, codes = load('data/xlsx_content.json')
            nmpy_data = load('data/nmpy_data.dat')
            idx = load('data/index.json')
            LV = load('data/LV.dat')
            CL = load('data/CL.json')
            M = load('data/M.dat')
            graph(M, LV, CL, idx, 'filename', subgraphs=0)

            end = True
        except FileNotFoundError as e:
            if e.filename == 'data/xlsx_file.json':
                xlsx_file = download_data(URL)
                dump(xlsx_file, 'data/xlsx_file.json')
            elif e.filename == 'data/xlsx_content.json':
                dict_data, codes = convert_data(xlsx_file)
示例#4
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in1 = load('jsondb/трансформированные данные.json')
_in2 = load('jsondb/avg_std.json')

регионы = list(_in1.keys())
показатели = list(_in1[регионы[0]].keys())

data = np.zeros([len(показатели), len(регионы)])

rez = {}
for регион in регионы:
    poka = {}
    for показатель in показатели:
        try:
            показатель.index('%')
            x = (_in1[регион][показатель])
            poka.update({показатель: x})
        except ValueError:
            x = (_in1[регион][показатель] -
                 _in2[показатель]['avg']) / _in2[показатель]['std']
            poka.update({показатель: x})
    rez.update({регион: poka})

dump(rez, 'jsondb/нормированные данные.json')
示例#5
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in0 = load('jsondb/нормированные данные.json')
_in1 = load('jsondb/вес показателей.json')

регионы = list(_in0.keys())
показатели = list(_in0[регионы[0]].keys())
эталонный_регион = "Пермский край"

rez = {}
for эталонный_регион in регионы:
    row = {}
    for регион in регионы:
        if (эталонный_регион != регион):
            _sum = 0
            for показатель in показатели:
                try:
                    вес = _in1[показатель]
                    показатель_эт_региона = _in0[эталонный_регион][показатель]
                    показатель_региона = _in0[регион][показатель]
                    x = вес * ((показатель_эт_региона - показатель_региона)**2)
                    _sum += x
                except KeyError:
                    pass
            row.update({регион: _sum})
    rez.update({эталонный_регион: row})

dump(rez, 'jsondb/матрица структурных расстояний.json')
示例#6
0
        if i_name not in clustered:
            clustered += [i_name]
            cnt = []
            for j in range(len(CLL[i])):
                j_name = index[str(CLL[i][j][1])]
                if j_name not in clustered:
                    cnt += [j_name]
                    clustered += [j_name]
            rez.update({i_name: cnt})
    cnt = []
    for i in index:
        if index[i] not in clustered:
            cnt += [index[i]]
        try:
            rez.update({'empty': cnt})
        except IndexError:
            pass

    return rez

if __name__ == '__main__':
    A = load('A.dat')
    B = load('B.dat')
    LV = load('LV.dat')
    idx = load('index.json')
    print(
        dumps(filter_clusters(make_clusters(A, B, LV, idx)),
              indent=2,
              ensure_ascii=0))
#    print(dumps(make_clusters(A, B, LV, idx), indent=2, ensure_ascii=0))
示例#7
0
from utilites import load, dump

def stage_1(_in):
    rez = {}
    for reg in _in.keys():
        B = _in[reg]['Численность раб.силы (тыс. человек)']
        C = _in[reg]['с высшим образование от раб.силы %'] #
        D = _in[reg]['Численность безработных (тыс. человек)']
        E = _in[reg]['с высшим образованием от безработных %']
        Количество_людей_с_высшим_образованием = (B / 100) * C + (D / 100) * E #Расчет количества людей с высшим образованием 

        rez.update({reg:Количество_людей_с_высшим_образованием})
    return rez

if __name__ == '__main__':
    _in = load('jsondb/количество людей с ВО.json')
    _out = stage_1(_in)
    dump(_out, 'jsondb/Количество людей с высшим образованием из числа занятых и безработных.json')
示例#8
0
from utilites import load, dump

эталонный_регион = "Пермский край"

dists = load('jsondb/индекс структурного расстояния.json')

graph = "digraph g {\n"
for регион in dists.keys():
    if регион != эталонный_регион:
        _len = round(dists[регион]*10)
        _lab = round(dists[регион]*10)
        graph += '\t"%s" -> "%s" [len=%s _minlen=%s label=%s]\n' % (эталонный_регион, регион, _len, _len, _lab)

graph += "}\n"
    
open('/tmp/test', 'w').write(graph)
示例#9
0
from utilites import load, dump, compare
import numpy as np

regions = load('out.json')

_instr = """развитие	совершенствование	динамика			
производство	промышленное производство	промышленность			
создание					
долгосрочная перспектива					
инновационный сценарий					
консервативный сценарий					
экспорт					
импорт					
разработка					
модернизация	реконструкция				
повышение	улучшение	увеличение	расширение		
экономическое рост	темпы роста	высокие темпы роста	рост		
технологии	технологическое развитие	техника	технологические разработки		
инновации	инновационное развитие				
транспортная инфраструктура	автомобильные дороги	транспорт			
инвестиции	инвестиционная привлекательность				
социально-экономическое развитие					
производительность труда	рост производительности труда				
человеческое капитал					
здравоохранение	медицина				
государственная поддержка					
заработная плата					
бюджет	дефицит бюджета	профицит бюджета			
население	трудоспособное население	человек			
отрасли	виды деятельности				
наука					
示例#10
0
from math import sin, cos, radians
from matplotlib import pyplot as plt
from time import time
from utilites import load

import numpy as np

x_coordinates = []
y_coordinates = []

x, y, z = 0, 0, 0

out = load('scan-03.json')


def iter_measurments():
    for x in out:
        yield x


def normalize(layer):
    dst = np.zeros(361)
    cnt = np.ones(361)
    zzz = np.zeros(361)
    for z, φ, ρ in layer:
        cnt[round(φ)] += 1
        dst[round(φ)] += ρ
        zzz[round(φ)] = z
    dst /= cnt

    rez = []
示例#11
0
import re
import numpy as np

from utilites import load, dump
from xlwt import Workbook

matrix = load('jsondb/матрица для экселя.json')

wb = Workbook()

ws = wb.add_sheet('1')

i = 1
for region in matrix:
    ws.write(0, i, region)
    ws.write(i, 0, region)
    i += 1

j = 1
for region_a in matrix:
    i = 1
    for region_b in matrix:
        ws.write(i, j, matrix[region_a][region_b])
        i += 1
    j += 1

wb.save('/tmp/out.xls')
示例#12
0
from matplotlib import pyplot as plt
from utilites import load, dump, compare

_in = load('test1.json')
регионы = load('регионы.json')
rf = load('rf.json')

for k in rf.keys():
    _in[k].update({'Российская Федерация': rf[k]})

data = {}
for reg_a in регионы:
    row = {}
    for mat in _in.keys():
        found = 0
        for reg_b, idx in _in[mat].items():
            if compare(reg_a.lower(), reg_b.lower()) > 0.9:
                row.update({mat.capitalize(): 1 - idx})
                found = 1
        if not found:
            row.update({mat.capitalize(): 0})

    data.update({reg_a: row})

for reg in data.keys():
    x = 0
    n = 0
    for mat in data[reg].keys():
        x += data[reg][mat]
        n += 1
    x = x / n
示例#13
0
from utilites import load, dump

_in = load('jsondb/секторная структура.json')


def stage_2(_in):
    rez = {}
    for reg in _in.keys():
        data = {}
        for _pok in _in[reg].keys():
            A = _in[reg][_pok][
                'ВРП']  #ВРП по основным видам экономической деятельности
            B = _in[reg][_pok][
                'ЧИСЛ']  #Среднегодовая численность занятых по основным видам экономической деятельности
            X = A / (
                B * 1000
            )  #Расчет производительности труда по основным видам экономической деятельности

            data.update({_pok: X})

        rez.update({reg: data})
    return rez


if __name__ == '__main__':
    _in = load('jsondb/секторная структура.json')
    _out = stage_2(_in)
    dump(_out, 'jsondb/Производительность труда.json')
示例#14
0
from utilites import load, dump

def stage_4(_categories):
    критерии = set([ _categories[k][1] for k in _categories.keys() ])

    число_критериев = len(критерии)

    rez = {}
    for критерий in критерии:
        rez.update({критерий:0})

    for показатель in _categories.keys():
        критерий_показателя = _categories[показатель][1]
        фактор_показателя = _categories[показатель][0]

        rez[критерий_показателя] += 1

    M = {}
    for показатель in _categories.keys():
        критерий_показателя = _categories[показатель][1]
        число_показателей = rez[критерий_показателя]
        m = 1/число_критериев/число_показателей
        M.update({показатель:m})
    return M

if __name__ == '__main__':
    _categories = load('jsondb/categories.json')
    M = stage_4(_categories)
    dump(M,'jsondb/вес показателей.json')
示例#15
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in = load('jsondb/трансформированные данные.json')

регионы = list(_in.keys())
показатели = list(_in[регионы[0]].keys())

data = np.zeros([len(показатели), len(регионы)])

x = 0
for регион in регионы:
    y = 0
    for показатель in показатели:
        data[y, x] = _in[регион][показатель]
        y += 1
    x += 1

rez = {}
i = 0
for показатель in показатели:
    rez.update(
        {показатель: {
            'avg': np.average(data[i]),
            'std': np.std(data[i])
        }})
    i += 1

dump(rez, 'jsondb/avg_std.json')
示例#16
0
import xlwt
from utilites import load

_in1 = load('jsondb/матрица структурных расстояний.json')
_in2 = load('jsondb/regions.json')

for region in _in2:
    code = _in2[region]['code']
    try:
        try:
            distances = _in1[region]
        except KeyError:
            try:
                distances = _in1[_in2[region]['emissname']]
            except KeyError:
                try:
                    if 'Москва' in region:
                        distances = _in1['г. Москва']
                    elif 'Петербург' in region:
                        distances = _in1['г. Санкт-Петербург']
                    elif 'Осетия' in region:
                        distances = _in1['Республика Северная Осетия-Алания']
                except KeyError:
                    pass
        assert distances
        wb = xlwt.Workbook()
        ws = wb.add_sheet(region[:20])
        ws.write(0, 0, "N п/п")
        ws.write(0, 1, "Регион")
        ws.write(0, 2, "Индекс")
        i = 1
示例#17
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 12:21:02 2019

@author: dan
"""
from utilites import load, dump
from rutermextract import TermExtractor as TE
from sys import stderr

to_del = set()
udk = load('udk.json')

for code, value in [(k, udk[k]['text']) for k in udk.keys()]:
    if value:
        terms = [t.normalized for t in TE()(value)]
        data = udk[code]
        data.update({'terms': terms})
        udk.update({code: data})
        print(code, terms, file=stderr)
    else:
        to_del |= {code}

for code in to_del:
    udk.pop(code)

dump(udk, 'indexed.udk.json')
示例#18
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in = load('jsondb/исходные данные (ред).json')
скос0 = load('jsondb/скос.json')

регионы = list(_in.keys())
показатели = list(_in[регионы[0]].keys())

data = np.zeros([len(показатели), len(регионы)])

x = 0
for регион in регионы:
    y = 0
    for показатель in показатели:
        data[y,x] = _in[регион][показатель]
        y += 1
    x += 1


for i_показатель in range(len(показатели)):
    скос = скос0[показатели[i_показатель]]
    if abs(скос) > 0.5:
        скосы = []
        for n in [1,2,3,4]:
            скос_i = sp.stats.skew(data[i_показатель] ** (1/n), 0, 0)
            скосы += [(abs(скос_i), n)]
        
        n = min(скосы)[1]
示例#19
0
def find_stop_words(text):
    rez = []
    for word in wpt.tokenize(text):
        tags = ma.parse(word)[0].tag
        if 'UNKN' in tags or \
           'LATN' in tags or \
           'PNCT' in tags or \
           'NUMB' in tags or \
           'ROMN' in tags:
            rez += [word]
    return rez


try:
    word_normal_form = load('word_normal_form.json')
except FileNotFoundError:
    word_normal_form = {}

text = BeautifulSoup(open('lection.html').read(), 'lxml').text

try:
    stop_words = set(load('stop_words.json'))
except FileNotFoundError:
    stop_words = find_stop_words(text)


def get_normal_form(word):
    try:
        nf = word_normal_form[word]
    except KeyError:
示例#20
0
from matplotlib import pyplot as plt
from utilites import load, dump, compare

_in = load('test2.json')

russia = _in['Российская Федерация']
tatars = _in['Пермский край']

with open('Российская Федерация.dot','w') as dot:
    dot.write("digraph g {\n")
    dot.write('\t" " [shape = none];\n\toverlap = false;\n\tsep=-0.8\n')
    for mat, val in russia.items():
        if mat != "avg":
            dot.write('\t"%s" [shape = none, fontsize = %s, fontname="sans"]\n' % (mat.replace(' ','\\n'), val * 30))
    for mat, val in russia.items():
        if mat != "avg":
            dot.write('\t" " -> "%s" [style=invis] \n' % mat.replace(' ','\\n'))
    dot.write("}\n")
        
with open('Пермский край.dot','w') as dot:
    dot.write("digraph g {\n")
    dot.write('\t" " [shape = none];\n\toverlap = false;\n\tsep=-0.8\n')
    for mat, val in tatars.items():
        if mat != "avg":
            fontsize = 30 * val ** 2 if val > 0 else 10
            dot.write('\t"%s" [shape = none, fontsize = %s, fontname="sans"]\n' % (mat.replace(' ','\\n'), fontsize))
    for mat, val in russia.items():
        if mat != "avg":
            dot.write('\t" " -> "%s" [style=invis] \n' % mat.replace(' ','\\n'))
    dot.write("}\n")
        
示例#21
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 27 19:38:22 2018

@author: dan
"""
import re
from utilites import dump, load
from rutermextract import TermExtractor as TE                       
te = TE()

res = {}
subres = {}
for line in [ a.strip('\n') for a in load('specs.json'):
    try:
        m = re.match(r'[А-Я]+', line)
        if m.group() == line.split()[0]:
            name = line.capitalize().strip()
            try:
                res.update({oldname:subres})
                oldname = name
            except NameError:
                oldname = name
            subres = {}
        else:
            a = [ str(a) for a in te(line) ]
#            nname = ' и '.join(a[:2]).capitalize()
            nname = line.capitalize().strip()
            subres.update({nname:a})
    except AttributeError:
示例#22
0
from utilites import load, dump

def stage_3(_in1, _in2, _in3):
    for reg in _in2.keys():
        x = _in1[reg]
        _in2[reg]["Количество людей с высшим образованием из числа занятых и безработных (тыс.человек)"] = x
        for k in _in3[reg].keys():
            _in2[reg][k] = _in3[reg][k]
    return _in2

if __name__ == '__main__':
    _in1 = load('jsondb/Количество людей с высшим образованием из числа занятых и безработных.json')
    _in2 = load('jsondb/исходные данные.json')
    _in3 = load('jsondb/Производительность труда.json')
    _out = stage_3(_in1, _in2, _in3)  
    dump(_out, 'jsondb/исходные данные (ред).json')
示例#23
0
from utilites import dump, load
from bs4 import BeautifulSoup
import numpy as np

sentences = load('intuit_sents.json')
terms = load('intuit_terms.json')

try:
    text = load('tet.json')
except FileNotFoundError:    
    candidates = []
    for tokens_a in ( set(x[0]) for x in terms ):
        for tokens_b, n in ( (set(sentences[x]['tokens']), x) for x in sentences):
            if tokens_a & tokens_b: 
                candidates += [(int(n), len(tokens_a & tokens_b) / len(tokens_b), tokens_a & tokens_b)]
                
    candidates = sorted(candidates, key=lambda x: x[1], reverse=1)
    
    text = open('text.csv','w')
    used = []
    tokens = candidates[0][2]
    for pos, q, tags in candidates:
        if q > 0:
            i = pos
            s = sentences[str(i)]
            if i not in used:
                text.write("%s ^ %s ^ %s\n" % (s['sentence'], i, q))
                used += [i]
    
    text.close()
    text = sorted(text, key=lambda x: x[1])
示例#24
0
возможность цепочки квантовых превращений. Изолируя область наблюдения от 
посторонних шумов, мы сразу увидим, что излучение одномерно облучает торсионный 
кварк. Туманность трансформирует плоскополяризованный фотон. Квантовое 
состояние экстремально синхронизует ультрафиолетовый газ. Плазменное 
образование виртуально.

Осциллятор, как следует из совокупности экспериментальных наблюдений, поглощает 
фонон. Эксимер индуцирует сверхпроводник. Очевидно, что излучение оптически 
однородно. Сингулярность изотропно искажает квант. Расслоение вращает 
сверхпроводник. Солитон, в отличие от классического случая, неустойчив 
относительно гравитационных возмущений.
""".lower()


def get_udk(text, udk):
    terms_w = [(t.normalized, t.count) for t in TE()(text)]
    terms = set([_[0] for _ in terms_w])
    rez = {}
    for code, udk_terms in [(k, set(udk[k]['terms'])) for k in udk.keys()
                            if udk[k]['terms']]:
        x = terms & udk_terms
        if x:
            parts = code.split('.')
            print(parts)

    return rez


if __name__ == '__main__':
    udk = load('indexed.udk.json')
    print(get_udk(физика, udk))
示例#25
0
from glob import glob
from rutermextract import TermExtractor as TE
from nltk.tokenize import PunktSentenceTokenizer as PST
from nltk.tokenize import SpaceTokenizer as ST
from pymorphy2 import MorphAnalyzer
from utilites import load, dump, compare, compare_phrase
from math import exp, pow

import re

ngrams = load('ngrams.json')
to_upper_list = ['ВВП', 'ЕГЭ', 'РФ', 'ОАО', 'ЗАО', 'АПК', 'ВСТО', 'ВТО', 'ЦФО','СЗФО','ЮФО','СКФО','ПФО','УрФО','СФО','ДФО','ДВФО',]

ma = MorphAnalyzer()
pst = PST()
st = ST()
term_extractor = TE()

def k(t):
    return t.count * pow(len(st.tokenize(t.normalized)),2)
    
def norm(x):
    return pow(x, 1/2)
        
def term_normal_form(term):
    _in = term.normalized
    if _in.count(' ') == 0:
        if _in.upper() in to_upper_list:
            return _in.upper() 
        elif len(set(list(_in.upper()))) == 1:
            return 'test'
示例#26
0
        for region in regions:
            code = regions[region]["code"]
            if region in neib_regions[cluster].keys():
                clu.update({code:"#FB6C3F"})
            elif region in all_neib:
                clu.update({code:"#F0F075"})
            else:
                clu.update({code:"#8A92AB"})
        colors += [clu]
    return colors

if __name__ == '__main__':
    end = False
    while not end:
        try:
            fedstat_data = load('fedstat_data.json')
            filtered_data = load('filtered_data.json')
            structured_data = load('structured_data.json')
            clusters = load('clusters.json')
            spec_data = load('spec_data.json')

            calculated_sums = load('calculated_sums.json')
            calculated_lq = load('calculated_lq.json')
            distances = load('distances.json')
            cluster_hi_lo = load('cluster_hi_lo.json')
            neib_regions = load('neib_regions.json')
            region_colors = load('region_colors.json')
            end = True
        except FileNotFoundError as e:
            if e.filename == 'fedstat_data.json':
                fedstat_data = download_fedstat()
示例#27
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in = load('jsondb/исходные данные (ред).json')

регионы = list(_in.keys())
показатели = list(_in[регионы[0]].keys())

data = np.zeros([len(регионы), len(показатели)])

x = 0
for регион in регионы:
    y = 0
    for показатель in показатели:
        data[x, y] = _in[регион][показатель]
        y += 1
    x += 1

скос = sp.stats.skew(data, 0, 0)

rez = {}
i = 0
for показатель in показатели:
    rez.update({показатель: скос[i]})
    i += 1

dump(rez, 'jsondb/скос.json')
示例#28
0
from requests import get
from bs4 import BeautifulSoup as BS
from utilites import load, dump, compare

regions = load('data/regions.json')
distances = load('data/distances.json')


def get_wiki_center(region):
    def is_city(region):
        x = soup.find('div', {'class': "mw-parser-output"}).table.tbody.tr.text
        return x.count('Город') > 0 or x.count('Столица') > 0

    try:
        return regions[region]['center']
    except KeyError:
        soup = BS(get('https://ru.wikipedia.org/wiki/%s' %
                      region.replace(' ', '_')).content,
                  features="lxml")
        if is_city(region):
            regions[region].update({'center': region})
            return get_wiki_center(region)
        for th in soup('th'):
            if  th.text == 'Административный центр' or \
                th.text == 'Столица':
                cnt = th.parent.td.text.strip().strip('\n')
                regions[region].update({'center': cnt})
                return get_wiki_center(region)


def get_distance_adi(reg_A, reg_B):