コード例 #1
0
ファイル: ACCES.py プロジェクト: edemonpore/RTDAQ-32bit
    def UpdateData(self):
        self.t[self.ptr] = time.time() - self.t[0]
        if self.bAcquiring:
            data_in = ctypes.c_longdouble(
            )  # double-precision IEEE floating point data from ADC
            if self.AIOUSB.ADC_GetChannelV(-3, 0, ctypes.byref(data_in)) is 0:
                self.xdata[self.ptr] = float(
                    data_in.value) * 20  # Convert 0-5V to 0-100nm
            else:
                self.xdata[self.ptr] = 0
            if self.AIOUSB.ADC_GetChannelV(-3, 1, ctypes.byref(data_in)) is 0:
                self.ydata[self.ptr] = float(data_in.value) * 20
            else:
                self.ydata[self.ptr] = 0

        if __debug__ and not self.bAcquiring:
            self.xdata[self.ptr] = (math.sin(self.t[self.ptr]) + 1) * 50
            self.ydata[self.ptr] = (math.cos(self.t[self.ptr]) + 1) * 50

        self.xsetdata[self.ptr] = self.xset * 100 / 65535
        self.ysetdata[self.ptr] = self.yset * 100 / 65535
        self.zsetdata[self.ptr] = self.zset * 100 / 65535

        if self.ptr > self.datawindow:
            self.DataPlot(self.t[self.ptr - self.datawindow:self.ptr],
                          self.xdata[self.ptr - self.datawindow:self.ptr],
                          self.xsetdata[self.ptr - self.datawindow:self.ptr],
                          self.ydata[self.ptr - self.datawindow:self.ptr],
                          self.ysetdata[self.ptr - self.datawindow:self.ptr],
                          self.zsetdata[self.ptr - self.datawindow:self.ptr])

        self.ptr = self.ptr + 1
コード例 #2
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_power_ref(self):
     """     
     """
     power = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetPowerRef(C.byref(power))
     if (result != DLL_SUCCESS):
         print("TC4GetPowerRef failed")
         power = None
     return power.value
コード例 #3
0
def read_longdouble(hProcess, address):
    ReadBuffer = ctypes.c_longdouble()
    lpBuffer = ctypes.byref(ReadBuffer)
    nSize = ctypes.sizeof(ReadBuffer)
    bytesRead = ctypes.c_ulong(0)

    ctypes.windll.kernel32.ReadProcessMemory(hProcess, address, lpBuffer,
                                             nSize, bytesRead)
    return ReadBuffer.value
コード例 #4
0
 def post(self, request):
     sex = request.POST.get('sex')
     age = request.POST.get('age')
     duration = float(request.POST.get('duration'))
     mri = request.POST.get('mri')
     cortisol = request.POST.get('cortisol')
     plasma = request.POST.get('plasma')
     # context = {
     #     'sex' : sex,
     #     'age' : age,
     #     'duration' : duration,
     #     'mri': mri,
     #     'cortisol' : cortisol,
     #     'plasma' : plasma
     #
     # }
     cort_m2 = ctypes.c_longdouble(numpy.longdouble(cortisol))
     ach_m2 = ctypes.c_longdouble(numpy.longdouble(plasma))
     age_ = ctypes.c_longdouble(numpy.longdouble(age))
     duration_ = ctypes.c_longdouble(numpy.longdouble(duration))
     sex_ = ctypes.c_float(float(sex))
     mri_ = ctypes.c_float(float(mri))
     answ = libc.mainfunc(cort_m2, ach_m2, age_, duration_, sex_, mri_)
     #answ = libc.mainfunc(cort_m2, ach_m2, age_, duration_, sex_, mri_)
     #resstring = alloc_func(cort_m2, ach_m2, age_, duration_, sex_, mri_)
     #answ2 = ctypes.c_char_p.from_buffer(resstring)
     if answ == 0:
         text = "Remission within 3 years"
         percent = "93% [89%, 96%]"
     elif answ == 1:
         text = "Recurrence within 3 years"
         percent = "93% [89%, 96%]"
     cont = {
         'what_to_do' : '''alert('Hello! I am an alert box!!  %s '); ''',
         'answer': text,
         'percents': percent
     }
     #free_func = libc.mainfunc
     #free_func.argtypes = [ctypes.POINTER(ctypes.c_char), ]
     #free_func(answ)
     return render(request, 'mainpage.html', cont)
コード例 #5
0
def parse_longdouble(value):
    import ctypes
    from ctypes import c_longdouble, pointer

    val = c_longdouble()
    val_ptr = pointer(val)
    try:
        ctypes.cdll.LoadLibrary("libc.so.6").sscanf(value, "%Le", val_ptr)
    except WindowsError:
        return float(value)

    return np.ctypeslib.as_array(val_ptr, (1, ))[0]
コード例 #6
0
def parse_longdouble(value):
    import ctypes
    from ctypes import c_longdouble, pointer

    val = c_longdouble()
    val_ptr = pointer(val)
    try:
        ctypes.cdll.LoadLibrary("libc.so.6").sscanf(value, "%Le", val_ptr)
    except WindowsError:
        return float(value)

    return np.ctypeslib.as_array(val_ptr, (1,))[0]
コード例 #7
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_voltage_act(self):
     """     
     Parameters:
     [out]	p_vact	Actual voltage value [V]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     vact = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetVoltageAct(C.byref(vact))
     if (result != DLL_SUCCESS):
         print("TC4GetVoltageAct failed")
         vact = None
     return vact.value
コード例 #8
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_power_act(self):
     """     
     Parameters:
     [out]	p_pact	Actual power value [kW]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     pact = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetPowerAct(C.byref(pact))
     if (result != DLL_SUCCESS):
         print("TC4GetPowerAct failed")
         pact = None
     return pact.value
コード例 #9
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_resistance_ref(self):
     """
     Parameters:
     [out]	rref	PhysicalResistance [mOhm]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs   
     """
     resistance = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetResistanceRef(C.byref(resistance))
     if (result != DLL_SUCCESS):
         print("TC4GetResistanceRef failed")
         resistance = None
     return resistance.value
コード例 #10
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_current_act(self):
     """     
     Parameters:
     [out]	p_iact	Actual current value [A]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     iact = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetCurrentAct(C.byref(iact))
     if (result != DLL_SUCCESS):
         print("TC4GetCurrentAct failed")
         iact = None
     return iact.value
コード例 #11
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_current_ref(self):
     """     
     Parameters:
     [out]	iref	PhysicalCurrent [A]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     current = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetCurrentRef(C.byref(current))
     if (result != DLL_SUCCESS):
         print("TC4GetCurrentRef failed")
         current = None
     return current.value
コード例 #12
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def set_power_ref(self, pref):
     """     
     Parameters:
     [out]	rref	PhysicalResistance [mOhm]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     pref_double = C.c_longdouble()
     pref_double.value = float(pref)
     result = self.tcio_dll_obj.TC4GetPowerRef(C.byref(pref_double))
     if (result != DLL_SUCCESS):
         print("TC4GetPowerRef failed")
         pref_double = None
     return pref_double.value
コード例 #13
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_Q4_limit_current(self):
     """     
     Get Q4 controller current limit (parameter will be negative)
     Parameters:
     [out]	pCurrent	PhysicalCurrent [A]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs 
     """
     current = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetQ4LimitCurrent(C.byref(current))
     if (result != DLL_SUCCESS):
         print("DllClose failed")
         current = None
     return current
コード例 #14
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_Q4_limit_power(self):
     """     
     Get Q4 controller power limit (parameter will be negative)
     Parameters:
     [out]	pPower	PhysicalPower [kW]
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs 
     """
     power = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetQ4LimitPower(C.byref(power))
     if (result != DLL_SUCCESS):
         print("TC4GetQ4LimitPower failed")
         power = None
     return power
コード例 #15
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def get_resistance_act(self):
     """     
     Parameters:
     [out]	p_ract	Actual simulated resistance value
     Note:
     resistance is not measured - this will just read the set value
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     ract = C.c_longdouble()
     result = self.tcio_dll_obj.TC4GetResistanceAct(C.byref(ract))
     if (result != DLL_SUCCESS):
         print("TC4GetResistanceAct failed")
         ract = None
     return ract.value
コード例 #16
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def set_voltage_ref(self, vref):
     """     
     Parameters:
     [in]	vref	PhysicalVoltage [V]
     Precondition:
     Remote control input must be set to RS232
     Note:
     Calling these functions on a TopCon Slave will have no effect.
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     vref_double = C.c_longdouble()
     vref_double.value = float(vref)
     result = self.tcio_dll_obj.TC4SetVoltageRef(vref_double)
     if (result != DLL_SUCCESS):
         print("TC4SetVoltageRef failed")
     return vref_double.value
コード例 #17
0
ファイル: test_x64.py プロジェクト: tinix84/regatron_py
 def set_resistance_ref(self, rref):
     """     
     Parameters:
     [in]	rref	PhysicalResistance [mOhm]
     Precondition:
     Remote control input must be set to RS232
     Note:
     Calling these functions on a TopCon Slave will have no effect.
     Returns:
     DLL_SUCCESS for success or DLL_FAIL or other value if an error occurs
     """
     rref_double = C.c_longdouble()
     rref_double.value = rref
     result = self.tcio_dll_obj.TC4SetResistanceRef(rref_double)
     if (result != DLL_SUCCESS):
         print("TC4SetResistanceRef failed")
     return result.value
コード例 #18
0
ファイル: _objects.py プロジェクト: jianlingzhong/dill
    from io import StringIO as TextIO
    # built-in functions (CH 2)
    a['ByteArrayType'] = bytearray([1])
    # numeric and mathematical types (CH 9)
    a['FractionType'] = fractions.Fraction()
    a['NumberType'] = numbers.Number()
    # generic operating system services (CH 15)
    a['IOBaseType'] = io.IOBase()
    a['RawIOBaseType'] = io.RawIOBase()
    a['TextIOBaseType'] = io.TextIOBase()
    a['BufferedIOBaseType'] = io.BufferedIOBase()
    a['UnicodeIOType'] = TextIO() # the new StringIO
    a['LoggingAdapterType'] = logging.LoggingAdapter(_logger,_dict) # pickle ok
    if HAS_CTYPES:
        a['CBoolType'] = ctypes.c_bool(1)
        a['CLongDoubleType'] = ctypes.c_longdouble()
except ImportError:
    pass
try: # python 2.7
    import argparse
    # data types (CH 8)
    a['OrderedDictType'] = collections.OrderedDict(_dict)
    a['CounterType'] = collections.Counter(_dict)
    if HAS_CTYPES:
        a['CSSizeTType'] = ctypes.c_ssize_t()
    # generic operating system services (CH 15)
    a['NullHandlerType'] = logging.NullHandler() # pickle ok  # new 2.7
    a['ArgParseFileType'] = argparse.FileType() # pickle ok
#except AttributeError:
except ImportError:
    pass
コード例 #19
0
calculating = True

mandel = None

arrlen = width * height
cwidth = c_uint(int(width))
cheight = c_uint(int(height))
lib.mandelbrot.restype = ctypes.POINTER(c_uint32 * arrlen)

while True:

    if calculating:
        cresult = lib.mandelbrot(
            cwidth,
            cheight,
            c_longdouble(center[0] - mandel_range),
            c_longdouble(center[0] + mandel_range),
            c_longdouble(center[1] - mandel_range),
            c_longdouble(center[1] + mandel_range),
            c_uint32(int(max_iter)),
            c_longdouble(div_range),
            (ctypes.c_longdouble * len(coeffs))(*coeffs),
            (ctypes.c_longdouble * len(powers))(*powers),
            c_size_t(len(coeffs)),
        )

        mandel = np.array(cresult.contents).reshape((width, height))
        cmap = matplotlib.cm.get_cmap(cmaps[cmap_sel_ind], lut=max_iter)
        canvas = (cmap(mandel)[..., :3] * 255).astype("uint8")
        man = pygame.image.frombuffer(canvas.tobytes(), size, "RGB")
        screen.blit(man, (0, 0))
コード例 #20
0
ファイル: _objects.py プロジェクト: haojianggod/jd_etl_task
    # built-in functions (CH 2)
    a["ByteArrayType"] = bytearray([1])
    # numeric and mathematical types (CH 9)
    a["FractionType"] = fractions.Fraction()
    a["NumberType"] = numbers.Number()
    # generic operating system services (CH 15)
    a["IOBaseType"] = io.IOBase()
    a["RawIOBaseType"] = io.RawIOBase()
    a["TextIOBaseType"] = io.TextIOBase()
    a["BufferedIOBaseType"] = io.BufferedIOBase()
    a["UnicodeIOType"] = TextIO()  # the new StringIO
    a["LoggingAdapterType"] = logging.LoggingAdapter(_logger, _dict)  # pickle ok
    if HAS_CTYPES:
        a["CBoolType"] = ctypes.c_bool(1)
        a["CLongDoubleType"] = ctypes.c_longdouble()
except ImportError:
    pass
try:  # python 2.7
    import argparse

    # data types (CH 8)
    a["OrderedDictType"] = collections.OrderedDict(_dict)
    a["CounterType"] = collections.Counter(_dict)
    if HAS_CTYPES:
        a["CSSizeTType"] = ctypes.c_ssize_t()
    # generic operating system services (CH 15)
    a["NullHandlerType"] = logging.NullHandler()  # pickle ok  # new 2.7
    a["ArgParseFileType"] = argparse.FileType()  # pickle ok
# except AttributeError:
except ImportError:
コード例 #21
0
ファイル: dOut.py プロジェクト: melxman/UEFI-BIOS-Flasher
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_ushort(0x02)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_long(0x03)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_ulong(0x0A)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_int(0x0B)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_uint(0x0C)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_float(0x0D)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_double(0x0E)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_longdouble(0x0F)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_longlong(0x10)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_ulonglong(0x11)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_ubyte(0x12)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_byte(0x13)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_char('a')
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_wchar(u'b')
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'

    d.msg += '<arg ' + get_arg_xml("string test") + '></arg>'
コード例 #22
0
def generate_models(network):
    '''
    This method generates RACIPE models. 
    '''
    import numpy
    import numpy as np
    import ctypes
    import sys
    global clib

    node_dict = network.get_node_dict()

    node_id_dict = network.get_node_id_dict()

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    NUM_NODES = len(node_id_dict.keys())  #size of node_id_arr
    NUM_EDGES = len(edge_source_dict.keys())  #size of edge_id_arr

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1
    #create character array for work directory string:
    WORK_DIR = (network.get_work_dir()).encode('utf-8')

    #create character arrays for file names to be used in C:
    fname_dict_simu = network.get_fname_dict_simu()
    FNAME_STATES = fname_dict_simu['FNAME_STATES'].encode('utf-8')
    FNAME_LIMITCYCLES = fname_dict_simu['FNAME_LIMITCYCLES'].encode('utf-8')
    FNAME_SUMMARY = fname_dict_simu['FNAME_SUMMARY'].encode('utf-8')

    #create arrays for storing node and edge parameters:
    MPR_arr = np.zeros(NUM_NODES, dtype=np.double)
    DNR_arr = np.zeros(NUM_NODES, dtype=np.double)
    NODE_TYPE_arr = np.zeros(NUM_NODES, dtype=np.intc)

    TSH_arr = np.zeros(NUM_EDGES, dtype=np.double)
    HCO_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    FCH_arr = np.zeros(NUM_EDGES, dtype=np.double)

    #create array for storing the types of the edges:
    edge_type_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_type_dict.keys():
        edge_type_arr[i] = edge_type_dict[idx]
        i += 1

    #open file to write parameters:
    params_fname = network.get_params_fname()
    fh_params = open(params_fname, 'w')

    #open files to write parameters:
    fh_dict_nodeparams = OrderedDict()
    fh_dict_edgeparams = OrderedDict()
    fh_dict_nodeparams, fh_dict_edgeparams = open_parameter_files(network)

    #open files to write solutions:
    fname_dict_solutions, fh_dict_solutions = open_solution_files(network)
    #open file to write limit cycle trace:
    LCtrace_fname = network.get_LCtrace_fname()
    fh_LCtrace = open(LCtrace_fname, 'w')

    #import config_dict:
    config_dict = network.get_config_dict()

    model_no = 1
    while model_no <= int(config_dict['NUM_MODELS']):
        (nodeParam_dict, source_dict, master_dict) = set_parameters(network)

        i = 0
        for X in nodeParam_dict.keys():
            NODE_TYPE_arr[i] = nodeParam_dict[X][0]
            MPR_arr[i] = nodeParam_dict[X][1]
            #print(MPR_arr[i])
            DNR_arr[i] = nodeParam_dict[X][2]
            i += 1

        for idx, e in master_dict.items():
            TSH_arr[idx] = master_dict[idx][3]
            HCO_arr[idx] = master_dict[idx][4]
            FCH_arr[idx] = master_dict[idx][5]
        EXP_dict_arr = np.zeros(NUM_NODES * int(config_dict['NUM_RANDOM_ICS']),
                                dtype=np.double)

        #start_time=time.time()
        clib.find_solutions(\
             ctypes.create_string_buffer(WORK_DIR),
             ctypes.create_string_buffer(FNAME_STATES),
             ctypes.create_string_buffer(FNAME_LIMITCYCLES),
             ctypes.create_string_buffer(FNAME_SUMMARY),
             ctypes.c_int(model_no),
             ctypes.c_int(NUM_NODES),
             ctypes.c_int(NUM_EDGES),
             ctypes.c_int(int(config_dict['NUM_RANDOM_ICS'])),
             ctypes.c_int(int(config_dict['ITER_FOR_ODE'])),
             ctypes.c_double(float(config_dict['EULER_SIM_TIME'])),
             ctypes.c_double(float(config_dict['EULER_SIM_STEP_SIZE'])),
             ctypes.c_longdouble(float(config_dict['CONVERGENCE_PROXIMITY'])),
             ctypes.c_double(float(config_dict['TRANS_RATE_FACTOR'])),
             ctypes.c_void_p(MPR_arr.ctypes.data),
             ctypes.c_void_p(DNR_arr.ctypes.data),
             ctypes.c_void_p(NODE_TYPE_arr.ctypes.data),
             ctypes.c_void_p(edge_source_arr.ctypes.data),
             ctypes.c_void_p(edge_target_arr.ctypes.data),
             ctypes.c_void_p(edge_type_arr.ctypes.data),
             ctypes.c_void_p(TSH_arr.ctypes.data),
             ctypes.c_void_p(HCO_arr.ctypes.data),
             ctypes.c_void_p(FCH_arr.ctypes.data),
             ctypes.c_void_p(EXP_dict_arr.ctypes.data)
             )
        #end_time=time.time()

        #place the solutions in a dictionary:
        expression_dict = OrderedDict()
        expression_dict_ICs = OrderedDict()
        count_iteration = 0
        for i in range(0, NUM_NODES * int(config_dict['NUM_RANDOM_ICS']),
                       NUM_NODES):
            for node, node_id in node_id_dict.items():
                expression_dict[node] = EXP_dict_arr[i + node_id]
            expression_dict_ICs[count_iteration] = expression_dict.copy()
            count_iteration += 1
        (solution_dict,
         solution_count_dict) = count_states(config_dict, expression_dict_ICs,
                                             fh_LCtrace)
        save_parameters(fh_params, model_no, nodeParam_dict, master_dict,
                        solution_dict)
        save_parameters_5(fh_dict_nodeparams, fh_dict_edgeparams, model_no,
                          nodeParam_dict, master_dict, solution_dict)

        save_solutions(fh_dict_solutions, model_no, solution_dict)

        if (not model_no % 100):
            flush_solutions(fh_dict_solutions)
        model_no += 1
    fh_params.close()
    fh_LCtrace.close()
    close_solution_files(fname_dict_solutions, fh_dict_solutions)
    close_parameter_files(fh_dict_nodeparams, fh_dict_edgeparams)
    return None
コード例 #23
0
def cal_expressions(network):
    '''
    This method generates RACIPE models. 
    '''
    import numpy
    import numpy as np
    import ctypes
    import sys
    global clib

    node_dict = network.get_node_dict()

    node_id_dict = network.get_node_id_dict()

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    NUM_NODES = len(node_id_dict.keys())  #size of node_id_arr
    NUM_EDGES = len(edge_source_dict.keys())  #size of edge_id_arr

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1

    #create character array for work directory string:
    WORK_DIR = (network.get_work_dir()).encode('utf-8')

    #create character arrays for file names to be used in C:
    fname_dict_simu = network.get_fname_dict_simu()
    FNAME_STATES = fname_dict_simu['FNAME_STATES'].encode('utf-8')
    FNAME_LIMITCYCLES = fname_dict_simu['FNAME_LIMITCYCLES'].encode('utf-8')
    FNAME_SUMMARY = fname_dict_simu['FNAME_SUMMARY'].encode('utf-8')

    #create arrays for storing node and edge parameters:
    MPR_arr = np.zeros(NUM_NODES, dtype=np.double)
    DNR_arr = np.zeros(NUM_NODES, dtype=np.double)
    NODE_TYPE_arr = np.zeros(NUM_NODES, dtype=np.intc)

    TSH_arr = np.zeros(NUM_EDGES, dtype=np.double)
    HCO_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    FCH_arr = np.zeros(NUM_EDGES, dtype=np.double)

    #create array for storing node activities:
    NODE_ACT = np.zeros(NUM_NODES, dtype=np.intc)

    #create array for storing the types of the edges:
    edge_type_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_type_dict.keys():
        edge_type_arr[i] = edge_type_dict[idx]
        i += 1

    #open file to write parameters:
    params_fname = network.get_params_fname()
    fh_params = open(params_fname, 'w')

    #import config_dict:
    config_dict = network.get_config_dict()

    # initialize a dictionary:
    dict_act = OrderedDict()
    # get states activation from states file:
    fname_states_act = network.get_fname_states_act()
    fh_states = open(fname_states_act, 'r')

    # skip header:
    next(fh_states)
    # read line by line to place the activities into the dictionary:
    for line in fh_states:
        fields = line.strip().split("\t")
        key = fields[0]  # model no as the key
        dict_act[key] = fields[3:len(fields)]

    model_no = 1
    while model_no <= int(config_dict['NUM_MODELS']):
        (nodeParam_dict, source_dict, master_dict) = set_parameters(network)

        i = 0
        for X in nodeParam_dict.keys():
            NODE_TYPE_arr[i] = nodeParam_dict[X][0]
            MPR_arr[i] = nodeParam_dict[X][1]
            #print(MPR_arr[i])
            DNR_arr[i] = nodeParam_dict[X][2]
            i += 1

        for idx, e in master_dict.items():
            TSH_arr[idx] = master_dict[idx][3]
            HCO_arr[idx] = master_dict[idx][4]
            FCH_arr[idx] = master_dict[idx][5]

        if str(model_no) not in dict_act.keys():
            model_no = model_no + 1
            continue
        #print(dict_act.get(str(model_no)))

        # put the expression in the array:
        EXP_arr = np.zeros(NUM_NODES, dtype=np.double)
        i = 0
        for v in dict_act.get(str(model_no)):
            EXP_arr[i] = float(v)
            i = i + 1
        #print(EXP_arr)
        #start_time=time.time()
        clib.cal_expressions(\
             ctypes.create_string_buffer(WORK_DIR),
             ctypes.create_string_buffer(FNAME_STATES),
             ctypes.create_string_buffer(FNAME_LIMITCYCLES),
             ctypes.create_string_buffer(FNAME_SUMMARY),
             ctypes.c_int(model_no),
             ctypes.c_int(NUM_NODES),
             ctypes.c_int(NUM_EDGES),
             ctypes.c_int(int(config_dict['NUM_RANDOM_ICS'])),
             ctypes.c_int(int(config_dict['ITER_FOR_ODE'])),
             ctypes.c_double(float(config_dict['EULER_SIM_TIME'])),
             ctypes.c_double(float(config_dict['EULER_SIM_STEP_SIZE'])),
             ctypes.c_longdouble(float(config_dict['CONVERGENCE_PROXIMITY'])),
             ctypes.c_double(float(config_dict['TRANS_RATE_FACTOR'])),
             ctypes.c_void_p(MPR_arr.ctypes.data),
             ctypes.c_void_p(DNR_arr.ctypes.data),
             ctypes.c_void_p(NODE_TYPE_arr.ctypes.data),
             ctypes.c_void_p(edge_source_arr.ctypes.data),
             ctypes.c_void_p(edge_target_arr.ctypes.data),
             ctypes.c_void_p(edge_type_arr.ctypes.data),
             ctypes.c_void_p(TSH_arr.ctypes.data),
             ctypes.c_void_p(HCO_arr.ctypes.data),
             ctypes.c_void_p(FCH_arr.ctypes.data),
             ctypes.c_void_p(EXP_arr.ctypes.data)
             )
        model_no += 1
    return None
コード例 #24
0
    def attributeRoundTrip(self, file_ending):
        # write
        series = api.Series(
            "unittest_py_API." + file_ending,
            api.Access_Type.create
        )

        # write one of each supported types
        series.set_attribute("char", 'c')  # string
        series.set_attribute("pyint", 13)
        series.set_attribute("pyfloat", 3.1416)
        series.set_attribute("pystring", "howdy!")
        series.set_attribute("pystring2", str("howdy, too!"))
        series.set_attribute("pystring3", b"howdy, again!")
        series.set_attribute("pybool", False)

        # array of ...
        series.set_attribute("arr_pyint", (13, 26, 39, 52, ))
        series.set_attribute("arr_pyfloat", (1.2, 3.4, 4.5, 5.6, ))
        series.set_attribute("arr_pystring", ("x", "y", "z", "www", ))
        series.set_attribute("arr_pybool", (False, True, True, False, ))
        # list of ...
        series.set_attribute("l_pyint", [13, 26, 39, 52])
        series.set_attribute("l_pyfloat", [1.2, 3.4, 4.5, 5.6])
        series.set_attribute("l_pystring", ["x", "y", "z", "www"])
        series.set_attribute("l_pybool", [False, True, True, False])

        if found_numpy:
            series.set_attribute("int16", np.int16(234))
            series.set_attribute("int32", np.int32(43))
            series.set_attribute("int64", np.int64(987654321))
            series.set_attribute("uint16", np.uint16(134))
            series.set_attribute("uint32", np.uint32(32))
            series.set_attribute("uint64", np.int64(9876543210))
            series.set_attribute("single", np.single(1.234))
            series.set_attribute("double", np.double(1.234567))
            series.set_attribute("longdouble", np.longdouble(1.23456789))
            # array of ...
            series.set_attribute("arr_int16", (np.int16(23), np.int16(26), ))
            series.set_attribute("arr_int32", (np.int32(34), np.int32(37), ))
            series.set_attribute("arr_int64", (np.int64(45), np.int64(48), ))
            series.set_attribute("arr_uint16",
                                 (np.uint16(23), np.uint16(26), ))
            series.set_attribute("arr_uint32",
                                 (np.uint32(34), np.uint32(37), ))
            series.set_attribute("arr_uint64",
                                 (np.uint64(45), np.uint64(48), ))
            series.set_attribute("arr_single",
                                 (np.single(5.6), np.single(5.9), ))
            series.set_attribute("arr_double",
                                 (np.double(6.7), np.double(7.1), ))
            # list of ...
            series.set_attribute("l_int16", [np.int16(23), np.int16(26)])
            series.set_attribute("l_int32", [np.int32(34), np.int32(37)])
            series.set_attribute("l_int64", [np.int64(45), np.int64(48)])
            series.set_attribute("l_uint16", [np.uint16(23), np.uint16(26)])
            series.set_attribute("l_uint32", [np.uint32(34), np.uint32(37)])
            series.set_attribute("l_uint64", [np.uint64(45), np.uint64(48)])
            series.set_attribute("l_single", [np.single(5.6), np.single(5.9)])
            series.set_attribute("l_double", [np.double(6.7), np.double(7.1)])
            series.set_attribute("l_longdouble",
                                 [np.longdouble(7.8e9), np.longdouble(8.2e3)])
            # numpy.array of ...
            series.set_attribute("nparr_int16",
                                 np.array([234, 567], dtype=np.int16))
            series.set_attribute("nparr_int32",
                                 np.array([456, 789], dtype=np.int32))
            series.set_attribute("nparr_int64",
                                 np.array([678, 901], dtype=np.int64))
            series.set_attribute("nparr_single",
                                 np.array([1.2, 2.3], dtype=np.single))
            series.set_attribute("nparr_double",
                                 np.array([4.5, 6.7], dtype=np.double))
            series.set_attribute("nparr_longdouble",
                                 np.array([8.9, 7.6], dtype=np.longdouble))

        # c_types
        # TODO remove the .value and handle types directly?
        series.set_attribute("byte_c", ctypes.c_byte(30).value)
        series.set_attribute("ubyte_c", ctypes.c_ubyte(50).value)
        series.set_attribute("char_c", ctypes.c_char(100).value)  # 'd'
        series.set_attribute("int16_c", ctypes.c_int16(2).value)
        series.set_attribute("int32_c", ctypes.c_int32(3).value)
        series.set_attribute("int64_c", ctypes.c_int64(4).value)
        series.set_attribute("uint16_c", ctypes.c_uint16(5).value)
        series.set_attribute("uint32_c", ctypes.c_uint32(6).value)
        series.set_attribute("uint64_c", ctypes.c_uint64(7).value)
        series.set_attribute("float_c", ctypes.c_float(8.e9).value)
        series.set_attribute("double_c", ctypes.c_double(7.e289).value)
        # TODO init of > e304 ?
        series.set_attribute("longdouble_c", ctypes.c_longdouble(6.e200).value)

        del series

        # read back
        series = api.Series(
            "unittest_py_API." + file_ending,
            api.Access_Type.read_only
        )

        self.assertEqual(series.get_attribute("char"), "c")
        self.assertEqual(series.get_attribute("pystring"), "howdy!")
        self.assertEqual(series.get_attribute("pystring2"), "howdy, too!")
        self.assertEqual(bytes(series.get_attribute("pystring3")),
                         b"howdy, again!")
        self.assertEqual(series.get_attribute("pyint"), 13)
        self.assertAlmostEqual(series.get_attribute("pyfloat"), 3.1416)
        self.assertEqual(series.get_attribute("pybool"), False)

        if found_numpy:
            self.assertEqual(series.get_attribute("int16"), 234)
            self.assertEqual(series.get_attribute("int32"), 43)
            self.assertEqual(series.get_attribute("int64"), 987654321)
            self.assertAlmostEqual(series.get_attribute("single"), 1.234)
            self.assertAlmostEqual(series.get_attribute("double"),
                                   1.234567)
            self.assertAlmostEqual(series.get_attribute("longdouble"),
                                   1.23456789)
            # array of ... (will be returned as list)
            self.assertListEqual(series.get_attribute("arr_int16"),
                                 [np.int16(23), np.int16(26), ])
            # list of ...
            self.assertListEqual(series.get_attribute("l_int16"),
                                 [np.int16(23), np.int16(26)])
            self.assertListEqual(series.get_attribute("l_int32"),
                                 [np.int32(34), np.int32(37)])
            self.assertListEqual(series.get_attribute("l_int64"),
                                 [np.int64(45), np.int64(48)])
            self.assertListEqual(series.get_attribute("l_uint16"),
                                 [np.uint16(23), np.uint16(26)])
            self.assertListEqual(series.get_attribute("l_uint32"),
                                 [np.uint32(34), np.uint32(37)])
            self.assertListEqual(series.get_attribute("l_uint64"),
                                 [np.uint64(45), np.uint64(48)])
            # self.assertListEqual(series.get_attribute("l_single"),
            #     [np.single(5.6), np.single(5.9)])
            self.assertListEqual(series.get_attribute("l_double"),
                                 [np.double(6.7), np.double(7.1)])
            self.assertListEqual(series.get_attribute("l_longdouble"),
                                 [np.longdouble(7.8e9), np.longdouble(8.2e3)])

            # numpy.array of ...
            self.assertListEqual(series.get_attribute("nparr_int16"),
                                 [234, 567])
            self.assertListEqual(series.get_attribute("nparr_int32"),
                                 [456, 789])
            self.assertListEqual(series.get_attribute("nparr_int64"),
                                 [678, 901])
            np.testing.assert_almost_equal(
                series.get_attribute("nparr_single"), [1.2, 2.3])
            np.testing.assert_almost_equal(
                series.get_attribute("nparr_double"), [4.5, 6.7])
            np.testing.assert_almost_equal(
                series.get_attribute("nparr_longdouble"), [8.9, 7.6])
            # TODO instead of returning lists, return all arrays as np.array?
            # self.assertEqual(
            #     series.get_attribute("nparr_int16").dtype, np.int16)
            # self.assertEqual(
            #     series.get_attribute("nparr_int32").dtype, np.int32)
            # self.assertEqual(
            #     series.get_attribute("nparr_int64").dtype, np.int64)
            # self.assertEqual(
            #     series.get_attribute("nparr_single").dtype, np.single)
            # self.assertEqual(
            #     series.get_attribute("nparr_double").dtype, np.double)
            # self.assertEqual(
            #    series.get_attribute("nparr_longdouble").dtype, np.longdouble)

        # c_types
        self.assertEqual(series.get_attribute("byte_c"), 30)
        self.assertEqual(series.get_attribute("ubyte_c"), 50)
        self.assertEqual(chr(series.get_attribute("char_c")), 'd')
        self.assertEqual(series.get_attribute("int16_c"), 2)
        self.assertEqual(series.get_attribute("int32_c"), 3)
        self.assertEqual(series.get_attribute("int64_c"), 4)
        self.assertEqual(series.get_attribute("uint16_c"), 5)
        self.assertEqual(series.get_attribute("uint32_c"), 6)
        self.assertEqual(series.get_attribute("uint64_c"), 7)
        self.assertAlmostEqual(series.get_attribute("float_c"), 8.e9)
        self.assertAlmostEqual(series.get_attribute("double_c"), 7.e289)
        self.assertAlmostEqual(series.get_attribute("longdouble_c"),
                               ctypes.c_longdouble(6.e200).value)
コード例 #25
0
def simulate_network_cnoise(network, model_no, params_list):
    '''
    This method generates RACIPE models. 
    '''

    global clib

    import numpy
    import numpy as np
    import ctypes
    import sys
    import modelManager as mm

    node_dict = network.get_node_dict()
    node_id_dict = network.get_node_id_dict()

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    NUM_NODES = len(node_id_dict.keys())  #size of node_id_arr
    NUM_EDGES = len(edge_source_dict.keys())  #size of edge_id_arr

    #create arrays for storing noise level for each node:
    NOISE_strength = np.zeros(NUM_NODES, dtype=np.double)
    NOISE_strength_shot = np.zeros(NUM_NODES, dtype=np.double)

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1
    #create character array for work directory string:
    WORK_DIR = (network.get_work_dir()).encode('utf-8')

    #create character arrays for file names to be used in C:
    fname_dict_simu = network.get_fname_dict_simu()
    #FNAME_STATES = fname_dict_simu['FNAME_STATES'].encode('utf-8')
    FNAME_STATES = fname_dict_simu['FNAME_STATES_CNOISE'].encode('utf-8')
    FNAME_LIMITCYCLES = fname_dict_simu['FNAME_LIMITCYCLES'].encode('utf-8')
    FNAME_SUMMARY = fname_dict_simu['FNAME_SUMMARY'].encode('utf-8')

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1

    #create array for storing the types of the edges:
    edge_type_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_type_dict.keys():
        edge_type_arr[i] = edge_type_dict[idx]
        i += 1

    # create arrays for storing the parameters:
    MPR_arr = params_list[0]
    DNR_arr = params_list[1]

    TSH_arr = params_list[2]
    HCO_arr = params_list[3]
    FCH_arr = params_list[4]

    NODE_TYPE_arr = np.zeros(NUM_NODES, dtype=np.intc)
    node_dict = network.get_node_dict()
    i = 0
    for node in node_dict.keys():
        (node_type, mpr_range, dnr_range) = node_dict[node]
        NODE_TYPE_arr[i] = node_type
        i = i + 1

    #import config_dict:
    config_dict = network.get_config_dict()

    EXP_dict_arr = np.zeros(NUM_NODES * int(config_dict['NUM_RANDOM_ICS']),
                            dtype=np.double)

    clib.simulate_network_cnoise_gnw(\
         ctypes.create_string_buffer(WORK_DIR),
         ctypes.create_string_buffer(FNAME_STATES),
         ctypes.create_string_buffer(FNAME_LIMITCYCLES),
         ctypes.create_string_buffer(FNAME_SUMMARY),
         ctypes.c_int(model_no),
         ctypes.c_int(NUM_NODES),
         ctypes.c_int(NUM_EDGES),
         ctypes.c_int(int(config_dict['NUM_RANDOM_ICS'])),
         ctypes.c_int(int(config_dict['ITER_FOR_ODE'])),
         ctypes.c_double(float(config_dict['EULER_SIM_TIME'])),
         ctypes.c_double(float(config_dict['EULER_SIM_STEP_SIZE'])),
         ctypes.c_longdouble(float(config_dict['CONVERGENCE_PROXIMITY'])),
         ctypes.c_double(float(config_dict['TRANS_RATE_FACTOR'])),
         ctypes.c_void_p(MPR_arr.ctypes.data),
         ctypes.c_void_p(DNR_arr.ctypes.data),
         ctypes.c_void_p(NODE_TYPE_arr.ctypes.data),
         ctypes.c_void_p(edge_source_arr.ctypes.data),
         ctypes.c_void_p(edge_target_arr.ctypes.data),
         ctypes.c_void_p(edge_type_arr.ctypes.data),
         ctypes.c_void_p(TSH_arr.ctypes.data),
         ctypes.c_void_p(HCO_arr.ctypes.data),
         ctypes.c_void_p(FCH_arr.ctypes.data),
         ctypes.c_void_p(EXP_dict_arr.ctypes.data)
         )
    return None
コード例 #26
0
#!/usr/bin/python
import sys, ctypes
if sys.platform.startswith('linux'):
    libm = ctypes.cdll.LoadLibrary('libm.so.6')
    libc = ctypes.cdll.LoadLibrary('libc.so.6')
elif sys.platform == 'darwin':
    libm = ctypes.cdll.LoadLibrary('libSystem.dylib')
    libc = libm
elif sys.platform == 'win32':
    libm = ctypes.cdll.LoadLibrary('msvcr120.dll')
    libc = libm
else:
    raise ImportError

libm.sqrtl.restype = ctypes.c_longdouble
n = ctypes.c_longdouble()
z = int(sys.stdin.readline()) * 8 + 1
libc.sscanf(str(z), '%Lf', ctypes.byref(n))
n = libm.sqrtl(n)
q = int(n)
print('NO' if q * q != z else 'YES\n%d' % (q / 2))
コード例 #27
0
#!/usr/bin/python
import sys,ctypes
if sys.platform.startswith('linux'):
	libm=ctypes.cdll.LoadLibrary('libm.so.6')
	libc=ctypes.cdll.LoadLibrary('libc.so.6')
elif sys.platform=='darwin':
	libm=ctypes.cdll.LoadLibrary('libSystem.dylib')
	libc=libm
elif sys.platform=='win32':
	libm=ctypes.cdll.LoadLibrary('msvcr120.dll')
	libc=libm
else:
	raise ImportError

libm.sqrtl.restype=ctypes.c_longdouble
n=ctypes.c_longdouble()
z=int(sys.stdin.readline())*8+1
libc.sscanf(str(z),'%Lf',ctypes.byref(n))
n=libm.sqrtl(n)
q=int(n)
print('NO' if q*q!=z else 'YES\n%d'%(q/2))
コード例 #28
0
def cal_time_traj(network, model_no, params_list):
    '''
    This method generates RACIPE models. 
    '''

    #global clib
    import numpy
    import numpy as np
    import ctypes
    import sys
    import modelManager as mm

    # Import library functions
    clib = ctypes.cdll.LoadLibrary('./pertParamSim.so')
    clib.randu.argtypes = (ctypes.c_double, ctypes.c_double)
    clib.randu.restype = ctypes.c_double

    #Import network attributes:
    node_dict = network.get_node_dict()
    node_id_dict = network.get_node_id_dict()

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    NUM_NODES = len(node_id_dict.keys())  #size of node_id_arr
    NUM_EDGES = len(edge_source_dict.keys())  #size of edge_id_arr

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1
    #create character array for work directory string:
    WORK_DIR = (network.get_work_dir()).encode('utf-8')

    #create character arrays for file names to be used in C:
    fname_dict_simu = network.get_fname_dict_simu()
    FNAME_STATES = fname_dict_simu['FNAME_STATES'].encode('utf-8')
    FNAME_LIMITCYCLES = fname_dict_simu['FNAME_LIMITCYCLES'].encode('utf-8')
    FNAME_SUMMARY = fname_dict_simu['FNAME_SUMMARY'].encode('utf-8')

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1

    #create array for storing the types of the edges:
    edge_type_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_type_dict.keys():
        edge_type_arr[i] = edge_type_dict[idx]
        i += 1

    # create arrays for storing the parameters:
    MPR_arr = params_list[0]
    DNR_arr = params_list[1]

    TSH_arr = params_list[2]
    HCO_arr = params_list[3]
    FCH_arr = params_list[4]

    print("cal_time_traj")
    print(MPR_arr)
    print(DNR_arr)
    print(TSH_arr)
    print(HCO_arr)
    print(FCH_arr)
    #sys.exit(0)

    NODE_TYPE_arr = np.zeros(NUM_NODES, dtype=np.intc)
    node_dict = network.get_node_dict()
    i = 0
    for node in node_dict.keys():
        (node_type, mpr_range, dnr_range) = node_dict[node]
        NODE_TYPE_arr[i] = node_type
        i = i + 1

    #import config_dict:
    config_dict = network.get_config_dict()

    clib.find_traj_random_IC(\
             ctypes.create_string_buffer(WORK_DIR),
             ctypes.create_string_buffer(FNAME_STATES),
             ctypes.create_string_buffer(FNAME_LIMITCYCLES),
             ctypes.create_string_buffer(FNAME_SUMMARY),
             ctypes.c_int(model_no),
             ctypes.c_int(NUM_NODES),
             ctypes.c_int(NUM_EDGES),
             ctypes.c_int(int(config_dict['NUM_RANDOM_ICS'])),
             ctypes.c_int(int(config_dict['ITER_FOR_ODE'])),
             ctypes.c_double(float(config_dict['EULER_SIM_TIME'])),
             ctypes.c_double(float(config_dict['EULER_SIM_STEP_SIZE'])),
             ctypes.c_longdouble(float(config_dict['CONVERGENCE_PROXIMITY'])),
             ctypes.c_double(float(config_dict['TRANS_RATE_FACTOR'])),
             ctypes.c_void_p(MPR_arr.ctypes.data),
             ctypes.c_void_p(DNR_arr.ctypes.data),
             ctypes.c_void_p(NODE_TYPE_arr.ctypes.data),
             ctypes.c_void_p(edge_source_arr.ctypes.data),
             ctypes.c_void_p(edge_target_arr.ctypes.data),
             ctypes.c_void_p(edge_type_arr.ctypes.data),
             ctypes.c_void_p(TSH_arr.ctypes.data),
             ctypes.c_void_p(HCO_arr.ctypes.data),
             ctypes.c_void_p(FCH_arr.ctypes.data)
             )

    return None
    sys.exit(0)

    EXP_dict_arr = np.zeros(NUM_NODES * int(config_dict['NUM_RANDOM_ICS']),
                            dtype=np.double)

    clib.find_solutions(\
         ctypes.create_string_buffer(WORK_DIR),
         ctypes.create_string_buffer(FNAME_STATES),
         ctypes.create_string_buffer(FNAME_LIMITCYCLES),
         ctypes.create_string_buffer(FNAME_SUMMARY),
         ctypes.c_int(model_no),
         ctypes.c_int(NUM_NODES),
         ctypes.c_int(NUM_EDGES),
         ctypes.c_int(int(config_dict['NUM_RANDOM_ICS'])),
         ctypes.c_int(int(config_dict['ITER_FOR_ODE'])),
         ctypes.c_double(float(config_dict['EULER_SIM_TIME'])),
         ctypes.c_double(float(config_dict['EULER_SIM_STEP_SIZE'])),
         ctypes.c_longdouble(float(config_dict['CONVERGENCE_PROXIMITY'])),
         ctypes.c_double(float(config_dict['TRANS_RATE_FACTOR'])),
         ctypes.c_void_p(MPR_arr.ctypes.data),
         ctypes.c_void_p(DNR_arr.ctypes.data),
         ctypes.c_void_p(NODE_TYPE_arr.ctypes.data),
         ctypes.c_void_p(edge_source_arr.ctypes.data),
         ctypes.c_void_p(edge_target_arr.ctypes.data),
         ctypes.c_void_p(edge_type_arr.ctypes.data),
         ctypes.c_void_p(TSH_arr.ctypes.data),
         ctypes.c_void_p(HCO_arr.ctypes.data),
         ctypes.c_void_p(FCH_arr.ctypes.data),
         ctypes.c_void_p(EXP_dict_arr.ctypes.data)
         )
    return None
def generate_models_to_be_deleted(rcp): 
    '''
    This method generates RACIPE models. 
    '''
    import numpy
    import numpy as np
    import ctypes
    import sys

    import modelManager as mm
    global clib

    MODEL_DIR = "/Users/kateba/research/cellcycle-3.stoch/data-raw/earlyG1-midG1/"
    MO = mm.Models(MODEL_DIR)
    EXP_dict = MO.get_EXP_dict()

    MPR_dict = MO.get_MPR_dict()
    DNR_dict = MO.get_DNR_dict()

    TSH_dict = MO.get_TSH_dict()
    FCH_dict = MO.get_FCH_dict()
    HCO_dict = MO.get_HCO_dict()

    # obtain the model ids:
    MODEL_LIST = list(HCO_dict.keys())

    node_id_dict=rcp.get_node_id_dict()

    edge_source_dict=rcp.get_edge_source_dict()
    edge_target_dict=rcp.get_edge_target_dict()
    edge_type_dict=rcp.get_edge_type_dict()

    NUM_NODES=len(node_id_dict.keys()) #size of node_id_arr
    NUM_EDGES=len(edge_source_dict.keys()) #size of edge_id_arr

    # add appropriate noise:
    NOISE=10.0 # 30.0 

    NOISE_SHOT=0
    SCALING=0.93

    #create array for storing the source nodes of the edges:
    edge_source_arr=np.zeros(NUM_EDGES,dtype=np.intc) 
    i=0
    for idx in edge_source_dict.keys():
        edge_source_arr[i]=edge_source_dict[idx]
        i+=1

    #create array for storing the target nodes of the edges:
    edge_target_arr=np.zeros(NUM_EDGES,dtype=np.intc) 
    i=0
    for idx in edge_target_dict.keys():
        edge_target_arr[i]=edge_target_dict[idx]
        i+=1
    #create character array for work directory string:  
    WORK_DIR=(rcp.get_work_dir()).encode('utf-8')

    #create arrays for storing node and edge parameters:
    MPR_arr=np.zeros(NUM_NODES,dtype=np.double)
    NOISE_strength=np.zeros(NUM_NODES,dtype=np.double)
    NOISE_strength_shot=np.zeros(NUM_NODES,dtype=np.double)
    DNR_arr=np.zeros(NUM_NODES,dtype=np.double)
    NODE_TYPE_arr=np.zeros(NUM_NODES,dtype=np.intc)

    TSH_arr=np.zeros(NUM_EDGES,dtype=np.double)
    HCO_arr=np.zeros(NUM_EDGES,dtype=np.intc)
    FCH_arr=np.zeros(NUM_EDGES,dtype=np.double)

    #create array for storing the types of the edges:
    edge_type_arr=np.zeros(NUM_EDGES,dtype=np.intc) 
    i=0
    for idx in edge_type_dict.keys():
        edge_type_arr[i]=edge_type_dict[idx]
        i+=1

    #open file to write parameters:
    params_fname=rcp.get_params_fname()
    fh_params=open(params_fname,'w')

    #open files to write parameters:
    fh_dict_nodeparams=OrderedDict()
    fh_dict_edgeparams=OrderedDict()
    fh_dict_nodeparams,fh_dict_edgeparams=open_parameter_files(rcp)

    #open files to write solutions:
    fname_dict_solutions,fh_dict_solutions=open_solution_files(rcp)
    #open file to write limit cycle trace:
    LCtrace_fname=rcp.get_LCtrace_fname()
    fh_LCtrace=open(LCtrace_fname,'w')
   
    #import config_dict:
    config_dict=rcp.get_config_dict()

    for model_no in MODEL_LIST:
        #(nodeParam_dict,source_dict,master_dict)=set_parameters(rcp)
        (nodeParam_dict,source_dict,master_dict)=mm.set_parameters_bymodel(rcp, MO, model_no)


        i=0
        for X in nodeParam_dict.keys():  
            NODE_TYPE_arr[i]=nodeParam_dict[X][0]
            MPR_arr[i]=nodeParam_dict[X][1]
            NOISE_strength[i]=1
            NOISE_strength_shot[i]=1
            DNR_arr[i]=nodeParam_dict[X][2]
            i+=1

        for idx,e in master_dict.items():  
            TSH_arr[idx]=master_dict[idx][3]
            HCO_arr[idx]=master_dict[idx][4]
            FCH_arr[idx]=master_dict[idx][5]
        EXP_dict_arr=np.zeros(NUM_NODES*int(config_dict['NUM_RANDOM_ICS']),
                              dtype=np.double) 

        #start_time=time.time()
        clib.find_solutions_stochastic_annealing(ctypes.create_string_buffer(WORK_DIR),
             ctypes.c_int(model_no),
             ctypes.c_int(NUM_NODES),
             ctypes.c_int(NUM_EDGES),
             ctypes.c_int(int(config_dict['NUM_RANDOM_ICS'])),
             ctypes.c_int(int(config_dict['ITER_FOR_ODE'])),
             ctypes.c_double(float(config_dict['EULER_SIM_TIME'])),
             ctypes.c_double(float(config_dict['EULER_SIM_STEP_SIZE'])),
             ctypes.c_longdouble(float(config_dict['CONVERGENCE_PROXIMITY'])),
             ctypes.c_double(float(config_dict['TRANS_RATE_FACTOR'])),
             ctypes.c_void_p(MPR_arr.ctypes.data), 
             ctypes.c_void_p(DNR_arr.ctypes.data), 
             ctypes.c_void_p(NODE_TYPE_arr.ctypes.data),
             ctypes.c_void_p(edge_source_arr.ctypes.data), 
             ctypes.c_void_p(edge_target_arr.ctypes.data), 
             ctypes.c_void_p(edge_type_arr.ctypes.data), 
             ctypes.c_void_p(TSH_arr.ctypes.data), 
             ctypes.c_void_p(HCO_arr.ctypes.data), 
             ctypes.c_void_p(FCH_arr.ctypes.data), 
             ctypes.c_void_p(EXP_dict_arr.ctypes.data),
             ctypes.c_void_p(NOISE_strength.ctypes.data), 
             ctypes.c_void_p(NOISE_strength_shot.ctypes.data), 
             ctypes.c_double(NOISE),
             ctypes.c_double(NOISE_SHOT),
             ctypes.c_double(SCALING)
             )
        #end_time=time.time()

        #place the solutions in a dictionary:
        expression_dict=OrderedDict()
        expression_dict_ICs=OrderedDict()
        count_iteration=0
        for i in range(0,NUM_NODES*int(config_dict['NUM_RANDOM_ICS']),
                         NUM_NODES):
            for node,node_id in node_id_dict.items():
                expression_dict[node]=EXP_dict_arr[i+node_id]
            expression_dict_ICs[count_iteration]=expression_dict.copy()
            count_iteration+=1
        (solution_dict,solution_count_dict)=count_states(config_dict,
                                                         expression_dict_ICs,
                                                         fh_LCtrace)
        save_parameters(fh_params,model_no,nodeParam_dict,
                        master_dict,solution_dict)
        save_parameters_5(fh_dict_nodeparams, fh_dict_edgeparams,model_no,
                        nodeParam_dict,master_dict,solution_dict)

        save_solutions(fh_dict_solutions,model_no,solution_dict)

        if (not model_no%100):
            flush_solutions(fh_dict_solutions)
        #model_no+=1
    fh_params.close()
    fh_LCtrace.close()
    close_solution_files(fname_dict_solutions,fh_dict_solutions)
    close_parameter_files(fh_dict_nodeparams,fh_dict_edgeparams)
    return None 
コード例 #30
0
def write_longdouble(hProcess, address, value):
    ctypes.windll.kernel32.WriteProcessMemory(
        hProcess, address, ctypes.byref(ctypes.c_longdouble(value)),
        ctypes.sizeof(ctypes.c_longdouble(value)), ctypes.c_ulong(0))
コード例 #31
0
def anneal_network_stochastic_gnw(network, model_no, params_list,
                                  steady_state_exp):
    '''
    This method generates RACIPE models. 
    '''

    global ensSimu

    import numpy
    import numpy as np
    import ctypes
    import sys

    import modelManager as mm

    #import config_dict:
    config_dict = network.get_config_dict()

    #add appropriate noise level:
    #extract starting noise for annealing from the dictionary:
    NOISE = np.double(config_dict['STARTING_NOISE_ANN'])

    #NOISE=10.0 # 30.0

    NOISE_SHOT = 0

    # add appropriate scaling for noise:
    #SCALING=0.90
    SCALING = np.double(config_dict['NOISE_SCALING_FACTOR_ANN'])

    node_dict = network.get_node_dict()
    node_id_dict = network.get_node_id_dict()

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    NUM_NODES = len(node_id_dict.keys())  #size of node_id_arr
    NUM_EDGES = len(edge_source_dict.keys())  #size of edge_id_arr

    #create arrays for storing noise level for each node:
    NOISE_strength = np.zeros(NUM_NODES, dtype=np.double)
    NOISE_strength_shot = np.zeros(NUM_NODES, dtype=np.double)

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1
    #create character array for work directory string:
    WORK_DIR = (network.get_work_dir()).encode('utf-8')

    #create character arrays for file names to be used in C:
    fname_dict_simu = network.get_fname_dict_simu()
    FNAME_STATES = fname_dict_simu['FNAME_STATES'].encode('utf-8')
    FNAME_LIMITCYCLES = fname_dict_simu['FNAME_LIMITCYCLES'].encode('utf-8')
    FNAME_SUMMARY = fname_dict_simu['FNAME_SUMMARY'].encode('utf-8')

    FNAME_STATES_ANNEALED = fname_dict_simu['FNAME_STATES_ANNEALED'].encode(
        'utf-8')

    #print(FNAME_STATES_ANNEALED)

    edge_source_dict = network.get_edge_source_dict()
    edge_target_dict = network.get_edge_target_dict()
    edge_type_dict = network.get_edge_type_dict()

    #create array for storing the source nodes of the edges:
    edge_source_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_source_dict.keys():
        edge_source_arr[i] = edge_source_dict[idx]
        i += 1

    #create array for storing the target nodes of the edges:
    edge_target_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_target_dict.keys():
        edge_target_arr[i] = edge_target_dict[idx]
        i += 1

    #create array for storing the types of the edges:
    edge_type_arr = np.zeros(NUM_EDGES, dtype=np.intc)
    i = 0
    for idx in edge_type_dict.keys():
        edge_type_arr[i] = edge_type_dict[idx]
        i += 1

    # create arrays for storing the parameters:
    MPR_arr = params_list[0]
    DNR_arr = params_list[1]

    TSH_arr = params_list[2]
    HCO_arr = params_list[3]
    FCH_arr = params_list[4]

    NODE_TYPE_arr = np.zeros(NUM_NODES, dtype=np.intc)
    node_dict = network.get_node_dict()

    i = 0
    for node in node_dict.keys():
        (node_type, mpr_range, dnr_range) = node_dict[node]
        NODE_TYPE_arr[i] = node_type

        NOISE_strength[i] = 1
        NOISE_strength_shot[i] = 1
        i = i + 1

    EXP_dict_arr = np.zeros(NUM_NODES * int(config_dict['NUM_RANDOM_ICS']),
                            dtype=np.double)

    ensSimu.stochastic_anneal_network_gnw(\
         ctypes.create_string_buffer(WORK_DIR),
         ctypes.create_string_buffer(FNAME_STATES_ANNEALED),
         ctypes.create_string_buffer(FNAME_LIMITCYCLES),
         ctypes.create_string_buffer(FNAME_SUMMARY),
         ctypes.c_int(model_no),
         ctypes.c_int(NUM_NODES),
         ctypes.c_int(NUM_EDGES),
         ctypes.c_int(int(config_dict['NUM_RANDOM_ICS'])),
         ctypes.c_int(int(config_dict['ITER_FOR_ODE'])),
         ctypes.c_double(float(config_dict['EULER_SIM_TIME'])),
         ctypes.c_double(float(config_dict['EULER_SIM_STEP_SIZE'])),
         ctypes.c_longdouble(float(config_dict['CONVERGENCE_PROXIMITY'])),
         ctypes.c_double(float(config_dict['TRANS_RATE_FACTOR'])),
         ctypes.c_void_p(steady_state_exp.ctypes.data),
         ctypes.c_void_p(MPR_arr.ctypes.data),
         ctypes.c_void_p(DNR_arr.ctypes.data),
         ctypes.c_void_p(NODE_TYPE_arr.ctypes.data),
         ctypes.c_void_p(edge_source_arr.ctypes.data),
         ctypes.c_void_p(edge_target_arr.ctypes.data),
         ctypes.c_void_p(edge_type_arr.ctypes.data),
         ctypes.c_void_p(TSH_arr.ctypes.data),
         ctypes.c_void_p(HCO_arr.ctypes.data),
         ctypes.c_void_p(FCH_arr.ctypes.data),
         ctypes.c_void_p(EXP_dict_arr.ctypes.data),
         ctypes.c_double(NOISE),
         ctypes.c_double(SCALING)
         )
    return None
コード例 #32
0
    def test05_ctypes_as_ref_and_ptr(self):
        """Use ctypes for pass-by-ref/ptr"""

        # See:
        #  https://docs.python.org/2/library/ctypes.html#fundamental-data-types
        #
        # ctypes type       C type                                      Python type
        # ------------------------------------------------------------------------------
        # c_bool            _Bool                                       bool (1)
        #
        # c_char            char 1-character                            string
        # c_wchar           wchar_t 1-character                         unicode string
        # c_byte            char                                        int/long
        # c_ubyte           unsigned char                               int/long
        #
        # c_short           short                                       int/long
        # c_ushort          unsigned short                              int/long
        # c_int             int                                         int/long
        # c_uint            unsigned int                                int/long
        # c_long            long                                        int/long
        # c_ulong           unsigned long                               int/long
        # c_longlong        __int64 or long long                        int/long
        # c_ulonglong       unsigned __int64 or unsigned long long      int/long
        #
        # c_float           float                                       float
        # c_double          double                                      float
        # c_longdouble      long double                                 float

        import cppyy, ctypes

        ctd = cppyy.gbl.CppyyTestData()

        ### pass by reference/pointer and set value back

        for e in ['_r', '_p']:
            # boolean type
            b = ctypes.c_bool(False)
            getattr(ctd, 'set_bool' + e)(b)
            assert b.value == True

            # char types
            if e == '_r':
                c = ctypes.c_char(b'\0')
                getattr(ctd, 'set_char' + e)(c)
                assert c.value == b'a'
                c = ctypes.c_wchar(u'\0')
                getattr(ctd, 'set_wchar' + e)(c)
                assert c.value == u'b'
                c = ctypes.c_byte(0)
                getattr(ctd, 'set_schar' + e)(c)
                assert c.value == ord('c')
            c = ctypes.c_ubyte(0)
            getattr(ctd, 'set_uchar' + e)(c)
            assert c.value == ord('d')

            # integer types
            i = ctypes.c_short(0)
            getattr(ctd, 'set_short' + e)(i)
            assert i.value == -1
            i = ctypes.c_ushort(0)
            getattr(ctd, 'set_ushort' + e)(i)
            assert i.value == 2
            i = ctypes.c_int(0)
            getattr(ctd, 'set_int' + e)(i)
            assert i.value == -3
            i = ctypes.c_uint(0)
            getattr(ctd, 'set_uint' + e)(i)
            assert i.value == 4
            i = ctypes.c_long(0)
            getattr(ctd, 'set_long' + e)(i)
            assert i.value == -5
            i = ctypes.c_ulong(0)
            getattr(ctd, 'set_ulong' + e)(i)
            assert i.value == 6
            i = ctypes.c_longlong(0)
            getattr(ctd, 'set_llong' + e)(i)
            assert i.value == -7
            i = ctypes.c_ulonglong(0)
            getattr(ctd, 'set_ullong' + e)(i)
            assert i.value == 8

            # floating point types
            f = ctypes.c_float(0)
            getattr(ctd, 'set_float' + e)(f)
            assert f.value == 5.
            f = ctypes.c_double(0)
            getattr(ctd, 'set_double' + e)(f)
            assert f.value == -5.
            f = ctypes.c_longdouble(0)
            getattr(ctd, 'set_ldouble' + e)(f)
            assert f.value == 10.

    ### pass by pointer and set value back, now using byref (not recommended)

        cb = ctypes.byref

        # boolean type
        b = ctypes.c_bool(False)
        ctd.set_bool_p(cb(b))
        assert b.value == True

        # char types
        c = ctypes.c_ubyte(0)
        ctd.set_uchar_p(cb(c))
        assert c.value == ord('d')

        # integer types
        i = ctypes.c_short(0)
        ctd.set_short_p(cb(i))
        assert i.value == -1
        i = ctypes.c_ushort(0)
        ctd.set_ushort_p(cb(i))
        assert i.value == 2
        i = ctypes.c_int(0)
        ctd.set_int_p(cb(i))
        assert i.value == -3
        i = ctypes.c_uint(0)
        ctd.set_uint_p(cb(i))
        assert i.value == 4
        i = ctypes.c_long(0)
        ctd.set_long_p(cb(i))
        assert i.value == -5
        i = ctypes.c_ulong(0)
        ctd.set_ulong_p(cb(i))
        assert i.value == 6
        i = ctypes.c_longlong(0)
        ctd.set_llong_p(cb(i))
        assert i.value == -7
        i = ctypes.c_ulonglong(0)
        ctd.set_ullong_p(cb(i))
        assert i.value == 8

        # floating point types
        f = ctypes.c_float(0)
        ctd.set_float_p(cb(f))
        assert f.value == 5.
        f = ctypes.c_double(0)
        ctd.set_double_p(cb(f))
        assert f.value == -5.

        ### pass by ptr/ptr with allocation (ptr/ptr is ambiguous in it's task, so many
        # types are allowed to pass; this tests allocation into the pointer)

        from ctypes import POINTER

        # boolean type
        b = POINTER(ctypes.c_bool)()
        ctd.set_bool_ppa(b)
        assert b[0] == True
        assert b[1] == False
        assert b[2] == True
        cppyy.ll.array_delete(b)

        # char types
        c = POINTER(ctypes.c_ubyte)()
        ctd.set_uchar_ppa(c)
        assert c[0] == ord('k')
        assert c[1] == ord('l')
        assert c[2] == ord('m')
        cppyy.ll.array_delete(c)

        # integer types
        i = POINTER(ctypes.c_short)()
        ctd.set_short_ppa(i)
        assert i[0] == -1
        assert i[1] == -2
        assert i[2] == -3
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_ushort)()
        ctd.set_ushort_ppa(i)
        assert i[0] == 4
        assert i[1] == 5
        assert i[2] == 6
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_int)()
        ctd.set_int_ppa(i)
        assert i[0] == -7
        assert i[1] == -8
        assert i[2] == -9
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_uint)()
        ctd.set_uint_ppa(i)
        assert i[0] == 10
        assert i[1] == 11
        assert i[2] == 12
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_long)()
        ctd.set_long_ppa(i)
        assert i[0] == -13
        assert i[1] == -14
        assert i[2] == -15
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_ulong)()
        ctd.set_ulong_ppa(i)
        assert i[0] == 16
        assert i[1] == 17
        assert i[2] == 18
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_longlong)()
        ctd.set_llong_ppa(i)
        assert i[0] == -19
        assert i[1] == -20
        assert i[2] == -21
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_ulonglong)()
        ctd.set_ullong_ppa(i)
        assert i[0] == 22
        assert i[1] == 23
        assert i[2] == 24
        cppyy.ll.array_delete(i)

        # floating point types
        f = POINTER(ctypes.c_float)()
        ctd.set_float_ppa(f)
        assert f[0] == 5
        assert f[1] == 10
        assert f[2] == 20
        cppyy.ll.array_delete(f)
        f = POINTER(ctypes.c_double)()
        ctd.set_double_ppa(f)
        assert f[0] == -5
        assert f[1] == -10
        assert f[2] == -20
        cppyy.ll.array_delete(f)
        f = POINTER(ctypes.c_longdouble)()
        ctd.set_ldouble_ppa(f)
        assert f[0] == 5
        assert f[1] == 10
        assert f[2] == 20
        cppyy.ll.array_delete(f)
コード例 #33
0
    # built-in functions (CH 2)
    a['ByteArrayType'] = bytearray([1])
    # numeric and mathematical types (CH 9)
    a['FractionType'] = fractions.Fraction()
    a['NumberType'] = numbers.Number()
    # generic operating system services (CH 15)
    a['IOBaseType'] = io.IOBase()
    a['RawIOBaseType'] = io.RawIOBase()
    a['TextIOBaseType'] = io.TextIOBase()
    a['BufferedIOBaseType'] = io.BufferedIOBase()
    a['UnicodeIOType'] = TextIO()  # the new StringIO
    a['LoggingAdapterType'] = logging.LoggingAdapter(_logger,
                                                     _dict)  # pickle ok
    if HAS_CTYPES:
        a['CBoolType'] = ctypes.c_bool(1)
        a['CLongDoubleType'] = ctypes.c_longdouble()
except ImportError:
    pass
try:  # python 2.7
    import argparse
    # data types (CH 8)
    a['OrderedDictType'] = collections.OrderedDict(_dict)
    a['CounterType'] = collections.Counter(_dict)
    if HAS_CTYPES:
        a['CSSizeTType'] = ctypes.c_ssize_t()
    # generic operating system services (CH 15)
    a['NullHandlerType'] = logging.NullHandler()  # pickle ok  # new 2.7
    a['ArgParseFileType'] = argparse.FileType()  # pickle ok
except (AttributeError, ImportError):
    pass
コード例 #34
0
import ctypes as ct

NUM_SAMPS_PER_CHAN = ct.c_int32(1)
TIMEOUT = ct.c_longdouble(1.0)  # one second
NI_DAQ_BUFFER_SIZE = 1000


class DAQConfiguration(object):
    """Settings required for NI-DAQ"""
    def __init__(self,
                 device_name,
                 channels="ai0:7",
                 rate=1000,
                 minVal=-10,
                 maxVal=10):
        self.device_name = device_name
        self.channels = channels
        self.rate = ct.c_double(rate)
        self.minVal = ct.c_double(minVal)
        self.maxVal = ct.c_double(maxVal)

    @property
    def physicalChannel(self):
        return "{0}/{1}".format(self.device_name, self.channels)