def delete_employees(self, employee_ids):
     os.chdir(self._save_path)
     for id in employee_ids:
         try:
             os.remove("{}.emp".format(id))
         except:
             IO.stdErr("Could not delete employee {}".format(id))
    def update_employee(self, employee):
        """
        updates the record for the supplied Employee object
        if no employee record with the supplied employee id exists,
        nothing happens. use save_employee for this.
        @params:
            employee: The Employee object for which to update the record
        @return: -
        """
        lines = []
        updated = False
        with open(self._file) as source:
            for line in source:
                if line.startswith(CSV_COMMENT):
                    lines.append(line)
                    continue
                split = line.split(",")
                if split[0] == employee.employee_id:
                    lines.append(employee.get_csv_line())
                    updated = True
                    continue
                lines.append(line)

        with open(self._file, "w") as target:
            for line in lines:
                target.write(line)

        if not updated:
            IO.stdErr("Could not find the supplied employee to update")
 def update_employee(self, employee):
     os.chdir(self._save_path)
     target_file = "{}.emp".format(employee.employee_id)
     if not os.path.isfile(target_file):
         IO.stdErr("Could not find the supplied employee to update")
         return
     self.save_employees([employee])
Example #4
0
    def prepare_to_move_files(self, zip_dict, conf):
        #
        if not os.path.exists(conf.classified_folder):
            os.mkdir(conf.classified_folder)

        #
        move_list = []
        unzip_list = []

        # manager
        for manager in self.manager_list:
            ma_path = os.path.join(conf.classified_folder, manager.name)

            # module
            for module in manager.module_list:
                mo_path = os.path.join(ma_path, module.name)

                # line
                for line in module.line_list:
                    line_folder = IOHelper.Naming.valid_name(
                        line.name)  # line num is not specified
                    li_path = os.path.join(mo_path, line_folder)

                    # ini, server side do not need ini
                    if conf.write_ini:
                        ini = IOHelper.INI()
                        line.report_list = sorted(line.report_list)
                        ini.write(li_path + '\\error_package.ini',
                                  line.report_list)

                    #
                    for i, report_id in enumerate(line.report_list):
                        # move small portion of zip files to folder
                        if 0 < conf.num_zip_move <= i:
                            continue

                        # src
                        # dict struct: id->(folder, zip)
                        src = zip_dict[report_id][1]

                        # dst
                        dfn = IOHelper.DumpFileName(conf)
                        zip_fname = dfn.zip_name_from_id(report_id)
                        dst = os.path.join(li_path, zip_fname)

                        # print(dst, len(line.report_list))

                        # add to move list
                        move_list.append((src, dst))

                        if 0 <= conf.num_zip_extract <= i:
                            continue

                        # add to unzip list
                        unzip_list.append(dst)

        return move_list, unzip_list
 def save_employees(self, employees):
     for emp in employees:
         try:
             file_name = "{}.emp".format(emp.employee_id)
             file_path = os.path.join(self._save_path, file_name)
             pickle.dump(emp, open(file_path, "wb"))
         except:
             err_text = "Could not serialise {}"
             IO.stdErr(err_text.format(emp.employee_id))
Example #6
0
    def __init__(self, base_path):
        #ensure base path exists
        if not os.path.exists(base_path):
            IOHelper.create_directory(base_path)

        #make instance paths
        self.inst_path = os.path.join(base_path, IOHelper.generate_uuid())
        self.in_path = os.path.join(self.inst_path, "in")
        self.out_path = os.path.join(self.inst_path, "out")
 def delete_employees(self, employee_ids):
     c = 'DELETE FROM employees WHERE id="{}"'
     for id in employee_ids:
         command = c.format(id)
         try:
             self._execute_command(command)
         except Exception as err:
             IO.stdErr("There was an error deleting employee {}".format(id))
             print(str(err))
 def update_employee(self, emp):
     c = 'UPDATE employees SET gender = "{}", age = {}, sales = {},' \
         + ' bmi = "{}", salary = {}, birthday = "{}" WHERE id ="{}"'
     command = c.format(emp.gender, emp.age, emp.sales, emp.bmi, emp.salary,
                        emp.birthday, emp.employee_id)
     try:
         self._execute_command(command)
     except Exception as err:
         IO.stdErr("There was an error deleting employee {}".format(id))
         print(str(err))
 def save_employees(self, employees):
     c = 'INSERT INTO employees VALUES ("{}", "{}", "{}", "{}", "{}", "{}", "{}")'
     for e in employees:
         command = c.format(e.employee_id, e.gender, e.age, e.sales, e.bmi,
                            e.salary, e.get_birthday_string())
         try:
             self._execute_command(command)
         except Exception as err:
             IO.stdErr("There was an error deleting employee {}".format(id))
             print(str(err))
def GetConfiguration():
    try:
        if IOHelper.IsInRaspberry():
            f = urllib.request.urlopen(RemoteConfigurationFile)
            mybytes = f.read()
            configurationFileContent = mybytes.decode("utf8")
        else:
            configurationFileContent = IOHelper.ReadFromFile(LocalConfigurationFile)
        configuration = Configuration.from_json(json.loads(configurationFileContent))
        return configuration
    except:
        raise
        return None
def main():

    file = IOHelper().checkArg(sys.argv)
    if (len(file) < 1):
        print("Missing file")
        exit(1)

    d = Dataset()
    d.loadFile(file[0])

    fig, axes = plt.subplots(figsize=(18, 10))
    fig.tight_layout()

    for index in range(6, 19):

        mean = d.mean(d.getFeature(index))
        std = d.standardDeviation(d.getFeature(index), mean)

        if mean >= -10 and mean <= 10 and std >= -10 and std <= 10:
            addFeatureOnSubplot(index, d.getFeature(index), d.getName(index),
                                1)
        elif mean >= -500 and mean <= 500 and std >= -500 and std <= 500:
            addFeatureOnSubplot(index, d.getFeature(index), d.getName(index),
                                2)
        elif mean >= -2000 and mean <= 2000 and std >= -2000 and std <= 2000:
            addFeatureOnSubplot(index, d.getFeature(index), d.getName(index),
                                3)
        else:
            addFeatureOnSubplot(index, d.getFeature(index), d.getName(index),
                                4)

    # plt.title(d.getName(index))

    plt.savefig('scatter_plot.png')
    plt.show()
Example #12
0
    def parse_webpage(url_base, start_idx, end_idx):
        # download webpages
        try:
            vd = IOHelper.VisualizeDownload(url_base)
            page_info = vd.go()
        except Exception as e:
            write_information("failed to get web page!")
            return []

        # decode to utf-8
        page_info = page_info.decode('utf-8')
        # print(page_info)

        # find all report names
        p_name = re.compile(r'>(error_report_([\d]*).zip)<')
        id_list = p_name.findall(page_info)  # currently unsorted
        # print(id_list)
        id_list = sorted(id_list, key=lambda x: int(x[1]))
        write_information(
            'totally <%d> files found on server, ranging from %s to %s' %
            (len(id_list), id_list[0][1], id_list[-1][1]))

        # create file list
        new_id_list = []
        for report in id_list:
            idx = int(report[1])
            if start_idx >= 0 and idx < start_idx:
                continue
            if end_idx >= 0 and idx > end_idx:
                continue
            new_id_list.append(idx)
        return new_id_list
Example #13
0
def main():

    file = IOHelper().checkArg(sys.argv)
    if (len(file) < 1):
        print("Missing file")
        exit(1)

    d = Dataset()
    d.loadFile(file[0])

    fig, axes = plt.subplots(figsize=(18, 10))
    fig.tight_layout()

    start = 6
    width = 13

    widthStart = 0
    widthEnd = widthStart + width
    ystart = start
    for i in range(width):
        drawOneSub(d, start, ystart, range(widthStart, widthEnd))
        widthStart += width
        widthEnd += width
        start += 1
    print("")

    # plt.title(d.getName(index))

    plt.savefig('scatter_plot.png')
    plt.show()
    def get_all_employees(self):
        os.chdir(self._save_path)
        all_files = glob("*.emp")
        employees = []

        for f in all_files:
            try:
                new_emp = pickle.load(open(f, "rb"))
                if type(new_emp).__name__ == "Employee":
                    employees.append(new_emp)
                else:
                    err_text = "File {} does not contain an employee object."
                    IO.stdErr(err_text.format(f))
            except:
                err_text = "Could not read file: {}"
                IO.stdErr(err_text.format(f))
        return employees
Example #15
0
def get_devices():
    report = listed_command("adb devices -l")
    devices = []
    if len(report) > 1:
        for lines in report[1:]:
            if lines != "":
                deviceIP = IOHelper.until_1st_space(lines)
                info = IOHelper.after_1st_space(lines).split(" ")
                product = info[1].split(":")[1]
                model = info[2].split(":")[1]
                tp_id = info[1].split(":")[1]
                devices.append(
                    RemoteDevice(deviceIP=deviceIP,
                                 product=product,
                                 model=model,
                                 transport_id=tp_id))
    return devices
Example #16
0
    def write_excel(self, fname):

        print("modifications: ")
        print(self.modify_rule)

        rules = self.get_raw_rules()

        ex = IOHelper.XLS()
        ex.write(fname, self.data, rules)
Example #17
0
    def process(self, report_id, f_info):
        f_datetime = None
        f_size = None
        if f_info:
            f_datetime = f_info[0]
            f_size = f_info[1]

        #
        dfn = IOHelper.DumpFileName(self.conf)
        filename = dfn.zip_name_from_id(report_id)

        self.zip_path = os.path.join(self.zip_folder, filename)
        self.unzip_dir = os.path.join(self.unzip_folder,
                                      filename.split('.')[0])
        dmp_path = os.path.join(self.unzip_dir, self.dump_name)
        xml_path = os.path.join(self.unzip_dir, self.dump_xml)

        self.remove_overdue(self.zip_path, self.unzip_dir, xml_path)

        self.status_valid = True

        # 下载文件
        res = self.try_download(filename, self.zip_path)
        if not self.status_valid:
            self.status_valid = True
            return False
        if not res:
            return False

        # 修改文件时间
        res = self.try_modifytime(filename, self.zip_path, f_datetime)
        if not self.status_valid:
            self.status_valid = True
            return False
        if not res:
            return False

        # 解压
        res = self.try_unzip(filename, self.zip_path, self.unzip_dir)
        if not self.status_valid:
            self.status_valid = True
            return False
        if not res:
            return False

        # 分析
        res = self.try_analyze(filename, self.zip_path, self.unzip_dir,
                               dmp_path, xml_path)
        if not self.status_valid:
            self.status_valid = True
            return False
        if not res:
            return False

        return True
Example #18
0
    def get_classified_file(self):
        report_list = []
        dfn = IOHelper.DumpFileName(self.conf)
        for root, dirs, files in os.walk(self.conf.classified_folder):
            for file in files:
                if file.startswith(
                        self.conf.folder_prefix) and file.endswith(".zip"):
                    report_list.append(dfn.get_report_id(file.split('.')[0]))

        write_information('totally %d classified files' % len(report_list))
        return sorted(report_list)
Example #19
0
    def load(self, fpath):
        f = codecs.open(fpath, 'r', 'utf-8')
        for line in f.readlines():
            data = line.split()
            if len(data) < 3:
                continue

            record = IOHelper.xls_record()
            record.module = data[0]
            record.manager = data[1]
            record.line = data[2]
            self.invalid_list.append(record)
Example #20
0
def main():

    file = IOHelper().checkArg(sys.argv)
    if (len(file) < 1):
        print("Missing file")
        exit(1)

    d = Dataset()
    d.loadFile(file[0])

    d.printFeatureHeader()
    d.printAllFeature()
def main():

    nbOutput = 4

    file = IOHelper().checkArg(sys.argv)
    if (len(file) < 2):
        print("Missing file")
        exit(1)

    d = Dataset()
    d.loadFile(file[0])

    featuresId = range(7, 19)
    # nbInput = len(featuresId)
    X = generateDataset(d, featuresId)

    X, nbInput = d.featureExpand(d, X)
    X = d.featureRescale(d, X)

    allWeight, AllOutput = csvToArray(file[1])

    allclassifier = MultiClassifier(nbInput, AllOutput)
    allclassifier.initWeight(allWeight)

    with open('houses.csv', 'w') as file:
        file.write("Index,Hogwarts House\n")
        for i, d in enumerate(X):
            name = allclassifier.predict(d)
            file.write(str(i) + "," + name + "\n")
    def get_all_employees(self):
        command = "SELECT * FROM employees"
        lines = self._execute_command(command)

        employees = []

        for l in lines:
            try:
                parameters = {}
                parameters["empid"] = IC.convert_input(l[0], "empid")
                parameters["gender"] = IC.convert_input(l[1], "gender")
                parameters["age"] = IC.convert_input(l[2], "age")
                parameters["sales"] = IC.convert_input(l[3], "sales")
                parameters["bmi"] = IC.convert_input(l[4], "bmi")
                parameters["salary"] = IC.convert_input(l[5], "salary")
                parameters["birthday"] = IC.convert_input(l[6], "birthday")
                employees.append(employee.create_employee(parameters))
            except Exception as err:
                IO.stdErr("Error in translating database row: " + str(l))
                IO.stdErr(str(err))
                print(parameters)
        return employees
Example #23
0
    def create_folders(self):
        """create folders for new record"""
        for record in self.data:
            if record.update_folder:  # no corresponding folder for this record, create it
                folder = record.to_folder(self.config.classified_folder)
                if not os.path.exists(folder):
                    os.mkdirs(folder)

                # write ini file for current folder
                ini = IOHelper.INI()
                ini.write(os.path.join(folder, 'error_package.ini'),
                          record.report_list)

                # move zip files to current folder
                report_list = record.report_list[0:conf.num_zip_move]
                fm = IOHelper.FileMover(self.config)
                move_list = fm.move(conf.zip_folder, folder, report_list)

                zip_list = [pair[1] for pair in move_list]
                fm.unzip_files(zip_list)

                record.update_folder = False
Example #24
0
    def to_records(self):
        records = []
        for manager in self.manager_list:
            for module in manager.module_list:
                for line in module.line_list:

                    rec = IOHelper.xls_record()
                    rec.line = line.name
                    rec.module = module.name
                    rec.manager = manager.name
                    rec.num = len(line.report_list)
                    rec.report_list = line.report_list

                    records.append(rec)
        return records
Example #25
0
    def get_raw_rules(self):
        raw_rules = []
        for k, v in self.modify_rule.items():
            raw_rule = IOHelper.xls_record()

            raw_rule.module = k[0]  # module
            # raw_rule.version        version ignored
            raw_rule.manager = k[1]  # manager
            raw_rule.line = k[2]  # line
            # raw_rule.num       num ignored
            # raw_rule.remark       remark ignored
            raw_rule.modify_code = v[0]  # modify code
            raw_rule.modify_info = v[1]  # modify info

            raw_rules.append(raw_rule)
        return raw_rules
Example #26
0
def fetch_analyze(conf,
                  md,
                  repeat_num=-1,
                  interval=5,
                  ignore_classified=False,
                  remove_after_use=False):
    # if not prepare_log(conf):
    #     write_information('prepare log failed!')
    #     return

    if not prepare_dll(conf):
        write_information('prepare dll failed!')
        write_information('dll path: %s' % conf.dumpload_dll)
        return

    if not prepare_symbol(conf):
        write_information('prepare symbol failed!')
        write_information('symbol path: %s' % conf.symbol_folder)
        return

    js = JobAssigner(conf, md)

    write_information('system started...')
    count = 0
    while True:
        if 0 < repeat_num and repeat_num <= count:
            break
        if count > 99990:
            count = 0
        write_information("<The %s time>" % count)
        count += 1

        # 清理之前失效的临时文件夹
        if remove_after_use:
            dc = IOHelper.DirCleaner(conf)
            # dc.clean_zip()
            dc.clean_unzip()

        js.go(conf.thread_num,
              conf.idx_beg,
              conf.idx_end,
              enquire_webpage=conf.retrieve_webpage,
              ignore_classified=ignore_classified,
              remove_after_use=remove_after_use)
        time.sleep(interval)

    return js.report_list
Example #27
0
    def record_from_str(self, s):
        # vs string structure
        # module.dll ! classname :: otherinfo 行 lineidx + 0x89 字节
        # GlobalEnvironment.dll!CGlobalEnvLite::ReleaseObject()  行200 + 0x5 字节

        record = IOHelper.xls_record()
        record.module, clas, func, idx = IOHelper.VSDbgNaming.get_mod_clas_func_idx(
            s)
        record.manager = self.md.which_manager(record.module, clas)

        fname = IOHelper.WinDbgNaming.name_from_clas_func_idx(clas, func, idx)
        record.line = fname[:80]

        # print("new record:")
        # print(record)

        return record
 def get_all_employees(self):
     """
     reads the file this object was initiated with and returns all contained
     employees as Employee objects in a list
     @params: -
     @return: list of Employee objects, may be empty
     """
     employees = []
     errors = []
     # using file as a resource so I dont forget to close it
     with open(self._file) as source:
         skipped_first = False
         for line in source:
             if not skipped_first:
                 skipped_first = True
                 continue
             if line.startswith(CSV_COMMENT):
                 #print("Encountered comment: " + line)
                 continue
             try:
                 #print("reading line: " + line)
                 split = line.split(",")
                 # TODO: HIGH: validate data
                 emp_id = IC.convert_input(split[0], "empid")
                 gender = IC.convert_input(split[1], "gender")
                 sales = IC.convert_input(split[2], "sales")
                 bmi = IC.convert_input(split[3], "bmi")
                 salary = IC.convert_input(split[4], "salary")
                 bday = IC.convert_input(split[5], "birthday")
                 age = IC.convert_input(split[6], "age")
                 attributes = {
                     "empid": emp_id,
                     "gender": gender,
                     "sales": sales,
                     "bmi": bmi,
                     "salary": salary,
                     "birthday": bday,
                     "age": age
                 }
                 # TODO: high: catch ValueError from employee creation
                 employees.append(employee.create_employee(attributes))
             except Exception as err:
                 errors.append("Error when reading line: {}".format(line))
     [IO.stdErr(e) for e in errors]
     return employees
Example #29
0
    def get_update_detail(self):
        #
        changes = {}
        for idx, record in enumerate(self.data):
            new_record = copy.deepcopy(record)

            k = (record.module, record.manager, record.line)
            if not self.modify_rule.get(k):  # good record, no need to update
                continue

            code, info = self.modify_rule[k]
            # the modify code by modify rule must be negative!
            if code == -1:
                # delete
                # make the new record an empty one
                new_record = IOHelper.xls_record()
            elif code == -2:
                # rename
                # load new information from dump symbol
                new_record = self.record_from_str(info)
                new_record.num = record.num
                new_record.report_list = record.report_list
            changes[idx] = new_record
        return changes
def main_routine (wd="./",cfg="./python/parameter.cfg",cnt=11,delay=27.725,sptype=0,phase=0.0):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  FuncInfo      = sp.zeros([3,cnt])
  FuncInfoPhase = sp.zeros([3,cnt])
  FuncShiftRead = sp.zeros([3,cnt,functime.size],complex)

  denom    = sp.zeros([3])
#  denom[0] = cumtrapz( sp.absolute(Reg2DownRead[ti:tf])**2, x=None, dx=dt )[-1] 
#  denom[1] = cumtrapz( sp.absolute(Reg2UpRead[ti:tf])**2, x=None, dx=dt )[-1] 

  denom[0] = cumtrapz( sp.absolute(Reg2UpRead[ti:tf]+Reg2DownRead[ti:tf])**2, x=None, dx=dt )[-1] 
  denom[1] = cumtrapz( sp.real(Reg2UpRead[ti:tf]+Reg2DownRead[ti:tf]), x=None, dx=dt )[-1] 
  denom[2] = cumtrapz( sp.imag(Reg2UpRead[ti:tf]+Reg2DownRead[ti:tf]), x=None, dx=dt )[-1] 

#  denom[0] = sp.absolute[denom[0]]
#  denom[1] = sp.absolute[denom[1]]
#  denom[2] = sp.absolute[denom[2]]

  for i in sp.arange(0.0,cnt):
    myDelay = i/(cnt-1.0)*delay
    

    shift=sp.absolute(time['read'][:]-(functime[0]-myDelay)).argmin()-1
    print myDelay,functime[0],functime[0]-myDelay,shift,time['read'][shift]

    
#    FuncShiftRead[0,i,:] = Reg2DownRead[shift:shift+functime.size]
    FuncShiftRead[0,i,:] = sp.exp(-1j*phase*sp.pi)*Reg2Down[shift:shift+functime.size] + Reg2Read[shift:shift+functime.size]
    FuncShiftRead[1,i,:] = Reg2UpRead  [ti:tf]
    FuncShiftRead[2,i,:] = FuncShiftRead[0,i,:] + FuncShiftRead[1,i,:]


    FuncInfo[0,i]        = cumtrapz( sp.absolute(FuncShiftRead[2,i,:])**2, x=None, dx=dt )[-1]
    FuncInfo[0,i]       /= sp.absolute(denom[0])

    FuncInfo[1,i]        = cumtrapz( sp.real(FuncShiftRead[2,i,:]), x=None, dx=dt )[-1]
    FuncInfo[1,i]       /= sp.absolute(denom[1])

    FuncInfo[2,i]        = cumtrapz( sp.imag(FuncShiftRead[2,i,:]), x=None, dx=dt )[-1]
    FuncInfo[2,i]       /= sp.absolute(denom[2])

#    FuncInfoIntegrand    = sp.absolute(FuncSuperRead[i,:]) * sp.absolute(Reg2UpRead[ti:tf])
#    FuncInfo[i,1]        = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]/denom[1]

#    FuncInfoIntegrand    = FuncSuperRead[i,:].conj() * Reg2UpRead[ti:tf]
#    FuncInfoPhase[i,0]   = cumtrapz( FuncInfoIntegrand.real, x=None, dx=dt )[-1]/denom[1]
#    FuncInfoPhase[i,1]   = cumtrapz( FuncInfoIntegrand.imag, x=None, dx=dt )[-1]/denom[1]


  xx, yy = sp.meshgrid(functime,sp.linspace(0.0,delay,cnt))
  xx0    = sp.linspace(0.0,delay,cnt)

#  zzR    = FuncSuperRead.real/FuncSuperRead.real.max()
#  zzI    = FuncSuperRead.imag/FuncSuperRead.imag.max()
  zz0A    = sp.absolute(FuncShiftRead[0,:,:])**2/((sp.absolute(FuncShiftRead[0:1,:,:])**2).max())
  zz1A    = sp.absolute(FuncShiftRead[1,:,:])**2/((sp.absolute(FuncShiftRead[0:1,:,:])**2).max())
  zzDA    = sp.absolute(FuncShiftRead[2,:,:])**2/((sp.absolute(FuncShiftRead[0:1,:,:])**2).max())

  zmin   = -1.5
  zmax   = +1.0
  fs     = 20

  fig  = plt.figure()

  if sptype==0: # 3d plotting
    fig0 = fig.add_subplot(231, projection='3d')
    fig0.plot_surface(xx, yy, zz0A, rstride=1, cstride=5, cmap="Blues", alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
    fig0.contourf(xx, yy, zz0A, zdir='z', offset=zmin, cmap="Blues", vmin=-1, vmax=1,zorder=1.0)
    fig0.set_zlim(zmin,zmax)
    fig0.set_title("a) normalized $|A_0(t-\Delta t)|^2$",fontsize=fs)
    fig0.set_xlabel("$t$ in ns",fontsize=fs)
    fig0.set_ylabel("$\Delta t$ in ns.",fontsize=fs)

    fig1 = fig.add_subplot(232, projection='3d')
    fig1.plot_surface(xx, yy, zz1A, rstride=1, cstride=5, cmap="Reds", alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
    fig1.contourf(xx, yy, zz1A, zdir='z', offset=zmin, cmap="Reds", vmin=-1, vmax=1,zorder=1.0)
    fig1.set_zlim(zmin,zmax)
    fig1.set_title("b) normalized $|A_1(t)|^2$",fontsize=fs)
    fig1.set_xlabel("$t$ in ns",fontsize=fs)
    fig1.set_ylabel("$\Delta t$ in ns.",fontsize=fs)

    fig2 = fig.add_subplot(233, projection='3d')
    fig2.plot_surface(xx, yy, zzDA, rstride=1, cstride=5, cmap="Greens", alpha=0.5,zorder=11.0,vmin=-1, vmax=4)
    fig2.contourf(xx, yy, zzDA, zdir='z', offset=zmin, cmap="Greens", vmin=-1, vmax=4,zorder=1.0)
    fig2.set_zlim(zmin,4*zmax)
    fig2.set_title("c) normalized $|A_0(t-\Delta t)-A_1(t)|^2$",fontsize=fs)
    fig2.set_xlabel("$t$ in ns",fontsize=fs)
    fig2.set_ylabel("$\Delta t$ in ns.",fontsize=fs)
  else :
    pltId=(cnt-1)/2
    yMax = round(max(max(zzDA[0,:]),max(zzDA[pltId,:]),max(zzDA[-1,:]))) + 0.5
    yMin = min(min(zzDA[0,:]),min(zzDA[pltId,:]),min(zzDA[-1,:]))

    plt.subplot2grid((2,3),(0,0))
    plt.title("a) no delay, $\Delta t=0$",fontsize=fs)
    plt.plot(functime,zzDA[0,:],linewidth="2",color="black")
    plt.xlabel("$t$ in ns",fontsize=fs)
    plt.ylabel("$|A_0(t-\Delta t) + A_1(t)|^2$ in a.u.",fontsize=fs)
    plt.xlim(min(functime),max(functime))
    plt.ylim(yMin,yMax)
   

    plt.subplot2grid((2,3),(0,1))
    plt.title("b) medium delay, $\Delta t=\Delta t_{max}/2=$"+"{:}ns".format(pltId/(cnt-1.0)*delay),fontsize=fs)
    plt.plot(functime,zzDA[pltId,:],linewidth="2",color="black")
    plt.xlabel("$t$ in ns",fontsize=fs)
    plt.xlim(min(functime),max(functime))
    plt.ylim(yMin,yMax)
    
    plt.subplot2grid((2,3),(0,2))
    plt.title("c) maximal delay, $\Delta t=\Delta t_{max}=$"+"{:}ns".format(delay),fontsize=fs)
    plt.plot(functime,zzDA[-1,:],linewidth="2",color="black")
    plt.xlabel("$t$ in ns",fontsize=fs)
    plt.xlim(min(functime),max(functime))
    plt.ylim(yMin,yMax)


  plt.subplot2grid((2,3),(1,0))
  plt.plot(xx0,FuncInfo[1,:],linewidth="2",color="red")
  plt.title("d) area under $Re[A_0(t-\Delta t)+A_1(t)]$",fontsize=fs)
  plt.xlabel("$\Delta t$ in ns",fontsize=fs)
  plt.xlim(min(xx0),max(xx0))

  plt.subplot2grid((2,3),(1,1))
  plt.plot(xx0,FuncInfo[2,:],linewidth="2",color="magenta")
  plt.title("e) area under $Im[A_0(t-\Delta t)+A_1(t)]$",fontsize=fs)
  plt.xlabel("$\Delta t$ in ns",fontsize=fs)
  plt.xlim(min(xx0),max(xx0))

  plt.subplot2grid((2,3),(1,2))
  plt.plot(xx0,FuncInfo[0,:],linewidth="2",color="green")
  plt.title("f) area under $|A_0(t-\Delta t)+A_1(t)|^2$",fontsize=fs)
  plt.xlabel("$\Delta t$ in ns",fontsize=fs)
  plt.xlim(min(xx0),max(xx0))

#  FuncInfoPhase[:,0]-=min(FuncInfoPhase[:,0])
#  FuncInfoPhase[:,0]/=0.5*max(sp.absolute(FuncInfoPhase[:,0]))
#  FuncInfoPhase[:,0]-=1.0

#  FuncInfoPhase[:,1]-=min(FuncInfoPhase[:,1])
#  FuncInfoPhase[:,1]/=0.5*max(sp.absolute(FuncInfoPhase[:,1]))
#  FuncInfoPhase[:,1]-=1.0

#  plt.subplot2grid((2,3),(1,2),colspan=1,rowspan=1)
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,0],linewidth="2",color="red")
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,1],linewidth="2",color="magenta")
#  plt.title("f) $O_{\mathbb{C}}$ scaled & translated, $(O_{\mathbb{C}}($'$1$'$)-I_R)/I_0$",fontsize=fs)
##  plt.title("$\\frac{1}{N}\int_{T_{{\cal F}1}}^{T_{{\cal F}2}}dt\,A_0(t;\phi_0)^*\cdot A_1(t)$ scaled & translated",fontsize=fs)
#  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
#  plt.ylim(-1,1)

##  myPhase  = sp.zeros([cnt,2])
##  for i in sp.arange(0,cnt):
##    myPhase[i,0]=acos(FuncInfoPhase[i,0])/sp.pi
##    myPhase[i,1]=acos(FuncInfoPhase[i,1])/sp.pi

##  plt.subplot2grid((2,3),(1,2),colspan=1,rowspan=1)
##  plt.plot(sp.linspace(0.0,2.0,cnt),myPhase[:,0])
##  plt.plot(sp.linspace(0.0,2.0,cnt),myPhase[:,1])
#  

##  fig0.plot(memo_times[:], fitness[:,conf[pltId]], zs=tmax, zdir='y',lw=1.5, color="green")

  plt.show()
Example #31
0
def main_routine (wd="./",cfg="./python/spinanalysis.cfg",myMap="jet",generate=1,plottype=0,w1=2400,w2=2450,w3=2500,w4=2550,w5=2600,cut=0,nano=1):

  ### read config file ###
  print ("load from config file: " + cfg)
  cfg=IOHelper.loadSpin(wd,cfg)

  omega_c     = float(cfg['NVSETUP']['{omega_c}'])
  ### read config file ###

  if (generate==1):
    cmd = "./scripts/ifort-spinAnalysis.sh " + wd
    print ("compile fortran routines: "+cmd)
    call(cmd.split())

    print ("### call SpinAnalysis")
    cmd=wd+"SpinAnalysis"
    analysis = Popen(cmd.split(), stdin=PIPE)  # run fortran program with piped standard input
    output   = analysis.communicate()[0]
#  generateInput.wait()
 
  filebase ="./thesis/dat/decay/sin_drive_00h_A0_0.0_0.0i_"

  filename= filebase+"cavity.dat"
  time,__,cavityR,cavityI = sp.loadtxt(filename).T
  cavity = cavityR + 1j*cavityI

  filename= filebase+"spin.dat"
  times,__,  spinR,  spinI = sp.loadtxt(filename).T
  spin   = spinR + 1j*spinI

  tott        = int(cfg['MESpin']['{timecnt_analysis}'])
  timeBinSpin = int(cfg['MESpin']['{timebin_spin}'])

  filename = filebase + "spin_%#07.2fns.dat" % (times[-1])
  omega,__,__ = sp.loadtxt(filename).T

  spin2d      = sp.zeros([sp.size(times),sp.size(omega)],complex)

  omega_c      = float(cfg['NVSETUP']['{omega_c}'])
  omega       *= omega_c

  print "### load data ..."
  myMin = 0
  myMax = 0
  for t in sp.linspace(0,sp.size(times)-1,sp.size(times)):
    filename = filebase + "spin_%#07.2fns.dat" % (times[t])

    __,spinSlideR,spinSlideI = sp.loadtxt(filename).T
    spin2d[t,:]=spinSlideR+1j*spinSlideI 

    if (min(min(spinSlideR),min(spinSlideI)) < myMin): myMin = min(min(spinSlideR),min(spinSlideI))
    if (max(max(spinSlideR),max(spinSlideI)) > myMax): myMax = max(max(spinSlideR),max(spinSlideI))
    
#    print "{0:05.2f}".format(int(t))
#  do t=1,tott,timeBinSpin
#    tmp = nint(mytime(t)*1d2)
#    write(timerange,"(I0.4,F0.2,A)") int(tmp/1d2),tmp/1d2-int(tmp/1d2),"ns"
#    write(*,"(1A1,A,I,A,I,$)") char(13),"--- spin dynamics at "//trim(timerange)//":", t, " of ", size(mytime)

  myMax = max(sp.absolute(myMin),sp.absolute(myMax))
  myMin = -myMax

  fs=20
  label_size = 20
  plt.rcParams['xtick.labelsize'] = label_size 
  plt.rcParams['ytick.labelsize'] = label_size 

  if (nano==1):
    timelabel = "ns"
  else :
    time  *= 1e-3
    times *= 1e-3
    cut   *= 1e-3
    timelabel = "$\mu$s"

  if (plottype == 0): 
    plt.plot(time,sp.absolute(cavity)**2, color="green",linewidth=2.0, label="cavity-amplitude")
    plt.plot(times,sp.absolute(spin)**2, color="red",linewidth=2.0, label="collective spin-wave")
    plt.plot([cut,cut],[omega[-1],omega[1]],"k--")
    plt.ylabel("$|A(t)|^2$; $|S_x(t)|^2$",fontsize=fs)
    plt.xlabel("$t$ in "+timelabel,fontsize=fs)
    plt.legend()

  elif (plottype == 1): 
    plt.subplot(1,3,1)
    plt.plot(times,sp.real(spin2d[:,w1]))
    plt.plot(times,sp.real(spin2d[:,w2]))
    plt.plot(times,sp.real(spin2d[:,w3]))
    plt.plot(times,sp.real(spin2d[:,w4]))
    plt.plot(times,sp.real(spin2d[:,w5]))
    plt.ylabel("$|B_k(t)|^2$",fontsize=fs)
    plt.title("Real part")
    plt.xlabel("$t$ in "+timelabel,fontsize=fs)

    plt.subplot(1,3,2)
    plt.plot(times,sp.imag(spin2d[:,w1]))
    plt.plot(times,sp.imag(spin2d[:,w2]))
    plt.plot(times,sp.imag(spin2d[:,w3]))
    plt.plot(times,sp.imag(spin2d[:,w4]))
    plt.plot(times,sp.imag(spin2d[:,w5]))
    plt.title("Imaginary part")
    plt.xlabel("$t$ in "+timelabel,fontsize=fs)

    plt.subplot(1,3,3)
    plt.plot(times,sp.absolute(spin2d[:,w1]+spin2d[:,w2]+spin2d[:,w3]+spin2d[:,w4]+spin2d[:,w5])**2/5.0)
    plt.title("Collective spin")
    plt.xlabel("$t$ in "+timelabel,fontsize=fs)

  elif (plottype == 2): 
    ### prepare colormap ###################################################################
    fig0_colors=sp.linspace(myMin,myMax,100)
    ### prepare colormap ###################################################################

    c = mcolors.ColorConverter().to_rgb

    if (myMap == "custom"):
      cm = make_colormap([c('cyan'), c('black'), 0.499, c('black'), 0.501, c('black'), c('magenta')])
    else:
      cm       = plt.cm.get_cmap(myMap) 

    otick = [round_sig(0.995*omega_c,4), 
             round_sig(0.9975*omega_c,4),
             round_sig(omega_c,4),        
             round_sig(1.0025*omega_c,4),
             round_sig(1.005*omega_c,4)]

    fig = plt.figure()
    fig0 = fig.add_subplot(121)
    fig0.invert_yaxis()
    fig0.contourf(times,omega,spin2d.real.T,fig0_colors,cmap=cm,vmin=myMin*0.6,vmax=myMax*0.6)
    fig0.plot([cut,cut],[omega[-1],omega[1]],color="white")
    fig0.set_xlabel("$t$ in "+timelabel, fontsize=fs)
    fig0.set_xlim(times[0],times[-1])
    fig0.set_ylabel("$\omega$ in GHz", fontsize=fs)
    fig0.set_ylim([otick[0],otick[-1]])
    fig0.set_yticks(otick)
    fig0.tick_params(direction='out')
    fig0.title("a) Real part")

    fig1 = fig.add_subplot(122)
    fig1.invert_yaxis()
    cp1=fig1.contourf(times,omega,spin2d.imag.T,fig0_colors,cmap=cm,vmin=myMin*0.6,vmax=myMax*0.6)
    fig1.plot([cut,cut],[omega[-1],omega[1]],color="white")
    fig1.set_xlabel("$t$ in "+timelabel, fontsize=fs)
    fig1.set_xlim(times[0],times[-1])
    fig1.set_ylim([otick[0],otick[-1]])
    fig1.set_yticks(otick)
    fig1.axes.yaxis.set_ticklabels([])
    fig1.tick_params(direction='out')
    fig1.title("b) Imaginary part")


    cbtick = [-round_sig(myMax*0.99,2), 
              -round_sig(myMax/2,2),
              0.0,        
              round_sig(myMax/2,2),
              round_sig(myMax*0.99,2)]

    cb =plt.colorbar(cp1,label="Spin-wave amplitude",ticks=cbtick)
    ax = cb.ax
    text = ax.yaxis.label
    font = font_manager.FontProperties(size=fs)
    text.set_font_properties(font)
    cb.update_ticks()
    
    
  
  plt.show ()
Example #32
0
def main_routine (wd="./",cfg="./python/parameter.cfg",start=-1,cut1=1000.0,cut2=1000.0,cut3=1000.0,stop=-1,test=0,plotType=0,impose=0,par1=0.0,par2=0.0):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  cavityDownStore,cavityDownRead    =IOHelper.harmonics_storage("down",**cfg)
  cavityUpStore  ,cavityUpRead      =IOHelper.harmonics_storage("up",**cfg)
  time                              =IOHelper.time_storage(**cfg)

  time['write'][:] *= 1e9
  time['store'][:] *= 1e9
  time['read'] [:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf]

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]

  filename       =IOHelper.getVectorMemory(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T  #sp.random.random_sample([dimH])+0j
  alphaS         =reGamma[0:nStore]-1j*imGamma[0:nStore]
  beta           =reGamma[-1]      -1j*imGamma[-1]
  ### read data ###

  ### plotting
  cavityDownReg1     = sp.dot(alphaD.conj(),cavityWrite)
  cavityDownReg2 = sp.dot(alphaS.conj(),cavityDownStore[0:nStore][:])+beta.conj()*cavityDownStore[-2][:]+cavityDownStore[-1][:]
  cavityDownReg3 = sp.dot(alphaS.conj(),cavityDownRead [0:nStore][:])+beta.conj()*cavityDownRead [-2][:]+cavityDownRead [-1][:]

  cavityUpReg1 = sp.dot(alphaU.conj(),cavityWrite)
  cavityUpReg2 = sp.dot(alphaS.conj(),cavityUpStore[0:nStore][:])+beta.conj()*cavityUpStore[-2][:]+cavityUpStore[-1][:]
  cavityUpReg3 = sp.dot(alphaS.conj(),cavityUpRead [0:nStore][:])+beta.conj()*cavityUpRead [-2][:]+cavityUpRead [-1][:]

  cavitySuperReg1 = superimpose(cavityDownReg1,cavityUpReg1,par1,par2)
  cavitySuperReg2 = superimpose(cavityDownReg2,cavityUpReg2,par1,par2)
  cavitySuperReg3 = superimpose(cavityDownReg3,cavityUpReg3,par1,par2)

  cavityCheckReg1 = superimpose(sp.dot(alphaD.conj(),cavityWrite),sp.dot(alphaU.conj(),cavityWrite),par1,par2)
  cavityCheckReg2 = sp.dot(alphaS.conj(),cavityUpStore[0:nStore][:])+beta.conj()*cavityUpStore[-2][:]+superimpose(cavityDownStore[-1],cavityUpStore[-1],par1,par2)
  cavityCheckReg3 = sp.dot(alphaS.conj(),cavityUpRead [0:nStore][:])+beta.conj()*cavityUpRead [-2][:]+superimpose(cavityDownRead[-1],cavityUpRead[-1],par1,par2)

  ReadDownReg2    = sp.dot(alphaD.conj(),cavityMemo) + sp.dot(alphaR.conj(),cavityRead)
  ReadUpReg2      = sp.dot(alphaU.conj(),cavityMemo) + sp.dot(alphaR.conj(),cavityRead)
  ReadSuperReg2   = superimpose(ReadDownReg2,ReadUpReg2,par1,par2)
  ReadDownReg2   *= beta.conj()
  ReadUpReg2     *= beta.conj()
  ReadSuperReg2  *= beta.conj()

  fs = 20

  plt.subplot(4,3,1)
  plt.title("state '0', $A(t)$",fontsize=fs)
  plt.plot(functime,ReadDownReg2[ti:tf].real,color="darkgray",linewidth=2)
  plt.plot(functime,cavityDownReg3[ti:tf].real,color="blue",linewidth=2)
  plt.xlim([min(functime),max(functime)])
  plt.ylabel("real part",fontsize=fs)

  plt.subplot(4,3,4)
  plt.plot(functime,ReadDownReg2[ti:tf].imag,color="darkgray",linewidth=2)
  plt.plot(functime,cavityDownReg3[ti:tf].imag,color="blue",linewidth=2)
  plt.xlim([min(functime),max(functime)])
  plt.ylabel("imag part",fontsize=fs)

  plt.subplot(4,3,2)
  plt.title("state '1', $A(t)$",fontsize=fs)
  plt.plot(functime,ReadUpReg2[ti:tf].real,color="darkgray",linewidth=2)
  plt.plot(functime,cavityUpReg3[ti:tf].real,color="red",linewidth=2)
  plt.xlim([min(functime),max(functime)])

  plt.subplot(4,3,5)
  plt.plot(functime,ReadUpReg2[ti:tf].imag,color="darkgray",linewidth=2)
  plt.plot(functime,cavityUpReg3[ti:tf].imag,color="red",linewidth=2)
  plt.xlim([min(functime),max(functime)])

  plt.subplot(4,3,3)
  if (impose != 1):
    plt.title("$\\alpha_{S}$",fontsize=fs)
    plt.bar(sp.arange(1,nStore+1,1),alphaS.real,color="green")
  else :
    plt.title("superposition, $A(t)$",fontsize=fs)
    plt.plot(functime,ReadSuperReg2[ti:tf].real,color="darkgray",linewidth=2)
    plt.plot(functime,cavitySuperReg3[ti:tf].real,color="green",linewidth=2)
    plt.xlim([min(functime),max(functime)])

  plt.subplot(4,3,6)
  if (impose != 1):
    plt.bar(sp.arange(1,nStore+1,1),alphaS.imag,color="green")
  else :
    plt.plot(functime,ReadSuperReg2[ti:tf].imag,color="darkgray",linewidth=2)
    plt.plot(functime,cavitySuperReg3[ti:tf].imag,color="green",linewidth=2)
    plt.xlim([min(functime),max(functime)])


  plt.subplot2grid((4,3),(2,0),colspan=3,rowspan=2)

  cavityCheckReg1,cavityCheckReg2,cavityCheckReg3 = pltFunction(cavityCheckReg1,cavityCheckReg2,cavityCheckReg3,plotType)
  cavitySuperReg1,cavitySuperReg2,cavitySuperReg3 = pltFunction(cavitySuperReg1,cavitySuperReg2,cavitySuperReg3,plotType)
  cavityDownReg1, cavityDownReg2, cavityDownReg3  = pltFunction(cavityDownReg1, cavityDownReg2, cavityDownReg3, plotType)
  cavityUpReg1,   cavityUpReg2,   cavityUpReg3    = pltFunction(cavityUpReg1,   cavityUpReg2,   cavityUpReg3,   plotType)

  if (test==1):
    print ("### compile fortran routines")
    cmd = "./scripts/ifort-memoryHarmonics.sh " + wd
    call(cmd.split())

    print ("### call memoryOptimized")
    cmd=wd+"memoryOptimized"
    call(cmd.split())

    print ("### call memorySuperimposed")
    cmd=wd+"memorySuperimposed"
    generateSuperposition = Popen(cmd.split(), stdin=PIPE)                     # run fortran program with piped standard input
    cmd = "echo {:}".format(par1)                                              # communication with fortran-routine: chose superposition parameter
    generateInput     = Popen(cmd.split(), stdout=generateSuperposition.stdin) # send action to fortran program
    output            = generateSuperposition.communicate()[0]
    generateInput.wait()

    filename = cfg['FILES']['{prefix}']+cfg['FILES']['{name_readwrite}']+\
               cfg['FILES']['{name_storage}']+cfg['FILES']['{name_optimized}']

    mytimeU,__,A_Re_U,A_Im_U = sp.loadtxt(filename+"cavity_up_stored"   +cfg['FILES']['{postfix}']).T
    mytimeD,__,A_Re_D,A_Im_D = sp.loadtxt(filename+"cavity_down_stored" +cfg['FILES']['{postfix}']).T
    mytimeS,__,A_Re_S,A_Im_S = sp.loadtxt(filename+"cavity_super_stored"+cfg['FILES']['{postfix}']).T

    cavityMode_U,cavityMode_D,cavityMode_S = pltFunction(A_Re_U+1j*A_Im_U, A_Re_D+1j*A_Im_D, A_Re_S+1j*A_Im_S,plotType)

  cavityMaxDown = max(max(cavityDownReg1),max(cavityDownReg2),max(cavityDownReg3))
  cavityMaxUp   = max(max(cavityUpReg1),max(cavityUpReg2),max(cavityUpReg3))
  cavityMaxSuper= max(max(cavitySuperReg1),max(cavitySuperReg2),max(cavitySuperReg3))
  cavityMax     = max(cavityMaxDown,cavityMaxUp,cavityMaxSuper)

  cavityMinDown = min(min(cavityDownReg1),min(cavityDownReg2),min(cavityDownReg3))
  cavityMinUp   = min(min(cavityUpReg1),min(cavityUpReg2),min(cavityUpReg3))
  cavityMinSuper= max(min(cavitySuperReg1),min(cavitySuperReg2),min(cavitySuperReg3))
  cavityMin     = min(cavityMinDown,cavityMinUp,cavityMinSuper)

  plt.plot(time['write'],cavityDownReg1,color="blue",linewidth=2)
  plt.plot(time['store'],cavityDownReg2,color="blue",linewidth=2)
  plt.plot(time['read'] ,cavityDownReg3,color="blue",linewidth=2,label="state '0'")

  plt.plot(time['write'],cavityUpReg1,color="red",linewidth=2)
  plt.plot(time['store'],cavityUpReg2,color="red",linewidth=2)
  plt.plot(time['read'] ,cavityUpReg3,color="red",linewidth=2,label="state '1'")

  if (impose == 1):
    plt.plot(time['write'],cavitySuperReg1,color="green",linewidth=2)
    plt.plot(time['store'],cavitySuperReg2,color="green",linewidth=2)
    plt.plot(time['read'] ,cavitySuperReg3,color="green",linewidth=2,label="super state")

  if (test == 1):
    plt.plot(mytimeD,cavityMode_D,label="state '0' test",color="cyan")
    plt.plot(mytimeU,cavityMode_U,label="state '1' test",color="magenta")
    if (impose == 1):
      plt.plot(time['write'],cavityCheckReg1,color="orange")
      plt.plot(time['store'],cavityCheckReg2,color="orange")
      plt.plot(time['read'] ,cavityCheckReg3,color="orange",label="super state")
      plt.plot(mytimeS,cavityMode_S,label="super state test",color="brown")

#  plt.legend()
  plt.xlabel('time in ns',fontsize=fs)
  plt.ylabel('$|A(t)|^2$',fontsize=fs)

  
  if start != -1 and stop != -1:
    plt.xlim([start,stop])
  else:
    plt.xlim([min(time['write']),max(time['read'])])

  plt.ylim([cavityMin*1.1,cavityMax*1.1])

  plt.fill_between(functime, cavityMax*1.1, cavityMin*1.1, color='lightgray', facecolor='lightgray', alpha=0.5)
  plt.plot([time['store'][0],time['store'][0]], [cavityMin*1.1,cavityMax*1.1], 'k--')
  plt.plot([time['read'] [0],time['read'] [0]], [cavityMin*1.1,cavityMax*1.1], 'k--')

  plt.plot([cut1,cut1],[0,cavityMax*1.1],linewidth=2.0)
  plt.plot([cut2,cut2],[0,cavityMax*1.1],linewidth=2.0)
  plt.plot([cut3,cut3],[0,cavityMax*1.1],linewidth=2.0)
  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",thetaCnt=11,phiCnt=11,p3d=0,myMap="rainbow"):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]     # /float(cfg['OCConstraints']['{amplitude_up}'])
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown] # /float(cfg['OCConstraints']['{amplitude_down}'])
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]   # /float(cfg['OCConstraints']['{amplitude_read}'])
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  FuncInfoOlap  = sp.zeros([2,thetaCnt,phiCnt],complex)

  I00  =    cumtrapz( (Reg2Down[ti:tf].conj() * Reg2Down[ti:tf]).real, x=None, dx=dt )[-1]
  I0R  = 1j*cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Down[ti:tf]).imag, x=None, dx=dt )[-1]
  I0R +=    cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Down[ti:tf]).real, x=None, dx=dt )[-1]

  I11  =    cumtrapz( (Reg2Up  [ti:tf].conj() * Reg2Up  [ti:tf]).real, x=None, dx=dt )[-1]
  I1R  = 1j*cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Up  [ti:tf]).imag, x=None, dx=dt )[-1]
  I1R +=    cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Up  [ti:tf]).real, x=None, dx=dt )[-1]

  fs     = 20

  for i in sp.arange(0.0,thetaCnt):
    theta = i/(thetaCnt-1.0)   # from 0 to 1 * pi
    
    for j in sp.arange(0.0,phiCnt):
      phi = j/(phiCnt-1.0)*2.0 # from 0 to 2 * pi
      
      FuncCavity     = sp.cos(theta*sp.pi)*Reg2Down[ti:tf] + sp.sin(theta*sp.pi)*sp.exp(-1j*phi*sp.pi)*Reg2Up[ti:tf]
      FuncCavity[:] += Reg2Read  [ti:tf]

#      plt.title("state $\\theat={0:}$, $\\phi={1:}$".format(theta,phi),fontsize=fs)
#      plt.plot(time['read'][ti:tf],sp.absolute(FuncCavity)**2,color="green",linewidth=2)
#      plt.plot(time['read'][ti:tf],sp.absolute(Reg2DownRead[ti:tf])**2,color="blue",linewidth=2)
#      plt.plot(time['read'][ti:tf],sp.absolute(Reg2UpRead[ti:tf])**2,color="red",linewidth=2)
#      plt.ylabel("$A(t)$",fontsize=fs)
#      plt.xlim([time['read'][ti],time['read'][tf]])
#      plt.show()

      FuncInfoOlap [0,i,j]  =    cumtrapz( (FuncCavity[:].conj() * Reg2Down[ti:tf]).real, x=None, dx=dt )[-1]
      FuncInfoOlap [0,i,j] += 1j*cumtrapz( (FuncCavity[:].conj() * Reg2Down[ti:tf]).imag, x=None, dx=dt )[-1]
      FuncInfoOlap [0,i,j]  =    (FuncInfoOlap [0,i,j]-I0R)/I00

      FuncInfoOlap [1,i,j]  =    cumtrapz( (FuncCavity[:].conj() * Reg2Up[ti:tf]).real, x=None, dx=dt )[-1]
      FuncInfoOlap [1,i,j] += 1j*cumtrapz( (FuncCavity[:].conj() * Reg2Up[ti:tf]).imag, x=None, dx=dt )[-1]
      FuncInfoOlap [1,i,j]  =    (FuncInfoOlap [1,i,j]-I1R)/I11

  xx, yy = sp.meshgrid(sp.linspace(0.0,2.0,phiCnt),sp.linspace(0.0,1.0,thetaCnt))

  zmin   = 0.0
  zmax   = +1.0

  zzOlapR0 = FuncInfoOlap [0,:,:].real
  zzOlapI0 = FuncInfoOlap [0,:,:].imag
  print zzOlapI0  

  zzOlapR1 = FuncInfoOlap [1,:,:].real
  zzOlapI1 = FuncInfoOlap [1,:,:].imag

  fig  = plt.figure()

  fig1 = fig.add_subplot(221, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapR0, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR0.min(), vmax=zzOlapR0.max())
  fig1.set_zlim(-1,1)
  fig1.set_title("a) Re$[(\\tilde O($\"$0$\"$)-\\tilde {\cal I}_{0R})/\\tilde {\cal I}_{00}]\\approx\cos(\\theta)$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi / \pi$",fontsize=fs)

  fig1 = fig.add_subplot(223, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapI0, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI0.min(), vmax=zzOlapI0.max())
  fig1.set_zlim(-0.01,0.01)
  fig1.set_title("c) Im$[(\\tilde O($\"$0$\"$)-\\tilde {\cal I}_{0R})/\\tilde {\cal I}_{00}]\\approx0$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi/\pi$",fontsize=fs)

  fig1 = fig.add_subplot(222, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapR1, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR1.min(), vmax=zzOlapR1.max())
  fig1.set_zlim(-1,1)
  fig1.set_title("b) Re$[(\\tilde O($\"$1$\"$)-\\tilde {\cal I}_{1R})/\\tilde {\cal I}_{11}]\\approx\sin(\\theta)\cdot\cos(\phi)$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi / \pi$",fontsize=fs)

  fig1 = fig.add_subplot(224, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapI1, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI1.min(), vmax=zzOlapI1.max())
  fig1.set_zlim(-1,1)
#  fig1.set_title("a) Re$[(O_{\mathbb{C}}("0")-\\tilde {\¢al I}_{0R})/\\tilde {\¢al I}_{00}]$",fontsize=fs)
  fig1.set_title("d) Im$[(\\tilde O($\"$1$\"$)-\\tilde {\cal I}_{1R})/\\tilde {\cal I}_{11}]\\approx\sin(\\theta)\cdot\sin(\phi)$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi/\pi$",fontsize=fs)

  plt.show()
def main_routine (baseDir="./",configPath="./python/parameter.cfg",generationType="r"):
  print "#################################################################"
  print "#################################################################"
  print "### optimal control #############################################"
  print "### preparation of smallest overlap functional ##################"
  print "#################################################################"
  print "#################################################################"

  ### globals for functional variation
  global time, cavityRead, cavityMemo, \
         nRead, nDown, nUp, nWrite, dimH, \
         cfg, \
         h0, hc_up, hc_down, hs_up, hs_down, hsep, \
         weight_up, weight_down, sepZeroWeight, \
         normUp, normDown, normRead, \
         hole, \
         iteration

  tmpDir=baseDir+"tmp/"
  #  parser.add_argument("--cfg" ,  help="config path")
  ### check for arguments, g: generate data, r: read data ###

  ### read config file ###
  print ("load from config file: " + configPath)

  configParser = cp.ConfigParser()
  configParser.read(configPath)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)

  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  nTimeRead =int(cfg['OCTime']['{read_timecnt}'])
  dimH      =nRead + 2*nWrite

  normRead =float(cfg['OCConstraints']['{amplitude_read}']) 
  normDown =float(cfg['OCConstraints']['{amplitude_down}']) 
  normUp   =float(cfg['OCConstraints']['{amplitude_up}']) 

  name_readwrite = IOHelper.getNameReadWrite(**cfg)
  name_vector    = IOHelper.getVectorOverlap(**cfg)
  ### read config file ###


  ### prepare data with fortran ###
  cmd = "mkdir -p " + tmpDir
  print (tmpDir)
  call(cmd.split())
  replace_in_file('./python/py.parNvCenter.F95'       , tmpDir +'parNvCenter.F95',        **cfg['NVSETUP'])
  replace_in_file('./python/py.parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95', **cfg['OCFourier'])
  replace_in_file(tmpDir +'parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95',     **cfg['OCConstraints'])
  replace_in_file(tmpDir +'parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95',     **cfg['OCTime'])
  replace_in_file(tmpDir +'parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95',     **cfg['FILES'])

  #write config file
  with open(cfg['FILES']['{prefix}']+"parameter.cfg", 'wb') as configfile:
    configParser.write(configfile)

  cmd = "mv "+tmpDir+"parSmallestOverlap.F95 "+baseDir+"srcOptCntrl/parSmallestOverlap.F95"
  call(cmd.split())
  cmd = "mv "+tmpDir+"parNvCenter.F95 "+baseDir+"srcNv/parNvCenter.F95"
  call(cmd.split())

  print ("compile fortran routines")
  cmd = "./scripts/ifort-generateHarmonics.sh " + baseDir
  call(cmd.split())

  print ("invoke " +baseDir +"generateHarmonics")

  cmd = baseDir+"generateHarmonics"
  generateHarmonics = Popen(cmd.split(), stdin=PIPE)
  cmd = "echo " + generationType
  generateInput     = Popen(cmd.split(), stdout=generateHarmonics.stdin)
  output            = generateHarmonics.communicate()[0]
  generateInput.wait()
  ### prepare data with fortran ###


  ### read data for functional variation ###
  __,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                     =IOHelper.functionaltimes_readwrite(**cfg)

  h0,hs_down,hs_up,hc_down,hc_up,hsep=IOHelper.read_MtrxOverlap(**cfg['FILES']) 
  hole                               =IOHelper.read_HoleData(**cfg['FILES']) 
  ### read data for functional variation ###


  ### functional variation ###
  print ("\nstart minimization: ")

  varMax = 20
  varStep = 1
  success = False

  #constraints for constraintWeightDown and constraintWeightUp
  funcTime  =float(time['tfunc'])
  weight_down=float(cfg ['OCConstraints']['{temporal_weight_down}'])*funcTime/2.0
  weight_up  =float(cfg ['OCConstraints']['{temporal_weight_up}'])*funcTime/2.0

  minContraints= ( {'type' : 'ineq', 'fun'  : constraintNormRead },
                   {'type' : 'eq', 'fun'  : constraintNormDown },
                   {'type' : 'eq', 'fun'  : constraintNormUp },
                   {'type' : 'eq', 'fun'  : constraintWeightDown },
                   {'type' : 'eq', 'fun'  : constraintWeightUp },
#                   {'type' : 'eq', 'fun'  : constraintRealMaxCoefficient },
                   {'type' : 'ineq', 'fun'  : constraintZeroStartDown },
                   {'type' : 'ineq', 'fun'  : constraintZeroStartUp },
                   {'type' : 'ineq', 'fun'  : constraintPartialOverlap },
                   {'type' : 'ineq', 'fun'  : constraintStoreUp },
                   {'type' : 'ineq', 'fun'  : constraintStoreDownIneq },
#
  #                 {'type' : 'ineq', 'fun'  : constraintSeperateZero },
#                   {'type' : 'eq', 'fun'  : constraintStoreDown },
#                   {'type' : 'eq', 'fun'  : constraintHoleValue },
#                   {'type' : 'eq', 'fun'  : constraintHoleSlope },
#                   {'type' : 'eq', 'fun'  : constraintHoleCurv },
                 )


  while varStep < varMax and not success :
    gamma0=initGamma0()
    x,x0  =initx(gamma0)

  #    print (" calculate sepzero to initialize vector x (method=SLSQP):")
  #    iteration=1
  #    res=minimize(seperateZeroStore, #seperateZero, # smallestAbsoluteOverlap,
  #                 x0, #res.x, 
  #                 method='SLSQP',
  #                 constraints=sepzeroContraints,
  #                 tol=cfg['OCConstraints']['{tol_sepzero}'],
  #                 options={'maxiter' : 25000, 'disp' : True},
  #                 callback=monitor
  #               )

  #    x0=res.x
  #    sepZeroWeight = res.fun

  #    funcTime  =float(time['tfunc'])
  #    weight=float(cfg ['OCConstraints']['{temporal_weight_limit}'])
  #    sepZeroWeight=weight*funcTime/2e0

    print (" calculate smallest overlap of absolute values (method=SLSQP):")
    iteration=1
    res=minimize(seperateZero, #smallestOverlapSeperateZero, # smallestOverlapSeperatePeaks, #smallestComplxOverlap, # smallestAbsoluteOverlap, # smallestOverlapSeperateZeroPartial, #
                 x0, 
                 method='SLSQP',
                 constraints=minContraints,
                 tol=cfg['OCConstraints']['{tol_classic}'],
                 options={'maxiter' : 25000, 'disp' : True},
                 callback=monitor
               )

    success=res.success
    gamma=getGamma(res.x)

    print ("")    
    print (" current norm(aplhaR) = " +str(sp.linalg.norm(gamma[     :nRead])))
    print (" current norm(aplhaD) = " +str(sp.linalg.norm(gamma[nRead:nDown])))
    print (" current norm(aplhaU) = " +str(sp.linalg.norm(gamma[nDown:nUp  ])))
    print (" current partial Olap = " +str(partialOverlap(res.x)))
#    print (" current hole(value)  = " +str(constraintHoleValue(res.x)))
#    print (" current hole(slope)  = " +str(constraintHoleSlope(res.x)))
#    print (" current hole(value)  = " +str(constraintHoleCurv(res.x)))

   
    varStep+=1

  if (success):
    print ("\ndone with minimization, succeeded:")
  else:
    print ("\ndone with minimization, no success:")

  sp.savetxt(name_vector,sp.array([gamma.real,gamma.conj().imag]).T) 
                             # [real(gamma), imag(gamma)].conj()

  cmd=baseDir+"generateOptimized"
  call(cmd.split())
def main_routine (wd="./",cfg="./python/parameter.cfg",generationType="p",\
                  toMinimize =2,\
                  cavityMatch=1,\
                  silent=0,\
                  useBeta=0,\
                  cutoff=10000,dimGrid=11,id0=0,id1=1,id2=2,pltId='funval',pltLim=1000,pltBins=40,myCmap="brg"):
  print "#################################################################"
  print "#################################################################"
  print "### optimal control #############################################"
  print "### memory pulse evaluation #####################################"
  print "#################################################################"
  print "#################################################################"

  ### globals for functional variation
  global cons, fun, dim, conf

  conf['toMinimize'] =toMinimize
  conf['cavityMatch']=cavityMatch
  conf['silent']     =silent
  if (useBeta == 0):
    conf['useBeta']    = False
  else:
    conf['useBeta']    = True

  conf['id0']        =id0
  conf['id1']        =id1
  conf['id2']        =id2
  conf['cutoff']     =cutoff

  ### globals for functional variation

  ### generate working environment ###
  print ("### working directory: " + wd)
  tmpDir = wd+"tmp/"  
  cmd = "mkdir -p " + tmpDir
  call(cmd.split())
  ### generate working environment ###

  ### read config file ###
  print ("### load config file: " + cfg)
  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  conf['MEConstraints'] = cfg['MEConstraints'].copy()
  conf['FITNESS']=  cfg['FITNESS'].copy()
  conf['FITNESS']['{mutationrate}']=sp.zeros([conf['entries']])
  conf['FITNESS']['{mutationrate}'][conf['funval']]       =cfg['FITNESS']['{mut_functional}']
  conf['FITNESS']['{mutationrate}'][conf['fidelity_down']]=cfg['FITNESS']['{mut_fidelity_down}']
  conf['FITNESS']['{mutationrate}'][conf['fidelity_up']]  =cfg['FITNESS']['{mut_fidelity_up}']
  conf['FITNESS']['{mutationrate}'][conf['memolap']]      =cfg['FITNESS']['{mut_memolap}']
  conf['FITNESS']['{mutationrate}'][conf['alpha']]        =cfg['FITNESS']['{mut_alpha}']
  conf['FITNESS']['{mutationrate}'][conf['beta']]         =cfg['FITNESS']['{mut_beta}']
  conf['FITNESS']['{mutationrate}'][conf['success']]      =cfg['FITNESS']['{mut_success}']

  cons['alpha_norm']=float(cfg['MEConstraints']["{storage_amplitude}"])
  cons['beta_low']  =float(cfg['MEConstraints']["{limit_low_beta}"])
  cons['beta_top']  =float(cfg['MEConstraints']["{limit_top_beta}"])
  cons['chi2_Tol']  =float(cfg['MEConstraints']['{tol_chi2}'])

  dim['alpha']=int(cfg['MEFourier']['{storage_harmonic}'])
  dim['total']=dim['alpha']+3

  prefix        =cfg['FILES']['{prefix}']
  postfix       =cfg['FILES']['{postfix}']
  name_optimized=cfg['FILES']['{name_optimized}']

  name_spin     =cfg['FILES']['{name_spin}']
  name_cavity   =cfg['FILES']['{name_cavity}']

  cfg['dim_grid']    =dimGrid
  name_readwrite=IOHelper.getNameReadWrite(**cfg) 
  name_storage  =IOHelper.getNameStorage  (**cfg) 
  name_varinit  =IOHelper.getNameInitialVariation (**cfg)

  myTime        =IOHelper.functionaltimes_readwrite(**cfg) # reads time and updates cfg: 
                                                           #   cfg['METime']['{fidelity_ti}'] = myTime['idx_ti']
                                                           #   cfg['METime']['{fidelity_tf}'] = myTime['idx_tf']


  gridPhi    =sp.linspace(0.0, 2.0*sp.pi, num=2*dimGrid-1)
  gridTheta  =sp.linspace(0.0, sp.pi, num=dimGrid)
  minfun     =sp.zeros([len(gridPhi),len(gridTheta),conf['entries']+3])

  if (generationType == "p"):
    print "## read from file: " + name_varinit
    raw = sp.loadtxt(name_varinit)
    minfun  = raw.reshape(len(gridPhi),len(gridTheta),conf['entries']+3)
    for i in sp.arange(0,len(gridPhi),1):
      for j in sp.arange(0,len(gridTheta),1):
        minfun[i,j,conf['fitness']] = MemoryPulseFunctional.fitnessFunction(minfun[i,j,:])

  else:
    ### prepare and complie fortran routines ###
    print ("### prepare fortran routines")
    replace_in_file('./python/py.parNvCenter.F95'   , tmpDir +'parNvCenter.F95'   , **cfg['NVSETUP'])
    replace_in_file('./python/py.parMemoryPulse.F95', tmpDir +'parMemoryPulse.F95', **cfg['MEFourier'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['OCFourier'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['MESpin'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['MEConstraints'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['OCConstraints'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['METime'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['OCTime'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['FILES'])

    #write config file
    with open(prefix+"parameter.cfg", 'wb') as configfile:
      configParser.write(configfile)
    ### read config file ###

    print ("### compile fortran routines")
    cmd = "mv "+tmpDir+"parMemoryPulse.F95 "+wd+"srcOptCntrl/parMemoryPulse.F95"
    call(cmd.split())
    cmd = "mv "+tmpDir+"parNvCenter.F95 "+wd+"srcNv/parNvCenter.F95"
    call(cmd.split())

    cmd = "./scripts/ifort-memoryHarmonics.sh " + wd
    call(cmd.split())

    print ("### invoke  fortran routines")
    print ("### generation Type: " + generationType)
    cmd = wd+"memoryHarmonics"                                             # location of executable fortran program
    generateHarmonics = Popen(cmd.split(), stdin=PIPE)                     # run fortran program with piped standard input
    cmd = "echo " + generationType                                         # communication with fortran-routine: chose action -> read or generate
    generateInput     = Popen(cmd.split(), stdout=generateHarmonics.stdin) # send action to fortran program
    output            = generateHarmonics.communicate()[0]
    generateInput.wait()
    ### prepare and complie fortran routines ###

    ### read data for functional variation ###
    cons['cavityT2_down'], \
    cons['cavityT2_up']    = IOHelper.read_CavityMemory (**cfg['FILES'])

    fun ['mtrxBeta_up'],   \
    cons['vecT2_up']   ,   \
    cons['fidelity_up'],   \
    cons['mtrxMemOlap']    = IOHelper.read_MtrxMemory("up",  **cfg['FILES']) 

    fun ['mtrxBeta_down'], \
    cons['vecT2_down']   , \
    cons['fidelity_down'], \
    __                     = IOHelper.read_MtrxMemory("down",  **cfg['FILES']) 
    ### read data for functional variation ###

    ### functional variation ###
    print ("\n### start minimization: ")
    print ("### on initial "+ str(sp.shape(minfun)[0])+"x"+str(sp.shape(minfun)[1])  + "-grid (phi,theta) on sphere")

    mincnt=0
    cntPhi  =0
    t0=0
    tcnt=len(gridTheta)

    for phi in gridPhi[0:len(gridPhi)-1]: 
      theta_i=0
      if(cntPhi > 0):
        t0=1
        tcnt=len(gridTheta)-1
        theta_i=1

      ### parallel evaluation with <cpu_count()> cores ###################################
      pool    = multiprocessing.Pool(processes=multiprocessing.cpu_count())

      results = [ pool.apply_async(evaluateSphericalVariation, args=(phi,theta,cntPhi,cntTheta))
                 for theta,cntTheta in zip(gridTheta[t0:tcnt],sp.arange(t0,tcnt,1)) ]

      for p in results:
        myResult,i,j =p.get()
        minfun[i,j,:]=myResult

      #kill multiprocessing pool !!!
      pool.terminate()
      ### parallel evaluation with <cpu_count()> cores ###################################


      ### sequentiell evaluateion 1 core #################################################
#      for theta in gridTheta[t0:tcnt]:
#        minfun[cntPhi,theta_i,:],__,__=MemoryPulseFunctional.evaluateSphericalVariation (phi,theta,cntPhi,theta_i)
#        theta_i+=1
      ### sequentiell evaluateion 1 core #################################################

      cntPhi=cntPhi+1
  #  end for phi

    minfun[ :, 0,:]=minfun[0, 0,:] # theta=0  : same vector on unit-sphere
    minfun[ :,-1,:]=minfun[0,-1,:] # theta=pi : same vector on unit-sphere
    minfun[-1, :,:]=minfun[0, :,:] # periodic

    print "\n### write to file: " + name_varinit
    sp.savetxt(name_varinit,minfun.reshape((len(gridPhi)*len(gridTheta),conf['entries']+3)),\
       header=' alpha0['+str(id0)+']; alpha0['+str(id1)+']; alpha0['+str(id2)+'];'\
             +' fitness; success; norm[alpha]; abs[beta]; memolap; fidelity_up; fidelity_down; minfun') 

  print "#################################################################"
  print "#################################################################"


  font = {
  'fontsize'            : 26,
  }

  mytitle=MemoryPulseFunctional.getName(pltId)

  ### prepare surface_plot ###############################################################
  x = outer(cos(gridPhi), sin(gridTheta))
  y = outer(sin(gridPhi), sin(gridTheta))
  z = outer(ones(size(gridPhi)), cos(gridTheta))

  myDensity=sp.zeros([len(gridPhi),len(gridTheta)])
  for i in sp.arange(0,len(gridPhi),1):
    for j in sp.arange(0,len(gridTheta),1):
      if (minfun[i,j,conf[pltId]] >= pltLim):
        myDensity[i,j] = pltLim+1
      else:
        myDensity[i,j] = minfun[i,j,conf[pltId]]

      
  # "afmhot", "hot", "terrain", "brg"
  cm       = plt.cm.get_cmap(myCmap) 
  myColors = cm(myDensity/pltLim)
  ### prepare surface_plot ###############################################################

  ### prepare colormap ###################################################################
  fig0_colors=sp.linspace(0,pltLim,pltBins)
  ### prepare colormap ###################################################################

  ### prepare histogram ##################################################################
  yHist,xHist = sp.histogram(myDensity.flatten(),pltBins)
#  xSpan = pltxHist.max()-xHist.min()
#  Color = [cm(((ix-xHist.min())/xSpan)) for ix in xHist]

  Color = [cm(((ix)/pltLim)) for ix in xHist]
  ### prepare histogram ##################################################################

  ### calculate fittest solutions ########################################################
  cntFit = 0

  for i in sp.arange(0,len(gridPhi),1):
    for j in sp.arange(0,len(gridTheta),1):

      if minfun[i,j,conf['fitness']] != 0.0 :
        cntFit+=1
      
      if (minfun[i,j,conf[pltId]] >= pltLim):
        myDensity[i,j] = pltLim
      else:
        myDensity[i,j] = minfun[i,j,conf[pltId]]
      
  if (cntFit > 0):
    fitAlpha =sp.zeros([cntFit,int(cfg['MEFourier']['{storage_harmonic}'])])  

    cntFit = 0
  
    for i in sp.arange(0,len(gridPhi),1):
      for j in sp.arange(0,len(gridTheta),1):
        if minfun[i,j,conf['fitness']] != 0.0 :
          print minfun[i,j,3:]
  
          fitAlpha[cntFit,conf['id0']]=minfun[i,j,0]
          fitAlpha[cntFit,conf['id1']]=minfun[i,j,1]
          fitAlpha[cntFit,conf['id2']]=minfun[i,j,2]

          cntFit+=1

    name_fittest=IOHelper.getNameInitialFittest(**cfg)
    print "\n### write fittest to file: " + name_fittest
    sp.savetxt(name_fittest,fitAlpha,\
       header='# alpha0[0] ... alpha0[n]') 

  print "### fitness counter: {0:} of {1:}".format(cntFit,sp.shape(minfun)[0]*sp.shape(minfun)[1])
  ### calculate fittest solutions ########################################################


  fig = plt.figure()


  ### plot surface_plot ##################################################################
  fig3D = fig.add_subplot(131, projection='3d')
  surf  = fig3D.plot_surface(x, y, z, rstride=1, cstride=1,facecolors=myColors)
  fig3D.plot(cos(gridPhi), sin(gridPhi), zs=0, zdir='z',lw=0.5, color="black")
  fig3D.plot(cos(gridPhi), sin(gridPhi), zs=0, zdir='x',lw=0.5, color="black")
  fig3D.set_xlabel("$\\alpha_{:}$".format(id0), **font)
  fig3D.set_ylabel("$\\alpha_{:}$".format(id1), **font)
  fig3D.set_zlabel("$\\alpha_{:}$".format(id2), **font)
  fig3D.set_title("a) 4d-plot of "+mytitle, fontsize = 20)
  ### plot surface_plot ##################################################################


  ### plot colormap ######################################################################
  fig0 = fig.add_subplot(132)
  fig0.invert_yaxis()
  cp0=fig0.contourf(gridPhi/sp.pi,gridTheta/sp.pi,minfun[:,:,conf[pltId]].T,fig0_colors,cmap=cm)
  plt.colorbar(cp0)
  fig0.set_xlabel("$\phi/\pi$", **font)
  fig0.set_ylabel("$\\theta/\pi$", **font)
  fig0.set_title("b) map of "+mytitle, fontsize = 20)
  ### plot colormap ######################################################################


  ### plot histogram #####################################################################
  figBar=fig.add_subplot(133)
  figBar.bar(xHist[:-1],yHist,color=Color,width=xHist[1]-xHist[0])
  figBar.set_xlim([0,pltLim])
  figBar.set_ylim([0,max(yHist[0:len(yHist)-1])])
  figBar.set_xlabel(mytitle, fontsize=20)
  figBar.set_ylabel("count", fontsize=20)
  figBar.set_title("c) histogram", fontsize = 20)
  ### plot histogram #####################################################################

  plt.show()
Example #36
0
def upload_textarea(request,spath):
    ext_allowed = ['gif', 'jpg', 'jpeg', 'png','bmp']
    max_size = 2621440
    today = datetime.datetime.today()
    #save_dir = 'image/%d/%d/%d/' % (today.year, today.month, today.day)
    spath = spath+'/'
    save_path = os.path.join(settings.MEDIA_ROOT, spath)
    save_url = os.path.join(settings.MEDIA_URL, spath)
    #print save_dir, save_path, save_url
    
    if request.method == 'POST':
        file = request.FILES['imgFile']

        if not file.name:
            return HttpResponse(json.dumps(
                { 'error': 1, 'message': u'请选择要上传的文件' }
            ))

        ext = file.name.split('.').pop()
        if ext not in ext_allowed:
            return HttpResponse(json.dumps(
                { 'error': 1, 'message': u'请上传后缀为%s的文件' %  ext_allowed}
            ))

        if file.size > max_size:
            return HttpResponse(json.dumps(
                { 'error': 1, 'message': u'上传的文件大小不能超过2.5MB'}
            ))

        if not os.path.isdir(save_path):
            os.makedirs(save_path)
        
        file_name_no_ext = str(uuid.uuid1())
        #new_file = '%s.%s' % (int(time.time()), ext)
        new_file = '%s.%s' % (file_name_no_ext, ext)

        destination = open(save_path+new_file, 'wb+')
        for chunk in file.chunks():
            destination.write(chunk)
        destination.close()
        
        import IOHelper
        file_md5 = IOHelper.GetFileMD5(save_path+new_file)
        edit_new_file = '%s.%s' % (file_md5, ext)
        if os.path.exists(save_path+edit_new_file): #如果该文件的MD5已存在,则删除
            os.remove(save_path+new_file)
        else: #否则改名
            os.rename(save_path+new_file, save_path+edit_new_file)
               
        if settings.FILE_SAVE_DISK_TYPE == 1: #保存到七牛云
            from QiNiuHelper import  SaveFileToQiNiu
            status,qiniu_text = SaveFileToQiNiu(settings.BASE_DIR + save_url+edit_new_file,True)
            if status == 0:
                return HttpResponse(json.dumps(
                    { 'error': 0, 'message':qiniu_text }
                ))
            else:
                return HttpResponse(json.dumps(
                    { 'error': 0, 'url': 'http://'+qiniu_text}
                ))
        else:
            return HttpResponse(json.dumps(
                    { 'error': 0, 'url': '/'+save_url+edit_new_file}
            ))
        
        
        # TODO we should show the uploaded file and the manager url   save_url+new_file
        #return  HttpResponse("Upload Succsefull to URL:%s" % (save_url+new_file)  )
        #return HttpResponse(json.dumps(
        #    {'error':0,'message':save_url+new_file}
        #))
    else:
        raise Http404
def main_routine (wd="./",cfg="./python/parameter.cfg",thetaCnt=11,phiCnt=11,bloch=0,myMap="jet",minOlap=0,fortranCheck=0,gridR=5,gridC=5):

  ### read config file ###
  print ("load from config file: " + cfg)
  cfg=IOHelper.loadCfg(wd,cfg)

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  spos          = sp.zeros([2,thetaCnt,phiCnt],complex)
  FuncInfoOlap  = sp.zeros([2,thetaCnt,phiCnt],complex)
  gamma         = sp.zeros([thetaCnt,phiCnt],complex)
  delta         = sp.zeros([thetaCnt,phiCnt],complex)

#  I00  = 1j*cumtrapz( (Reg2Down[ti:tf].conj() * Reg2Down[ti:tf]).imag, x=None, dx=dt )[-1]
  I00  =    cumtrapz( (Reg2Down[ti:tf] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]
  I01  = 1j*cumtrapz( (Reg2Up  [ti:tf] * Reg2Down[ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I01 +=    cumtrapz( (Reg2Up  [ti:tf] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]
  I0R  = 1j*cumtrapz( (Reg2Read[ti:tf] * Reg2Down[ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I0R +=    cumtrapz( (Reg2Read[ti:tf] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]

#  I11  = 1j*cumtrapz( (Reg2Up  [ti:tf].conj() * Reg2Up  [ti:tf]).imag, x=None, dx=dt )[-1]
  I11  =    cumtrapz( (Reg2Up  [ti:tf] * Reg2Up  [ti:tf].conj()).real, x=None, dx=dt )[-1]
  I10  = 1j*cumtrapz( (Reg2Down[ti:tf] * Reg2Up  [ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I10 +=    cumtrapz( (Reg2Down[ti:tf] * Reg2Up  [ti:tf].conj()).real, x=None, dx=dt )[-1]
  I1R  = 1j*cumtrapz( (Reg2Read[ti:tf] * Reg2Up  [ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I1R +=    cumtrapz( (Reg2Read[ti:tf] * Reg2Up  [ti:tf].conj()).real, x=None, dx=dt )[-1]

  for i in sp.arange(0.0,thetaCnt):
    theta = i/(thetaCnt-1.0)   # from 0 to 1 * pi
    
    for j in sp.arange(0.0,phiCnt):
      phi = j/(phiCnt-1.0)*2.0 # from 0 to 2 * pi
      
      spos[0,i,j]    = sp.cos(theta*sp.pi/2.0) 
      spos[1,i,j]    = sp.sin(theta*sp.pi/2.0)*sp.exp(1j*phi*sp.pi)

  if fortranCheck == 1:
    cmd = "./scripts/ifort-checkBloch.sh " + wd
    print ("compile fortran routines: "+cmd)
    call(cmd.split())

    print ("### call checkBloch")
    cmd=wd+"checkBloch"
    generateSuperposition = Popen(cmd.split(), stdin=PIPE)                     # run fortran program with piped standard input
    cmd = "echo {:}".format(thetaCnt)                                          # communication with fortran-routine: chose superposition parameter
    generateInput     = Popen(cmd.split(), stdout=generateSuperposition.stdin) # send action to fortran program
    cmd = "echo {:}".format(phiCnt)                                            # communication with fortran-routine: chose superposition parameter
    generateInput     = Popen(cmd.split(), stdout=generateSuperposition.stdin) # send action to fortran program
    output            = generateSuperposition.communicate()[0]
    generateInput.wait()

    FuncInfoOlap [0,:,:],FuncInfoOlap [1,:,:]=IOHelper.read_MtrxProjection(thetaCnt,phiCnt,**cfg['FILES'])

  else:
    for i in sp.arange(0.0,thetaCnt):     
      for j in sp.arange(0.0,phiCnt):
        FuncCavity     = spos[0,i,j]*Reg2Down[ti:tf] + spos[1,i,j]*Reg2Up[ti:tf]
        FuncCavity[:] += Reg2Read  [ti:tf]

        FuncInfoOlap [0,i,j]  =    cumtrapz( (FuncCavity[:] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]
        FuncInfoOlap [0,i,j] += 1j*cumtrapz( (FuncCavity[:] * Reg2Down[ti:tf].conj()).imag, x=None, dx=dt )[-1]

        FuncInfoOlap [1,i,j]  =    cumtrapz( (FuncCavity[:] * Reg2Up[ti:tf].conj()).real, x=None, dx=dt )[-1]
        FuncInfoOlap [1,i,j] += 1j*cumtrapz( (FuncCavity[:] * Reg2Up[ti:tf].conj()).imag, x=None, dx=dt )[-1]

  if minOlap==0:
    gamma[:,:]=((FuncInfoOlap [0,:,:]-I0R)*I11+(I1R-FuncInfoOlap [1,:,:])*I01)/(I11*I00-I01*I10)
    delta[:,:]=((FuncInfoOlap [1,:,:]-I1R)*I00+(I0R-FuncInfoOlap [0,:,:])*I10)/(I11*I00-I01*I10)
  else :
    gamma[:,:]= (FuncInfoOlap [0,:,:]-I0R)/I00
    delta[:,:]= (FuncInfoOlap [1,:,:]-I1R)/I11

  fs   = 22
  label_size = 12
  plt.rcParams['xtick.labelsize'] = label_size 
  plt.rcParams['ytick.labelsize'] = label_size 
  plt.rcParams['xtick.major.pad']='20'
  plt.rcParams['ytick.major.pad']='20'
  fig  = plt.figure()

  if bloch == 0:
    xx, yy = sp.meshgrid(sp.linspace(0.0,2.0,phiCnt),sp.linspace(0.0,1.0,thetaCnt))

    zmin   =  0.0
    zmax   = +1.0

    zzOlapR0 = gamma [:,:].real
    zzOlapI0 = gamma [:,:].imag
    zzErr0   = sp.absolute(gamma[:,:]-spos[0,:,:])

    zzOlapR1 = delta [:,:].real
    zzOlapI1 = delta [:,:].imag
    zzErr1   = sp.absolute(delta[:,:]-spos[1,:,:])    

    fig1 = fig.add_subplot(321, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapR0, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR0.min(), vmax=zzOlapR0.max())
    fig1.set_zlim(0,1)
#    fig1.set_title("Re$[\,\gamma_R\,]\\approx\cos(\\theta/2)$",fontsize=fs)
    fig1.set_title("Re$[\,\gamma_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)

    fig1 = fig.add_subplot(323, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapI0, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI0.min(), vmax=zzOlapI0.max())
#    fig1.set_zlim(-0.01,0.01)
#    fig1.set_title("Im$[\,\gamma_R\,]\\approx\cos(\\theta/2)$",fontsize=fs)
    fig1.set_title("Im$[\,\gamma_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W/\pi$",fontsize=fs)

    fig1 = fig.add_subplot(322, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapR1, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR1.min(), vmax=zzOlapR1.max())
    fig1.set_zlim(-1,1)
#    fig1.set_title("Re$[\,\delta_R\,]\\approx\sin(\\theta/2)\cos(\phi)$",fontsize=fs)
    fig1.set_title("Re$[\,\delta_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)

    fig1 = fig.add_subplot(324, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapI1, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI1.min(), vmax=zzOlapI1.max())
    fig1.set_zlim(-1,1)
#    fig1.set_title("Im$[\,\delta_R\,]\\approx\sin(\\theta/2)\sin(\phi)$",fontsize=fs)
    fig1.set_title("Im$[\,\delta_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W/\pi$",fontsize=fs)

    fig1 = fig.add_subplot(325, projection='3d')
    fig1.plot_surface(xx, yy, zzErr0, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzErr0.min(), vmax=zzErr0.max())
#    fig1.set_zlim(-1,1)
#    fig1.set_title("Re$[\,\delta_R\,]\\approx\sin(\\theta/2)\cos(\phi)$",fontsize=fs)
    fig1.set_title("$\epsilon_\gamma$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)


    fig1 = fig.add_subplot(326, projection='3d')
    fig1.plot_surface(xx, yy, zzErr1, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzErr1.min(), vmax=zzErr1.max())
#    fig1.set_zlim(-1,1)
#    fig1.set_title("Re$[\,\delta_R\,]\\approx\sin(\\theta/2)\cos(\phi)$",fontsize=fs)
    fig1.set_title("$\epsilon_\delta$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)

  else:
  
#    x_expect = 2e0*sp.real(FuncInfoOlap [0,:,:]*FuncInfoOlap [1,:,:])
#  

    x      = 2e0*sp.real(spos[0,:,:].conj()*spos [1,:,:])
    y      = 2e0*sp.real(spos[0,:,:].conj()*spos [1,:,:]/1.0j)
    z      = sp.absolute(spos[0,:,:])**2   -sp.absolute(spos [1,:,:])**2

    xprime = 2e0*sp.real(gamma [:,:].conj()*delta [:,:])
    yprime = 2e0*sp.real(gamma [:,:].conj()*delta [:,:]/1.0j)
    zprime = sp.absolute(gamma [:,:])**2   -sp.absolute(delta [:,:])**2
    
    myDensity = sp.sqrt(sp.absolute(x-xprime)**2 + sp.absolute(y-yprime)**2 + sp.absolute(z-zprime)**2)
#    myDensity = 1.0 -  (x*xprime + y*yprime + z*zprime) 
    
    cm       = plt.cm.get_cmap(myMap) 
    myMin    = myDensity.min()
    myMax    = max(sp.absolute(myDensity.max()),sp.absolute(myDensity.min()))
    myColors = cm(myDensity/myMax)
    m        = plt.cm.ScalarMappable(cmap=myMap)

    fig3D = fig.add_subplot(1, 1, 1, projection='3d')

    surf  = fig3D.plot_surface(xprime, yprime, zprime, rstride=1, cstride=1, linewidth=1, color="black", 
                               facecolors=myColors,shade=False,antialiased=True,
                               vmin=myMin, vmax=myMax)
#    fig3D.plot_wireframe(x*1.01, y*1.01, z*1.01, rstride=1, cstride=1,alpha=1,linewidth=1,color="black")
    tick2=(myMin+myMax)/2.0
    tick1=round_sig(myMin+(myMax-myMin)*0.1,2)
    tick3=round_sig(myMax-(myMax-myMin)*0.1,2)
    tick2=round_sig(tick2,2)
    print "### error boundaries:", tick1,tick2,tick3

    m.set_array(myDensity)
    cb= plt.colorbar(m,shrink=0.5,aspect=7,ticks=([tick1,tick2,tick3]))    
    cb.formatter.set_scientific(True) 
    cb.formatter.set_powerlimits((0, 0))
    cb.update_ticks()
    
    fig3D.set_xlabel("$\langle \sigma_x(\gamma^\prime,\delta^\prime) \\rangle$", fontsize=fs)
    fig3D.set_ylabel("$\langle \sigma_y(\gamma^\prime,\delta^\prime) \\rangle$", fontsize=fs)
    fig3D.set_zlabel("$\langle \sigma_z(\gamma^\prime,\delta^\prime) \\rangle$", fontsize=fs)
    
    fig3D.set_xticks([-1,0,1])
    fig3D.set_xlim([-1.01,1.01])
    fig3D.xaxis._axinfo['label']['space_factor'] = 2.0

    fig3D.set_yticks([-1,0,1])
    fig3D.set_ylim([-1.01,1.01])
    fig3D.yaxis._axinfo['label']['space_factor'] = 2.0

    fig3D.set_zticks([-1,0,1])
    fig3D.set_zlim([-1.01,1.01])
    fig3D.zaxis._axinfo['label']['space_factor'] = 2.0

    
  plt.show()
def main_routine (writeBase=8.0,writeCnt=1,readBase=2.0,readCnt=1,datPath="dat/",prefix="pa",destPath="../parallel/",gentype="c",funcCfg=0):
  """
     Parameters:
       -----------
       --writeBase: maximum value of writing time interval in multiples of Pi/{base_rabi}.
                    (float)
       --wirteCnt:  number of different writing intervals from 1.0 to writeBase times Pi/{base_rabi}
                    (int)
       --readBase:  maximum value of reading time interval in multiples of Pi/{base_rabi}.
                    (float)
       --readCnt:   number of different reading intervals from 1.0 to readBase times Pi/{base_rabi}
                    (int)
       --destPath:  directory where output files are generated (for every parameter setting of
                    writeBase/writeCnt, readBase/readCnt a corresponding subdirectory is created)
                    (string)
       --gentype :  type of data generation -->
                    g : generate data with modNv
                    r : read data with modNv and 
                    c : collect  data and produce 3d plot of reading area
  """
  dWrite   = sp.array(range(0,writeCnt))
  dRead    = sp.array(range(0,readCnt))

  if (writeCnt == 1):
    write_base = sp.ones([readCnt])*writeBase
  else:
    write_base = (1.0+(writeBase-1.0)/float(writeCnt-1)*dWrite[:])

  if (readCnt == 1):
    read_base = sp.ones([writeCnt])*readBase
  else:
    read_base  = (1.0+(readBase-1.0)/float(readCnt-1)*dRead[:])

  print read_base

#  print (write_base)
#  print (read_base)

  if (gentype=="g" or gentype=="r"): # generate
    pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())

    results = [ pool.apply_async(run_single_job, args=(wb,rb,datPath,prefix,destPath,gentype,funcCfg))
                 for wb,rb in zip(write_base, read_base) ]

    results = [ p.get() for p in results ]
    pool.terminate()

  elif (gentype=="c"): # collect

    configPath="./python/parameter.cfg"
    print ("load from config file: " + configPath)
    configParser = cp.ConfigParser()
    configParser.read(configPath)
    cfg=configParser.__dict__['_sections'].copy()
   
    nRead =int(cfg['OCFourier']['{read_harmonic}'])
    nWrite=int(cfg['OCFourier']['{write_harmonic}'])

    timeCntWrite = int(cfg['OCTime']['{write_timecnt}'])
    timeCntRead  = int(cfg['OCTime']['{read_timecnt}'])
    timeCnt      = timeCntRead+timeCntWrite

    omega_c=float(cfg['NVSETUP']['{omega_c}'])*2.0*sp.pi
    omega_r=float(cfg['OCFourier']['{base_rabi}'])/1e6
    tUnit  =sp.pi/(2.0*sp.pi*1e3*omega_r)

    filelist=[]
    div     =10.0
#    readCnt = 17
    cavity=sp.zeros((2,readCnt,timeCntRead))
    time    =sp.zeros(timeCnt)
    wb=write_base[-1]  # choose last element
    errCnt=[]

    name_optimized=cfg['FILES']['{name_optimized}']
    name_readwrite=IOHelper.getNameReadWrite(**cfg) 


    for rb in range(readCnt):
      newDir=dest(destPath,wb,read_base[rb])
      cfg['FILES']['{prefix}'] = newDir+datPath+prefix+name_readwrite+name_optimized

      try:
        filename=cfg['FILES']['{prefix}']+"cavityMode_read_down"+cfg['FILES']['{postfix}']
        print filename
        time,real,imag = sp.loadtxt(filename).T
        cavity[0,rb,:] = real[timeCntWrite:timeCntWrite+timeCntRead]**2+imag[timeCntWrite:timeCntWrite+timeCntRead]**2
      except:
        errCnt.append("down: {:8.4f}\n".format(read_base[rb]))

      try:
        filename=cfg['FILES']['{prefix}']+"cavityMode_read_up"+cfg['FILES']['{postfix}']
        time,real,imag = sp.loadtxt(filename).T
        cavity[1,rb,:] = real[timeCntWrite:timeCntWrite+timeCntRead]**2+imag[timeCntWrite:timeCntWrite+timeCntRead]**2
      except:
        errCnt.append("up: {:8.4f}\n".format(read_base[rb]))

    if (len(errCnt) != 0):
      print ("can't read some files:\n" + str(errCnt))

    print ("generating color map")

    # read funtional times t2, t3
    newDir=dest(destPath,wb,read_base.max())
    cfg['FILES']['{prefix}']=newDir+datPath+prefix
    functime                =IOHelper.functionaltimes_readwrite(**cfg)

    ti=float(functime['ti'])/omega_c/tUnit  # in nano seconds
    ti_i = int(functime['idx_ti'])-1

    tf=float(functime['tf'])/omega_c/tUnit  # in nano seconds
    tf_i = int(functime['idx_tf'])

    functimeX   =sp.array([1.0,readBase])
    functimeY   =sp.array([(tf+ti)/2.0,tf])
    cutShortX   =sp.array([1.0,1.0])
    cutLargeX   =sp.array([readBase,readBase])
    cutShortY   =sp.array([writeBase,writeBase+readBase/2.0])
    cutLargeY   =sp.array([writeBase,writeBase+readBase])
    functimeZ   =sp.array([-1.5,-1.5])
    functimeYMid=sp.array([ti + (tf-ti)/4.0,ti+ (tf-ti)/2.0])
    # read funtional times t2, t3

    # define the grid over which the function should be plotted (xx and yy are matrices)
    xx, yy = sp.meshgrid(sp.linspace(1.0,readBase,readCnt),
                         sp.linspace(ti,tf,tf_i-ti_i))
    zz0     = cavity[0,:,ti_i:tf_i].T/cavity[:,:,ti_i:tf_i].max()
    zz1     = cavity[1,:,ti_i:tf_i].T/cavity[:,:,ti_i:tf_i].max()

#    xx, yy = sp.meshgrid(sp.linspace(1.0,readBase,readCnt),
#                         sp.linspace(time[timeCntRead/div]/tUnit,time[-1]/tUnit,timeCntRead/div))
#    zz1     = cavity[0,:,:].T/cavity[:,:,:].max()
#    zz1     = cavity[1,:,:].T/cavity[:,:,:].max()

    font = {
    'fontsize'            : 26,
    'verticalalignment'   : 'top',
    'horizontalalignment' : 'center'
    }

#    cm('font', **font)
#    rc('text', usetex=True)


    fig = plt.figure()
#    ax = fig.gca(projection='3d')
    fig0 = fig.add_subplot(121, projection='3d')
    fig0.plot_surface(xx, yy, zz0, rstride=10, cstride=5, cmap=cm.Blues, alpha=0.5,zorder=11.0,vmin=-0.25, vmax=1)
    fig0.contourf(xx, yy, zz0, zdir='z', offset=-1.5, cmap=cm.Blues,vmin=-0.25, vmax=1)
    fig0.plot(functimeX, functimeY, functimeZ,'k--',zorder=10.0) 
    fig0.plot(functimeX, functimeYMid, functimeZ,'k--',zorder=10.0) 
    fig0.plot(cutShortX, cutShortY, functimeZ,'m-',linewidth=2.5,zorder=10.0) 
    fig0.plot(cutLargeX, cutLargeY, functimeZ,'g-',linewidth=2.5,zorder=10.0) 
    fig0.set_title("a) state \"0\"", **font)
    fig0.set_xlabel("$\Delta T_{\cal F} \, / \, \\frac{T_R}{2}$", **font)
    fig0.set_ylabel("$t \, / \, \\frac{T_R}{2}$", **font)
    fig0.set_zlabel("$\left|A(t)\\right|^2 \, / \, \left|A_{max}(t)\\right|^2$", **font)
    fig0.set_zlim(-1.5, 1.0)

    fig1 = fig.add_subplot(122, projection='3d')
    fig1.plot_surface(xx, yy, zz1, rstride=10, cstride=5, cmap=cm.Reds, alpha=0.5,zorder=11.0,vmin=-0.25, vmax=1)
    fig1.contourf(xx, yy, zz1, zdir='z', offset=-1.5, cmap=cm.Reds,vmin=-0.25, vmax=1)
    fig1.plot(functimeX, functimeY, functimeZ,'k--',zorder=10.0) 
    fig1.plot(functimeX, functimeYMid, functimeZ,'k--',zorder=10.0) 
    fig1.plot(cutShortX, cutShortY, functimeZ,'m-',linewidth=2.5,zorder=10.0) 
    fig1.plot(cutLargeX, cutLargeY, functimeZ,'g-',linewidth=2.5,zorder=10.0) 
    fig1.set_title("b) state \"1\"", **font)
    fig1.set_xlabel("$\Delta T_{\cal F} \, / \, \\frac{T_R}{2}$", **font)
    fig1.set_ylabel("$t \, / \, \\frac{T_R}{2}$", **font)
    fig1.set_zlabel("$\left|A(t)\\right|^2 \, / \, \left|A_{max}(t)\\right|^2$", **font)
    fig1.set_zlim(-1.5, 1.0)


#    plt.subplot(1, 2, 1)
#    plt.pcolor(xx,yy,zz0)
#    plt.axis([xx.min(),xx.max(),yy.min(),yy.max()])
#    plt.plot(functimeX,functimeY, 'w', linewidth=2)
#    plt.plot(functimeX,functimeYMid, 'w-', linewidth=2)
#    plt.title("time bin state \"0\"")
#    plt.xlabel("$T_{functional} \, / \, \\frac{\pi}{\Omega_R[MHz]}$", **font)
#    plt.ylabel("$t \, / \, \\frac{\pi}{\Omega_R[MHz]}$", **font)

#    plt.subplot(1, 2, 2)
#    plt.pcolor(xx,yy,zz1)
#    plt.axis([xx.min(),xx.max(),ti,tf])
#    plt.plot(functimeX,functimeY, 'w', linewidth=2)
#    plt.plot(functimeX,functimeYMid, 'w-', linewidth=2)
#    plt.title("time bin sstate \"1\"")
#    plt.xlabel("$T_{functional} \, / \, \\frac{\pi}{\Omega_R[MHz]}$", **font)

#    plt.colorbar(label="$\left|A_{0,/1}(t)\\right|^2 \, / \, max(\left|A(t))\\right|^2$")

    plt.show()

  else:
    print ("option unkown: gentype="+gentype)
def main_routine (wd="./",cfg="./python/parameter.cfg",cnt=11,sptype=1,myCmap="RdYlBu"):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  FuncInfo      = sp.zeros([cnt,2])
  FuncInfoPhase = sp.zeros([cnt,2])
  FuncSuperRead = sp.zeros([cnt,functime.size],complex)

  denom    = sp.zeros([2])
  denom[0] = cumtrapz( sp.absolute(Reg2DownRead[ti:tf])**2, x=None, dx=dt )[-1] 
  denom[1] = cumtrapz( sp.absolute(Reg2UpRead[ti:tf])**2, x=None, dx=dt )[-1] 
  
  for i in sp.arange(0.0,cnt):
    phi = i*2.0/(cnt-1.0)

    Reg1Super       = superimpose(Reg1Down,Reg1Up,phi,sptype)
    Reg2Super       = superimpose(Reg2Down,Reg2Up,phi,sptype)
    Reg2SuperRead   = Reg2Super + Reg2Read

    FuncSuperRead[i,:]   = Reg2SuperRead[ti:tf]
 
    FuncInfoIntegrand    = sp.absolute(FuncSuperRead[i,:]) * sp.absolute(Reg2DownRead[ti:tf])
    FuncInfo[i,0]        = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]/denom[0]
   
    FuncInfoIntegrand    = sp.absolute(FuncSuperRead[i,:]) * sp.absolute(Reg2UpRead[ti:tf])
    FuncInfo[i,1]        = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]/denom[1]

    FuncInfoIntegrand    = FuncSuperRead[i,:].conj() * Reg2UpRead[ti:tf]
    FuncInfoPhase[i,0]   = cumtrapz( FuncInfoIntegrand.real, x=None, dx=dt )[-1]/denom[1]
    FuncInfoPhase[i,1]   = cumtrapz( FuncInfoIntegrand.imag, x=None, dx=dt )[-1]/denom[1]


  xx, yy = sp.meshgrid(functime,sp.linspace(0.0,2.0,cnt))

  zzR    = FuncSuperRead.real/FuncSuperRead.real.max()
  zzI    = FuncSuperRead.imag/FuncSuperRead.imag.max()
  zzA    = sp.absolute(FuncSuperRead)**2/((sp.absolute(FuncSuperRead)**2).max())

  zmin   = -1.5
  zmax   = +1.0
  fs     = 20

  cm        = plt.cm.get_cmap(myCmap)
  myColors = cm(zzR)

  fig  = plt.figure()
  fig0 = fig.add_subplot(231, projection='3d')
  fig0.plot_surface(xx, yy, zzA, rstride=10, cstride=5, cmap=cm, alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
  fig0.contourf(xx, yy, zzA, zdir='z', offset=zmin, cmap=cm, vmin=-1, vmax=1,zorder=1.0)
  fig0.set_zlim(zmin,zmax)
  fig0.set_title("a) normalized $|A_0(t;\phi_0)|^2$",fontsize=fs)
  fig0.set_xlabel("$t$ in ns",fontsize=fs)
  fig0.set_ylabel("$\phi_0/\pi$",fontsize=fs)

  fig1 = fig.add_subplot(232, projection='3d')
  fig1.plot_surface(xx, yy, zzR, rstride=10, cstride=5, cmap=cm, alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
  fig1.contourf(xx, yy, zzR, zdir='z', offset=zmin, cmap=cm, vmin=-1, vmax=1,zorder=1.0)
  fig1.set_zlim(zmin,zmax)
  fig1.set_title("b) normalized $Re[\,A_0(t;\phi_0)\,]$",fontsize=fs)
  fig1.set_xlabel("$t$ in ns",fontsize=fs)
  fig1.set_ylabel("$\phi_0/\pi$",fontsize=fs)

  fig2 = fig.add_subplot(233, projection='3d')
  fig2.plot_surface(xx, yy, zzI, rstride=10, cstride=5, cmap=cm, alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
  fig2.contourf(xx, yy, zzI, zdir='z', offset=zmin, cmap=cm, vmin=-1, vmax=1,zorder=1.0)
  fig2.set_zlim(zmin,zmax)
  fig2.set_title("c) normalized $Im[\,A_0(t;\phi_0)\,]$",fontsize=fs)
  fig2.set_xlabel("$t$ in ns",fontsize=fs)
  fig2.set_ylabel("$\phi_0/\pi$",fontsize=fs)

  plt.subplot2grid((2,3),(1,0),colspan=1,rowspan=1)
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfo[:,0],label="overlap with $i=$'$0$'",linewidth="2",color="blue")
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfo[:,1],label="overlap with $i=$'$1$'",linewidth="2",color="red")
  plt.ylim(0,1.1)
  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
  plt.legend(bbox_to_anchor=(0.52, 0.0), loc=3, borderaxespad=0.)
  plt.title("d) classical overlap, $O_{\mathbb{R}}(i)$",fontsize=fs)
#  plt.title("$\\frac{1}{N}\int_{T_{{\cal F}1}}^{T_{{\cal F}2}}dt\,|A_0(t;\phi_0)|\cdot|A_i(t)|$",fontsize=fs)

#  FuncInfoPhase[:,0]-=min(FuncInfoPhase[:,0])
#  FuncInfoPhase[:,0]/=0.5*max(sp.absolute(FuncInfoPhase[:,0]))
#  FuncInfoPhase[:,0]-=1.0

#  FuncInfoPhase[:,1]-=min(FuncInfoPhase[:,1])
#  FuncInfoPhase[:,1]/=0.5*max(sp.absolute(FuncInfoPhase[:,1]))
#  FuncInfoPhase[:,1]-=1.0

  plt.subplot2grid((2,3),(1,1),colspan=1,rowspan=1)
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,0],label="Re[ $O_{\mathbb{C}}($'$1$'$)$ ]",linewidth="2",color="red")
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,1],label="Im[ $O_{\mathbb{C}}($'$1$'$)$ ]",linewidth="2",color="magenta")
  plt.title("e) complex overlap, $O_{\mathbb{C}}($'$1$'$)$",fontsize=fs)
#  plt.title("$\\frac{1}{N}\int_{T_{{\cal F}1}}^{T_{{\cal F}2}}dt\,A_0(t;\phi_0)^*\cdot A_1(t)$",fontsize=fs)
  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
  plt.legend(bbox_to_anchor=(0.66, 0.0), loc=3, borderaxespad=0.)
  plt.ylim(-1,1.1)

  FuncInfoPhase[:,0]-=min(FuncInfoPhase[:,0])
  FuncInfoPhase[:,0]/=0.5*max(sp.absolute(FuncInfoPhase[:,0]))
  FuncInfoPhase[:,0]-=1.0

  FuncInfoPhase[:,1]-=min(FuncInfoPhase[:,1])
  FuncInfoPhase[:,1]/=0.5*max(sp.absolute(FuncInfoPhase[:,1]))
  FuncInfoPhase[:,1]-=1.0

#  plt.subplot2grid((2,3),(1,2),colspan=1,rowspan=1)
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,0],linewidth="2",color="red")
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,1],linewidth="2",color="magenta")
#  plt.title("f) $O_{\mathbb{C}}$ scaled & translated, $(O_{\mathbb{C}}($'$1$'$)-I_R)/I_0$",fontsize=fs)
#  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
#  plt.ylim(-1,1)


  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",gammaCnt=11,bloch=0,myMap="custom",project=0):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  myDensity     = sp.zeros([functime.size,gammaCnt])
  FuncCavity    = sp.zeros([functime.size,gammaCnt],complex)
  spos          = sp.zeros([2,gammaCnt])
  FuncInfoOlap  = sp.zeros([2,gammaCnt],complex)

  I00  =    cumtrapz( sp.real(Reg2DownRead[ti:tf] * Reg2DownRead[ti:tf].conj()), x=None, dx=dt )[-1]
  I11  =    cumtrapz( sp.real(Reg2UpRead[ti:tf]   * Reg2UpRead[ti:tf].conj()),   x=None, dx=dt )[-1]

  for g in sp.arange(0.0,gammaCnt):
    gamma = g/(gammaCnt-1.0)   

    myDensity[:,g]=1.0-gamma
            
    spos[0,g]        = gamma
    spos[1,g]        = 1.0-gamma
    FuncCavity[:,g]  = spos[0,g]*Reg2Down[ti:tf] + spos[1,g]*Reg2Up[ti:tf]
    FuncCavity[:,g] += Reg2Read  [ti:tf]

    FuncInfoOlap [0,g]  =    cumtrapz( (FuncCavity[:,g] * Reg2DownRead[ti:tf].conj()).real, x=None, dx=dt )[-1]
    FuncInfoOlap [0,g] += 1j*cumtrapz( (FuncCavity[:,g] * Reg2DownRead[ti:tf].conj()).imag, x=None, dx=dt )[-1]
    FuncInfoOlap [0,g] /=    I00 
    FuncInfoOlap [0,g]  =    sp.absolute(FuncInfoOlap [0,g]) 

    FuncInfoOlap [1,g]  =    cumtrapz( (FuncCavity[:,g] * Reg2UpRead[ti:tf].conj()).real, x=None, dx=dt )[-1]
    FuncInfoOlap [1,g] += 1j*cumtrapz( (FuncCavity[:,g] * Reg2UpRead[ti:tf].conj()).imag, x=None, dx=dt )[-1]
    FuncInfoOlap [1,g] /=    I11       
    FuncInfoOlap [1,g]  =    sp.absolute(FuncInfoOlap [1,g]) 

#    FuncInfoOlap [0,g]  =    cumtrapz( sp.absolute(FuncCavity[:,g]) * sp.absolute(Reg2DownRead[ti:tf].conj()), x=None, dx=dt )[-1]
#    FuncInfoOlap [0,g] /=    I00 

#    FuncInfoOlap [1,g]  =    cumtrapz( sp.absolute(FuncCavity[:,g]) * sp.absolute(Reg2UpRead[ti:tf].conj()), x=None, dx=dt )[-1]
#    FuncInfoOlap [1,g] /=    I11       

  fig  = plt.figure()
  fs   = 22
  label_size = 20
  plt.rcParams['xtick.labelsize'] = label_size 
  plt.rcParams['ytick.labelsize'] = label_size 

  xx, yy = sp.meshgrid(sp.linspace(0.0,1.0,gammaCnt),functime)

  zmax      = (sp.absolute(FuncCavity)**2).max()

  c = mcolors.ColorConverter().to_rgb
  
  if myMap =="custom" :
    cm = make_colormap(
        [c('blue'), c('purple'), c('red')])
  else:
    cm       = plt.cm.get_cmap(myMap) 
    
  myColors = cm(myDensity)

  fig1 = fig.add_subplot(111, projection='3d')
  fig1.plot(spos[0,:], FuncInfoOlap [0,:].real, zs=functime[ project], zdir='y',lw=2.5, color="blue",label="$\gamma^{\prime}$",zorder=0.1)
  fig1.plot(spos[0,:], FuncInfoOlap [1,:].real, zs=functime[ project], zdir='y',lw=2.5, color="red" ,label="$\delta^{\prime}$",zorder=0.1)

  fig1.plot_surface(xx, yy, sp.absolute(FuncCavity)**2/zmax,rstride=1, cstride=1,alpha=1,facecolors=myColors, antialiased=False)
  fig1.plot_wireframe(xx, yy, sp.absolute(FuncCavity)**2/zmax, rstride=15, cstride=3,alpha=1,linewidth=1,color="black")


  fig1.legend(fontsize=fs)
  fig1.set_zlim(0,1.1)
  fig1.set_ylim(functime[0],functime[-1])
  fig1.set_xticks([0,0.5,1])
  fig1.set_yticks([55,75,95])
  fig1.set_zticks([0,0.5,1])
  fig1.set_xlim(0,1)
  fig1.set_zlabel("$|A(t)|^2$",fontsize=fs)
  fig1.set_ylabel("$t$ in ns",fontsize=fs)
  fig1.set_xlabel("$\gamma$",fontsize=fs)
  fig1.xaxis._axinfo['label']['space_factor'] = 2.0
  fig1.yaxis._axinfo['label']['space_factor'] = 2.0
  fig1.zaxis._axinfo['label']['space_factor'] = 2.0


#  m.set_array(myDensity)
#  plt.colorbar(m,shrink=0.5,aspect=7)    
    
  plt.show()
#if(movie_released):
#    key_words.append(movie_name+ " " + movie_language + " Movie Review");


# Call method to perform training
#print "Systems is learning and getting trained to predict :) :)....\n"


#--------------------------------------- STEP 2: TWITTER DATA---------------------------------------------

twitter_data = {}
is_tweet_from_file = False

# check if data is already present or should be fetched
if (IOHelper.checkIfFileExists('../Data/TwitterDataContainer', key_word + '.csv')):
    print "Data already present !! Skipping data fetch from twitter"
    twitter_data[0] = IOHelper.readCsvToStringList('../Data/TwitterDataContainer/'+ key_word + '.csv')
    print "Completed fetching tweets from file !!\n\n"
    is_tweet_from_file = True
else:
    # Fetch data from twitter
    #print "Fetching tweets from Twitter for keyword = ' " + key_word +" '. Please wait.....\n"
    print "Fetching tweets from Twitter for keyword = ' " + movie_name + " Movie" +" '. Please wait.....\n"
    #twitter_data[0] = get_tweets(key_word, 100)
    twitter_data[0] = get_tweets(movie_name+' Movie', 15)
    print "Completed fetching tweets from Twitter !!\n\n"


#--------------------------------------- STEP 3: YOUTUBE DATA---------------------------------------------
def main_routine (wd="./",cfg="./python/parameter.cfg",delayCnt=11,delay=27.725,phaseCnt=11,sType=1,p3d=0,AMap="Blues",RMap="Reds",IMap="Greens"):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

#  FuncInfo      = sp.zeros([3,delayCnt,phaseCnt])
#  FuncInfoPhase = sp.zeros([3,delayCnt,phaseCnt])
#  FuncShiftRead = sp.zeros([3,delayCnt,phaseCnt,functime.size],complex)
  FuncShiftRead = sp.zeros([delayCnt,phaseCnt,functime.size],complex)
  FuncInfoOlap  = sp.zeros([3,delayCnt,phaseCnt])
  FuncInfoArea  = sp.zeros([3,delayCnt,phaseCnt])

  for i in sp.arange(0.0,delayCnt):
    myDelay = i/(delayCnt-1.0)*delay

    shift=sp.absolute(time['read'][:]-(functime[0]-myDelay)).argmin()-1
    
    for j in sp.arange(0.0,phaseCnt):
      phi = j*2.0*sp.pi/(phaseCnt-1.0)
      
      FuncShiftRead[i,j,:]  = sp.exp(-1j*phi)*Reg2Down[shift:shift+functime.size] + Reg2Read[shift:shift+functime.size]
      FuncShiftRead[i,j,:] += Reg2UpRead  [ti:tf] # ????? why ??????


      FuncInfoIntegrand     = sp.absolute(FuncShiftRead[i,j,:])*sp.absolute(Reg2UpRead[ti:tf])
      FuncInfoOlap [0,i,j]  = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]

      FuncInfoIntegrand     = FuncShiftRead[i,j,:].conj() * Reg2UpRead[ti:tf]
      FuncInfoOlap [1,i,j]  = cumtrapz( FuncInfoIntegrand.real, x=None, dx=dt )[-1]
      FuncInfoOlap [2,i,j]  = cumtrapz( FuncInfoIntegrand.imag, x=None, dx=dt )[-1]


      FuncInfoArea [0,i,j]  = cumtrapz( sp.absolute(FuncShiftRead[i,j,:])**2, x=None, dx=dt )[-1]
      FuncInfoArea [1,i,j]  = cumtrapz( sp.real    (FuncShiftRead[i,j,:])   , x=None, dx=dt )[-1]
      FuncInfoArea [2,i,j]  = cumtrapz( sp.imag    (FuncShiftRead[i,j,:])   , x=None, dx=dt )[-1]



  xx, yy = sp.meshgrid(sp.linspace(0.0,2.0*sp.pi,phaseCnt),sp.linspace(0.0,delay,delayCnt))

  zzOlap2 = FuncInfoOlap[0,:,:]#/(sp.absolute(FuncInfoOlap[0,:,:]).max())
  zzOlapR = FuncInfoOlap[1,:,:]#/(sp.absolute(FuncInfoOlap[1,:,:]).max())
  zzOlapI = FuncInfoOlap[2,:,:]#/(sp.absolute(FuncInfoOlap[2,:,:]).max())

  zzArea2 = FuncInfoArea[0,:,:]#/(sp.absolute(FuncInfoArea[0,:,:]).max())
  zzAreaR = FuncInfoArea[1,:,:]#/(sp.absolute(FuncInfoArea[1,:,:]).max())
  zzAreaI = FuncInfoArea[2,:,:]#/(sp.absolute(FuncInfoArea[2,:,:]).max())

  zmin   = 0.0
  zmax   = +1.0
  fs     = 20

  fig  = plt.figure()

  fig1 = fig.add_subplot(231, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapR, rstride=5, cstride=5, cmap=RMap, alpha=0.5,zorder=11.0,vmin=zzOlapR.min(), vmax=zzOlapR.max())
#  fig1.contourf(xx, yy, zzOlapR, zdir='z', offset=zmin, cmap=RMap, vmin=-1, vmax=1,zorder=1.0)
  fig1.set_zlim(zzOlapR.min(),zzOlap2.max())
  fig1.set_title("a) Re$(O_{\mathbb{C}}(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t);A_1(t)))$",fontsize=fs)
  fig1.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig1.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig2 = fig.add_subplot(232, projection='3d')
  fig2.plot_surface(xx, yy, zzOlapI, rstride=5, cstride=5, cmap=IMap, alpha=0.5,zorder=11.0,vmin=zzOlapI.min(), vmax=zzOlapI.max())
#  fig2.contourf(xx, yy, zzOlapI, zdir='z', offset=zmin, cmap=IMap, vmin=-1, vmax=1,zorder=1.0)
  fig2.set_zlim(zzOlapI.min(),zzOlapI.max())
  fig2.set_title("b) Im$(O_{\mathbb{C}}(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t);A_1(t)))$",fontsize=fs)
  fig2.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig2.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig0 = fig.add_subplot(233, projection='3d')
  fig0.plot_surface(xx, yy, zzOlap2, rstride=5, cstride=5, cmap=AMap, alpha=0.5,zorder=11.0,vmin=zzOlap2.min(), vmax=zzOlap2.max())
#  fig0.contourf(xx, yy, zzOlap2, zdir='z', offset=zmin, cmap=AMap, vmin=0, vmax=1,zorder=1.0)
  fig0.set_zlim(zzOlap2.min(),zzOlap2.max())
  fig0.set_title("c) $O_{\mathbb{R}}(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t);A_1(t))$",fontsize=fs)
  fig0.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig0.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig4 = fig.add_subplot(234, projection='3d')
  fig4.plot_surface(xx, yy, zzAreaR, rstride=5, cstride=5, cmap=RMap, alpha=0.5,zorder=11.0,vmin=zzAreaR.min(), vmax=zzAreaR.max())
#  fig4.contourf(xx, yy, zzAreaR, zdir='z', offset=zmin, cmap=RMap, vmin=-1, vmax=1,zorder=1.0)
  fig4.set_zlim(zzAreaR.min(),zzAreaR.max())
  fig4.set_title("d) Area under Re$(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t))$",fontsize=fs)
  fig4.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig4.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig5 = fig.add_subplot(235, projection='3d')
  fig5.plot_surface(xx, yy, zzAreaI, rstride=5, cstride=5, cmap=IMap, alpha=0.5,zorder=11.0,vmin=zzAreaI.min(), vmax=zzAreaI.max())
 # fig5.contourf(xx, yy, zzAreaI, zdir='z', offset=zmin, cmap=IMap, vmin=-1, vmax=1,zorder=1.0)
  fig5.set_zlim(zzAreaI.min(),zzAreaI.max())
  fig5.set_title("e) Area under Im$(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t))$",fontsize=fs)
  fig5.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig5.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig3 = fig.add_subplot(236, projection='3d')
  fig3.plot_surface(xx, yy, zzArea2, rstride=5, cstride=5, cmap=AMap, alpha=0.5,zorder=11.0,vmin=zzArea2.min(), vmax=zzArea2.max())
#  fig3.contourf(xx, yy, zzArea2, zdir='z', offset=zmin, cmap=AMap, vmin=0, vmax=1,zorder=1.0)
  fig3.set_zlim(zzArea2.min(),zzArea2.max())
  fig3.set_title("f) Area under $|e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t)|^2$",fontsize=fs)
  fig3.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig3.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",start=-1,cut1=1000.0,cut2=1000.0,cut3=1000.0,stop=-1,test=0,plotType=0,impose=0,par1=0.0,par2=0.0):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf]

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)
  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2DownRead    = Reg2Down + sp.dot(alphaR.conj(),cavityRead)

  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2UpRead      = Reg2Up + sp.dot(alphaR.conj(),cavityRead)

  Reg1Super       = superimpose(Reg1Down,Reg1Up,par1,par2)
  Reg2Super       = superimpose(Reg2Down,Reg2Up,par1,par2)
  Reg2SuperRead   = Reg2Super + sp.dot(alphaR.conj(),cavityRead)

  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  minT = min(functime) # min(time['read'])
  maxT = max(functime) # min(time['read'])

  minYComplete = -0.6
  maxYComplete =  0.6

  minYInfo = -0.6
  maxYInfo =  0.4

  minYRead = -0.4
  maxYRead =  0.6

  fs = 25

  plt.subplot(5,3,1)
  plt.title("state '0'",fontsize=fs)
  plt.plot(time['read'],Reg2DownRead.real,color="blue",linewidth=2)
  plt.plot(time['read'],Reg2DownRead.imag,color="lightblue",linewidth=2)
  plt.ylabel("$A(t)$",fontsize=fs)
  plt.ylim([minYComplete,maxYComplete])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,2)
  plt.title("state '1'",fontsize=fs)
  plt.plot(time['read'],Reg2UpRead.real,color="red",linewidth=2)
  plt.plot(time['read'],Reg2UpRead.imag,color="orange",linewidth=2)
  plt.ylim([minYComplete,maxYComplete])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,3)
  plt.title("phaseshift $\phi_0=${:}$\pi$".format(par1),fontsize=fs)
  plt.plot(time['read'],Reg2SuperRead.real,color="green",linewidth=2)
  plt.plot(time['read'],Reg2SuperRead.imag,color="lightgreen",linewidth=2)
  plt.ylim([minYComplete,maxYComplete])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,4)
  plt.plot(time['read'],sp.absolute(Reg2DownRead)**2,color="blue",linewidth=2)
  plt.ylabel("$|A(t)|^2$",fontsize=fs)
  plt.ylim([0,(max(sp.absolute(minYComplete),sp.absolute(maxYComplete)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,5)
  plt.plot(time['read'],sp.absolute(Reg2UpRead)**2,color="red",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYComplete),sp.absolute(maxYComplete)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,6)
  plt.plot(time['read'],sp.absolute(Reg2SuperRead)**2,color="green",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYComplete),sp.absolute(maxYComplete)))])
  plt.xlim([minT,maxT])


  plt.subplot(5,3,7)
  plt.plot(time['read'],Reg2Down.real,color="blue",linewidth=2)
  plt.plot(time['read'],Reg2Down.imag,color="lightblue",linewidth=2)
  plt.ylabel("$\\tilde{A}(t)$",fontsize=fs)
  plt.ylim([minYInfo,maxYInfo])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,8)
  plt.plot(time['read'],Reg2Up.real,color="red",linewidth=2)
  plt.plot(time['read'],Reg2Up.imag,color="orange",linewidth=2)
  plt.ylim([minYInfo,maxYInfo])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,9)
  plt.plot(time['read'],Reg2Super.real,color="green",linewidth=2)
  plt.plot(time['read'],Reg2Super.imag,color="lightgreen",linewidth=2)
  plt.ylim([minYInfo,maxYInfo])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,10)
  plt.plot(time['read'],sp.absolute(Reg2Down)**2,color="blue",linewidth=2)
  plt.ylabel("$|\\tilde{A}(t)|^2$",fontsize=fs)
  plt.ylim([0,(max(sp.absolute(minYInfo),sp.absolute(maxYInfo)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,11)
  plt.plot(time['read'],sp.absolute(Reg2Up)**2,color="red",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYInfo),sp.absolute(maxYInfo)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,12)
  plt.plot(time['read'],sp.absolute(Reg2Super)**2,color="green",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYInfo),sp.absolute(maxYInfo)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,13)
  plt.plot(time['read'],Reg2Read.real,linewidth=2,color="black")
  plt.plot(time['read'],Reg2Read.imag,linewidth=2,color="darkgray")
  plt.ylim([minYRead,maxYRead])
  plt.xlim([minT,maxT])
  plt.ylabel("$\\tilde{A}_R(t)$",fontsize=fs)
  plt.xlabel("$t$ in ns",fontsize=fs)

  plt.subplot(5,3,14)
  plt.plot(time['read'],Reg2Read.real,linewidth=2,color="black")
  plt.plot(time['read'],Reg2Read.imag,linewidth=2,color="darkgray")
  plt.ylim([minYRead,maxYRead])
  plt.xlim([minT,maxT])
  plt.xlabel("$t$ in ns",fontsize=fs)

  plt.subplot(5,3,15)
  plt.plot(time['read'],Reg2Read.real,linewidth=2,color="black")
  plt.plot(time['read'],Reg2Read.imag,linewidth=2,color="darkgray")
  plt.ylim([minYRead,maxYRead])
  plt.xlim([minT,maxT])
  plt.xlabel("$t$ in ns",fontsize=fs)

#  plt.subplot(4,3,5)
#  plt.plot(functime,ReadUpReg2[ti:tf].imag,color="darkgray",linewidth=2)
#  plt.plot(functime,cavityUpReg3[ti:tf].imag,color="red",linewidth=2)
#  plt.xlim([min(functime),max(functime)])

#  plt.subplot(4,3,3)
#  if (impose != 1):
#    plt.title("$\\alpha_{S}$")
#    plt.bar(sp.arange(1,nStore+1,1),alphaS.real,color="green")
#  else :
#    plt.title("superposition, $A(t)$")
#    plt.plot(functime,ReadSuperReg2[ti:tf].real,color="darkgray",linewidth=2)
#    plt.plot(functime,cavitySuperReg3[ti:tf].real,color="green",linewidth=2)
#    plt.xlim([min(functime),max(functime)])

#  plt.subplot(4,3,6)
#  if (impose != 1):
#    plt.bar(sp.arange(1,nStore+1,1),alphaS.imag,color="green")
#  else :
#    plt.plot(functime,ReadSuperReg2[ti:tf].imag,color="darkgray",linewidth=2)
#    plt.plot(functime,cavitySuperReg3[ti:tf].imag,color="green",linewidth=2)
#    plt.xlim([min(functime),max(functime)])


#  plt.subplot2grid((4,3),(2,0),colspan=3,rowspan=2)

#  cavityCheckReg1,cavityCheckReg2,cavityCheckReg3 = pltFunction(cavityCheckReg1,cavityCheckReg2,cavityCheckReg3,plotType)
#  cavitySuperReg1,cavitySuperReg2,cavitySuperReg3 = pltFunction(cavitySuperReg1,cavitySuperReg2,cavitySuperReg3,plotType)
#  cavityDownReg1, cavityDownReg2, cavityDownReg3  = pltFunction(cavityDownReg1, cavityDownReg2, cavityDownReg3, plotType)
#  cavityUpReg1,   cavityUpReg2,   cavityUpReg3    = pltFunction(cavityUpReg1,   cavityUpReg2,   cavityUpReg3,   plotType)

#  if (test==1):
#    print ("### compile fortran routines")
#    cmd = "./scripts/ifort-memoryHarmonics.sh " + wd
#    call(cmd.split())

#    print ("### call memoryOptimized")
#    cmd=wd+"memoryOptimized"
#    call(cmd.split())

#    print ("### call memorySuperimposed")
#    cmd=wd+"memorySuperimposed"
#    generateSuperposition = Popen(cmd.split(), stdin=PIPE)                     # run fortran program with piped standard input
#    cmd = "echo {:}".format(par1)                                              # communication with fortran-routine: chose superposition parameter
#    generateInput     = Popen(cmd.split(), stdout=generateSuperposition.stdin) # send action to fortran program
#    output            = generateSuperposition.communicate()[0]
#    generateInput.wait()

#    filename = cfg['FILES']['{prefix}']+cfg['FILES']['{name_readwrite}']+\
#               cfg['FILES']['{name_storage}']+cfg['FILES']['{name_optimized}']

#    mytimeU,__,A_Re_U,A_Im_U = sp.loadtxt(filename+"cavity_up_stored"   +cfg['FILES']['{postfix}']).T
#    mytimeD,__,A_Re_D,A_Im_D = sp.loadtxt(filename+"cavity_down_stored" +cfg['FILES']['{postfix}']).T
#    mytimeS,__,A_Re_S,A_Im_S = sp.loadtxt(filename+"cavity_super_stored"+cfg['FILES']['{postfix}']).T

#    cavityMode_U,cavityMode_D,cavityMode_S = pltFunction(A_Re_U+1j*A_Im_U, A_Re_D+1j*A_Im_D, A_Re_S+1j*A_Im_S,plotType)

#  cavityMaxDown = max(max(cavityDownReg1),max(cavityDownReg2),max(cavityDownReg3))
#  cavityMaxUp   = max(max(cavityUpReg1),max(cavityUpReg2),max(cavityUpReg3))
#  cavityMaxSuper= max(max(cavitySuperReg1),max(cavitySuperReg2),max(cavitySuperReg3))
#  cavityMax     = max(cavityMaxDown,cavityMaxUp,cavityMaxSuper)

#  cavityMinDown = min(min(cavityDownReg1),min(cavityDownReg2),min(cavityDownReg3))
#  cavityMinUp   = min(min(cavityUpReg1),min(cavityUpReg2),min(cavityUpReg3))
#  cavityMinSuper= max(min(cavitySuperReg1),min(cavitySuperReg2),min(cavitySuperReg3))
#  cavityMin     = min(cavityMinDown,cavityMinUp,cavityMinSuper)

#  plt.plot(time['write'],cavityDownReg1,color="blue",linewidth=2)
#  plt.plot(time['store'],cavityDownReg2,color="blue",linewidth=2)
#  plt.plot(time['read'] ,cavityDownReg3,color="blue",linewidth=2,label="state '0'")

#  plt.plot(time['write'],cavityUpReg1,color="red",linewidth=2)
#  plt.plot(time['store'],cavityUpReg2,color="red",linewidth=2)
#  plt.plot(time['read'] ,cavityUpReg3,color="red",linewidth=2,label="state '1'")

#  if (impose == 1):
#    plt.plot(time['write'],cavitySuperReg1,color="green",linewidth=2)
#    plt.plot(time['store'],cavitySuperReg2,color="green",linewidth=2)
#    plt.plot(time['read'] ,cavitySuperReg3,color="green",linewidth=2,label="super state")

#  if (test == 1):
#    plt.plot(mytimeD,cavityMode_D,label="state '0' test",color="cyan")
#    plt.plot(mytimeU,cavityMode_U,label="state '1' test",color="magenta")
#    if (impose == 1):
#      plt.plot(time['write'],cavityCheckReg1,color="orange")
#      plt.plot(time['store'],cavityCheckReg2,color="orange")
#      plt.plot(time['read'] ,cavityCheckReg3,color="orange",label="super state")
#      plt.plot(mytimeS,cavityMode_S,label="super state test",color="brown")

##  plt.legend()
#  plt.xlabel('time in ns')
#  plt.ylabel('$|A(t)|^2$')

#  
#  if start != -1 and stop != -1:
#    plt.xlim([start,stop])
#  else:
#    plt.xlim([min(time['write']),max(time['read'])])

#  plt.ylim([cavityMin*1.1,cavityMax*1.1])

#  plt.fill_between(functime, cavityMax*1.1, cavityMin*1.1, color='lightgray', facecolor='lightgray', alpha=0.5)
#  plt.plot([time['store'][0],time['store'][0]], [cavityMin*1.1,cavityMax*1.1], 'k--')
#  plt.plot([time['read'] [0],time['read'] [0]], [cavityMin*1.1,cavityMax*1.1], 'k--')

#  plt.plot([cut1,cut1],[0,cavityMax*1.1],linewidth=2.0)
#  plt.plot([cut2,cut2],[0,cavityMax*1.1],linewidth=2.0)
#  plt.plot([cut3,cut3],[0,cavityMax*1.1],linewidth=2.0)

  plt.show()